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