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