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