Drop goto in copy_file()
[geeqie.git] / src / ui-fileops.cc
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 <cstdio>
23 #include <cstdlib>
24 #include <cstring>
25 #include <memory>
26
27 #include <unistd.h>
28 #include <utime.h>
29
30 #include "main.h"
31 #include "ui-fileops.h"
32
33 #include "md5-util.h"
34 #include "filefilter.h"
35 #include "layout.h"
36 #include "utilops.h"
37 #include "secure-save.h"
38
39 /*
40  *-----------------------------------------------------------------------------
41  * generic file information and manipulation routines (public)
42  *-----------------------------------------------------------------------------
43  */
44
45
46
47 void print_term(gboolean err, const gchar *text_utf8)
48 {
49         gchar *text_l;
50
51         text_l = g_locale_from_utf8(text_utf8, -1, nullptr, nullptr, nullptr);
52         if (err)
53                 {
54                 fputs((text_l) ? text_l : text_utf8, stderr);
55                 }
56         else
57                 {
58                 fputs((text_l) ? text_l : text_utf8, stdout);
59                 }
60         if(command_line && command_line->ssi)
61                 secure_fputs(command_line->ssi, (text_l) ? text_l : text_utf8);
62         g_free(text_l);
63 }
64
65 static void encoding_dialog(const gchar *path)
66 {
67         static gboolean warned_user = FALSE;
68         GenericDialog *gd;
69         GString *string;
70         const gchar *lc;
71         const gchar *bf;
72
73         if (warned_user) return;
74         warned_user = TRUE;
75
76         lc = getenv("LANG");
77         bf = getenv("G_BROKEN_FILENAMES");
78
79         string = g_string_new("");
80         g_string_append(string, _("One or more filenames are not encoded with the preferred locale character set.\n"));
81         g_string_append_printf(string, _("Operations on, and display of these files with %s may not succeed.\n"), PACKAGE);
82         g_string_append(string, "\n");
83         g_string_append(string, _("If your filenames are not encoded in utf-8, try setting the environment variable G_BROKEN_FILENAMES=1\n"));
84         if (bf)
85                 g_string_append_printf(string, _("It appears G_BROKEN_FILENAMES is set to %s\n"), bf);
86         else
87                 g_string_append(string, _("It appears G_BROKEN_FILENAMES is not set\n"));
88         g_string_append(string, "\n");
89         g_string_append_printf(string, _("The locale appears to be set to \"%s\"\n(set by the LANG environment variable)\n"), (lc) ? lc : "undefined");
90         if (lc && (strstr(lc, "UTF-8") || strstr(lc, "utf-8")))
91                 {
92                 gchar *name;
93                 name = g_convert(path, -1, "UTF-8", "ISO-8859-1", nullptr, nullptr, nullptr);
94                 string = g_string_append(string, _("\nPreferred encoding appears to be UTF-8, however the file:\n"));
95                 g_string_append_printf(string, "\"%s\"\n", (name) ? name : _("[name not displayable]"));
96
97                 if (g_utf8_validate(path, -1, nullptr))
98                         g_string_append_printf(string, _("\"%s\" is encoded in valid UTF-8."), (name) ? name : _("[name not displayable]"));
99                 else
100                         g_string_append_printf(string, _("\"%s\" is not encoded in valid UTF-8."), (name) ? name : _("[name not displayable]"));
101                 g_string_append(string, "\n");
102                 g_free(name);
103                 }
104
105         gd = generic_dialog_new(_("Filename encoding locale mismatch"),
106                                 "locale warning", nullptr, TRUE, nullptr, nullptr);
107         generic_dialog_add_button(gd, GQ_ICON_CLOSE, _("Close"), nullptr, TRUE);
108
109         generic_dialog_add_message(gd, GQ_ICON_DIALOG_WARNING,
110                                    _("Filename encoding locale mismatch"), string->str, TRUE);
111
112         gtk_widget_show(gd->dialog);
113
114         g_string_free(string, TRUE);
115 }
116
117 #if GQ_DEBUG_PATH_UTF8
118 gchar *path_to_utf8_debug(const gchar *path, const gchar *file, gint line)
119 #else
120 gchar *path_to_utf8(const gchar *path)
121 #endif
122 {
123         gchar *utf8;
124         GError *error = nullptr;
125
126         if (!path) return nullptr;
127
128         utf8 = g_filename_to_utf8(path, -1, nullptr, nullptr, &error);
129         if (error)
130                 {
131 #if GQ_DEBUG_PATH_UTF8
132                 log_printf("%s:%d: Unable to convert filename to UTF-8:\n%s\n%s\n", file, line, path, error->message);
133 #else
134                 log_printf("Unable to convert filename to UTF-8:\n%s\n%s\n", path, error->message);
135 #endif
136                 g_error_free(error);
137                 encoding_dialog(path);
138                 }
139         if (!utf8)
140                 {
141                 /* just let it through, but bad things may happen */
142                 utf8 = g_strdup(path);
143                 }
144
145         return utf8;
146 }
147
148 #if GQ_DEBUG_PATH_UTF8
149 gchar *path_from_utf8_debug(const gchar *utf8, const gchar *file, gint line)
150 #else
151 gchar *path_from_utf8(const gchar *utf8)
152 #endif
153 {
154         gchar *path;
155         GError *error = nullptr;
156
157         if (!utf8) return nullptr;
158
159         path = g_filename_from_utf8(utf8, -1, nullptr, nullptr, &error);
160         if (error)
161                 {
162 #if GQ_DEBUG_PATH_UTF8
163                 log_printf("%s:%d: Unable to convert filename to locale from UTF-8:\n%s\n%s\n", file, line, utf8, error->message);
164 #else
165                 log_printf("Unable to convert filename to locale from UTF-8:\n%s\n%s\n", utf8, error->message);
166 #endif
167                 g_error_free(error);
168                 }
169         if (!path)
170                 {
171                 /* if invalid UTF-8, text probably still in original form, so just copy it */
172                 path = g_strdup(utf8);
173                 }
174
175         return path;
176 }
177
178 /* first we try the HOME environment var, if that doesn't work, we try g_get_homedir(). */
179 const gchar *homedir()
180 {
181         static gchar *home = nullptr;
182
183         if (!home)
184                 home = path_to_utf8(getenv("HOME"));
185
186         if (!home)
187                 home = path_to_utf8(g_get_home_dir());
188
189         DEBUG_1("Home directory: %s", home);
190
191         return home;
192 }
193
194 static gchar *xdg_dir_get(const gchar *key, const gchar *fallback)
195 {
196         gchar *dir = getenv(key);
197
198         if (!dir || dir[0] == '\0')
199                 {
200                 return g_build_filename(homedir(), fallback, NULL);
201                 }
202
203         DEBUG_1("Got xdg %s: %s", key, dir);
204
205         return path_to_utf8(dir);
206 }
207
208 const gchar *xdg_data_home_get()
209 {
210         static const gchar *xdg_data_home = nullptr;
211
212         if (xdg_data_home) return xdg_data_home;
213
214         xdg_data_home = xdg_dir_get("XDG_DATA_HOME", ".local/share");
215
216         return xdg_data_home;
217 }
218
219 const gchar *xdg_config_home_get()
220 {
221         static const gchar *xdg_config_home = nullptr;
222
223         if (xdg_config_home) return xdg_config_home;
224
225         xdg_config_home = xdg_dir_get("XDG_CONFIG_HOME", ".config");
226
227         return xdg_config_home;
228 }
229
230 const gchar *xdg_cache_home_get()
231 {
232         static const gchar *xdg_cache_home = nullptr;
233
234         if (xdg_cache_home) return xdg_cache_home;
235
236         xdg_cache_home = xdg_dir_get("XDG_CACHE_HOME", ".cache");
237
238         return xdg_cache_home;
239 }
240
241 const gchar *get_rc_dir()
242 {
243         static gchar *rc_dir = nullptr;
244
245         if (rc_dir) return rc_dir;
246
247         if (USE_XDG)
248                 {
249                 rc_dir = g_build_filename(xdg_config_home_get(), GQ_APPNAME_LC, NULL);
250                 }
251         else
252                 {
253                 rc_dir = g_build_filename(homedir(), GQ_RC_DIR, NULL);
254                 }
255
256         return rc_dir;
257 }
258
259 const gchar *get_collections_dir()
260 {
261         static gchar *collections_dir = nullptr;
262
263         if (collections_dir) return collections_dir;
264
265         if (USE_XDG)
266                 {
267                 collections_dir = g_build_filename(xdg_data_home_get(), GQ_APPNAME_LC, GQ_COLLECTIONS_DIR, NULL);
268                 }
269         else
270                 {
271                 collections_dir = g_build_filename(get_rc_dir(), GQ_COLLECTIONS_DIR, NULL);
272                 }
273
274         return collections_dir;
275 }
276
277 const gchar *get_trash_dir()
278 {
279         static gchar *trash_dir = nullptr;
280
281         if (trash_dir) return trash_dir;
282
283         if (USE_XDG)
284                 {
285                 trash_dir = g_build_filename(xdg_data_home_get(), GQ_APPNAME_LC, GQ_TRASH_DIR, NULL);
286                 }
287         else
288                 {
289                 trash_dir = g_build_filename(get_rc_dir(), GQ_TRASH_DIR, NULL);
290         }
291
292         return trash_dir;
293 }
294
295 const gchar *get_window_layouts_dir()
296 {
297         static gchar *window_layouts_dir = nullptr;
298
299         if (window_layouts_dir) return window_layouts_dir;
300
301         if (USE_XDG)
302                 {
303                 window_layouts_dir = g_build_filename(xdg_config_home_get(), GQ_APPNAME_LC, GQ_WINDOW_LAYOUTS_DIR, NULL);
304                 }
305         else
306                 {
307                 window_layouts_dir = g_build_filename(get_rc_dir(), GQ_WINDOW_LAYOUTS_DIR, NULL);
308                 }
309
310         return window_layouts_dir;
311 }
312
313 gboolean stat_utf8(const gchar *s, struct stat *st)
314 {
315         gchar *sl;
316         gboolean ret;
317
318         if (!s) return FALSE;
319         sl = path_from_utf8(s);
320         ret = (stat(sl, st) == 0);
321         g_free(sl);
322
323         return ret;
324 }
325
326 gboolean lstat_utf8(const gchar *s, struct stat *st)
327 {
328         gchar *sl;
329         gboolean ret;
330
331         if (!s) return FALSE;
332         sl = path_from_utf8(s);
333         ret = (lstat(sl, st) == 0);
334         g_free(sl);
335
336         return ret;
337 }
338
339 gboolean isname(const gchar *s)
340 {
341         struct stat st;
342
343         return stat_utf8(s, &st);
344 }
345
346 gboolean isfile(const gchar *s)
347 {
348         struct stat st;
349
350         return (stat_utf8(s, &st) && S_ISREG(st.st_mode));
351 }
352
353 gboolean isdir(const gchar *s)
354 {
355         struct stat st;
356
357         return (stat_utf8(s, &st) && S_ISDIR(st.st_mode));
358 }
359
360 gboolean islink(const gchar *s)
361 {
362         struct stat st;
363
364         return (lstat_utf8(s, &st) && S_ISLNK(st.st_mode));
365 }
366
367 gint64 filesize(const gchar *s)
368 {
369         struct stat st;
370
371         if (!stat_utf8(s, &st)) return 0;
372         return st.st_size;
373 }
374
375 time_t filetime(const gchar *s)
376 {
377         struct stat st;
378
379         if (!stat_utf8(s, &st)) return 0;
380         return st.st_mtime;
381 }
382
383 gboolean filetime_set(const gchar *s, time_t tval)
384 {
385         gboolean ret = FALSE;
386
387         if (tval > 0)
388                 {
389                 struct utimbuf ut;
390                 gchar *sl;
391
392                 ut.actime = ut.modtime = tval;
393
394                 sl = path_from_utf8(s);
395                 ret = (utime(sl, &ut) == 0);
396                 g_free(sl);
397                 }
398
399         return ret;
400 }
401
402 gboolean is_readable_file(const gchar *s)
403 {
404         if (!s || !s[0] || !isfile(s)) return FALSE;
405         return access_file(s, R_OK);
406 }
407
408 gboolean access_file(const gchar *s, gint mode)
409 {
410         gchar *sl;
411         gint ret;
412
413         if (!s || !s[0]) return FALSE;
414
415         sl = path_from_utf8(s);
416         ret = (access(sl, mode) == 0);
417         g_free(sl);
418
419         return ret;
420 }
421
422 gboolean unlink_file(const gchar *s)
423 {
424         gchar *sl;
425         gboolean ret;
426
427         if (!s) return FALSE;
428
429         sl = path_from_utf8(s);
430         ret = (unlink(sl) == 0);
431         g_free(sl);
432
433         return ret;
434 }
435
436 #pragma GCC diagnostic push
437 #pragma GCC diagnostic ignored "-Wunused-function"
438 gboolean symlink_utf8_unused(const gchar *source, const gchar *target)
439 {
440         gchar *sl;
441         gchar *tl;
442         gboolean ret;
443
444         if (!source || !target) return FALSE;
445
446         sl = path_from_utf8(source);
447         tl = path_from_utf8(target);
448
449         ret = (symlink(sl, tl) == 0);
450
451         g_free(sl);
452         g_free(tl);
453
454         return ret;
455 }
456 #pragma GCC diagnostic pop
457
458 gboolean mkdir_utf8(const gchar *s, gint mode)
459 {
460         gchar *sl;
461         gboolean ret;
462
463         if (!s) return FALSE;
464
465         sl = path_from_utf8(s);
466         ret = (mkdir(sl, mode) == 0);
467         g_free(sl);
468         return ret;
469 }
470
471 gboolean rmdir_utf8(const gchar *s)
472 {
473         gchar *sl;
474         gboolean ret;
475
476         if (!s) return FALSE;
477
478         sl = path_from_utf8(s);
479         ret = (rmdir(sl) == 0);
480         g_free(sl);
481
482         return ret;
483 }
484
485 gboolean copy_file_attributes(const gchar *s, const gchar *t, gint perms, gint mtime)
486 {
487         struct stat st;
488         gchar *sl, *tl;
489         gboolean ret = FALSE;
490
491         if (!s || !t) return FALSE;
492
493         sl = path_from_utf8(s);
494         tl = path_from_utf8(t);
495
496         if (stat(sl, &st) == 0)
497                 {
498                 struct utimbuf tb;
499
500                 ret = TRUE;
501
502                 /* set the dest file attributes to that of source (ignoring errors) */
503
504                 if (perms)
505                         {
506                         ret = chown(tl, st.st_uid, st.st_gid);
507                         /* Ignores chown errors, while still doing chown
508                            (so root still can copy files preserving ownership) */
509                         ret = TRUE;
510                         if (chmod(tl, st.st_mode) < 0) {
511                             struct stat st2;
512                             if (stat(tl, &st2) != 0 || st2.st_mode != st.st_mode) {
513                                 ret = FALSE;
514                             }
515                         }
516                         }
517
518                 tb.actime = st.st_atime;
519                 tb.modtime = st.st_mtime;
520                 if (mtime && utime(tl, &tb) < 0) ret = FALSE;
521                 }
522
523         g_free(sl);
524         g_free(tl);
525
526         return ret;
527 }
528
529 /* paths are in filesystem encoding */
530 static gboolean hard_linked(const gchar *a, const gchar *b)
531 {
532         struct stat sta;
533         struct stat stb;
534
535         if (stat(a, &sta) !=  0 || stat(b, &stb) != 0) return FALSE;
536
537         return (sta.st_dev == stb.st_dev &&
538                 sta.st_ino == stb.st_ino);
539 }
540
541 static void fclose_safe(FILE *fp)
542 {
543         if (fp) fclose(fp);
544 }
545
546 gboolean copy_file(const gchar *s, const gchar *t)
547 {
548         gchar buf[16384];
549         size_t b;
550         gint fd = -1;
551
552         std::unique_ptr<gchar, decltype(&g_free)> sl{path_from_utf8(s), g_free};
553         std::unique_ptr<gchar, decltype(&g_free)> tl{path_from_utf8(t), g_free};
554
555         if (hard_linked(sl.get(), tl.get()))
556                 {
557                 return TRUE;
558                 }
559
560         /* Do not dereference absolute symlinks, but copy them "as is".
561         * For a relative symlink, we don't know how to properly change it when
562         * copied/moved to another dir to keep pointing it to same target as
563         * a relative symlink, so we turn it into absolute symlink using
564         * realpath() instead. */
565         auto copy_symlink = [](const gchar *sl, const gchar *tl) -> gboolean
566                 {
567                 struct stat st;
568                 if (!lstat_utf8(sl, &st) && S_ISLNK(st.st_mode))
569                         {
570                         return FALSE;
571                         }
572
573                 gchar *link_target;
574                 ssize_t i;
575
576                 link_target = static_cast<gchar *>(g_malloc(st.st_size + 1));
577                 i = readlink(sl, link_target, st.st_size);
578                 if (i<0)
579                         {
580                         g_free(link_target);
581                         return FALSE;  // try a "normal" copy
582                         }
583                 link_target[st.st_size] = '\0';
584
585                 if (link_target[0] != G_DIR_SEPARATOR) // if it is a relative symlink
586                         {
587                         gchar *absolute;
588
589                         const gchar *lastslash = strrchr(sl, G_DIR_SEPARATOR);
590                         gint len = lastslash - sl + 1;
591
592                         absolute = static_cast<gchar *>(g_malloc(len + st.st_size + 1));
593                         strncpy(absolute, sl, len);
594                         strcpy(absolute + len, link_target);
595                         g_free(link_target);
596                         link_target = absolute;
597
598                         gchar *realPath;
599                         realPath = realpath(link_target, nullptr);
600
601                         if (realPath != nullptr) // successfully resolved into an absolute path
602                                 {
603                                 g_free(link_target);
604                                 link_target = g_strdup(realPath);
605                                 g_free(realPath);
606                                 }
607                         else                 // could not get absolute path, got some error instead
608                                 {
609                                 g_free(link_target);
610                                 return FALSE;  // so try a "normal" copy
611                                 }
612                         }
613
614                 if (stat_utf8(tl, &st)) unlink(tl); // first try to remove directory entry in destination directory if such entry exists
615
616                 gint success = (symlink(link_target, tl) == 0);
617                 g_free(link_target);
618
619                 return success;
620                 };
621
622         if (copy_symlink(sl.get(), tl.get()))
623                 {
624                 return TRUE;
625                 }
626
627         // if symlink did not succeed, continue on to try a copy procedure
628         std::unique_ptr<FILE, decltype(&fclose_safe)> fi{fopen(sl.get(), "rb"), fclose_safe};
629         if (!fi)
630                 {
631                 return FALSE;
632                 }
633
634         /* First we write to a temporary file, then we rename it on success,
635            and attributes from original file are copied */
636         std::unique_ptr<gchar, decltype(&g_free)> randname{g_strconcat(tl.get(), ".tmp_XXXXXX", NULL), g_free};
637         if (!randname)
638                 {
639                 return FALSE;
640                 }
641
642         fd = g_mkstemp(randname.get());
643         if (fd == -1)
644                 {
645                 return FALSE;
646                 }
647
648         std::unique_ptr<FILE, decltype(&fclose_safe)> fo{fdopen(fd, "wb"), fclose_safe};
649         if (!fo) {
650                 close(fd);
651                 return FALSE;
652         }
653
654         while ((b = fread(buf, sizeof(gchar), sizeof(buf), fi.get())) && b != 0)
655                 {
656                 if (fwrite(buf, sizeof(gchar), b, fo.get()) != b)
657                         {
658                         unlink(randname.get());
659                         return FALSE;
660                         }
661                 }
662
663         if (rename(randname.get(), tl.get()) < 0) {
664                 unlink(randname.get());
665                 return FALSE;
666         }
667
668         return copy_file_attributes(s, t, TRUE, TRUE);
669 }
670
671 gboolean move_file(const gchar *s, const gchar *t)
672 {
673         gchar *sl, *tl;
674         gboolean ret = TRUE;
675
676         if (!s || !t) return FALSE;
677
678         sl = path_from_utf8(s);
679         tl = path_from_utf8(t);
680         if (rename(sl, tl) < 0)
681                 {
682                 /* this may have failed because moving a file across filesystems
683                 was attempted, so try copy and delete instead */
684                 if (copy_file(s, t))
685                         {
686                         if (unlink(sl) < 0)
687                                 {
688                                 /* err, now we can't delete the source file so return FALSE */
689                                 ret = FALSE;
690                                 }
691                         }
692                 else
693                         {
694                         ret = FALSE;
695                         }
696                 }
697         g_free(sl);
698         g_free(tl);
699
700         return ret;
701 }
702
703 gboolean rename_file(const gchar *s, const gchar *t)
704 {
705         gchar *sl, *tl;
706         gboolean ret;
707
708         if (!s || !t) return FALSE;
709
710         sl = path_from_utf8(s);
711         tl = path_from_utf8(t);
712         ret = (rename(sl, tl) == 0);
713         g_free(sl);
714         g_free(tl);
715
716         return ret;
717 }
718
719 gchar *get_current_dir()
720 {
721         gchar *pathl;
722         gchar *path8;
723
724         pathl = g_get_current_dir();
725         path8 = path_to_utf8(pathl);
726         g_free(pathl);
727
728         return path8;
729 }
730
731 void string_list_free(GList *list)
732 {
733         g_list_free_full(list, g_free);
734 }
735
736 GList *string_list_copy(const GList *list)
737 {
738         GList *new_list = nullptr;
739         auto work = const_cast<GList *>(list);
740
741         while (work)
742                 {
743                 gchar *path;
744
745                 path = static_cast<gchar *>(work->data);
746                 work = work->next;
747
748                 new_list = g_list_prepend(new_list, g_strdup(path));
749                 }
750
751         return g_list_reverse(new_list);
752 }
753
754 gchar *unique_filename(const gchar *path, const gchar *ext, const gchar *divider, gboolean pad)
755 {
756         gchar *unique;
757         gint n = 1;
758
759         if (!ext) ext = "";
760         if (!divider) divider = "";
761
762         unique = g_strconcat(path, ext, NULL);
763         while (isname(unique))
764                 {
765                 g_free(unique);
766                 if (pad)
767                         {
768                         unique = g_strdup_printf("%s%s%03d%s", path, divider, n, ext);
769                         }
770                 else
771                         {
772                         unique = g_strdup_printf("%s%s%d%s", path, divider, n, ext);
773                         }
774                 n++;
775                 if (n > 999)
776                         {
777                         /* well, we tried */
778                         g_free(unique);
779                         return nullptr;
780                         }
781                 }
782
783         return unique;
784 }
785
786 #pragma GCC diagnostic push
787 #pragma GCC diagnostic ignored "-Wunused-function"
788 gchar *unique_filename_simple_unused(const gchar *path)
789 {
790         gchar *unique;
791         const gchar *name;
792         const gchar *ext;
793
794         if (!path) return NULL;
795
796         name = filename_from_path(path);
797         if (!name) return NULL;
798
799         ext = registered_extension_from_path(name);
800
801         if (!ext)
802                 {
803                 unique = unique_filename(path, NULL, "_", TRUE);
804                 }
805         else
806                 {
807                 gchar *base;
808
809                 base = remove_extension_from_path(path);
810                 unique = unique_filename(base, ext, "_", TRUE);
811                 g_free(base);
812                 }
813
814         return unique;
815 }
816 #pragma GCC diagnostic pop
817
818 const gchar *filename_from_path(const gchar *path)
819 {
820         const gchar *base;
821
822         if (!path) return nullptr;
823
824         base = strrchr(path, G_DIR_SEPARATOR);
825         if (base) return base + 1;
826
827         return path;
828 }
829
830 gchar *remove_level_from_path(const gchar *path)
831 {
832         const gchar *base;
833
834         if (!path) return g_strdup("");
835
836         base = strrchr(path, G_DIR_SEPARATOR);
837         /* Take account of a file being in the root ( / ) folder - ensure the returned value
838          * is at least one character long */
839         if (base) return g_strndup(path, (strlen(path)-strlen(base)) == 0 ? 1 : (strlen(path)-strlen(base)));
840
841         return g_strdup("");
842 }
843
844 gboolean file_extension_match(const gchar *path, const gchar *ext)
845 {
846         gint p;
847         gint e;
848
849         if (!path) return FALSE;
850         if (!ext) return TRUE;
851
852         p = strlen(path);
853         e = strlen(ext);
854
855         /** @FIXME utf8 */
856         return (p > e && g_ascii_strncasecmp(path + p - e, ext, e) == 0);
857 }
858
859 gchar *remove_extension_from_path(const gchar *path)
860 {
861         const gchar *reg_ext;
862
863         if (!path) return nullptr;
864
865         reg_ext = registered_extension_from_path(path);
866
867         return g_strndup(path, strlen(path) - (reg_ext == nullptr ? 0 : strlen(reg_ext)));
868 }
869
870 void parse_out_relatives(gchar *path)
871 {
872         gint s, t;
873
874         if (!path) return;
875
876         s = t = 0;
877
878         while (path[s] != '\0')
879                 {
880                 if (path[s] == G_DIR_SEPARATOR && path[s+1] == '.')
881                         {
882                         /* /. occurrence, let's see more */
883                         gint p = s + 2;
884
885                         if (path[p] == G_DIR_SEPARATOR || path[p] == '\0')
886                                 {
887                                 /* /./ or /., just skip this part */
888                                 s = p;
889                                 continue;
890                                 }
891                         else if (path[p] == '.' && (path[p+1] == G_DIR_SEPARATOR || path[p+1] == '\0'))
892                                 {
893                                 /* /../ or /.., remove previous part, ie. /a/b/../ becomes /a/ */
894                                 s = p + 1;
895                                 if (t > 0) t--;
896                                 while (path[t] != G_DIR_SEPARATOR && t > 0) t--;
897                                 continue;
898                                 }
899                         }
900
901                 if (s != t) path[t] = path[s];
902                 t++;
903                 s++;
904                 }
905
906         if (t == 0 && path[t] == G_DIR_SEPARATOR) t++;
907         if (t > 1 && path[t-1] == G_DIR_SEPARATOR) t--;
908         path[t] = '\0';
909 }
910
911 gboolean file_in_path(const gchar *name)
912 {
913         gchar *path;
914         gchar *namel;
915         gint p, l;
916         gboolean ret = FALSE;
917
918         if (!name) return FALSE;
919         path = g_strdup(getenv("PATH"));
920         if (!path) return FALSE;
921         namel = path_from_utf8(name);
922
923         p = 0;
924         l = strlen(path);
925         while (p < l && !ret)
926                 {
927                 gchar *f;
928                 gint e = p;
929                 while (path[e] != ':' && path[e] != '\0') e++;
930                 path[e] = '\0';
931                 e++;
932                 f = g_build_filename(path + p, namel, NULL);
933                 if (isfile(f)) ret = TRUE;
934                 g_free(f);
935                 p = e;
936                 }
937         g_free(namel);
938         g_free(path);
939
940         return ret;
941 }
942
943 gboolean recursive_mkdir_if_not_exists(const gchar *path, mode_t mode)
944 {
945         if (!path) return FALSE;
946
947         if (!isdir(path))
948                 {
949                 gchar *npath = g_strdup(path);
950                 gchar *p = npath;
951
952                 while (p[0] != '\0')
953                         {
954                         p++;
955                         if (p[0] == G_DIR_SEPARATOR || p[0] == '\0')
956                                 {
957                                 gboolean end = TRUE;
958
959                                 if (p[0] != '\0')
960                                         {
961                                         p[0] = '\0';
962                                         end = FALSE;
963                                         }
964
965                                 if (!isdir(npath))
966                                         {
967                                         DEBUG_1("creating sub dir:%s", npath);
968                                         if (!mkdir_utf8(npath, mode))
969                                                 {
970                                                 log_printf("create dir failed: %s\n", npath);
971                                                 g_free(npath);
972                                                 return FALSE;
973                                                 }
974                                         }
975
976                                 if (!end) p[0] = G_DIR_SEPARATOR;
977                                 }
978                         }
979                 g_free(npath);
980                 }
981
982         return TRUE;
983 }
984
985 /* does filename utf8 to filesystem encoding first */
986 gboolean md5_get_digest_from_file_utf8(const gchar *path, guchar digest[16])
987 {
988         gboolean success;
989         gchar *pathl;
990
991         pathl = path_from_utf8(path);
992         success = md5_get_digest_from_file(pathl, digest);
993         g_free(pathl);
994
995         return success;
996 }
997
998
999 gchar *md5_text_from_file_utf8(const gchar *path, const gchar *error_text)
1000 {
1001         std::unique_ptr<gchar, decltype(&g_free)> pathl{path_from_utf8(path), g_free};
1002
1003         auto md5_text = md5_get_string_from_file(pathl.get());
1004
1005         return md5_text ? md5_text : g_strdup(error_text);
1006 }
1007
1008 /* Download web file
1009  */
1010 struct WebData
1011 {
1012         GenericDialog *gd;
1013         GCancellable *cancellable;
1014         LayoutWindow *lw;
1015
1016         GtkWidget *progress;
1017         GFile *tmp_g_file;
1018         GFile *web_file;
1019 };
1020
1021 static void web_file_async_ready_cb(GObject *source_object, GAsyncResult *res, gpointer data)
1022 {
1023         GError *error = nullptr;
1024         auto web = static_cast<WebData *>(data);
1025         gchar *tmp_filename;
1026
1027         if (!g_cancellable_is_cancelled(web->cancellable))
1028                 {
1029                 generic_dialog_close(web->gd);
1030                 }
1031
1032         if (g_file_copy_finish(G_FILE(source_object), res, &error))
1033                 {
1034                 tmp_filename = g_file_get_parse_name(web->tmp_g_file);
1035                 g_free(tmp_filename);
1036                 layout_set_path(web->lw, g_file_get_path(web->tmp_g_file));
1037                 }
1038         else
1039                 {
1040                 file_util_warning_dialog(_("Web file download failed"), error->message, GQ_ICON_DIALOG_ERROR, nullptr);
1041                 }
1042
1043         g_object_unref(web->tmp_g_file);
1044         web->tmp_g_file = nullptr;
1045         g_object_unref(web->cancellable);
1046         g_object_unref(web->web_file);
1047 }
1048
1049 static void web_file_progress_cb(goffset current_num_bytes, goffset total_num_bytes, gpointer data)
1050 {
1051         auto web = static_cast<WebData *>(data);
1052
1053         if (!g_cancellable_is_cancelled(web->cancellable))
1054                 {
1055                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(web->progress), static_cast<gdouble>(current_num_bytes) / total_num_bytes);
1056                 }
1057 }
1058
1059 static void download_web_file_cancel_button_cb(GenericDialog *, gpointer data)
1060 {
1061         auto web = static_cast<WebData *>(data);
1062
1063         g_cancellable_cancel(web->cancellable);
1064 }
1065
1066 gboolean download_web_file(const gchar *text, gboolean minimized, gpointer data)
1067 {
1068         gchar *scheme;
1069         auto lw = static_cast<LayoutWindow *>(data);
1070         gchar *tmp_dir;
1071         GError *error = nullptr;
1072         WebData *web;
1073         gchar *base;
1074         gboolean ret = FALSE;
1075         gchar *message;
1076         FileFormatClass format_class;
1077
1078         scheme = g_uri_parse_scheme(text);
1079         if (g_strcmp0("http", scheme) == 0 || g_strcmp0("https", scheme) == 0)
1080                 {
1081                 format_class = filter_file_get_class(text);
1082
1083                 if (format_class == FORMAT_CLASS_IMAGE || format_class == FORMAT_CLASS_RAWIMAGE || format_class == FORMAT_CLASS_VIDEO || format_class == FORMAT_CLASS_DOCUMENT)
1084                         {
1085                         tmp_dir = g_dir_make_tmp("geeqie_XXXXXX", &error);
1086                         if (error)
1087                                 {
1088                                 log_printf("Error: could not create temporary file n%s\n", error->message);
1089                                 g_error_free(error);
1090                                 error = nullptr;
1091                                 ret = TRUE;
1092                                 }
1093                         else
1094                                 {
1095                                 web = g_new0(WebData, 1);
1096                                 web->lw = lw;
1097
1098                                 web->web_file = g_file_new_for_uri(text);
1099
1100                                 base = g_strdup(g_file_get_basename(web->web_file));
1101                                 web->tmp_g_file = g_file_new_for_path(g_build_filename(tmp_dir, base, NULL));
1102
1103                                 web->gd = generic_dialog_new(_("Download web file"), "download_web_file", nullptr, TRUE, download_web_file_cancel_button_cb, web);
1104
1105                                 message = g_strconcat(_("Downloading "), base, NULL);
1106                                 generic_dialog_add_message(web->gd, GQ_ICON_DIALOG_INFO, message, nullptr, FALSE);
1107
1108                                 web->progress = gtk_progress_bar_new();
1109                                 gtk_box_pack_start(GTK_BOX(web->gd->vbox), web->progress, FALSE, FALSE, 0);
1110                                 gtk_widget_show(web->progress);
1111                                 if (minimized)
1112                                         {
1113                                         gtk_window_iconify(GTK_WINDOW(web->gd->dialog));
1114                                         }
1115
1116                                 gtk_widget_show(web->gd->dialog);
1117                                 web->cancellable = g_cancellable_new();
1118                                 g_file_copy_async(web->web_file, web->tmp_g_file, G_FILE_COPY_OVERWRITE, G_PRIORITY_LOW, web->cancellable, web_file_progress_cb, web, web_file_async_ready_cb, web);
1119
1120                                 g_free(base);
1121                                 g_free(message);
1122                                 ret = TRUE;
1123                                 }
1124                         }
1125                 }
1126         else
1127                 {
1128                 ret = FALSE;
1129                 }
1130
1131         g_free(scheme);
1132         return ret;
1133
1134 }
1135
1136 gboolean rmdir_recursive(GFile *file, GCancellable *cancellable, GError **error)
1137 {
1138         g_autoptr(GFileEnumerator) enumerator = nullptr;
1139
1140         enumerator = g_file_enumerate_children(file, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancellable, nullptr);
1141
1142         while (enumerator != nullptr)
1143                 {
1144                  GFile *child;
1145
1146                 if (!g_file_enumerator_iterate(enumerator, nullptr, &child, cancellable, error))
1147                         return FALSE;
1148                 if (child == nullptr)
1149                         break;
1150                 if (!rmdir_recursive(child, cancellable, error))
1151                         return FALSE;
1152                 }
1153
1154         return g_file_delete(file, cancellable, error);
1155 }
1156
1157 /**
1158  * @brief Retrieves the internal scale factor that maps from window coordinates to the actual device pixels
1159  * @param  -
1160  * @returns scale factor
1161  *
1162  *
1163  */
1164 gint scale_factor()
1165 {
1166         LayoutWindow *lw = nullptr;
1167
1168         layout_valid(&lw);
1169         return gtk_widget_get_scale_factor(lw->window);
1170 }
1171 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */