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