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