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