Simplify GString usage
[geeqie.git] / src / remote.cc
1 /*
2  * Copyright (C) 2004 John Ellis
3  * Copyright (C) 2008 - 2016 The Geeqie Team
4  *
5  * Author: John Ellis
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include "main.h"
23 #include "remote.h"
24
25 #include "cache-maint.h"
26 #include "collect.h"
27 #include "collect-io.h"
28 #include "exif.h"
29 #include "filedata.h"
30 #include "filefilter.h"
31 #include "image.h"
32 #include "img-view.h"
33 #include "layout-image.h"
34 #include "layout-util.h"
35 #include "misc.h"
36 #include "pixbuf-renderer.h"
37 #include "slideshow.h"
38 #include "ui-fileops.h"
39 #include "ui-misc.h"
40 #include "utilops.h"
41 #include "rcfile.h"
42 #include "view-file.h"
43
44 #include <csignal>
45 #include <sys/socket.h>
46 #include <sys/un.h>
47
48 #include "glua.h"
49
50 #define SERVER_MAX_CLIENTS 8
51
52 #define REMOTE_SERVER_BACKLOG 4
53
54
55 #ifndef UNIX_PATH_MAX
56 #define UNIX_PATH_MAX 108
57 #endif
58
59
60 static RemoteConnection *remote_client_open(const gchar *path);
61 static gint remote_client_send(RemoteConnection *rc, const gchar *text);
62 static void gr_raise(const gchar *text, GIOChannel *channel, gpointer data);
63
64 static LayoutWindow *lw_id = nullptr; /* points to the window set by the --id option */
65
66 struct RemoteClient {
67         gint fd;
68         guint channel_id; /* event source id */
69         RemoteConnection *rc;
70 };
71
72 struct RemoteData {
73         CollectionData *command_collection;
74         GList *file_list;
75         gboolean single_dir;
76 };
77
78 /* To enable file names containing newlines to be processed correctly,
79  * the --print0 remote option sets returned data to be terminated with a null
80  * character rather a newline
81  */
82 static gboolean print0 = FALSE;
83
84 /* Remote commands from main.cc are prepended with the current dir the remote
85  * command was made from. Some remote commands require this. The
86  * value is stored here
87  */
88 static gchar *pwd = nullptr;
89
90 /**
91  * @brief Ensures file path is absolute.
92  * @param[in] filename Filepath, absolute or relative to calling directory
93  * @returns absolute path
94  *
95  * If first character of input filepath is not the directory
96  * separator, assume it as a relative path and prepend
97  * the directory the remote command was initiated from
98  *
99  * Return value must be freed with g_free()
100  */
101 static gchar *set_pwd(gchar *filename)
102 {
103         gchar *temp;
104
105         if (strncmp(filename, G_DIR_SEPARATOR_S, 1) != 0)
106                 {
107                 temp = g_build_filename(pwd, filename, NULL);
108                 }
109         else
110                 {
111                 temp = g_strdup(filename);
112                 }
113
114         return temp;
115 }
116
117 static gboolean remote_server_client_cb(GIOChannel *source, GIOCondition condition, gpointer data)
118 {
119         auto client = static_cast<RemoteClient *>(data);
120         RemoteConnection *rc;
121         GIOStatus status = G_IO_STATUS_NORMAL;
122
123         lw_id = nullptr;
124         rc = client->rc;
125
126         if (condition & G_IO_IN)
127                 {
128                 gchar *buffer = nullptr;
129                 GError *error = nullptr;
130                 gsize termpos;
131                 /** @FIXME it should be possible to terminate the command with a null character */
132                 g_io_channel_set_line_term(source, "<gq_end_of_command>", -1);
133                 while ((status = g_io_channel_read_line(source, &buffer, nullptr, &termpos, &error)) == G_IO_STATUS_NORMAL)
134                         {
135                         if (buffer)
136                                 {
137                                 buffer[termpos] = '\0';
138
139                                 if (strlen(buffer) > 0)
140                                         {
141                                         if (rc->read_func) rc->read_func(rc, buffer, source, rc->read_data);
142                                         g_io_channel_write_chars(source, "<gq_end_of_command>", -1, nullptr, nullptr); /* empty line finishes the command */
143                                         g_io_channel_flush(source, nullptr);
144                                         }
145                                 g_free(buffer);
146
147                                 buffer = nullptr;
148                                 }
149                         }
150
151                 if (error)
152                         {
153                         log_printf("error reading socket: %s\n", error->message);
154                         g_error_free(error);
155                         }
156                 }
157
158         if (condition & G_IO_HUP || status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
159                 {
160                 rc->clients = g_list_remove(rc->clients, client);
161
162                 DEBUG_1("HUP detected, closing client.");
163                 DEBUG_1("client count %d", g_list_length(rc->clients));
164
165                 g_source_remove(client->channel_id);
166                 close(client->fd);
167                 g_free(client);
168                 }
169
170         return TRUE;
171 }
172
173 static void remote_server_client_add(RemoteConnection *rc, gint fd)
174 {
175         RemoteClient *client;
176         GIOChannel *channel;
177
178         if (g_list_length(rc->clients) > SERVER_MAX_CLIENTS)
179                 {
180                 log_printf("maximum remote clients of %d exceeded, closing connection\n", SERVER_MAX_CLIENTS);
181                 close(fd);
182                 return;
183                 }
184
185         client = g_new0(RemoteClient, 1);
186         client->rc = rc;
187         client->fd = fd;
188
189         channel = g_io_channel_unix_new(fd);
190         client->channel_id = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, static_cast<GIOCondition>(G_IO_IN | G_IO_HUP),
191                                                  remote_server_client_cb, client, nullptr);
192         g_io_channel_unref(channel);
193
194         rc->clients = g_list_append(rc->clients, client);
195         DEBUG_1("client count %d", g_list_length(rc->clients));
196 }
197
198 static void remote_server_clients_close(RemoteConnection *rc)
199 {
200         while (rc->clients)
201                 {
202                 auto client = static_cast<RemoteClient *>(rc->clients->data);
203
204                 rc->clients = g_list_remove(rc->clients, client);
205
206                 g_source_remove(client->channel_id);
207                 close(client->fd);
208                 g_free(client);
209                 }
210 }
211
212 static gboolean remote_server_read_cb(GIOChannel *, GIOCondition, gpointer data)
213 {
214         auto rc = static_cast<RemoteConnection *>(data);
215         gint fd;
216         guint alen;
217
218         fd = accept(rc->fd, nullptr, &alen);
219         if (fd == -1)
220                 {
221                 log_printf("error accepting socket: %s\n", strerror(errno));
222                 return TRUE;
223                 }
224
225         remote_server_client_add(rc, fd);
226
227         return TRUE;
228 }
229
230 gboolean remote_server_exists(const gchar *path)
231 {
232         RemoteConnection *rc;
233
234         /* verify server up */
235         rc = remote_client_open(path);
236         remote_close(rc);
237
238         if (rc) return TRUE;
239
240         /* unable to connect, remove socket file to free up address */
241         unlink(path);
242         return FALSE;
243 }
244
245 static RemoteConnection *remote_server_open(const gchar *path)
246 {
247         RemoteConnection *rc;
248         struct sockaddr_un addr;
249         gint sun_path_len;
250         gint fd;
251         GIOChannel *channel;
252
253         if (remote_server_exists(path))
254                 {
255                 log_printf("Address already in use: %s\n", path);
256                 return nullptr;
257                 }
258
259         fd = socket(PF_UNIX, SOCK_STREAM, 0);
260         if (fd == -1) return nullptr;
261
262         addr.sun_family = AF_UNIX;
263         sun_path_len = MIN(strlen(path) + 1, UNIX_PATH_MAX);
264         strncpy(addr.sun_path, path, sun_path_len);
265         if (bind(fd, reinterpret_cast<const struct sockaddr*>(&addr), sizeof(addr)) == -1 ||
266             listen(fd, REMOTE_SERVER_BACKLOG) == -1)
267                 {
268                 log_printf("error subscribing to socket: %s\n", strerror(errno));
269                 close(fd);
270                 return nullptr;
271                 }
272
273         rc = g_new0(RemoteConnection, 1);
274
275         rc->server = TRUE;
276         rc->fd = fd;
277         rc->path = g_strdup(path);
278
279         channel = g_io_channel_unix_new(rc->fd);
280         g_io_channel_set_flags(channel, G_IO_FLAG_NONBLOCK, nullptr);
281
282         rc->channel_id = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, G_IO_IN,
283                                              remote_server_read_cb, rc, nullptr);
284         g_io_channel_unref(channel);
285
286         return rc;
287 }
288
289 static void remote_server_subscribe(RemoteConnection *rc, RemoteReadFunc *func, gpointer data)
290 {
291         if (!rc || !rc->server) return;
292
293         rc->read_func = func;
294         rc->read_data = data;
295 }
296
297
298 static RemoteConnection *remote_client_open(const gchar *path)
299 {
300         RemoteConnection *rc;
301         struct stat st;
302         struct sockaddr_un addr;
303         gint sun_path_len;
304         gint fd;
305
306         if (stat(path, &st) != 0 || !S_ISSOCK(st.st_mode)) return nullptr;
307
308         fd = socket(PF_UNIX, SOCK_STREAM, 0);
309         if (fd == -1) return nullptr;
310
311         addr.sun_family = AF_UNIX;
312         sun_path_len = MIN(strlen(path) + 1, UNIX_PATH_MAX);
313         strncpy(addr.sun_path, path, sun_path_len);
314         if (connect(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == -1)
315                 {
316                 DEBUG_1("error connecting to socket: %s", strerror(errno));
317                 close(fd);
318                 return nullptr;
319                 }
320
321         rc = g_new0(RemoteConnection, 1);
322         rc->server = FALSE;
323         rc->fd = fd;
324         rc->path = g_strdup(path);
325
326         return rc;
327 }
328
329 static sig_atomic_t sigpipe_occurred = FALSE;
330
331 static void sighandler_sigpipe(gint)
332 {
333         sigpipe_occurred = TRUE;
334 }
335
336 static gboolean remote_client_send(RemoteConnection *rc, const gchar *text)
337 {
338         struct sigaction new_action, old_action;
339         gboolean ret = FALSE;
340         GError *error = nullptr;
341         GIOChannel *channel;
342
343         if (!rc || rc->server) return FALSE;
344         if (!text) return TRUE;
345
346         sigpipe_occurred = FALSE;
347
348         new_action.sa_handler = sighandler_sigpipe;
349         sigemptyset(&new_action.sa_mask);
350         new_action.sa_flags = 0;
351
352         /* setup our signal handler */
353         sigaction(SIGPIPE, &new_action, &old_action);
354
355         channel = g_io_channel_unix_new(rc->fd);
356
357         g_io_channel_write_chars(channel, text, -1, nullptr, &error);
358         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, &error);
359         g_io_channel_flush(channel, &error);
360
361         if (error)
362                 {
363                 log_printf("error reading socket: %s\n", error->message);
364                 g_error_free(error);
365                 ret = FALSE;;
366                 }
367         else
368                 {
369                 ret = TRUE;
370                 }
371
372         if (ret)
373                 {
374                 gchar *buffer = nullptr;
375                 gsize termpos;
376                 g_io_channel_set_line_term(channel, "<gq_end_of_command>", -1);
377                 while (g_io_channel_read_line(channel, &buffer, nullptr, &termpos, &error) == G_IO_STATUS_NORMAL)
378                         {
379                         if (buffer)
380                                 {
381                                 if (g_strstr_len(buffer, -1, "<gq_end_of_command>") == buffer) /* empty line finishes the command */
382                                         {
383                                         g_free(buffer);
384                                         fflush(stdout);
385                                         break;
386                                         }
387                                 buffer[termpos] = '\0';
388                                 if (g_strstr_len(buffer, -1, "print0") != nullptr)
389                                         {
390                                         print0 = TRUE;
391                                         }
392                                 else
393                                         {
394                                         if (print0)
395                                                 {
396                                                 printf("%s%c", buffer, 0);
397                                                 }
398                                         else
399                                                 {
400                                                 printf("%s\n", buffer);
401                                                 }
402                                         }
403                                 g_free(buffer);
404                                 buffer = nullptr;
405                                 }
406                         }
407
408                 if (error)
409                         {
410                         log_printf("error reading socket: %s\n", error->message);
411                         g_error_free(error);
412                         ret = FALSE;
413                         }
414                 }
415
416
417         /* restore the original signal handler */
418         sigaction(SIGPIPE, &old_action, nullptr);
419         g_io_channel_unref(channel);
420         return ret;
421 }
422
423 void remote_close(RemoteConnection *rc)
424 {
425         if (!rc) return;
426
427         if (rc->server)
428                 {
429                 remote_server_clients_close(rc);
430
431                 g_source_remove(rc->channel_id);
432                 unlink(rc->path);
433                 }
434
435         if (rc->read_data)
436                 g_free(rc->read_data);
437
438         close(rc->fd);
439
440         g_free(rc->path);
441         g_free(rc);
442 }
443
444 /*
445  *-----------------------------------------------------------------------------
446  * remote functions
447  *-----------------------------------------------------------------------------
448  */
449
450 static void gr_image_next(const gchar *, GIOChannel *, gpointer)
451 {
452         layout_image_next(lw_id);
453 }
454
455 static void gr_new_window(const gchar *, GIOChannel *, gpointer)
456 {
457         LayoutWindow *lw = nullptr;
458
459         if (!layout_valid(&lw)) return;
460
461         lw_id = layout_new_from_default();
462
463         layout_set_path(lw_id, pwd);
464 }
465
466 static gboolean gr_close_window_cb(gpointer)
467 {
468         if (!layout_valid(&lw_id)) return FALSE;
469
470         layout_menu_close_cb(nullptr, lw_id);
471
472         return G_SOURCE_REMOVE;
473 }
474
475 static void gr_close_window(const gchar *, GIOChannel *, gpointer)
476 {
477         g_idle_add((gr_close_window_cb), nullptr);
478 }
479
480 static void gr_image_prev(const gchar *, GIOChannel *, gpointer)
481 {
482         layout_image_prev(lw_id);
483 }
484
485 static void gr_image_first(const gchar *, GIOChannel *, gpointer)
486 {
487         layout_image_first(lw_id);
488 }
489
490 static void gr_image_last(const gchar *, GIOChannel *, gpointer)
491 {
492         layout_image_last(lw_id);
493 }
494
495 static void gr_fullscreen_toggle(const gchar *, GIOChannel *, gpointer)
496 {
497         layout_image_full_screen_toggle(lw_id);
498 }
499
500 static void gr_fullscreen_start(const gchar *, GIOChannel *, gpointer)
501 {
502         layout_image_full_screen_start(lw_id);
503 }
504
505 static void gr_fullscreen_stop(const gchar *, GIOChannel *, gpointer)
506 {
507         layout_image_full_screen_stop(lw_id);
508 }
509
510 static void gr_lw_id(const gchar *text, GIOChannel *, gpointer)
511 {
512         lw_id = layout_find_by_layout_id(text);
513         if (!lw_id)
514                 {
515                 log_printf("remote sent window ID that does not exist:\"%s\"\n",text);
516                 }
517         layout_valid(&lw_id);
518 }
519
520 static void gr_slideshow_start_rec(const gchar *text, GIOChannel *, gpointer)
521 {
522         GList *list;
523         gchar *tilde_filename;
524
525         tilde_filename = expand_tilde(text);
526
527         FileData *dir_fd = file_data_new_dir(tilde_filename);
528         g_free(tilde_filename);
529
530         layout_valid(&lw_id);
531         list = filelist_recursive_full(dir_fd, lw_id->options.file_view_list_sort.method, lw_id->options.file_view_list_sort.ascend, lw_id->options.file_view_list_sort.case_sensitive);
532         file_data_unref(dir_fd);
533         if (!list) return;
534
535         layout_image_slideshow_stop(lw_id);
536         layout_image_slideshow_start_from_list(lw_id, list);
537 }
538
539 static void gr_cache_thumb(const gchar *text, GIOChannel *, gpointer)
540 {
541         if (!g_strcmp0(text, "clear"))
542                 {
543                 cache_maintain_home_remote(FALSE, TRUE, nullptr);
544                 }
545         else if (!g_strcmp0(text, "clean"))
546                 {
547                 cache_maintain_home_remote(FALSE, FALSE, nullptr);
548                 }
549 }
550
551 static void gr_cache_shared(const gchar *text, GIOChannel *, gpointer)
552 {
553         if (!g_strcmp0(text, "clear"))
554                 cache_manager_standard_process_remote(TRUE);
555         else if (!g_strcmp0(text, "clean"))
556                 cache_manager_standard_process_remote(FALSE);
557 }
558
559 static void gr_cache_metadata(const gchar *, GIOChannel *, gpointer)
560 {
561         cache_maintain_home_remote(TRUE, FALSE, nullptr);
562 }
563
564 static void gr_cache_render(const gchar *text, GIOChannel *, gpointer)
565 {
566         cache_manager_render_remote(text, FALSE, FALSE, nullptr);
567 }
568
569 static void gr_cache_render_recurse(const gchar *text, GIOChannel *, gpointer)
570 {
571         cache_manager_render_remote(text, TRUE, FALSE, nullptr);
572 }
573
574 static void gr_cache_render_standard(const gchar *text, GIOChannel *, gpointer)
575 {
576         if(options->thumbnails.spec_standard)
577                 {
578                 cache_manager_render_remote(text, FALSE, TRUE, nullptr);
579                 }
580 }
581
582 static void gr_cache_render_standard_recurse(const gchar *text, GIOChannel *, gpointer)
583 {
584         if(options->thumbnails.spec_standard)
585                 {
586                 cache_manager_render_remote(text, TRUE, TRUE, nullptr);
587                 }
588 }
589
590 static void gr_slideshow_toggle(const gchar *, GIOChannel *, gpointer)
591 {
592         layout_image_slideshow_toggle(lw_id);
593 }
594
595 static void gr_slideshow_start(const gchar *, GIOChannel *, gpointer)
596 {
597         layout_image_slideshow_start(lw_id);
598 }
599
600 static void gr_slideshow_stop(const gchar *, GIOChannel *, gpointer)
601 {
602         layout_image_slideshow_stop(lw_id);
603 }
604
605 static void gr_slideshow_delay(const gchar *text, GIOChannel *, gpointer)
606 {
607         gdouble t1, t2, t3, n;
608         gint res;
609
610         res = sscanf(text, "%lf:%lf:%lf", &t1, &t2, &t3);
611         if (res == 3)
612                 {
613                 n = (t1 * 3600) + (t2 * 60) + t3;
614                 if (n < SLIDESHOW_MIN_SECONDS || n > SLIDESHOW_MAX_SECONDS ||
615                                 t1 >= 24 || t2 >= 60 || t3 >= 60)
616                         {
617                         printf_term(TRUE, "Remote slideshow delay out of range (%.1f to %.1f)\n",
618                                                                 SLIDESHOW_MIN_SECONDS, SLIDESHOW_MAX_SECONDS);
619                         return;
620                         }
621                 }
622         else if (res == 2)
623                 {
624                 n = t1 * 60 + t2;
625                 if (n < SLIDESHOW_MIN_SECONDS || n > SLIDESHOW_MAX_SECONDS ||
626                                 t1 >= 60 || t2 >= 60)
627                         {
628                         printf_term(TRUE, "Remote slideshow delay out of range (%.1f to %.1f)\n",
629                                                                 SLIDESHOW_MIN_SECONDS, SLIDESHOW_MAX_SECONDS);
630                         return;
631                         }
632                 }
633         else if (res == 1)
634                 {
635                 n = t1;
636                 if (n < SLIDESHOW_MIN_SECONDS || n > SLIDESHOW_MAX_SECONDS)
637                         {
638                         printf_term(TRUE, "Remote slideshow delay out of range (%.1f to %.1f)\n",
639                                                                 SLIDESHOW_MIN_SECONDS, SLIDESHOW_MAX_SECONDS);
640                         return;
641                         }
642                 }
643         else
644                 {
645                 n = 0;
646                 }
647
648         options->slideshow.delay = static_cast<gint>(n * 10.0 + 0.01);
649 }
650
651 static void gr_tools_show(const gchar *, GIOChannel *, gpointer)
652 {
653         gboolean popped;
654         gboolean hidden;
655
656         if (layout_tools_float_get(lw_id, &popped, &hidden) && hidden)
657                 {
658                 layout_tools_float_set(lw_id, popped, FALSE);
659                 }
660 }
661
662 static void gr_tools_hide(const gchar *, GIOChannel *, gpointer)
663 {
664         gboolean popped;
665         gboolean hidden;
666
667         if (layout_tools_float_get(lw_id, &popped, &hidden) && !hidden)
668                 {
669                 layout_tools_float_set(lw_id, popped, TRUE);
670                 }
671 }
672
673 static gboolean gr_quit_idle_cb(gpointer)
674 {
675         exit_program();
676
677         return G_SOURCE_REMOVE;
678 }
679
680 static void gr_quit(const gchar *, GIOChannel *, gpointer)
681 {
682         /* schedule exit when idle, if done from within a
683          * remote handler remote_close will crash
684          */
685         g_idle_add(gr_quit_idle_cb, nullptr);
686 }
687
688 static void gr_file_load_no_raise(const gchar *text, GIOChannel *, gpointer)
689 {
690         gchar *filename;
691         gchar *tilde_filename;
692
693         if (!download_web_file(text, TRUE, nullptr))
694                 {
695                 tilde_filename = expand_tilde(text);
696                 filename = set_pwd(tilde_filename);
697
698                 if (isfile(filename))
699                         {
700                         if (file_extension_match(filename, GQ_COLLECTION_EXT))
701                                 {
702                                 collection_window_new(filename);
703                                 }
704                         else
705                                 {
706                                 layout_set_path(lw_id, filename);
707                                 }
708                         }
709                 else if (isdir(filename))
710                         {
711                         layout_set_path(lw_id, filename);
712                         }
713                 else
714                         {
715                         log_printf("remote sent filename that does not exist:\"%s\"\n", filename);
716                         layout_set_path(lw_id, homedir());
717                         }
718
719                 g_free(filename);
720                 g_free(tilde_filename);
721                 }
722 }
723
724 static void gr_file_load(const gchar *text, GIOChannel *channel, gpointer data)
725 {
726         gr_file_load_no_raise(text, channel, data);
727
728         gr_raise(text, channel, data);
729 }
730
731 static void gr_pixel_info(const gchar *, GIOChannel *channel, gpointer)
732 {
733         gchar *pixel_info;
734         gint x_pixel, y_pixel;
735         gint width, height;
736         gint r_mouse, g_mouse, b_mouse;
737         PixbufRenderer *pr;
738
739         if (!layout_valid(&lw_id)) return;
740
741         pr = reinterpret_cast<PixbufRenderer*>(lw_id->image->pr);
742
743         if (pr)
744                 {
745                 pixbuf_renderer_get_image_size(pr, &width, &height);
746                 if (width < 1 || height < 1) return;
747
748                 pixbuf_renderer_get_mouse_position(pr, &x_pixel, &y_pixel);
749
750                 if (x_pixel >= 0 && y_pixel >= 0)
751                         {
752                         pixbuf_renderer_get_pixel_colors(pr, x_pixel, y_pixel,
753                                                          &r_mouse, &g_mouse, &b_mouse);
754
755                         pixel_info = g_strdup_printf(_("[%d,%d]: RGB(%3d,%3d,%3d)"),
756                                                  x_pixel, y_pixel,
757                                                  r_mouse, g_mouse, b_mouse);
758
759                         g_io_channel_write_chars(channel, pixel_info, -1, nullptr, nullptr);
760                         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
761
762                         g_free(pixel_info);
763                         }
764                 else
765                         {
766                         return;
767                         }
768                 }
769         else
770                 {
771                 return;
772                 }
773 }
774
775 static void gr_rectangle(const gchar *, GIOChannel *channel, gpointer)
776 {
777         gchar *rectangle_info;
778         PixbufRenderer *pr;
779         gint x1, y1, x2, y2;
780
781         if (!options->draw_rectangle) return;
782         if (!layout_valid(&lw_id)) return;
783
784         pr = reinterpret_cast<PixbufRenderer*>(lw_id->image->pr);
785
786         if (pr)
787                 {
788                 image_get_rectangle(&x1, &y1, &x2, &y2);
789                 rectangle_info = g_strdup_printf(_("%dx%d+%d+%d"),
790                                         (x2 > x1) ? x2 - x1 : x1 - x2,
791                                         (y2 > y1) ? y2 - y1 : y1 - y2,
792                                         (x2 > x1) ? x1 : x2,
793                                         (y2 > y1) ? y1 : y2);
794
795                 g_io_channel_write_chars(channel, rectangle_info, -1, nullptr, nullptr);
796                 g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
797
798                 g_free(rectangle_info);
799                 }
800 }
801
802 static void gr_render_intent(const gchar *, GIOChannel *channel, gpointer)
803 {
804         gchar *render_intent;
805
806         switch (options->color_profile.render_intent)
807                 {
808                 case 0:
809                         render_intent = g_strdup("Perceptual");
810                         break;
811                 case 1:
812                         render_intent = g_strdup("Relative Colorimetric");
813                         break;
814                 case 2:
815                         render_intent = g_strdup("Saturation");
816                         break;
817                 case 3:
818                         render_intent = g_strdup("Absolute Colorimetric");
819                         break;
820                 default:
821                         render_intent = g_strdup("none");
822                         break;
823                 }
824
825         g_io_channel_write_chars(channel, render_intent, -1, nullptr, nullptr);
826         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
827
828         g_free(render_intent);
829 }
830
831 static void get_filelist(const gchar *text, GIOChannel *channel, gboolean recurse)
832 {
833         GList *list = nullptr;
834         FileFormatClass format_class;
835         FileData *dir_fd;
836         FileData *fd;
837         GList *work;
838         gchar *tilde_filename;
839
840         if (strcmp(text, "") == 0)
841                 {
842                 if (layout_valid(&lw_id))
843                         {
844                         dir_fd = file_data_new_dir(lw_id->dir_fd->path);
845                         }
846                 else
847                         {
848                         return;
849                         }
850                 }
851         else
852                 {
853                 tilde_filename = expand_tilde(text);
854                 if (isdir(tilde_filename))
855                         {
856                         dir_fd = file_data_new_dir(tilde_filename);
857                         }
858                 else
859                         {
860                         g_free(tilde_filename);
861                         return;
862                         }
863                 g_free(tilde_filename);
864                 }
865
866         if (recurse)
867                 {
868                 list = filelist_recursive(dir_fd);
869                 }
870         else
871                 {
872                 filelist_read(dir_fd, &list, nullptr);
873                 }
874
875         GString *out_string = g_string_new(nullptr);
876         work = list;
877         while (work)
878                 {
879                 fd = static_cast<FileData *>(work->data);
880                 g_string_append(out_string, fd->path);
881                 format_class = filter_file_get_class(fd->path);
882
883                 switch (format_class)
884                         {
885                         case FORMAT_CLASS_IMAGE:
886                                 out_string = g_string_append(out_string, "    Class: Image");
887                                 break;
888                         case FORMAT_CLASS_RAWIMAGE:
889                                 out_string = g_string_append(out_string, "    Class: RAW image");
890                                 break;
891                         case FORMAT_CLASS_META:
892                                 out_string = g_string_append(out_string, "    Class: Metadata");
893                                 break;
894                         case FORMAT_CLASS_VIDEO:
895                                 out_string = g_string_append(out_string, "    Class: Video");
896                                 break;
897                         case FORMAT_CLASS_COLLECTION:
898                                 out_string = g_string_append(out_string, "    Class: Collection");
899                                 break;
900                         case FORMAT_CLASS_DOCUMENT:
901                                 out_string = g_string_append(out_string, "    Class: Document");
902                                 break;
903                         case FORMAT_CLASS_ARCHIVE:
904                                 out_string = g_string_append(out_string, "    Class: Archive");
905                                 break;
906                         case FORMAT_CLASS_UNKNOWN:
907                                 out_string = g_string_append(out_string, "    Class: Unknown");
908                                 break;
909                         default:
910                                 out_string = g_string_append(out_string, "    Class: Unknown");
911                                 break;
912                         }
913                 out_string = g_string_append(out_string, "\n");
914                 work = work->next;
915                 }
916
917         g_io_channel_write_chars(channel, out_string->str, -1, nullptr, nullptr);
918         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
919
920         g_string_free(out_string, TRUE);
921         filelist_free(list);
922         file_data_unref(dir_fd);
923 }
924
925 static void gr_get_selection(const gchar *, GIOChannel *channel, gpointer)
926 {
927         if (!layout_valid(&lw_id)) return;
928
929         GList *selected = layout_selection_list(lw_id);  // Keep copy to free.
930         GString *out_string = g_string_new(nullptr);
931
932         GList *work = selected;
933         while (work)
934                 {
935                 auto fd = static_cast<FileData *>(work->data);
936                 g_assert(fd->magick == FD_MAGICK);
937
938                 g_string_append_printf(out_string, "%s    %s\n",
939                                        fd->path,
940                                        format_class_list[filter_file_get_class(fd->path)]);
941
942                 work = work->next;
943                 }
944
945         g_io_channel_write_chars(channel, out_string->str, -1, nullptr, nullptr);
946         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
947
948         filelist_free(selected);
949         g_string_free(out_string, TRUE);
950 }
951
952 static void gr_selection_add(const gchar *text, GIOChannel *, gpointer)
953 {
954         if (!layout_valid(&lw_id)) return;
955
956         FileData *fd_to_select = nullptr;
957         if (strcmp(text, "") == 0)
958                 {
959                 // No file specified, use current fd.
960                 fd_to_select = layout_image_get_fd(lw_id);
961                 }
962         else
963                 {
964                 // Search through the current file list for a file matching the specified path.
965                 // "Match" is either a basename match or a file path match.
966                 gchar *path = expand_tilde(text);
967                 gchar *filename = g_path_get_basename(path);
968                 gchar *slash_plus_filename = g_strdup_printf("%s%s", G_DIR_SEPARATOR_S, filename);
969
970                 GList *file_list = layout_list(lw_id);
971                 for (GList *work = file_list; work && !fd_to_select; work = work->next)
972                         {
973                         auto fd = static_cast<FileData *>(work->data);
974                         if (!strcmp(path, fd->path) || g_str_has_suffix(fd->path, slash_plus_filename))
975                                 {
976                                 fd_to_select = file_data_ref(fd);
977                                 continue;  // will exit loop.
978                                 }
979
980                         for (GList *sidecar = fd->sidecar_files; sidecar && !fd_to_select; sidecar = sidecar->next)
981                                 {
982                                 auto side_fd = static_cast<FileData *>(sidecar->data);
983                                 if (!strcmp(path, side_fd->path)
984                                     || g_str_has_suffix(side_fd->path, slash_plus_filename))
985                                         {
986                                         fd_to_select = file_data_ref(side_fd);
987                                         continue;  // will exit both nested loops.
988                                         }
989                                 }
990                         }
991
992                 if (!fd_to_select)
993                         {
994                         log_printf("remote sent --selection-add filename that could not be found: \"%s\"\n",
995                                    filename);
996                         }
997
998                 filelist_free(file_list);
999                 g_free(slash_plus_filename);
1000                 g_free(filename);
1001                 g_free(path);
1002                 }
1003
1004         if (fd_to_select)
1005                 {
1006                 GList *to_select = g_list_append(nullptr, fd_to_select);
1007                 // Using the "_list" variant doesn't clear the existing selection.
1008                 layout_select_list(lw_id, to_select);
1009                 filelist_free(to_select);
1010                 }
1011 }
1012
1013 static void gr_selection_clear(const gchar *, GIOChannel *, gpointer)
1014 {
1015         layout_select_none(lw_id);  // Checks lw_id validity internally.
1016 }
1017
1018 static void gr_selection_remove(const gchar *text, GIOChannel *, gpointer)
1019 {
1020         if (!layout_valid(&lw_id)) return;
1021
1022         GList *selected = layout_selection_list(lw_id);  // Keep copy to free.
1023         if (!selected)
1024                 {
1025                 log_printf("remote sent --selection-remove with empty selection.");
1026                 return;
1027                 }
1028
1029         FileData *fd_to_deselect = nullptr;
1030         gchar *path = nullptr;
1031         gchar *filename = nullptr;
1032         gchar *slash_plus_filename = nullptr;
1033         if (strcmp(text, "") == 0)
1034                 {
1035                 // No file specified, use current fd.
1036                 fd_to_deselect = layout_image_get_fd(lw_id);
1037                 if (!fd_to_deselect)
1038                         {
1039                         log_printf("remote sent \"--selection-remove:\" with no current image");
1040                         filelist_free(selected);
1041                         return;
1042                         }
1043                 }
1044         else
1045                 {
1046                 // Search through the selection list for a file matching the specified path.
1047                 // "Match" is either a basename match or a file path match.
1048                 path = expand_tilde(text);
1049                 filename = g_path_get_basename(path);
1050                 slash_plus_filename = g_strdup_printf("%s%s", G_DIR_SEPARATOR_S, filename);
1051                 }
1052
1053         GList *prior_link = nullptr;  // Stash base for link removal to avoid a second traversal.
1054         GList *link_to_remove = nullptr;
1055         for (GList *work = selected; work; prior_link = work, work = work->next)
1056                 {
1057                 auto fd = static_cast<FileData *>(work->data);
1058                 if (fd_to_deselect)
1059                         {
1060                         if (fd == fd_to_deselect)
1061                                 {
1062                                 link_to_remove = work;
1063                                 break;
1064                                 }
1065                         }
1066                 else
1067                         {
1068                         // path, filename, and slash_plus_filename should be defined.
1069
1070                         if (!strcmp(path, fd->path) || g_str_has_suffix(fd->path, slash_plus_filename))
1071                                 {
1072                                 link_to_remove = work;
1073                                 break;
1074                                 }
1075                         }
1076                 }
1077
1078         if (!link_to_remove)
1079                 {
1080                 if (fd_to_deselect)
1081                         {
1082                         log_printf("remote sent \"--selection-remove:\" but current image is not selected");
1083                         }
1084                 else
1085                         {
1086                         log_printf("remote sent \"--selection-remove:%s\" but that filename is not selected",
1087                                    filename);
1088                         }
1089                 }
1090         else
1091                 {
1092                 if (link_to_remove == selected)
1093                         {
1094                         // Remove first link.
1095                         selected = g_list_remove_link(selected, link_to_remove);
1096                         filelist_free(link_to_remove);
1097                         link_to_remove = nullptr;
1098                         }
1099                 else
1100                         {
1101                         // Remove a subsequent link.
1102                         prior_link = g_list_remove_link(prior_link, link_to_remove);
1103                         filelist_free(link_to_remove);
1104                         link_to_remove = nullptr;
1105                         }
1106
1107                 // Re-select all but the deselected item.
1108                 layout_select_none(lw_id);
1109                 layout_select_list(lw_id, selected);
1110                 }
1111
1112         filelist_free(selected);
1113         file_data_unref(fd_to_deselect);
1114         g_free(slash_plus_filename);
1115         g_free(filename);
1116         g_free(path);
1117 }
1118
1119 static void gr_collection(const gchar *text, GIOChannel *channel, gpointer)
1120 {
1121         GString *contents = g_string_new(nullptr);
1122
1123         if (is_collection(text))
1124                 {
1125                 collection_contents(text, &contents);
1126                 }
1127         else
1128                 {
1129                 return;
1130                 }
1131
1132         g_io_channel_write_chars(channel, contents->str, -1, nullptr, nullptr);
1133         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1134
1135         g_string_free(contents, TRUE);
1136 }
1137
1138 static void gr_collection_list(const gchar *, GIOChannel *channel, gpointer)
1139 {
1140
1141         GList *collection_list = nullptr;
1142         GList *work;
1143         GString *out_string = g_string_new(nullptr);
1144
1145         collect_manager_list(&collection_list, nullptr, nullptr);
1146
1147         work = collection_list;
1148         while (work)
1149                 {
1150                 auto collection_name = static_cast<const gchar *>(work->data);
1151                 out_string = g_string_append(out_string, collection_name);
1152                 out_string = g_string_append(out_string, "\n");
1153
1154                 work = work->next;
1155                 }
1156
1157         g_io_channel_write_chars(channel, out_string->str, -1, nullptr, nullptr);
1158         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1159
1160         g_list_free_full(collection_list, g_free);
1161         g_string_free(out_string, TRUE);
1162 }
1163
1164 static gboolean wait_cb(gpointer data)
1165 {
1166         gint position = GPOINTER_TO_INT(data);
1167         gint x = position >> 16;
1168         gint y = position - (x << 16);
1169
1170         gtk_window_move(GTK_WINDOW(lw_id->window), x, y);
1171
1172         return G_SOURCE_REMOVE;
1173 }
1174
1175 static void gr_geometry(const gchar *text, GIOChannel *, gpointer)
1176 {
1177         gchar **geometry;
1178
1179         if (!layout_valid(&lw_id) || !text)
1180                 {
1181                 return;
1182                 }
1183
1184         if (text[0] == '+')
1185                 {
1186                 geometry = g_strsplit_set(text, "+", 3);
1187                 if (geometry[1] != nullptr && geometry[2] != nullptr )
1188                         {
1189                         gtk_window_move(GTK_WINDOW(lw_id->window), atoi(geometry[1]), atoi(geometry[2]));
1190                         }
1191                 }
1192         else
1193                 {
1194                 geometry = g_strsplit_set(text, "+x", 4);
1195                 if (geometry[0] != nullptr && geometry[1] != nullptr)
1196                         {
1197                         gtk_window_resize(GTK_WINDOW(lw_id->window), atoi(geometry[0]), atoi(geometry[1]));
1198                         }
1199                 if (geometry[2] != nullptr && geometry[3] != nullptr)
1200                         {
1201                         /* There is an occasional problem with a window_move immediately after a window_resize */
1202                         g_idle_add(wait_cb, GINT_TO_POINTER((atoi(geometry[2]) << 16) + atoi(geometry[3])));
1203                         }
1204                 }
1205         g_strfreev(geometry);
1206 }
1207
1208 static void gr_filelist(const gchar *text, GIOChannel *channel, gpointer)
1209 {
1210         get_filelist(text, channel, FALSE);
1211 }
1212
1213 static void gr_filelist_recurse(const gchar *text, GIOChannel *channel, gpointer)
1214 {
1215         get_filelist(text, channel, TRUE);
1216 }
1217
1218 static void gr_file_tell(const gchar *, GIOChannel *channel, gpointer)
1219 {
1220         gchar *out_string;
1221         gchar *collection_name = nullptr;
1222
1223         if (!layout_valid(&lw_id)) return;
1224
1225         if (image_get_path(lw_id->image))
1226                 {
1227                 if (lw_id->image->collection && lw_id->image->collection->name)
1228                         {
1229                         collection_name = remove_extension_from_path(lw_id->image->collection->name);
1230                         out_string = g_strconcat(image_get_path(lw_id->image), "    Collection: ", collection_name, NULL);
1231                         }
1232                 else
1233                         {
1234                         out_string = g_strconcat(image_get_path(lw_id->image), NULL);
1235                         }
1236                 }
1237         else
1238                 {
1239                 out_string = g_strconcat(lw_id->dir_fd->path, G_DIR_SEPARATOR_S, NULL);
1240                 }
1241
1242         g_io_channel_write_chars(channel, out_string, -1, nullptr, nullptr);
1243         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1244
1245         g_free(collection_name);
1246         g_free(out_string);
1247 }
1248
1249 static void gr_file_info(const gchar *, GIOChannel *channel, gpointer)
1250 {
1251         gchar *filename;
1252         FileData *fd;
1253         gchar *country_name;
1254         gchar *country_code;
1255         gchar *timezone;
1256         gchar *local_time;
1257         GString *out_string;
1258         FileFormatClass format_class;
1259
1260         if (!layout_valid(&lw_id)) return;
1261
1262         if (image_get_path(lw_id->image))
1263                 {
1264                 filename = g_strdup(image_get_path(lw_id->image));
1265                 fd = file_data_new_group(filename);
1266                 out_string = g_string_new(nullptr);
1267
1268                 if (fd->pixbuf)
1269                         {
1270                         format_class = filter_file_get_class(image_get_path(lw_id->image));
1271                         }
1272                 else
1273                         {
1274                         format_class = FORMAT_CLASS_UNKNOWN;
1275                         }
1276
1277                 g_string_append_printf(out_string, _("Class: %s\n"), format_class_list[format_class]);
1278
1279                 if (fd->page_total > 1)
1280                         {
1281                         g_string_append_printf(out_string, _("Page no: %d/%d\n"), fd->page_num + 1, fd->page_total);
1282                         }
1283
1284                 if (fd->exif)
1285                         {
1286                         country_name = exif_get_data_as_text(fd->exif, "formatted.countryname");
1287                         if (country_name)
1288                                 {
1289                                 g_string_append_printf(out_string, _("Country name: %s\n"), country_name);
1290                                 g_free(country_name);
1291                                 }
1292
1293                         country_code = exif_get_data_as_text(fd->exif, "formatted.countrycode");
1294                         if (country_name)
1295                                 {
1296                                 g_string_append_printf(out_string, _("Country code: %s\n"), country_code);
1297                                 g_free(country_code);
1298                                 }
1299
1300                         timezone = exif_get_data_as_text(fd->exif, "formatted.timezone");
1301                         if (timezone)
1302                                 {
1303                                 g_string_append_printf(out_string, _("Timezone: %s\n"), timezone);
1304                                 g_free(timezone);
1305                                 }
1306
1307                         local_time = exif_get_data_as_text(fd->exif, "formatted.localtime");
1308                         if (local_time)
1309                                 {
1310                                 g_string_append_printf(out_string, ("Local time: %s\n"), local_time);
1311                                 g_free(local_time);
1312                                 }
1313                         }
1314
1315                 g_io_channel_write_chars(channel, out_string->str, -1, nullptr, nullptr);
1316                 g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1317
1318                 g_string_free(out_string, TRUE);
1319                 file_data_unref(fd);
1320                 g_free(filename);
1321                 }
1322 }
1323
1324 static gchar *config_file_path(const gchar *param)
1325 {
1326         gchar *path = nullptr;
1327         gchar *full_name = nullptr;
1328
1329         if (file_extension_match(param, ".xml"))
1330                 {
1331                 path = g_build_filename(get_window_layouts_dir(), param, NULL);
1332                 }
1333         else if (file_extension_match(param, nullptr))
1334                 {
1335                 full_name = g_strconcat(param, ".xml", NULL);
1336                 path = g_build_filename(get_window_layouts_dir(), full_name, NULL);
1337                 }
1338
1339         if (!isfile(path))
1340                 {
1341                 g_free(path);
1342                 path = nullptr;
1343                 }
1344
1345         g_free(full_name);
1346         return path;
1347 }
1348
1349 static gboolean is_config_file(const gchar *param)
1350 {
1351         gchar *name = nullptr;
1352
1353         name = config_file_path(param);
1354         if (name)
1355                 {
1356                 g_free(name);
1357                 return TRUE;
1358                 }
1359         return FALSE;
1360 }
1361
1362 static void gr_config_load(const gchar *text, GIOChannel *, gpointer)
1363 {
1364         gchar *filename = expand_tilde(text);
1365
1366         if (!g_strstr_len(filename, -1, G_DIR_SEPARATOR_S))
1367                 {
1368                 if (is_config_file(filename))
1369                         {
1370                         gchar *tmp = config_file_path(filename);
1371                         g_free(filename);
1372                         filename = tmp;
1373                         }
1374                 }
1375
1376         if (isfile(filename))
1377                 {
1378                 load_config_from_file(filename, FALSE);
1379                 }
1380         else
1381                 {
1382                 log_printf("remote sent filename that does not exist:\"%s\"\n", filename);
1383                 layout_set_path(nullptr, homedir());
1384                 }
1385
1386         g_free(filename);
1387 }
1388
1389 static void gr_get_sidecars(const gchar *text, GIOChannel *channel, gpointer)
1390 {
1391         gchar *filename = expand_tilde(text);
1392         FileData *fd = file_data_new_group(filename);
1393
1394         GList *work;
1395         if (fd->parent) fd = fd->parent;
1396
1397         g_io_channel_write_chars(channel, fd->path, -1, nullptr, nullptr);
1398         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1399
1400         work = fd->sidecar_files;
1401
1402         while (work)
1403                 {
1404                 fd = static_cast<FileData *>(work->data);
1405                 work = work->next;
1406                 g_io_channel_write_chars(channel, fd->path, -1, nullptr, nullptr);
1407                 g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1408                 }
1409         g_free(filename);
1410 }
1411
1412 static void gr_get_destination(const gchar *text, GIOChannel *channel, gpointer)
1413 {
1414         gchar *filename = expand_tilde(text);
1415         FileData *fd = file_data_new_group(filename);
1416
1417         if (fd->change && fd->change->dest)
1418                 {
1419                 g_io_channel_write_chars(channel, fd->change->dest, -1, nullptr, nullptr);
1420                 g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1421                 }
1422         g_free(filename);
1423 }
1424
1425 static void gr_file_view(const gchar *text, GIOChannel *, gpointer)
1426 {
1427         gchar *filename;
1428         gchar *tilde_filename = expand_tilde(text);
1429
1430         filename = set_pwd(tilde_filename);
1431
1432         view_window_new(file_data_new_group(filename));
1433         g_free(filename);
1434         g_free(tilde_filename);
1435 }
1436
1437 static void gr_list_clear(const gchar *, GIOChannel *, gpointer data)
1438 {
1439         auto remote_data = static_cast<RemoteData *>(data);
1440
1441         remote_data->command_collection = nullptr;
1442         remote_data->file_list = nullptr;
1443         remote_data->single_dir = TRUE;
1444 }
1445
1446 static void gr_list_add(const gchar *text, GIOChannel *, gpointer data)
1447 {
1448         auto remote_data = static_cast<RemoteData *>(data);
1449         gboolean is_new = TRUE;
1450         gchar *path = nullptr;
1451         FileData *fd;
1452         FileData *first;
1453
1454         /** @FIXME Should check if file is in current dir, has tilde or is relative */
1455         if (!isfile(text))
1456                 {
1457                 log_printf("Warning: File does not exist --remote --list-add:%s", text);
1458
1459                 return;
1460                 }
1461
1462         /* If there is a files list on the command line
1463          * check if they are all in the same folder
1464          */
1465         if (remote_data->single_dir)
1466                 {
1467                 GList *work;
1468                 work = remote_data->file_list;
1469                 while (work && remote_data->single_dir)
1470                         {
1471                         gchar *dirname;
1472                         dirname = g_path_get_dirname((static_cast<FileData *>(work->data))->path);
1473                         if (!path)
1474                                 {
1475                                 path = g_strdup(dirname);
1476                                 }
1477                         else
1478                                 {
1479                                 if (g_strcmp0(path, dirname) != 0)
1480                                         {
1481                                         remote_data->single_dir = FALSE;
1482                                         }
1483                                 }
1484                         g_free(dirname);
1485                         work = work->next;
1486                         }
1487                 g_free(path);
1488                 }
1489
1490         gchar *pathname = g_path_get_dirname(text);
1491         layout_set_path(lw_id, pathname);
1492         g_free(pathname);
1493
1494         fd = file_data_new_simple(text);
1495         remote_data->file_list = g_list_append(remote_data->file_list, fd);
1496         file_data_unref(fd);
1497
1498         vf_select_none(lw_id->vf);
1499         remote_data->file_list = g_list_reverse(remote_data->file_list);
1500
1501         layout_select_list(lw_id, remote_data->file_list);
1502         layout_refresh(lw_id);
1503         first = static_cast<FileData *>(g_list_first(vf_selection_get_list(lw_id->vf))->data);
1504         layout_set_fd(lw_id, first);
1505
1506                 CollectionData *cd;
1507                 CollectWindow *cw;
1508
1509         if (!remote_data->command_collection && !remote_data->single_dir)
1510                 {
1511                 cw = collection_window_new(nullptr);
1512                 cd = cw->cd;
1513
1514                 collection_path_changed(cd);
1515
1516                 remote_data->command_collection = cd;
1517                 }
1518         else if (!remote_data->single_dir)
1519                 {
1520                 is_new = (!collection_get_first(remote_data->command_collection));
1521                 }
1522
1523         if (!remote_data->single_dir)
1524                 {
1525                 layout_image_set_collection(lw_id, remote_data->command_collection, collection_get_first(remote_data->command_collection));
1526                 if (collection_add(remote_data->command_collection, file_data_new_group(text), FALSE) && is_new)
1527                         {
1528                         layout_image_set_collection(lw_id, remote_data->command_collection, collection_get_first(remote_data->command_collection));
1529                         }
1530                 }
1531 }
1532
1533 static void gr_action(const gchar *text, GIOChannel *, gpointer)
1534 {
1535         GtkAction *action;
1536
1537         if (!layout_valid(&lw_id))
1538                 {
1539                 return;
1540                 }
1541
1542         if (g_strstr_len(text, -1, ".desktop") != nullptr)
1543                 {
1544                 file_util_start_editor_from_filelist(text, layout_selection_list(lw_id), layout_get_path(lw_id), lw_id->window);
1545                 }
1546         else
1547                 {
1548                 action = gtk_action_group_get_action(lw_id->action_group, text);
1549                 if (action)
1550                         {
1551                         gtk_action_activate(action);
1552                         }
1553                 else
1554                         {
1555                         log_printf("Action %s unknown", text);
1556                         }
1557                 }
1558 }
1559
1560 static void gr_action_list(const gchar *, GIOChannel *channel, gpointer)
1561 {
1562         ActionItem *action_item;
1563         gchar *action_list;
1564         gint max_length = 0;
1565         GList *list_final = nullptr;
1566         GList *list = nullptr;
1567         GList *work;
1568         GString *out_string = g_string_new(nullptr);
1569
1570         if (!layout_valid(&lw_id))
1571                 {
1572                 return;
1573                 }
1574
1575         list = get_action_items();
1576         work = list;
1577
1578         /* Get the length required for padding */
1579         while (work)
1580                 {
1581                 action_item = static_cast<ActionItem *>(work->data);
1582                 if (g_utf8_strlen(action_item->name, -1) > max_length)
1583                         {
1584                         max_length = g_utf8_strlen(action_item->name, -1);
1585                         }
1586
1587                 work = work->next;
1588                 }
1589
1590         work = list;
1591
1592         /* Pad the action names to the same column for readable output */
1593         while (work)
1594                 {
1595                 action_item = static_cast<ActionItem *>(work->data);
1596
1597                 action_list = g_strdup_printf("%-*s", max_length + 4, action_item->name);
1598                 list_final = g_list_prepend(list_final, g_strconcat(action_list, action_item->label, nullptr));
1599
1600                 g_free(action_list);
1601                 work = work->next;
1602                 }
1603
1604         action_items_free(list);
1605
1606         list_final = g_list_reverse(list_final);
1607
1608         work = list_final;
1609         while (work)
1610                 {
1611                 out_string = g_string_append(out_string, static_cast<gchar *>(work->data) );
1612                 out_string = g_string_append(out_string, "\n");
1613                 work = work->next;
1614                 }
1615
1616         string_list_free(list_final);
1617
1618         g_io_channel_write_chars(channel, out_string->str, -1, nullptr, nullptr);
1619         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1620
1621         g_string_free(out_string, TRUE);
1622 }
1623
1624 static void gr_raise(const gchar *, GIOChannel *, gpointer)
1625 {
1626         if (layout_valid(&lw_id))
1627                 {
1628                 gtk_window_present(GTK_WINDOW(lw_id->window));
1629                 }
1630 }
1631
1632 static void gr_pwd(const gchar *text, GIOChannel *, gpointer)
1633 {
1634         LayoutWindow *lw = nullptr;
1635
1636         layout_valid(&lw);
1637
1638         g_free(pwd);
1639         pwd = g_strdup(text);
1640         lw_id = lw;
1641 }
1642
1643 static void gr_print0(const gchar *, GIOChannel *channel, gpointer)
1644 {
1645         g_io_channel_write_chars(channel, "print0", -1, nullptr, nullptr);
1646         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1647 }
1648
1649 #ifdef HAVE_LUA
1650 static void gr_lua(const gchar *text, GIOChannel *channel, gpointer)
1651 {
1652         gchar *result = nullptr;
1653         gchar **lua_command;
1654
1655         lua_command = g_strsplit(text, ",", 2);
1656
1657         if (lua_command[0] && lua_command[1])
1658                 {
1659                 FileData *fd = file_data_new_group(lua_command[0]);
1660                 result = g_strdup(lua_callvalue(fd, lua_command[1], nullptr));
1661                 if (result)
1662                         {
1663                         g_io_channel_write_chars(channel, result, -1, nullptr, nullptr);
1664                         }
1665                 else
1666                         {
1667                         g_io_channel_write_chars(channel, N_("lua error: no data"), -1, nullptr, nullptr);
1668                         }
1669                 }
1670         else
1671                 {
1672                 g_io_channel_write_chars(channel, N_("lua error: no data"), -1, nullptr, nullptr);
1673                 }
1674
1675         g_io_channel_write_chars(channel, "<gq_end_of_command>", -1, nullptr, nullptr);
1676
1677         g_strfreev(lua_command);
1678         g_free(result);
1679 }
1680 #endif
1681
1682 struct RemoteCommandEntry {
1683         const gchar *opt_s;
1684         const gchar *opt_l;
1685         void (*func)(const gchar *text, GIOChannel *channel, gpointer data);
1686         gboolean needs_extra;
1687         gboolean prefer_command_line;
1688         const gchar *parameter;
1689         const gchar *description;
1690 };
1691
1692 static RemoteCommandEntry remote_commands[] = {
1693         /* short, long                  callback,               extra, prefer, parameter, description */
1694         { nullptr, "--action:",          gr_action,            TRUE,  FALSE, N_("<ACTION>"), N_("execute keyboard action (See Help/Reference/Remote Keyboard Actions)") },
1695         { nullptr, "--action-list",          gr_action_list,    FALSE,  FALSE, nullptr, N_("list available keyboard actions (some are redundant)") },
1696         { "-b", "--back",               gr_image_prev,          FALSE, FALSE, nullptr, N_("previous image") },
1697         { nullptr, "--close-window",       gr_close_window,        FALSE, FALSE, nullptr, N_("close window") },
1698         { nullptr, "--config-load:",       gr_config_load,         TRUE,  FALSE, N_("<FILE>|layout ID"), N_("load configuration from FILE") },
1699         { "-cm","--cache-metadata",      gr_cache_metadata,               FALSE, FALSE, nullptr, N_("clean the metadata cache") },
1700         { "-cr:", "--cache-render:",    gr_cache_render,        TRUE, FALSE, N_("<folder>  "), N_(" render thumbnails") },
1701         { "-crr:", "--cache-render-recurse:", gr_cache_render_recurse, TRUE, FALSE, N_("<folder> "), N_("render thumbnails recursively") },
1702         { "-crs:", "--cache-render-shared:", gr_cache_render_standard, TRUE, FALSE, N_("<folder> "), N_(" render thumbnails (see Help)") },
1703         { "-crsr:", "--cache-render-shared-recurse:", gr_cache_render_standard_recurse, TRUE, FALSE, N_("<folder>"), N_(" render thumbnails recursively (see Help)") },
1704         { "-cs:", "--cache-shared:",    gr_cache_shared,        TRUE, FALSE, N_("clear|clean"), N_("clear or clean shared thumbnail cache") },
1705         { "-ct:", "--cache-thumbs:",    gr_cache_thumb,         TRUE, FALSE, N_("clear|clean"), N_("clear or clean thumbnail cache") },
1706         { "-d", "--delay=",             gr_slideshow_delay,     TRUE,  FALSE, N_("<[H:][M:][N][.M]>"), N_("set slide show delay to Hrs Mins N.M seconds") },
1707         { nullptr, "--first",              gr_image_first,         FALSE, FALSE, nullptr, N_("first image") },
1708         { "-f", "--fullscreen",         gr_fullscreen_toggle,   FALSE, TRUE,  nullptr, N_("toggle full screen") },
1709         { nullptr, "--file:",              gr_file_load,           TRUE,  FALSE, N_("<FILE>|<URL>"), N_("open FILE or URL, bring Geeqie window to the top") },
1710         { nullptr, "file:",                gr_file_load,           TRUE,  FALSE, N_("<FILE>|<URL>"), N_("open FILE or URL, bring Geeqie window to the top") },
1711         { nullptr, "--File:",              gr_file_load_no_raise,  TRUE,  FALSE, N_("<FILE>|<URL>"), N_("open FILE or URL, do not bring Geeqie window to the top") },
1712         { nullptr, "File:",                gr_file_load_no_raise,  TRUE,  FALSE, N_("<FILE>|<URL>"), N_("open FILE or URL, do not bring Geeqie window to the top") },
1713         { "-fs","--fullscreen-start",   gr_fullscreen_start,    FALSE, FALSE, nullptr, N_("start full screen") },
1714         { "-fS","--fullscreen-stop",    gr_fullscreen_stop,     FALSE, FALSE, nullptr, N_("stop full screen") },
1715         { nullptr, "--geometry=",          gr_geometry,            TRUE, FALSE, N_("<GEOMETRY>"), N_("set window geometry") },
1716         { nullptr, "--get-collection:",    gr_collection,          TRUE,  FALSE, N_("<COLLECTION>"), N_("get collection content") },
1717         { nullptr, "--get-collection-list", gr_collection_list,    FALSE, FALSE, nullptr, N_("get collection list") },
1718         { nullptr, "--get-destination:",        gr_get_destination,     TRUE,  FALSE, N_("<FILE>"), N_("get destination path of FILE (See Plugins Configuration)") },
1719         { nullptr, "--get-file-info",      gr_file_info,           FALSE, FALSE, nullptr, N_("get file info") },
1720         { nullptr, "--get-filelist:",      gr_filelist,            TRUE,  FALSE, N_("[<FOLDER>]"), N_("get list of files and class") },
1721         { nullptr, "--get-filelist-recurse:", gr_filelist_recurse, TRUE,  FALSE, N_("[<FOLDER>]"), N_("get list of files and class recursive") },
1722         { nullptr, "--get-rectangle",      gr_rectangle,           FALSE, FALSE, nullptr, N_("get rectangle co-ordinates") },
1723         { nullptr, "--get-render-intent",  gr_render_intent,       FALSE, FALSE, nullptr, N_("get render intent") },
1724         { nullptr, "--get-selection",      gr_get_selection,       FALSE, FALSE, nullptr, N_("get list of selected files") },
1725         { nullptr, "--get-sidecars:",      gr_get_sidecars,        TRUE,  FALSE, N_("<FILE>"), N_("get list of sidecars of FILE") },
1726         { nullptr, "--id:",                gr_lw_id,               TRUE, FALSE, N_("<ID>"), N_("window id for following commands") },
1727         { nullptr, "--last",               gr_image_last,          FALSE, FALSE, nullptr, N_("last image") },
1728         { nullptr, "--list-add:",          gr_list_add,            TRUE,  FALSE, N_("<FILE>"), N_("add FILE to command line collection list") },
1729         { nullptr, "--list-clear",         gr_list_clear,          FALSE, FALSE, nullptr, N_("clear command line collection list") },
1730 #ifdef HAVE_LUA
1731         { nullptr, "--lua:",               gr_lua,                 TRUE, FALSE, N_("<FILE>,<lua script>"), N_("run lua script on FILE") },
1732 #endif
1733         { nullptr, "--new-window",         gr_new_window,          FALSE, FALSE, nullptr, N_("new window") },
1734         { "-n", "--next",               gr_image_next,          FALSE, FALSE, nullptr, N_("next image") },
1735         { nullptr, "--pixel-info",         gr_pixel_info,          FALSE, FALSE, nullptr, N_("print pixel info of mouse pointer on current image") },
1736         { nullptr, "--print0",             gr_print0,              TRUE, FALSE, nullptr, N_("terminate returned data with null character instead of newline") },
1737         { nullptr, "--PWD:",               gr_pwd,                 TRUE, FALSE, N_("<PWD>"), N_("use PWD as working directory for following commands") },
1738         { "-q", "--quit",               gr_quit,                FALSE, FALSE, nullptr, N_("quit") },
1739         { nullptr, "--raise",              gr_raise,               FALSE, FALSE, nullptr, N_("bring the Geeqie window to the top") },
1740         { nullptr, "raise",                gr_raise,               FALSE, FALSE, nullptr, N_("bring the Geeqie window to the top") },
1741         { nullptr, "--selection-add:",     gr_selection_add,       TRUE,  FALSE, N_("[<FILE>]"), N_("adds the current file (or the specified file) to the current selection") },
1742         { nullptr, "--selection-clear",    gr_selection_clear,     FALSE, FALSE, nullptr, N_("clears the current selection") },
1743         { nullptr, "--selection-remove:",  gr_selection_remove,    TRUE,  FALSE, N_("[<FILE>]"), N_("removes the current file (or the specified file) from the current selection") },
1744         { "-s", "--slideshow",          gr_slideshow_toggle,    FALSE, TRUE,  nullptr, N_("toggle slide show") },
1745         { nullptr, "--slideshow-recurse:", gr_slideshow_start_rec, TRUE,  FALSE, N_("<FOLDER>"), N_("start recursive slide show in FOLDER") },
1746         { "-ss","--slideshow-start",    gr_slideshow_start,     FALSE, FALSE, nullptr, N_("start slide show") },
1747         { "-sS","--slideshow-stop",     gr_slideshow_stop,      FALSE, FALSE, nullptr, N_("stop slide show") },
1748         { nullptr, "--tell",               gr_file_tell,           FALSE, FALSE, nullptr, N_("print filename [and Collection] of current image") },
1749         { "+t", "--tools-show",         gr_tools_show,          FALSE, TRUE,  nullptr, N_("show tools") },
1750         { "-t", "--tools-hide",         gr_tools_hide,          FALSE, TRUE,  nullptr, N_("hide tools") },
1751         { nullptr, "--view:",              gr_file_view,           TRUE,  FALSE, N_("<FILE>"), N_("open FILE in new window") },
1752         { nullptr, "view:",                gr_file_view,           TRUE,  FALSE, N_("<FILE>"), N_("open FILE in new window") },
1753         { nullptr, nullptr, nullptr, FALSE, FALSE, nullptr, nullptr }
1754 };
1755
1756 static RemoteCommandEntry *remote_command_find(const gchar *text, const gchar **offset)
1757 {
1758         gboolean match = FALSE;
1759         gint i;
1760
1761         i = 0;
1762         while (!match && remote_commands[i].func != nullptr)
1763                 {
1764                 if (remote_commands[i].needs_extra)
1765                         {
1766                         if (remote_commands[i].opt_s &&
1767                             strncmp(remote_commands[i].opt_s, text, strlen(remote_commands[i].opt_s)) == 0)
1768                                 {
1769                                 if (offset) *offset = text + strlen(remote_commands[i].opt_s);
1770                                 return &remote_commands[i];
1771                                 }
1772                         else if (remote_commands[i].opt_l &&
1773                                  strncmp(remote_commands[i].opt_l, text, strlen(remote_commands[i].opt_l)) == 0)
1774                                 {
1775                                 if (offset) *offset = text + strlen(remote_commands[i].opt_l);
1776                                 return &remote_commands[i];
1777                                 }
1778                         }
1779                 else
1780                         {
1781                         if ((remote_commands[i].opt_s && strcmp(remote_commands[i].opt_s, text) == 0) ||
1782                             (remote_commands[i].opt_l && strcmp(remote_commands[i].opt_l, text) == 0))
1783                                 {
1784                                 if (offset) *offset = text;
1785                                 return &remote_commands[i];
1786                                 }
1787                         }
1788
1789                 i++;
1790                 }
1791
1792         return nullptr;
1793 }
1794
1795 static void remote_cb(RemoteConnection *, const gchar *text, GIOChannel *channel, gpointer data)
1796 {
1797         RemoteCommandEntry *entry;
1798         const gchar *offset;
1799
1800         entry = remote_command_find(text, &offset);
1801         if (entry && entry->func)
1802                 {
1803                 entry->func(offset, channel, data);
1804                 }
1805         else
1806                 {
1807                 log_printf("unknown remote command:%s\n", text);
1808                 }
1809 }
1810
1811 void remote_help()
1812 {
1813         gint i;
1814         gchar *s_opt_param;
1815         gchar *l_opt_param;
1816
1817         print_term(FALSE, _("Remote command list:\n"));
1818
1819         i = 0;
1820         while (remote_commands[i].func != nullptr)
1821                 {
1822                 if (remote_commands[i].description)
1823                         {
1824                         s_opt_param = g_strdup(remote_commands[i].opt_s  ? remote_commands[i].opt_s : "" );
1825                         l_opt_param = g_strconcat(remote_commands[i].opt_l, remote_commands[i].parameter, NULL);
1826                         printf_term(FALSE, "  %-4s %-40s%-s\n",
1827                                         s_opt_param,
1828                                         l_opt_param,
1829                                         _(remote_commands[i].description));
1830                         g_free(s_opt_param);
1831                         g_free(l_opt_param);
1832                         }
1833                 i++;
1834                 }
1835         printf_term(FALSE, _("\n\n  All other command line parameters are used as plain files if they exist.\n\n  The name of a collection, with or without either path or extension (.gqv) may be used.\n"));
1836 }
1837
1838 GList *remote_build_list(GList *list, gint argc, gchar *argv[], GList **errors)
1839 {
1840         gint i;
1841
1842         i = 1;
1843         while (i < argc)
1844                 {
1845                 RemoteCommandEntry *entry;
1846
1847                 entry = remote_command_find(argv[i], nullptr);
1848                 if (entry)
1849                         {
1850                         list = g_list_append(list, argv[i]);
1851                         }
1852                 else if (errors && !isname(argv[i]))
1853                         {
1854                         *errors = g_list_append(*errors, argv[i]);
1855                         }
1856                 i++;
1857                 }
1858
1859         return list;
1860 }
1861
1862 /**
1863  * @param arg_exec Binary (argv0)
1864  * @param remote_list Evaluated and recognized remote commands
1865  * @param path The current path
1866  * @param cmd_list List of all non collections in Path (gchar *path)
1867  * @param collection_list List of all collections in argv
1868  */
1869 void remote_control(const gchar *arg_exec, GList *remote_list, const gchar *path,
1870                     GList *cmd_list, GList *collection_list)
1871 {
1872         RemoteConnection *rc;
1873         gboolean started = FALSE;
1874         gchar *buf;
1875
1876         buf = g_build_filename(get_rc_dir(), ".command", NULL);
1877         rc = remote_client_open(buf);
1878         if (!rc)
1879                 {
1880                 GString *command;
1881                 GList *work;
1882                 gint retry_count = 12;
1883                 gboolean blank = FALSE;
1884
1885                 printf_term(FALSE, _("Remote %s not running, starting..."), GQ_APPNAME);
1886
1887                 command = g_string_new(arg_exec);
1888
1889                 work = remote_list;
1890                 while (work)
1891                         {
1892                         gchar *text;
1893                         RemoteCommandEntry *entry;
1894
1895                         text = static_cast<gchar *>(work->data);
1896                         work = work->next;
1897
1898                         entry = remote_command_find(text, nullptr);
1899                         if (entry)
1900                                 {
1901                                 /* If Geeqie is not running, stop the --new-window command opening a second window */
1902                                 if (g_strcmp0(text, "--new-window") == 0)
1903                                         {
1904                                         remote_list = g_list_remove(remote_list, text);
1905                                         }
1906                                 if (entry->prefer_command_line)
1907                                         {
1908                                         remote_list = g_list_remove(remote_list, text);
1909                                         g_string_append(command, " ");
1910                                         g_string_append(command, text);
1911                                         }
1912                                 if (entry->opt_l && strcmp(entry->opt_l, "file:") == 0)
1913                                         {
1914                                         blank = TRUE;
1915                                         }
1916                                 }
1917                         }
1918
1919                 if (blank || cmd_list || path) g_string_append(command, " --blank");
1920                 if (get_debug_level()) g_string_append(command, " --debug");
1921
1922                 g_string_append(command, " &");
1923                 runcmd(command->str);
1924                 g_string_free(command, TRUE);
1925
1926                 while (!rc && retry_count > 0)
1927                         {
1928                         usleep((retry_count > 10) ? 500000 : 1000000);
1929                         rc = remote_client_open(buf);
1930                         if (!rc) print_term(FALSE, ".");
1931                         retry_count--;
1932                         }
1933
1934                 print_term(FALSE, "\n");
1935
1936                 started = TRUE;
1937                 }
1938         g_free(buf);
1939
1940         if (rc)
1941                 {
1942                 GList *work;
1943                 const gchar *prefix;
1944                 gboolean use_path = TRUE;
1945                 gboolean sent = FALSE;
1946
1947                 work = remote_list;
1948                 while (work)
1949                         {
1950                         gchar *text;
1951                         RemoteCommandEntry *entry;
1952
1953                         text = static_cast<gchar *>(work->data);
1954                         work = work->next;
1955
1956                         entry = remote_command_find(text, nullptr);
1957                         if (entry &&
1958                             entry->opt_l &&
1959                             strcmp(entry->opt_l, "file:") == 0) use_path = FALSE;
1960
1961                         remote_client_send(rc, text);
1962
1963                         sent = TRUE;
1964                         }
1965
1966                 if (cmd_list && cmd_list->next)
1967                         {
1968                         prefix = "--list-add:";
1969                         remote_client_send(rc, "--list-clear");
1970                         }
1971                 else
1972                         {
1973                         prefix = "file:";
1974                         }
1975
1976                 work = cmd_list;
1977                 while (work)
1978                         {
1979                         gchar *text;
1980
1981                         text = g_strconcat(prefix, work->data, NULL);
1982                         remote_client_send(rc, text);
1983                         g_free(text);
1984                         work = work->next;
1985
1986                         sent = TRUE;
1987                         }
1988
1989                 if (path && !cmd_list && use_path)
1990                         {
1991                         gchar *text;
1992
1993                         text = g_strdup_printf("file:%s", path);
1994                         remote_client_send(rc, text);
1995                         g_free(text);
1996
1997                         sent = TRUE;
1998                         }
1999
2000                 work = collection_list;
2001                 while (work)
2002                         {
2003                         const gchar *name;
2004                         gchar *text;
2005
2006                         name = static_cast<const gchar *>(work->data);
2007                         work = work->next;
2008
2009                         text = g_strdup_printf("file:%s", name);
2010                         remote_client_send(rc, text);
2011                         g_free(text);
2012
2013                         sent = TRUE;
2014                         }
2015
2016                 if (!started && !sent)
2017                         {
2018                         remote_client_send(rc, "raise");
2019                         }
2020                 }
2021         else
2022                 {
2023                 print_term(TRUE, _("Remote not available\n"));
2024                 }
2025
2026         _exit(0);
2027 }
2028
2029 RemoteConnection *remote_server_init(gchar *path, CollectionData *command_collection)
2030 {
2031         RemoteConnection *remote_connection = remote_server_open(path);
2032         auto remote_data = g_new(RemoteData, 1);
2033
2034         remote_data->command_collection = command_collection;
2035
2036         remote_server_subscribe(remote_connection, remote_cb, remote_data);
2037         return remote_connection;
2038 }
2039 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */