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