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