diff --git a/internal/agent/cursorlocal.go b/internal/agent/cursorlocal.go index 83a2c2f39..067a98607 100644 --- a/internal/agent/cursorlocal.go +++ b/internal/agent/cursorlocal.go @@ -85,7 +85,7 @@ func cursorLocalRoots() []string { return out } return append(proc.SystemDirs("/opt", "/usr/share", "/usr/lib"), filepath.Join(home, ".local", "share"), filepath.Join(home, "Applications"), - filepath.Join(home, ".local", "bin"), filepath.Join(home, "bin"), filepath.Join(home, "Downloads"), home) + filepath.Join(home, ".local", "bin"), filepath.Join(home, "bin"), appdir.Downloads(), filepath.Join(home, "Downloads"), home) } // findCursorLocal is the program of the Cursor Private Inference among the diff --git a/internal/appdir/appdir.go b/internal/appdir/appdir.go index 269fcf0a4..08e35aabf 100644 --- a/internal/appdir/appdir.go +++ b/internal/appdir/appdir.go @@ -149,7 +149,8 @@ func hasFiles(dir string) bool { // sharedFolder says whether dir is a folder every app or download shares: // /Applications and ~/Applications on a Mac, and the home folder, its -// Downloads, Desktop and Documents everywhere. Tests change it. +// Downloads, Desktop and Documents everywhere, under home and where the +// system keeps them (UserFolder). Tests change it. var sharedFolder = func(dir string) bool { var dirs []string if runtime.GOOS == "darwin" { @@ -157,8 +158,11 @@ var sharedFolder = func(dir string) bool { } if h, err := Home(); err == nil { dirs = append(dirs, h) - for _, d := range []string{"Downloads", "Desktop", "Documents"} { + for _, d := range []string{DownloadsFolder, DesktopFolder, DocumentsFolder} { dirs = append(dirs, filepath.Join(h, d)) + if p := UserFolder(d); p != "" { + dirs = append(dirs, p) // where the system keeps it, moved or not + } } if runtime.GOOS == "darwin" { dirs = append(dirs, filepath.Join(h, "Applications")) diff --git a/internal/appdir/userdirs.go b/internal/appdir/userdirs.go new file mode 100644 index 000000000..b5cdf30e3 --- /dev/null +++ b/internal/appdir/userdirs.go @@ -0,0 +1,135 @@ +package appdir + +import ( + "bufio" + "os" + "path/filepath" + "runtime" + "strings" +) + +// A user folder: Downloads, Desktop or Documents, as the system keeps it. +const ( + DownloadsFolder = "Downloads" + DesktopFolder = "Desktop" + DocumentsFolder = "Documents" +) + +// xdgNames are the user-dirs.dirs variables of each folder. +var xdgNames = map[string]string{ + DownloadsFolder: "XDG_DOWNLOAD_DIR", + DesktopFolder: "XDG_DESKTOP_DIR", + DocumentsFolder: "XDG_DOCUMENTS_DIR", +} + +// UserFolder is where the system keeps the user's folder kind (Downloads, +// Desktop or Documents), which the user or the system may have moved off +// home\kind: Windows' known folder (FOLDERID_Downloads, which OneDrive or +// the folder's Location tab moves to another drive), the XDG user folder +// on Linux and the BSDs ($XDG_CONFIG_HOME/user-dirs.dirs, written in the +// user's language, ~/下载 on a Chinese desktop), and ~/kind on a Mac, +// where it can't be moved. A failed lookup is home\kind, as before; "" +// with no usable home folder. +func UserFolder(kind string) string { + h, err := Home() + if err != nil { + return "" + } + return userFolderOn(runtime.GOOS, h, kind) +} + +// Downloads is UserFolder(DownloadsFolder). +func Downloads() string { return UserFolder(DownloadsFolder) } + +func userFolderOn(goos, home, kind string) string { + switch goos { + case "darwin": + case "windows": + if p := windowsFolder(home, kind); p != "" { + return p + } + default: + if p := xdgUserDir(home, kind); p != "" { + return p + } + } + return filepath.Join(home, kind) +} + +// knownFolder is Windows' path of the known folder kind and of the profile +// it belongs to ("" off Windows, or when it can't be read). Tests change it. +var knownFolder = osKnownFolder + +// windowsFolder is the known folder kind when home is the profile Windows +// keeps it for. A home magpie was given of its own (USERPROFILE set to +// another folder, as a test's or a portable setup's) keeps its own +// home\kind: the known folder is another home's. +func windowsFolder(home, kind string) string { + p, profile := knownFolder(kind) + if p == "" || profile == "" || !strings.EqualFold(filepath.Clean(profile), filepath.Clean(home)) { + return "" + } + return p +} + +// xdgUserDir is kind's folder from user-dirs.dirs, as xdg-user-dir reads +// it: a quoted "$HOME/…" or absolute path. A file that can't be read, or +// has no usable line for it, is "". +func xdgUserDir(home, kind string) string { + name := xdgNames[kind] + if name == "" { + return "" + } + cfg := Getenv("XDG_CONFIG_HOME") + if cfg == "" { + cfg = filepath.Join(home, ".config") + } + f, err := os.Open(filepath.Join(cfg, "user-dirs.dirs")) + if err != nil { + return "" + } + defer f.Close() + got := "" + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + k, v, ok := strings.Cut(line, "=") + if !ok || strings.TrimSpace(k) != name { + continue + } + if p := xdgValue(home, strings.TrimSpace(v)); p != "" { + got = p // the last one wins, as the shell sourcing it has it + } + } + if sc.Err() != nil { + return "" + } + return got +} + +// xdgValue is a user-dirs.dirs value as a path: "$HOME/x" under home, +// "/x" as it is, with a backslash keeping the character after it. Anything +// else (unquoted, relative, another variable) is "", as the spec allows +// only these two. +func xdgValue(home, v string) string { + if len(v) < 2 || v[0] != '"' || v[len(v)-1] != '"' { + return "" + } + var b strings.Builder + for i := 1; i < len(v)-1; i++ { + if v[i] == '\\' && i+1 < len(v)-1 { + i++ + } + b.WriteByte(v[i]) + } + s := b.String() + switch { + case s == "$HOME": + return home + case strings.HasPrefix(s, "$HOME/"): + return filepath.Join(home, filepath.FromSlash(s[len("$HOME/"):])) + case strings.HasPrefix(s, "/"): + return filepath.Clean(s) + } + return "" +} diff --git a/internal/appdir/userdirs_other.go b/internal/appdir/userdirs_other.go new file mode 100644 index 000000000..4f1a3d8b9 --- /dev/null +++ b/internal/appdir/userdirs_other.go @@ -0,0 +1,6 @@ +//go:build !windows + +package appdir + +// osKnownFolder has nothing off Windows. +func osKnownFolder(string) (path, profile string) { return "", "" } diff --git a/internal/appdir/userdirs_test.go b/internal/appdir/userdirs_test.go new file mode 100644 index 000000000..8db59aa37 --- /dev/null +++ b/internal/appdir/userdirs_test.go @@ -0,0 +1,182 @@ +package appdir + +import ( + "os" + "path/filepath" + "testing" +) + +// userDirsZH is user-dirs.dirs as xdg-user-dirs-update writes it on a +// Chinese desktop (Ubuntu 24.04, zh_CN.UTF-8): Downloads is ~/下载, not +// ~/Downloads (1Shin on Discord: an export joined $HOME/Downloads). +const userDirsZH = `# This file is written by xdg-user-dirs-update +# If you want to change or add directories, just edit the line you're +# interested in. All local changes will be retained on the next run. +# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped +# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an +# absolute path. No other format is supported. +# +XDG_DESKTOP_DIR="$HOME/桌面" +XDG_DOWNLOAD_DIR="$HOME/下载" +XDG_TEMPLATES_DIR="$HOME/模板" +XDG_PUBLICSHARE_DIR="$HOME/公共的" +XDG_DOCUMENTS_DIR="$HOME/文档" +XDG_MUSIC_DIR="$HOME/音乐" +XDG_PICTURES_DIR="$HOME/图片" +XDG_VIDEOS_DIR="$HOME/视频" +` + +func userDirsHome(t *testing.T, dirs string) string { + t.Helper() + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + if dirs != "" { + os.MkdirAll(filepath.Join(h, ".config"), 0o700) + if err := os.WriteFile(filepath.Join(h, ".config", "user-dirs.dirs"), []byte(dirs), 0o600); err != nil { + t.Fatal(err) + } + } + return h +} + +func fakeKnownFolder(t *testing.T, f func(kind string) (string, string)) { + t.Helper() + was := knownFolder + knownFolder = f + t.Cleanup(func() { knownFolder = was }) +} + +func TestUserFolderXDG(t *testing.T) { + h := userDirsHome(t, userDirsZH) + for kind, want := range map[string]string{ + DownloadsFolder: filepath.Join(h, "下载"), + DesktopFolder: filepath.Join(h, "桌面"), + DocumentsFolder: filepath.Join(h, "文档"), + } { + if got := userFolderOn("linux", h, kind); got != want { + t.Errorf("linux %s: %q, want %q", kind, got, want) + } + if got := userFolderOn("freebsd", h, kind); got != want { + t.Errorf("freebsd %s: %q, want %q", kind, got, want) + } + } + // A Mac's Downloads can't be moved: a user-dirs.dirs there is no one's. + if got, want := userFolderOn("darwin", h, DownloadsFolder), filepath.Join(h, "Downloads"); got != want { + t.Errorf("darwin: %q, want %q", got, want) + } +} + +func TestUserFolderXDGLines(t *testing.T) { + for _, c := range []struct { + name, dirs, want string + }{ + {"absolute", `XDG_DOWNLOAD_DIR="/mnt/data/dl"`, "/mnt/data/dl"}, + {"escaped", `XDG_DOWNLOAD_DIR="$HOME/my \"dl\""`, "~/my \"dl\""}, + {"spaces round =", ` XDG_DOWNLOAD_DIR = "$HOME/dl"`, "~/dl"}, + {"turned off", `XDG_DOWNLOAD_DIR="$HOME/"`, "~"}, + {"home itself", `XDG_DOWNLOAD_DIR="$HOME"`, "~"}, + {"the last wins", "XDG_DOWNLOAD_DIR=\"$HOME/a\"\nXDG_DOWNLOAD_DIR=\"$HOME/b\"", "~/b"}, + {"commented", `# XDG_DOWNLOAD_DIR="$HOME/a"`, "~/Downloads"}, + {"unquoted", `XDG_DOWNLOAD_DIR=$HOME/a`, "~/Downloads"}, + {"relative", `XDG_DOWNLOAD_DIR="a/b"`, "~/Downloads"}, + {"another variable", `XDG_DOWNLOAD_DIR="$XDG_DATA_HOME/a"`, "~/Downloads"}, + {"another folder only", `XDG_MUSIC_DIR="$HOME/a"`, "~/Downloads"}, + {"empty file", "\n", "~/Downloads"}, + } { + t.Run(c.name, func(t *testing.T) { + h := userDirsHome(t, c.dirs) + want := c.want + if want[0] == '/' { + want = filepath.FromSlash(want) + } else if want == "~" { + want = h + } else if len(want) > 1 && want[:2] == "~/" { + want = filepath.Join(h, filepath.FromSlash(want[2:])) + } + if got := userFolderOn("linux", h, DownloadsFolder); got != want { + t.Errorf("%q, want %q", got, want) + } + }) + } +} + +// With no user-dirs.dirs, or XDG_CONFIG_HOME unset (home/.config is read), +// or relative (ignored, as the spec asks). +func TestUserFolderXDGConfigHome(t *testing.T) { + h := userDirsHome(t, "") + if got, want := userFolderOn("linux", h, DownloadsFolder), filepath.Join(h, "Downloads"); got != want { + t.Errorf("no file: %q, want %q", got, want) + } + userDirsHome2 := func(cfg string) { + os.MkdirAll(filepath.Join(h, ".config"), 0o700) + os.WriteFile(filepath.Join(h, ".config", "user-dirs.dirs"), []byte(`XDG_DOWNLOAD_DIR="$HOME/dl"`), 0o600) + t.Setenv("XDG_CONFIG_HOME", cfg) + } + for _, cfg := range []string{"", "rel/cfg"} { + userDirsHome2(cfg) + if got, want := userFolderOn("linux", h, DownloadsFolder), filepath.Join(h, "dl"); got != want { + t.Errorf("XDG_CONFIG_HOME %q: %q, want %q", cfg, got, want) + } + } + other := t.TempDir() + os.WriteFile(filepath.Join(other, "user-dirs.dirs"), []byte(`XDG_DOWNLOAD_DIR="$HOME/other"`), 0o600) + t.Setenv("XDG_CONFIG_HOME", other) + if got, want := userFolderOn("linux", h, DownloadsFolder), filepath.Join(h, "other"); got != want { + t.Errorf("XDG_CONFIG_HOME set: %q, want %q", got, want) + } +} + +// Windows' Downloads is the known folder (moved to D:\ or OneDrive), when +// magpie's home is the profile Windows keeps it for. +func TestUserFolderWindows(t *testing.T) { + h := userDirsHome(t, userDirsZH) // not read on Windows + moved := filepath.Join(t.TempDir(), "OneDrive", "Downloads") + fakeKnownFolder(t, func(kind string) (string, string) { + if kind != DownloadsFolder { + return "", "" + } + return moved, h + }) + if got := userFolderOn("windows", h, DownloadsFolder); got != moved { + t.Errorf("moved: %q, want %q", got, moved) + } + if got, want := userFolderOn("windows", h, DesktopFolder), filepath.Join(h, "Desktop"); got != want { + t.Errorf("lookup failed: %q, want %q", got, want) + } + // Another home's known folder: magpie's own home keeps home\Downloads. + other := t.TempDir() + if got, want := userFolderOn("windows", other, DownloadsFolder), filepath.Join(other, "Downloads"); got != want { + t.Errorf("another home: %q, want %q", got, want) + } + fakeKnownFolder(t, func(string) (string, string) { return moved, "" }) + if got, want := userFolderOn("windows", h, DownloadsFolder), filepath.Join(h, "Downloads"); got != want { + t.Errorf("no profile: %q, want %q", got, want) + } +} + +// A data folder beside magpie in a moved Downloads isn't its portable one +// either (tangle778's case, in the folder the system keeps). +func TestSharedFolderMovedDownloads(t *testing.T) { + h := userDirsHome(t, userDirsZH) + moved := filepath.Join(h, "下载") + fakeKnownFolder(t, func(kind string) (string, string) { + if kind == DownloadsFolder { + return moved, h + } + return "", "" + }) + if UserFolder(DownloadsFolder) == filepath.Join(h, "Downloads") { + t.Skip("this system's Downloads can't be moved") + } + if !sharedFolder(moved) { + t.Errorf("%s not shared", moved) + } + if !sharedFolder(filepath.Join(h, "Downloads")) { + t.Error("home's Downloads not shared") + } + if sharedFolder(filepath.Join(moved, "magpie")) { + t.Error("a folder inside shared") + } +} diff --git a/internal/appdir/userdirs_windows.go b/internal/appdir/userdirs_windows.go new file mode 100644 index 000000000..f7654bdb5 --- /dev/null +++ b/internal/appdir/userdirs_windows.go @@ -0,0 +1,29 @@ +package appdir + +import "golang.org/x/sys/windows" + +var knownFolderIDs = map[string]*windows.KNOWNFOLDERID{ + DownloadsFolder: windows.FOLDERID_Downloads, + DesktopFolder: windows.FOLDERID_Desktop, + DocumentsFolder: windows.FOLDERID_Documents, +} + +// osKnownFolder is SHGetKnownFolderPath of kind and of the profile folder, +// made or not (KF_FLAG_DONT_VERIFY: without it a missing folder is an +// error; a caller that needs it there checks). Windows expands the +// %USERPROFILE% in it from the environment of a process's first call. +func osKnownFolder(kind string) (path, profile string) { + id := knownFolderIDs[kind] + if id == nil { + return "", "" + } + p, err := windows.KnownFolderPath(id, windows.KF_FLAG_DONT_VERIFY) + if err != nil { + return "", "" + } + pr, err := windows.KnownFolderPath(windows.FOLDERID_Profile, windows.KF_FLAG_DONT_VERIFY) + if err != nil { + return "", "" + } + return p, pr +} diff --git a/internal/appdir/userdirs_windows_test.go b/internal/appdir/userdirs_windows_test.go new file mode 100644 index 000000000..02ec72fc2 --- /dev/null +++ b/internal/appdir/userdirs_windows_test.go @@ -0,0 +1,49 @@ +package appdir + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "golang.org/x/sys/windows/registry" +) + +// The known folder read is Windows' own: the user's Downloads as Explorer +// keeps it in User Shell Folders (where a move to another drive or +// OneDrive is written), read only. Windows expands its %USERPROFILE% once +// a process, with the environment of the first call, so the check runs in +// a child of its own that makes that call here. +func TestKnownFolderIsExplorers(t *testing.T) { + if os.Getenv("MAGPIE_KNOWN_FOLDER_CHILD") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestKnownFolderIsExplorers$", "-test.v") + cmd.Env = append(os.Environ(), "MAGPIE_KNOWN_FOLDER_CHILD=1") + out, err := cmd.CombinedOutput() + t.Logf("%s", out) + if err != nil { + t.Fatal(err) + } + return + } + path, profile := osKnownFolder(DownloadsFolder) + if path == "" || profile == "" { + t.Fatalf("no known folder: %q, %q", path, profile) + } + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders`, registry.QUERY_VALUE) + if err != nil { + t.Skip("no User Shell Folders:", err) + } + defer k.Close() + v, _, err := k.GetStringValue("{374DE290-123F-4565-9164-39C4925E467B}") + if err != nil { + t.Skip("Downloads not in User Shell Folders:", err) + } + if v, err = registry.ExpandString(v); err != nil { + t.Fatal(err) + } + if !strings.EqualFold(filepath.Clean(v), filepath.Clean(path)) { + t.Errorf("known folder %q, Explorer's %q", path, v) + } + t.Logf("Downloads %s, profile %s", path, profile) +} diff --git a/internal/gui/backup.go b/internal/gui/backup.go index 75eb124c8..abefd5dca 100644 --- a/internal/gui/backup.go +++ b/internal/gui/backup.go @@ -10,6 +10,7 @@ import ( "path/filepath" "time" + "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/backup" "github.com/yetone/magpie/internal/davsync" "github.com/yetone/magpie/internal/edit" @@ -164,12 +165,16 @@ func busy(err error) error { return nil } -// downloads is where an export is saved: the Downloads folder, or home -// when there is none. +// downloads is where an export is saved: the Downloads folder the system +// keeps (appdir.Downloads: Windows' known folder, the XDG one on Linux, +// which 1Shin on Discord had moved off home\Downloads), else +// home\Downloads, else home when there is none. func downloads() string { home, _ := os.UserHomeDir() - if d := filepath.Join(home, "Downloads"); isDir(d) { - return d + for _, d := range []string{appdir.Downloads(), filepath.Join(home, "Downloads")} { + if d != "" && isDir(d) { + return d + } } return home } diff --git a/internal/gui/backup_test.go b/internal/gui/backup_test.go index 8c1e026cd..ff4d8fbda 100644 --- a/internal/gui/backup_test.go +++ b/internal/gui/backup_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "runtime" "strings" "testing" @@ -91,3 +92,36 @@ func TestBackupLibraryRoundTrip(t *testing.T) { t.Fatalf("instructions: %q", iv.Shared) } } + +// 1Shin on Discord: an export joined $HOME/Downloads. On a Linux desktop in +// Chinese, Downloads is ~/下载 (user-dirs.dirs); the export goes there, and +// to home\Downloads when the folder named there isn't one. +func TestExportGoesToTheSystemsDownloads(t *testing.T) { + if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { + t.Skip("user-dirs.dirs is read on Linux and the BSDs (appdir's tests fake Windows' known folder)") + } + h := sandboxHome(t) + os.MkdirAll(filepath.Join(h, ".config"), 0o700) + os.WriteFile(filepath.Join(h, ".config", "user-dirs.dirs"), []byte("XDG_DOWNLOAD_DIR=\"$HOME/下载\"\n"), 0o600) + mux := http.NewServeMux() + backupRoutes(mux, folderOnly{}) + export := func() string { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/backup/export", strings.NewReader(`{"pass":"pw"}`))) + if w.Code != 200 { + t.Fatalf("export: %d %s", w.Code, w.Body) + } + var out struct{ Path string } + json.Unmarshal(w.Body.Bytes(), &out) + return filepath.Dir(filepath.Join(h, strings.TrimPrefix(out.Path, "~"))) + } + os.MkdirAll(filepath.Join(h, "Downloads"), 0o700) + if got, want := export(), filepath.Join(h, "Downloads"); got != want { + t.Errorf("~/下载 not made yet: saved in %s, want %s", got, want) + } + os.MkdirAll(filepath.Join(h, "下载"), 0o700) + if got, want := export(), filepath.Join(h, "下载"); got != want { + t.Errorf("saved in %s, want %s", got, want) + } +}