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