Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions docs/architecture/mapped-organize.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <reason>`.

| 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
Expand Down Expand Up @@ -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).

Expand All @@ -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
Expand Down
23 changes: 23 additions & 0 deletions scripts/fork-dev-update.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 失败" }
Expand Down
15 changes: 14 additions & 1 deletion src/DeskBox/App.MappedOrganize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,27 @@ 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)
{
Log($"[Startup] Optional step 'mapped-organize' failed: {ex}");
}
}

/// <summary>Synchronous restore of every DeskBox-hidden desktop item; safe to call repeatedly.</summary>
private void RestoreMappedOrganizeBeforeExit(string reason, bool sessionEnd = false) =>
_mappedOrganizeService?.RestoreIconsForExit(reason, sessionEnd);

private void ShutdownMappedOrganize()
{
_mappedOrganizeService?.Dispose();
Expand Down
8 changes: 8 additions & 0 deletions src/DeskBox/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1510,6 +1510,8 @@
// 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)
{
Expand Down Expand Up @@ -2401,6 +2403,9 @@

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();
Expand Down Expand Up @@ -2785,7 +2790,7 @@
return null;
}

return window.CurrentContent is Controls.WidgetContents.TodoWidgetContentAdapter adapter &&

Check warning on line 2793 in src/DeskBox/App.xaml.cs

View workflow job for this annotation

GitHub Actions / Build and test

Dereference of a possibly null reference.

Check warning on line 2793 in src/DeskBox/App.xaml.cs

View workflow job for this annotation

GitHub Actions / Build and test

Dereference of a possibly null reference.
adapter.ViewModel.IsInitialized
? adapter.ViewModel
: null;
Expand Down Expand Up @@ -6602,6 +6607,9 @@
// 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
{
Expand Down
121 changes: 121 additions & 0 deletions src/DeskBox/Platform/ForkFileIdentityNative.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace DeskBox.Platform;

/// <summary>
/// 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.
/// </summary>
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);

/// <summary>Identity of a file or folder, or null when it cannot be read (not NTFS, gone, no access).</summary>
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;
}
}

/// <summary>
/// Final path (\\?\ form) of the entry with this id, opened by id on the
/// volume of <paramref name="volumeHintDirectory"/>; null when the entry
/// no longer exists there (deleted, or moved to another volume).
/// </summary>
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;
}
}
}
4 changes: 4 additions & 0 deletions src/DeskBox/Services/AppLifecycleRecoveryWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ private IntPtr WindowSubclassProc(
{
InvokeEndSessionAction("end-session");
}
else
{
ForkSessionEndSignal.RaiseCancelled(); // GOXF fork: 映射整理 re-hides
}
}
else if (message == AppLifecycleRecoverySignalClassifier.WmWtsSessionChange)
{
Expand Down
3 changes: 2 additions & 1 deletion src/DeskBox/Services/DesktopOrganizationScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
10 changes: 10 additions & 0 deletions src/DeskBox/Services/MappedOrganizeDesktopVisibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,16 @@ public static bool IsHiddenByDeskBox(string? path)
}
}

/// <summary>
/// Attributes as the desktop organizer should see them: an entry hidden by
/// DeskBox (in the ledger) is a normal desktop item, not 「无法整理」.
/// </summary>
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<string> paths)
{
var copy = new HashSet<string>(paths, StringComparer.OrdinalIgnoreCase);
Expand Down
Loading
Loading