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