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