From ca4f145a95774ee1c134d8f7a81b89e5f89dbbda Mon Sep 17 00:00:00 2001 From: GOXF Date: Sun, 8 Nov 2026 09:41:34 +0000 Subject: [PATCH] =?UTF-8?q?fix(=E6=98=A0=E5=B0=84=E6=95=B4=E7=90=86):=20?= =?UTF-8?q?=E9=80=80=E5=87=BA=E5=89=8D=E8=BF=98=E5=8E=9F=E9=9A=90=E8=97=8F?= =?UTF-8?q?=E9=A1=B9=EF=BC=88=E5=90=AB=E5=85=B3=E6=9C=BA/=E9=87=8D?= =?UTF-8?q?=E5=90=AF/=E6=B3=A8=E9=94=80=EF=BC=89+=20=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=20+=20=E7=A7=BB=E5=87=BA=E6=A1=8C=E9=9D=A2?= =?UTF-8?q?=E6=97=B6=E6=B8=85=E9=99=A4=E9=9A=90=E8=97=8F=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 所有退出路径先同步还原:托盘退出/重启/更新(ShutdownApplicationAsync 第一步)、 WM_QUERYENDSESSION/WM_ENDSESSION(关机、重启、注销、安装器 Restart Manager), 会话结束被取消时重新隐藏;ProcessExit;后台线程崩溃(尽力) - 启动恢复:恢复部件前先把记录里的隐藏项全部还原并记日志,之后再按映射隐藏 - 整理扫描把 DeskBox 隐藏的项当普通桌面项(不再「本次无法整理」) - 隐藏项被移到别的文件夹/回收站:按 NTFS 文件 ID 找到新位置并清除隐藏属性 - fork-dev-update.ps1 强制结束后按记录还原 - 单元测试 ForkHiddenRestoreTests --- docs/architecture/mapped-organize.md | 59 +++++- scripts/fork-dev-update.ps1 | 23 ++ src/DeskBox/App.MappedOrganize.cs | 15 +- src/DeskBox/App.xaml.cs | 8 + .../Platform/ForkFileIdentityNative.cs | 121 +++++++++++ .../Services/AppLifecycleRecoveryWatcher.cs | 4 + .../Services/DesktopOrganizationScanner.cs | 3 +- .../MappedOrganizeDesktopVisibility.cs | 10 + .../Services/MappedOrganizeExitSafety.cs | 197 ++++++++++++++++++ .../MappedOrganizeService.LeakGuard.cs | 79 +++++++ .../MappedOrganizeService.Visibility.cs | 18 +- src/DeskBox/Services/MappedOrganizeService.cs | 45 +++- tests/DeskBox.Tests/ForkHiddenRestoreTests.cs | 92 ++++++++ 13 files changed, 659 insertions(+), 15 deletions(-) create mode 100644 src/DeskBox/Platform/ForkFileIdentityNative.cs create mode 100644 src/DeskBox/Services/MappedOrganizeExitSafety.cs create mode 100644 src/DeskBox/Services/MappedOrganizeService.LeakGuard.cs create mode 100644 tests/DeskBox.Tests/ForkHiddenRestoreTests.cs diff --git a/docs/architecture/mapped-organize.md b/docs/architecture/mapped-organize.md index 7294f24f6..b97b07563 100644 --- a/docs/architecture/mapped-organize.md +++ b/docs/architecture/mapped-organize.md @@ -77,6 +77,54 @@ Ordinary organization never targets mapped widgets: they are filtered out in * Settings warns when Explorer shows hidden items (HKCU …\Explorer\Advanced `Hidden`=1): mapped entries then still appear as faded icons. +### Restore before every exit (fix/mapped-hidden-restore) + +Goal: whenever DeskBox is not running, no desktop entry stays hidden by it. +`RestoreIconsForExit(reason, sessionEnd)` is synchronous and idempotent +(`MappedOrganizeExitGate`); log line `[MappedOrganize] Restored desktop items for `. + +| Exit path | What runs | +| --- | --- | +| Tray exit, 重启, in-app update (`ShutdownForUpdate/RestartAsync`), dev「更新并重启」 | first line of `ShutdownApplicationAsync` (before any bounded teardown step can time out), again in the shutdown step | +| Windows shutdown / restart / sign-out, installer Restart Manager | `WM_QUERYENDSESSION` / `WM_ENDSESSION` on the tray window → `FlushSettingsForEndSession` → restore; a cancelled session end (`WM_ENDSESSION` FALSE) re-hides (`ForkSessionEndSignal`) | +| `Environment.Exit` / fatal startup | `ProcessExit` | +| Crash on a background thread | `AppDomain.UnhandledException` (terminating) — best effort | +| Hard kill (Task Manager, `Stop-Process -Force`) | cannot run; `fork-dev-update.ps1` restores from the ledger after its own force-kill; next start: `MappedOrganizeStartupRecovery` (startup step `mapped-organize-recovery`, before widget restore) shows every ledger entry, logs it, then the service hides the members again; uninstaller as before | + +The desktop organizer (`DesktopOrganizationScanner`) reads attributes through +`MappedOrganizeHiddenRegistry.EffectiveAttributes`, so a ledger entry is a +normal item, never 「本次无法整理」. Older builds (no ledger support) cannot do +this — they are why the post-restart desktop showed 0 items. + +### Hidden attribute never leaves the desktop + +When an entry is hidden its NTFS id (volume serial + file index) is captured. +A ledger entry the desktop watcher reports as deleted is opened by id +(`ForkFileIdentityNative`, `OpenFileById` + `GetFinalPathNameByHandle`): if it +now lives outside the desktop (another folder, cut/paste, dragged out of a +mapped widget, Recycle Bin) its hidden attribute is cleared there and it leaves +the ledger (`MappedOrganizeLeakPolicy`). Not covered: a *copy* of a hidden +entry (copies keep attributes) and a move to another volume (copy + delete). + +### Research: hiding icons without file attributes + +* 360 桌面助手 / Fences: keep the desktop SysListView32 but position icons + under their own fence windows (Fences moves icon positions via + LVM_SETITEMPOSITION and draws its own frame; "quick-hide" hides the whole + list view). WPS 桌面整理 hides the whole icon layer (SysListView32 + ShowWindow / Explorer "show desktop icons") and draws every item, mapped or + not, in its own windows. None of them touch file attributes. +* This codebase already has the whole-layer approach: `DesktopIconVisibilityService` + (SW_HIDE of the desktop SysListView32, not persisted by Explorer) behind the + legacy `desktopIconsHiddenByDeskBox` marker, from the first mapped build. + A "hide icon layer + show unmapped items in a DeskBox desktop surface" mode + is feasible: needs a full-screen-per-monitor desktop-layer widget that lists + unmapped desktop items with free positioning (or a grid), Explorer-restart + re-apply (periodic check exists), desktop drop target / context menu / rename + / keyboard parity, and blank-area double-click behaviour. Rough effort: 5–8 + focused dev days for a usable version, more for full Explorer parity + (icon positions, multi-monitor layouts, F2/Del/Ctrl+A on the desktop). + ## 「放回桌面」 The item menu row 「移回桌面」 reads 「放回桌面」 in mapped widgets and calls @@ -217,6 +265,10 @@ topology profiles and wake recovery apply unchanged. * `DesktopAutoOrganizationWatcher.cs`: 只映射 hand-off (one block). * `DesktopOrganizationSettingsSection.xaml`: one host panel for the mode card. * `installer/DeskBox.Uninstall.iss`: include + one call. +* Exit safety: `App.xaml.cs` 3 lines (startup recovery step, restore at top of + `ShutdownApplicationAsync` and `FlushSettingsForEndSession`), + `AppLifecycleRecoveryWatcher.cs` (ENDSESSION FALSE signal), + `DesktopOrganizationScanner.cs` (effective attributes). * `Strings/*.json`: 6 keys inserted after `DesktopOrganization.Preview.Title` (zh-CN / zh-TW translated, other locales English fallback). @@ -233,10 +285,9 @@ topology profiles and wake recovery apply unchanged. (grouping is per category). * The auto/manual switch for mapped widgets stays in the mapped widget's blank-area menu. -* Moving / copying a mapped item out to another folder keeps the Hidden - attribute DeskBox set (NTFS carries it along); membership and the hidden - ledger are cleaned up by the desktop watcher, but the file stays hidden at - the destination. +* Copying a mapped item to another folder, or moving it to another volume, + keeps the Hidden attribute on the copy (moves on the same volume are fixed, + see 「Hidden attribute never leaves the desktop」). * 拖到桌面 = 放回桌面: a drop onto another desktop icon is not treated as put-back (one whose label equals a dragged entry's name is); icon placement needs 自动排列图标 off (网格对齐 still snaps it). Touch / pen diff --git a/scripts/fork-dev-update.ps1 b/scripts/fork-dev-update.ps1 index 617c13322..355447f37 100644 --- a/scripts/fork-dev-update.ps1 +++ b/scripts/fork-dev-update.ps1 @@ -19,6 +19,29 @@ try { Get-Process DeskBox -ErrorAction SilentlyContinue | Stop-Process -Force Start-Sleep -Seconds 1 + # 映射整理:被强制结束的 DeskBox 来不及还原被隐藏的桌面项,这里按记录还原 + try { + $dataRoot = if ($env:DESKBOX_DEV_DATA_ROOT) { $env:DESKBOX_DEV_DATA_ROOT } else { Join-Path $env:LOCALAPPDATA "DeskBox" } + $ledger = Join-Path $dataRoot "data\mapped-organize.hidden" + if (Test-Path -LiteralPath $ledger) { + $restored = 0 + foreach ($line in Get-Content -LiteralPath $ledger -Encoding UTF8) { + $item = $line.Trim() + if (-not $item -or -not (Test-Path -LiteralPath $item)) { continue } + $entry = Get-Item -LiteralPath $item -Force + if ($entry.Attributes -band [IO.FileAttributes]::Hidden) { + $entry.Attributes = $entry.Attributes -band (-bnot [IO.FileAttributes]::Hidden) + $restored++ + } + } + Set-Content -LiteralPath $ledger -Value "" -NoNewline + if ($restored -gt 0) { Write-Host "==> 已还原 $restored 个被隐藏的桌面项" -ForegroundColor Cyan } + } + } + catch { + Write-Host "!! 还原隐藏的桌面项失败(DeskBox 下次启动会再还原):$($_.Exception.Message)" -ForegroundColor Yellow + } + Write-Host "==> 拉取 origin/$Branch" -ForegroundColor Cyan git fetch origin $Branch if ($LASTEXITCODE -ne 0) { throw "git fetch 失败" } diff --git a/src/DeskBox/App.MappedOrganize.cs b/src/DeskBox/App.MappedOrganize.cs index 261ffc46a..773c8a822 100644 --- a/src/DeskBox/App.MappedOrganize.cs +++ b/src/DeskBox/App.MappedOrganize.cs @@ -28,7 +28,16 @@ private void InitializeMappedOrganize(WidgetManager widgetManager) // (Environment.Exit from fatal handlers, session end). A hard kill // cannot run this; the next start repairs it from the durable // marker, and Explorer itself shows the icons again on restart. - AppDomain.CurrentDomain.ProcessExit += (_, _) => _mappedOrganizeService?.RestoreIconsForExit(); + AppDomain.CurrentDomain.ProcessExit += (_, _) => _mappedOrganizeService?.RestoreIconsForExit("process-exit"); + // A crash on a background thread ends the process: best effort. + AppDomain.CurrentDomain.UnhandledException += (_, args) => + { + if (args.IsTerminating) + { + _mappedOrganizeService?.RestoreIconsForExit("crash"); + } + }; + ForkSessionEndSignal.Cancelled += () => _mappedOrganizeService?.ResumeAfterCancelledSessionEnd(); } catch (Exception ex) { @@ -36,6 +45,10 @@ private void InitializeMappedOrganize(WidgetManager widgetManager) } } + /// Synchronous restore of every DeskBox-hidden desktop item; safe to call repeatedly. + private void RestoreMappedOrganizeBeforeExit(string reason, bool sessionEnd = false) => + _mappedOrganizeService?.RestoreIconsForExit(reason, sessionEnd); + private void ShutdownMappedOrganize() { _mappedOrganizeService?.Dispose(); diff --git a/src/DeskBox/App.xaml.cs b/src/DeskBox/App.xaml.cs index 723f45f6b..54b021721 100644 --- a/src/DeskBox/App.xaml.cs +++ b/src/DeskBox/App.xaml.cs @@ -1510,6 +1510,8 @@ await RunOptionalStartupStepAsync( // before the restoration phase starts writing normalized state). await startupAutomaticSnapshotTask; if (IsShuttingDown) return; + // GOXF fork: 映射整理 — show items a killed / crashed / older run left hidden. + RunOptionalStartupStep("mapped-organize-recovery", MappedOrganizeStartupRecovery.Run); int recoveredDesktopItems = 0; if (SuppressFileMutatingStartup) { @@ -2401,6 +2403,9 @@ private void OnLifecycleRecoveryRequested(string reason) private void FlushSettingsForEndSession(string reason) { + // GOXF fork: 映射整理 — show every DeskBox-hidden desktop item before + // Windows ends the process (shutdown / restart / sign-out / installer). + RestoreMappedOrganizeBeforeExit(reason, sessionEnd: true); // The OS ends the process after this flush without the shutdown // sequence, so the launch breadcrumb is closed here. _startupSessionLedger?.MarkCleanExit(); @@ -6602,6 +6607,9 @@ private async Task ShutdownApplicationAsync() // Recorded first so a death anywhere inside teardown still reads as // an intentional exit on the next launch (storm-guard semantics). _startupSessionLedger?.MarkCleanExit(); + // GOXF fork: 映射整理 — restore hidden desktop items first, before any + // bounded teardown step can time out and skip the later steps. + RestoreMappedOrganizeBeforeExit("shutdown"); bool dependentTeardownCompleted = true; try { diff --git a/src/DeskBox/Platform/ForkFileIdentityNative.cs b/src/DeskBox/Platform/ForkFileIdentityNative.cs new file mode 100644 index 000000000..b70db4932 --- /dev/null +++ b/src/DeskBox/Platform/ForkFileIdentityNative.cs @@ -0,0 +1,121 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace DeskBox.Platform; + +/// +/// GOXF fork, 「映射整理」: stable NTFS identity (volume serial + file index) +/// of a desktop entry DeskBox hid, so an entry that leaves the desktop (moved +/// to another folder, cut/paste, dragged out, recycled) can be found again by +/// its id and its hidden attribute cleared at the new location. A +/// FileSystemWatcher only reports such a move as a deletion on the desktop. +/// +internal static partial class ForkFileIdentityNative +{ + private const uint FileReadAttributes = 0x0080; + private const uint FileShareAll = 0x0001 | 0x0002 | 0x0004; + private const uint OpenExisting = 3; + private const uint FileFlagBackupSemantics = 0x02000000; + + [StructLayout(LayoutKind.Sequential)] + private struct ByHandleFileInformation + { + public uint FileAttributes; + public uint CreationTimeLow; + public uint CreationTimeHigh; + public uint LastAccessTimeLow; + public uint LastAccessTimeHigh; + public uint LastWriteTimeLow; + public uint LastWriteTimeHigh; + public uint VolumeSerialNumber; + public uint FileSizeHigh; + public uint FileSizeLow; + public uint NumberOfLinks; + public uint FileIndexHigh; + public uint FileIndexLow; + } + + [StructLayout(LayoutKind.Explicit, Size = 24)] + private struct FileIdDescriptor + { + [FieldOffset(0)] public uint Size; + [FieldOffset(4)] public int Type; // FileIdType = 0 + [FieldOffset(8)] public long FileId; + } + + [LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static partial SafeFileHandle CreateFile( + string fileName, uint desiredAccess, uint shareMode, nint securityAttributes, + uint creationDisposition, uint flagsAndAttributes, nint templateFile); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool GetFileInformationByHandle(SafeFileHandle file, out ByHandleFileInformation information); + + [LibraryImport("kernel32.dll", SetLastError = true)] + private static partial SafeFileHandle OpenFileById( + SafeFileHandle volumeHint, in FileIdDescriptor fileId, uint desiredAccess, uint shareMode, + nint securityAttributes, uint flagsAndAttributes); + + [LibraryImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", SetLastError = true)] + private static unsafe partial uint GetFinalPathNameByHandle(SafeFileHandle file, char* path, uint length, uint flags); + + /// Identity of a file or folder, or null when it cannot be read (not NTFS, gone, no access). + public static (uint VolumeSerial, ulong FileIndex)? TryGet(string path) + { + try + { + using SafeFileHandle handle = CreateFile(path, FileReadAttributes, FileShareAll, 0, OpenExisting, FileFlagBackupSemantics, 0); + if (handle.IsInvalid || !GetFileInformationByHandle(handle, out ByHandleFileInformation info)) + { + return null; + } + + ulong index = ((ulong)info.FileIndexHigh << 32) | info.FileIndexLow; + return index == 0 ? null : (info.VolumeSerialNumber, index); + } + catch (Exception) + { + return null; + } + } + + /// + /// Final path (\\?\ form) of the entry with this id, opened by id on the + /// volume of ; null when the entry + /// no longer exists there (deleted, or moved to another volume). + /// + public static unsafe string? TryResolvePath(uint volumeSerial, ulong fileIndex, string volumeHintDirectory) + { + try + { + using SafeFileHandle hint = CreateFile(volumeHintDirectory, FileReadAttributes, FileShareAll, 0, OpenExisting, FileFlagBackupSemantics, 0); + if (hint.IsInvalid || + !GetFileInformationByHandle(hint, out ByHandleFileInformation hintInfo) || + hintInfo.VolumeSerialNumber != volumeSerial) + { + return null; + } + + var descriptor = new FileIdDescriptor { Size = 24, Type = 0, FileId = unchecked((long)fileIndex) }; + using SafeFileHandle file = OpenFileById(hint, in descriptor, FileReadAttributes, FileShareAll, 0, FileFlagBackupSemantics); + if (file.IsInvalid) + { + return null; + } + + char* buffer = stackalloc char[1024]; + uint length = GetFinalPathNameByHandle(file, buffer, 1024, 0); + if (length == 0 || length >= 1024) + { + return null; + } + + return new string(buffer, 0, (int)length); + } + catch (Exception) + { + return null; + } + } +} diff --git a/src/DeskBox/Services/AppLifecycleRecoveryWatcher.cs b/src/DeskBox/Services/AppLifecycleRecoveryWatcher.cs index 93347e1b3..d47944412 100644 --- a/src/DeskBox/Services/AppLifecycleRecoveryWatcher.cs +++ b/src/DeskBox/Services/AppLifecycleRecoveryWatcher.cs @@ -145,6 +145,10 @@ private IntPtr WindowSubclassProc( { InvokeEndSessionAction("end-session"); } + else + { + ForkSessionEndSignal.RaiseCancelled(); // GOXF fork: 映射整理 re-hides + } } else if (message == AppLifecycleRecoverySignalClassifier.WmWtsSessionChange) { diff --git a/src/DeskBox/Services/DesktopOrganizationScanner.cs b/src/DeskBox/Services/DesktopOrganizationScanner.cs index ee3d7ee49..9ff262120 100644 --- a/src/DeskBox/Services/DesktopOrganizationScanner.cs +++ b/src/DeskBox/Services/DesktopOrganizationScanner.cs @@ -146,7 +146,8 @@ private DesktopOrganizationFileSnapshot CreateSnapshot( try { - FileAttributes attributes = File.GetAttributes(fullPath); + // GOXF fork: entries hidden by 「映射整理」 are normal desktop items. + FileAttributes attributes = MappedOrganizeHiddenRegistry.EffectiveAttributes(fullPath, File.GetAttributes(fullPath)); isDirectory = (attributes & FileAttributes.Directory) != 0; bool isHiddenOrSystem = (attributes & (FileAttributes.Hidden | FileAttributes.System)) != 0 || name.Equals("desktop.ini", StringComparison.OrdinalIgnoreCase); diff --git a/src/DeskBox/Services/MappedOrganizeDesktopVisibility.cs b/src/DeskBox/Services/MappedOrganizeDesktopVisibility.cs index fefbe2c8b..7add16a11 100644 --- a/src/DeskBox/Services/MappedOrganizeDesktopVisibility.cs +++ b/src/DeskBox/Services/MappedOrganizeDesktopVisibility.cs @@ -152,6 +152,16 @@ public static bool IsHiddenByDeskBox(string? path) } } + /// + /// Attributes as the desktop organizer should see them: an entry hidden by + /// DeskBox (in the ledger) is a normal desktop item, not 「无法整理」. + /// + public static FileAttributes EffectiveAttributes(string path, FileAttributes attributes) => + Effective(attributes, (attributes & FileAttributes.Hidden) != 0 && IsHiddenByDeskBox(path)); + + public static FileAttributes Effective(FileAttributes attributes, bool hiddenByDeskBox) => + hiddenByDeskBox ? attributes & ~FileAttributes.Hidden : attributes; + internal static void Publish(IEnumerable paths) { var copy = new HashSet(paths, StringComparer.OrdinalIgnoreCase); diff --git a/src/DeskBox/Services/MappedOrganizeExitSafety.cs b/src/DeskBox/Services/MappedOrganizeExitSafety.cs new file mode 100644 index 000000000..87ba1625b --- /dev/null +++ b/src/DeskBox/Services/MappedOrganizeExitSafety.cs @@ -0,0 +1,197 @@ +namespace DeskBox.Services; + +/// NTFS identity of a desktop entry DeskBox hid (volume serial + file index). +public readonly record struct MappedOrganizeFileIdentity(uint VolumeSerial, ulong FileIndex); + +/// +/// GOXF fork, 「映射整理」: whether DeskBox currently keeps mapped entries +/// hidden. Every exit path (tray exit, restart / update, Windows +/// shutdown / restart / sign-out, crash) restores the entries first; a +/// session end that another application cancels resumes hiding, a real exit +/// never does. Pure and thread-safe; unit-tested in ForkHiddenRestoreTests. +/// +public sealed class MappedOrganizeExitGate +{ + private readonly object _gate = new(); + private State _state; + + private enum State + { + Running, + RestoredForSessionEnd, + Exiting, + } + + /// True while mapped entries must stay visible (restored for exit / session end). + public bool IsRestored + { + get + { + lock (_gate) + { + return _state != State.Running; + } + } + } + + /// + /// Records a restore. is a Windows + /// QUERYENDSESSION / ENDSESSION, which can still be cancelled; anything + /// else is final. Returns true when this call is the first restore. + /// + public bool Restore(bool sessionEnd) + { + lock (_gate) + { + bool first = _state == State.Running; + if (!sessionEnd) + { + _state = State.Exiting; + } + else if (first) + { + _state = State.RestoredForSessionEnd; + } + + return first; + } + } + + /// The session end was cancelled: hide again unless DeskBox is exiting anyway. + public bool TryResume() + { + lock (_gate) + { + if (_state != State.RestoredForSessionEnd) + { + return false; + } + + _state = State.Running; + return true; + } + } +} + +/// Raised by the lifecycle watcher when a Windows session end is cancelled (WM_ENDSESSION with FALSE). +public static class ForkSessionEndSignal +{ + public static event Action? Cancelled; + + public static void RaiseCancelled() + { + try + { + Cancelled?.Invoke(); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Session-end cancel handler failed: {ex.Message}"); + } + } +} + +/// +/// Where a DeskBox-hidden desktop entry went after the desktop reported it +/// deleted. The hidden attribute must never travel with it: a moved entry is +/// made visible at its new location and leaves the ledger. +/// +public static class MappedOrganizeLeakPolicy +{ + public enum Outcome + { + /// Really deleted (or moved to another volume): just forget it. + Gone, + + /// Still a desktop entry (a rename seen as delete): keep the record. + StillOnDesktop, + + /// Moved elsewhere (another folder, the Recycle Bin): clear the attribute there. + LeftDesktop, + } + + public static Outcome Classify(string? resolvedPath, Func isDesktopEntry) + { + if (string.IsNullOrWhiteSpace(resolvedPath)) + { + return Outcome.Gone; + } + + return isDesktopEntry(resolvedPath) ? Outcome.StillOnDesktop : Outcome.LeftDesktop; + } + + /// Turns a GetFinalPathNameByHandle result (\\?\C:\x, \\?\UNC\srv\share\x) into a normal path. + public static string NormalizeFinalPath(string path) + { + if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase)) + { + return @"\\" + path[8..]; + } + + return path.StartsWith(@"\\?\", StringComparison.Ordinal) ? path[4..] : path; + } +} + +/// +/// Startup recovery: before widgets are restored, every entry the ledger says +/// DeskBox hid is made visible again (a previous run was killed, crashed, or +/// was an older build), the ledger is emptied and the outcome is logged. The +/// mapped-organize service then hides the current members again. +/// +public static class MappedOrganizeStartupRecovery +{ + /// The ledger entries that still exist and are hidden. + public static IReadOnlyList PlanRestore(IEnumerable ledger, Func probe) => + ledger + .Where(path => probe(path) is { } attributes && (attributes & FileAttributes.Hidden) != 0) + .ToList(); + + public static void Run() + { + string ledgerPath = MappedOrganizeHiddenRegistry.LedgerPath(); + if (!File.Exists(ledgerPath)) + { + return; + } + + IReadOnlyList ledger = MappedOrganizeHiddenLedger.Parse(File.ReadAllText(ledgerPath)); + if (ledger.Count == 0) + { + return; + } + + int restored = 0; + var failed = new List(); + foreach (string path in PlanRestore(ledger, ProbeAttributes)) + { + try + { + File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.Hidden); + restored++; + } + catch (Exception ex) + { + failed.Add(path); + App.Log($"[MappedOrganize] Startup recovery could not show '{path}': {ex.Message}"); + } + } + + // Entries that could not be restored stay recorded so the service + // (or the uninstaller) retries them; everything else is visible now. + File.WriteAllText(ledgerPath, MappedOrganizeHiddenLedger.Serialize(failed)); + MappedOrganizeHiddenRegistry.Publish(failed); + App.Log($"[MappedOrganize] Startup recovery: ledger had {ledger.Count} entries, restored {restored}, failed {failed.Count}."); + } + + private static FileAttributes? ProbeAttributes(string path) + { + try + { + return File.Exists(path) || Directory.Exists(path) ? File.GetAttributes(path) : null; + } + catch (Exception) + { + return null; + } + } +} diff --git a/src/DeskBox/Services/MappedOrganizeService.LeakGuard.cs b/src/DeskBox/Services/MappedOrganizeService.LeakGuard.cs new file mode 100644 index 000000000..3ff5c2e10 --- /dev/null +++ b/src/DeskBox/Services/MappedOrganizeService.LeakGuard.cs @@ -0,0 +1,79 @@ +using DeskBox.Platform; + +namespace DeskBox.Services; + +/// +/// 「映射整理」 hidden-attribute leak guard (GOXF fork). A DeskBox-hidden +/// desktop entry that leaves the desktop (moved / cut-pasted / dragged into +/// another folder, or recycled) keeps its file id on the same volume; the +/// desktop watcher only reports a deletion, so the entry is found again by +/// the id captured when it was hidden, made visible where it now lives, and +/// dropped from the ledger. Cost: one CreateFile when an entry is hidden and +/// one OpenFileById per deleted ledger entry. +/// +public sealed partial class MappedOrganizeService +{ + private int HiddenLedgerCount + { + get + { + lock (_visibilityGate) + { + return _hiddenLedger.Count; + } + } + } + + /// Caller holds . + private void CaptureIdentity(string path) + { + if (ForkFileIdentityNative.TryGet(path) is { } identity) + { + _hiddenIdentities[MappedOrganizeMembership.NormalizePath(path)] = + new MappedOrganizeFileIdentity(identity.VolumeSerial, identity.FileIndex); + } + } + + private void ReleaseIfMovedOffDesktop(string path) + { + try + { + string key = MappedOrganizeMembership.NormalizePath(path); + lock (_visibilityGate) + { + if (!_hiddenLedger.Contains(key)) + { + return; + } + + string? resolved = null; + if (_hiddenIdentities.TryGetValue(key, out MappedOrganizeFileIdentity identity) && + Path.GetDirectoryName(key) is { Length: > 0 } desktopDirectory) + { + string? finalPath = ForkFileIdentityNative.TryResolvePath(identity.VolumeSerial, identity.FileIndex, desktopDirectory); + resolved = finalPath is null ? null : MappedOrganizeLeakPolicy.NormalizeFinalPath(finalPath); + } + + switch (MappedOrganizeLeakPolicy.Classify(resolved, IsDesktopEntryPath)) + { + case MappedOrganizeLeakPolicy.Outcome.StillOnDesktop: + return; + case MappedOrganizeLeakPolicy.Outcome.LeftDesktop: + bool shown = TrySetHidden(resolved!, hidden: false); + App.Log($"[MappedOrganize] Hidden entry left the desktop: '{key}' -> '{resolved}', attribute cleared={shown}."); + break; + default: + break; + } + + _hiddenLedger.Remove(key); + _hiddenIdentities.Remove(key); + PersistHiddenLedger(); + } + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Leak guard failed for '{path}': {ex.Message}"); + } + } +} diff --git a/src/DeskBox/Services/MappedOrganizeService.Visibility.cs b/src/DeskBox/Services/MappedOrganizeService.Visibility.cs index 373cb31ae..aaaad6e61 100644 --- a/src/DeskBox/Services/MappedOrganizeService.Visibility.cs +++ b/src/DeskBox/Services/MappedOrganizeService.Visibility.cs @@ -13,7 +13,8 @@ public sealed partial class MappedOrganizeService private readonly HashSet _keptOnDesktop = new(StringComparer.OrdinalIgnoreCase); private FileSystemWatcher? _modeWatcher; private DesktopOrganizeMode _mode = DesktopOrganizeMode.MoveToWidgets; - private volatile bool _restoredForExit; + private readonly MappedOrganizeExitGate _exitGate = new(); + private readonly Dictionary _hiddenIdentities = new(StringComparer.OrdinalIgnoreCase); /// Entries currently marked 「放回桌面」 (copy; UI thread). public IReadOnlyCollection KeptOnDesktopSnapshot() => _keptOnDesktop.ToArray(); @@ -126,6 +127,10 @@ private void LoadVisibilityState() _hiddenLedger.Clear(); _hiddenLedger.UnionWith(ReadList(HiddenLedgerPath, MappedOrganizeHiddenLedger.Parse)); MappedOrganizeHiddenRegistry.Publish(_hiddenLedger); + foreach (string path in _hiddenLedger) + { + CaptureIdentity(path); + } } _keptOnDesktop.Clear(); @@ -145,7 +150,7 @@ private void ReconcileDesktopVisibility() { lock (_visibilityGate) { - List desired = _restoredForExit || _isDisposed + List desired = _exitGate.IsRestored || _isDisposed ? new List() : LiveMappedWidgets().SelectMany(MappedOrganizeMembership.GetMembers).ToList(); MappedOrganizeHiddenLedger.Plan plan = MappedOrganizeHiddenLedger.Reconcile(desired, _hiddenLedger, ProbeAttributes); @@ -163,6 +168,7 @@ private void ReconcileDesktopVisibility() foreach (string path in plan.Forget) { ledgerChanged |= _hiddenLedger.Remove(path); + _hiddenIdentities.Remove(path); } if (ledgerChanged) @@ -176,6 +182,7 @@ private void ReconcileDesktopVisibility() if (TrySetHidden(path, hidden: true)) { hidden++; + CaptureIdentity(path); } else { @@ -193,6 +200,7 @@ private void ReconcileDesktopVisibility() { restored++; _hiddenLedger.Remove(path); + _hiddenIdentities.Remove(path); ledgerChanged = true; } } @@ -221,6 +229,12 @@ private void RenameVisibilityRecords(string oldPath, string newPath, out bool wa { if (MappedOrganizeHiddenLedger.Rename(_hiddenLedger, oldPath, newPath)) { + string oldKey = MappedOrganizeMembership.NormalizePath(oldPath); + if (_hiddenIdentities.Remove(oldKey, out MappedOrganizeFileIdentity identity)) + { + _hiddenIdentities[MappedOrganizeMembership.NormalizePath(newPath)] = identity; + } + PersistHiddenLedger(); } } diff --git a/src/DeskBox/Services/MappedOrganizeService.cs b/src/DeskBox/Services/MappedOrganizeService.cs index 6b52d66bd..5d73ee556 100644 --- a/src/DeskBox/Services/MappedOrganizeService.cs +++ b/src/DeskBox/Services/MappedOrganizeService.cs @@ -163,24 +163,54 @@ public void Shutdown() } /// - /// Best-effort restore usable from ProcessExit / fatal paths: every entry - /// DeskBox hid becomes visible again (membership stays; the next start - /// hides the members again). + /// Synchronous restore for every exit path (tray exit, restart / update, + /// Windows session end, ProcessExit, crash): every entry DeskBox hid + /// becomes visible again before the process can end (membership stays; + /// the next start hides the members again). Idempotent and fast (one + /// attribute write per hidden entry). marks a + /// Windows QUERYENDSESSION / ENDSESSION, which another application can + /// still cancel (see ). /// - public void RestoreIconsForExit() + public void RestoreIconsForExit(string reason = "exit", bool sessionEnd = false) { try { - _restoredForExit = true; + bool first = _exitGate.Restore(sessionEnd); + int before = HiddenLedgerCount; + long started = Environment.TickCount64; ReconcileDesktopVisibility(); - DesktopIconVisibilityService.Apply(hidden: false); + if (first || before > 0) + { + App.Log($"[MappedOrganize] Restored desktop items for {reason}: ledger {before} -> {HiddenLedgerCount} in {Environment.TickCount64 - started} ms."); + } + + if (first) + { + DesktopIconVisibilityService.Apply(hidden: false); + } } catch (Exception ex) { - App.Log($"[MappedOrganize] Restoring desktop items on exit failed: {ex.Message}"); + App.Log($"[MappedOrganize] Restoring desktop items for {reason} failed: {ex.Message}"); } } + /// Another application cancelled the Windows session end: hide the mapped entries again. + public void ResumeAfterCancelledSessionEnd() + { + if (_isDisposed || !_exitGate.TryResume()) + { + return; + } + + App.Log("[MappedOrganize] Session end was cancelled; hiding mapped desktop items again."); + Enqueue(() => + { + ReconcileDesktopVisibility(); + return Task.CompletedTask; + }); + } + public void SetAutoAssignNewItems(bool enabled) { if (_autoAssignNewItems == enabled) @@ -633,6 +663,7 @@ private Task OnEntryCreated(string path) private Task OnEntryDeleted(string path) { _pendingNewEntries.Remove(path); + ReleaseIfMovedOffDesktop(path); if (MappedOrganizeKeepList.Release(_keptOnDesktop, [path])) { SaveKeptOnDesktop(); diff --git a/tests/DeskBox.Tests/ForkHiddenRestoreTests.cs b/tests/DeskBox.Tests/ForkHiddenRestoreTests.cs new file mode 100644 index 000000000..b309223c8 --- /dev/null +++ b/tests/DeskBox.Tests/ForkHiddenRestoreTests.cs @@ -0,0 +1,92 @@ +using DeskBox.Services; + +namespace DeskBox.Tests; + +/// GOXF fork 「映射整理」: restore-before-exit state, startup recovery plan and the hidden-attribute leak policy. +public sealed class ForkHiddenRestoreTests +{ + private static readonly string Desktop = Path.Combine(Path.GetTempPath(), "deskbox-fork-hidden-tests", "Desktop"); + + private static string D(string name) => MappedOrganizeMembership.NormalizePath(Path.Combine(Desktop, name)); + + [Fact] + public void ExitGate_FinalExit_NeverResumes() + { + var gate = new MappedOrganizeExitGate(); + Assert.False(gate.IsRestored); + Assert.True(gate.Restore(sessionEnd: false)); + Assert.True(gate.IsRestored); + Assert.False(gate.Restore(sessionEnd: false)); + Assert.False(gate.TryResume()); + Assert.True(gate.IsRestored); + } + + [Fact] + public void ExitGate_CancelledSessionEnd_ResumesHiding() + { + var gate = new MappedOrganizeExitGate(); + Assert.True(gate.Restore(sessionEnd: true)); + Assert.False(gate.Restore(sessionEnd: true)); // QUERYENDSESSION then ENDSESSION + Assert.True(gate.IsRestored); + Assert.True(gate.TryResume()); + Assert.False(gate.IsRestored); + Assert.False(gate.TryResume()); + } + + [Fact] + public void ExitGate_ShutdownDuringSessionEnd_StaysRestored() + { + var gate = new MappedOrganizeExitGate(); + gate.Restore(sessionEnd: true); + gate.Restore(sessionEnd: false); + Assert.False(gate.TryResume()); + Assert.True(gate.IsRestored); + } + + [Fact] + public void StartupRecovery_RestoresOnlyExistingHiddenLedgerEntries() + { + var files = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [D("hidden.png")] = FileAttributes.Archive | FileAttributes.Hidden, + [D("visible.png")] = FileAttributes.Archive, + }; + + IReadOnlyList plan = MappedOrganizeStartupRecovery.PlanRestore( + [D("hidden.png"), D("visible.png"), D("gone.png")], + path => files.TryGetValue(path, out FileAttributes? value) ? value : null); + + Assert.Equal(new[] { D("hidden.png") }, plan); + } + + [Fact] + public void LeakPolicy_ClassifiesWhereTheEntryWent() + { + static bool IsDesktop(string path) => + string.Equals(Path.GetDirectoryName(path), MappedOrganizeMembership.NormalizePath(Desktop), StringComparison.OrdinalIgnoreCase); + + Assert.Equal(MappedOrganizeLeakPolicy.Outcome.Gone, MappedOrganizeLeakPolicy.Classify(null, IsDesktop)); + Assert.Equal(MappedOrganizeLeakPolicy.Outcome.StillOnDesktop, MappedOrganizeLeakPolicy.Classify(D("renamed.png"), IsDesktop)); + Assert.Equal( + MappedOrganizeLeakPolicy.Outcome.LeftDesktop, + MappedOrganizeLeakPolicy.Classify(Path.Combine(Desktop, "Sub", "moved.png"), IsDesktop)); + } + + [Theory] + [InlineData(@"\\?\C:\Users\me\Docs\a.txt", @"C:\Users\me\Docs\a.txt")] + [InlineData(@"\\?\UNC\server\share\a.txt", @"\\server\share\a.txt")] + [InlineData(@"C:\plain\a.txt", @"C:\plain\a.txt")] + public void LeakPolicy_NormalizesFinalPaths(string input, string expected) => + Assert.Equal(expected, MappedOrganizeLeakPolicy.NormalizeFinalPath(input)); + + [Fact] + public void Registry_EffectiveAttributes_TreatDeskBoxHiddenAsNormal() + { + FileAttributes hidden = FileAttributes.Archive | FileAttributes.Hidden; + Assert.Equal(FileAttributes.Archive, MappedOrganizeHiddenRegistry.Effective(hidden, hiddenByDeskBox: true)); + Assert.Equal(hidden, MappedOrganizeHiddenRegistry.Effective(hidden, hiddenByDeskBox: false)); + Assert.Equal( + FileAttributes.Archive | FileAttributes.System, + MappedOrganizeHiddenRegistry.Effective(FileAttributes.Archive | FileAttributes.System | FileAttributes.Hidden, hiddenByDeskBox: true)); + } +}