2 * Copyright (C) 2006 John Ellis
3 * Copyright (C) 2008 - 2016 The Geeqie Team
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.
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.
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.
31 #include <sys/param.h>
36 #include <gtk/gtk.h> /* for locale warning dialog */
39 #include "ui_fileops.h"
41 #include "ui_utildlg.h" /* for locale warning dialog */
44 #include "filefilter.h"
47 #include "secure_save.h"
50 *-----------------------------------------------------------------------------
51 * generic file information and manipulation routines (public)
52 *-----------------------------------------------------------------------------
57 void print_term(gboolean err, const gchar *text_utf8)
61 text_l = g_locale_from_utf8(text_utf8, -1, NULL, NULL, NULL);
64 fputs((text_l) ? text_l : text_utf8, stderr);
68 fputs((text_l) ? text_l : text_utf8, stdout);
70 if(command_line && command_line->ssi)
71 secure_fputs(command_line->ssi, (text_l) ? text_l : text_utf8);
75 static void encoding_dialog(const gchar *path)
77 static gboolean warned_user = FALSE;
83 if (warned_user) return;
87 bf = getenv("G_BROKEN_FILENAMES");
89 string = g_string_new("");
90 g_string_append(string, _("One or more filenames are not encoded with the preferred locale character set.\n"));
91 g_string_append_printf(string, _("Operations on, and display of these files with %s may not succeed.\n"), PACKAGE);
92 g_string_append(string, "\n");
93 g_string_append(string, _("If your filenames are not encoded in utf-8, try setting the environment variable G_BROKEN_FILENAMES=1\n"));
95 g_string_append_printf(string, _("It appears G_BROKEN_FILENAMES is set to %s\n"), bf);
97 g_string_append(string, _("It appears G_BROKEN_FILENAMES is not set\n"));
98 g_string_append(string, "\n");
99 g_string_append_printf(string, _("The locale appears to be set to \"%s\"\n(set by the LANG environment variable)\n"), (lc) ? lc : "undefined");
100 if (lc && (strstr(lc, "UTF-8") || strstr(lc, "utf-8")))
103 name = g_convert(path, -1, "UTF-8", "ISO-8859-1", NULL, NULL, NULL);
104 string = g_string_append(string, _("\nPreferred encoding appears to be UTF-8, however the file:\n"));
105 g_string_append_printf(string, "\"%s\"\n", (name) ? name : _("[name not displayable]"));
107 if (g_utf8_validate(path, -1, NULL))
108 g_string_append_printf(string, _("\"%s\" is encoded in valid UTF-8."), (name) ? name : _("[name not displayable]"));
110 g_string_append_printf(string, _("\"%s\" is not encoded in valid UTF-8."), (name) ? name : _("[name not displayable]"));
111 g_string_append(string, "\n");
115 gd = generic_dialog_new(_("Filename encoding locale mismatch"),
116 "locale warning", NULL, TRUE, NULL, NULL);
117 generic_dialog_add_button(gd, GTK_STOCK_CLOSE, NULL, NULL, TRUE);
119 generic_dialog_add_message(gd, GTK_STOCK_DIALOG_WARNING,
120 _("Filename encoding locale mismatch"), string->str, TRUE);
122 gtk_widget_show(gd->dialog);
124 g_string_free(string, TRUE);
127 #if GQ_DEBUG_PATH_UTF8
128 gchar *path_to_utf8_debug(const gchar *path, const gchar *file, gint line)
130 gchar *path_to_utf8(const gchar *path)
134 GError *error = NULL;
136 if (!path) return NULL;
138 utf8 = g_filename_to_utf8(path, -1, NULL, NULL, &error);
141 #if GQ_DEBUG_PATH_UTF8
142 log_printf("%s:%d: Unable to convert filename to UTF-8:\n%s\n%s\n", file, line, path, error->message);
144 log_printf("Unable to convert filename to UTF-8:\n%s\n%s\n", path, error->message);
147 encoding_dialog(path);
151 /* just let it through, but bad things may happen */
152 utf8 = g_strdup(path);
158 #if GQ_DEBUG_PATH_UTF8
159 gchar *path_from_utf8_debug(const gchar *utf8, const gchar *file, gint line)
161 gchar *path_from_utf8(const gchar *utf8)
165 GError *error = NULL;
167 if (!utf8) return NULL;
169 path = g_filename_from_utf8(utf8, -1, NULL, NULL, &error);
172 #if GQ_DEBUG_PATH_UTF8
173 log_printf("%s:%d: Unable to convert filename to locale from UTF-8:\n%s\n%s\n", file, line, utf8, error->message);
175 log_printf("Unable to convert filename to locale from UTF-8:\n%s\n%s\n", utf8, error->message);
181 /* if invalid UTF-8, text probaby still in original form, so just copy it */
182 path = g_strdup(utf8);
188 /* first we try the HOME environment var, if that doesn't work, we try g_get_homedir(). */
189 const gchar *homedir(void)
191 static gchar *home = NULL;
194 home = path_to_utf8(getenv("HOME"));
197 home = path_to_utf8(g_get_home_dir());
199 DEBUG_1("Home directory: %s", home);
204 static gchar *xdg_dir_get(const gchar *key, const gchar *fallback)
206 gchar *dir = getenv(key);
208 if (!dir || dir[0] == '\0')
210 return g_build_filename(homedir(), fallback, NULL);
213 DEBUG_1("Got xdg %s: %s", key, dir);
215 return path_to_utf8(dir);
218 const gchar *xdg_data_home_get(void)
220 static const gchar *xdg_data_home = NULL;
222 if (xdg_data_home) return xdg_data_home;
224 xdg_data_home = xdg_dir_get("XDG_DATA_HOME", ".local/share");
226 return xdg_data_home;
229 const gchar *xdg_config_home_get(void)
231 static const gchar *xdg_config_home = NULL;
233 if (xdg_config_home) return xdg_config_home;
235 xdg_config_home = xdg_dir_get("XDG_CONFIG_HOME", ".config");
237 return xdg_config_home;
240 const gchar *xdg_cache_home_get(void)
242 static const gchar *xdg_cache_home = NULL;
244 if (xdg_cache_home) return xdg_cache_home;
246 xdg_cache_home = xdg_dir_get("XDG_CACHE_HOME", ".cache");
248 return xdg_cache_home;
251 const gchar *get_rc_dir(void)
253 static gchar *rc_dir = NULL;
255 if (rc_dir) return rc_dir;
259 rc_dir = g_build_filename(xdg_config_home_get(), GQ_APPNAME_LC, NULL);
263 rc_dir = g_build_filename(homedir(), GQ_RC_DIR, NULL);
269 const gchar *get_collections_dir(void)
271 static gchar *collections_dir = NULL;
273 if (collections_dir) return collections_dir;
277 collections_dir = g_build_filename(xdg_data_home_get(), GQ_APPNAME_LC, GQ_COLLECTIONS_DIR, NULL);
281 collections_dir = g_build_filename(get_rc_dir(), GQ_COLLECTIONS_DIR, NULL);
284 return collections_dir;
287 const gchar *get_trash_dir(void)
289 static gchar *trash_dir = NULL;
291 if (trash_dir) return trash_dir;
295 trash_dir = g_build_filename(xdg_data_home_get(), GQ_APPNAME_LC, GQ_TRASH_DIR, NULL);
299 trash_dir = g_build_filename(get_rc_dir(), GQ_TRASH_DIR, NULL);
305 const gchar *get_window_layouts_dir(void)
307 static gchar *window_layouts_dir = NULL;
309 if (window_layouts_dir) return window_layouts_dir;
313 window_layouts_dir = g_build_filename(xdg_config_home_get(), GQ_APPNAME_LC, GQ_WINDOW_LAYOUTS_DIR, NULL);
317 window_layouts_dir = g_build_filename(get_rc_dir(), GQ_WINDOW_LAYOUTS_DIR, NULL);
320 return window_layouts_dir;
323 gboolean stat_utf8(const gchar *s, struct stat *st)
328 if (!s) return FALSE;
329 sl = path_from_utf8(s);
330 ret = (stat(sl, st) == 0);
336 gboolean lstat_utf8(const gchar *s, struct stat *st)
341 if (!s) return FALSE;
342 sl = path_from_utf8(s);
343 ret = (lstat(sl, st) == 0);
349 gboolean isname(const gchar *s)
353 return stat_utf8(s, &st);
356 gboolean isfile(const gchar *s)
360 return (stat_utf8(s, &st) && S_ISREG(st.st_mode));
363 gboolean isdir(const gchar *s)
367 return (stat_utf8(s, &st) && S_ISDIR(st.st_mode));
370 gboolean islink(const gchar *s)
374 return (lstat_utf8(s, &st) && S_ISLNK(st.st_mode));
377 gint64 filesize(const gchar *s)
381 if (!stat_utf8(s, &st)) return 0;
385 time_t filetime(const gchar *s)
389 if (!stat_utf8(s, &st)) return 0;
393 gboolean filetime_set(const gchar *s, time_t tval)
395 gboolean ret = FALSE;
402 ut.actime = ut.modtime = tval;
404 sl = path_from_utf8(s);
405 ret = (utime(sl, &ut) == 0);
412 gboolean is_readable_file(const gchar *s)
414 if (!s || !s[0] || !isfile(s)) return FALSE;
415 return access_file(s, R_OK);
418 gboolean access_file(const gchar *s, gint mode)
423 if (!s || !s[0]) return FALSE;
425 sl = path_from_utf8(s);
426 ret = (access(sl, mode) == 0);
432 gboolean unlink_file(const gchar *s)
437 if (!s) return FALSE;
439 sl = path_from_utf8(s);
440 ret = (unlink(sl) == 0);
446 gboolean symlink_utf8(const gchar *source, const gchar *target)
452 if (!source || !target) return FALSE;
454 sl = path_from_utf8(source);
455 tl = path_from_utf8(target);
457 ret = (symlink(sl, tl) == 0);
465 gboolean mkdir_utf8(const gchar *s, gint mode)
470 if (!s) return FALSE;
472 sl = path_from_utf8(s);
473 ret = (mkdir(sl, mode) == 0);
478 gboolean rmdir_utf8(const gchar *s)
483 if (!s) return FALSE;
485 sl = path_from_utf8(s);
486 ret = (rmdir(sl) == 0);
492 gboolean copy_file_attributes(const gchar *s, const gchar *t, gint perms, gint mtime)
496 gboolean ret = FALSE;
498 if (!s || !t) return FALSE;
500 sl = path_from_utf8(s);
501 tl = path_from_utf8(t);
503 if (stat(sl, &st) == 0)
509 /* set the dest file attributes to that of source (ignoring errors) */
513 ret = chown(tl, st.st_uid, st.st_gid);
514 /* Ignores chown errors, while still doing chown
515 (so root still can copy files preserving ownership) */
517 if (chmod(tl, st.st_mode) < 0) {
519 if (stat(tl, &st2) != 0 || st2.st_mode != st.st_mode) {
525 tb.actime = st.st_atime;
526 tb.modtime = st.st_mtime;
527 if (mtime && utime(tl, &tb) < 0) ret = FALSE;
536 /* paths are in filesystem encoding */
537 static gboolean hard_linked(const gchar *a, const gchar *b)
542 if (stat(a, &sta) != 0 || stat(b, &stb) != 0) return FALSE;
544 return (sta.st_dev == stb.st_dev &&
545 sta.st_ino == stb.st_ino);
548 gboolean copy_file(const gchar *s, const gchar *t)
554 gchar *randname = NULL;
560 sl = path_from_utf8(s);
561 tl = path_from_utf8(t);
563 if (hard_linked(sl, tl))
569 /* Do not dereference absolute symlinks, but copy them "as is".
570 * For a relative symlink, we don't know how to properly change it when
571 * copied/moved to another dir to keep pointing it to same target as
572 * a relative symlink, so we turn it into absolute symlink using
573 * realpath() instead. */
575 if (lstat_utf8(sl, &st) && S_ISLNK(st.st_mode))
580 link_target = g_malloc(st.st_size + 1);
581 i = readlink(sl, link_target, st.st_size);
585 goto orig_copy; // try a "normal" copy
587 link_target[st.st_size] = '\0';
589 if (link_target[0] != G_DIR_SEPARATOR) // if it is a relative symlink
593 gchar *lastslash = strrchr(sl, G_DIR_SEPARATOR);
594 gint len = lastslash - sl + 1;
596 absolute = g_malloc(len + st.st_size + 1);
597 strncpy(absolute, sl, len);
598 strcpy(absolute + len, link_target);
600 link_target = absolute;
603 realPath = realpath(link_target, NULL);
605 if (realPath != NULL) // successfully resolved into an absolute path
608 link_target = g_strdup(realPath);
611 else // could not get absolute path, got some error instead
614 goto orig_copy; // so try a "normal" copy
618 if (stat_utf8(tl, &st)) unlink(tl); // first try to remove directory entry in destination directory if such entry exists
620 gint success = (symlink(link_target, tl) == 0);
628 } // if symlink did not succeed, continue on to try a copy procedure
631 fi = fopen(sl, "rb");
634 /* First we write to a temporary file, then we rename it on success,
635 and attributes from original file are copied */
636 randname = g_strconcat(tl, ".tmp_XXXXXX", NULL);
637 if (!randname) goto end;
639 fd = g_mkstemp(randname);
640 if (fd == -1) goto end;
642 fo = fdopen(fd, "wb");
648 while ((b = fread(buf, sizeof(gchar), sizeof(buf), fi)) && b != 0)
650 if (fwrite(buf, sizeof(gchar), b, fo) != b)
657 fclose(fi); fi = NULL;
658 fclose(fo); fo = NULL;
660 if (rename(randname, tl) < 0) {
665 ret = copy_file_attributes(s, t, TRUE, TRUE);
672 if (randname) g_free(randname);
676 gboolean move_file(const gchar *s, const gchar *t)
681 if (!s || !t) return FALSE;
683 sl = path_from_utf8(s);
684 tl = path_from_utf8(t);
685 if (rename(sl, tl) < 0)
687 /* this may have failed because moving a file across filesystems
688 was attempted, so try copy and delete instead */
693 /* err, now we can't delete the source file so return FALSE */
708 gboolean rename_file(const gchar *s, const gchar *t)
713 if (!s || !t) return FALSE;
715 sl = path_from_utf8(s);
716 tl = path_from_utf8(t);
717 ret = (rename(sl, tl) == 0);
724 gchar *get_current_dir(void)
729 pathl = g_get_current_dir();
730 path8 = path_to_utf8(pathl);
736 void g_free_wrapper(void *data, void *userdata)
741 void string_list_free(GList *list)
743 g_list_foreach(list, (GFunc)g_free_wrapper, NULL);
747 GList *string_list_copy(const GList *list)
749 GList *new_list = NULL;
750 GList *work = (GList *) list;
759 new_list = g_list_prepend(new_list, g_strdup(path));
762 return g_list_reverse(new_list);
765 gchar *unique_filename(const gchar *path, const gchar *ext, const gchar *divider, gboolean pad)
771 if (!divider) divider = "";
773 unique = g_strconcat(path, ext, NULL);
774 while (isname(unique))
779 unique = g_strdup_printf("%s%s%03d%s", path, divider, n, ext);
783 unique = g_strdup_printf("%s%s%d%s", path, divider, n, ext);
797 gchar *unique_filename_simple(const gchar *path)
803 if (!path) return NULL;
805 name = filename_from_path(path);
806 if (!name) return NULL;
808 ext = registered_extension_from_path(name);
812 unique = unique_filename(path, NULL, "_", TRUE);
818 base = remove_extension_from_path(path);
819 unique = unique_filename(base, ext, "_", TRUE);
826 const gchar *filename_from_path(const gchar *path)
830 if (!path) return NULL;
832 base = strrchr(path, G_DIR_SEPARATOR);
833 if (base) return base + 1;
838 gchar *remove_level_from_path(const gchar *path)
842 if (!path) return g_strdup("");
844 base = strrchr(path, G_DIR_SEPARATOR);
845 /* Take account of a file being in the root ( / ) folder - ensure the returned value
846 * is at least one character long */
847 if (base) return g_strndup(path, (strlen(path)-strlen(base)) == 0 ? 1 : (strlen(path)-strlen(base)));
852 gboolean file_extension_match(const gchar *path, const gchar *ext)
857 if (!path) return FALSE;
858 if (!ext) return TRUE;
864 return (p > e && g_ascii_strncasecmp(path + p - e, ext, e) == 0);
867 gchar *remove_extension_from_path(const gchar *path)
869 const gchar *reg_ext;
871 if (!path) return NULL;
873 reg_ext = registered_extension_from_path(path);
875 return g_strndup(path, strlen(path) - (reg_ext == NULL ? 0 : strlen(reg_ext)));
878 void parse_out_relatives(gchar *path)
886 while (path[s] != '\0')
888 if (path[s] == G_DIR_SEPARATOR && path[s+1] == '.')
890 /* /. occurence, let's see more */
893 if (path[p] == G_DIR_SEPARATOR || path[p] == '\0')
895 /* /./ or /., just skip this part */
899 else if (path[p] == '.' && (path[p+1] == G_DIR_SEPARATOR || path[p+1] == '\0'))
901 /* /../ or /.., remove previous part, ie. /a/b/../ becomes /a/ */
904 while (path[t] != G_DIR_SEPARATOR && t > 0) t--;
909 if (s != t) path[t] = path[s];
914 if (t == 0 && path[t] == G_DIR_SEPARATOR) t++;
915 if (t > 1 && path[t-1] == G_DIR_SEPARATOR) t--;
919 gboolean file_in_path(const gchar *name)
924 gboolean ret = FALSE;
926 if (!name) return FALSE;
927 path = g_strdup(getenv("PATH"));
928 if (!path) return FALSE;
929 namel = path_from_utf8(name);
933 while (p < l && !ret)
937 while (path[e] != ':' && path[e] != '\0') e++;
940 f = g_build_filename(path + p, namel, NULL);
941 if (isfile(f)) ret = TRUE;
951 gboolean recursive_mkdir_if_not_exists(const gchar *path, mode_t mode)
953 if (!path) return FALSE;
957 gchar *npath = g_strdup(path);
963 if (p[0] == G_DIR_SEPARATOR || p[0] == '\0')
975 DEBUG_1("creating sub dir:%s", npath);
976 if (!mkdir_utf8(npath, mode))
978 log_printf("create dir failed: %s\n", npath);
984 if (!end) p[0] = G_DIR_SEPARATOR;
993 /* does filename utf8 to filesystem encoding first */
994 gboolean md5_get_digest_from_file_utf8(const gchar *path, guchar digest[16])
999 pathl = path_from_utf8(path);
1000 success = md5_get_digest_from_file(pathl, digest);
1007 gchar *md5_text_from_file_utf8(const gchar *path, const gchar *error_text)
1011 if (!md5_get_digest_from_file_utf8(path, digest)) return g_strdup(error_text);
1013 return md5_digest_to_text(digest);
1016 /* Download web file
1018 typedef struct _WebData WebData;
1022 GCancellable *cancellable;
1025 GtkWidget *progress;
1030 static void web_file_async_ready_cb(GObject *source_object, GAsyncResult *res, gpointer data)
1032 GError *error = NULL;
1033 WebData* web = data;
1034 gchar *tmp_filename;
1036 if (!g_cancellable_is_cancelled(web->cancellable))
1038 generic_dialog_close(web->gd);
1041 if (g_file_copy_finish(G_FILE(source_object), res, &error))
1043 tmp_filename = g_file_get_parse_name(web->tmp_g_file);
1044 g_free(tmp_filename);
1045 layout_set_path(web->lw, g_file_get_path(web->tmp_g_file));
1049 file_util_warning_dialog(_("Web file download failed"), error->message, GTK_STOCK_DIALOG_ERROR, NULL);
1052 g_object_unref(web->tmp_g_file);
1053 web->tmp_g_file = NULL;
1054 g_object_unref(web->cancellable);
1055 g_object_unref(web->web_file);
1058 static void web_file_progress_cb(goffset current_num_bytes, goffset total_num_bytes, gpointer data)
1060 WebData* web = data;
1062 if (!g_cancellable_is_cancelled(web->cancellable))
1064 gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(web->progress), (gdouble)current_num_bytes / total_num_bytes);
1068 static void download_web_file_cancel_button_cb(GenericDialog *gd, gpointer data)
1070 WebData* web = data;
1072 g_cancellable_cancel(web->cancellable);
1075 gboolean download_web_file(const gchar *text, gboolean minimized, gpointer data)
1078 LayoutWindow *lw = data;
1080 GError *error = NULL;
1085 FileFormatClass format_class;
1087 scheme = g_uri_parse_scheme(text);
1088 if (g_strcmp0("http", scheme) == 0 || g_strcmp0("https", scheme) == 0)
1090 format_class = filter_file_get_class(text);
1092 if (format_class == FORMAT_CLASS_IMAGE || format_class == FORMAT_CLASS_RAWIMAGE || format_class == FORMAT_CLASS_VIDEO || format_class == FORMAT_CLASS_DOCUMENT)
1094 tmp_dir = g_dir_make_tmp("geeqie_XXXXXX", &error);
1097 log_printf("Error: could not create temporary file n%s\n", error->message);
1098 g_error_free(error);
1104 web = g_new0(WebData, 1);
1107 web->web_file = g_file_new_for_uri(text);
1109 base = g_strdup(g_file_get_basename(web->web_file));
1110 web->tmp_g_file = g_file_new_for_path(g_build_filename(tmp_dir, base, NULL));
1112 web->gd = generic_dialog_new(_("Download web file"), "download_web_file", NULL, TRUE, download_web_file_cancel_button_cb, web);
1114 message = g_strconcat(_("Downloading "), base, NULL);
1115 generic_dialog_add_message(web->gd, GTK_STOCK_DIALOG_INFO, message, NULL, FALSE);
1117 web->progress = gtk_progress_bar_new();
1118 gtk_box_pack_start(GTK_BOX(web->gd->vbox), web->progress, FALSE, FALSE, 0);
1119 gtk_widget_show(web->progress);
1122 gtk_window_iconify(GTK_WINDOW(web->gd->dialog));
1125 gtk_widget_show(web->gd->dialog);
1126 web->cancellable = g_cancellable_new();
1127 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);
1144 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */