From 42dc08f514751849ac755aeade0ba5748ab925b5 Mon Sep 17 00:00:00 2001 From: Gaebabi <45709904+Gaebabi@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:52:58 +0900 Subject: [PATCH 1/6] [1/1 Folder indexing] Preserve small drive segments and avoid redundant traversal --- Directory.Build.props | 2 +- docs/FOLDER_MONITORING.md | 6 +- src/macos/Info.plist | 4 +- src/platforms/resources/FolderChanges.cs | 41 +++-- src/platforms/resources/FolderMonitor.cs | 157 ++++++++++++------ src/platforms/resources/FolderUsage.cs | 7 +- src/platforms/resources/FolderUsageCache.cs | 12 +- src/windows/DriveUsagePanel.cs | 65 ++++++-- tests/hardware/PersistentFolderContracts.cs | 31 +++- tests/model-providers-ui/FolderUiContracts.cs | 30 +++- 10 files changed, 260 insertions(+), 95 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index d03a60a..e141a91 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 1.45.9 + 1.45.10 10.0.15 diff --git a/docs/FOLDER_MONITORING.md b/docs/FOLDER_MONITORING.md index 4e5107f..9a5a5a6 100644 --- a/docs/FOLDER_MONITORING.md +++ b/docs/FOLDER_MONITORING.md @@ -14,7 +14,7 @@ The visible scan shares one metadata budget across all configured drives: at mos A spinner appears immediately to the right of a drive's capacity label while uncached directory measurement is active. Cached traversal, permission requests and idle waits do not keep it spinning. It clears after every work slice, completion, cancellation and failure, and does not spin for unrelated drives. The tooltip reports indexed folder/file counts so a large first index shows actual progress. Its animation stops when the indicator is hidden. -The Windows gauge keeps drive metadata above a separate12px allocation bar. Tracked folders use opaque colors with diagonal texture and visible separators; other used space is neutral and free space stays unfilled. Wide folder segments show their share directly. Small segments retain their measured width and expose the exact share on hover. Drives without tracked folders use the same used/free scale. +The Windows gauge keeps drive metadata above a separate12px allocation bar. Tracked folders use opaque colors with diagonal texture; other used space is neutral and free space stays unfilled. Wide folder segments show their share directly. A positive allocation smaller than one screen pixel gets one colored pixel, with separators reserved for wider segments. The tooltip retains the actual allocation and share. Drives without tracked folders use the same used/free scale. CPU, memory, GPU and VRAM use the same separated metadata/current-percentage bars. Quarter marks help compare utilization; missing readings stay empty with an unavailable value. Historical trend graphs remain in the resource tooltip rather than behind the text. @@ -24,6 +24,10 @@ Up to eight folders can be tracked per drive. Paths must be absolute and inside Folder measurements run independently after configuration changes. The initial measurement reads tracked trees in bounded cancellable slices and checkpoints directory snapshots, file allocations and pending changes together. Windows filesystem notifications wake the indexer; journal replay identifies actual changes and ignores timestamp-only activity that cannot change allocation. Notifications are grouped for two seconds, and unchanged subtrees are not enumerated again. Cached readings remain available between slices. Root/ancestor identity is checked when restoring an index, rather than repeatedly while unchanged monitoring is idle. Allocation totals for unrelated drives are reused. New or renamed trees are measured at their new paths, deleted entries are removed, and hard-link allocation is counted once per drive. Idle folders have no recurring full-tree scan. Very large first indexes can take longer than one minute and retain completed work when closed. +The monitor retains each drive's journal status across scan slices. A filesystem change triggers journal replay only on the affected drive with a readable journal. A drive without journal support, such as a mapped drive, can finish its first bounded measurement and update changed directories from live notifications. The monitor rechecks journal support when the watcher resets or the user requests a refresh. Idle index retries consult known failures and reuse successful directory snapshots. + +Metadata changes on a tracked folder itself recheck its identity and listing access. Directory timestamp notices generated by traversal do not invalidate their parent listings. Structural changes, file allocation changes, and attribute or security notifications still refresh the affected data. A routine file change does not discard the folder's directory snapshots. + Each completed folder/work slice is published immediately. Indexing does not overlap or delay existing disk I/O samples or the UI thread. Removed configurations cancel pending work, and version checks prevent old results from reappearing. Lost notifications use retained journal coverage where available; missing ranges require rebuilding affected data. Deleted roots are watched through an existing ancestor until they return. Unavailable watchers report partial coverage; failed observations and connections retry on the existing sixty-second schedule. Empty, missing, inaccessible, partial, cached and pending readings remain distinct. Tracked file contents are unchanged. Administrative approval is requested only after the user activates the journal-setup lock. Index-owned SQLite writes are excluded from change invalidation to prevent self-triggered indexing. Their actual allocation is still measured and included when the cache directory is inside a tracked folder. Private cache maintenance is separate from recursive user-folder traversal. diff --git a/src/macos/Info.plist b/src/macos/Info.plist index 27a0fc5..fce3f93 100644 --- a/src/macos/Info.plist +++ b/src/macos/Info.plist @@ -7,8 +7,8 @@ CFBundleExecutableCodexSwitch CFBundlePackageTypeAPPL CFBundleInfoDictionaryVersion6.0 - CFBundleShortVersionString1.45.9 - CFBundleVersion1.45.9 + CFBundleShortVersionString1.45.10 + CFBundleVersion1.45.10 CFBundleIconFileapp-icon.icns LSMinimumSystemVersion15.0 LSApplicationCategoryTypepublic.app-category.utilities diff --git a/src/platforms/resources/FolderChanges.cs b/src/platforms/resources/FolderChanges.cs index 1e95908..51e191f 100644 --- a/src/platforms/resources/FolderChanges.cs +++ b/src/platforms/resources/FolderChanges.cs @@ -5,17 +5,21 @@ namespace CodexAccountDesk; +internal enum FolderChange { Entries, ItemChanged, RootMetadata, Reset } + internal sealed class FolderChanges : IDisposable { - private readonly Action _changed; + private readonly Action _changed; private readonly Func _ignore; private readonly List _watchers = new(); private volatile bool _retry = true; + private volatile bool _watchingFolder; private int _identityChanged; internal bool TakeIdentityChange() => Interlocked.Exchange(ref _identityChanged, 0) != 0; internal string Path { get; } internal bool Available => !_retry; - internal FolderChanges(string path, Action changed, Func? ignore = null) { Path = path; _changed = changed; _ignore = ignore ?? (_ => false); } + internal FolderChanges(string path, Action changed, Func ignore) + { Path = path; _changed = changed; _ignore = ignore; } internal bool Connect() { if (!_retry || !OperatingSystem.IsWindows()) return false; @@ -28,46 +32,55 @@ internal bool Connect() if (!ancestor.Exists || (ancestor.Attributes & FileAttributes.ReparsePoint) != 0) candidate = ancestor.Parent; if (candidate == null) { _retry = true; return false; } var recursive = DriveMonitor.RootComparer.Equals(candidate.FullName, Path); - Add(candidate.FullName, recursive); - if (recursive && candidate.Parent != null) Add(candidate.Parent.FullName, false); + _watchingFolder = recursive; + const NotifyFilters rootChanges = NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Security; + if (recursive) + { + Add(candidate.FullName, true, NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite); + Add(candidate.FullName, true, NotifyFilters.Attributes | NotifyFilters.Security, attributesOnly: true); + if (candidate.Parent != null) Add(candidate.Parent.FullName, false, rootChanges); + } + else Add(candidate.FullName, false, rootChanges); return true; } catch (IOException) { _retry = true; Dispose(); return false; } catch (UnauthorizedAccessException) { _retry = true; Dispose(); return false; } catch (ArgumentException) { _retry = true; Dispose(); return false; } } - private void Add(string scope, bool recursive) + private void Add(string scope, bool recursive, NotifyFilters filters, bool attributesOnly = false) { var watcher = new FileSystemWatcher(scope) { IncludeSubdirectories = recursive, - NotifyFilter = recursive - ? NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.Attributes | NotifyFilters.Security - : NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Security, + NotifyFilter = filters, InternalBufferSize = 65536, }; - watcher.Changed += (_, e) => Notify(e.FullPath, recursive); + watcher.Changed += (_, e) => Notify(e.FullPath, recursive, changed: true, attributesOnly: attributesOnly); watcher.Created += (_, e) => Notify(e.FullPath, recursive); watcher.Deleted += (_, e) => Notify(e.FullPath, recursive); watcher.Renamed += (_, e) => { Notify(e.OldFullPath, recursive); Notify(e.FullPath, recursive); }; - watcher.Error += (_, _) => { _retry = true; _changed(Path, true); }; + watcher.Error += (_, _) => { _retry = true; _changed(Path, FolderChange.Reset); }; _watchers.Add(watcher); watcher.EnableRaisingEvents = true; } - private void Notify(string path, bool recursive) + private void Notify(string path, bool recursive, bool changed = false, bool attributesOnly = false) { if (_ignore(path)) return; if (!recursive) { var prefix = System.IO.Path.TrimEndingDirectorySeparator(path) + System.IO.Path.DirectorySeparatorChar; if (DriveMonitor.RootComparer.Equals(path, Path) || Path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) - { _retry = true; Interlocked.Exchange(ref _identityChanged, 1); _changed(Path, true); } + { + if (changed && _watchingFolder) _changed(Path, FolderChange.RootMetadata); + else { _retry = true; Interlocked.Exchange(ref _identityChanged, 1); _changed(Path, FolderChange.Reset); } + } return; } - var directory = System.IO.Path.GetDirectoryName(path); - _changed(directory ?? Path, false); + if (changed && !attributesOnly) _changed(path, FolderChange.ItemChanged); + else _changed(System.IO.Path.GetDirectoryName(path) ?? Path, FolderChange.Entries); } public void Dispose() { + _watchingFolder = false; foreach (var watcher in _watchers) watcher.Dispose(); _watchers.Clear(); } diff --git a/src/platforms/resources/FolderMonitor.cs b/src/platforms/resources/FolderMonitor.cs index 29e642d..77c55d2 100644 --- a/src/platforms/resources/FolderMonitor.cs +++ b/src/platforms/resources/FolderMonitor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using System.Text.Json; @@ -20,15 +21,22 @@ internal sealed class FolderMonitor : IAsyncDisposable private Dictionary _current = new(DriveMonitor.RootComparer); private readonly Dictionary _status = new(DriveMonitor.RootComparer); private readonly HashSet _dirty = new(DriveMonitor.RootComparer), _reset = new(DriveMonitor.RootComparer), _rebuild = new(DriveMonitor.RootComparer); + private readonly HashSet _refresh = new(DriveMonitor.RootComparer); + private readonly HashSet _checkRoots = new(DriveMonitor.RootComparer); + private readonly HashSet _changedItems = new(DriveMonitor.RootComparer); private readonly FolderScanBudget _budget = new(); private readonly string? _indexDirectory; + private readonly Func _probeJournal; private FolderUsage.Cache _cache; private Task? _run; + private long _journalProbes; private int _version; private bool _active = true, _needsMeasurement = true; private string? _measuringRoot; - internal FolderMonitor(string? indexDirectory = null) { _indexDirectory = indexDirectory; _cache = new(_budget); } + internal FolderMonitor(string? indexDirectory = null, Func? probeJournal = null) + { _indexDirectory = indexDirectory; _probeJournal = probeJournal ?? WindowsFolderJournal.Probe; _cache = new(_budget); } internal (long Roots, long Directories) QueryCounts { get { var cache = Volatile.Read(ref _cache); return (cache.RootReads, cache.DirectoryReads); } } + internal long JournalProbes => Interlocked.Read(ref _journalProbes); internal bool IsMeasuring { get { lock (_sync) return _scan != null; } } internal bool IsMeasuringRoot(string root) { lock (_sync) return _active && DriveMonitor.RootComparer.Equals(root, _measuringRoot); } internal FolderIndexStatus? IndexStatus(string root) { lock (_sync) return _status.GetValueOrDefault(root); } @@ -38,14 +46,20 @@ public void Configure(DrivePreference[] preferences) { lock (_sync) { - _scan?.Cancel(); _configuration = preferences; _version++; _dirty.Clear(); _reset.Clear(); _needsMeasurement = true; - _current = preferences.ToDictionary(p => p.Root, p => (p.Folders ?? Array.Empty()).Select(f => new FolderReading(f.Path, f.Color, null, FolderState.Scanning)).ToArray(), DriveMonitor.RootComparer); + _scan?.Cancel(); _configuration = preferences; _version++; _dirty.Clear(); _reset.Clear(); _refresh.Clear(); _rebuild.Clear(); _checkRoots.Clear(); _changedItems.Clear(); _needsMeasurement = true; + var previous = _current; + _current = preferences.ToDictionary(p => p.Root, p => (p.Folders ?? Array.Empty()).Select(folder => + { + var saved = previous.GetValueOrDefault(p.Root)?.FirstOrDefault(row => DriveMonitor.RootComparer.Equals(row.Path, folder.Path)); + return saved?.Bytes != null ? saved with { Path = folder.Path, Color = folder.Color, State = FolderState.Scanning } + : new FolderReading(folder.Path, folder.Color, null, FolderState.Scanning); + }).ToArray(), DriveMonitor.RootComparer); Signal(); } } internal void RefreshIndex(string root, bool rebuild) { - lock (_sync) { if (rebuild) _rebuild.Add(root); _needsMeasurement = true; Signal(); } + lock (_sync) { (rebuild ? _rebuild : _refresh).Add(root); Signal(); } } public void Start() { _run ??= Task.Run(RunAsync); } public void SetActive(bool active) @@ -57,17 +71,27 @@ public void SetActive(bool active) } } private void Signal() { if (_changed.CurrentCount == 0) _changed.Release(); } - private void Invalidate(int version, string path, bool reset) + private void Invalidate(int version, string path, FolderChange change) { lock (_sync) { if (version != _version || _stop.IsCancellationRequested) return; - (reset ? _reset : _dirty).Add(path); if (_active) Signal(); + var pending = change switch + { + FolderChange.ItemChanged => _changedItems, + FolderChange.RootMetadata => _checkRoots, + FolderChange.Reset => _reset, + _ => _dirty + }; + pending.Add(path); if (_active) Signal(); } } private async Task RunAsync() { var watches = new List(); FolderIndexStore? store = null; + var journal = new Dictionary(DriveMonitor.RootComparer); + var lastCheckpoint = Stopwatch.GetTimestamp(); + var loadManaged = true; var cache = _cache; var cachedVersion = -1; var retry = false; var indexFaulted = false; try { @@ -87,7 +111,7 @@ private async Task RunAsync() } if (cachedVersion != version) { - foreach (var watch in watches) watch.Dispose(); watches.Clear(); cache.Flush(); + foreach (var watch in watches) watch.Dispose(); watches.Clear(); cache.Flush(); journal.Clear(); if (_indexDirectory != null && preferences.Any(p => p.Folders?.Length > 0)) store ??= new(_indexDirectory); if (store != null) { @@ -100,75 +124,92 @@ private async Task RunAsync() Changed?.Invoke(); } cache = new(_budget, store) { DirectoriesPerSlice = store == null ? int.MaxValue : 8 }; - cache.Configure(preferences); cache.RefreshManaged(_stop.Token); Volatile.Write(ref _cache, cache); cachedVersion = version; + cache.Configure(preferences); Volatile.Write(ref _cache, cache); cachedVersion = version; loadManaged = true; foreach (var folder in preferences.SelectMany(p => p.Folders ?? Array.Empty())) - watches.Add(new(folder.Path, (path, full) => Invalidate(version, path, full), cache.Owns)); + watches.Add(new(folder.Path, (path, change) => Invalidate(version, path, change), cache.Owns)); lock (_sync) if (version == _version) _current = preferences.ToDictionary(p => p.Root, p => cache.Saved(p.Root).Select(r => store != null && r.Bytes.HasValue ? r with { State = FolderState.Cached } : r).ToArray(), DriveMonitor.RootComparer); Changed?.Invoke(); } if (!active) { await _changed.WaitAsync(_stop.Token); continue; } - string[] dirty, reset, rebuild; bool pending; CancellationTokenSource scan; + string[] dirty, reset, rebuild, refresh, checkRoots, changedItems; bool pending; CancellationTokenSource scan; lock (_sync) { if (!_active || version != _version) continue; _changed.Wait(0); pending = _needsMeasurement; _needsMeasurement = false; - dirty = _dirty.ToArray(); reset = _reset.ToArray(); rebuild = _rebuild.ToArray(); _dirty.Clear(); _reset.Clear(); _rebuild.Clear(); + dirty = _dirty.ToArray(); reset = _reset.ToArray(); rebuild = _rebuild.ToArray(); refresh = _refresh.ToArray(); + checkRoots = _checkRoots.ToArray(); _checkRoots.Clear(); + changedItems = _changedItems.ToArray(); _changedItems.Clear(); + _dirty.Clear(); _reset.Clear(); _rebuild.Clear(); _refresh.Clear(); _scan = scan = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token); } var continueWork = false; + var appliedChanges = false; try { - var journal = new Dictionary(DriveMonitor.RootComparer); - void Synchronize() + var recheck = reset.Select(path => Path.GetPathRoot(path)!).Concat(rebuild).Concat(refresh).ToHashSet(DriveMonitor.RootComparer); + var changedDirectories = dirty.ToHashSet(DriveMonitor.RootComparer); + // Windows can emit Changed for directory metadata during enumeration. Only structural + // directory events and changes to non-directory entries invalidate a listing. + foreach (var item in changedItems) + if (!cache.KnownDirectory(item) && Path.GetDirectoryName(item) is string directory) changedDirectories.Add(directory); + var changed = changedDirectories.Select(path => Path.GetPathRoot(path)!).ToHashSet(DriveMonitor.RootComparer); + var affected = changed.Concat(recheck).Concat(checkRoots.Select(path => Path.GetPathRoot(path)!)).ToHashSet(DriveMonitor.RootComparer); + foreach (var watch in watches) { - if (store == null) return; + scan.Token.ThrowIfCancellationRequested(); + if (!watch.Available && (loadManaged || pending || retry || reset.Contains(watch.Path, DriveMonitor.RootComparer) + || refresh.Contains(Path.GetPathRoot(watch.Path)!, DriveMonitor.RootComparer))) _budget.Query(watch.Connect, scan.Token); + } + if (loadManaged) { cache.RefreshManaged(scan.Token); loadManaged = false; } + // Establish the watchers before reading the cursor so work arriving after it remains observable. + if (store != null) foreach (var drive in preferences.Where(p => p.Folders?.Length > 0)) { - var status = _budget.Query(() => WindowsFolderJournal.Probe(drive.Root), scan.Token); journal[drive.Root] = status; + if (journal.TryGetValue(drive.Root, out var known) && !recheck.Contains(drive.Root) && + !(known.Access == FolderIndexAccess.Ready && changed.Contains(drive.Root)) && + !(retry && known.Access == FolderIndexAccess.Unavailable)) continue; + var status = _budget.Query(() => + { + Interlocked.Increment(ref _journalProbes); + return _probeJournal(drive.Root); + }, scan.Token); var progress = cache.Progress(drive.Root); lock (_sync) if (version == _version) _status[drive.Root] = new(status.Access, progress.Directories, progress.Files, status.Error > 0 ? status.Error.ToString(System.Globalization.CultureInfo.InvariantCulture) : null); - } - Changed?.Invoke(); - foreach (var drive in preferences.Where(p => p.Folders?.Length > 0)) - { - var status = journal[drive.Root]; - if (status.Access != FolderIndexAccess.Ready) continue; - if (cache.Cursors.TryGetValue(drive.Root, out var saved) && WindowsFolderJournal.Covers(status, saved)) - cache.SaveCursor(drive.Root, WindowsFolderJournal.Replay(drive.Root, status, saved, _budget, change => cache.Invalidate(drive.Root, change), scan.Token)); - else + Changed?.Invoke(); + if (status.Access == FolderIndexAccess.Ready) { - foreach (var folder in drive.Folders!) if (cache.HasSavedIndex(folder.Path)) cache.Reset(folder.Path); - cache.SaveCursor(drive.Root, new(status.JournalId, status.NextUsn)); + if (cache.Cursors.TryGetValue(drive.Root, out var saved) && WindowsFolderJournal.Covers(status, saved)) + cache.SaveCursor(drive.Root, WindowsFolderJournal.Replay(drive.Root, status, saved, _budget, change => cache.Invalidate(drive.Root, change), scan.Token)); + else + { + foreach (var folder in drive.Folders!) if (cache.HasSavedIndex(folder.Path)) cache.Reset(folder.Path); + cache.SaveCursor(drive.Root, new(status.JournalId, status.NextUsn)); + } } + journal[drive.Root] = status; } - } - cache.Checkpoint = Synchronize; - Synchronize(); - foreach (var watch in watches) - { - scan.Token.ThrowIfCancellationRequested(); - if (!watch.Available) _budget.Query(watch.Connect, scan.Token); - } - // The watcher covers changes while the journal checkpoint is being read. - Synchronize(); - foreach (var path in dirty) + foreach (var path in changedDirectories) if (store == null || !journal.TryGetValue(Path.GetPathRoot(path)!, out var source) || source.Access != FolderIndexAccess.Ready) cache.Invalidate(path); foreach (var path in reset) if (watches.Where(w => DriveMonitor.RootComparer.Equals(w.Path, path)).Any(w => w.TakeIdentityChange()) || store == null || !journal.TryGetValue(Path.GetPathRoot(path)!, out var source) || source.Access != FolderIndexAccess.Ready) cache.Reset(path); foreach (var root in rebuild) foreach (var folder in preferences.Where(p => DriveMonitor.RootComparer.Equals(p.Root, root)).SelectMany(p => p.Folders ?? Array.Empty())) cache.Reset(folder.Path); + foreach (var path in checkRoots) cache.CheckRootOnRead(path); + appliedChanges = true; if (retry) cache.RetryPartial(); var allowed = preferences.Where(p => store == null || !journal.TryGetValue(p.Root, out var access) || access.Access == FolderIndexAccess.Ready || - access.Access == FolderIndexAccess.Unsupported && (rebuild.Contains(p.Root, DriveMonitor.RootComparer) || p.Folders?.All(f => !cache.HasSavedIndex(f.Path)) == true || dirty.Concat(reset).Any(d => DriveMonitor.RootComparer.Equals(Path.GetPathRoot(d), p.Root)))) .ToArray(); + access.Access == FolderIndexAccess.Unsupported && (affected.Contains(p.Root) || + p.Folders!.Any(f => !cache.HasSavedIndex(f.Path)) || cache.HasWorkFor(p.Folders!.Select(f => f.Path)))).ToArray(); + var allowedRoots = allowed.Select(p => p.Root).ToHashSet(DriveMonitor.RootComparer); var paths = allowed.SelectMany(p => p.Folders ?? Array.Empty()).Select(p => p.Path).ToArray(); - var measure = pending || dirty.Length > 0 || reset.Length > 0 || rebuild.Length > 0 || cache.HasWorkFor(paths) || retry && allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Partial)); + var measure = pending || affected.Count > 0 || cache.HasWorkFor(paths) || retry && allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Partial)); if (measure && paths.Length > 0) { - var result = FolderUsage.Scan(allowed, scan.Token, measured: (root, reading) => + FolderUsage.Scan(allowed, scan.Token, measured: (root, reading) => { var progress = cache.Progress(root); lock (_sync) @@ -184,13 +225,12 @@ void Synchronize() Changed?.Invoke(); }); cache.Configure(preferences); - if (OperatingSystem.IsWindows()) - foreach (var root in result.Keys.ToArray()) - result[root] = result[root].Select(row => row.State == FolderState.Available && watches.Any(w => DriveMonitor.RootComparer.Equals(w.Path, row.Path) && !w.Available) - ? row with { State = FolderState.Partial, Skipped = row.Skipped + 1 } : row).ToArray(); - lock (_sync) if (version == _version) foreach (var pair in result) _current[pair.Key] = pair.Value; } - cache.Flush(); cache.RefreshManaged(scan.Token); + continueWork = cache.HasWorkFor(paths) || allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Scanning)); + if (store?.HasChanges == true && (!continueWork || Stopwatch.GetElapsedTime(lastCheckpoint) >= TimeSpan.FromSeconds(1))) + { + cache.Flush(); cache.RefreshManaged(scan.Token); lastCheckpoint = Stopwatch.GetTimestamp(); + } lock (_sync) { if (version == _version) @@ -199,8 +239,11 @@ void Synchronize() var source = journal.GetValueOrDefault(preference.Root); var saved = cache.Saved(preference.Root); if (store != null && source?.Access != FolderIndexAccess.Ready) - _current[preference.Root] = saved.Select(row => row with { State = row.Bytes.HasValue ? FolderState.Cached : FolderState.Unavailable }).ToArray(); - else if (measure) _current[preference.Root] = saved; + _current[preference.Root] = saved.Select(row => row.State == FolderState.Scanning && allowedRoots.Contains(preference.Root) ? row + : row with { State = row.Bytes.HasValue ? FolderState.Cached : row.State == FolderState.Scanning ? FolderState.Unavailable : row.State }).ToArray(); + else if (measure) _current[preference.Root] = saved.Select(row => + row.State == FolderState.Available && watches.Any(w => DriveMonitor.RootComparer.Equals(w.Path, row.Path) && !w.Available) + ? row with { State = FolderState.Partial, Skipped = row.Skipped + 1 } : row).ToArray(); if (store != null) { var progress = cache.Progress(preference.Root); @@ -208,18 +251,28 @@ void Synchronize() source?.Error is > 0 ? source.Error.ToString(System.Globalization.CultureInfo.InvariantCulture) : null); } } - continueWork = cache.HasWorkFor(paths) || allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Scanning)); } Changed?.Invoke(); } - catch (OperationCanceledException) when (scan.IsCancellationRequested) { lock (_sync) _needsMeasurement = true; cache.Flush(); } + catch (OperationCanceledException) when (scan.IsCancellationRequested) + { + lock (_sync) + { + _needsMeasurement = true; + if (!appliedChanges && version == _version) + { + _dirty.UnionWith(dirty); _reset.UnionWith(reset); _rebuild.UnionWith(rebuild); _refresh.UnionWith(refresh); + _checkRoots.UnionWith(checkRoots); _changedItems.UnionWith(changedItems); + } + } + cache.Flush(); + } finally { - cache.Checkpoint = null; lock (_sync) { _measuringRoot = null; _scan = null; scan.Dispose(); } Changed?.Invoke(); } - var signaled = await _changed.WaitAsync(TimeSpan.FromSeconds(continueWork ? 1 : 60), _stop.Token); + var signaled = await _changed.WaitAsync(continueWork ? TimeSpan.FromMilliseconds(250) : TimeSpan.FromSeconds(60), _stop.Token); retry = !signaled && !continueWork; if (signaled) await Task.Delay(TimeSpan.FromSeconds(2), _stop.Token); } diff --git a/src/platforms/resources/FolderUsage.cs b/src/platforms/resources/FolderUsage.cs index 2b86dc6..c85f47e 100644 --- a/src/platforms/resources/FolderUsage.cs +++ b/src/platforms/resources/FolderUsage.cs @@ -80,7 +80,7 @@ private static FolderReading Read(string root, FolderPreference folder, Cancella if (!OperatingSystem.IsWindows()) return new(folder.Path, folder.Color, null, FolderState.Unsupported); cancellation.ThrowIfCancellationRequested(); var work = cache.Pending(folder.Path); - if (work == null) + if (work == null || cache.NeedsRootCheck(folder.Path)) { cache.Begin(folder.Path); uint volume; @@ -92,10 +92,9 @@ private static FolderReading Read(string root, FolderPreference folder, Cancella if ((cache.Query(() => File.GetAttributes(path), cancellation) & FileAttributes.ReparsePoint) != 0) return Failed(FolderState.Unavailable); } - if ((cache.Query(() => File.GetAttributes(folder.Path), cancellation) & FileAttributes.Directory) == 0) return Failed(FolderState.Unavailable); var info = cache.Query(() => { - using var handle = CreateFileW(NativePath(folder.Path), 0x80, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero); + using var handle = CreateFileW(NativePath(folder.Path), 0x81, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero); if (handle.IsInvalid || !GetFileInformationByHandle(handle, out var value)) throw new IOException("Folder volume cannot be read.", new Win32Exception(Marshal.GetLastWin32Error())); return value; @@ -111,7 +110,7 @@ private static FolderReading Read(string root, FolderPreference folder, Cancella catch (UnauthorizedAccessException) { return Failed(FolderState.Unavailable); } cache.Trust(folder.Path); if (cache.TryReuse(folder.Path, out var saved)) return saved with { Color = folder.Color }; - work = cache.Start(folder.Path, volume); + work = cache.Pending(folder.Path) ?? cache.Start(folder.Path, volume); } var processed = 0; var slice = Stopwatch.StartNew(); diff --git a/src/platforms/resources/FolderUsageCache.cs b/src/platforms/resources/FolderUsageCache.cs index 37ee681..5114fef 100644 --- a/src/platforms/resources/FolderUsageCache.cs +++ b/src/platforms/resources/FolderUsageCache.cs @@ -48,7 +48,6 @@ internal sealed class Work private readonly Dictionary _readings = new(DriveMonitor.RootComparer); internal readonly Dictionary Cursors = new(DriveMonitor.RootComparer); private readonly Dictionary _persistedCursors = new(DriveMonitor.RootComparer); - internal Action? Checkpoint; internal int DirectoriesPerSlice { get; set; } = int.MaxValue; internal long DirectoryReads { get; private set; } internal long RootReads { get; private set; } @@ -125,7 +124,7 @@ internal void BeginScan() { } internal bool TryReuse(string folder, out FolderReading reading) { return _readings.TryGetValue(folder, out reading!) && reading.State != FolderState.Scanning && !_work.ContainsKey(folder) && - (_store == null || _trusted.Contains(folder)) && !_dirty.Concat(_reset).Any(path => DriveMonitor.RootComparer.Equals(path, folder) || Inside(folder, path) || Inside(path, folder)); + _trusted.Contains(folder) && !_dirty.Concat(_reset).Any(path => DriveMonitor.RootComparer.Equals(path, folder) || Inside(folder, path) || Inside(path, folder)); } internal void Begin(string folder) { RootReads++; } internal Work? Pending(string folder) => _work.GetValueOrDefault(folder); @@ -133,6 +132,8 @@ internal bool TryReuse(string folder, out FolderReading reading) internal Work Start(string folder, uint volume) { var value = new Work(folder, volume); _work[folder] = value; return value; } internal long Bytes(string folder) => _bytes.GetValueOrDefault(folder); internal void Trust(string folder) => _trusted.Add(folder); + internal bool NeedsRootCheck(string folder) => !_trusted.Contains(folder); + internal void CheckRootOnRead(string folder) => _trusted.Remove(folder); internal string[] UntrustedRoots => _roots.Keys.Where(p => !_trusted.Contains(p)).ToArray(); internal void Finish(string folder) { @@ -254,8 +255,10 @@ private void SetDirectory(string directory, FolderEntry[] entries) directory = canonical; if (_directories.TryGetValue(directory, out var old)) RemoveReferences(directory, old); _directories[directory] = entries; _byFolder[folder].Add(directory); + var failed = false; foreach (var entry in entries) { + failed |= entry.Failed; if ((entry.Attributes & (FileAttributes.Directory | FileAttributes.ReparsePoint)) == FileAttributes.Directory && entry.Id != 0) { _directoryIds[new(Path.GetPathRoot(directory)!.ToUpperInvariant(), entry.Volume, entry.Id)] = entry.Path; _knownDirectories.Add(entry.Path); } if (!entry.Resolved || entry.Failed) continue; @@ -266,7 +269,7 @@ private void SetDirectory(string directory, FolderEntry[] entries) else if (!DriveMonitor.RootComparer.Equals(file.FirstDirectory, directory)) (file.OtherDirectories ??= new(DriveMonitor.RootComparer)).Add(directory); } if (_dirty.Remove(directory)) Delete(FolderIndexStore.DirtyKind, directory); - _failed.Remove(directory); + if (failed) _failed.Add(directory); else _failed.Remove(directory); if (!Owns(directory)) Put(FolderIndexStore.DirectoryKind, directory, entries); if (old != null) Prune(old, directory); } @@ -306,14 +309,13 @@ internal IEnumerable Entries(DirectoryInfo directory, uint volume, if (!children.TryGetValue(child.Path, out var id) || id == 0 || id != child.Id) Reset(child.Path, false); } SetDirectory(path, fresh); - if (++_writes % 64 == 0) { Checkpoint?.Invoke(); Flush(); } + if (++_writes % 64 == 0) Flush(); return fresh; } internal void FailDirectory(string path) { foreach (var child in _directories.Keys.Where(p => DriveMonitor.RootComparer.Equals(path, p) || Inside(path, p)).ToArray()) RemoveDirectory(child); _dirty.Remove(path); _failed.Add(path); } internal void RetryPartial() { foreach (var directory in _failed.ToArray()) Invalidate(directory); - foreach (var pair in _directories) if (pair.Value.Any(e => e.Failed)) Invalidate(pair.Key); foreach (var row in _readings.Values.Where(r => r.State == FolderState.Partial)) foreach (var path in _directoryIds.Values.Where(p => (DriveMonitor.RootComparer.Equals(p, row.Path) || Inside(row.Path, p)) && !_directories.ContainsKey(p)).ToArray()) Invalidate(path); } diff --git a/src/windows/DriveUsagePanel.cs b/src/windows/DriveUsagePanel.cs index 546c186..76f88a0 100644 --- a/src/windows/DriveUsagePanel.cs +++ b/src/windows/DriveUsagePanel.cs @@ -56,7 +56,7 @@ private sealed class DriveCell : Grid public string Root { get; } public bool Fits => _text.ActualWidth >= 20 && _temperature.ActualWidth + 22 < ActualWidth && _ioFills.All(fill => fill.Height is >= 0 and <= 16); private readonly Border _track = new() { CornerRadius = new CornerRadius(4) }; - private readonly Grid _segments = new() { ClipToBounds = true, FlowDirection = FlowDirection.LeftToRight }; + private readonly Canvas _segments = new() { ClipToBounds = true, FlowDirection = FlowDirection.LeftToRight }; private readonly TextBlock _text = new() { FontSize = 11, FontWeight = FontWeights.SemiBold, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(5, 0, 4, 0) }; private readonly Run _capacity = new(); @@ -71,6 +71,7 @@ private sealed class DriveCell : Grid private readonly Border[] _ioTracks = new Border[2], _ioFills = new Border[2]; private readonly Action _openDirectory; private readonly List _buttons = new(); + private DriveSegment[] _allocation = Array.Empty(); public DriveCell(string root, Action openDirectory, Action enableIndex, Action rebuildIndex) { Root = root; _openDirectory = openDirectory; _rebuildIndex = rebuildIndex; Margin = new Thickness(0, 2, 4, 2); @@ -100,7 +101,41 @@ public DriveCell(string root, Action openDirectory, Action enabl track.Children.Add(_ioTracks[index]); track.Children.Add(_ioFills[index]); throughput.Children.Add(track); } Grid.SetColumn(throughput, 3); content.Children.Add(throughput); - _segments.SizeChanged += (_, _) => _segments.Clip = new RectangleGeometry(new Rect(_segments.RenderSize), 4, 4); + _segments.SizeChanged += (_, _) => + { + _segments.Clip = new RectangleGeometry(new Rect(_segments.RenderSize), 4, 4); + SetSegmentWidths(); + }; + } + private void SetSegmentWidths() + { + var scale = VisualTreeHelper.GetDpi(_segments).DpiScaleX; + var pixels = Math.Round(_segments.ActualWidth * scale); + var total = _allocation.Sum(segment => (double)segment.Bytes); + if (pixels <= 0 || total <= 0) return; + bool NeedsPixel(DriveSegment segment) => segment.Color.HasValue && pixels * segment.Bytes / total < 1; + var remaining = pixels; + var remainingBytes = total; + foreach (var segment in _allocation.Where(NeedsPixel)) + { + remaining--; + remainingBytes -= segment.Bytes; + } + remaining = Math.Max(0, remaining); + var edge = 0.0; + for (var index = 0; index < _allocation.Length; index++) + { + var segment = _allocation[index]; + var start = Math.Min(pixels, Math.Round(edge)); + if (NeedsPixel(segment)) edge += 1; + else if (remainingBytes > 0) edge += remaining * segment.Bytes / remainingBytes; + var button = _buttons[index]; + var left = start / scale; + var width = (Math.Min(pixels, Math.Round(edge)) - start) / scale; + if (Canvas.GetLeft(button) != left) Canvas.SetLeft(button, left); + if (button.Width != width) button.Width = width; + if (button.Height != _segments.ActualHeight) button.Height = _segments.ActualHeight; + } } public void Refresh(DriveReading reading, Burn0Theme theme) { @@ -111,16 +146,17 @@ public void Refresh(DriveReading reading, Burn0Theme theme) if (segments.Length == 0) segments = new[] { new DriveSegment(reading.Root, 1, null) }; if (!_buttons.Select(b => b.Label).SequenceEqual(segments.Select(s => s.Label))) { - _segments.Children.Clear(); _segments.ColumnDefinitions.Clear(); _buttons.Clear(); + _segments.Children.Clear(); _buttons.Clear(); foreach (var segment in segments) { var button = new SegmentButton(segment.Label, segment.Color.HasValue ? segment.Label : Root, _openDirectory); - _segments.ColumnDefinitions.Add(new()); Grid.SetColumn(button, _buttons.Count); _buttons.Add(button); _segments.Children.Add(button); + _buttons.Add(button); _segments.Children.Add(button); } } + _allocation = segments; + SetSegmentWidths(); for (var i = 0; i < segments.Length; i++) { - _segments.ColumnDefinitions[i].Width = new GridLength(segments[i].Bytes, GridUnitType.Star); _buttons[i].Refresh(segments[i], reading, theme); } var label = string.IsNullOrWhiteSpace(reading.Label) ? reading.Root[..2] : reading.Label; @@ -198,14 +234,14 @@ private sealed class SegmentButton : Button HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, IsHitTestVisible = false }; public SegmentButton(string label, string path, Action openDirectory) { - Label = label; Tag = path; Padding = new Thickness(0); BorderThickness = new Thickness(0); MinHeight = 0; + Label = label; Tag = path; Padding = new Thickness(0); BorderThickness = new Thickness(0); MinHeight = 0; Width = 0; Height = 0; Background = Brushes.Transparent; Cursor = System.Windows.Input.Cursors.Hand; HorizontalContentAlignment = HorizontalAlignment.Stretch; VerticalContentAlignment = VerticalAlignment.Stretch; var presenter = new FrameworkElementFactory(typeof(ContentPresenter)); presenter.SetValue(ContentPresenter.ContentProperty, new TemplateBindingExtension(ContentProperty)); Template = new ControlTemplate(typeof(Button)) { VisualTree = presenter }; var surface = new Grid { Background = Brushes.Transparent }; surface.Children.Add(_fill); surface.Children.Add(_pattern); surface.Children.Add(_share); Content = surface; - SizeChanged += (_, _) => _share.Visibility = ActualWidth >= 40 && _share.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + SizeChanged += (_, _) => UpdateExtent(); Click += (_, _) => openDirectory(path); } public void Refresh(DriveSegment segment, DriveReading reading, Burn0Theme theme) @@ -214,9 +250,7 @@ public void Refresh(DriveSegment segment, DriveReading reading, Burn0Theme theme var brush = segment.Color is int color ? DriveSettingsWindow.FolderBrush(color) : theme.Color(segment.Label == "folders.free" ? "success" : "muted"); _fill.Background = plain || segment.Label == "folders.free" ? Brushes.Transparent : new SolidColorBrush(brush.Color) { Opacity = segment.Color.HasValue ? 1 : theme.Dark ? 0.55 : 0.48 }; - var separator = segment.Label == "folders.free" ? 0 : 1; - _fill.BorderBrush = theme.Color("canvas"); _fill.BorderThickness = new Thickness(0, 0, separator, 0); - _pattern.Margin = new Thickness(0, 0, separator, 0); + _fill.BorderBrush = theme.Color("canvas"); if (segment.Color.HasValue) { var drawing = new GeometryDrawing(null, new Pen(new SolidColorBrush(Colors.White) { Opacity = 0.24 }, 2), @@ -227,7 +261,7 @@ public void Refresh(DriveSegment segment, DriveReading reading, Burn0Theme theme } else _pattern.Background = Brushes.Transparent; _share.Text = segment.Color.HasValue && reading.Total > 0 ? (100.0 * segment.Bytes / reading.Total.Value).ToString("0.#", Loc.Culture) + "%" : ""; - _share.Visibility = ActualWidth >= 40 && _share.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + UpdateExtent(); var folder = reading.Folders?.FirstOrDefault(f => f.Path == segment.Label); var bytes = plain ? reading.Free : folder?.Bytes ?? segment.Bytes; var value = bytes.HasValue ? (bytes.Value / 1073741824.0).ToString("0.###", Loc.Culture) + " GiB" : "—"; @@ -235,10 +269,17 @@ public void Refresh(DriveSegment segment, DriveReading reading, Burn0Theme theme var details = (string)Tag; if (bytes.HasValue && reading.Total > 0) details += "\n" + (100.0 * bytes.Value / reading.Total.Value).ToString("0.0", Loc.Culture) + "%"; if (plain) details += " · " + Loc.T("folders.free"); - if (folder?.State == FolderState.Partial) details += " · " + Loc.T("folders.partial"); + if (folder?.State is FolderState.Partial or FolderState.Cached or FolderState.Scanning) + details += " · " + Loc.T(folder.State switch { FolderState.Partial => "folders.partial", FolderState.Cached => "folders.cached", _ => "folders.scanning" }); details += "\n" + Loc.T("folders.open"); ToolTipTheme.Resource(this, title, value, details, theme, "text"); AutomationProperties.SetName(this, title + " " + value + "\n" + details); } + private void UpdateExtent() + { + var separator = Label != "folders.free" && ActualWidth >= 4 ? 1 : 0; + _fill.BorderThickness = _pattern.Margin = new Thickness(0, 0, separator, 0); + _share.Visibility = ActualWidth >= 40 && _share.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + } } } diff --git a/tests/hardware/PersistentFolderContracts.cs b/tests/hardware/PersistentFolderContracts.cs index a4235d7..b9ccdcd 100644 --- a/tests/hardware/PersistentFolderContracts.cs +++ b/tests/hardware/PersistentFolderContracts.cs @@ -114,9 +114,36 @@ long Expected() => Directory.EnumerateFiles(Path.Combine(temporary, "data"), "*" { monitor.Configure(new[] { new DrivePreference { Root = root, Folders = new[] { new FolderPreference { Path = owned } } } }); monitor.Start(); await Wait(() => monitor.Read(root).Single().State == FolderState.Available && !monitor.IsMeasuring); - var queries = monitor.QueryCounts; await Task.Delay(3500); + var queries = monitor.QueryCounts; var probes = monitor.JournalProbes; + await Task.Delay(TimeSpan.FromSeconds(65)); check("Index-owned writes inside a tracked tree reach idle and retain their physical allocation", () => - Assert(!monitor.IsMeasuringRoot(root) && monitor.QueryCounts == queries && monitor.Read(root).Single().Bytes >= 8192)); + Assert(!monitor.IsMeasuringRoot(root) && monitor.QueryCounts == queries && monitor.JournalProbes == probes && monitor.Read(root).Single().Bytes >= 8192)); + } + var unsupported = Path.Combine(temporary, "unsupported"); + var nested = unsupported; + for (var level = 0; level < 12; level++) nested = Path.Combine(nested, "level"); + Directory.CreateDirectory(nested); + var deepestFile = Path.Combine(nested, "last.bin"); + File.WriteAllBytes(deepestFile, new byte[65536]); + var allocation = FolderUsage.Allocation(deepestFile).Bytes; + await using (var monitor = new FolderMonitor(Path.Combine(temporary, "unsupported-index"), _ => new(FolderIndexAccess.Unsupported))) + { + monitor.Configure(new[] { new DrivePreference { Root = root, Folders = new[] { new FolderPreference { Path = unsupported } } } }); + monitor.Start(); + await Wait(() => monitor.Read(root).Single().Bytes == allocation && monitor.Read(root).Single().State == FolderState.Cached && !monitor.IsMeasuring); + check("A drive without a journal finishes the entire bounded first scan without reprobing between slices", () => + { + if (monitor.QueryCounts != (1, 13) || monitor.JournalProbes != 1) + throw new InvalidOperationException($"Unexpected initial measurement work: {monitor.QueryCounts}; journal probes: {monitor.JournalProbes}."); + }); + File.WriteAllBytes(deepestFile, new byte[131072]); + var updated = FolderUsage.Allocation(deepestFile).Bytes; + await Wait(() => monitor.Read(root).Single().Bytes == updated && monitor.Read(root).Single().State == FolderState.Cached && !monitor.IsMeasuring); + check("A later watcher change on a drive without a journal rereads only the changed directory", () => + { + if (monitor.QueryCounts.Directories != 14 || monitor.JournalProbes != 1) + throw new InvalidOperationException($"Unexpected watcher measurement work: {monitor.QueryCounts}; journal probes: {monitor.JournalProbes}."); + }); } var foreign = Path.Combine(temporary, "foreign"); Directory.CreateDirectory(foreign); var foreignFile = Path.Combine(foreign, "allocation.sqlite3"); var original = Encoding.UTF8.GetBytes("not-an-owned-index"); File.WriteAllBytes(foreignFile, original); diff --git a/tests/model-providers-ui/FolderUiContracts.cs b/tests/model-providers-ui/FolderUiContracts.cs index be04daa..3a2dadd 100644 --- a/tests/model-providers-ui/FolderUiContracts.cs +++ b/tests/model-providers-ui/FolderUiContracts.cs @@ -69,6 +69,21 @@ internal static void Verify(AccountService service, string output, List after.Refresh(new[] { tracked with { Free = 299 * gib } }, theme); if (!segments.SequenceEqual(Find