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