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