Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(fix) respect OS Documents/Music locations for defaults (#522) (#523)

rafi612a2589ece2b5b
diff --git a/.specify/bugs/os-folders-defaults/assessment.md b/.specify/bugs/os-folders-defaults/assessment.md
new file mode 100644
index 00000000..52815ba8
--- /dev/null
+++ b/.specify/bugs/os-folders-defaults/assessment.md
@@ -0,0 +1,77 @@
+# Bug Assessment: OS Documents/Music locations ignored for default folders
+
+- **Slug**: os-folders-defaults
+- **Created**: 2026-11-05
+- **Source**: https://github.com/nota-daw/nota/issues/522 (host: github.com, allowlisted; fetch permitted without prompting)
+- **Verdict**: valid
+- **Severity**: medium (wrong default browser/save locations on relocated/translated Documents/Music; creates unwanted `~/Documents`; no data loss or crash, but affects every Linux user with custom XDG user-dirs and Windows users with redirected Known Folders)
+
+## Report (verbatim or summarized)
+
+> **Respect OS Documents/Music locations for default Projects/Samples folders** — Nota hardcodes `~/Documents/Nota Projects` (`SettingsService.ResolvedProjectsFolder`) and `~/Music/Nota Samples`, ignoring XDG user-dirs on Linux and Known Folders on Windows. With relocated/translated Documents this creates an unwanted `~/Documents`.
+>
+> Expected: resolve via `XDG_DOCUMENTS_DIR` / `XDG_MUSIC_DIR` on Linux, `MyDocuments`/`MyMusic` on Windows/macOS, with `~/Documents` fallback; existing `settings.json` override always wins.
+
+Source URL: https://github.com/nota-daw/nota/issues/522
+
+## Symptom
+
+On Linux with a relocated or translated Documents folder (e.g. `~/Dokumenty`), and on Windows with redirected Documents/Music (OneDrive, custom location), Nota still browses/suggests `~/Documents/Nota Projects` and `~/Music/Nota Samples`, creating the hardcoded directory. Expected: defaults follow the OS locations; an explicit `settings.json` `ProjectsFolder`/`SamplesFolder` always wins.
+
+## Reproduction
+
+1. On Linux, set `XDG_DOCUMENTS_DIR="$HOME/Dokumenty"` in `~/.config/user-dirs.dirs` (or use a system with translated user dirs).
+2. Ensure `settings.json` has empty `ProjectsFolder`/`SamplesFolder` (defaults).
+3. Start Nota, open browser Files/Projects tab or Save dialog (`MainWindow.Files.cs`).
+4. Observed: root/suggested location is `~/Documents/Nota Projects`, and `~/Documents` gets created. Expected: `~/Dokumenty/Nota Projects`.
+
+[NEEDS CLARIFICATION: exact behavior when `XDG_*_DIR` is disabled (`"$HOME"`) — fallback should be `$HOME/Nota Projects`, not recreating `Documents`. To confirm with reporter/maintainer.]
+
+## Suspected Code Paths
+
+- `src/managed/Nota.Infrastructure/Settings/SettingsService.cs:45-51` — `ResolvedSamplesFolder()` / `ResolvedProjectsFolder()` do `Path.Combine(Home, "Music", "Nota Samples")` and `Path.Combine(Home, "Documents", "Nota Projects")` when the setting is empty, then `EnsureDir()`. This is the root.
+- `src/managed/Nota.Infrastructure/NotaPaths.cs:21` — `Home => Environment.GetFolderPath(UserProfile)` (`~`); no XDG user-dirs or Known-Folder lookup anywhere.
+- `src/managed/Nota.Application/Settings.cs:37-40` — `SamplesFolder`/`ProjectsFolder` empty-means-default contract; unchanged by fix.
+- Callers that inherit the bug (no change needed, they use the resolvers): `src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs:633,704,906`, `src/managed/Nota.App/MainWindow.Files.cs:37,231,387`, `src/managed/Nota.App/PreferencesWindow.cs:946,949`, `src/managed/Nota.Infrastructure/Mosaic/MosaicLibrary.cs:32,162`, `src/managed/Nota.Infrastructure/SampleStore/SampleStore.cs:38`.
+
+Grep confirms no existing `XDG_DOCUMENTS`, `user-dirs.dirs`, `xdg-user-dir`, or `SpecialFolder.MyDocuments`/`MyMusic` handling for these defaults.
+
+## Root Cause Hypothesis
+
+Defaults are hardcoded to English `~/Documents` / `~/Music` instead of resolving the OS user folders. Confidence: **high** — directly visible in `SettingsService.cs:45-51`; Linux XDG user-dirs and Windows Known Folders are never consulted. `.NET Environment.SpecialFolder.MyDocuments` alone is not sufficient as the fix without verification on Linux, hence an explicit `user-dirs.dirs` parser is proposed.
+
+## Proposed Remediation
+
+**Preferred**: add a small testable resolver in `Nota.Infrastructure` (next to `NotaPaths`), used by both `Resolved*Folder()` methods:
+
+- Linux: parse `$XDG_CONFIG_HOME/user-dirs.dirs`, fallback `~/.config/user-dirs.dirs`; keys `XDG_DOCUMENTS_DIR` / `XDG_MUSIC_DIR`; handle quotes, `$HOME/...`, absolute paths, missing file, and disabled (`"$HOME"` → `$HOME/<fallback-name>`); final fallback `~/Documents` / `~/Music`. No shell-out to `xdg-user-dir` (deterministic, testable, no process spawn on UI path).
+- Windows/macOS: `Environment.SpecialFolder.MyDocuments` / `MyMusic` (respects redirection/OneDrive), fallback to `Home/Documents` / `Home/Music` when empty.
+- Keep contract: non-empty `settings.json` value always wins; keep `EnsureDir()` best-effort creation; no migration of existing `~/Documents/Nota Projects`.
+- Shape: e.g. `UserDirs.GetDocumentsDir(Home)` / `GetMusicDir(Home)` with injectable env/file readers for tests; `SettingsService` appends `Nota Projects` / `Nota Samples`.
+
+**Alternatives**:
+- Use only `Environment.SpecialFolder.MyDocuments/MyMusic` everywhere: smaller, but relies on undocumented .NET-on-Linux XDG mapping; less deterministic for tests.
+- Shell out to `xdg-user-dir DOCUMENTS/MUSIC`: reuses freedesktop logic, but adds process dependency and failure modes on startup/UI path.
+
+**Files likely to change**:
+- `src/managed/Nota.Infrastructure/Settings/SettingsService.cs`
+- `src/managed/Nota.Infrastructure/NotaPaths.cs` (or new `UserDirs.cs` next to it)
+- `tests/Nota.SmokeTest/*` (new resolver tests; existing `SampleStoreTests.cs:178-179` fakes remain valid)
+
+**Tests to add or update**:
+- Parser: quoted values, `$HOME` expansion, absolute path, missing file, disabled (`$HOME`), `XDG_CONFIG_HOME` override.
+- Resolver: Linux XDG hit, fallback to `~/Documents`/`~/Music`; Windows `MyDocuments` path when available.
+- Existing smoke test must stay green (`scripts/build-linux.sh` / `scripts/build.sh`).
+
+## Risks & Considerations
+
+- Creating directories stays best-effort; permission failures must remain swallowed (existing behavior).
+- Disabled Documents (`XDG_DOCUMENTS_DIR="$HOME"`) must not recreate `~/Documents` — use `$HOME/Nota Projects`.
+- Localized names with spaces/Unicode must survive parsing and `Path.Combine`.
+- No audio-thread impact (settings/UI path only); no C ABI change; no new dependency (AGPL hygiene clean).
+- User-visible default path change needs `CHANGELOG.md [Unreleased]` entry; `nota-docs`/`nota-features` only if maintainers deem the default-location change user-visible enough.
+
+## Open Questions
+
+- [NEEDS CLARIFICATION: disabled-dir fallback — confirm `$HOME/Nota Projects` vs `~/Documents/Nota Projects` when `XDG_DOCUMENTS_DIR="$HOME"`.]
+- [NEEDS CLARIFICATION: should Windows also migrate existing custom-folder users, or only affect fresh defaults? Presumed defaults-only.]
diff --git a/.specify/bugs/os-folders-defaults/fix.md b/.specify/bugs/os-folders-defaults/fix.md
new file mode 100644
index 00000000..00fb826c
--- /dev/null
+++ b/.specify/bugs/os-folders-defaults/fix.md
@@ -0,0 +1,46 @@
+# Bug Fix: OS Documents/Music locations for default folders
+
+- **Slug**: os-folders-defaults
+- **Fixed**: 2026-11-05
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+Defaults for the Projects/Samples library now resolve through the OS user folders: freedesktop `user-dirs.dirs` on Linux, Known Folders (`MyDocuments`/`MyMusic`) on Windows/macOS, with `~/Documents` / `~/Music` fallback. An explicit `settings.json` value still always wins; directory creation stays best-effort.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/managed/Nota.Infrastructure/UserDirs.cs` | added | XDG parser + OS-dispatched resolver, pure/testable parts `internal` |
+| `src/managed/Nota.Infrastructure/Settings/SettingsService.cs` | modified | defaults via `UserDirs.GetDocumentsDir()` / `GetMusicDir()`; removed now-unused `Home` |
+| `tests/Nota.SmokeTest/UserDirsTests.cs` | added test | 13 checks: parser, disabled dirs, fallbacks, XDG path |
+| `tests/Nota.SmokeTest/Program.cs` | modified | `--user-dirs` standalone run + full-run wiring |
+| `CHANGELOG.md` | modified | `[Unreleased] Fixed` entry referencing #522 |
+| Review follow-up (PR #523) | modified | `Unquote()` decodes `\"` `\\` `\$` `` \` `` inside quotes (P2); test expectations built with `Path.Combine` so they hold on Windows (P1); +2 checks (15 total) |
+
+## Diff Highlights (optional)
+
+- `SettingsService.ResolvedProjectsFolder()` default changed from `Path.Combine(Home, "Documents", "Nota Projects")` to `Path.Combine(UserDirs.GetDocumentsDir(), "Nota Projects")` (same shape for samples).
+- Disabled XDG dir (`XDG_*_DIR="$HOME"`) resolves to `$HOME`, so the final default is `$HOME/Nota Projects` instead of recreating `~/Documents`.
+
+## Tests Added or Updated
+
+- `UserDirsTests.Run` — quoted `$HOME` expansion, absolute path with spaces, missing key → null, disabled `$HOME`/`$HOME/` → home, unquoted value, Linux hit/fallback/disabled, Known-Folder hit/fallback, `user-dirs.dirs` path default + `XDG_CONFIG_HOME` override.
+
+## Local Verification
+
+- Commands run: `dotnet build src/managed/Nota.Infrastructure/Nota.Infrastructure.csproj` → success (1 pre-existing nullable warning in `LanguageCatalog.cs`, unrelated).
+- `dotnet run --project tests/Nota.SmokeTest -- --user-dirs` → `USER DIRS PASSED` (13/13).
+- `dotnet run --project tests/Nota.SmokeTest -- --linux-desktop` → `LINUX DESKTOP PASSED` (no regression in neighbouring area).
+- Full `scripts/build-linux.sh` not run (heavy native+full-smoke); recommended before PR.
+
+## Deviations from Assessment
+
+None. Open question on disabled dirs resolved as assessed: base returns `$HOME`, giving `$HOME/Nota Projects` / `$HOME/Nota Samples`.
+
+## Follow-ups
+
+- Run `scripts/build-linux.sh` (full smoke) before opening the PR; target `develop`, `Closes #522`.
+- Consider `nota-docs`/`nota-features` only if maintainers deem the changed default location user-visible enough (CHANGELOG entry already added).
diff --git a/.specify/bugs/os-folders-defaults/test.md b/.specify/bugs/os-folders-defaults/test.md
new file mode 100644
index 00000000..c115f098
--- /dev/null
+++ b/.specify/bugs/os-folders-defaults/test.md
@@ -0,0 +1,52 @@
+# Bug Verification: OS Documents/Music locations for default folders
+
+- **Slug**: os-folders-defaults
+- **Tested**: 2026-11-05
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+The original symptom no longer reproduces through the production path, the 13 new checks pass, and the neighbouring Linux-desktop suite shows no regression.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (post-fix, XDG hit) | harness printing `UserDirs` with `HOME=/tmp/opencode/fakehome`, `user-dirs.dirs` → `Dokumenty`/`Muzyka` | pass | `DOC=/tmp/opencode/fakehome/Dokumenty` (old code gave `…/Documents`) |
+| Reproduction (post-fix, fallback) | same harness with empty home, no `user-dirs.dirs` | pass | `DOC=…/Documents`, `MUS=…/Music` as designed |
+| New / updated tests | `dotnet run --project tests/Nota.SmokeTest -- --user-dirs` | pass | 13/13, `USER DIRS PASSED` |
+| Regression suite | `dotnet run --project tests/Nota.SmokeTest -- --linux-desktop` | pass | `LINUX DESKTOP PASSED`, engine starts |
+| Lint / type-check | `dotnet build` of touched projects (via the runs above) | pass | only pre-existing nullable warning in `LanguageCatalog.cs` |
+| Hardcode sweep | grep `"Documents"` / `"Music", "Nota` in source | pass | only fallback names in `UserDirs.cs` + tests remain |
+| Full gate | `scripts/build-linux.sh` | fail (2, unrelated) | only `RenderPoolTests` overload timing checks fail (see below); everything else green |
+
+## Output Excerpts
+
+```
+HOME=/tmp/opencode/fakehome
+DOC=/tmp/opencode/fakehome/Dokumenty
+MUS=/tmp/opencode/fakehome/Muzyka
+...
+HOME=/tmp/opencode/emptyhome
+DOC=/tmp/opencode/emptyhome/Documents
+MUS=/tmp/opencode/emptyhome/Music
+USER DIRS PASSED
+LINUX DESKTOP PASSED
+```
+
+## Residual Risks
+
+- Full `scripts/build-linux.sh` run 2026-11-05: `SMOKE TEST FAILED (2)` — both are
+ `RenderPoolTests` overload timing checks (`100 of 4125 blocks late after warm-up`,
+ `at most 6 late blocks within 50 ms`). They fail consistently on this machine
+ independent of this change (engine render-pool timing, no settings/UI path involved;
+ same failures documented before in `.specify/bugs/render-pool-review-232/test.md` and
+ `.specify/bugs/dsp-perf-regressions/test.md`). Owner's call: ignored for this PR, to be
+ fixed separately.
+- Windows/macOS Known-Folder branch covered by injected-path unit checks only, not by a real redirected-folder machine.
+
+## Recommendation
+
+Close the bug — verified end-to-end. Open the PR against `develop` with `Closes #522` after the full build passes.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 22b98375..4e919e39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Fixed
+- **Default Projects/Samples folders follow the OS locations** (#522): the browser and
+ save dialogs no longer default to hardcoded `~/Documents/Nota Projects` and
+ `~/Music/Nota Samples`. On Linux they read `user-dirs.dirs` (`XDG_DOCUMENTS_DIR`,
+ `XDG_MUSIC_DIR`), on Windows/macOS the Known Folders, so a relocated or translated
+ Documents folder no longer grows an unwanted `~/Documents`. An explicit folder in
+ Settings still always wins.
- **Nota Remote on iPhone and iPad launches several clips at once** (#512): touching two or
more clips on the Scenes screen together launched none of them, or only one — iOS Safari
only sends a tap for a single finger. Every clip, scene and Stop button now takes its own
diff --git a/src/managed/Nota.Infrastructure/Settings/SettingsService.cs b/src/managed/Nota.Infrastructure/Settings/SettingsService.cs
index d2c311b6..0e7b320a 100644
--- a/src/managed/Nota.Infrastructure/Settings/SettingsService.cs
+++ b/src/managed/Nota.Infrastructure/Settings/SettingsService.cs
@@ -40,15 +40,13 @@ public sealed class SettingsService : ISettingsService
Changed?.Invoke();
}
- private static string Home => NotaPaths.Home;
-
public string ResolvedSamplesFolder()
=> EnsureDir(string.IsNullOrWhiteSpace(Current.SamplesFolder)
- ? Path.Combine(Home, "Music", "Nota Samples") : Current.SamplesFolder);
+ ? Path.Combine(UserDirs.GetMusicDir(), "Nota Samples") : Current.SamplesFolder);
public string ResolvedProjectsFolder()
=> EnsureDir(string.IsNullOrWhiteSpace(Current.ProjectsFolder)
- ? Path.Combine(Home, "Documents", "Nota Projects") : Current.ProjectsFolder);
+ ? Path.Combine(UserDirs.GetDocumentsDir(), "Nota Projects") : Current.ProjectsFolder);
public string PresetsFolder() => NotaPaths.SubDir("presets");
diff --git a/src/managed/Nota.Infrastructure/UserDirs.cs b/src/managed/Nota.Infrastructure/UserDirs.cs
new file mode 100644
index 00000000..cebcb57b
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/UserDirs.cs
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// OS user folders for the library defaults (#522): Linux reads freedesktop user-dirs
+// (translated/relocated Documents/Music), Windows/macOS use their Known Folders, so a
+// non-English home does not grow an unwanted ~/Documents. Pure except for the file read
+// and SpecialFolder lookup on the production path; the smoke test drives the pure parts.
+
+using System.Text;
+
+namespace Nota.Infrastructure;
+
+public static class UserDirs
+{
+ /// <summary>Base folder user projects live in (without "Nota Projects").</summary>
+ public static string GetDocumentsDir()
+ => GetKnownDir("DOCUMENTS", "Documents", Environment.SpecialFolder.MyDocuments);
+
+ /// <summary>Base folder the sample library lives in (without "Nota Samples").</summary>
+ public static string GetMusicDir()
+ => GetKnownDir("MUSIC", "Music", Environment.SpecialFolder.MyMusic);
+
+ internal static string GetKnownDir(string xdgName, string fallbackName, Environment.SpecialFolder folder)
+ {
+ string home = NotaPaths.Home;
+ if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS())
+ {
+ try
+ {
+ string known = Environment.GetFolderPath(folder);
+ if (!string.IsNullOrWhiteSpace(known)) return known;
+ }
+ catch { /* best-effort: fall through to ~/fallback */ }
+ return Path.Combine(home, fallbackName);
+ }
+
+ string? content = TryReadXdgFile(home);
+ return ResolveBaseDir(xdgName, fallbackName, home, content, specialFolderPath: null, useXdg: true);
+ }
+
+ internal static string ResolveBaseDir(string xdgName, string fallbackName, string home, string? fileContent, string? specialFolderPath, bool useXdg)
+ {
+ if (!useXdg)
+ return !string.IsNullOrWhiteSpace(specialFolderPath) ? specialFolderPath : Path.Combine(home, fallbackName);
+ string? parsed = ParseXdgDir(fileContent, xdgName, home);
+ return !string.IsNullOrWhiteSpace(parsed) ? parsed : Path.Combine(home, fallbackName);
+ }
+
+ internal static string GetXdgFilePath(string home, string? xdgConfigHome)
+ => Path.Combine(string.IsNullOrEmpty(xdgConfigHome) ? Path.Combine(home, ".config") : xdgConfigHome, "user-dirs.dirs");
+
+ internal static string? TryReadXdgFile(string home)
+ {
+ try
+ {
+ string path = GetXdgFilePath(home, Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"));
+ return File.Exists(path) ? File.ReadAllText(path) : null;
+ }
+ catch { return null; }
+ }
+
+ internal static string? ParseXdgDir(string? fileContent, string key, string home)
+ {
+ if (string.IsNullOrEmpty(fileContent) || string.IsNullOrEmpty(home)) return null;
+ string prefix = "XDG_" + key + "_DIR=";
+ foreach (var rawLine in fileContent.Split('\n'))
+ {
+ string line = rawLine.Trim();
+ if (line.Length == 0 || line[0] == '#') continue;
+ if (!line.StartsWith(prefix, StringComparison.Ordinal)) continue;
+ string value = line[prefix.Length..].Trim();
+ if (value.Length == 0) return null;
+ if (value[0] == '"')
+ // Quoted: ends at the first *unescaped* quote; \" \\ \$ \` decode
+ // to their literal char (shell double-quote rules, the escaping
+ // xdg-user-dirs-update emits), so My\"Docs keeps its quote.
+ value = Unquote(value[1..]);
+ else
+ {
+ int hash = value.IndexOf('#');
+ if (hash >= 0) value = value[..hash];
+ value = value.Trim().Trim('"', '\'');
+ }
+ if (value.Length == 0) return null;
+ // Disabled per the spec ($HOME alone): keep everything under $HOME so a
+ // disabled Documents dir is not recreated.
+ string trimmed = value.TrimEnd('/', '\\');
+ if (trimmed is "$HOME" || trimmed.Equals(home.TrimEnd('/', '\\'), StringComparison.Ordinal))
+ return home;
+ if (value.StartsWith("$HOME/", StringComparison.Ordinal))
+ return Path.Combine(home, value["$HOME/".Length..]);
+ if (value.StartsWith("$HOME", StringComparison.Ordinal))
+ return home + value["$HOME".Length..];
+ if (Path.IsPathRooted(value)) return value;
+ return Path.Combine(home, value);
+ }
+ return null;
+ }
+
+ internal static string Unquote(string rest)
+ {
+ var sb = new StringBuilder(rest.Length);
+ for (int i = 0; i < rest.Length; i++)
+ {
+ char c = rest[i];
+ if (c == '"') break;
+ if (c == '\\' && i + 1 < rest.Length && rest[i + 1] is '$' or '`' or '"' or '\\')
+ {
+ sb.Append(rest[i + 1]);
+ i++;
+ }
+ else sb.Append(c);
+ }
+ return sb.ToString();
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 26fe975f..fabcb6fa 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -433,6 +433,15 @@ if (args.Length >= 1 && args[0] == "--linux-desktop")
return failures == 0 ? 0 : 1;
}
+// OS user-folder defaults alone: `--user-dirs` (#522). Also part of the full run.
+if (args.Length >= 1 && args[0] == "--user-dirs")
+{
+ Console.WriteLine("-- user dirs --");
+ foreach (var (ok, label) in UserDirsTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "USER DIRS PASSED" : $"USER DIRS FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+
// Sends stay out of undo and automation: `--sends` (specs/069). Also part of the full run.
if (args.Length >= 1 && args[0] == "--sends")
{
@@ -15562,6 +15571,9 @@ foreach (var (ok, label) in SectionRearrangeTests.Run()) Check(ok, label);
Console.WriteLine("-- linux desktop --");
foreach (var (ok, label) in LinuxDesktopTests.Run()) Check(ok, label);
+Console.WriteLine("-- user dirs --");
+foreach (var (ok, label) in UserDirsTests.Run()) Check(ok, label);
+
Console.WriteLine("-- range clipboard --");
foreach (var (ok, label) in RangeClipboardTests.Run()) Check(ok, label);
diff --git a/tests/Nota.SmokeTest/UserDirsTests.cs b/tests/Nota.SmokeTest/UserDirsTests.cs
new file mode 100644
index 00000000..f6805236
--- /dev/null
+++ b/tests/Nota.SmokeTest/UserDirsTests.cs
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// OS user-folder defaults (#522): the XDG parser and the resolver fallbacks. Pure.
+// Expected paths are built with Path.Combine so the checks hold on every OS.
+// Runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --user-dirs`.
+
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class UserDirsTests
+{
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ const string home = "/home/u";
+
+ var quoted = UserDirs.ParseXdgDir("XDG_DOCUMENTS_DIR=\"$HOME/Dokumenty\"\n", "DOCUMENTS", home);
+ yield return (quoted == Path.Combine(home, "Dokumenty"), "userdirs: quoted $HOME/Documents parses with a translated name");
+
+ var spaced = UserDirs.ParseXdgDir("XDG_MUSIC_DIR=\"/media/dane/Muzyka moja\"\n", "MUSIC", home);
+ yield return (spaced == "/media/dane/Muzyka moja", "userdirs: an absolute path with spaces survives");
+
+ var escapedQuote = UserDirs.ParseXdgDir("XDG_DOCUMENTS_DIR=\"$HOME/My\\\"Docs\"\n", "DOCUMENTS", home);
+ yield return (escapedQuote == Path.Combine(home, "My\"Docs"), "userdirs: an escaped quote inside quotes survives");
+
+ var escapedBackslash = UserDirs.ParseXdgDir("XDG_MUSIC_DIR=\"$HOME/a\\\\b\"\n", "MUSIC", home);
+ yield return (escapedBackslash == Path.Combine(home, "a\\b"), "userdirs: an escaped backslash decodes to one");
+
+ var missing = UserDirs.ParseXdgDir("# comment\n\nXDG_DOWNLOAD_DIR=\"$HOME/Pobrane\"\n", "DOCUMENTS", home);
+ yield return (missing is null, "userdirs: a missing key parses to null (fallback applies)");
+
+ var disabled = UserDirs.ParseXdgDir("XDG_DOCUMENTS_DIR=\"$HOME\"\n", "DOCUMENTS", home);
+ yield return (disabled == home, "userdirs: a disabled dir ($HOME) resolves to home, not ~/Documents");
+
+ var disabledSlash = UserDirs.ParseXdgDir("XDG_DOCUMENTS_DIR=\"$HOME/\"\n", "DOCUMENTS", home);
+ yield return (disabledSlash == home, "userdirs: a disabled dir ($HOME/) resolves to home too");
+
+ var unquoted = UserDirs.ParseXdgDir("XDG_DOCUMENTS_DIR=$HOME/Docs\n", "DOCUMENTS", home);
+ yield return (unquoted == Path.Combine(home, "Docs"), "userdirs: an unquoted $HOME value still expands");
+
+ var hit = UserDirs.ResolveBaseDir("DOCUMENTS", "Documents", home, "XDG_DOCUMENTS_DIR=\"$HOME/Dokumenty\"\n", null, useXdg: true);
+ yield return (hit == Path.Combine(home, "Dokumenty"), "userdirs: linux hit uses the XDG dir");
+
+ var fallback = UserDirs.ResolveBaseDir("DOCUMENTS", "Documents", home, null, null, useXdg: true);
+ yield return (fallback == Path.Combine(home, "Documents"), "userdirs: missing user-dirs falls back to ~/Documents");
+
+ var disabledBase = UserDirs.ResolveBaseDir("DOCUMENTS", "Documents", home, "XDG_DOCUMENTS_DIR=\"$HOME\"\n", null, useXdg: true);
+ yield return (disabledBase == home, "userdirs: disabled XDG dir falls back to home, not ~/Documents");
+
+ var known = UserDirs.ResolveBaseDir("DOCUMENTS", "Documents", home, null, @"D:\Docs", useXdg: false);
+ yield return (known == @"D:\Docs", "userdirs: redirected Known Folder wins on Windows/macOS");
+
+ var knownFallback = UserDirs.ResolveBaseDir("MUSIC", "Music", home, null, " ", useXdg: false);
+ yield return (knownFallback == Path.Combine(home, "Music"), "userdirs: empty Known Folder falls back to ~/Music");
+
+ var cfgDefault = UserDirs.GetXdgFilePath(home, null);
+ yield return (cfgDefault == Path.Combine(home, ".config", "user-dirs.dirs"), "userdirs: default user-dirs path is ~/.config/user-dirs.dirs");
+
+ var cfgOverride = UserDirs.GetXdgFilePath(home, "/tmp/xdg");
+ yield return (cfgOverride == Path.Combine("/tmp/xdg", "user-dirs.dirs"), "userdirs: XDG_CONFIG_HOME relocates user-dirs.dirs");
+ }
+}