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