a70b7fa068621a64398243c5b948becfe5f2265c
[geeqie.git] / src / main.c
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 <gdk/gdkkeysyms.h> /* for keyboard values */
23
24 #include <signal.h>
25 #include <sys/mman.h>
26
27 #include <math.h>
28 #ifdef G_OS_UNIX
29 #include <pwd.h>
30 #endif
31 #include <locale.h>
32
33 #include "main.h"
34
35 #include "cache.h"
36 #include "collect.h"
37 #include "collect-io.h"
38 #include "filedata.h"
39 #include "filefilter.h"
40 #include "history_list.h"
41 #include "image-overlay.h"
42 #include "layout.h"
43 #include "layout_image.h"
44 #include "layout_util.h"
45 #include "options.h"
46 #include "remote.h"
47 #include "secure_save.h"
48 #include "similar.h"
49 #include "ui_fileops.h"
50 #include "ui_utildlg.h"
51 #include "cache_maint.h"
52 #include "thumb.h"
53 #include "metadata.h"
54 #include "editors.h"
55 #include "exif.h"
56 #include "histogram.h"
57 #include "pixbuf_util.h"
58 #include "glua.h"
59
60 #ifdef HAVE_CLUTTER
61 #include <clutter-gtk/clutter-gtk.h>
62 #endif
63
64 #ifdef HAVE_GTHREAD
65 /** @FIXME see below */
66 #include <X11/Xlib.h>
67 #endif
68
69 gboolean thumb_format_changed = FALSE;
70 static RemoteConnection *remote_connection = NULL;
71
72 gchar *gq_prefix;
73 gchar *gq_localedir;
74 gchar *gq_helpdir;
75 gchar *gq_htmldir;
76 gchar *gq_app_dir;
77 gchar *gq_bin_dir;
78 gchar *desktop_file_template;
79
80 /*
81  *-----------------------------------------------------------------------------
82  * keyboard functions
83  *-----------------------------------------------------------------------------
84  */
85
86 void keyboard_scroll_calc(gint *x, gint *y, GdkEventKey *event)
87 {
88         static gint delta = 0;
89         static guint32 time_old = 0;
90         static guint keyval_old = 0;
91
92         if (event->state & GDK_CONTROL_MASK)
93                 {
94                 if (*x < 0) *x = G_MININT / 2;
95                 if (*x > 0) *x = G_MAXINT / 2;
96                 if (*y < 0) *y = G_MININT / 2;
97                 if (*y > 0) *y = G_MAXINT / 2;
98
99                 return;
100                 }
101
102         if (options->progressive_key_scrolling)
103                 {
104                 guint32 time_diff;
105
106                 time_diff = event->time - time_old;
107
108                 /* key pressed within 125ms ? (1/8 second) */
109                 if (time_diff > 125 || event->keyval != keyval_old) delta = 0;
110
111                 time_old = event->time;
112                 keyval_old = event->keyval;
113
114                 delta += 2;
115                 }
116         else
117                 {
118                 delta = 8;
119                 }
120
121         *x = *x * delta * options->keyboard_scroll_step;
122         *y = *y * delta * options->keyboard_scroll_step;
123 }
124
125
126
127 /*
128  *-----------------------------------------------------------------------------
129  * command line parser (private) hehe, who needs popt anyway?
130  *-----------------------------------------------------------------------------
131  */
132
133 static void parse_command_line_add_file(const gchar *file_path, gchar **path, gchar **file,
134                                         GList **list, GList **collection_list)
135 {
136         gchar *path_parsed;
137
138         path_parsed = g_strdup(file_path);
139         parse_out_relatives(path_parsed);
140
141         if (file_extension_match(path_parsed, GQ_COLLECTION_EXT))
142                 {
143                 *collection_list = g_list_append(*collection_list, path_parsed);
144                 }
145         else
146                 {
147                 if (!*path) *path = remove_level_from_path(path_parsed);
148                 if (!*file) *file = g_strdup(path_parsed);
149                 *list = g_list_prepend(*list, path_parsed);
150                 }
151 }
152
153 static void parse_command_line_add_dir(const gchar *dir, gchar **path, gchar **file,
154                                        GList **list)
155 {
156 #if 0
157         /* This is broken because file filter is not initialized yet.
158         */
159         GList *files;
160         gchar *path_parsed;
161         FileData *dir_fd;
162
163         path_parsed = g_strdup(dir);
164         parse_out_relatives(path_parsed);
165         dir_fd = file_data_new_dir(path_parsed);
166
167
168         if (filelist_read(dir_fd, &files, NULL))
169                 {
170                 GList *work;
171
172                 files = filelist_filter(files, FALSE);
173                 files = filelist_sort_path(files);
174
175                 work = files;
176                 while (work)
177                         {
178                         FileData *fd = work->data;
179                         if (!*path) *path = remove_level_from_path(fd->path);
180                         if (!*file) *file = g_strdup(fd->path);
181                         *list = g_list_prepend(*list, fd);
182
183                         work = work->next;
184                         }
185
186                 g_list_free(files);
187                 }
188
189         g_free(path_parsed);
190         file_data_unref(dir_fd);
191 #else
192         DEBUG_1("multiple directories specified, ignoring: %s", dir);
193 #endif
194 }
195
196 static void parse_command_line_process_dir(const gchar *dir, gchar **path, gchar **file,
197                                            GList **list, gchar **first_dir)
198 {
199
200         if (!*list && !*first_dir)
201                 {
202                 *first_dir = g_strdup(dir);
203                 }
204         else
205                 {
206                 if (*first_dir)
207                         {
208                         parse_command_line_add_dir(*first_dir, path, file, list);
209                         g_free(*first_dir);
210                         *first_dir = NULL;
211                         }
212                 parse_command_line_add_dir(dir, path, file, list);
213                 }
214 }
215
216 static void parse_command_line_process_file(const gchar *file_path, gchar **path, gchar **file,
217                                             GList **list, GList **collection_list, gchar **first_dir)
218 {
219
220         if (*first_dir)
221                 {
222                 parse_command_line_add_dir(*first_dir, path, file, list);
223                 g_free(*first_dir);
224                 *first_dir = NULL;
225                 }
226         parse_command_line_add_file(file_path, path, file, list, collection_list);
227 }
228
229 static void parse_command_line(gint argc, gchar *argv[])
230 {
231         GList *list = NULL;
232         GList *remote_list = NULL;
233         GList *remote_errors = NULL;
234         gboolean remote_do = FALSE;
235         gchar *first_dir = NULL;
236         gchar *app_lock;
237         gchar *pwd;
238         gchar *current_dir;
239         gchar *geometry = NULL;
240         GtkWidget *dialog_warning;
241         GString *command_line_errors = g_string_new(NULL);
242
243         command_line = g_new0(CommandLine, 1);
244
245         command_line->argc = argc;
246         command_line->argv = argv;
247         command_line->regexp = NULL;
248
249         if (argc > 1)
250                 {
251                 gint i;
252                 gchar *base_dir = get_current_dir();
253                 i = 1;
254                 while (i < argc)
255                         {
256                         gchar *cmd_line = path_to_utf8(argv[i]);
257                         gchar *cmd_all = g_build_filename(base_dir, cmd_line, NULL);
258
259                         if (cmd_line[0] == G_DIR_SEPARATOR && isdir(cmd_line))
260                                 {
261                                 parse_command_line_process_dir(cmd_line, &command_line->path, &command_line->file, &list, &first_dir);
262                                 }
263                         else if (isdir(cmd_all))
264                                 {
265                                 parse_command_line_process_dir(cmd_all, &command_line->path, &command_line->file, &list, &first_dir);
266                                 }
267                         else if (cmd_line[0] == G_DIR_SEPARATOR && isfile(cmd_line))
268                                 {
269                                 parse_command_line_process_file(cmd_line, &command_line->path, &command_line->file,
270                                                                 &list, &command_line->collection_list, &first_dir);
271                                 }
272                         else if (isfile(cmd_all))
273                                 {
274                                 parse_command_line_process_file(cmd_all, &command_line->path, &command_line->file,
275                                                                 &list, &command_line->collection_list, &first_dir);
276                                 }
277                         else if (download_web_file(cmd_line, FALSE, NULL))
278                                 {
279                                 }
280                         else if (is_collection(cmd_line))
281                                 {
282                                 gchar *path = NULL;
283
284                                 path = collection_path(cmd_line);
285                                 parse_command_line_process_file(path, &command_line->path, &command_line->file,
286                                                                 &list, &command_line->collection_list, &first_dir);
287                                 g_free(path);
288                                 }
289                         else if (strncmp(cmd_line, "--debug", 7) == 0 && (cmd_line[7] == '\0' || cmd_line[7] == '='))
290                                 {
291                                 /* do nothing but do not produce warnings */
292                                 }
293                         else if (strncmp(cmd_line, "--disable-clutter", 17) == 0 && (cmd_line[17] == '\0'))
294                                 {
295                                 /* do nothing but do not produce warnings */
296                                 }
297                         else if (strcmp(cmd_line, "+t") == 0 ||
298                                  strcmp(cmd_line, "--with-tools") == 0)
299                                 {
300                                 command_line->tools_show = TRUE;
301
302                                 remote_list = g_list_append(remote_list, "+t");
303                                 }
304                         else if (strcmp(cmd_line, "-t") == 0 ||
305                                  strcmp(cmd_line, "--without-tools") == 0)
306                                 {
307                                 command_line->tools_hide = TRUE;
308
309                                 remote_list = g_list_append(remote_list, "-t");
310                                 }
311                         else if (strcmp(cmd_line, "-f") == 0 ||
312                                  strcmp(cmd_line, "--fullscreen") == 0)
313                                 {
314                                 command_line->startup_full_screen = TRUE;
315                                 }
316                         else if (strcmp(cmd_line, "-s") == 0 ||
317                                  strcmp(cmd_line, "--slideshow") == 0)
318                                 {
319                                 command_line->startup_in_slideshow = TRUE;
320                                 }
321                         else if (strcmp(cmd_line, "-l") == 0 ||
322                                  strcmp(cmd_line, "--list") == 0)
323                                 {
324                                 command_line->startup_command_line_collection = TRUE;
325                                 }
326                         else if (strncmp(cmd_line, "--geometry=", 11) == 0)
327                                 {
328                                 if (!command_line->geometry) command_line->geometry = g_strdup(cmd_line + 11);
329                                 }
330                         else if (strcmp(cmd_line, "-r") == 0 ||
331                                  strcmp(cmd_line, "--remote") == 0)
332                                 {
333                                 if (!remote_do)
334                                         {
335                                         remote_do = TRUE;
336                                         remote_list = remote_build_list(remote_list, argc - i, &argv[i], &remote_errors);
337                                         }
338                                 }
339                         else if ((strcmp(cmd_line, "+w") == 0) ||
340                                                 strcmp(cmd_line, "--show-log-window") == 0)
341                                 {
342                                 command_line->log_window_show = TRUE;
343                                 }
344                         else if (strncmp(cmd_line, "-o:", 3) == 0)
345                                 {
346                                 command_line->log_file = g_strdup(cmd_line + 3);
347                                 }
348                         else if (strncmp(cmd_line, "--log-file:", 11) == 0)
349                                 {
350                                 command_line->log_file = g_strdup(cmd_line + 11);
351                                 }
352                         else if (strncmp(cmd_line, "-g:", 3) == 0)
353                                 {
354                                 set_regexp(g_strdup(cmd_line+3));
355                                 }
356                         else if (strncmp(cmd_line, "-grep:", 6) == 0)
357                                 {
358                                 set_regexp(g_strdup(cmd_line+3));
359                                 }
360                         else if (strncmp(cmd_line, "-n", 2) == 0)
361                                 {
362                                 command_line->new_instance = TRUE;
363                                 }
364                         else if (strncmp(cmd_line, "--new-instance", 14) == 0)
365                                 {
366                                 command_line->new_instance = TRUE;
367                                 }
368                         else if (strcmp(cmd_line, "-rh") == 0 ||
369                                  strcmp(cmd_line, "--remote-help") == 0)
370                                 {
371                                 remote_help();
372                                 exit(0);
373                                 }
374                         else if (strcmp(cmd_line, "--blank") == 0)
375                                 {
376                                 command_line->startup_blank = TRUE;
377                                 }
378                         else if (strcmp(cmd_line, "-v") == 0 ||
379                                  strcmp(cmd_line, "--version") == 0)
380                                 {
381                                 printf_term(FALSE, "%s %s GTK%d\n", GQ_APPNAME, VERSION, gtk_major_version);
382                                 exit(0);
383                                 }
384                         else if (strcmp(cmd_line, "--alternate") == 0)
385                                 {
386                                 /* enable faster experimental algorithm */
387                                 log_printf("Alternate similarity algorithm enabled\n");
388                                 image_sim_alternate_set(TRUE);
389                                 }
390                         else if (strcmp(cmd_line, "-h") == 0 ||
391                                  strcmp(cmd_line, "--help") == 0)
392                                 {
393                                 printf_term(FALSE, "%s %s\n", GQ_APPNAME, VERSION);
394                                 printf_term(FALSE, _("Usage: %s [options] [path]\n\n"), GQ_APPNAME_LC);
395                                 print_term(FALSE, _("valid options are:\n"));
396                                 print_term(FALSE, _("  +t, --with-tools                 force show of tools\n"));
397                                 print_term(FALSE, _("  -t, --without-tools              force hide of tools\n"));
398                                 print_term(FALSE, _("  -f, --fullscreen                 start in full screen mode\n"));
399                                 print_term(FALSE, _("  -s, --slideshow                  start in slideshow mode\n"));
400                                 print_term(FALSE, _("  -l, --list [files] [collections] open collection window for command line\n"));
401                                 print_term(FALSE, _("      --blank                      start with blank file list\n"));
402                                 print_term(FALSE, _("      --geometry=XxY+XOFF+YOFF     set main window location\n"));
403                                 print_term(FALSE, _("  -n, --new-instance               open a new instance of Geeqie\n"));
404                                 print_term(FALSE, _("  -r, --remote                     send following commands to open window\n"));
405                                 print_term(FALSE, _("  -rh,--remote-help                print remote command list\n"));
406 #ifdef DEBUG
407                                 print_term(FALSE, _("      --debug[=level]              turn on debug output\n"));
408                                 print_term(FALSE, _("  -g:<regexp>, --grep:<regexp>     filter debug output\n"));
409 #endif
410                                 print_term(FALSE, _("  +w, --show-log-window            show log window\n"));
411                                 print_term(FALSE, _("  -o:<file>, --log-file:<file>     save log data to file\n"));
412                                 print_term(FALSE, _("  -v, --version                    print version info\n"));
413                                 print_term(FALSE, _("  -h, --help                       show this message\n"));
414                                 print_term(FALSE, _("      --disable-clutter            disable use of Clutter library (i.e. GPU accel.)\n\n"));
415
416 #if 0
417                                 /* these options are not officially supported!
418                                  * only for testing new features, no need to translate them */
419                                 print_term(FALSE, "  --alternate                use alternate similarity algorithm\n");
420 #endif
421
422
423                                 exit(0);
424                                 }
425                         else if (!remote_do)
426                                 {
427                                 command_line_errors = g_string_append(command_line_errors, cmd_line);
428                                 command_line_errors = g_string_append(command_line_errors, "\n");
429                                 }
430
431                         g_free(cmd_all);
432                         g_free(cmd_line);
433                         i++;
434                         }
435
436                 if (command_line_errors->len > 0)
437                         {
438                         dialog_warning = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", "Invalid parameter(s):");
439                         gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog_warning), "%s", command_line_errors->str);
440                         gtk_window_set_title(GTK_WINDOW(dialog_warning), GQ_APPNAME);
441                         gtk_window_set_keep_above(GTK_WINDOW(dialog_warning), TRUE);
442                         gtk_dialog_run(GTK_DIALOG(dialog_warning));
443                         gtk_widget_destroy(dialog_warning);
444                         g_string_free(command_line_errors, TRUE);
445
446                         exit(EXIT_FAILURE);
447                         }
448
449                 g_free(base_dir);
450                 parse_out_relatives(command_line->path);
451                 parse_out_relatives(command_line->file);
452                 }
453
454         list = g_list_reverse(list);
455
456         if (!command_line->path && first_dir)
457                 {
458                 command_line->path = first_dir;
459                 first_dir = NULL;
460
461                 parse_out_relatives(command_line->path);
462                 }
463         g_free(first_dir);
464
465         if (!command_line->new_instance)
466                 {
467                 /* If Geeqie is already running, prevent a second instance
468                  * from being started. Open a new window instead.
469                  */
470                 app_lock = g_build_filename(get_rc_dir(), ".command", NULL);
471                 if (remote_server_exists(app_lock) && !remote_do)
472                         {
473                         remote_do = TRUE;
474                         if (command_line->geometry)
475                                 {
476                                 geometry = g_strdup_printf("--geometry=%s", command_line->geometry);
477                                 remote_list = g_list_prepend(remote_list, geometry);
478                                 }
479                         remote_list = g_list_prepend(remote_list, "--new-window");
480                         }
481                 g_free(app_lock);
482                 }
483
484         if (remote_do)
485                 {
486                 if (remote_errors)
487                         {
488                         GList *work = remote_errors;
489
490                         while (work)
491                                 {
492                                 gchar *opt = work->data;
493
494                                 command_line_errors = g_string_append(command_line_errors, opt);
495                                 command_line_errors = g_string_append(command_line_errors, "\n");
496                                 work = work->next;
497                                 }
498
499                         dialog_warning = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", "Invalid parameter(s):");
500                         gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog_warning), "%s", command_line_errors->str);
501                         gtk_window_set_title(GTK_WINDOW(dialog_warning), GQ_APPNAME);
502                         gtk_window_set_keep_above(GTK_WINDOW(dialog_warning), TRUE);
503                         gtk_dialog_run(GTK_DIALOG(dialog_warning));
504                         gtk_widget_destroy(dialog_warning);
505                         g_string_free(command_line_errors, TRUE);
506
507                         exit(EXIT_FAILURE);
508                         }
509
510                 /* prepend the current dir the remote command was made from,
511                  * for use by any remote command that needs it
512                  */
513                 current_dir = g_get_current_dir();
514                 pwd = g_strconcat("--PWD:", current_dir, NULL);
515                 remote_list = g_list_prepend(remote_list, pwd);
516
517                 remote_control(argv[0], remote_list, command_line->path, list, command_line->collection_list);
518                 /* There is no return to this point
519                  */
520                 g_free(pwd);
521                 g_free(current_dir);
522                 }
523         g_free(geometry);
524         g_list_free(remote_list);
525
526         if (list && list->next)
527                 {
528                 command_line->cmd_list = list;
529                 }
530         else
531                 {
532                 string_list_free(list);
533                 command_line->cmd_list = NULL;
534                 }
535
536         if (command_line->startup_blank)
537                 {
538                 g_free(command_line->path);
539                 command_line->path = NULL;
540                 g_free(command_line->file);
541                 command_line->file = NULL;
542                 filelist_free(command_line->cmd_list);
543                 command_line->cmd_list = NULL;
544                 string_list_free(command_line->collection_list);
545                 command_line->collection_list = NULL;
546                 }
547 }
548
549 static void parse_command_line_for_debug_option(gint argc, gchar *argv[])
550 {
551 #ifdef DEBUG
552         const gchar *debug_option = "--debug";
553         gint len = strlen(debug_option);
554
555         if (argc > 1)
556                 {
557                 gint i;
558
559                 for (i = 1; i < argc; i++)
560                         {
561                         const gchar *cmd_line = argv[i];
562                         if (strncmp(cmd_line, debug_option, len) == 0)
563                                 {
564                                 gint cmd_line_len = strlen(cmd_line);
565
566                                 /* we now increment the debug state for verbosity */
567                                 if (cmd_line_len == len)
568                                         debug_level_add(1);
569                                 else if (cmd_line[len] == '=' && g_ascii_isdigit(cmd_line[len+1]))
570                                         {
571                                         gint n = atoi(cmd_line + len + 1);
572                                         if (n < 0) n = 1;
573                                         debug_level_add(n);
574                                         }
575                                 }
576                         }
577                 }
578
579         DEBUG_1("debugging output enabled (level %d)", get_debug_level());
580 #endif
581 }
582
583 #ifdef HAVE_CLUTTER
584 static gboolean parse_command_line_for_clutter_option(gint argc, gchar *argv[])
585 {
586         const gchar *clutter_option = "--disable-clutter";
587         gint len = strlen(clutter_option);
588         gboolean ret = FALSE;
589
590         if (argc > 1)
591                 {
592                 gint i;
593
594                 for (i = 1; i < argc; i++)
595                         {
596                         const gchar *cmd_line = argv[i];
597                         if (strncmp(cmd_line, clutter_option, len) == 0)
598                                 {
599                                 ret = TRUE;
600                                 }
601                         }
602                 }
603
604         return ret;
605 }
606 #endif
607
608 /*
609  *-----------------------------------------------------------------------------
610  * startup, init, and exit
611  *-----------------------------------------------------------------------------
612  */
613
614 #define RC_HISTORY_NAME "history"
615 #define RC_MARKS_NAME "marks"
616
617 static void setup_env_path(void)
618 {
619         const gchar *old_path = g_getenv("PATH");
620         gchar *path = g_strconcat(gq_bin_dir, ":", old_path, NULL);
621         g_setenv("PATH", path, TRUE);
622         g_free(path);
623 }
624
625 static void keys_load(void)
626 {
627         gchar *path;
628
629         path = g_build_filename(get_rc_dir(), RC_HISTORY_NAME, NULL);
630         history_list_load(path);
631         g_free(path);
632 }
633
634 static void keys_save(void)
635 {
636         gchar *path;
637
638         path = g_build_filename(get_rc_dir(), RC_HISTORY_NAME, NULL);
639         history_list_save(path);
640         g_free(path);
641 }
642
643 static void marks_load(void)
644 {
645         gchar *path;
646
647         path = g_build_filename(get_rc_dir(), RC_MARKS_NAME, NULL);
648         marks_list_load(path);
649         g_free(path);
650 }
651
652 static void marks_save(gboolean save)
653 {
654         gchar *path;
655
656         path = g_build_filename(get_rc_dir(), RC_MARKS_NAME, NULL);
657         marks_list_save(path, save);
658         g_free(path);
659 }
660
661 static void mkdir_if_not_exists(const gchar *path)
662 {
663         if (isdir(path)) return;
664
665         log_printf(_("Creating %s dir:%s\n"), GQ_APPNAME, path);
666
667         if (!recursive_mkdir_if_not_exists(path, 0755))
668                 {
669                 log_printf(_("Could not create dir:%s\n"), path);
670                 }
671 }
672
673
674 /* We add to duplicate and modify  gtk_accel_map_print() and gtk_accel_map_save()
675  * to improve the reliability in special cases (especially when disk is full)
676  * These functions are now using secure saving stuff.
677  */
678 static void gq_accel_map_print(
679                     gpointer    data,
680                     const gchar *accel_path,
681                     guint       accel_key,
682                     GdkModifierType accel_mods,
683                     gboolean    changed)
684 {
685         GString *gstring = g_string_new(changed ? NULL : "; ");
686         SecureSaveInfo *ssi = data;
687         gchar *tmp, *name;
688
689         g_string_append(gstring, "(gtk_accel_path \"");
690
691         tmp = g_strescape(accel_path, NULL);
692         g_string_append(gstring, tmp);
693         g_free(tmp);
694
695         g_string_append(gstring, "\" \"");
696
697         name = gtk_accelerator_name(accel_key, accel_mods);
698         tmp = g_strescape(name, NULL);
699         g_free(name);
700         g_string_append(gstring, tmp);
701         g_free(tmp);
702
703         g_string_append(gstring, "\")\n");
704
705         secure_fwrite(gstring->str, sizeof(*gstring->str), gstring->len, ssi);
706
707         g_string_free(gstring, TRUE);
708 }
709
710 static gboolean gq_accel_map_save(const gchar *path)
711 {
712         gchar *pathl;
713         SecureSaveInfo *ssi;
714         GString *gstring;
715
716         pathl = path_from_utf8(path);
717         ssi = secure_open(pathl);
718         g_free(pathl);
719         if (!ssi)
720                 {
721                 log_printf(_("error saving file: %s\n"), path);
722                 return FALSE;
723                 }
724
725         gstring = g_string_new("; ");
726         if (g_get_prgname())
727                 g_string_append(gstring, g_get_prgname());
728         g_string_append(gstring, " GtkAccelMap rc-file         -*- scheme -*-\n");
729         g_string_append(gstring, "; this file is an automated accelerator map dump\n");
730         g_string_append(gstring, ";\n");
731
732         secure_fwrite(gstring->str, sizeof(*gstring->str), gstring->len, ssi);
733
734         g_string_free(gstring, TRUE);
735
736         gtk_accel_map_foreach((gpointer) ssi, gq_accel_map_print);
737
738         if (secure_close(ssi))
739                 {
740                 log_printf(_("error saving file: %s\nerror: %s\n"), path,
741                            secsave_strerror(secsave_errno));
742                 return FALSE;
743                 }
744
745         return TRUE;
746 }
747
748 static gchar *accep_map_filename(void)
749 {
750         return g_build_filename(get_rc_dir(), "accels", NULL);
751 }
752
753 static void accel_map_save(void)
754 {
755         gchar *path;
756
757         path = accep_map_filename();
758         gq_accel_map_save(path);
759         g_free(path);
760 }
761
762 static void accel_map_load(void)
763 {
764         gchar *path;
765         gchar *pathl;
766
767         path = accep_map_filename();
768         pathl = path_from_utf8(path);
769         gtk_accel_map_load(pathl);
770         g_free(pathl);
771         g_free(path);
772 }
773
774 static void gtkrc_load(void)
775 {
776         gchar *path;
777         gchar *pathl;
778
779         /* If a gtkrc file exists in the rc directory, add it to the
780          * list of files to be parsed at the end of gtk_init() */
781         path = g_build_filename(get_rc_dir(), "gtkrc", NULL);
782         pathl = path_from_utf8(path);
783         if (access(pathl, R_OK) == 0)
784                 gtk_rc_add_default_file(pathl);
785         g_free(pathl);
786         g_free(path);
787 }
788
789 static void exit_program_final(void)
790 {
791         LayoutWindow *lw = NULL;
792         GList *list;
793         LayoutWindow *tmp_lw;
794
795          /* make sure that external editors are loaded, we would save incomplete configuration otherwise */
796         layout_editors_reload_finish();
797
798         remote_close(remote_connection);
799
800         collect_manager_flush();
801
802         /* Save the named windows */
803         if (layout_window_list && layout_window_list->next)
804                 {
805                 list = layout_window_list;
806                 while (list)
807                         {
808                         tmp_lw = list->data;
809                         if (!g_str_has_prefix(tmp_lw->options.id, "lw"))
810                                 {
811                                 save_layout(list->data);
812                                 }
813                         list = list->next;
814                         }
815                 }
816
817         save_options(options);
818         keys_save();
819         accel_map_save();
820
821         if (layout_valid(&lw))
822                 {
823                 layout_free(lw);
824                 }
825
826         secure_close(command_line->ssi);
827
828         gtk_main_quit();
829 }
830
831 static GenericDialog *exit_dialog = NULL;
832
833 static void exit_confirm_cancel_cb(GenericDialog *gd, gpointer data)
834 {
835         exit_dialog = NULL;
836         generic_dialog_close(gd);
837 }
838
839 static void exit_confirm_exit_cb(GenericDialog *gd, gpointer data)
840 {
841         exit_dialog = NULL;
842         generic_dialog_close(gd);
843         exit_program_final();
844 }
845
846 static gint exit_confirm_dlg(void)
847 {
848         GtkWidget *parent;
849         LayoutWindow *lw;
850         gchar *msg;
851
852         if (exit_dialog)
853                 {
854                 gtk_window_present(GTK_WINDOW(exit_dialog->dialog));
855                 return TRUE;
856                 }
857
858         if (!collection_window_modified_exists()) return FALSE;
859
860         parent = NULL;
861         lw = NULL;
862         if (layout_valid(&lw))
863                 {
864                 parent = lw->window;
865                 }
866
867         msg = g_strdup_printf("%s - %s", GQ_APPNAME, _("exit"));
868         exit_dialog = generic_dialog_new(msg,
869                                 "exit", parent, FALSE,
870                                 exit_confirm_cancel_cb, NULL);
871         g_free(msg);
872         msg = g_strdup_printf(_("Quit %s"), GQ_APPNAME);
873         generic_dialog_add_message(exit_dialog, GTK_STOCK_DIALOG_QUESTION,
874                                    msg, _("Collections have been modified. Quit anyway?"), TRUE);
875         g_free(msg);
876         generic_dialog_add_button(exit_dialog, GTK_STOCK_QUIT, NULL, exit_confirm_exit_cb, TRUE);
877
878         gtk_widget_show(exit_dialog->dialog);
879
880         return TRUE;
881 }
882
883 static void exit_program_write_metadata_cb(gint success, const gchar *dest_path, gpointer data)
884 {
885         if (success) exit_program();
886 }
887
888 void exit_program(void)
889 {
890         layout_image_full_screen_stop(NULL);
891
892         if (metadata_write_queue_confirm(FALSE, exit_program_write_metadata_cb, NULL)) return;
893
894         options->marks_save ? marks_save(TRUE) : marks_save(FALSE);
895
896         if (exit_confirm_dlg()) return;
897
898         exit_program_final();
899 }
900
901 /* This code is supposed to handle situation when a file mmaped by image_loader
902  * or by exif loader is truncated by some other process.
903  * This is probably not completely correct according to posix, because
904  * mmap is not in the list of calls that can be used safely in signal handler,
905  * but anyway, the handler is called in situation when the application would
906  * crash otherwise.
907  * Ideas for improvement are welcome ;)
908  */
909 /** @FIXME this probably needs some better ifdefs. Please report any compilation problems */
910
911 #if defined(SIGBUS) && defined(SA_SIGINFO)
912 static void sigbus_handler_cb(int signum, siginfo_t *info, void *context)
913 {
914         unsigned long pagesize = sysconf(_SC_PAGE_SIZE);
915         DEBUG_1("SIGBUS %p", info->si_addr);
916         mmap((void *)(((unsigned long)info->si_addr / pagesize) * pagesize), pagesize, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
917 }
918 #endif
919
920 static void setup_sigbus_handler(void)
921 {
922 #if defined(SIGBUS) && defined(SA_SIGINFO)
923         struct sigaction sigbus_action;
924         sigfillset(&sigbus_action.sa_mask);
925         sigbus_action.sa_sigaction = sigbus_handler_cb;
926         sigbus_action.sa_flags = SA_SIGINFO;
927
928         sigaction(SIGBUS, &sigbus_action, NULL);
929 #endif
930 }
931
932 /**
933  * @brief Set up the application paths
934  * 
935  * This function is required for use of AppImages. AppImages are
936  * relocatable, and therefore cannot use fixed paths to various components.
937  * These paths were originally #defines created during compilation.
938  * They are now variables, all defined relative to one level above the
939  * directory that the executable is run from.
940  */
941 static void create_application_paths()
942 {
943         gchar buf[1024];
944         gchar *dirname;
945         gchar *basename;
946         gchar *tmp;
947
948         memset(buf, 0, sizeof(buf));
949         if (readlink("/proc/self/exe", buf, sizeof(buf) - 1) < 0)
950                 {
951                 /* There was an error. Perhaps the path does not exist
952                  * or the buffer is not big enough. */
953                 log_printf("Can't get path from /proc/self/exe");
954                 exit(1);
955                 }
956
957         dirname = g_path_get_dirname(buf); // default is /usr/bin/
958         gq_prefix = g_path_get_dirname(dirname);
959
960         gq_localedir = g_build_filename(gq_prefix, "share", "locale", NULL);
961         tmp = g_build_filename(gq_prefix, "share", "doc", NULL);
962         gq_helpdir = g_strconcat(tmp, G_DIR_SEPARATOR_S, "geeqie-", VERSION, NULL);
963         gq_htmldir = g_build_filename(gq_helpdir, "html", NULL);
964         gq_app_dir = g_build_filename(gq_prefix, "share", "geeqie", NULL);
965         gq_bin_dir = g_build_filename(gq_prefix, "lib", "geeqie", NULL);
966         desktop_file_template = g_build_filename(gq_app_dir, "template.desktop", NULL);
967
968         g_free(tmp);
969         g_free(dirname);
970 }
971
972 gint main(gint argc, gchar *argv[])
973 {
974         CollectionData *first_collection = NULL;
975         gchar *buf;
976         CollectionData *cd = NULL;
977         gboolean disable_clutter = FALSE;
978         gboolean single_dir = TRUE;
979         LayoutWindow *lw;
980
981 #ifdef HAVE_GTHREAD
982 #if !GLIB_CHECK_VERSION(2,32,0)
983         g_thread_init(NULL);
984 #endif
985         gdk_threads_init();
986         gdk_threads_enter();
987
988 #endif
989
990         /* init execution time counter (debug only) */
991         init_exec_time();
992
993         create_application_paths();
994
995         /* setup locale, i18n */
996         setlocale(LC_ALL, "");
997
998 #ifdef ENABLE_NLS
999         bindtextdomain(PACKAGE, gq_localedir);
1000         bind_textdomain_codeset(PACKAGE, "UTF-8");
1001         textdomain(PACKAGE);
1002 #endif
1003
1004         exif_init();
1005
1006 #ifdef HAVE_LUA
1007         lua_init();
1008 #endif
1009
1010         /* setup random seed for random slideshow */
1011         srand(time(NULL));
1012
1013         setup_sigbus_handler();
1014
1015         /* register global notify functions */
1016         file_data_register_notify_func(cache_notify_cb, NULL, NOTIFY_PRIORITY_HIGH);
1017         file_data_register_notify_func(thumb_notify_cb, NULL, NOTIFY_PRIORITY_HIGH);
1018         file_data_register_notify_func(histogram_notify_cb, NULL, NOTIFY_PRIORITY_HIGH);
1019         file_data_register_notify_func(collect_manager_notify_cb, NULL, NOTIFY_PRIORITY_LOW);
1020         file_data_register_notify_func(metadata_notify_cb, NULL, NOTIFY_PRIORITY_LOW);
1021
1022
1023         gtkrc_load();
1024
1025         parse_command_line_for_debug_option(argc, argv);
1026         DEBUG_1("%s main: gtk_init", get_exec_time());
1027 #ifdef HAVE_CLUTTER
1028         if (parse_command_line_for_clutter_option(argc, argv))
1029                 {
1030                 disable_clutter = TRUE;
1031                 gtk_init(&argc, &argv);
1032                 }
1033         else
1034                 {
1035                 if (gtk_clutter_init(&argc, &argv) != CLUTTER_INIT_SUCCESS)
1036                         {
1037                         log_printf("Can't initialize clutter-gtk.\nStart Geeqie with the option \"geeqie --disable-clutter\"");
1038                         exit(1);
1039                         }
1040                 }
1041 #else
1042         gtk_init(&argc, &argv);
1043 #endif
1044
1045         if (gtk_major_version < GTK_MAJOR_VERSION ||
1046             (gtk_major_version == GTK_MAJOR_VERSION && gtk_minor_version < GTK_MINOR_VERSION) )
1047                 {
1048                 log_printf("!!! This is a friendly warning.\n");
1049                 log_printf("!!! The version of GTK+ in use now is older than when %s was compiled.\n", GQ_APPNAME);
1050                 log_printf("!!!  compiled with GTK+-%d.%d\n", GTK_MAJOR_VERSION, GTK_MINOR_VERSION);
1051                 log_printf("!!!   running with GTK+-%d.%d\n", gtk_major_version, gtk_minor_version);
1052                 log_printf("!!! %s may quit unexpectedly with a relocation error.\n", GQ_APPNAME);
1053                 }
1054
1055         DEBUG_1("%s main: pixbuf_inline_register_stock_icons", get_exec_time());
1056         pixbuf_inline_register_stock_icons();
1057
1058         DEBUG_1("%s main: setting default options before commandline handling", get_exec_time());
1059         options = init_options(NULL);
1060         setup_default_options(options);
1061         if (disable_clutter)
1062                 {
1063                 options->disable_gpu = TRUE;
1064                 }
1065
1066         DEBUG_1("%s main: parse_command_line", get_exec_time());
1067         parse_command_line(argc, argv);
1068
1069         DEBUG_1("%s main: mkdir_if_not_exists", get_exec_time());
1070         /* these functions don't depend on config file */
1071         mkdir_if_not_exists(get_rc_dir());
1072         mkdir_if_not_exists(get_collections_dir());
1073         mkdir_if_not_exists(get_thumbnails_cache_dir());
1074         mkdir_if_not_exists(get_metadata_cache_dir());
1075         mkdir_if_not_exists(get_window_layouts_dir());
1076
1077         setup_env_path();
1078
1079         keys_load();
1080         accel_map_load();
1081
1082         /* restore session from the config file */
1083
1084
1085         DEBUG_1("%s main: load_options", get_exec_time());
1086         if (!load_options(options))
1087                 {
1088                 /* load_options calls these functions after it parses global options, we have to call it here if it fails */
1089                 filter_add_defaults();
1090                 filter_rebuild();
1091                 }
1092
1093 #ifdef HAVE_CLUTTER
1094 /** @FIXME For the background of this see:
1095  * https://github.com/BestImageViewer/geeqie/issues/397
1096  * The feature CLUTTER_FEATURE_SWAP_EVENTS indictates if the
1097  * system is liable to exhibit this problem.
1098  * The user is provided with an override in Preferences/Behavior
1099  */
1100         if (!options->override_disable_gpu && !options->disable_gpu)
1101                 {
1102                 DEBUG_1("CLUTTER_FEATURE_SWAP_EVENTS %d",clutter_feature_available(CLUTTER_FEATURE_SWAP_EVENTS));
1103                 if (clutter_feature_available(CLUTTER_FEATURE_SWAP_EVENTS) != 0)
1104                         {
1105                         options->disable_gpu = TRUE;
1106                         }
1107                 }
1108 #endif
1109
1110         /* handle missing config file and commandline additions*/
1111         if (!layout_window_list)
1112                 {
1113                 /* broken or no config file */
1114                 layout_new_from_config(NULL, NULL, TRUE);
1115                 }
1116
1117         layout_editors_reload_start();
1118
1119         /* If no --list option, open a separate collection window for each
1120          * .gqv file on the command line
1121          */
1122         if (command_line->collection_list && !command_line->startup_command_line_collection)
1123                 {
1124                 GList *work;
1125
1126                 work = command_line->collection_list;
1127                 while (work)
1128                         {
1129                         CollectWindow *cw;
1130                         const gchar *path;
1131
1132                         path = work->data;
1133                         work = work->next;
1134
1135                         cw = collection_window_new(path);
1136                         if (!first_collection && cw) first_collection = cw->cd;
1137                         }
1138                 }
1139
1140         if (command_line->log_file)
1141                 {
1142                 gchar *pathl;
1143                 gchar *path = g_strdup(command_line->log_file);
1144
1145                 pathl = path_from_utf8(path);
1146                 command_line->ssi = secure_open(pathl);
1147                 }
1148
1149         /* If there is a files list on the command line and no --list option,
1150          * check if they are all in the same folder
1151          */
1152         if (command_line->cmd_list && !(command_line->startup_command_line_collection))
1153                 {
1154                 GList *work;
1155                 gchar *path = NULL;
1156
1157                 work = command_line->cmd_list;
1158
1159                 while (work && single_dir)
1160                         {
1161                         gchar *dirname;
1162
1163                         dirname = g_path_get_dirname(work->data);
1164                         if (!path)
1165                                 {
1166                                 path = g_strdup(dirname);
1167                                 }
1168                         else
1169                                 {
1170                                 if (g_strcmp0(path, dirname) != 0)
1171                                         {
1172                                         single_dir = FALSE;
1173                                         }
1174                                 }
1175                         g_free(dirname);
1176                         work = work->next;
1177                         }
1178                 g_free(path);
1179                 }
1180
1181         /* Files from multiple folders, or --list option given
1182          * then open an unnamed collection and insert all files
1183          */
1184         if ((command_line->cmd_list && !single_dir) || (command_line->startup_command_line_collection && command_line->cmd_list))
1185                 {
1186                 GList *work;
1187                 CollectWindow *cw;
1188
1189                 cw = collection_window_new(NULL);
1190                 cd = cw->cd;
1191
1192                 collection_path_changed(cd);
1193
1194                 work = command_line->cmd_list;
1195                 while (work)
1196                         {
1197                         FileData *fd;
1198
1199                         fd = file_data_new_simple(work->data);
1200                         collection_add(cd, fd, FALSE);
1201                         file_data_unref(fd);
1202                         work = work->next;
1203                         }
1204
1205                 work = command_line->collection_list;
1206                 while (work)
1207                         {
1208                         collection_load(cd, (gchar *)work->data, COLLECTION_LOAD_APPEND);
1209                         work = work->next;
1210                         }
1211
1212                 if (cd->list) layout_image_set_collection(NULL, cd, cd->list->data);
1213
1214                 /* mem leak, we never unref this collection when !startup_command_line_collection
1215                  * (the image view of the main window does not hold a ref to the collection)
1216                  * this is sort of unavoidable, for if it did hold a ref, next/back
1217                  * may not work as expected when closing collection windows.
1218                  *
1219                  * collection_unref(cd);
1220                  */
1221
1222                 }
1223         else if (first_collection)
1224                 {
1225                 layout_image_set_collection(NULL, first_collection,
1226                                             collection_get_first(first_collection));
1227                 }
1228
1229         /* If the files on the command line are from one folder, select those files
1230          * unless it is a command line collection - then leave focus on collection window
1231          */
1232         lw = NULL;
1233         layout_valid(&lw);
1234
1235         if (single_dir && command_line->cmd_list && !command_line->startup_command_line_collection)
1236                 {
1237                 GList *work;
1238                 GList *selected;
1239                 FileData *fd;
1240
1241                 selected = NULL;
1242                 work = command_line->cmd_list;
1243                 while (work)
1244                         {
1245                         fd = file_data_new_simple((gchar *)work->data);
1246                         selected = g_list_append(selected, fd);
1247                         file_data_unref(fd);
1248                         work = work->next;
1249                         }
1250                 layout_select_list(lw, selected);
1251                 }
1252
1253         buf = g_build_filename(get_rc_dir(), ".command", NULL);
1254         remote_connection = remote_server_init(buf, cd);
1255         g_free(buf);
1256
1257         marks_load();
1258
1259         DEBUG_1("%s main: gtk_main", get_exec_time());
1260         gtk_main();
1261 #ifdef HAVE_GTHREAD
1262         gdk_threads_leave();
1263 #endif
1264         return 0;
1265 }
1266 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */