test TryExec,
[geeqie.git] / src / editors.c
1 /*
2  * Geeqie
3  * (C) 2006 John Ellis
4  * Copyright (C) 2008 The Geeqie Team
5  *
6  * Author: John Ellis
7  *
8  * This software is released under the GNU General Public License (GNU GPL).
9  * Please read the included file COPYING for more information.
10  * This software comes with no warranty of any kind, use at your own risk!
11  */
12
13
14 #include "main.h"
15 #include "editors.h"
16
17 #include "filedata.h"
18 #include "filefilter.h"
19 #include "misc.h"
20 #include "ui_fileops.h"
21 #include "ui_spinner.h"
22 #include "ui_utildlg.h"
23 #include "utilops.h"
24
25 #include <errno.h>
26
27
28 #define EDITOR_WINDOW_WIDTH 500
29 #define EDITOR_WINDOW_HEIGHT 300
30
31
32
33 typedef struct _EditorVerboseData EditorVerboseData;
34 struct _EditorVerboseData {
35         GenericDialog *gd;
36         GtkWidget *button_close;
37         GtkWidget *button_stop;
38         GtkWidget *text;
39         GtkWidget *progress;
40         GtkWidget *spinner;
41 };
42
43 typedef struct _EditorData EditorData;
44 struct _EditorData {
45         gint flags;
46         GPid pid;
47         GList *list;
48         gint count;
49         gint total;
50         gboolean stopping;
51         EditorVerboseData *vd;
52         EditorCallback callback;
53         gpointer data;
54         const EditorDescription *editor;
55 };
56
57
58 static void editor_verbose_window_progress(EditorData *ed, const gchar *text);
59 static gint editor_command_next_start(EditorData *ed);
60 static gint editor_command_next_finish(EditorData *ed, gint status);
61 static gint editor_command_done(EditorData *ed);
62 static gint editor_command_parse(const EditorDescription *editor, GList *list, gchar **output);
63
64 /*
65  *-----------------------------------------------------------------------------
66  * external editor routines
67  *-----------------------------------------------------------------------------
68  */
69
70 GHashTable *editors = NULL;
71
72 #ifdef G_KEY_FILE_DESKTOP_GROUP
73 #define DESKTOP_GROUP G_KEY_FILE_DESKTOP_GROUP
74 #else
75 #define DESKTOP_GROUP "Desktop Entry"
76 #endif
77
78 void editor_description_free(EditorDescription *editor)
79 {
80         if (!editor) return;
81         
82         g_free(editor->key);
83         g_free(editor->name);
84         g_free(editor->exec);
85         g_free(editor->menu_path);
86         g_free(editor->hotkey);
87         string_list_free(editor->ext_list);
88         g_free(editor->icon);
89         g_free(editor->file);
90         g_free(editor);
91 }
92
93 static GList *editor_mime_types_to_extensions(gchar **mime_types)
94 {
95         /* FIXME: this should be rewritten to use the shared mime database, as soon as we switch to gio */
96         
97         static const gchar *conv_table[][2] = {
98                 {"application/x-ufraw", "%raw"},
99                 {"image/*",             "*"},
100                 {"image/bmp",           ".bmp"},
101                 {"image/gif",           ".gif"},
102                 {"image/jpeg",          ".jpeg;.jpg"},
103                 {"image/jpg",           ".jpg;.jpeg"},
104                 {"image/pcx",           ".pcx"},
105                 {"image/png",           ".png"},
106                 {"image/svg",           ".svg"},
107                 {"image/svg+xml",       ".svg"},
108                 {"image/svg+xml-compressed",    ".svg"},        
109                 {"image/tiff",          ".tiff;.tif"},
110                 {"image/x-bmp",         ".bmp"},
111                 {"image/x-canon-crw",   ".crw"},
112                 {"image/x-cr2",         ".cr2"},
113                 {"image/x-dcraw",       "%raw"},
114                 {"image/x-ico",         ".ico"},
115                 {"image/x-mrw",         ".mrw"},
116                 {"image/x-MS-bmp",      ".bmp"},
117                 {"image/x-nef",         ".nef"},
118                 {"image/x-orf",         ".orf"},
119                 {"image/x-pcx",         ".pcx"},
120                 {"image/xpm",           ".xpm"},
121                 {"image/x-png",         ".png"},
122                 {"image/x-portable-anymap",     ".pam"},        
123                 {"image/x-portable-bitmap",     ".pbm"},
124                 {"image/x-portable-graymap",    ".pgm"},
125                 {"image/x-portable-pixmap",     ".ppm"},
126                 {"image/x-psd",         ".psd"},
127                 {"image/x-raf",         ".raf"},
128                 {"image/x-sgi",         ".sgi"},
129                 {"image/x-tga",         ".tga"},
130                 {"image/x-xbitmap",     ".xbm"},
131                 {"image/x-xcf",         ".xcf"},
132                 {"image/x-xpixmap",     ".xpm"},
133                 {"image/x-x3f",         ".x3f"},
134                 {NULL, NULL}};
135         
136         gint i, j;
137         GList *list = NULL;
138         
139         for (i = 0; mime_types[i]; i++) 
140                 for (j = 0; conv_table[j][0]; j++)
141                         if (strcmp(mime_types[i], conv_table[j][0]) == 0)
142                                 list = g_list_concat(list, filter_to_list(conv_table[j][1]));
143         
144         return list;
145 }
146
147 static gboolean editor_read_desktop_file(const gchar *path)
148 {
149         GKeyFile *key_file;
150         EditorDescription *editor;
151         gchar *extensions;
152         const gchar *key = filename_from_path(path);
153         gchar **categories, **only_show_in, **not_show_in;
154         gchar *try_exec;
155
156         if (g_hash_table_lookup(editors, key)) return FALSE; /* the file found earlier wins */
157         
158         key_file = g_key_file_new();
159         if (!g_key_file_load_from_file(key_file, path, 0, NULL))
160                 {
161                 g_key_file_free(key_file);
162                 return FALSE;
163                 }
164         
165         editor = g_new0(EditorDescription, 1);
166         
167         editor->key = g_strdup(key);
168         editor->file = g_strdup(path);
169
170         g_hash_table_insert(editors, editor->key, editor);
171
172         if (g_key_file_get_boolean(key_file, DESKTOP_GROUP, "Hidden", NULL)) editor->hidden = TRUE;
173
174         categories = g_key_file_get_string_list(key_file, DESKTOP_GROUP, "Categories", NULL, NULL);
175         if (categories)
176                 {
177                 gboolean found = FALSE;
178                 gint i;
179                 for (i = 0; categories[i]; i++) 
180                         /* IMHO "Graphics" is exactly the category that we are interested in, so this does not have to be configurable */
181                         if (strcmp(categories[i], "Graphics") == 0 ||
182                             strcmp(categories[i], "X-Geeqie") == 0) 
183                                 {
184                                 found = TRUE;
185                                 break;
186                                 }
187                 if (!found) editor->hidden = TRUE;
188                 g_strfreev(categories);
189                 }
190         else
191                 {
192                 editor->hidden = TRUE;
193                 }
194
195         only_show_in = g_key_file_get_string_list(key_file, DESKTOP_GROUP, "OnlyShowIn", NULL, NULL);
196         if (only_show_in)
197                 {
198                 gboolean found = FALSE;
199                 gint i;
200                 for (i = 0; only_show_in[i]; i++) 
201                         if (strcmp(only_show_in[i], "X-Geeqie") == 0)
202                                 {
203                                 found = TRUE;
204                                 break;
205                                 }
206                 if (!found) editor->hidden = TRUE;
207                 g_strfreev(only_show_in);
208                 }
209
210         not_show_in = g_key_file_get_string_list(key_file, DESKTOP_GROUP, "NotShowIn", NULL, NULL);
211         if (not_show_in)
212                 {
213                 gboolean found = FALSE;
214                 gint i;
215                 for (i = 0; not_show_in[i]; i++) 
216                         if (strcmp(not_show_in[i], "X-Geeqie") == 0)
217                                 {
218                                 found = TRUE;
219                                 break;
220                                 }
221                 if (found) editor->hidden = TRUE;
222                 g_strfreev(not_show_in);
223                 }
224                 
225                 
226         try_exec = g_key_file_get_string(key_file, DESKTOP_GROUP, "TryExec", NULL);
227         if (try_exec && !editor->hidden)
228                 {
229                 gchar *try_exec_res = g_find_program_in_path(try_exec);
230                 if (!try_exec_res) editor->hidden = TRUE;
231                 g_free(try_exec_res);
232                 g_free(try_exec);
233                 }
234                 
235         if (editor->hidden) 
236                 {
237                 /* hidden editors will be deleted, no need to parse the rest */
238                 g_key_file_free(key_file);
239                 return TRUE;
240                 }
241         
242         editor->name = g_key_file_get_locale_string(key_file, DESKTOP_GROUP, "Name", NULL, NULL);
243         editor->icon = g_key_file_get_string(key_file, DESKTOP_GROUP, "Icon", NULL);
244
245         editor->exec = g_key_file_get_string(key_file, DESKTOP_GROUP, "Exec", NULL);
246         
247         /* we take only editors that accept parameters, FIXME: the test can be improved */
248         if (!strchr(editor->exec, '%')) editor->hidden = TRUE; 
249         
250         editor->menu_path = g_key_file_get_string(key_file, DESKTOP_GROUP, "X-Geeqie-Menu-Path", NULL);
251         if (!editor->menu_path) editor->menu_path = g_strdup("EditMenu/ExternalMenu");
252         
253         editor->hotkey = g_key_file_get_string(key_file, DESKTOP_GROUP, "X-Geeqie-Hotkey", NULL);
254
255         extensions = g_key_file_get_string(key_file, DESKTOP_GROUP, "X-Geeqie-File-Extensions", NULL);
256         if (extensions)
257                 editor->ext_list = filter_to_list(extensions);
258         else
259                 {
260                 gchar **mime_types = g_key_file_get_string_list(key_file, DESKTOP_GROUP, "MimeType", NULL, NULL);
261                 if (mime_types)
262                         {
263                         editor->ext_list = editor_mime_types_to_extensions(mime_types);
264                         g_strfreev(mime_types);
265                         if (!editor->ext_list) editor->hidden = TRUE; 
266                         }
267                 
268                 }
269                 
270
271         if (g_key_file_get_boolean(key_file, DESKTOP_GROUP, "X-Geeqie-Keep-Fullscreen", NULL)) editor->flags |= EDITOR_KEEP_FS;
272         if (g_key_file_get_boolean(key_file, DESKTOP_GROUP, "X-Geeqie-Verbose", NULL)) editor->flags |= EDITOR_VERBOSE;
273         if (g_key_file_get_boolean(key_file, DESKTOP_GROUP, "X-Geeqie-Verbose-Multi", NULL)) editor->flags |= EDITOR_VERBOSE_MULTI;
274         if (g_key_file_get_boolean(key_file, DESKTOP_GROUP, "X-Geeqie-Filter", NULL)) editor->flags |= EDITOR_DEST;
275         if (g_key_file_get_boolean(key_file, DESKTOP_GROUP, "Terminal", NULL)) editor->flags |= EDITOR_TERMINAL;
276
277         
278         editor->flags |= editor_command_parse(editor, NULL, NULL);
279         g_key_file_free(key_file);
280         
281         return TRUE;    
282 }
283
284 static gboolean editor_remove_desktop_file_cb(gpointer key, gpointer value, gpointer user_data)
285 {
286         EditorDescription *editor = value;
287         return editor->hidden;
288 }
289
290 static void editor_read_desktop_dir(const gchar *path)
291 {
292         DIR *dp;
293         struct dirent *dir;
294         gchar *pathl;
295
296         pathl = path_from_utf8(path);
297         dp = opendir(pathl);
298         g_free(pathl);
299         if (!dp)
300                 {
301                 /* dir not found */
302                 return;
303                 }
304         while ((dir = readdir(dp)) != NULL)
305                 {
306                 gchar *namel = dir->d_name;
307                 size_t len = strlen(namel);
308                 
309                 if (len > 8 && strncasecmp(namel + len - 8, ".desktop", 8) == 0)
310                         {
311                         gchar *name = path_to_utf8(namel);
312                         gchar *dpath = g_build_filename(path, name, NULL);
313                         editor_read_desktop_file(dpath);
314                         g_free(dpath);
315                         g_free(name);
316                         }       
317                 }
318         closedir(dp);
319 }
320
321 void editor_load_descriptions(void)
322 {
323         gchar *path;
324         gchar *xdg_data_dirs;
325         gchar *all_dirs;
326         gchar **split_dirs;
327         gint i;
328         
329         if (!editors)
330                 {
331                 editors = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, (GDestroyNotify)editor_description_free);
332                 }
333
334         xdg_data_dirs = getenv("XDG_DATA_DIRS");
335         if (xdg_data_dirs && xdg_data_dirs[0])
336                 xdg_data_dirs = path_to_utf8(xdg_data_dirs);
337         else
338                 xdg_data_dirs = g_strdup("/usr/share");
339         
340         all_dirs = g_strconcat(get_rc_dir(), ":", GQ_APP_DIR, ":", xdg_data_home_get(), ":", xdg_data_dirs, NULL);
341         
342         g_free(xdg_data_dirs);
343
344         split_dirs = g_strsplit(all_dirs, ":", 0);
345         
346         g_free(all_dirs);
347
348         for (i = 0; split_dirs[i]; i++)
349                 {
350                 path = g_build_filename(split_dirs[i], "applications", NULL);
351                 editor_read_desktop_dir(path);
352                 g_free(path);
353                 }
354                 
355         g_strfreev(split_dirs);
356         
357         g_hash_table_foreach_remove(editors, editor_remove_desktop_file_cb, NULL);
358 }
359
360 static void editor_list_add_cb(gpointer key, gpointer value, gpointer data)
361 {
362         GList **listp = data;
363         EditorDescription *editor = value;
364         
365         /* do not show the special commands in any list, they are called explicitelly */ 
366         if (strcmp(editor->key, CMD_COPY) == 0 ||
367             strcmp(editor->key, CMD_MOVE) == 0 ||  
368             strcmp(editor->key, CMD_RENAME) == 0 ||
369             strcmp(editor->key, CMD_DELETE) == 0 ||
370             strcmp(editor->key, CMD_FOLDER) == 0) return;
371
372         *listp = g_list_prepend(*listp, editor);
373 }
374
375 GList *editor_list_get(void)
376 {
377         GList *editors_list = NULL;
378         g_hash_table_foreach(editors, editor_list_add_cb, &editors_list);
379         return editors_list;
380 }
381
382 /* ------------------------------ */
383
384
385 static void editor_verbose_data_free(EditorData *ed)
386 {
387         if (!ed->vd) return;
388         g_free(ed->vd);
389         ed->vd = NULL;
390 }
391
392 static void editor_data_free(EditorData *ed)
393 {
394         editor_verbose_data_free(ed);
395         g_free(ed);
396 }
397
398 static void editor_verbose_window_close(GenericDialog *gd, gpointer data)
399 {
400         EditorData *ed = data;
401
402         generic_dialog_close(gd);
403         editor_verbose_data_free(ed);
404         if (ed->pid == -1) editor_data_free(ed); /* the process has already terminated */
405 }
406
407 static void editor_verbose_window_stop(GenericDialog *gd, gpointer data)
408 {
409         EditorData *ed = data;
410         ed->stopping = TRUE;
411         ed->count = 0;
412         editor_verbose_window_progress(ed, _("stopping..."));
413 }
414
415 static void editor_verbose_window_enable_close(EditorVerboseData *vd)
416 {
417         vd->gd->cancel_cb = editor_verbose_window_close;
418
419         spinner_set_interval(vd->spinner, -1);
420         gtk_widget_set_sensitive(vd->button_stop, FALSE);
421         gtk_widget_set_sensitive(vd->button_close, TRUE);
422 }
423
424 static EditorVerboseData *editor_verbose_window(EditorData *ed, const gchar *text)
425 {
426         EditorVerboseData *vd;
427         GtkWidget *scrolled;
428         GtkWidget *hbox;
429         gchar *buf;
430
431         vd = g_new0(EditorVerboseData, 1);
432
433         vd->gd = file_util_gen_dlg(_("Edit command results"), "editor_results",
434                                    NULL, FALSE,
435                                    NULL, ed);
436         buf = g_strdup_printf(_("Output of %s"), text);
437         generic_dialog_add_message(vd->gd, NULL, buf, NULL);
438         g_free(buf);
439         vd->button_stop = generic_dialog_add_button(vd->gd, GTK_STOCK_STOP, NULL,
440                                                    editor_verbose_window_stop, FALSE);
441         gtk_widget_set_sensitive(vd->button_stop, FALSE);
442         vd->button_close = generic_dialog_add_button(vd->gd, GTK_STOCK_CLOSE, NULL,
443                                                     editor_verbose_window_close, TRUE);
444         gtk_widget_set_sensitive(vd->button_close, FALSE);
445
446         scrolled = gtk_scrolled_window_new(NULL, NULL);
447         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolled), GTK_SHADOW_IN);
448         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled),
449                                        GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
450         gtk_box_pack_start(GTK_BOX(vd->gd->vbox), scrolled, TRUE, TRUE, 5);
451         gtk_widget_show(scrolled);
452
453         vd->text = gtk_text_view_new();
454         gtk_text_view_set_editable(GTK_TEXT_VIEW(vd->text), FALSE);
455         gtk_widget_set_size_request(vd->text, EDITOR_WINDOW_WIDTH, EDITOR_WINDOW_HEIGHT);
456         gtk_container_add(GTK_CONTAINER(scrolled), vd->text);
457         gtk_widget_show(vd->text);
458
459         hbox = gtk_hbox_new(FALSE, 0);
460         gtk_box_pack_start(GTK_BOX(vd->gd->vbox), hbox, FALSE, FALSE, 0);
461         gtk_widget_show(hbox);
462
463         vd->progress = gtk_progress_bar_new();
464         gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(vd->progress), 0.0);
465         gtk_box_pack_start(GTK_BOX(hbox), vd->progress, TRUE, TRUE, 0);
466         gtk_widget_show(vd->progress);
467
468         vd->spinner = spinner_new(NULL, SPINNER_SPEED);
469         gtk_box_pack_start(GTK_BOX(hbox), vd->spinner, FALSE, FALSE, 0);
470         gtk_widget_show(vd->spinner);
471
472         gtk_widget_show(vd->gd->dialog);
473
474         ed->vd = vd;
475         return vd;
476 }
477
478 static void editor_verbose_window_fill(EditorVerboseData *vd, gchar *text, gint len)
479 {
480         GtkTextBuffer *buffer;
481         GtkTextIter iter;
482
483         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(vd->text));
484         gtk_text_buffer_get_iter_at_offset(buffer, &iter, -1);
485         gtk_text_buffer_insert(buffer, &iter, text, len);
486 }
487
488 static void editor_verbose_window_progress(EditorData *ed, const gchar *text)
489 {
490         if (!ed->vd) return;
491
492         if (ed->total)
493                 {
494                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(ed->vd->progress), (gdouble)ed->count / ed->total);
495                 }
496
497         gtk_progress_bar_set_text(GTK_PROGRESS_BAR(ed->vd->progress), (text) ? text : "");
498 }
499
500 static gboolean editor_verbose_io_cb(GIOChannel *source, GIOCondition condition, gpointer data)
501 {
502         EditorData *ed = data;
503         gchar buf[512];
504         gsize count;
505
506         if (condition & G_IO_IN)
507                 {
508                 while (g_io_channel_read_chars(source, buf, sizeof(buf), &count, NULL) == G_IO_STATUS_NORMAL)
509                         {
510                         if (!g_utf8_validate(buf, count, NULL))
511                                 {
512                                 gchar *utf8;
513
514                                 utf8 = g_locale_to_utf8(buf, count, NULL, NULL, NULL);
515                                 if (utf8)
516                                         {
517                                         editor_verbose_window_fill(ed->vd, utf8, -1);
518                                         g_free(utf8);
519                                         }
520                                 else
521                                         {
522                                         editor_verbose_window_fill(ed->vd, "Error converting text to valid utf8\n", -1);
523                                         }
524                                 }
525                         else
526                                 {
527                                 editor_verbose_window_fill(ed->vd, buf, count);
528                                 }
529                         }
530                 }
531
532         if (condition & (G_IO_ERR | G_IO_HUP))
533                 {
534                 g_io_channel_shutdown(source, TRUE, NULL);
535                 return FALSE;
536                 }
537
538         return TRUE;
539 }
540
541 typedef enum {
542         PATH_FILE,
543         PATH_FILE_URL,
544         PATH_DEST
545 } PathType;
546
547
548 static gchar *editor_command_path_parse(const FileData *fd, PathType type, const EditorDescription *editor)
549 {
550         GString *string;
551         gchar *pathl;
552         const gchar *p = NULL;
553
554         string = g_string_new("");
555
556         if (type == PATH_FILE || type == PATH_FILE_URL)
557                 {
558                 GList *work = editor->ext_list;
559
560                 if (!work)
561                         p = fd->path;
562                 else
563                         {
564                         while (work)
565                                 {
566                                 GList *work2;
567                                 gchar *ext = work->data;
568                                 work = work->next;
569
570                                 if (strcmp(ext, "*") == 0 ||
571                                     strcasecmp(ext, fd->extension) == 0)
572                                         {
573                                         p = fd->path;
574                                         break;
575                                         }
576
577                                 work2 = fd->sidecar_files;
578                                 while (work2)
579                                         {
580                                         FileData *sfd = work2->data;
581                                         work2 = work2->next;
582
583                                         if (strcasecmp(ext, sfd->extension) == 0)
584                                                 {
585                                                 p = sfd->path;
586                                                 break;
587                                                 }
588                                         }
589                                 if (p) break;
590                                 }
591                         if (!p) return NULL;
592                         }
593                 }
594         else if (type == PATH_DEST)
595                 {
596                 if (fd->change && fd->change->dest)
597                         p = fd->change->dest;
598                 else
599                         p = "";
600                 }
601
602         while (*p != '\0')
603                 {
604                 /* must escape \, ", `, and $ to avoid problems,
605                  * we assume system shell supports bash-like escaping
606                  */
607                 if (strchr("\\\"`$", *p) != NULL)
608                         {
609                         string = g_string_append_c(string, '\\');
610                         }
611                 string = g_string_append_c(string, *p);
612                 p++;
613                 }
614
615         if (type == PATH_FILE_URL) g_string_prepend(string, "file://");
616         pathl = path_from_utf8(string->str);
617         g_string_free(string, TRUE);
618
619         return pathl;
620 }
621
622
623 static gint editor_command_parse(const EditorDescription *editor, GList *list, gchar **output)
624 {
625         gint flags = 0;
626         const gchar *p;
627         GString *result = NULL;
628
629         if (output)
630                 result = g_string_new("");
631
632         if (editor->exec[0] == '\0')
633                 {
634                 flags |= EDITOR_ERROR_EMPTY;
635                 goto err;
636                 }
637         
638         p = editor->exec;
639         /* skip leading whitespaces if any */
640         while (g_ascii_isspace(*p)) p++;
641
642         /* command */
643
644         while (*p)
645                 {
646                 if (*p != '%')
647                         {
648                         if (output) result = g_string_append_c(result, *p);
649                         }
650                 else /* *p == '%' */
651                         {
652                         gchar *pathl = NULL;
653
654                         p++;
655
656                         switch (*p)
657                                 {
658                                 case 'f': /* single file */
659                                 case 'u': /* single url */
660                                         flags |= EDITOR_FOR_EACH;
661                                         if (flags & EDITOR_SINGLE_COMMAND)
662                                                 {
663                                                 flags |= EDITOR_ERROR_INCOMPATIBLE;
664                                                 goto err;
665                                                 }
666                                         if (output)
667                                                 {
668                                                 /* use the first file from the list */
669                                                 if (!list || !list->data)
670                                                         {
671                                                         flags |= EDITOR_ERROR_NO_FILE;
672                                                         goto err;
673                                                         }
674                                                 pathl = editor_command_path_parse((FileData *)list->data,
675                                                                                   (*p == 'f') ? PATH_FILE : PATH_FILE_URL,
676                                                                                   editor);
677                                                 if (!pathl)
678                                                         {
679                                                         flags |= EDITOR_ERROR_NO_FILE;
680                                                         goto err;
681                                                         }
682                                                 result = g_string_append_c(result, '"');
683                                                 result = g_string_append(result, pathl);
684                                                 g_free(pathl);
685                                                 result = g_string_append_c(result, '"');
686                                                 }
687                                         break;
688
689                                 case 'F':
690                                 case 'U':
691                                         flags |= EDITOR_SINGLE_COMMAND;
692                                         if (flags & (EDITOR_FOR_EACH | EDITOR_DEST))
693                                                 {
694                                                 flags |= EDITOR_ERROR_INCOMPATIBLE;
695                                                 goto err;
696                                                 }
697
698                                         if (output)
699                                                 {
700                                                 /* use whole list */
701                                                 GList *work = list;
702                                                 gboolean ok = FALSE;
703
704                                                 while (work)
705                                                         {
706                                                         FileData *fd = work->data;
707                                                         pathl = editor_command_path_parse(fd, (*p == 'F') ? PATH_FILE : PATH_FILE_URL, editor);
708
709                                                         if (pathl)
710                                                                 {
711                                                                 ok = TRUE;
712                                                                 if (work != list) g_string_append_c(result, ' ');
713                                                                 result = g_string_append_c(result, '"');
714                                                                 result = g_string_append(result, pathl);
715                                                                 g_free(pathl);
716                                                                 result = g_string_append_c(result, '"');
717                                                                 }
718                                                         work = work->next;
719                                                         }
720                                                 if (!ok)
721                                                         {
722                                                         flags |= EDITOR_ERROR_NO_FILE;
723                                                         goto err;
724                                                         }
725                                                 }
726                                         break;
727                                 case 'i':
728                                         if (output)
729                                                 {
730                                                 result = g_string_append(result, editor->icon);
731                                                 }
732                                         break;
733                                 case 'c':
734                                         if (output)
735                                                 {
736                                                 result = g_string_append(result, editor->name);
737                                                 }
738                                         break;
739                                 case 'k':
740                                         if (output)
741                                                 {
742                                                 result = g_string_append(result, editor->file);
743                                                 }
744                                         break;
745                                 case '%':
746                                         /* %% = % escaping */
747                                         if (output) result = g_string_append_c(result, *p);
748                                         break;
749                                 case 'd':
750                                 case 'D':
751                                 case 'n':
752                                 case 'N':
753                                 case 'v':
754                                 case 'm':
755                                         /* deprecated according to spec, ignore */
756                                         break;
757                                 default:
758                                         flags |= EDITOR_ERROR_SYNTAX;
759                                         goto err;
760                                 }
761                         }
762                 p++;
763                 }
764
765         if (output) *output = g_string_free(result, FALSE);
766         return flags;
767
768
769 err:
770         if (output)
771                 {
772                 g_string_free(result, TRUE);
773                 *output = NULL;
774                 }
775         return flags;
776 }
777
778
779 static void editor_child_exit_cb (GPid pid, gint status, gpointer data)
780 {
781         EditorData *ed = data;
782         g_spawn_close_pid(pid);
783         ed->pid = -1;
784
785         editor_command_next_finish(ed, status);
786 }
787
788
789 static gint editor_command_one(const EditorDescription *editor, GList *list, EditorData *ed)
790 {
791         gchar *command;
792         FileData *fd = list->data;
793         GPid pid;
794         gint standard_output;
795         gint standard_error;
796         gboolean ok;
797
798         ed->pid = -1;
799         ed->flags = editor->flags | editor_command_parse(editor, list, &command);
800
801         ok = !(ed->flags & EDITOR_ERROR_MASK);
802
803         if (ok)
804                 {
805                 ok = (options->shell.path && *options->shell.path);
806                 if (!ok) log_printf("ERROR: empty shell command\n");
807                         
808                 if (ok)
809                         {
810                         ok = (access(options->shell.path, X_OK) == 0);
811                         if (!ok) log_printf("ERROR: cannot execute shell command '%s'\n", options->shell.path);
812                         }
813
814                 if (!ok) ed->flags |= EDITOR_ERROR_CANT_EXEC;
815                 }
816
817         if (ok)
818                 {
819                 gchar *working_directory;
820                 gchar *args[4];
821                 guint n = 0;
822
823                 working_directory = remove_level_from_path(fd->path);
824                 args[n++] = options->shell.path;
825                 if (options->shell.options && *options->shell.options)
826                         args[n++] = options->shell.options;
827                 args[n++] = command;
828                 args[n] = NULL;
829
830                 if ((ed->flags & EDITOR_DEST) && fd->change && fd->change->dest) /* FIXME: error handling */
831                         {
832                         setenv("GEEQIE_DESTINATION", fd->change->dest, TRUE);
833                         }
834                 else
835                         {
836                         unsetenv("GEEQIE_DESTINATION");
837                         }
838
839                 ok = g_spawn_async_with_pipes(working_directory, args, NULL,
840                                       G_SPAWN_DO_NOT_REAP_CHILD, /* GSpawnFlags */
841                                       NULL, NULL,
842                                       &pid,
843                                       NULL,
844                                       ed->vd ? &standard_output : NULL,
845                                       ed->vd ? &standard_error : NULL,
846                                       NULL);
847                 
848                 g_free(working_directory);
849
850                 if (!ok) ed->flags |= EDITOR_ERROR_CANT_EXEC;
851                 }
852
853         if (ok)
854                 {
855                 g_child_watch_add(pid, editor_child_exit_cb, ed);
856                 ed->pid = pid;
857                 }
858
859         if (ed->vd)
860                 {
861                 if (!ok)
862                         {
863                         gchar *buf;
864
865                         buf = g_strdup_printf(_("Failed to run command:\n%s\n"), editor->file);
866                         editor_verbose_window_fill(ed->vd, buf, strlen(buf));
867                         g_free(buf);
868
869                         }
870                 else
871                         {
872                         GIOChannel *channel_output;
873                         GIOChannel *channel_error;
874
875                         channel_output = g_io_channel_unix_new(standard_output);
876                         g_io_channel_set_flags(channel_output, G_IO_FLAG_NONBLOCK, NULL);
877                         g_io_channel_set_encoding(channel_output, NULL, NULL);
878
879                         g_io_add_watch_full(channel_output, G_PRIORITY_HIGH, G_IO_IN | G_IO_ERR | G_IO_HUP,
880                                             editor_verbose_io_cb, ed, NULL);
881                         g_io_channel_unref(channel_output);
882
883                         channel_error = g_io_channel_unix_new(standard_error);
884                         g_io_channel_set_flags(channel_error, G_IO_FLAG_NONBLOCK, NULL);
885                         g_io_channel_set_encoding(channel_error, NULL, NULL);
886
887                         g_io_add_watch_full(channel_error, G_PRIORITY_HIGH, G_IO_IN | G_IO_ERR | G_IO_HUP,
888                                             editor_verbose_io_cb, ed, NULL);
889                         g_io_channel_unref(channel_error);
890                         }
891                 }
892
893         g_free(command);
894
895         return ed->flags & EDITOR_ERROR_MASK;
896 }
897
898 static gint editor_command_next_start(EditorData *ed)
899 {
900         if (ed->vd) editor_verbose_window_fill(ed->vd, "\n", 1);
901
902         if (ed->list && ed->count < ed->total)
903                 {
904                 FileData *fd;
905                 gint error;
906
907                 fd = ed->list->data;
908
909                 if (ed->vd)
910                         {
911                         editor_verbose_window_progress(ed, (ed->flags & EDITOR_FOR_EACH) ? fd->path : _("running..."));
912                         }
913                 ed->count++;
914
915                 error = editor_command_one(ed->editor, ed->list, ed);
916                 if (!error && ed->vd)
917                         {
918                         gtk_widget_set_sensitive(ed->vd->button_stop, (ed->list != NULL) );
919                         if (ed->flags & EDITOR_FOR_EACH)
920                                 {
921                                 editor_verbose_window_fill(ed->vd, fd->path, strlen(fd->path));
922                                 editor_verbose_window_fill(ed->vd, "\n", 1);
923                                 }
924                         }
925
926                 if (!error)
927                         return 0;
928                 else
929                         /* command was not started, call the finish immediately */
930                         return editor_command_next_finish(ed, 0);
931                 }
932
933         /* everything is done */
934         return editor_command_done(ed);
935 }
936
937 static gint editor_command_next_finish(EditorData *ed, gint status)
938 {
939         gint cont = ed->stopping ? EDITOR_CB_SKIP : EDITOR_CB_CONTINUE;
940
941         if (status)
942                 ed->flags |= EDITOR_ERROR_STATUS;
943
944         if (ed->flags & EDITOR_FOR_EACH)
945                 {
946                 /* handle the first element from the list */
947                 GList *fd_element = ed->list;
948
949                 ed->list = g_list_remove_link(ed->list, fd_element);
950                 if (ed->callback)
951                         {
952                         cont = ed->callback(ed->list ? ed : NULL, ed->flags, fd_element, ed->data);
953                         if (ed->stopping && cont == EDITOR_CB_CONTINUE) cont = EDITOR_CB_SKIP;
954                         }
955                 filelist_free(fd_element);
956                 }
957         else
958                 {
959                 /* handle whole list */
960                 if (ed->callback)
961                         cont = ed->callback(NULL, ed->flags, ed->list, ed->data);
962                 filelist_free(ed->list);
963                 ed->list = NULL;
964                 }
965
966         if (cont == EDITOR_CB_SUSPEND)
967                 return ed->flags & EDITOR_ERROR_MASK;
968         else if (cont == EDITOR_CB_SKIP)
969                 return editor_command_done(ed);
970         else
971                 return editor_command_next_start(ed);
972 }
973
974 static gint editor_command_done(EditorData *ed)
975 {
976         gint flags;
977
978         if (ed->vd)
979                 {
980                 const gchar *text;
981
982                 if (ed->count == ed->total)
983                         {
984                         text = _("done");
985                         }
986                 else
987                         {
988                         text = _("stopped by user");
989                         }
990                 editor_verbose_window_progress(ed, text);
991                 editor_verbose_window_enable_close(ed->vd);
992                 }
993
994         /* free the not-handled items */
995         if (ed->list)
996                 {
997                 ed->flags |= EDITOR_ERROR_SKIPPED;
998                 if (ed->callback) ed->callback(NULL, ed->flags, ed->list, ed->data);
999                 filelist_free(ed->list);
1000                 ed->list = NULL;
1001                 }
1002
1003         ed->count = 0;
1004
1005         flags = ed->flags & EDITOR_ERROR_MASK;
1006
1007         if (!ed->vd) editor_data_free(ed);
1008
1009         return flags;
1010 }
1011
1012 void editor_resume(gpointer ed)
1013 {
1014         editor_command_next_start(ed);
1015 }
1016
1017 void editor_skip(gpointer ed)
1018 {
1019         editor_command_done(ed);
1020 }
1021
1022 static gint editor_command_start(const EditorDescription *editor, const gchar *text, GList *list, EditorCallback cb, gpointer data)
1023 {
1024         EditorData *ed;
1025         gint flags = editor->flags;
1026
1027         if (flags & EDITOR_ERROR_MASK) return flags & EDITOR_ERROR_MASK;
1028
1029         ed = g_new0(EditorData, 1);
1030         ed->list = filelist_copy(list);
1031         ed->flags = flags;
1032         ed->editor = editor;
1033         ed->total = (flags & EDITOR_SINGLE_COMMAND) ? 1 : g_list_length(list);
1034         ed->count = 0;
1035         ed->stopping = FALSE;
1036         ed->callback = cb;
1037         ed->data =  data;
1038
1039         if ((flags & EDITOR_VERBOSE_MULTI) && list && list->next)
1040                 flags |= EDITOR_VERBOSE;
1041
1042         if (flags & EDITOR_VERBOSE)
1043                 editor_verbose_window(ed, text);
1044
1045         editor_command_next_start(ed);
1046         /* errors from editor_command_next_start will be handled via callback */
1047         return flags & EDITOR_ERROR_MASK;
1048 }
1049
1050 gboolean is_valid_editor_command(const gchar *key)
1051 {
1052         if (!key) return FALSE;
1053         return g_hash_table_lookup(editors, key) != NULL;
1054 }
1055
1056 gint start_editor_from_filelist_full(const gchar *key, GList *list, EditorCallback cb, gpointer data)
1057 {
1058         gint error;
1059         EditorDescription *editor;
1060         if (!key) return FALSE;
1061         
1062         editor = g_hash_table_lookup(editors, key);
1063
1064         if (!list) return FALSE;
1065         if (!editor) return FALSE;
1066
1067         error = editor_command_start(editor, editor->name, list, cb, data);
1068
1069         if (error & EDITOR_ERROR_MASK)
1070                 {
1071                 gchar *text = g_strdup_printf(_("%s\n\"%s\""), editor_get_error_str(error), editor->file);
1072                 
1073                 file_util_warning_dialog(_("Invalid editor command"), text, GTK_STOCK_DIALOG_ERROR, NULL);
1074                 g_free(text);
1075                 }
1076
1077         return error;
1078 }
1079
1080 gint start_editor_from_filelist(const gchar *key, GList *list)
1081 {
1082         return start_editor_from_filelist_full(key, list,  NULL, NULL);
1083 }
1084
1085 gint start_editor_from_file_full(const gchar *key, FileData *fd, EditorCallback cb, gpointer data)
1086 {
1087         GList *list;
1088         gint error;
1089
1090         if (!fd) return FALSE;
1091
1092         list = g_list_append(NULL, fd);
1093         error = start_editor_from_filelist_full(key, list, cb, data);
1094         g_list_free(list);
1095         return error;
1096 }
1097
1098 gint start_editor_from_file(const gchar *key, FileData *fd)
1099 {
1100         return start_editor_from_file_full(key, fd, NULL, NULL);
1101 }
1102
1103 gint editor_window_flag_set(const gchar *key)
1104 {
1105         EditorDescription *editor;
1106         if (!key) return TRUE;
1107         
1108         editor = g_hash_table_lookup(editors, key);
1109         if (!editor) return TRUE;
1110
1111         return (editor->flags & EDITOR_KEEP_FS);
1112 }
1113
1114 gint editor_is_filter(const gchar *key)
1115 {
1116         EditorDescription *editor;
1117         if (!key) return TRUE;
1118         
1119         editor = g_hash_table_lookup(editors, key);
1120         if (!editor) return TRUE;
1121
1122         return (editor->flags & EDITOR_DEST);
1123 }
1124
1125 const gchar *editor_get_error_str(gint flags)
1126 {
1127         if (flags & EDITOR_ERROR_EMPTY) return _("Editor template is empty.");
1128         if (flags & EDITOR_ERROR_SYNTAX) return _("Editor template has incorrect syntax.");
1129         if (flags & EDITOR_ERROR_INCOMPATIBLE) return _("Editor template uses incompatible macros.");
1130         if (flags & EDITOR_ERROR_NO_FILE) return _("Can't find matching file type.");
1131         if (flags & EDITOR_ERROR_CANT_EXEC) return _("Can't execute external editor.");
1132         if (flags & EDITOR_ERROR_STATUS) return _("External editor returned error status.");
1133         if (flags & EDITOR_ERROR_SKIPPED) return _("File was skipped.");
1134         return _("Unknown error.");
1135 }
1136
1137 const gchar *editor_get_name(const gchar *key)
1138 {
1139         EditorDescription *editor = g_hash_table_lookup(editors, key);
1140
1141         if (!editor) return NULL;
1142
1143         return editor->name;
1144 }
1145 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */