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