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