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