clang-tidy: readability-isolate-declaration
[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(_("One or more filenames are not encoded with the preferred locale character set.\n"));
80         g_string_append_printf(string, _("Operations on, and display of these files with %s may not succeed.\n"), PACKAGE);
81         g_string_append(string, "\n");
82         g_string_append(string, _("If your filenames are not encoded in utf-8, try setting the environment variable G_BROKEN_FILENAMES=1\n"));
83         if (bf)
84                 g_string_append_printf(string, _("It appears G_BROKEN_FILENAMES is set to %s\n"), bf);
85         else
86                 g_string_append(string, _("It appears G_BROKEN_FILENAMES is not set\n"));
87         g_string_append(string, "\n");
88         g_string_append_printf(string, _("The locale appears to be set to \"%s\"\n(set by the LANG environment variable)\n"), (lc) ? lc : "undefined");
89         if (lc && (strstr(lc, "UTF-8") || strstr(lc, "utf-8")))
90                 {
91                 gchar *name;
92                 name = g_convert(path, -1, "UTF-8", "ISO-8859-1", nullptr, nullptr, nullptr);
93                 string = g_string_append(string, _("\nPreferred encoding appears to be UTF-8, however the file:\n"));
94                 g_string_append_printf(string, "\"%s\"\n", (name) ? name : _("[name not displayable]"));
95
96                 if (g_utf8_validate(path, -1, nullptr))
97                         g_string_append_printf(string, _("\"%s\" is encoded in valid UTF-8."), (name) ? name : _("[name not displayable]"));
98                 else
99                         g_string_append_printf(string, _("\"%s\" is not encoded in valid UTF-8."), (name) ? name : _("[name not displayable]"));
100                 g_string_append(string, "\n");
101                 g_free(name);
102                 }
103
104         gd = generic_dialog_new(_("Filename encoding locale mismatch"),
105                                 "locale warning", nullptr, TRUE, nullptr, nullptr);
106         generic_dialog_add_button(gd, GQ_ICON_CLOSE, _("Close"), nullptr, TRUE);
107
108         generic_dialog_add_message(gd, GQ_ICON_DIALOG_WARNING,
109                                    _("Filename encoding locale mismatch"), string->str, TRUE);
110
111         gtk_widget_show(gd->dialog);
112
113         g_string_free(string, TRUE);
114 }
115
116 #if GQ_DEBUG_PATH_UTF8
117 gchar *path_to_utf8_debug(const gchar *path, const gchar *file, gint line)
118 #else
119 gchar *path_to_utf8(const gchar *path)
120 #endif
121 {
122         gchar *utf8;
123         GError *error = nullptr;
124
125         if (!path) return nullptr;
126
127         utf8 = g_filename_to_utf8(path, -1, nullptr, nullptr, &error);
128         if (error)
129                 {
130 #if GQ_DEBUG_PATH_UTF8
131                 log_printf("%s:%d: Unable to convert filename to UTF-8:\n%s\n%s\n", file, line, path, error->message);
132 #else
133                 log_printf("Unable to convert filename to UTF-8:\n%s\n%s\n", path, error->message);
134 #endif
135                 g_error_free(error);
136                 encoding_dialog(path);
137                 }
138         if (!utf8)
139                 {
140                 /* just let it through, but bad things may happen */
141                 utf8 = g_strdup(path);
142                 }
143
144         return utf8;
145 }
146
147 #if GQ_DEBUG_PATH_UTF8
148 gchar *path_from_utf8_debug(const gchar *utf8, const gchar *file, gint line)
149 #else
150 gchar *path_from_utf8(const gchar *utf8)
151 #endif
152 {
153         gchar *path;
154         GError *error = nullptr;
155
156         if (!utf8) return nullptr;
157
158         path = g_filename_from_utf8(utf8, -1, nullptr, nullptr, &error);
159         if (error)
160                 {
161 #if GQ_DEBUG_PATH_UTF8
162                 log_printf("%s:%d: Unable to convert filename to locale from UTF-8:\n%s\n%s\n", file, line, utf8, error->message);
163 #else
164                 log_printf("Unable to convert filename to locale from UTF-8:\n%s\n%s\n", utf8, error->message);
165 #endif
166                 g_error_free(error);
167                 }
168         if (!path)
169                 {
170                 /* if invalid UTF-8, text probably still in original form, so just copy it */
171                 path = g_strdup(utf8);
172                 }
173
174         return path;
175 }
176
177 /* first we try the HOME environment var, if that doesn't work, we try g_get_homedir(). */
178 const gchar *homedir()
179 {
180         static gchar *home = nullptr;
181
182         if (!home)
183                 home = path_to_utf8(getenv("HOME"));
184
185         if (!home)
186                 home = path_to_utf8(g_get_home_dir());
187
188         DEBUG_1("Home directory: %s", home);
189
190         return home;
191 }
192
193 static gchar *xdg_dir_get(const gchar *key, const gchar *fallback)
194 {
195         gchar *dir = getenv(key);
196
197         if (!dir || dir[0] == '\0')
198                 {
199                 return g_build_filename(homedir(), fallback, NULL);
200                 }
201
202         DEBUG_1("Got xdg %s: %s", key, dir);
203
204         return path_to_utf8(dir);
205 }
206
207 const gchar *xdg_data_home_get()
208 {
209         static const gchar *xdg_data_home = nullptr;
210
211         if (xdg_data_home) return xdg_data_home;
212
213         xdg_data_home = xdg_dir_get("XDG_DATA_HOME", ".local/share");
214
215         return xdg_data_home;
216 }
217
218 const gchar *xdg_config_home_get()
219 {
220         static const gchar *xdg_config_home = nullptr;
221
222         if (xdg_config_home) return xdg_config_home;
223
224         xdg_config_home = xdg_dir_get("XDG_CONFIG_HOME", ".config");
225
226         return xdg_config_home;
227 }
228
229 const gchar *xdg_cache_home_get()
230 {
231         static const gchar *xdg_cache_home = nullptr;
232
233         if (xdg_cache_home) return xdg_cache_home;
234
235         xdg_cache_home = xdg_dir_get("XDG_CACHE_HOME", ".cache");
236
237         return xdg_cache_home;
238 }
239
240 const gchar *get_rc_dir()
241 {
242         static gchar *rc_dir = nullptr;
243
244         if (rc_dir) return rc_dir;
245
246         if (USE_XDG)
247                 {
248                 rc_dir = g_build_filename(xdg_config_home_get(), GQ_APPNAME_LC, NULL);
249                 }
250         else
251                 {
252                 rc_dir = g_build_filename(homedir(), GQ_RC_DIR, NULL);
253                 }
254
255         return rc_dir;
256 }
257
258 const gchar *get_collections_dir()
259 {
260         static gchar *collections_dir = nullptr;
261
262         if (collections_dir) return collections_dir;
263
264         if (USE_XDG)
265                 {
266                 collections_dir = g_build_filename(xdg_data_home_get(), GQ_APPNAME_LC, GQ_COLLECTIONS_DIR, NULL);
267                 }
268         else
269                 {
270                 collections_dir = g_build_filename(get_rc_dir(), GQ_COLLECTIONS_DIR, NULL);
271                 }
272
273         return collections_dir;
274 }
275
276 const gchar *get_trash_dir()
277 {
278         static gchar *trash_dir = nullptr;
279
280         if (trash_dir) return trash_dir;
281
282         if (USE_XDG)
283                 {
284                 trash_dir = g_build_filename(xdg_data_home_get(), GQ_APPNAME_LC, GQ_TRASH_DIR, NULL);
285                 }
286         else
287                 {
288                 trash_dir = g_build_filename(get_rc_dir(), GQ_TRASH_DIR, NULL);
289         }
290
291         return trash_dir;
292 }
293
294 const gchar *get_window_layouts_dir()
295 {
296         static gchar *window_layouts_dir = nullptr;
297
298         if (window_layouts_dir) return window_layouts_dir;
299
300         if (USE_XDG)
301                 {
302                 window_layouts_dir = g_build_filename(xdg_config_home_get(), GQ_APPNAME_LC, GQ_WINDOW_LAYOUTS_DIR, NULL);
303                 }
304         else
305                 {
306                 window_layouts_dir = g_build_filename(get_rc_dir(), GQ_WINDOW_LAYOUTS_DIR, NULL);
307                 }
308
309         return window_layouts_dir;
310 }
311
312 gboolean stat_utf8(const gchar *s, struct stat *st)
313 {
314         gchar *sl;
315         gboolean ret;
316
317         if (!s) return FALSE;
318         sl = path_from_utf8(s);
319         ret = (stat(sl, st) == 0);
320         g_free(sl);
321
322         return ret;
323 }
324
325 gboolean lstat_utf8(const gchar *s, struct stat *st)
326 {
327         gchar *sl;
328         gboolean ret;
329
330         if (!s) return FALSE;
331         sl = path_from_utf8(s);
332         ret = (lstat(sl, st) == 0);
333         g_free(sl);
334
335         return ret;
336 }
337
338 gboolean isname(const gchar *s)
339 {
340         struct stat st;
341
342         return stat_utf8(s, &st);
343 }
344
345 gboolean isfile(const gchar *s)
346 {
347         struct stat st;
348
349         return (stat_utf8(s, &st) && S_ISREG(st.st_mode));
350 }
351
352 gboolean isdir(const gchar *s)
353 {
354         struct stat st;
355
356         return (stat_utf8(s, &st) && S_ISDIR(st.st_mode));
357 }
358
359 gboolean islink(const gchar *s)
360 {
361         struct stat st;
362
363         return (lstat_utf8(s, &st) && S_ISLNK(st.st_mode));
364 }
365
366 gint64 filesize(const gchar *s)
367 {
368         struct stat st;
369
370         if (!stat_utf8(s, &st)) return 0;
371         return st.st_size;
372 }
373
374 time_t filetime(const gchar *s)
375 {
376         struct stat st;
377
378         if (!stat_utf8(s, &st)) return 0;
379         return st.st_mtime;
380 }
381
382 gboolean filetime_set(const gchar *s, time_t tval)
383 {
384         gboolean ret = FALSE;
385
386         if (tval > 0)
387                 {
388                 struct utimbuf ut;
389                 gchar *sl;
390
391                 ut.actime = ut.modtime = tval;
392
393                 sl = path_from_utf8(s);
394                 ret = (utime(sl, &ut) == 0);
395                 g_free(sl);
396                 }
397
398         return ret;
399 }
400
401 gboolean is_readable_file(const gchar *s)
402 {
403         if (!s || !s[0] || !isfile(s)) return FALSE;
404         return access_file(s, R_OK);
405 }
406
407 gboolean access_file(const gchar *s, gint mode)
408 {
409         gchar *sl;
410         gint ret;
411
412         if (!s || !s[0]) return FALSE;
413
414         sl = path_from_utf8(s);
415         ret = (access(sl, mode) == 0);
416         g_free(sl);
417
418         return ret;
419 }
420
421 gboolean unlink_file(const gchar *s)
422 {
423         gchar *sl;
424         gboolean ret;
425
426         if (!s) return FALSE;
427
428         sl = path_from_utf8(s);
429         ret = (unlink(sl) == 0);
430         g_free(sl);
431
432         return ret;
433 }
434
435 #pragma GCC diagnostic push
436 #pragma GCC diagnostic ignored "-Wunused-function"
437 gboolean symlink_utf8_unused(const gchar *source, const gchar *target)
438 {
439         gchar *sl;
440         gchar *tl;
441         gboolean ret;
442
443         if (!source || !target) return FALSE;
444
445         sl = path_from_utf8(source);
446         tl = path_from_utf8(target);
447
448         ret = (symlink(sl, tl) == 0);
449
450         g_free(sl);
451         g_free(tl);
452
453         return ret;
454 }
455 #pragma GCC diagnostic pop
456
457 gboolean mkdir_utf8(const gchar *s, gint mode)
458 {
459         gchar *sl;
460         gboolean ret;
461
462         if (!s) return FALSE;
463
464         sl = path_from_utf8(s);
465         ret = (mkdir(sl, mode) == 0);
466         g_free(sl);
467         return ret;
468 }
469
470 gboolean rmdir_utf8(const gchar *s)
471 {
472         gchar *sl;
473         gboolean ret;
474
475         if (!s) return FALSE;
476
477         sl = path_from_utf8(s);
478         ret = (rmdir(sl) == 0);
479         g_free(sl);
480
481         return ret;
482 }
483
484 gboolean copy_file_attributes(const gchar *s, const gchar *t, gint perms, gint mtime)
485 {
486         struct stat st;
487         gchar *sl;
488         gchar *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;
674         gchar *tl;
675         gboolean ret = TRUE;
676
677         if (!s || !t) return FALSE;
678
679         sl = path_from_utf8(s);
680         tl = path_from_utf8(t);
681         if (rename(sl, tl) < 0)
682                 {
683                 /* this may have failed because moving a file across filesystems
684                 was attempted, so try copy and delete instead */
685                 if (copy_file(s, t))
686                         {
687                         if (unlink(sl) < 0)
688                                 {
689                                 /* err, now we can't delete the source file so return FALSE */
690                                 ret = FALSE;
691                                 }
692                         }
693                 else
694                         {
695                         ret = FALSE;
696                         }
697                 }
698         g_free(sl);
699         g_free(tl);
700
701         return ret;
702 }
703
704 gboolean rename_file(const gchar *s, const gchar *t)
705 {
706         gchar *sl;
707         gchar *tl;
708         gboolean ret;
709
710         if (!s || !t) return FALSE;
711
712         sl = path_from_utf8(s);
713         tl = path_from_utf8(t);
714         ret = (rename(sl, tl) == 0);
715         g_free(sl);
716         g_free(tl);
717
718         return ret;
719 }
720
721 gchar *get_current_dir()
722 {
723         gchar *pathl;
724         gchar *path8;
725
726         pathl = g_get_current_dir();
727         path8 = path_to_utf8(pathl);
728         g_free(pathl);
729
730         return path8;
731 }
732
733 void string_list_free(GList *list)
734 {
735         g_list_free_full(list, g_free);
736 }
737
738 GList *string_list_copy(const GList *list)
739 {
740         GList *new_list = nullptr;
741         auto work = const_cast<GList *>(list);
742
743         while (work)
744                 {
745                 gchar *path;
746
747                 path = static_cast<gchar *>(work->data);
748                 work = work->next;
749
750                 new_list = g_list_prepend(new_list, g_strdup(path));
751                 }
752
753         return g_list_reverse(new_list);
754 }
755
756 gchar *unique_filename(const gchar *path, const gchar *ext, const gchar *divider, gboolean pad)
757 {
758         gchar *unique;
759         gint n = 1;
760
761         if (!ext) ext = "";
762         if (!divider) divider = "";
763
764         unique = g_strconcat(path, ext, NULL);
765         while (isname(unique))
766                 {
767                 g_free(unique);
768                 if (pad)
769                         {
770                         unique = g_strdup_printf("%s%s%03d%s", path, divider, n, ext);
771                         }
772                 else
773                         {
774                         unique = g_strdup_printf("%s%s%d%s", path, divider, n, ext);
775                         }
776                 n++;
777                 if (n > 999)
778                         {
779                         /* well, we tried */
780                         g_free(unique);
781                         return nullptr;
782                         }
783                 }
784
785         return unique;
786 }
787
788 #pragma GCC diagnostic push
789 #pragma GCC diagnostic ignored "-Wunused-function"
790 gchar *unique_filename_simple_unused(const gchar *path)
791 {
792         gchar *unique;
793         const gchar *name;
794         const gchar *ext;
795
796         if (!path) return nullptr;
797
798         name = filename_from_path(path);
799         if (!name) return nullptr;
800
801         ext = registered_extension_from_path(name);
802
803         if (!ext)
804                 {
805                 unique = unique_filename(path, nullptr, "_", TRUE);
806                 }
807         else
808                 {
809                 gchar *base;
810
811                 base = remove_extension_from_path(path);
812                 unique = unique_filename(base, ext, "_", TRUE);
813                 g_free(base);
814                 }
815
816         return unique;
817 }
818 #pragma GCC diagnostic pop
819
820 const gchar *filename_from_path(const gchar *path)
821 {
822         const gchar *base;
823
824         if (!path) return nullptr;
825
826         base = strrchr(path, G_DIR_SEPARATOR);
827         if (base) return base + 1;
828
829         return path;
830 }
831
832 gchar *remove_level_from_path(const gchar *path)
833 {
834         const gchar *base;
835
836         if (!path) return g_strdup("");
837
838         base = strrchr(path, G_DIR_SEPARATOR);
839         /* Take account of a file being in the root ( / ) folder - ensure the returned value
840          * is at least one character long */
841         if (base) return g_strndup(path, (strlen(path)-strlen(base)) == 0 ? 1 : (strlen(path)-strlen(base)));
842
843         return g_strdup("");
844 }
845
846 gboolean file_extension_match(const gchar *path, const gchar *ext)
847 {
848         gint p;
849         gint e;
850
851         if (!path) return FALSE;
852         if (!ext) return TRUE;
853
854         p = strlen(path);
855         e = strlen(ext);
856
857         /** @FIXME utf8 */
858         return (p > e && g_ascii_strncasecmp(path + p - e, ext, e) == 0);
859 }
860
861 gchar *remove_extension_from_path(const gchar *path)
862 {
863         const gchar *reg_ext;
864
865         if (!path) return nullptr;
866
867         reg_ext = registered_extension_from_path(path);
868
869         return g_strndup(path, strlen(path) - (reg_ext == nullptr ? 0 : strlen(reg_ext)));
870 }
871
872 void parse_out_relatives(gchar *path)
873 {
874         gint s;
875         gint t;
876
877         if (!path) return;
878
879         s = t = 0;
880
881         while (path[s] != '\0')
882                 {
883                 if (path[s] == G_DIR_SEPARATOR && path[s+1] == '.')
884                         {
885                         /* /. occurrence, let's see more */
886                         gint p = s + 2;
887
888                         if (path[p] == G_DIR_SEPARATOR || path[p] == '\0')
889                                 {
890                                 /* /./ or /., just skip this part */
891                                 s = p;
892                                 continue;
893                                 }
894
895                         if (path[p] == '.' && (path[p+1] == G_DIR_SEPARATOR || path[p+1] == '\0'))
896                                 {
897                                 /* /../ or /.., remove previous part, ie. /a/b/../ becomes /a/ */
898                                 s = p + 1;
899                                 if (t > 0) t--;
900                                 while (path[t] != G_DIR_SEPARATOR && t > 0) t--;
901                                 continue;
902                                 }
903                         }
904
905                 if (s != t) path[t] = path[s];
906                 t++;
907                 s++;
908                 }
909
910         if (t == 0 && path[t] == G_DIR_SEPARATOR) t++;
911         if (t > 1 && path[t-1] == G_DIR_SEPARATOR) t--;
912         path[t] = '\0';
913 }
914
915 gboolean file_in_path(const gchar *name)
916 {
917         gchar *path;
918         gchar *namel;
919         gint p;
920         gint l;
921         gboolean ret = FALSE;
922
923         if (!name) return FALSE;
924         path = g_strdup(getenv("PATH"));
925         if (!path) return FALSE;
926         namel = path_from_utf8(name);
927
928         p = 0;
929         l = strlen(path);
930         while (p < l && !ret)
931                 {
932                 gchar *f;
933                 gint e = p;
934                 while (path[e] != ':' && path[e] != '\0') e++;
935                 path[e] = '\0';
936                 e++;
937                 f = g_build_filename(path + p, namel, NULL);
938                 if (isfile(f)) ret = TRUE;
939                 g_free(f);
940                 p = e;
941                 }
942         g_free(namel);
943         g_free(path);
944
945         return ret;
946 }
947
948 gboolean recursive_mkdir_if_not_exists(const gchar *path, mode_t mode)
949 {
950         if (!path) return FALSE;
951
952         if (!isdir(path))
953                 {
954                 gchar *npath = g_strdup(path);
955                 gchar *p = npath;
956
957                 while (p[0] != '\0')
958                         {
959                         p++;
960                         if (p[0] == G_DIR_SEPARATOR || p[0] == '\0')
961                                 {
962                                 gboolean end = TRUE;
963
964                                 if (p[0] != '\0')
965                                         {
966                                         p[0] = '\0';
967                                         end = FALSE;
968                                         }
969
970                                 if (!isdir(npath))
971                                         {
972                                         DEBUG_1("creating sub dir:%s", npath);
973                                         if (!mkdir_utf8(npath, mode))
974                                                 {
975                                                 log_printf("create dir failed: %s\n", npath);
976                                                 g_free(npath);
977                                                 return FALSE;
978                                                 }
979                                         }
980
981                                 if (!end) p[0] = G_DIR_SEPARATOR;
982                                 }
983                         }
984                 g_free(npath);
985                 }
986
987         return TRUE;
988 }
989
990 /* does filename utf8 to filesystem encoding first */
991 gboolean md5_get_digest_from_file_utf8(const gchar *path, guchar digest[16])
992 {
993         gboolean success;
994         gchar *pathl;
995
996         pathl = path_from_utf8(path);
997         success = md5_get_digest_from_file(pathl, digest);
998         g_free(pathl);
999
1000         return success;
1001 }
1002
1003
1004 gchar *md5_text_from_file_utf8(const gchar *path, const gchar *error_text)
1005 {
1006         std::unique_ptr<gchar, decltype(&g_free)> pathl{path_from_utf8(path), g_free};
1007
1008         auto md5_text = md5_get_string_from_file(pathl.get());
1009
1010         return md5_text ? md5_text : g_strdup(error_text);
1011 }
1012
1013 /* Download web file
1014  */
1015 struct WebData
1016 {
1017         GenericDialog *gd;
1018         GCancellable *cancellable;
1019         LayoutWindow *lw;
1020
1021         GtkWidget *progress;
1022         GFile *tmp_g_file;
1023         GFile *web_file;
1024 };
1025
1026 static void web_file_async_ready_cb(GObject *source_object, GAsyncResult *res, gpointer data)
1027 {
1028         GError *error = nullptr;
1029         auto web = static_cast<WebData *>(data);
1030         gchar *tmp_filename;
1031
1032         if (!g_cancellable_is_cancelled(web->cancellable))
1033                 {
1034                 generic_dialog_close(web->gd);
1035                 }
1036
1037         if (g_file_copy_finish(G_FILE(source_object), res, &error))
1038                 {
1039                 tmp_filename = g_file_get_parse_name(web->tmp_g_file);
1040                 g_free(tmp_filename);
1041                 layout_set_path(web->lw, g_file_get_path(web->tmp_g_file));
1042                 }
1043         else
1044                 {
1045                 file_util_warning_dialog(_("Web file download failed"), error->message, GQ_ICON_DIALOG_ERROR, nullptr);
1046                 }
1047
1048         g_object_unref(web->tmp_g_file);
1049         web->tmp_g_file = nullptr;
1050         g_object_unref(web->cancellable);
1051         g_object_unref(web->web_file);
1052 }
1053
1054 static void web_file_progress_cb(goffset current_num_bytes, goffset total_num_bytes, gpointer data)
1055 {
1056         auto web = static_cast<WebData *>(data);
1057
1058         if (!g_cancellable_is_cancelled(web->cancellable))
1059                 {
1060                 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(web->progress), static_cast<gdouble>(current_num_bytes) / total_num_bytes);
1061                 }
1062 }
1063
1064 static void download_web_file_cancel_button_cb(GenericDialog *, gpointer data)
1065 {
1066         auto web = static_cast<WebData *>(data);
1067
1068         g_cancellable_cancel(web->cancellable);
1069 }
1070
1071 gboolean download_web_file(const gchar *text, gboolean minimized, gpointer data)
1072 {
1073         gchar *scheme;
1074         auto lw = static_cast<LayoutWindow *>(data);
1075         gchar *tmp_dir;
1076         GError *error = nullptr;
1077         WebData *web;
1078         gchar *base;
1079         gboolean ret = FALSE;
1080         gchar *message;
1081         FileFormatClass format_class;
1082
1083         scheme = g_uri_parse_scheme(text);
1084         if (g_strcmp0("http", scheme) == 0 || g_strcmp0("https", scheme) == 0)
1085                 {
1086                 format_class = filter_file_get_class(text);
1087
1088                 if (format_class == FORMAT_CLASS_IMAGE || format_class == FORMAT_CLASS_RAWIMAGE || format_class == FORMAT_CLASS_VIDEO || format_class == FORMAT_CLASS_DOCUMENT)
1089                         {
1090                         tmp_dir = g_dir_make_tmp("geeqie_XXXXXX", &error);
1091                         if (error)
1092                                 {
1093                                 log_printf("Error: could not create temporary file n%s\n", error->message);
1094                                 g_error_free(error);
1095                                 error = nullptr;
1096                                 ret = TRUE;
1097                                 }
1098                         else
1099                                 {
1100                                 web = g_new0(WebData, 1);
1101                                 web->lw = lw;
1102
1103                                 web->web_file = g_file_new_for_uri(text);
1104
1105                                 base = g_strdup(g_file_get_basename(web->web_file));
1106                                 web->tmp_g_file = g_file_new_for_path(g_build_filename(tmp_dir, base, NULL));
1107
1108                                 web->gd = generic_dialog_new(_("Download web file"), "download_web_file", nullptr, TRUE, download_web_file_cancel_button_cb, web);
1109
1110                                 message = g_strconcat(_("Downloading "), base, NULL);
1111                                 generic_dialog_add_message(web->gd, GQ_ICON_DIALOG_INFO, message, nullptr, FALSE);
1112
1113                                 web->progress = gtk_progress_bar_new();
1114                                 gq_gtk_box_pack_start(GTK_BOX(web->gd->vbox), web->progress, FALSE, FALSE, 0);
1115                                 gtk_widget_show(web->progress);
1116                                 if (minimized)
1117                                         {
1118                                         gtk_window_iconify(GTK_WINDOW(web->gd->dialog));
1119                                         }
1120
1121                                 gtk_widget_show(web->gd->dialog);
1122                                 web->cancellable = g_cancellable_new();
1123                                 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);
1124
1125                                 g_free(base);
1126                                 g_free(message);
1127                                 ret = TRUE;
1128                                 }
1129                         }
1130                 }
1131         else
1132                 {
1133                 ret = FALSE;
1134                 }
1135
1136         g_free(scheme);
1137         return ret;
1138
1139 }
1140
1141 gboolean rmdir_recursive(GFile *file, GCancellable *cancellable, GError **error)
1142 {
1143         g_autoptr(GFileEnumerator) enumerator = nullptr;
1144
1145         enumerator = g_file_enumerate_children(file, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, cancellable, nullptr);
1146
1147         while (enumerator != nullptr)
1148                 {
1149                  GFile *child;
1150
1151                 if (!g_file_enumerator_iterate(enumerator, nullptr, &child, cancellable, error))
1152                         return FALSE;
1153                 if (child == nullptr)
1154                         break;
1155                 if (!rmdir_recursive(child, cancellable, error))
1156                         return FALSE;
1157                 }
1158
1159         return g_file_delete(file, cancellable, error);
1160 }
1161
1162 /**
1163  * @brief Retrieves the internal scale factor that maps from window coordinates to the actual device pixels
1164  * @param  -
1165  * @returns scale factor
1166  *
1167  *
1168  */
1169 gint scale_factor()
1170 {
1171         LayoutWindow *lw = nullptr;
1172
1173         layout_valid(&lw);
1174         return gtk_widget_get_scale_factor(lw->window);
1175 }
1176 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */