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