Fix #314: Remote commands for thumbnail 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 "filedata.h"
28 #include "image.h"
29 #include "img-view.h"
30 #include "layout.h"
31 #include "layout_image.h"
32 #include "misc.h"
33 #include "slideshow.h"
34 #include "ui_fileops.h"
35 #include "rcfile.h"
36
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <signal.h>
40 #include <errno.h>
41
42
43 #define SERVER_MAX_CLIENTS 8
44
45 #define REMOTE_SERVER_BACKLOG 4
46
47
48 #ifndef UNIX_PATH_MAX
49 #define UNIX_PATH_MAX 108
50 #endif
51
52
53 static RemoteConnection *remote_client_open(const gchar *path);
54 static gint remote_client_send(RemoteConnection *rc, const gchar *text);
55 static void gr_raise(const gchar *text, GIOChannel *channel, gpointer data);
56
57
58 typedef struct _RemoteClient RemoteClient;
59 struct _RemoteClient {
60         gint fd;
61         guint channel_id; /* event source id */
62         RemoteConnection *rc;
63 };
64
65 typedef struct _RemoteData RemoteData;
66 struct _RemoteData {
67         CollectionData *command_collection;
68 };
69
70
71 static gboolean remote_server_client_cb(GIOChannel *source, GIOCondition condition, gpointer data)
72 {
73         RemoteClient *client = data;
74         RemoteConnection *rc;
75         GIOStatus status = G_IO_STATUS_NORMAL;
76
77         rc = client->rc;
78
79         if (condition & G_IO_IN)
80                 {
81                 gchar *buffer = NULL;
82                 GError *error = NULL;
83                 gsize termpos;
84
85                 while ((status = g_io_channel_read_line(source, &buffer, NULL, &termpos, &error)) == G_IO_STATUS_NORMAL)
86                         {
87                         if (buffer)
88                                 {
89                                 buffer[termpos] = '\0';
90
91                                 if (strlen(buffer) > 0)
92                                         {
93                                         if (rc->read_func) rc->read_func(rc, buffer, source, rc->read_data);
94                                         g_io_channel_write_chars(source, "\n", -1, NULL, NULL); /* empty line finishes the command */
95                                         g_io_channel_flush(source, NULL);
96                                         }
97                                 g_free(buffer);
98
99                                 buffer = NULL;
100                                 }
101                         }
102
103                 if (error)
104                         {
105                         log_printf("error reading socket: %s\n", error->message);
106                         g_error_free(error);
107                         }
108                 }
109
110         if (condition & G_IO_HUP || status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR)
111                 {
112                 rc->clients = g_list_remove(rc->clients, client);
113
114                 DEBUG_1("HUP detected, closing client.");
115                 DEBUG_1("client count %d", g_list_length(rc->clients));
116
117                 g_source_remove(client->channel_id);
118                 close(client->fd);
119                 g_free(client);
120                 }
121
122         return TRUE;
123 }
124
125 static void remote_server_client_add(RemoteConnection *rc, gint fd)
126 {
127         RemoteClient *client;
128         GIOChannel *channel;
129
130         if (g_list_length(rc->clients) > SERVER_MAX_CLIENTS)
131                 {
132                 log_printf("maximum remote clients of %d exceeded, closing connection\n", SERVER_MAX_CLIENTS);
133                 close(fd);
134                 return;
135                 }
136
137         client = g_new0(RemoteClient, 1);
138         client->rc = rc;
139         client->fd = fd;
140
141         channel = g_io_channel_unix_new(fd);
142         client->channel_id = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, G_IO_IN | G_IO_HUP,
143                                                  remote_server_client_cb, client, NULL);
144         g_io_channel_unref(channel);
145
146         rc->clients = g_list_append(rc->clients, client);
147         DEBUG_1("client count %d", g_list_length(rc->clients));
148 }
149
150 static void remote_server_clients_close(RemoteConnection *rc)
151 {
152         while (rc->clients)
153                 {
154                 RemoteClient *client = rc->clients->data;
155
156                 rc->clients = g_list_remove(rc->clients, client);
157
158                 g_source_remove(client->channel_id);
159                 close(client->fd);
160                 g_free(client);
161                 }
162 }
163
164 static gboolean remote_server_read_cb(GIOChannel *source, GIOCondition condition, gpointer data)
165 {
166         RemoteConnection *rc = data;
167         gint fd;
168         guint alen;
169
170         fd = accept(rc->fd, NULL, &alen);
171         if (fd == -1)
172                 {
173                 log_printf("error accepting socket: %s\n", strerror(errno));
174                 return TRUE;
175                 }
176
177         remote_server_client_add(rc, fd);
178
179         return TRUE;
180 }
181
182 static gboolean remote_server_exists(const gchar *path)
183 {
184         RemoteConnection *rc;
185
186         /* verify server up */
187         rc = remote_client_open(path);
188         remote_close(rc);
189
190         if (rc) return TRUE;
191
192         /* unable to connect, remove socket file to free up address */
193         unlink(path);
194         return FALSE;
195 }
196
197 static RemoteConnection *remote_server_open(const gchar *path)
198 {
199         RemoteConnection *rc;
200         struct sockaddr_un addr;
201         gint sun_path_len;
202         gint fd;
203         GIOChannel *channel;
204
205         if (remote_server_exists(path))
206                 {
207                 log_printf("Address already in use: %s\n", path);
208                 return NULL;
209                 }
210
211         fd = socket(PF_UNIX, SOCK_STREAM, 0);
212         if (fd == -1) return NULL;
213
214         addr.sun_family = AF_UNIX;
215         sun_path_len = MIN(strlen(path) + 1, UNIX_PATH_MAX);
216         strncpy(addr.sun_path, path, sun_path_len);
217         if (bind(fd, &addr, sizeof(addr)) == -1 ||
218             listen(fd, REMOTE_SERVER_BACKLOG) == -1)
219                 {
220                 log_printf("error subscribing to socket: %s\n", strerror(errno));
221                 close(fd);
222                 return NULL;
223                 }
224
225         rc = g_new0(RemoteConnection, 1);
226
227         rc->server = TRUE;
228         rc->fd = fd;
229         rc->path = g_strdup(path);
230
231         channel = g_io_channel_unix_new(rc->fd);
232         g_io_channel_set_flags(channel, G_IO_FLAG_NONBLOCK, NULL);
233
234         rc->channel_id = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT, G_IO_IN,
235                                              remote_server_read_cb, rc, NULL);
236         g_io_channel_unref(channel);
237
238         return rc;
239 }
240
241 static void remote_server_subscribe(RemoteConnection *rc, RemoteReadFunc *func, gpointer data)
242 {
243         if (!rc || !rc->server) return;
244
245         rc->read_func = func;
246         rc->read_data = data;
247 }
248
249
250 static RemoteConnection *remote_client_open(const gchar *path)
251 {
252         RemoteConnection *rc;
253         struct stat st;
254         struct sockaddr_un addr;
255         gint sun_path_len;
256         gint fd;
257
258         if (stat(path, &st) != 0 || !S_ISSOCK(st.st_mode)) return NULL;
259
260         fd = socket(PF_UNIX, SOCK_STREAM, 0);
261         if (fd == -1) return NULL;
262
263         addr.sun_family = AF_UNIX;
264         sun_path_len = MIN(strlen(path) + 1, UNIX_PATH_MAX);
265         strncpy(addr.sun_path, path, sun_path_len);
266         if (connect(fd, &addr, sizeof(addr)) == -1)
267                 {
268                 DEBUG_1("error connecting to socket: %s", strerror(errno));
269                 close(fd);
270                 return NULL;
271                 }
272
273         rc = g_new0(RemoteConnection, 1);
274         rc->server = FALSE;
275         rc->fd = fd;
276         rc->path = g_strdup(path);
277
278         return rc;
279 }
280
281 static sig_atomic_t sigpipe_occured = FALSE;
282
283 static void sighandler_sigpipe(gint sig)
284 {
285         sigpipe_occured = TRUE;
286 }
287
288 static gboolean remote_client_send(RemoteConnection *rc, const gchar *text)
289 {
290         struct sigaction new_action, old_action;
291         gboolean ret = FALSE;
292         GError *error = NULL;
293         GIOChannel *channel;
294
295         if (!rc || rc->server) return FALSE;
296         if (!text) return TRUE;
297
298         sigpipe_occured = FALSE;
299
300         new_action.sa_handler = sighandler_sigpipe;
301         sigemptyset(&new_action.sa_mask);
302         new_action.sa_flags = 0;
303
304         /* setup our signal handler */
305         sigaction(SIGPIPE, &new_action, &old_action);
306
307         channel = g_io_channel_unix_new(rc->fd);
308
309         g_io_channel_write_chars(channel, text, -1, NULL, &error);
310         g_io_channel_write_chars(channel, "\n", -1, NULL, &error);
311         g_io_channel_flush(channel, &error);
312
313         if (error)
314                 {
315                 log_printf("error reading socket: %s\n", error->message);
316                 g_error_free(error);
317                 ret = FALSE;;
318                 }
319         else
320                 {
321                 ret = TRUE;
322                 }
323
324         if (ret)
325                 {
326                 gchar *buffer = NULL;
327                 gsize termpos;
328                 while (g_io_channel_read_line(channel, &buffer, NULL, &termpos, &error) == G_IO_STATUS_NORMAL)
329                         {
330                         if (buffer)
331                                 {
332                                 if (buffer[0] == '\n') /* empty line finishes the command */
333                                         {
334                                         g_free(buffer);
335                                         fflush(stdout);
336                                         break;
337                                         }
338                                 buffer[termpos] = '\0';
339                                 printf("%s\n", buffer);
340                                 g_free(buffer);
341                                 buffer = NULL;
342                                 }
343                         }
344
345                 if (error)
346                         {
347                         log_printf("error reading socket: %s\n", error->message);
348                         g_error_free(error);
349                         ret = FALSE;
350                         }
351                 }
352
353
354         /* restore the original signal handler */
355         sigaction(SIGPIPE, &old_action, NULL);
356         g_io_channel_unref(channel);
357         return ret;
358 }
359
360 void remote_close(RemoteConnection *rc)
361 {
362         if (!rc) return;
363
364         if (rc->server)
365                 {
366                 remote_server_clients_close(rc);
367
368                 g_source_remove(rc->channel_id);
369                 unlink(rc->path);
370                 }
371
372         if (rc->read_data)
373                 g_free(rc->read_data);
374
375         close(rc->fd);
376
377         g_free(rc->path);
378         g_free(rc);
379 }
380
381 /*
382  *-----------------------------------------------------------------------------
383  * remote functions
384  *-----------------------------------------------------------------------------
385  */
386
387 static void gr_image_next(const gchar *text, GIOChannel *channel, gpointer data)
388 {
389         layout_image_next(NULL);
390 }
391
392 static void gr_image_prev(const gchar *text, GIOChannel *channel, gpointer data)
393 {
394         layout_image_prev(NULL);
395 }
396
397 static void gr_image_first(const gchar *text, GIOChannel *channel, gpointer data)
398 {
399         layout_image_first(NULL);
400 }
401
402 static void gr_image_last(const gchar *text, GIOChannel *channel, gpointer data)
403 {
404         layout_image_last(NULL);
405 }
406
407 static void gr_fullscreen_toggle(const gchar *text, GIOChannel *channel, gpointer data)
408 {
409         layout_image_full_screen_toggle(NULL);
410 }
411
412 static void gr_fullscreen_start(const gchar *text, GIOChannel *channel, gpointer data)
413 {
414         layout_image_full_screen_start(NULL);
415 }
416
417 static void gr_fullscreen_stop(const gchar *text, GIOChannel *channel, gpointer data)
418 {
419         layout_image_full_screen_stop(NULL);
420 }
421
422 static void gr_slideshow_start_rec(const gchar *text, GIOChannel *channel, gpointer data)
423 {
424         GList *list;
425         FileData *dir_fd = file_data_new_dir(text);
426         list = filelist_recursive(dir_fd);
427         file_data_unref(dir_fd);
428         if (!list) return;
429 //printf("length: %d\n", g_list_length(list));
430         layout_image_slideshow_stop(NULL);
431         layout_image_slideshow_start_from_list(NULL, list);
432 }
433
434 static void gr_cache_thumb(const gchar *text, GIOChannel *channel, gpointer data)
435 {
436         if (!g_strcmp0(text, "clear"))
437                 cache_maintain_home_remote(FALSE, TRUE);
438         else if (!g_strcmp0(text, "clean"))
439                 cache_maintain_home_remote(FALSE, FALSE);
440 }
441
442 static void gr_cache_shared(const gchar *text, GIOChannel *channel, gpointer data)
443 {
444         if (!g_strcmp0(text, "clear"))
445                 cache_manager_standard_process_remote(TRUE);
446         else if (!g_strcmp0(text, "clean"))
447                 cache_manager_standard_process_remote(FALSE);
448 }
449
450 static void gr_cache_metadata(const gchar *text, GIOChannel *channel, gpointer data)
451 {
452         cache_maintain_home_remote(TRUE, FALSE);
453 }
454
455 static void gr_cache_clear(const gchar *text, GIOChannel *channel, gpointer data)
456 {
457         cache_maintain_home_remote(FALSE, TRUE);
458 }
459
460 static void gr_cache_render(const gchar *text, GIOChannel *channel, gpointer data)
461 {
462         cache_manager_render_remote(text, FALSE, FALSE);
463 }
464
465 static void gr_cache_render_recurse(const gchar *text, GIOChannel *channel, gpointer data)
466 {
467         cache_manager_render_remote(text, TRUE, FALSE);
468 }
469
470 static void gr_cache_render_standard(const gchar *text, GIOChannel *channel, gpointer data)
471 {
472         if(options->thumbnails.spec_standard)
473                 cache_manager_render_remote(text, FALSE, TRUE);
474 }
475
476 static void gr_cache_render_standard_recurse(const gchar *text, GIOChannel *channel, gpointer data)
477 {
478         if(options->thumbnails.spec_standard)
479                 cache_manager_render_remote(text, TRUE, TRUE);
480 }
481
482 static void gr_slideshow_toggle(const gchar *text, GIOChannel *channel, gpointer data)
483 {
484         layout_image_slideshow_toggle(NULL);
485 }
486
487 static void gr_slideshow_start(const gchar *text, GIOChannel *channel, gpointer data)
488 {
489         layout_image_slideshow_start(NULL);
490 }
491
492 static void gr_slideshow_stop(const gchar *text, GIOChannel *channel, gpointer data)
493 {
494         layout_image_slideshow_stop(NULL);
495 }
496
497 static void gr_slideshow_delay(const gchar *text, GIOChannel *channel, gpointer data)
498 {
499         gdouble n;
500
501         n = g_ascii_strtod(text, NULL);
502         if (n < SLIDESHOW_MIN_SECONDS || n > SLIDESHOW_MAX_SECONDS)
503                 {
504                 printf_term("Remote slideshow delay out of range (%.1f to %.1f)\n",
505                             SLIDESHOW_MIN_SECONDS, SLIDESHOW_MAX_SECONDS);
506                 return;
507                 }
508         options->slideshow.delay = (gint)(n * 10.0 + 0.01);
509 }
510
511 static void gr_tools_show(const gchar *text, GIOChannel *channel, gpointer data)
512 {
513         gboolean popped;
514         gboolean hidden;
515
516         if (layout_tools_float_get(NULL, &popped, &hidden) && hidden)
517                 {
518                 layout_tools_float_set(NULL, popped, FALSE);
519                 }
520 }
521
522 static void gr_tools_hide(const gchar *text, GIOChannel *channel, gpointer data)
523 {
524         gboolean popped;
525         gboolean hidden;
526
527         if (layout_tools_float_get(NULL, &popped, &hidden) && !hidden)
528                 {
529                 layout_tools_float_set(NULL, popped, TRUE);
530                 }
531 }
532
533 static gboolean gr_quit_idle_cb(gpointer data)
534 {
535         exit_program();
536
537         return FALSE;
538 }
539
540 static void gr_quit(const gchar *text, GIOChannel *channel, gpointer data)
541 {
542         /* schedule exit when idle, if done from within a
543          * remote handler remote_close will crash
544          */
545         g_idle_add(gr_quit_idle_cb, NULL);
546 }
547
548 static void gr_file_load_no_raise(const gchar *text, GIOChannel *channel, gpointer data)
549 {
550         gchar *filename = expand_tilde(text);
551
552         if (isfile(filename))
553                 {
554                 if (file_extension_match(filename, GQ_COLLECTION_EXT))
555                         {
556                         collection_window_new(filename);
557                         }
558                 else
559                         {
560                         layout_set_path(NULL, filename);
561                         }
562                 }
563         else if (isdir(filename))
564                 {
565                 layout_set_path(NULL, filename);
566                 }
567         else
568                 {
569                 log_printf("remote sent filename that does not exist:\"%s\"\n", filename);
570                 layout_set_path(NULL, homedir());
571                 }
572
573         g_free(filename);
574 }
575
576 static void gr_file_load(const gchar *text, GIOChannel *channel, gpointer data)
577 {
578         gr_file_load_no_raise(text, channel, data);
579
580         gr_raise(text, channel, data);
581 }
582
583 static void gr_file_tell(const gchar *text, GIOChannel *channel, gpointer data)
584 {
585         LayoutWindow *lw = NULL; /* NULL to force layout_valid() to do some magic */
586         if (!layout_valid(&lw)) return;
587         if (image_get_path(lw->image))
588                 {
589                 g_io_channel_write_chars(channel, image_get_path(lw->image), -1, NULL, NULL);
590                 g_io_channel_write_chars(channel, "\n", -1, NULL, NULL);
591                 }
592 }
593
594 static void gr_config_load(const gchar *text, GIOChannel *channel, gpointer data)
595 {
596         gchar *filename = expand_tilde(text);
597
598         if (isfile(filename))
599                 {
600                 load_config_from_file(filename, FALSE);
601                 }
602         else
603                 {
604                 log_printf("remote sent filename that does not exist:\"%s\"\n", filename);
605                 layout_set_path(NULL, homedir());
606                 }
607
608         g_free(filename);
609 }
610
611 static void gr_get_sidecars(const gchar *text, GIOChannel *channel, gpointer data)
612 {
613         gchar *filename = expand_tilde(text);
614         FileData *fd = file_data_new_group(filename);
615
616         GList *work;
617         if (fd->parent) fd = fd->parent;
618
619         g_io_channel_write_chars(channel, fd->path, -1, NULL, NULL);
620         g_io_channel_write_chars(channel, "\n", -1, NULL, NULL);
621
622         work = fd->sidecar_files;
623
624         while (work)
625                 {
626                 fd = work->data;
627                 work = work->next;
628                 g_io_channel_write_chars(channel, fd->path, -1, NULL, NULL);
629                 g_io_channel_write_chars(channel, "\n", -1, NULL, NULL);
630                 }
631         g_free(filename);
632 }
633
634 static void gr_get_destination(const gchar *text, GIOChannel *channel, gpointer data)
635 {
636         gchar *filename = expand_tilde(text);
637         FileData *fd = file_data_new_group(filename);
638
639         if (fd->change && fd->change->dest)
640                 {
641                 g_io_channel_write_chars(channel, fd->change->dest, -1, NULL, NULL);
642                 g_io_channel_write_chars(channel, "\n", -1, NULL, NULL);
643                 }
644         g_free(filename);
645 }
646
647 static void gr_file_view(const gchar *text, GIOChannel *channel, gpointer data)
648 {
649         gchar *filename = expand_tilde(text);
650
651         view_window_new(file_data_new_group(filename));
652         g_free(filename);
653 }
654
655 static void gr_list_clear(const gchar *text, GIOChannel *channel, gpointer data)
656 {
657         RemoteData *remote_data = data;
658
659         if (remote_data->command_collection)
660                 {
661                 collection_unref(remote_data->command_collection);
662                 remote_data->command_collection = NULL;
663                 }
664 }
665
666 static void gr_list_add(const gchar *text, GIOChannel *channel, gpointer data)
667 {
668         RemoteData *remote_data = data;
669         gboolean new = TRUE;
670
671         if (!remote_data->command_collection)
672                 {
673                 CollectionData *cd;
674
675                 cd = collection_new("");
676
677                 g_free(cd->path);
678                 cd->path = NULL;
679                 g_free(cd->name);
680                 cd->name = g_strdup(_("Command line"));
681
682                 remote_data->command_collection = cd;
683                 }
684         else
685                 {
686                 new = (!collection_get_first(remote_data->command_collection));
687                 }
688
689         if (collection_add(remote_data->command_collection, file_data_new_group(text), FALSE) && new)
690                 {
691                 layout_image_set_collection(NULL, remote_data->command_collection,
692                                             collection_get_first(remote_data->command_collection));
693                 }
694 }
695
696 static void gr_raise(const gchar *text, GIOChannel *channel, gpointer data)
697 {
698         LayoutWindow *lw = NULL;
699
700         if (layout_valid(&lw))
701                 {
702                 gtk_window_present(GTK_WINDOW(lw->window));
703                 }
704 }
705
706 typedef struct _RemoteCommandEntry RemoteCommandEntry;
707 struct _RemoteCommandEntry {
708         gchar *opt_s;
709         gchar *opt_l;
710         void (*func)(const gchar *text, GIOChannel *channel, gpointer data);
711         gboolean needs_extra;
712         gboolean prefer_command_line;
713         gchar *parameter;
714         gchar *description;
715 };
716
717 static RemoteCommandEntry remote_commands[] = {
718         /* short, long                  callback,               extra, prefer, parameter, description */
719         { "-n", "--next",               gr_image_next,          FALSE, FALSE, NULL, N_("next image") },
720         { "-b", "--back",               gr_image_prev,          FALSE, FALSE, NULL, N_("previous image") },
721         { NULL, "--first",              gr_image_first,         FALSE, FALSE, NULL, N_("first image") },
722         { NULL, "--last",               gr_image_last,          FALSE, FALSE, NULL, N_("last image") },
723         { "-f", "--fullscreen",         gr_fullscreen_toggle,   FALSE, TRUE,  NULL, N_("toggle full screen") },
724         { "-fs","--fullscreen-start",   gr_fullscreen_start,    FALSE, FALSE, NULL, N_("start full screen") },
725         { "-fS","--fullscreen-stop",    gr_fullscreen_stop,     FALSE, FALSE, NULL, N_("stop full screen") },
726         { "-s", "--slideshow",          gr_slideshow_toggle,    FALSE, TRUE,  NULL, N_("toggle slide show") },
727         { "-ss","--slideshow-start",    gr_slideshow_start,     FALSE, FALSE, NULL, N_("start slide show") },
728         { "-sS","--slideshow-stop",     gr_slideshow_stop,      FALSE, FALSE, NULL, N_("stop slide show") },
729         { NULL, "--slideshow-recurse:", gr_slideshow_start_rec, TRUE,  FALSE, N_("<FOLDER>"), N_("start recursive slide show in FOLDER") },
730         { "-d", "--delay=",             gr_slideshow_delay,     TRUE,  FALSE, N_("<[N][.M]>"), N_("set slide show delay to N.M seconds") },
731         { "+t", "--tools-show",         gr_tools_show,          FALSE, TRUE,  NULL, N_("show tools") },
732         { "-t", "--tools-hide",         gr_tools_hide,          FALSE, TRUE,  NULL, N_("hide tools") },
733         { "-q", "--quit",               gr_quit,                FALSE, FALSE, NULL, N_("quit") },
734         { NULL, "--config-load:",       gr_config_load,         TRUE,  FALSE, N_("<FILE>"), N_("load configuration from FILE") },
735         { NULL, "--get-sidecars:",      gr_get_sidecars,        TRUE,  FALSE, N_("<FILE>"), N_("get list of sidecars of FILE") },
736         { NULL, "--get-destination:",   gr_get_destination,     TRUE,  FALSE, N_("<FILE>"), N_("get destination path of FILE") },
737         { NULL, "file:",                gr_file_load,           TRUE,  FALSE, N_("<FILE>"), N_("open FILE, bring Geeqie window to the top") },
738         { NULL, "File:",                gr_file_load_no_raise,  TRUE,  FALSE, N_("<FILE>"), N_("open FILE, do not bring Geeqie window to the top") },
739         { NULL, "--tell",               gr_file_tell,           FALSE, FALSE, NULL, N_("print filename of current image") },
740         { NULL, "view:",                gr_file_view,           TRUE,  FALSE, N_("<FILE>"), N_("open FILE in new window") },
741         { NULL, "--list-clear",         gr_list_clear,          FALSE, FALSE, NULL, N_("clear command line collection list") },
742         { NULL, "--list-add:",          gr_list_add,            TRUE,  FALSE, N_("<FILE>"), N_("add FILE to command line collection list") },
743         { NULL, "raise",                gr_raise,               FALSE, FALSE, NULL, N_("bring the Geeqie window to the top") },
744         { "-ct:", "--cache-thumbs:",    gr_cache_thumb,         TRUE, FALSE, N_("clear|clean"), N_("clear or clean thumbnail cache") },
745         { "-cs:", "--cache-shared:",    gr_cache_shared,        TRUE, FALSE, N_("clear|clean"), N_("clear or clean shared thumbnail cache") },
746         { "-cm","--cache-metadata",      gr_cache_metadata,               FALSE, FALSE, NULL, N_("    clean the metadata cache") },
747         { "-cr:", "--cache-render:",    gr_cache_render,        TRUE, FALSE, N_("<folder>  "), N_(" render thumbnails") },
748         { "-crr:", "--cache-render-recurse:", gr_cache_render_recurse, TRUE, FALSE, N_("<folder> "), N_("render thumbnails recursively") },
749         { "-crs:", "--cache-render-shared:", gr_cache_render_standard, TRUE, FALSE, N_("<folder> "), N_(" render thumbnails (see Help)") },
750         { "-crsr:", "--cache-render-shared-recurse:", gr_cache_render_standard_recurse, TRUE, FALSE, N_("<folder>"), N_(" render thumbnails recursively (see Help)") },
751         { NULL, NULL, NULL, FALSE, FALSE, NULL }
752 };
753
754 static RemoteCommandEntry *remote_command_find(const gchar *text, const gchar **offset)
755 {
756         gboolean match = FALSE;
757         gint i;
758
759         i = 0;
760         while (!match && remote_commands[i].func != NULL)
761                 {
762                 if (remote_commands[i].needs_extra)
763                         {
764                         if (remote_commands[i].opt_s &&
765                             strncmp(remote_commands[i].opt_s, text, strlen(remote_commands[i].opt_s)) == 0)
766                                 {
767                                 if (offset) *offset = text + strlen(remote_commands[i].opt_s);
768                                 return &remote_commands[i];
769                                 }
770                         else if (remote_commands[i].opt_l &&
771                                  strncmp(remote_commands[i].opt_l, text, strlen(remote_commands[i].opt_l)) == 0)
772                                 {
773                                 if (offset) *offset = text + strlen(remote_commands[i].opt_l);
774                                 return &remote_commands[i];
775                                 }
776                         }
777                 else
778                         {
779                         if ((remote_commands[i].opt_s && strcmp(remote_commands[i].opt_s, text) == 0) ||
780                             (remote_commands[i].opt_l && strcmp(remote_commands[i].opt_l, text) == 0))
781                                 {
782                                 if (offset) *offset = text;
783                                 return &remote_commands[i];
784                                 }
785                         }
786
787                 i++;
788                 }
789
790         return NULL;
791 }
792
793 static void remote_cb(RemoteConnection *rc, const gchar *text, GIOChannel *channel, gpointer data)
794 {
795         RemoteCommandEntry *entry;
796         const gchar *offset;
797
798         entry = remote_command_find(text, &offset);
799         if (entry && entry->func)
800                 {
801                 entry->func(offset, channel, data);
802                 }
803         else
804                 {
805                 log_printf("unknown remote command:%s\n", text);
806                 }
807 }
808
809 void remote_help(void)
810 {
811         gint i;
812         gchar *s_opt_param;
813         gchar *l_opt_param;
814
815         print_term(_("Remote command list:\n"));
816
817         i = 0;
818         while (remote_commands[i].func != NULL)
819                 {
820                 if (remote_commands[i].description)
821                         {
822                         s_opt_param = g_strconcat(remote_commands[i].opt_s, remote_commands[i].parameter, NULL);
823                         l_opt_param = g_strconcat(remote_commands[i].opt_l, remote_commands[i].parameter, NULL);
824                         printf_term("  %-11s%-1s %-30s%-s\n",
825                                     (remote_commands[i].opt_s) ? s_opt_param : "",
826                                     (remote_commands[i].opt_s && remote_commands[i].opt_l) ? "," : " ",
827                                     (remote_commands[i].opt_l) ? l_opt_param : "",
828                                     _(remote_commands[i].description));
829                         g_free(s_opt_param);
830                         g_free(l_opt_param);
831                         }
832                 i++;
833                 }
834         printf_term(N_("\n  All other command line parameters are used as plain files if they exists.\n"));
835 }
836
837 GList *remote_build_list(GList *list, gint argc, gchar *argv[], GList **errors)
838 {
839         gint i;
840
841         i = 1;
842         while (i < argc)
843                 {
844                 RemoteCommandEntry *entry;
845
846                 entry = remote_command_find(argv[i], NULL);
847                 if (entry)
848                         {
849                         list = g_list_append(list, argv[i]);
850                         }
851                 else if (errors && !isfile(argv[i]))
852                         {
853                         *errors = g_list_append(*errors, argv[i]);
854                         }
855                 i++;
856                 }
857
858         return list;
859 }
860
861 /**
862  * \param arg_exec Binary (argv0)
863  * \param remote_list Evaluated and recognized remote commands
864  * \param path The current path
865  * \param cmd_list List of all non collections in Path
866  * \param collection_list List of all collections in argv
867  */
868 void remote_control(const gchar *arg_exec, GList *remote_list, const gchar *path,
869                     GList *cmd_list, GList *collection_list)
870 {
871         RemoteConnection *rc;
872         gboolean started = FALSE;
873         gchar *buf;
874
875         buf = g_build_filename(get_rc_dir(), ".command", NULL);
876         rc = remote_client_open(buf);
877         if (!rc)
878                 {
879                 GString *command;
880                 GList *work;
881                 gint retry_count = 12;
882                 gboolean blank = FALSE;
883
884                 printf_term(_("Remote %s not running, starting..."), GQ_APPNAME);
885
886                 command = g_string_new(arg_exec);
887
888                 work = remote_list;
889                 while (work)
890                         {
891                         gchar *text;
892                         RemoteCommandEntry *entry;
893
894                         text = work->data;
895                         work = work->next;
896
897                         entry = remote_command_find(text, NULL);
898                         if (entry)
899                                 {
900                                 if (entry->prefer_command_line)
901                                         {
902                                         remote_list = g_list_remove(remote_list, text);
903                                         g_string_append(command, " ");
904                                         g_string_append(command, text);
905                                         }
906                                 if (entry->opt_l && strcmp(entry->opt_l, "file:") == 0)
907                                         {
908                                         blank = TRUE;
909                                         }
910                                 }
911                         }
912
913                 if (blank || cmd_list || path) g_string_append(command, " --blank");
914                 if (get_debug_level()) g_string_append(command, " --debug");
915
916                 g_string_append(command, " &");
917                 runcmd(command->str);
918                 g_string_free(command, TRUE);
919
920                 while (!rc && retry_count > 0)
921                         {
922                         usleep((retry_count > 10) ? 500000 : 1000000);
923                         rc = remote_client_open(buf);
924                         if (!rc) print_term(".");
925                         retry_count--;
926                         }
927
928                 print_term("\n");
929
930                 started = TRUE;
931                 }
932         g_free(buf);
933
934         if (rc)
935                 {
936                 GList *work;
937                 const gchar *prefix;
938                 gboolean use_path = TRUE;
939                 gboolean sent = FALSE;
940
941                 work = remote_list;
942                 while (work)
943                         {
944                         gchar *text;
945                         RemoteCommandEntry *entry;
946
947                         text = work->data;
948                         work = work->next;
949
950                         entry = remote_command_find(text, NULL);
951                         if (entry &&
952                             entry->opt_l &&
953                             strcmp(entry->opt_l, "file:") == 0) use_path = FALSE;
954
955                         remote_client_send(rc, text);
956
957                         sent = TRUE;
958                         }
959
960                 if (cmd_list && cmd_list->next)
961                         {
962                         prefix = "--list-add:";
963                         remote_client_send(rc, "--list-clear");
964                         }
965                 else
966                         {
967                         prefix = "file:";
968                         }
969
970                 work = cmd_list;
971                 while (work)
972                         {
973                         FileData *fd;
974                         gchar *text;
975
976                         fd = work->data;
977                         work = work->next;
978
979                         text = g_strconcat(prefix, fd->path, NULL);
980                         remote_client_send(rc, text);
981                         g_free(text);
982
983                         sent = TRUE;
984                         }
985
986                 if (path && !cmd_list && use_path)
987                         {
988                         gchar *text;
989
990                         text = g_strdup_printf("file:%s", path);
991                         remote_client_send(rc, text);
992                         g_free(text);
993
994                         sent = TRUE;
995                         }
996
997                 work = collection_list;
998                 while (work)
999                         {
1000                         const gchar *name;
1001                         gchar *text;
1002
1003                         name = work->data;
1004                         work = work->next;
1005
1006                         text = g_strdup_printf("file:%s", name);
1007                         remote_client_send(rc, text);
1008                         g_free(text);
1009
1010                         sent = TRUE;
1011                         }
1012
1013                 if (!started && !sent)
1014                         {
1015                         remote_client_send(rc, "raise");
1016                         }
1017                 }
1018         else
1019                 {
1020                 print_term(_("Remote not available\n"));
1021                 }
1022
1023         _exit(0);
1024 }
1025
1026 RemoteConnection *remote_server_init(gchar *path, CollectionData *command_collection)
1027 {
1028         RemoteConnection *remote_connection = remote_server_open(path);
1029         RemoteData *remote_data = g_new(RemoteData, 1);
1030
1031         remote_data->command_collection = command_collection;
1032
1033         remote_server_subscribe(remote_connection, remote_cb, remote_data);
1034         return remote_connection;
1035 }
1036 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */