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