Command line auto-completion enhancements
[geeqie.git] / src / main.cc
1 /*
2  * Copyright (C) 2006 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
24 #include <unistd.h>
25
26 #include <clocale>
27 #include <csignal>
28 #include <cstdlib>
29 #include <cstring>
30 #include <ctime>
31
32 #include <config.h>
33
34 #if HAVE_CLUTTER
35 #  include <clutter-gtk/clutter-gtk.h>
36 #  include <clutter/clutter.h>
37 #endif
38
39 #if HAVE_EXECINFO_H
40 #include <execinfo.h>
41 #endif
42
43 #include <gio/gio.h>
44 #include <glib-object.h>
45
46 #ifdef ENABLE_NLS
47 #  include <libintl.h>
48 #endif
49
50 #if HAVE_DEVELOPER
51 #include "third-party/backward.h"
52 #endif
53
54 #include "cache-maint.h"
55 #include "cache.h"
56 #include "collect-io.h"
57 #include "collect.h"
58 #include "compat.h"
59 #include "debug.h"
60 #include "exif.h"
61 #include "filedata.h"
62 #include "filefilter.h"
63 #include "glua.h"
64 #include "histogram.h"
65 #include "history-list.h"
66 #include "image.h"
67 #include "img-view.h"
68 #include "intl.h"
69 #include "layout-image.h"
70 #include "layout-util.h"
71 #include "layout.h"
72 #include "main-defines.h"
73 #include "metadata.h"
74 #include "misc.h"
75 #include "options.h"
76 #include "pixbuf-util.h"
77 #include "rcfile.h"
78 #include "remote.h"
79 #include "secure-save.h"
80 #include "third-party/whereami.h"
81 #include "thumb.h"
82 #include "ui-fileops.h"
83 #include "ui-utildlg.h"
84
85 gboolean thumb_format_changed = FALSE;
86 static RemoteConnection *remote_connection = nullptr;
87
88 gchar *gq_prefix;
89 gchar *gq_localedir;
90 gchar *gq_helpdir;
91 gchar *gq_htmldir;
92 gchar *gq_appdir;
93 gchar *gq_bindir;
94 gchar *gq_executable_path;
95 gchar *desktop_file_template;
96 gchar *instance_identifier;
97
98 #if defined(SA_SIGINFO)
99 void sig_handler_cb(int signo, siginfo_t *info, void *)
100 {
101         gchar hex_char[16];
102         const gchar *signal_name = nullptr;
103         gint i = 0;
104         guint64 addr;
105         guint64 char_index;
106         ssize_t len;
107 #if HAVE_EXECINFO_H
108         gint bt_size;
109         void *bt[1024];
110 #endif
111         struct signals
112                 {
113                 gint sig_no;
114                 const gchar *sig_name;
115                 };
116         struct signals signals_list[7];
117
118         signals_list[0].sig_no = SIGABRT;
119         signals_list[0].sig_name = "Abort";
120         signals_list[1].sig_no = SIGBUS;
121         signals_list[1].sig_name = "Bus error";
122         signals_list[2].sig_no = SIGFPE;
123         signals_list[2].sig_name = "Floating-point exception";
124         signals_list[3].sig_no = SIGILL;
125         signals_list[3].sig_name = "Illegal instruction";
126         signals_list[4].sig_no = SIGIOT;
127         signals_list[4].sig_name = "IOT trap";
128         signals_list[5].sig_no = SIGSEGV;
129         signals_list[5].sig_name = "Invalid memory reference";
130         signals_list[6].sig_no = -1;
131         signals_list[6].sig_name = "END";
132
133         hex_char[0] = '0';
134         hex_char[1] = '1';
135         hex_char[2] = '2';
136         hex_char[3] = '3';
137         hex_char[4] = '4';
138         hex_char[5] = '5';
139         hex_char[6] = '6';
140         hex_char[7] = '7';
141         hex_char[8] = '8';
142         hex_char[9] = '9';
143         hex_char[10] = 'a';
144         hex_char[11] = 'b';
145         hex_char[12] = 'c';
146         hex_char[13] = 'd';
147         hex_char[14] = 'e';
148         hex_char[15] = 'f';
149
150         signal_name = "Unknown signal";
151         while (signals_list[i].sig_no != -1)
152                 {
153                 if (signo == signals_list[i].sig_no)
154                         {
155                         signal_name = signals_list[i].sig_name;
156                         break;
157                         }
158                 i++;
159                 }
160
161         len = write(STDERR_FILENO, "Geeqie fatal error\n", 19);
162         len = write(STDERR_FILENO, "Signal: ", 8);
163         len = write(STDERR_FILENO, signal_name, strlen(signal_name));
164         len = write(STDERR_FILENO, "\n", 1);
165
166         len = write(STDERR_FILENO, "Code: ", 6);
167         len = write(STDERR_FILENO,  (info->si_code == SEGV_MAPERR) ? "Address not mapped" : "Invalid permissions", strlen((info->si_code == SEGV_MAPERR) ? "Address not mapped" : "Invalid permissions"));
168         len = write(STDERR_FILENO, "\n", 1);
169
170         len = write(STDERR_FILENO, "Address: ", 9);
171
172         if (info->si_addr == nullptr)
173                 {
174                 len = write(STDERR_FILENO, "0x0\n", 4);
175                 }
176         else
177                 {
178                 /* Assume the address is 64-bit */
179                 len = write(STDERR_FILENO, "0x", 2);
180                 addr = reinterpret_cast<guint64>(info->si_addr);
181
182                 for (i = 0; i < 16; i++)
183                         {
184                         char_index = addr & 0xf000000000000000;
185                         char_index = char_index >> 60;
186                         addr = addr << 4;
187
188                         len = write(STDERR_FILENO, &hex_char[char_index], 1);
189                         }
190                 len = write(STDERR_FILENO, "\n", 1);
191                 }
192
193 #if HAVE_EXECINFO_H
194         bt_size = backtrace(bt, 1024);
195         backtrace_symbols_fd(bt, bt_size, STDERR_FILENO);
196 #endif
197
198         /* Avoid "not used" warning */
199         len++;
200
201         exit(EXIT_FAILURE);
202 }
203 #else /* defined(SA_SIGINFO) */
204 void sig_handler_cb(int)
205 {
206 #if HAVE_EXECINFO_H
207         gint bt_size;
208         void *bt[1024];
209 #endif
210
211         write(STDERR_FILENO, "Geeqie fatal error\n", 19);
212         write(STDERR_FILENO, "Signal: Segmentation fault\n", 27);
213
214 #if HAVE_EXECINFO_H
215         bt_size = backtrace(bt, 1024);
216         backtrace_symbols_fd(bt, bt_size, STDERR_FILENO);
217 #endif
218
219         exit(EXIT_FAILURE);
220 }
221 #endif /* defined(SA_SIGINFO) */
222
223 /*
224  *-----------------------------------------------------------------------------
225  * keyboard functions
226  *-----------------------------------------------------------------------------
227  */
228
229 void keyboard_scroll_calc(gint *x, gint *y, GdkEventKey *event)
230 {
231         static gint delta = 0;
232         static guint32 time_old = 0;
233         static guint keyval_old = 0;
234
235         if (event->state & GDK_CONTROL_MASK)
236                 {
237                 if (*x < 0) *x = G_MININT / 2;
238                 if (*x > 0) *x = G_MAXINT / 2;
239                 if (*y < 0) *y = G_MININT / 2;
240                 if (*y > 0) *y = G_MAXINT / 2;
241
242                 return;
243                 }
244
245         if (options->progressive_key_scrolling)
246                 {
247                 guint32 time_diff;
248
249                 time_diff = event->time - time_old;
250
251                 /* key pressed within 125ms ? (1/8 second) */
252                 if (time_diff > 125 || event->keyval != keyval_old) delta = 0;
253
254                 time_old = event->time;
255                 keyval_old = event->keyval;
256
257                 delta += 2;
258                 }
259         else
260                 {
261                 delta = 8;
262                 }
263
264         *x = *x * delta * options->keyboard_scroll_step;
265         *y = *y * delta * options->keyboard_scroll_step;
266 }
267
268
269
270 /*
271  *-----------------------------------------------------------------------------
272  * command line parser (private) hehe, who needs popt anyway?
273  *-----------------------------------------------------------------------------
274  */
275
276 static void parse_command_line_add_file(const gchar *file_path, gchar **path, gchar **file,
277                                         GList **list, GList **collection_list)
278 {
279         gchar *path_parsed;
280
281         path_parsed = g_strdup(file_path);
282         parse_out_relatives(path_parsed);
283
284         if (file_extension_match(path_parsed, GQ_COLLECTION_EXT))
285                 {
286                 *collection_list = g_list_append(*collection_list, path_parsed);
287                 }
288         else
289                 {
290                 if (!*path) *path = remove_level_from_path(path_parsed);
291                 if (!*file) *file = g_strdup(path_parsed);
292                 *list = g_list_prepend(*list, path_parsed);
293                 }
294 }
295
296 static void parse_command_line_add_dir(const gchar *dir, gchar **, gchar **, GList **)
297 {
298 #if 0
299         /* This is broken because file filter is not initialized yet.
300         */
301         GList *files;
302         gchar *path_parsed;
303         FileData *dir_fd;
304
305         path_parsed = g_strdup(dir);
306         parse_out_relatives(path_parsed);
307         dir_fd = file_data_new_dir(path_parsed);
308
309
310         if (filelist_read(dir_fd, &files, NULL))
311                 {
312                 GList *work;
313
314                 files = filelist_filter(files, FALSE);
315                 files = filelist_sort_path(files);
316
317                 work = files;
318                 while (work)
319                         {
320                         FileData *fd = static_cast<FileData *>(work->data);
321                         if (!*path) *path = remove_level_from_path(fd->path);
322                         if (!*file) *file = g_strdup(fd->path);
323                         *list = g_list_prepend(*list, fd);
324
325                         work = work->next;
326                         }
327
328                 g_list_free(files);
329                 }
330
331         g_free(path_parsed);
332         file_data_unref(dir_fd);
333 #else
334         DEBUG_1("multiple directories specified, ignoring: %s", dir);
335 #endif
336 }
337
338 static void parse_command_line_process_dir(const gchar *dir, gchar **path, gchar **file,
339                                            GList **list, gchar **first_dir)
340 {
341
342         if (!*list && !*first_dir)
343                 {
344                 *first_dir = g_strdup(dir);
345                 }
346         else
347                 {
348                 if (*first_dir)
349                         {
350                         parse_command_line_add_dir(*first_dir, path, file, list);
351                         g_free(*first_dir);
352                         *first_dir = nullptr;
353                         }
354                 parse_command_line_add_dir(dir, path, file, list);
355                 }
356 }
357
358 static void parse_command_line_process_file(const gchar *file_path, gchar **path, gchar **file,
359                                             GList **list, GList **collection_list, gchar **first_dir)
360 {
361
362         if (*first_dir)
363                 {
364                 parse_command_line_add_dir(*first_dir, path, file, list);
365                 g_free(*first_dir);
366                 *first_dir = nullptr;
367                 }
368         parse_command_line_add_file(file_path, path, file, list, collection_list);
369 }
370
371 static void parse_command_line(gint argc, gchar *argv[])
372 {
373         GList *list = nullptr;
374         GList *remote_list = nullptr;
375         GList *remote_errors = nullptr;
376         gboolean remote_do = FALSE;
377         gchar *first_dir = nullptr;
378         gchar *app_lock;
379         gchar *pwd;
380         gchar *current_dir;
381         gchar *geometry = nullptr;
382         GtkWidget *dialog_warning;
383         GString *command_line_errors = g_string_new(nullptr);
384
385         command_line = g_new0(CommandLine, 1);
386
387         command_line->argc = argc;
388         command_line->argv = argv;
389         command_line->regexp = nullptr;
390
391         if (argc > 1)
392                 {
393                 gint i;
394                 gchar *base_dir = get_current_dir();
395                 i = 1;
396                 while (i < argc)
397                         {
398                         gchar *cmd_line = path_to_utf8(argv[i]);
399                         gchar *cmd_all = g_build_filename(base_dir, cmd_line, NULL);
400
401                         if (cmd_line[0] == G_DIR_SEPARATOR && isdir(cmd_line))
402                                 {
403                                 parse_command_line_process_dir(cmd_line, &command_line->path, &command_line->file, &list, &first_dir);
404                                 }
405                         else if (isdir(cmd_all))
406                                 {
407                                 parse_command_line_process_dir(cmd_all, &command_line->path, &command_line->file, &list, &first_dir);
408                                 }
409                         else if (cmd_line[0] == G_DIR_SEPARATOR && isfile(cmd_line))
410                                 {
411                                 parse_command_line_process_file(cmd_line, &command_line->path, &command_line->file,
412                                                                 &list, &command_line->collection_list, &first_dir);
413                                 }
414                         else if (isfile(cmd_all))
415                                 {
416                                 parse_command_line_process_file(cmd_all, &command_line->path, &command_line->file,
417                                                                 &list, &command_line->collection_list, &first_dir);
418                                 }
419                         else if (download_web_file(cmd_line, FALSE, nullptr))
420                                 {
421                                 }
422                         else if (is_collection(cmd_line))
423                                 {
424                                 gchar *path = nullptr;
425
426                                 path = collection_path(cmd_line);
427                                 parse_command_line_process_file(path, &command_line->path, &command_line->file,
428                                                                 &list, &command_line->collection_list, &first_dir);
429                                 g_free(path);
430                                 }
431                         else if (strncmp(cmd_line, "--debug", 7) == 0 && (cmd_line[7] == '\0' || cmd_line[7] == '='))
432                                 {
433                                 /* do nothing but do not produce warnings */
434                                 }
435                         else if (strncmp(cmd_line, "--disable-clutter", 17) == 0 && (cmd_line[17] == '\0'))
436                                 {
437                                 /* do nothing but do not produce warnings */
438                                 }
439                         else if (strcmp(cmd_line, "-T") == 0 ||
440                                  strcmp(cmd_line, "--with-tools") == 0)
441                                 {
442                                 command_line->tools_show = TRUE;
443
444                                 remote_list = g_list_append(remote_list, g_strdup("-T"));
445                                 }
446                         else if (strcmp(cmd_line, "-t") == 0 ||
447                                  strcmp(cmd_line, "--without-tools") == 0)
448                                 {
449                                 command_line->tools_hide = TRUE;
450
451                                 remote_list = g_list_append(remote_list, g_strdup("-t"));
452                                 }
453                         else if (strcmp(cmd_line, "-f") == 0 ||
454                                  strcmp(cmd_line, "--fullscreen") == 0)
455                                 {
456                                 command_line->startup_full_screen = TRUE;
457                                 }
458                         else if (strcmp(cmd_line, "-s") == 0 ||
459                                  strcmp(cmd_line, "--slideshow") == 0)
460                                 {
461                                 command_line->startup_in_slideshow = TRUE;
462                                 }
463                         else if (strcmp(cmd_line, "-l") == 0 ||
464                                  strcmp(cmd_line, "--list") == 0)
465                                 {
466                                 command_line->startup_command_line_collection = TRUE;
467                                 }
468                         else if (strncmp(cmd_line, "--geometry=", 11) == 0)
469                                 {
470                                 if (!command_line->geometry) command_line->geometry = g_strdup(cmd_line + 11);
471                                 }
472                         else if (strcmp(cmd_line, "-r") == 0 ||
473                                  strcmp(cmd_line, "--remote") == 0)
474                                 {
475                                 if (!remote_do)
476                                         {
477                                         remote_do = TRUE;
478                                         remote_list = remote_build_list(remote_list, argc - i, &argv[i], &remote_errors);
479                                         }
480                                 }
481                         else if ((strcmp(cmd_line, "-w") == 0) ||
482                                                 strcmp(cmd_line, "--show-log-window") == 0)
483                                 {
484                                 command_line->log_window_show = TRUE;
485                                 }
486                         else if (strncmp(cmd_line, "-o:", 3) == 0)
487                                 {
488                                 command_line->log_file = g_strdup(cmd_line + 3);
489                                 }
490                         else if (strncmp(cmd_line, "--log-file:", 11) == 0)
491                                 {
492                                 command_line->log_file = g_strdup(cmd_line + 11);
493                                 }
494                         else if (strncmp(cmd_line, "-g:", 3) == 0)
495                                 {
496                                 set_regexp(g_strdup(cmd_line+3));
497                                 }
498                         else if (strncmp(cmd_line, "-grep:", 6) == 0)
499                                 {
500                                 set_regexp(g_strdup(cmd_line+3));
501                                 }
502                         else if (strncmp(cmd_line, "-n", 2) == 0)
503                                 {
504                                 command_line->new_instance = TRUE;
505                                 }
506                         else if (strncmp(cmd_line, "--new-instance", 14) == 0)
507                                 {
508                                 command_line->new_instance = TRUE;
509                                 }
510                         else if (strcmp(cmd_line, "-rh") == 0 ||
511                                  strcmp(cmd_line, "--remote-help") == 0)
512                                 {
513                                 remote_help();
514                                 exit(0);
515                                 }
516                         else if (strcmp(cmd_line, "--blank") == 0)
517                                 {
518                                 command_line->startup_blank = TRUE;
519                                 }
520                         else if (strcmp(cmd_line, "-v") == 0 ||
521                                  strcmp(cmd_line, "--version") == 0)
522                                 {
523                                 printf_term(FALSE, "%s %s GTK%d\n", GQ_APPNAME, VERSION, gtk_major_version);
524                                 exit(0);
525                                 }
526                         else if (strcmp(cmd_line, "-h") == 0 ||
527                                  strcmp(cmd_line, "--help") == 0)
528                                 {
529                                 printf_term(FALSE, "%s %s\n", GQ_APPNAME, VERSION);
530                                 printf_term(FALSE, _("Usage: %s [options] [path]\n\n"), GQ_APPNAME_LC);
531                                 print_term(FALSE, _("Valid options:\n"));
532                                 print_term(FALSE, _("      --blank                      start with blank file list\n"));
533                                 print_term(FALSE, _("      --cache-maintenance <path>   run cache maintenance in non-GUI mode\n"));
534                                 print_term(FALSE, _("      --disable-clutter            disable use of Clutter library (i.e. GPU accel.)\n"));
535                                 print_term(FALSE, _("  -f, --fullscreen                 start in full screen mode\n"));
536                                 print_term(FALSE, _("      --geometry=WxH+XOFF+YOFF     set main window location\n"));
537                                 print_term(FALSE, _("  -h, --help                       show this message\n"));
538                                 print_term(FALSE, _("  -l, --list [files] [collections] open collection window for command line\n"));
539                                 print_term(FALSE, _("  -n, --new-instance               open a new instance of Geeqie *\n"));
540                                 print_term(FALSE, _("  -o:, --log-file:<file>           save log data to file\n"));
541                                 print_term(FALSE, _("  -r, --remote                     send following commands to open window\n"));
542                                 print_term(FALSE, _("  -rh, --remote-help               print remote command list\n"));
543                                 print_term(FALSE, _("  -s, --slideshow                  start in slideshow mode\n"));
544                                 print_term(FALSE, _("  -T, --with-tools                 force show of tools\n"));
545                                 print_term(FALSE, _("  -t, --without-tools              force hide of tools\n"));
546                                 print_term(FALSE, _("  -v, --version                    print version info\n"));
547                                 print_term(FALSE, _("  -w, --show-log-window            show log window\n"));
548 #ifdef DEBUG
549                                 print_term(FALSE, _("      --debug[=level]              turn on debug output\n"));
550                                 print_term(FALSE, _("  -g:, --grep:<regexp>             filter debug output\n"));
551 #endif
552
553                                 print_term(FALSE, "\n");
554                                 print_term(FALSE, "* Normally a single set of configuration files is used for all instances.\nHowever, the environment variables XDG_CONFIG_HOME, XDG_CACHE_HOME, XDG_DATA_HOME\ncan be used to modify this behavior on an individual basis e.g.\n\nXDG_CONFIG_HOME=/tmp/a XDG_CACHE_HOME=/tmp/b geeqie\n\n");
555
556                                 remote_help();
557
558
559                                 exit(0);
560                                 }
561                         else if (!remote_do)
562                                 {
563                                 g_string_append_printf(command_line_errors, is_remote_command(cmd_line) ? _("%s\n\nThis is a --remote command option\n") : _("%s\n\nThis option is unknown\n"), cmd_line);
564                                 }
565
566                         g_free(cmd_all);
567                         g_free(cmd_line);
568                         i++;
569                         }
570
571                 if (command_line_errors->len > 0)
572                         {
573                         dialog_warning = gtk_message_dialog_new(nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", "Invalid parameter(s):");
574                         gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog_warning), "%s", command_line_errors->str);
575                         gtk_window_set_title(GTK_WINDOW(dialog_warning), GQ_APPNAME);
576                         gq_gtk_window_set_keep_above(GTK_WINDOW(dialog_warning), TRUE);
577                         gtk_dialog_run(GTK_DIALOG(dialog_warning));
578                         g_object_unref(dialog_warning);
579                         g_string_free(command_line_errors, TRUE);
580
581                         exit(EXIT_FAILURE);
582                         }
583
584                 g_free(base_dir);
585                 parse_out_relatives(command_line->path);
586                 parse_out_relatives(command_line->file);
587                 }
588
589         list = g_list_reverse(list);
590
591         if (!command_line->path && first_dir)
592                 {
593                 command_line->path = first_dir;
594                 first_dir = nullptr;
595
596                 parse_out_relatives(command_line->path);
597                 }
598         g_free(first_dir);
599
600         if (!command_line->new_instance)
601                 {
602                 /* If Geeqie is already running, prevent a second instance
603                  * from being started. Open a new window instead.
604                  */
605                 app_lock = g_build_filename(get_rc_dir(), ".command", NULL);
606                 if (remote_server_exists(app_lock) && !remote_do)
607                         {
608                         remote_do = TRUE;
609                         if (command_line->geometry)
610                                 {
611                                 geometry = g_strdup_printf("--geometry=%s", command_line->geometry);
612                                 remote_list = g_list_prepend(remote_list, geometry);
613                                 }
614                         remote_list = g_list_prepend(remote_list, g_strdup("--new-window"));
615                         }
616                 g_free(app_lock);
617                 }
618
619         if (remote_do)
620                 {
621                 if (remote_errors)
622                         {
623                         GList *work = remote_errors;
624
625                         while (work)
626                                 {
627                                 auto opt = static_cast<gchar *>(work->data);
628
629                                 command_line_errors = g_string_append(command_line_errors, opt);
630                                 command_line_errors = g_string_append(command_line_errors, "\n");
631                                 work = work->next;
632                                 }
633
634                         dialog_warning = gtk_message_dialog_new(nullptr, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", "Invalid parameter(s):");
635                         gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog_warning), "%s", command_line_errors->str);
636                         gtk_window_set_title(GTK_WINDOW(dialog_warning), GQ_APPNAME);
637                         gq_gtk_window_set_keep_above(GTK_WINDOW(dialog_warning), TRUE);
638                         gtk_dialog_run(GTK_DIALOG(dialog_warning));
639                         g_object_unref(dialog_warning);
640                         g_string_free(command_line_errors, TRUE);
641
642                         exit(EXIT_FAILURE);
643                         }
644
645                 /* prepend the current dir the remote command was made from,
646                  * for use by any remote command that needs it
647                  */
648                 current_dir = g_get_current_dir();
649                 pwd = g_strconcat("--PWD:", current_dir, NULL);
650                 remote_list = g_list_prepend(remote_list, pwd);
651
652                 remote_control(argv[0], remote_list, command_line->path, list, command_line->collection_list);
653                 /* There is no return to this point
654                  */
655                 g_free(pwd);
656                 g_free(current_dir);
657                 }
658         g_free(geometry);
659         g_list_free(remote_list);
660
661         if (list && list->next)
662                 {
663                 command_line->cmd_list = list;
664                 }
665         else
666                 {
667                 g_list_free_full(list, g_free);
668                 command_line->cmd_list = nullptr;
669                 }
670
671         if (command_line->startup_blank)
672                 {
673                 g_free(command_line->path);
674                 command_line->path = nullptr;
675                 g_free(command_line->file);
676                 command_line->file = nullptr;
677                 filelist_free(command_line->cmd_list);
678                 command_line->cmd_list = nullptr;
679                 g_list_free_full(command_line->collection_list, g_free);
680                 command_line->collection_list = nullptr;
681                 }
682 }
683
684 static void parse_command_line_for_debug_option(gint argc, gchar *argv[])
685 {
686 #ifdef DEBUG
687         const gchar *debug_option = "--debug";
688         gint len = strlen(debug_option);
689
690         if (argc > 1)
691                 {
692                 gint i;
693
694                 for (i = 1; i < argc; i++)
695                         {
696                         const gchar *cmd_line = argv[i];
697                         if (strncmp(cmd_line, debug_option, len) == 0)
698                                 {
699                                 gint cmd_line_len = strlen(cmd_line);
700
701                                 /* we now increment the debug state for verbosity */
702                                 if (cmd_line_len == len)
703                                         debug_level_add(1);
704                                 else if (cmd_line[len] == '=' && g_ascii_isdigit(cmd_line[len+1]))
705                                         {
706                                         gint n = atoi(cmd_line + len + 1);
707                                         if (n < 0) n = 1;
708                                         debug_level_add(n);
709                                         }
710                                 }
711                         }
712                 }
713
714         DEBUG_1("debugging output enabled (level %d)", get_debug_level());
715 #endif
716 }
717
718 #if HAVE_CLUTTER
719 static gboolean parse_command_line_for_clutter_option(gint argc, gchar *argv[])
720 {
721         const gchar *clutter_option = "--disable-clutter";
722         gint len = strlen(clutter_option);
723         gboolean ret = FALSE;
724
725         if (argc > 1)
726                 {
727                 gint i;
728
729                 for (i = 1; i < argc; i++)
730                         {
731                         const gchar *cmd_line = argv[i];
732                         if (strncmp(cmd_line, clutter_option, len) == 0)
733                                 {
734                                 ret = TRUE;
735                                 }
736                         }
737                 }
738
739         return ret;
740 }
741 #endif
742
743 static gboolean parse_command_line_for_cache_maintenance_option(gint argc, gchar *argv[])
744 {
745         const gchar *cache_maintenance_option = "--cache-maintenance";
746         gint len = strlen(cache_maintenance_option);
747         gboolean ret = FALSE;
748
749         if (argc >= 2)
750                 {
751                 const gchar *cmd_line = argv[1];
752                 if (strncmp(cmd_line, cache_maintenance_option, len) == 0)
753                         {
754                         ret = TRUE;
755                         }
756                 }
757
758         return ret;
759 }
760
761 static void process_command_line_for_cache_maintenance_option(gint argc, gchar *argv[])
762 {
763         gchar *rc_path;
764         gchar *folder_path = nullptr;
765         gsize size;
766         gsize i = 0;
767         gchar *buf_config_file;
768         gint diff_count;
769
770         if (argc >= 3)
771                 {
772                 folder_path = expand_tilde(argv[2]);
773
774                 if (isdir(folder_path))
775                         {
776                         rc_path = g_build_filename(get_rc_dir(), RC_FILE_NAME, NULL);
777
778                         if (isfile(rc_path))
779                                 {
780                                 if (g_file_get_contents(rc_path, &buf_config_file, &size, nullptr))
781                                         {
782                                         while (i < size)
783                                                 {
784                                                 diff_count = strncmp("</global>", &buf_config_file[i], 9);
785                                                 if (diff_count == 0)
786                                                         {
787                                                         break;
788                                                         }
789                                                 i++;
790                                                 }
791                                         /* Load only the <global> section */
792                                         load_config_from_buf(buf_config_file, i + 9, FALSE);
793
794                                         if (options->thumbnails.enable_caching)
795                                                 {
796                                                 cache_maintenance(folder_path);
797                                                 }
798                                         else
799                                                 {
800                                                 print_term(TRUE, "Caching not enabled\n");
801                                                 exit(EXIT_FAILURE);
802                                                 }
803                                         g_free(buf_config_file);
804                                         }
805                                 else
806                                         {
807                                         print_term(TRUE, g_strconcat(_("Cannot load "), rc_path, "\n", NULL));
808                                         exit(EXIT_FAILURE);
809                                         }
810                                 }
811                         else
812                                 {
813                                 print_term(TRUE, g_strconcat(_("Configuration file path "), rc_path, _(" is not a file\n"), NULL));
814                                 exit(EXIT_FAILURE);
815                                 }
816                         g_free(rc_path);
817                         }
818                 else
819                         {
820                         print_term(TRUE, g_strconcat(argv[2], _(" is not a folder\n"), NULL));
821                         exit(EXIT_FAILURE);
822                         }
823                 g_free(folder_path);
824                 }
825         else
826                 {
827                 print_term(TRUE, _("No path parameter given\n"));
828                 exit(EXIT_FAILURE);
829                 }
830 }
831
832 /*
833  *-----------------------------------------------------------------------------
834  * startup, init, and exit
835  *-----------------------------------------------------------------------------
836  */
837
838 #define RC_HISTORY_NAME "history"
839 #define RC_MARKS_NAME "marks"
840
841 static void setup_env_path()
842 {
843         const gchar *old_path = g_getenv("PATH");
844         gchar *path = g_strconcat(gq_bindir, ":", old_path, NULL);
845         g_setenv("PATH", path, TRUE);
846         g_free(path);
847 }
848
849 static void keys_load()
850 {
851         gchar *path;
852
853         path = g_build_filename(get_rc_dir(), RC_HISTORY_NAME, NULL);
854         history_list_load(path);
855         g_free(path);
856 }
857
858 static void keys_save()
859 {
860         gchar *path;
861
862         path = g_build_filename(get_rc_dir(), RC_HISTORY_NAME, NULL);
863         history_list_save(path);
864         g_free(path);
865 }
866
867 static void marks_load()
868 {
869         gchar *path;
870
871         path = g_build_filename(get_rc_dir(), RC_MARKS_NAME, NULL);
872         marks_list_load(path);
873         g_free(path);
874 }
875
876 static void marks_save(gboolean save)
877 {
878         gchar *path;
879
880         path = g_build_filename(get_rc_dir(), RC_MARKS_NAME, NULL);
881         marks_list_save(path, save);
882         g_free(path);
883 }
884
885 static void mkdir_if_not_exists(const gchar *path)
886 {
887         if (isdir(path)) return;
888
889         log_printf(_("Creating %s dir:%s\n"), GQ_APPNAME, path);
890
891         if (!recursive_mkdir_if_not_exists(path, 0755))
892                 {
893                 log_printf(_("Could not create dir:%s\n"), path);
894                 }
895 }
896
897
898 /* We add to duplicate and modify  gtk_accel_map_print() and gtk_accel_map_save()
899  * to improve the reliability in special cases (especially when disk is full)
900  * These functions are now using secure saving stuff.
901  */
902 static void gq_accel_map_print(
903                     gpointer    data,
904                     const gchar *accel_path,
905                     guint       accel_key,
906                     GdkModifierType accel_mods,
907                     gboolean    changed)
908 {
909         GString *gstring = g_string_new(changed ? nullptr : "; ");
910         auto ssi = static_cast<SecureSaveInfo *>(data);
911         gchar *tmp;
912         gchar *name;
913
914         g_string_append(gstring, "(gtk_accel_path \"");
915
916         tmp = g_strescape(accel_path, nullptr);
917         g_string_append(gstring, tmp);
918         g_free(tmp);
919
920         g_string_append(gstring, "\" \"");
921
922         name = gtk_accelerator_name(accel_key, accel_mods);
923         tmp = g_strescape(name, nullptr);
924         g_free(name);
925         g_string_append(gstring, tmp);
926         g_free(tmp);
927
928         g_string_append(gstring, "\")\n");
929
930         secure_fwrite(gstring->str, sizeof(*gstring->str), gstring->len, ssi);
931
932         g_string_free(gstring, TRUE);
933 }
934
935 static gboolean gq_accel_map_save(const gchar *path)
936 {
937         gchar *pathl;
938         SecureSaveInfo *ssi;
939         GString *gstring;
940
941         pathl = path_from_utf8(path);
942         ssi = secure_open(pathl);
943         g_free(pathl);
944         if (!ssi)
945                 {
946                 log_printf(_("error saving file: %s\n"), path);
947                 return FALSE;
948                 }
949
950         gstring = g_string_new("; ");
951         if (g_get_prgname())
952                 g_string_append(gstring, g_get_prgname());
953         g_string_append(gstring, " GtkAccelMap rc-file         -*- scheme -*-\n");
954         g_string_append(gstring, "; this file is an automated accelerator map dump\n");
955         g_string_append(gstring, ";\n");
956
957         secure_fwrite(gstring->str, sizeof(*gstring->str), gstring->len, ssi);
958
959         g_string_free(gstring, TRUE);
960
961         gtk_accel_map_foreach(ssi, gq_accel_map_print);
962
963         if (secure_close(ssi))
964                 {
965                 log_printf(_("error saving file: %s\nerror: %s\n"), path,
966                            secsave_strerror(secsave_errno));
967                 return FALSE;
968                 }
969
970         return TRUE;
971 }
972
973 static gchar *accep_map_filename()
974 {
975         return g_build_filename(get_rc_dir(), "accels", NULL);
976 }
977
978 static void accel_map_save()
979 {
980         gchar *path;
981
982         path = accep_map_filename();
983         gq_accel_map_save(path);
984         g_free(path);
985 }
986
987 static void accel_map_load()
988 {
989         gchar *path;
990         gchar *pathl;
991
992         path = accep_map_filename();
993         pathl = path_from_utf8(path);
994         gtk_accel_map_load(pathl);
995         g_free(pathl);
996         g_free(path);
997 }
998
999 static void gtkrc_load()
1000 {
1001         gchar *path;
1002         gchar *pathl;
1003
1004         /* If a gtkrc file exists in the rc directory, add it to the
1005          * list of files to be parsed at the end of gtk_init() */
1006         path = g_build_filename(get_rc_dir(), "gtkrc", NULL);
1007         pathl = path_from_utf8(path);
1008         if (access(pathl, R_OK) == 0)
1009                 gtk_rc_add_default_file(pathl);
1010         g_free(pathl);
1011         g_free(path);
1012 }
1013
1014 static void exit_program_final()
1015 {
1016         LayoutWindow *lw = nullptr;
1017         GList *list;
1018         LayoutWindow *tmp_lw;
1019         gchar *archive_dir;
1020         GFile *archive_file;
1021
1022          /* make sure that external editors are loaded, we would save incomplete configuration otherwise */
1023         layout_editors_reload_finish();
1024
1025         remote_close(remote_connection);
1026
1027         collect_manager_flush();
1028
1029         /* Save the named windows */
1030         if (layout_window_list && layout_window_list->next)
1031                 {
1032                 list = layout_window_list;
1033                 while (list)
1034                         {
1035                         tmp_lw = static_cast<LayoutWindow *>(list->data);
1036                         if (!g_str_has_prefix(tmp_lw->options.id, "lw"))
1037                                 {
1038                                 save_layout(static_cast<LayoutWindow *>(list->data));
1039                                 }
1040                         list = list->next;
1041                         }
1042                 }
1043
1044         save_options(options);
1045         keys_save();
1046         accel_map_save();
1047
1048         if (layout_valid(&lw))
1049                 {
1050                 layout_free(lw);
1051                 }
1052
1053         /* Delete any files/folders in /tmp that have been created by the open archive function */
1054         archive_dir = g_build_filename(g_get_tmp_dir(), GQ_ARCHIVE_DIR, instance_identifier, NULL);
1055         if (isdir(archive_dir))
1056                 {
1057                 archive_file = g_file_new_for_path(archive_dir);
1058                 rmdir_recursive(archive_file, nullptr, nullptr);
1059                 g_free(archive_dir);
1060                 g_object_unref(archive_file);
1061                 }
1062
1063         /* If there are still sub-dirs created by another instance, this will fail
1064          * but that does not matter */
1065         archive_dir = g_build_filename(g_get_tmp_dir(), GQ_ARCHIVE_DIR, NULL);
1066         if (isdir(archive_dir))
1067                 {
1068                 archive_file = g_file_new_for_path(archive_dir);
1069                 g_file_delete(archive_file, nullptr, nullptr);
1070                 g_free(archive_dir);
1071                 g_object_unref(archive_file);
1072                 }
1073
1074         secure_close(command_line->ssi);
1075
1076         gtk_main_quit();
1077 }
1078
1079 static GenericDialog *exit_dialog = nullptr;
1080
1081 static void exit_confirm_cancel_cb(GenericDialog *gd, gpointer)
1082 {
1083         exit_dialog = nullptr;
1084         generic_dialog_close(gd);
1085 }
1086
1087 static void exit_confirm_exit_cb(GenericDialog *gd, gpointer)
1088 {
1089         exit_dialog = nullptr;
1090         generic_dialog_close(gd);
1091         exit_program_final();
1092 }
1093
1094 static gint exit_confirm_dlg()
1095 {
1096         GtkWidget *parent;
1097         LayoutWindow *lw;
1098         gchar *msg;
1099         GString *message;
1100
1101         if (exit_dialog)
1102                 {
1103                 gtk_window_present(GTK_WINDOW(exit_dialog->dialog));
1104                 return TRUE;
1105                 }
1106
1107         if (!collection_window_modified_exists() && (layout_window_count() == 1)) return FALSE;
1108
1109         parent = nullptr;
1110         lw = nullptr;
1111         if (layout_valid(&lw))
1112                 {
1113                 parent = lw->window;
1114                 }
1115
1116         msg = g_strdup_printf("%s - %s", GQ_APPNAME, _("exit"));
1117         exit_dialog = generic_dialog_new(msg,
1118                                 "exit", parent, FALSE,
1119                                 exit_confirm_cancel_cb, nullptr);
1120         g_free(msg);
1121         msg = g_strdup_printf(_("Quit %s"), GQ_APPNAME);
1122
1123         message = g_string_new(nullptr);
1124
1125         if (collection_window_modified_exists())
1126                 {
1127                 message = g_string_append(message, _("Collections have been modified.\n"));
1128                 }
1129
1130         if (layout_window_count() > 1)
1131                 {
1132                 g_string_append_printf(message, _("%d windows are open.\n\n"), layout_window_count());
1133                 }
1134
1135         message = g_string_append(message, _("Quit anyway?"));
1136
1137         generic_dialog_add_message(exit_dialog, GQ_ICON_DIALOG_QUESTION, msg, message->str, TRUE);
1138         g_free(msg);
1139         generic_dialog_add_button(exit_dialog, GQ_ICON_QUIT, _("Quit"), exit_confirm_exit_cb, TRUE);
1140
1141         gtk_widget_show(exit_dialog->dialog);
1142
1143         g_string_free(message, TRUE);
1144
1145         return TRUE;
1146 }
1147
1148 static void exit_program_write_metadata_cb(gint success, const gchar *, gpointer)
1149 {
1150         if (success) exit_program();
1151 }
1152
1153 void exit_program()
1154 {
1155         layout_image_full_screen_stop(nullptr);
1156
1157         if (metadata_write_queue_confirm(FALSE, exit_program_write_metadata_cb, nullptr)) return;
1158
1159         options->marks_save ? marks_save(TRUE) : marks_save(FALSE);
1160
1161         if (exit_confirm_dlg()) return;
1162
1163         exit_program_final();
1164 }
1165
1166 /* This code attempts to handle situation when a file mmaped by image_loader
1167  * or by exif loader is truncated by some other process.
1168  * This code is incorrect according to POSIX, because:
1169  *
1170  *   mmap is not async-signal-safe and thus may not be called from a signal handler
1171  *
1172  *   mmap must be called with a valid file descriptor.  POSIX requires that
1173  *   a fildes argument of -1 must cause mmap to return EBADF.
1174  *
1175  * See https://github.com/BestImageViewer/geeqie/issues/1052 for discussion of
1176  * an alternative approach.
1177  */
1178 /** @FIXME this probably needs some better ifdefs. Please report any compilation problems */
1179 /** @FIXME This section needs revising */
1180
1181 #pragma GCC diagnostic push
1182 #pragma GCC diagnostic ignored "-Wunused-function"
1183 #if defined(SIGBUS) && defined(SA_SIGINFO)
1184 static void sigbus_handler_cb_unused(int, siginfo_t *info, void *)
1185 {
1186         /*
1187          * @FIXME Design and implement a POSIX-acceptable approach,
1188          * after first documenting the sitations where SIGBUS occurs.
1189          * See https://github.com/BestImageViewer/geeqie/issues/1052 for discussion
1190          */
1191
1192         DEBUG_1("SIGBUS %p NOT HANDLED", info->si_addr);
1193         exit(EXIT_FAILURE);
1194 }
1195 #endif
1196
1197 static void setup_sigbus_handler_unused()
1198 {
1199 #if defined(SIGBUS) && defined(SA_SIGINFO)
1200         struct sigaction sigbus_action;
1201         sigfillset(&sigbus_action.sa_mask);
1202         sigbus_action.sa_sigaction = sigbus_handler_cb_unused;
1203         sigbus_action.sa_flags = SA_SIGINFO;
1204
1205         sigaction(SIGBUS, &sigbus_action, nullptr);
1206 #endif
1207 }
1208 #pragma GCC diagnostic pop
1209
1210 #if !HAVE_DEVELOPER
1211 static void setup_sig_handler()
1212 {
1213         struct sigaction sigsegv_action;
1214         sigfillset(&sigsegv_action.sa_mask);
1215         sigsegv_action.sa_sigaction = sig_handler_cb;
1216         sigsegv_action.sa_flags = SA_SIGINFO;
1217
1218         sigaction(SIGABRT, &sigsegv_action, nullptr);
1219         sigaction(SIGBUS, &sigsegv_action, nullptr);
1220         sigaction(SIGFPE, &sigsegv_action, nullptr);
1221         sigaction(SIGILL, &sigsegv_action, nullptr);
1222         sigaction(SIGIOT, &sigsegv_action, nullptr);
1223         sigaction(SIGSEGV, &sigsegv_action, nullptr);
1224 }
1225 #endif
1226
1227 static void set_theme_bg_color()
1228 {
1229         GdkRGBA bg_color;
1230         GdkRGBA theme_color;
1231         GtkStyleContext *style_context;
1232         GList *work;
1233         LayoutWindow *lw;
1234
1235         if (!options->image.use_custom_border_color)
1236                 {
1237                 work = layout_window_list;
1238                 lw = static_cast<LayoutWindow *>(work->data);
1239
1240                 style_context = gtk_widget_get_style_context(lw->window);
1241                 gtk_style_context_get_background_color(style_context, GTK_STATE_FLAG_NORMAL, &bg_color);
1242
1243                 theme_color.red = bg_color.red  ;
1244                 theme_color.green = bg_color.green  ;
1245                 theme_color.blue = bg_color.blue ;
1246
1247                 while (work)
1248                         {
1249                         lw = static_cast<LayoutWindow *>(work->data);
1250                         image_background_set_color(lw->image, &theme_color);
1251                         work = work->next;
1252                         }
1253                 }
1254
1255         view_window_colors_update();
1256 }
1257
1258 static gboolean theme_change_cb(GObject *, GParamSpec *, gpointer)
1259 {
1260         set_theme_bg_color();
1261
1262         return FALSE;
1263 }
1264
1265 /**
1266  * @brief Set up the application paths
1267  *
1268  * This function is required for use of AppImages. AppImages are
1269  * relocatable, and therefore cannot use fixed paths to various components.
1270  * These paths were originally #defines created during compilation.
1271  * They are now variables, all defined relative to one level above the
1272  * directory that the executable is run from.
1273  */
1274 static void create_application_paths()
1275 {
1276         gchar *dirname;
1277         gint length;
1278         gchar *path;
1279
1280         length = wai_getExecutablePath(nullptr, 0, nullptr);
1281         path = static_cast<gchar *>(malloc(length + 1));
1282         wai_getExecutablePath(path, length, nullptr);
1283         path[length] = '\0';
1284
1285         gq_executable_path = g_strdup(path);
1286         dirname = g_path_get_dirname(gq_executable_path);
1287         gq_prefix = g_path_get_dirname(dirname);
1288
1289         gq_localedir = g_build_filename(gq_prefix, GQ_LOCALEDIR, NULL);
1290         gq_helpdir = g_build_filename(gq_prefix, GQ_HELPDIR, NULL);
1291         gq_htmldir = g_build_filename(gq_prefix, GQ_HTMLDIR, NULL);
1292         gq_appdir = g_build_filename(gq_prefix, GQ_APPDIR, NULL);
1293         gq_bindir = g_build_filename(gq_prefix, GQ_BINDIR, NULL);
1294         desktop_file_template = g_build_filename(gq_appdir, "org.geeqie.template.desktop", NULL);
1295
1296         g_free(dirname);
1297         g_free(path);
1298 }
1299
1300 gint main(gint argc, gchar *argv[])
1301 {
1302         CollectionData *cd = nullptr;
1303         CollectionData *first_collection = nullptr;
1304         gboolean disable_clutter = FALSE;
1305         gboolean single_dir = TRUE;
1306         gchar *buf;
1307         GdkScreen *screen;
1308         GtkCssProvider *provider;
1309         GtkSettings *default_settings;
1310         LayoutWindow *lw;
1311
1312         gdk_set_allowed_backends("x11,*");
1313
1314         gdk_threads_init();
1315         gdk_threads_enter();
1316
1317         /* seg. fault handler */
1318 #if HAVE_DEVELOPER
1319         backward::SignalHandling sh{};
1320 #else
1321         setup_sig_handler();
1322 #endif
1323
1324         /* init execution time counter (debug only) */
1325         init_exec_time();
1326
1327         create_application_paths();
1328
1329         /* setup locale, i18n */
1330         setlocale(LC_ALL, "");
1331
1332 #ifdef ENABLE_NLS
1333         bindtextdomain(PACKAGE, gq_localedir);
1334         bind_textdomain_codeset(PACKAGE, "UTF-8");
1335         textdomain(PACKAGE);
1336 #endif
1337
1338         exif_init();
1339
1340 #if HAVE_LUA
1341         lua_init();
1342 #endif
1343
1344         /* setup random seed for random slideshow */
1345         srand(time(nullptr));
1346
1347 #if 0
1348         /* See later comment; this handler leads to UB. */
1349         setup_sigbus_handler();
1350 #endif
1351
1352         /* register global notify functions */
1353         file_data_register_notify_func(cache_notify_cb, nullptr, NOTIFY_PRIORITY_HIGH);
1354         file_data_register_notify_func(thumb_notify_cb, nullptr, NOTIFY_PRIORITY_HIGH);
1355         file_data_register_notify_func(histogram_notify_cb, nullptr, NOTIFY_PRIORITY_HIGH);
1356         file_data_register_notify_func(collect_manager_notify_cb, nullptr, NOTIFY_PRIORITY_LOW);
1357         file_data_register_notify_func(metadata_notify_cb, nullptr, NOTIFY_PRIORITY_LOW);
1358
1359
1360         gtkrc_load();
1361
1362         parse_command_line_for_debug_option(argc, argv);
1363         DEBUG_1("%s main: gtk_init", get_exec_time());
1364 #if HAVE_CLUTTER
1365         if (parse_command_line_for_clutter_option(argc, argv))
1366                 {
1367                 disable_clutter = TRUE;
1368                 gtk_init(&argc, &argv);
1369                 }
1370         else
1371                 {
1372                 if (gtk_clutter_init(&argc, &argv) != CLUTTER_INIT_SUCCESS)
1373                         {
1374                         log_printf("Can't initialize clutter-gtk.\nStart Geeqie with the option \"geeqie --disable-clutter\"");
1375                         runcmd("zenity --error --title=\"Geeqie\" --text \"Can't initialize clutter-gtk.\n\nStart Geeqie with the option:\n geeqie --disable-clutter\" --width=300");
1376                         exit(1);
1377                         }
1378                 }
1379 #else
1380         gtk_init(&argc, &argv);
1381 #endif
1382
1383         if (gtk_major_version < GTK_MAJOR_VERSION ||
1384             (gtk_major_version == GTK_MAJOR_VERSION && gtk_minor_version < GTK_MINOR_VERSION) )
1385                 {
1386                 log_printf("!!! This is a friendly warning.\n");
1387                 log_printf("!!! The version of GTK+ in use now is older than when %s was compiled.\n", GQ_APPNAME);
1388                 log_printf("!!!  compiled with GTK+-%d.%d\n", GTK_MAJOR_VERSION, GTK_MINOR_VERSION);
1389                 log_printf("!!!   running with GTK+-%d.%d\n", gtk_major_version, gtk_minor_version);
1390                 log_printf("!!! %s may quit unexpectedly with a relocation error.\n", GQ_APPNAME);
1391                 }
1392
1393         DEBUG_1("%s main: pixbuf_inline_register_stock_icons", get_exec_time());
1394         gtk_icon_theme_add_resource_path(gtk_icon_theme_get_default(), GQ_RESOURCE_PATH_ICONS);
1395         pixbuf_inline_register_stock_icons();
1396
1397         DEBUG_1("%s main: setting default options before commandline handling", get_exec_time());
1398         options = init_options(nullptr);
1399         setup_default_options(options);
1400         if (disable_clutter)
1401                 {
1402                 options->disable_gpu = TRUE;
1403                 }
1404
1405         /* Generate a unique identifier used by the open archive function */
1406         instance_identifier = g_strdup_printf("%x", g_random_int());
1407
1408         DEBUG_1("%s main: mkdir_if_not_exists", get_exec_time());
1409         /* these functions don't depend on config file */
1410         mkdir_if_not_exists(get_rc_dir());
1411         mkdir_if_not_exists(get_collections_dir());
1412         mkdir_if_not_exists(get_thumbnails_cache_dir());
1413         mkdir_if_not_exists(get_metadata_cache_dir());
1414         mkdir_if_not_exists(get_window_layouts_dir());
1415
1416         setup_env_path();
1417
1418         screen = gdk_screen_get_default();
1419         provider = gtk_css_provider_new();
1420         gtk_css_provider_load_from_resource(provider, GQ_RESOURCE_PATH_UI "/custom.css");
1421         gtk_style_context_add_provider_for_screen(screen, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
1422
1423         if (parse_command_line_for_cache_maintenance_option(argc, argv))
1424                 {
1425                 process_command_line_for_cache_maintenance_option(argc, argv);
1426                 }
1427         else
1428                 {
1429                 DEBUG_1("%s main: parse_command_line", get_exec_time());
1430                 parse_command_line(argc, argv);
1431
1432                 keys_load();
1433                 accel_map_load();
1434
1435                 /* restore session from the config file */
1436
1437
1438                 DEBUG_1("%s main: load_options", get_exec_time());
1439                 if (!load_options(options))
1440                         {
1441                         /* load_options calls these functions after it parses global options, we have to call it here if it fails */
1442                         filter_add_defaults();
1443                         filter_rebuild();
1444                         }
1445
1446         #if HAVE_CLUTTER
1447         /** @FIXME For the background of this see:
1448          * https://github.com/BestImageViewer/geeqie/issues/397
1449          * The feature CLUTTER_FEATURE_SWAP_EVENTS indictates if the
1450          * system is liable to exhibit this problem.
1451          * The user is provided with an override in Preferences/Behavior
1452          */
1453                 if (!options->override_disable_gpu && !options->disable_gpu)
1454                         {
1455                         DEBUG_1("CLUTTER_FEATURE_SWAP_EVENTS %d",clutter_feature_available(CLUTTER_FEATURE_SWAP_EVENTS));
1456                         if (clutter_feature_available(CLUTTER_FEATURE_SWAP_EVENTS) != 0)
1457                                 {
1458                                 options->disable_gpu = TRUE;
1459                                 }
1460                         }
1461         #endif
1462
1463                 /* handle missing config file and commandline additions*/
1464                 if (!layout_window_list)
1465                         {
1466                         /* broken or no config file or no <layout> section */
1467                         layout_new_from_default();
1468                         }
1469
1470                 layout_editors_reload_start();
1471
1472                 /* If no --list option, open a separate collection window for each
1473                  * .gqv file on the command line
1474                  */
1475                 if (command_line->collection_list && !command_line->startup_command_line_collection)
1476                         {
1477                         GList *work;
1478
1479                         work = command_line->collection_list;
1480                         while (work)
1481                                 {
1482                                 CollectWindow *cw;
1483                                 const gchar *path;
1484
1485                                 path = static_cast<const gchar *>(work->data);
1486                                 work = work->next;
1487
1488                                 cw = collection_window_new(path);
1489                                 if (!first_collection && cw) first_collection = cw->cd;
1490                                 }
1491                         }
1492
1493                 if (command_line->log_file)
1494                         {
1495                         gchar *pathl;
1496                         gchar *path = g_strdup(command_line->log_file);
1497
1498                         pathl = path_from_utf8(path);
1499                         command_line->ssi = secure_open(pathl);
1500                         }
1501
1502                 /* If there is a files list on the command line and no --list option,
1503                  * check if they are all in the same folder
1504                  */
1505                 if (command_line->cmd_list && !(command_line->startup_command_line_collection))
1506                         {
1507                         GList *work;
1508                         gchar *path = nullptr;
1509
1510                         work = command_line->cmd_list;
1511
1512                         while (work && single_dir)
1513                                 {
1514                                 gchar *dirname;
1515
1516                                 dirname = g_path_get_dirname(static_cast<const gchar *>(work->data));
1517                                 if (!path)
1518                                         {
1519                                         path = g_strdup(dirname);
1520                                         }
1521                                 else
1522                                         {
1523                                         if (g_strcmp0(path, dirname) != 0)
1524                                                 {
1525                                                 single_dir = FALSE;
1526                                                 }
1527                                         }
1528                                 g_free(dirname);
1529                                 work = work->next;
1530                                 }
1531                         g_free(path);
1532                         }
1533
1534                 /* Files from multiple folders, or --list option given
1535                  * then open an unnamed collection and insert all files
1536                  */
1537                 if ((command_line->cmd_list && !single_dir) || (command_line->startup_command_line_collection && command_line->cmd_list))
1538                         {
1539                         GList *work;
1540                         CollectWindow *cw;
1541
1542                         cw = collection_window_new(nullptr);
1543                         cd = cw->cd;
1544
1545                         collection_path_changed(cd);
1546
1547                         work = command_line->cmd_list;
1548                         while (work)
1549                                 {
1550                                 FileData *fd;
1551
1552                                 fd = file_data_new_simple(static_cast<const gchar *>(work->data));
1553                                 collection_add(cd, fd, FALSE);
1554                                 file_data_unref(fd);
1555                                 work = work->next;
1556                                 }
1557
1558                         work = command_line->collection_list;
1559                         while (work)
1560                                 {
1561                                 collection_load(cd, static_cast<gchar *>(work->data), COLLECTION_LOAD_APPEND);
1562                                 work = work->next;
1563                                 }
1564
1565                         if (cd->list) layout_image_set_collection(nullptr, cd, static_cast<CollectInfo *>(cd->list->data));
1566
1567                         /* mem leak, we never unref this collection when !startup_command_line_collection
1568                          * (the image view of the main window does not hold a ref to the collection)
1569                          * this is sort of unavoidable, for if it did hold a ref, next/back
1570                          * may not work as expected when closing collection windows.
1571                          *
1572                          * collection_unref(cd);
1573                          */
1574
1575                         }
1576                 else if (first_collection)
1577                         {
1578                         layout_image_set_collection(nullptr, first_collection,
1579                                                     collection_get_first(first_collection));
1580                         }
1581
1582                 /* If the files on the command line are from one folder, select those files
1583                  * unless it is a command line collection - then leave focus on collection window
1584                  */
1585                 lw = nullptr;
1586                 layout_valid(&lw);
1587
1588                 if (single_dir && command_line->cmd_list && !command_line->startup_command_line_collection)
1589                         {
1590                         GList *work;
1591                         GList *selected;
1592                         FileData *fd;
1593
1594                         selected = nullptr;
1595                         work = command_line->cmd_list;
1596                         while (work)
1597                                 {
1598                                 fd = file_data_new_simple(static_cast<gchar *>(work->data));
1599                                 selected = g_list_append(selected, fd);
1600                                 file_data_unref(fd);
1601                                 work = work->next;
1602                                 }
1603                         layout_select_list(lw, selected);
1604                         }
1605
1606                 buf = g_build_filename(get_rc_dir(), ".command", NULL);
1607                 remote_connection = remote_server_init(buf, cd);
1608                 g_free(buf);
1609
1610                 marks_load();
1611
1612                 default_settings = gtk_settings_get_default();
1613                 g_signal_connect(default_settings, "notify::gtk-theme-name", G_CALLBACK(theme_change_cb), NULL);
1614                 set_theme_bg_color();
1615                 }
1616
1617         /* Show a fade-out notification window if the server has a newer AppImage version */
1618         if (options->appimage_notifications)
1619                 {
1620                 if (g_getenv("APPDIR") && strstr(g_getenv("APPDIR"), "/tmp/.mount_Geeqie"))
1621                         {
1622                         appimage_notification();
1623                         }
1624                 else if (g_strstr_len(gq_executable_path, -1, "AppRun"))
1625                         {
1626                         /* Probably running an extracted AppImage */
1627                         appimage_notification();
1628                         }
1629                 }
1630
1631         DEBUG_1("%s main: gtk_main", get_exec_time());
1632         gtk_main();
1633
1634         gdk_threads_leave();
1635         return 0;
1636 }
1637 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */