From bcd28b62d20d84a5675aa7537dc0c2a5dec76029 Mon Sep 17 00:00:00 2001
From: GOXF <131693427+GOXF@users.noreply.github.com>
Date: Sun, 8 Nov 2026 03:49:52 +0000
Subject: [PATCH 1/2] =?UTF-8?q?feat(desktop-organize):=20=E6=98=A0?=
=?UTF-8?q?=E5=B0=84=E6=95=B4=E7=90=86=20=E2=80=94=20map=20desktop=20items?=
=?UTF-8?q?=20into=20widgets=20without=20moving=20files?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Adds a mapped (virtual) organize mode: the preview option 只映射,不移动文件
creates mapped-organize widgets that map the Desktop and only record
membership in their metadata. Native desktop icons are hidden while mapped
widgets exist and restored on dissolve/exit/startup repair. New desktop
items are auto-assigned after the auto-organize settle delay (switchable to
manual 一键整理). See docs/architecture/mapped-organize.md.
---
docs/architecture/mapped-organize.md | 90 ++
src/DeskBox/App.MappedOrganize.cs | 45 +
src/DeskBox/App.xaml.cs | 3 +
.../DesktopOrganizationTaskView.Actions.cs | 5 +
...ktopOrganizationTaskView.MappedOrganize.cs | 116 +++
.../Controls/DesktopOrganizationTaskView.xaml | 2 +
.../FileSurfaceContent.MappedOrganize.cs | 42 +
.../FileSurfaceContent.SelectionAndMenus.cs | 1 +
src/DeskBox/Models/MappedOrganizeModels.cs | 59 ++
.../Services/DesktopIconVisibilityService.cs | 66 ++
.../DesktopOrganizationCoordinator.cs | 6 +-
.../DesktopOrganizationRuleResolver.cs | 3 +-
.../Services/MappedOrganizeMembership.cs | 259 ++++++
src/DeskBox/Services/MappedOrganizeService.cs | 804 ++++++++++++++++++
.../Services/WidgetManager.MappedOrganize.cs | 31 +
src/DeskBox/Services/WidgetManager.cs | 3 +-
src/DeskBox/Strings/ar-SA.json | 6 +
src/DeskBox/Strings/bn-BD.json | 6 +
src/DeskBox/Strings/de-DE.json | 6 +
src/DeskBox/Strings/en-US.json | 6 +
src/DeskBox/Strings/es-ES.json | 6 +
src/DeskBox/Strings/fr-FR.json | 6 +
src/DeskBox/Strings/hi-IN.json | 6 +
src/DeskBox/Strings/ja-JP.json | 6 +
src/DeskBox/Strings/ko-KR.json | 6 +
src/DeskBox/Strings/pt-BR.json | 6 +
src/DeskBox/Strings/ru-RU.json | 6 +
src/DeskBox/Strings/zh-CN.json | 6 +
src/DeskBox/Strings/zh-TW.json | 6 +
.../WidgetViewModel.ItemHydration.cs | 1 +
.../WidgetViewModel.MappedOrganize.cs | 110 +++
.../ViewModels/WidgetViewModel.Operations.cs | 7 +
.../WidgetViewModel.SortingAndWatchers.cs | 6 +
src/DeskBox/ViewModels/WidgetViewModel.cs | 2 +
.../MappedOrganizeMembershipTests.cs | 162 ++++
35 files changed, 1897 insertions(+), 4 deletions(-)
create mode 100644 docs/architecture/mapped-organize.md
create mode 100644 src/DeskBox/App.MappedOrganize.cs
create mode 100644 src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs
create mode 100644 src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs
create mode 100644 src/DeskBox/Models/MappedOrganizeModels.cs
create mode 100644 src/DeskBox/Services/DesktopIconVisibilityService.cs
create mode 100644 src/DeskBox/Services/MappedOrganizeMembership.cs
create mode 100644 src/DeskBox/Services/MappedOrganizeService.cs
create mode 100644 src/DeskBox/Services/WidgetManager.MappedOrganize.cs
create mode 100644 src/DeskBox/ViewModels/WidgetViewModel.MappedOrganize.cs
create mode 100644 tests/DeskBox.Tests/MappedOrganizeMembershipTests.cs
diff --git a/docs/architecture/mapped-organize.md b/docs/architecture/mapped-organize.md
new file mode 100644
index 000000000..9f6748982
--- /dev/null
+++ b/docs/architecture/mapped-organize.md
@@ -0,0 +1,90 @@
+# 映射整理 (mapped / virtual desktop organize) — fork feature
+
+Fork-only feature (GOXF/DeskBox `custom`). Like 360桌面助手 / WPS 桌面整理:
+desktop items are grouped into widgets **without moving any file**.
+
+## Model
+
+* A mapped-organize widget is an ordinary `WidgetKind.File` widget whose
+ `MappedFolderPath` is the user Desktop. The existing desktop branch of
+ `WidgetViewModel.LoadFolderContentsAsync` already merges the Public Desktop
+ and the folder watchers already watch both folders.
+* `WidgetConfig.Metadata` carries the feature state, so nothing new is
+ serialized and backup/restore/removal follow the widget automatically:
+ * `DeskBox.MappedOrganize = "1"` – marks the widget.
+ * `DeskBox.MappedOrganize.Category` – classifier category it collects.
+ * `DeskBox.MappedOrganize.Members` – newline-separated absolute paths.
+* Membership is exclusive (one widget per desktop entry). All rules are in the
+ pure `Services/MappedOrganizeMembership.cs` (unit-tested in
+ `tests/DeskBox.Tests/MappedOrganizeMembershipTests.cs`).
+* `Services/MappedOrganizeService.cs` is the runtime owner (UI-thread
+ mutations, desktop `FileSystemWatcher`s, auto-assignment, icon state).
+* Global flags live in `data/mapped-organize.state` (plain `key=value`, no new
+ JSON context so the serialization inventory contract stays frozen):
+ `autoAssignNewItems` (default true) and `desktopIconsHiddenByDeskBox`.
+
+## Flows
+
+| Action | Effect |
+|---|---|
+| Preview option 「只映射,不移动文件」 | `DesktopOrganizationTaskView.MappedOrganize.cs` turns the selected buckets into `MappedOrganizeGroup`s (one per category; existing mapped widget of that category is reused). Files untouched. Everything not selected is then routed by the same rules when auto mode is on, because it would otherwise be invisible. |
+| Open / rename / delete inside a mapped widget | Ordinary folder pipeline on the real file. Rename keeps membership (watcher rename → `RenamePath`); delete drops it. |
+| Drag between mapped widgets / drop desktop items on one | `WidgetViewModel.ImportPathsAsync` → `ClaimMappedOrganizeDrop` → membership only. |
+| Drop non-desktop items on a mapped widget | Normal import (moves into the Desktop folder); the new entry is claimed by that widget (`ExpectIncoming`, 2 min). |
+| Drag from a mapped widget into a normal folder widget | Normal move; watcher delete drops the membership. |
+| Changes outside DeskBox | Service watcher: rename → keep membership; delete → drop; create → auto-assign. Startup prunes members that no longer exist. |
+| New desktop files | Auto mode (default): after `DesktopAutoOrganizationDelaySeconds` + 1 s size-stability check, classified with `DesktopOrganizationClassifier`; same-category mapped widget, else 「其他」 (created on demand). Manual mode: widget menu 「一键整理」 only. Toggle: widget menu 「自动归类新文件」. |
+| Dissolve a mapped widget (close/remove widget) | `RemoveWidgetAsync` with `RemoveWidgetOnly` (mapped widgets never follow managed storage) – only the membership in its config disappears. Remaining mapped widgets pick up the orphans (auto mode). |
+| 「退出映射整理(恢复桌面图标)」 | Dissolves every mapped widget, icons restored. |
+
+Ordinary organization never targets mapped widgets: they are filtered out in
+`DesktopOrganizationRuleResolver.Resolve`, `CreateExecutionPlan` and
+`GetDestinationOptions`.
+
+## Native desktop icons (user accepted hiding)
+
+Choice: hide the desktop `SysListView32` (child of the desktop
+`SHELLDLL_DefView`) with `ShowWindow(SW_HIDE)`
+(`Services/DesktopIconVisibilityService.cs`), **not** Explorer's persisted
+"Show desktop icons" setting.
+
+* Not persisted by Explorer → no failure mode can leave the user permanently
+ without icons (Explorer restart / sign-out always shows them again).
+* Hidden while ≥1 mapped widget exists; shown when the last one is dissolved,
+ on DeskBox shutdown (`ShutdownStep "mapped-organize"`), and best-effort in
+ `AppDomain.ProcessExit`.
+* Crash safety: `desktopIconsHiddenByDeskBox` is written *before* hiding. On
+ the next start `MappedOrganizeService.Initialize` either re-applies (mapped
+ widgets exist) or restores (none left). It runs even if widget restore fails.
+* Explorer restarts recreate a visible list view; a 4 s dispatcher timer
+ re-hides it while mapped widgets exist.
+
+## Multi-monitor / sleep
+
+Mapped widgets are normal widgets, so the existing monitor binding,
+topology profiles and wake recovery apply unchanged.
+
+## Upstream-touching edits (keep minimal for the 6-hourly upstream merge)
+
+* `App.xaml.cs`: 2× `InitializeMappedOrganize(widgetManager);` after widget
+ restore (success and failure path), 1 shutdown step.
+* `WidgetViewModel.cs` (attach/detach), `.ItemHydration.cs` (filter desktop
+ snapshot), `.SortingAndWatchers.cs` (upsert guard), `.Operations.cs` (drop
+ claim).
+* `DesktopOrganizationRuleResolver.cs`, `DesktopOrganizationCoordinator.cs`:
+ exclude mapped widgets.
+* `DesktopOrganizationTaskView.xaml` (+ `.Actions.cs` one call),
+ `FileSurfaceContent.SelectionAndMenus.cs` (one call).
+* `Strings/*.json`: 6 keys inserted after `DesktopOrganization.Preview.Title`
+ (zh-CN / zh-TW translated, other locales English fallback).
+
+## Known gaps
+
+* Manual mode: new desktop files stay unassigned (and therefore invisible
+ while icons are hidden) until 「一键整理」.
+* Preview "use existing widget" destination choices are ignored in mapped mode
+ (grouping is per category).
+* No dedicated entry in the Settings window yet; the auto/manual switch is in
+ the mapped widget's blank-area menu.
+* Not runtime-verified on a real desktop in this change (CI builds and runs
+ unit tests only).
diff --git a/src/DeskBox/App.MappedOrganize.cs b/src/DeskBox/App.MappedOrganize.cs
new file mode 100644
index 000000000..261ffc46a
--- /dev/null
+++ b/src/DeskBox/App.MappedOrganize.cs
@@ -0,0 +1,45 @@
+using DeskBox.Services;
+
+namespace DeskBox;
+
+/// Fork feature 「映射整理」: host lifecycle (start after widget restore, always restore icons on exit).
+public partial class App
+{
+ private MappedOrganizeService? _mappedOrganizeService;
+
+ private void InitializeMappedOrganize(WidgetManager widgetManager)
+ {
+ if (_mappedOrganizeService is not null)
+ {
+ return;
+ }
+
+ try
+ {
+ var service = new MappedOrganizeService(
+ SettingsService,
+ widgetManager,
+ LocalizationService,
+ UiDispatcherQueue);
+ _mappedOrganizeService = service;
+ MappedOrganizeService.Current = service;
+ service.Initialize();
+ // Last-chance restore for paths that bypass the orderly shutdown
+ // (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();
+ }
+ catch (Exception ex)
+ {
+ Log($"[Startup] Optional step 'mapped-organize' failed: {ex}");
+ }
+ }
+
+ private void ShutdownMappedOrganize()
+ {
+ _mappedOrganizeService?.Dispose();
+ _mappedOrganizeService = null;
+ MappedOrganizeService.Current = null;
+ }
+}
diff --git a/src/DeskBox/App.xaml.cs b/src/DeskBox/App.xaml.cs
index 39a1f2ade..dc973b810 100644
--- a/src/DeskBox/App.xaml.cs
+++ b/src/DeskBox/App.xaml.cs
@@ -1551,6 +1551,7 @@ await RunOptionalStartupStepAsync(
try
{
await widgetManager.RestoreWidgetsAsync();
+ InitializeMappedOrganize(widgetManager);
}
catch (Exception ex)
{
@@ -1559,6 +1560,7 @@ await RunOptionalStartupStepAsync(
// blocking startup.
Log($"[Startup] Optional step 'restore-widgets' failed: {ex}");
RecordStartupDegradation("restore-widgets", ex.ToString());
+ InitializeMappedOrganize(widgetManager);
if (startupDesktopLayerReadinessTask is not null)
{
startupDesktopLayerReadinessTask = null;
@@ -6785,6 +6787,7 @@ private async Task ShutdownCoreAsync()
shutdownGrace),
// Hooks must be removed while their owning tray window still exists.
ShutdownStep.Sync("global-hotkey", () => { GlobalHotkeyService?.Dispose(); GlobalHotkeyService = null; }),
+ ShutdownStep.Sync("mapped-organize", ShutdownMappedOrganize),
ShutdownStep.Sync("widgets", () => WidgetManager?.CloseAll()),
ShutdownStep.Sync("desktop-organization-window", () => { _desktopOrganizationWindow?.CloseForShutdown(); _desktopOrganizationWindow = null; }),
ShutdownStep.Sync("settings-window", () =>
diff --git a/src/DeskBox/Controls/DesktopOrganizationTaskView.Actions.cs b/src/DeskBox/Controls/DesktopOrganizationTaskView.Actions.cs
index fa3674639..ad8057ef8 100644
--- a/src/DeskBox/Controls/DesktopOrganizationTaskView.Actions.cs
+++ b/src/DeskBox/Controls/DesktopOrganizationTaskView.Actions.cs
@@ -16,6 +16,11 @@ private async void ExecuteButton_Click(object sender, RoutedEventArgs e)
return;
}
+ if (await TryRunMappedOrganizeAsync(previewPlan))
+ {
+ return;
+ }
+
DesktopOrganizationPlan plan;
try
{
diff --git a/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs b/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs
new file mode 100644
index 000000000..384cfcc1f
--- /dev/null
+++ b/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs
@@ -0,0 +1,116 @@
+using DeskBox.Models;
+using DeskBox.Services;
+using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Controls;
+
+namespace DeskBox.Controls;
+
+///
+/// Fork feature 「映射整理」: the preview's 「只映射,不移动文件」 option. When
+/// checked, confirming the preview creates mapped-organize widgets that only
+/// record membership; no file leaves the Desktop folders.
+///
+public sealed partial class DesktopOrganizationTaskView
+{
+ private bool _mapOnlyInitialized;
+
+ private void MapOnlyCheckBox_Loaded(object sender, RoutedEventArgs e)
+ {
+ if (_mapOnlyInitialized)
+ {
+ return;
+ }
+
+ _mapOnlyInitialized = true;
+ MapOnlyCheckBox.Content = T("MappedOrganize.Preview.MapOnly");
+ ToolTipService.SetToolTip(MapOnlyCheckBox, T("MappedOrganize.Preview.MapOnlyDescription"));
+ OrganizationCompleted += (_, _) => MapOnlyCheckBox.Visibility = Visibility.Collapsed;
+ }
+
+ /// Returns true when the mapped path handled the confirm click.
+ private async Task TryRunMappedOrganizeAsync(DesktopOrganizationPlan previewPlan)
+ {
+ if (MapOnlyCheckBox.IsChecked != true)
+ {
+ return false;
+ }
+
+ if (MappedOrganizeService.Current is not { } service)
+ {
+ ResultInfo.Severity = InfoBarSeverity.Error;
+ ResultInfo.Title = T("DesktopOrganization.Result.FailedTitle");
+ ResultInfo.Message = T("DesktopOrganization.Result.FailedBody");
+ ResultInfo.IsOpen = true;
+ return true;
+ }
+
+ List groups = previewPlan.Targets
+ .Where(target => !_targetSelections.TryGetValue(target.SourceBucketId, out DesktopOrganizationTargetSelection? selection) ||
+ selection.IsSelected)
+ .GroupBy(target => target.CategoryId, StringComparer.Ordinal)
+ .Select(group => new MappedOrganizeGroup(
+ group.Key,
+ ResolveMappedCategoryName(group.Key),
+ group.First().PlannedBounds,
+ group.SelectMany(target => target.Items)
+ .Where(item => !_excludedSourcePaths.Contains(item.SourcePath))
+ .Select(item => item.SourcePath)
+ .ToList()))
+ .Where(group => group.Paths.Count > 0)
+ .ToList();
+ if (groups.Count == 0)
+ {
+ ResultInfo.Severity = InfoBarSeverity.Warning;
+ ResultInfo.Title = T("DesktopOrganization.Preview.NothingSelectedTitle");
+ ResultInfo.Message = T("DesktopOrganization.Preview.NothingSelectedBody");
+ ResultInfo.IsOpen = true;
+ return true;
+ }
+
+ _isExecuting = true;
+ ExecuteButton.IsEnabled = false;
+ CancelButton.IsEnabled = false;
+ MapOnlyCheckBox.IsEnabled = false;
+ try
+ {
+ int count = await service.ApplyGroupsAsync(groups);
+ _hasCompletedExecution = true;
+ ResultInfo.Severity = InfoBarSeverity.Success;
+ ResultInfo.Title = T("DesktopOrganization.Result.SuccessTitle");
+ ResultInfo.Message = Format("MappedOrganize.Result.Success", count, groups.Count);
+ ResultInfo.IsOpen = true;
+ ExecuteButton.Visibility = Visibility.Collapsed;
+ CancelButton.Visibility = Visibility.Collapsed;
+ DoneButton.Visibility = Visibility.Visible;
+ DoneButton.Style = (Style)Application.Current.Resources["AccentButtonStyle"];
+ SourceSelectionHost.IsEnabled = false;
+ TargetSelectionHost.IsEnabled = false;
+ OrganizationCompleted?.Invoke(this, EventArgs.Empty);
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Mapped organize failed: {ex}");
+ ResultInfo.Severity = InfoBarSeverity.Error;
+ ResultInfo.Title = T("DesktopOrganization.Result.FailedTitle");
+ ResultInfo.Message = T("DesktopOrganization.Result.FailedBody");
+ ResultInfo.IsOpen = true;
+ ExecuteButton.IsEnabled = true;
+ }
+ finally
+ {
+ _isExecuting = false;
+ CancelButton.IsEnabled = true;
+ MapOnlyCheckBox.IsEnabled = true;
+ DoneButton.IsEnabled = true;
+ }
+
+ return true;
+ }
+
+ private static string ResolveMappedCategoryName(string categoryId)
+ {
+ string key = $"DesktopOrganization.Category.{categoryId}";
+ string localized = T(key);
+ return string.Equals(localized, key, StringComparison.Ordinal) ? categoryId : localized;
+ }
+}
diff --git a/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml b/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml
index 2c5890ddd..8a5ecd449 100644
--- a/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml
+++ b/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml
@@ -228,6 +228,8 @@
+
diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs
new file mode 100644
index 000000000..54a738630
--- /dev/null
+++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs
@@ -0,0 +1,42 @@
+using DeskBox.Services;
+using Microsoft.UI.Xaml.Controls;
+
+namespace DeskBox.Controls.WidgetContents;
+
+/// Fork feature 「映射整理」: blank-area menu entries of a mapped-organize widget.
+public sealed partial class FileSurfaceContent
+{
+ private void AddMappedOrganizeMenuItems(MenuFlyout flyout)
+ {
+ if (!ViewModel.IsMappedOrganizeWidget || MappedOrganizeService.Current is not { } service)
+ {
+ return;
+ }
+
+ flyout.Items.Add(new MenuFlyoutSeparator());
+
+ MenuFlyoutItem organizeNow = CreateMenuItem("MappedOrganize.Menu.OrganizeNow", "\uE8CB");
+ organizeNow.Click += async (_, _) =>
+ {
+ flyout.Hide();
+ await RunAsync(() => service.OrganizeNowAsync());
+ };
+ flyout.Items.Add(organizeNow);
+
+ var autoAssign = new ToggleMenuFlyoutItem
+ {
+ Text = T("MappedOrganize.Menu.AutoAssign"),
+ IsChecked = service.AutoAssignNewItems
+ };
+ autoAssign.Click += (_, _) => service.SetAutoAssignNewItems(autoAssign.IsChecked);
+ flyout.Items.Add(autoAssign);
+
+ MenuFlyoutItem dissolveAll = CreateMenuItem("MappedOrganize.Menu.DissolveAll", "\uE7A7");
+ dissolveAll.Click += async (_, _) =>
+ {
+ flyout.Hide();
+ await RunAsync(service.DissolveAllAsync);
+ };
+ flyout.Items.Add(dissolveAll);
+ }
+}
diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.SelectionAndMenus.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.SelectionAndMenus.cs
index 9d47311dc..1c7103b03 100644
--- a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.SelectionAndMenus.cs
+++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.SelectionAndMenus.cs
@@ -1311,6 +1311,7 @@ private MenuFlyout CreateContentAreaFlyout()
}
};
flyout.Items.Add(openFolder);
+ AddMappedOrganizeMenuItems(flyout);
if (hostItems.CloseWidgetItem is not null)
{
diff --git a/src/DeskBox/Models/MappedOrganizeModels.cs b/src/DeskBox/Models/MappedOrganizeModels.cs
new file mode 100644
index 000000000..3dfc30078
--- /dev/null
+++ b/src/DeskBox/Models/MappedOrganizeModels.cs
@@ -0,0 +1,59 @@
+namespace DeskBox.Models;
+
+///
+/// Fork feature 「映射整理」 (virtual desktop organize). A mapped-organize widget
+/// is an ordinary File widget whose
+/// is the user Desktop (the existing desktop branch of the folder loader
+/// already merges the Public Desktop) and that only shows the desktop entries
+/// recorded as its members. Files never leave the Desktop folders; only
+/// membership is stored, inside so it is
+/// persisted, backed up and removed together with the widget without any new
+/// serializer surface. See docs/architecture/mapped-organize.md.
+///
+public static class MappedOrganizeWidgetMetadata
+{
+ /// Metadata flag marking a File widget as a mapped-organize widget.
+ public const string FlagKey = "DeskBox.MappedOrganize";
+
+ /// Metadata value carrying the classifier category the widget collects.
+ public const string CategoryKey = "DeskBox.MappedOrganize.Category";
+
+ /// Newline-separated absolute member paths (a path can never contain a newline).
+ public const string MembersKey = "DeskBox.MappedOrganize.Members";
+
+ public const string FlagValue = "1";
+
+ public static bool IsMappedOrganize(WidgetConfig? widget) =>
+ widget is not null &&
+ widget.WidgetKind == WidgetKind.File &&
+ widget.Metadata is not null &&
+ widget.Metadata.TryGetValue(FlagKey, out string? value) &&
+ string.Equals(value, FlagValue, StringComparison.Ordinal);
+
+ public static string GetCategory(WidgetConfig widget) =>
+ widget.Metadata is not null &&
+ widget.Metadata.TryGetValue(CategoryKey, out string? value) &&
+ !string.IsNullOrWhiteSpace(value)
+ ? value
+ : DesktopOrganizationCategoryIds.Other;
+
+ public static void Mark(WidgetConfig widget, string categoryId)
+ {
+ widget.Metadata ??= [];
+ widget.Metadata[FlagKey] = FlagValue;
+ widget.Metadata[CategoryKey] = string.IsNullOrWhiteSpace(categoryId)
+ ? DesktopOrganizationCategoryIds.Other
+ : categoryId;
+ if (!widget.Metadata.ContainsKey(MembersKey))
+ {
+ widget.Metadata[MembersKey] = string.Empty;
+ }
+ }
+}
+
+/// One group of the mapped-organize preview: a category and the desktop paths it collects.
+public sealed record MappedOrganizeGroup(
+ string CategoryId,
+ string DisplayName,
+ DesktopOrganizationRect? PlannedBounds,
+ IReadOnlyList Paths);
diff --git a/src/DeskBox/Services/DesktopIconVisibilityService.cs b/src/DeskBox/Services/DesktopIconVisibilityService.cs
new file mode 100644
index 000000000..2a50884bf
--- /dev/null
+++ b/src/DeskBox/Services/DesktopIconVisibilityService.cs
@@ -0,0 +1,66 @@
+using DeskBox.Platform;
+
+namespace DeskBox.Services;
+
+///
+/// Hides / shows Explorer's native desktop icons for 「映射整理」.
+///
+/// Approach (see docs/architecture/mapped-organize.md): the desktop icon
+/// list view (SysListView32 under the desktop SHELLDLL_DefView) is hidden with
+/// ShowWindow(SW_HIDE). Unlike flipping Explorer's persisted "Show desktop
+/// icons" setting (HideIcons + WM_COMMAND 0x7402 toggle), this state is NOT
+/// persisted by Explorer: an Explorer restart, a DeskBox crash followed by a
+/// sign-out, or any failure mode always ends with the icons visible again, so
+/// DeskBox can never strand a user without desktop icons. The price is that
+/// DeskBox must re-apply the hide after Explorer recreates the window, which
+/// does with a cheap periodic check.
+///
+internal static class DesktopIconVisibilityService
+{
+ private const int SwShow = 5;
+
+ public static IntPtr FindDesktopIconListView()
+ {
+ IntPtr found = IntPtr.Zero;
+ Win32Helper.EnumWindows((hWnd, _) =>
+ {
+ IntPtr defView = Win32Helper.FindWindowEx(hWnd, IntPtr.Zero, "SHELLDLL_DefView", null);
+ if (defView == IntPtr.Zero)
+ {
+ return true;
+ }
+
+ IntPtr listView = Win32Helper.FindWindowEx(defView, IntPtr.Zero, "SysListView32", null);
+ if (listView != IntPtr.Zero && DesktopBlankHitTest.IsShellDesktopListView(listView))
+ {
+ found = listView;
+ return false;
+ }
+
+ return true;
+ }, IntPtr.Zero);
+ return found;
+ }
+
+ /// Returns true when the icons are (now) in the requested state.
+ public static bool Apply(bool hidden)
+ {
+ IntPtr listView = FindDesktopIconListView();
+ if (listView == IntPtr.Zero)
+ {
+ // Explorer is restarting or not running; nothing to hide, and a
+ // freshly created list view is visible by default.
+ return !hidden;
+ }
+
+ bool visible = Win32Helper.IsWindowVisible(listView);
+ if (visible == !hidden)
+ {
+ return true;
+ }
+
+ Win32Helper.ShowWindow(listView, hidden ? Win32Helper.SW_HIDE : SwShow);
+ App.Log($"[MappedOrganize] Desktop icons {(hidden ? "hidden" : "shown")} hwnd=0x{listView.ToInt64():X}");
+ return true;
+ }
+}
diff --git a/src/DeskBox/Services/DesktopOrganizationCoordinator.cs b/src/DeskBox/Services/DesktopOrganizationCoordinator.cs
index ff6de252a..d0398f691 100644
--- a/src/DeskBox/Services/DesktopOrganizationCoordinator.cs
+++ b/src/DeskBox/Services/DesktopOrganizationCoordinator.cs
@@ -73,7 +73,8 @@ public DesktopOrganizationPlan CreateExecutionPlan(
.Where(widget =>
widget.WidgetKind == WidgetKind.File &&
!widget.IsDisabled &&
- !string.IsNullOrWhiteSpace(widget.MappedFolderPath))
+ !string.IsNullOrWhiteSpace(widget.MappedFolderPath) &&
+ !MappedOrganizeWidgetMetadata.IsMappedOrganize(widget))
.ToDictionary(widget => widget.Id, StringComparer.Ordinal);
var targetsByDestination = new Dictionary(StringComparer.Ordinal);
var retainedByChoice = new List();
@@ -200,7 +201,8 @@ public IReadOnlyList GetDestinationOptions
.Where(widget =>
widget.WidgetKind == WidgetKind.File &&
!widget.IsDisabled &&
- !string.IsNullOrWhiteSpace(widget.MappedFolderPath))
+ !string.IsNullOrWhiteSpace(widget.MappedFolderPath) &&
+ !MappedOrganizeWidgetMetadata.IsMappedOrganize(widget))
.OrderBy(widget => widget.Name, StringComparer.CurrentCultureIgnoreCase)
.Select(widget => new DesktopOrganizationDestinationOption(
widget.Id,
diff --git a/src/DeskBox/Services/DesktopOrganizationRuleResolver.cs b/src/DeskBox/Services/DesktopOrganizationRuleResolver.cs
index 8635e9c3a..7234a7c01 100644
--- a/src/DeskBox/Services/DesktopOrganizationRuleResolver.cs
+++ b/src/DeskBox/Services/DesktopOrganizationRuleResolver.cs
@@ -13,7 +13,8 @@ public sealed class DesktopOrganizationRuleResolver
.Where(widget =>
widget.WidgetKind == WidgetKind.File &&
!widget.IsDisabled &&
- !string.IsNullOrWhiteSpace(widget.MappedFolderPath))
+ !string.IsNullOrWhiteSpace(widget.MappedFolderPath) &&
+ !MappedOrganizeWidgetMetadata.IsMappedOrganize(widget))
.Select(widget => widget.Id)
.ToHashSet(StringComparer.Ordinal);
diff --git a/src/DeskBox/Services/MappedOrganizeMembership.cs b/src/DeskBox/Services/MappedOrganizeMembership.cs
new file mode 100644
index 000000000..113511e1e
--- /dev/null
+++ b/src/DeskBox/Services/MappedOrganizeMembership.cs
@@ -0,0 +1,259 @@
+using DeskBox.Models;
+
+namespace DeskBox.Services;
+
+///
+/// Pure membership logic of 「映射整理」. Every desktop entry belongs to at most
+/// one mapped-organize widget; membership lives in the widget's metadata.
+/// No I/O happens here except where a caller passes a probe delegate, so the
+/// rules are unit-testable (see MappedOrganizeMembershipTests).
+///
+public static class MappedOrganizeMembership
+{
+ private const char Separator = '\n';
+
+ public static string NormalizePath(string path) =>
+ Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
+
+ public static IEnumerable MappedWidgets(IEnumerable widgets) =>
+ widgets.Where(MappedOrganizeWidgetMetadata.IsMappedOrganize);
+
+ public static IReadOnlyList GetMembers(WidgetConfig widget)
+ {
+ if (widget.Metadata is null ||
+ !widget.Metadata.TryGetValue(MappedOrganizeWidgetMetadata.MembersKey, out string? raw) ||
+ string.IsNullOrEmpty(raw))
+ {
+ return [];
+ }
+
+ return raw.Split(Separator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ }
+
+ /// Stores the members (normalized, de-duplicated, order kept). Returns true when the stored value changed.
+ public static bool SetMembers(WidgetConfig widget, IEnumerable paths)
+ {
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var ordered = new List();
+ foreach (string path in paths)
+ {
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ continue;
+ }
+
+ string normalized = NormalizePath(path);
+ if (seen.Add(normalized))
+ {
+ ordered.Add(normalized);
+ }
+ }
+
+ string value = string.Join(Separator, ordered);
+ widget.Metadata ??= [];
+ if (widget.Metadata.TryGetValue(MappedOrganizeWidgetMetadata.MembersKey, out string? previous) &&
+ string.Equals(previous, value, StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ widget.Metadata[MappedOrganizeWidgetMetadata.MembersKey] = value;
+ return true;
+ }
+
+ public static bool IsMember(WidgetConfig widget, string path)
+ {
+ string normalized = NormalizePath(path);
+ return GetMembers(widget).Any(member => string.Equals(member, normalized, StringComparison.OrdinalIgnoreCase));
+ }
+
+ public static WidgetConfig? FindOwner(IEnumerable widgets, string path)
+ {
+ string normalized = NormalizePath(path);
+ return MappedWidgets(widgets).FirstOrDefault(widget =>
+ GetMembers(widget).Any(member => string.Equals(member, normalized, StringComparison.OrdinalIgnoreCase)));
+ }
+
+ ///
+ /// Moves the given paths into the target widget's membership; membership is
+ /// exclusive, so the paths leave every other mapped widget. Never touches
+ /// the files. Returns the ids of every widget whose membership changed.
+ ///
+ public static IReadOnlyList Assign(
+ IEnumerable widgets,
+ string targetWidgetId,
+ IEnumerable paths)
+ {
+ List mapped = MappedWidgets(widgets).ToList();
+ WidgetConfig? target = mapped.FirstOrDefault(widget =>
+ string.Equals(widget.Id, targetWidgetId, StringComparison.Ordinal));
+ if (target is null)
+ {
+ return [];
+ }
+
+ var incoming = paths
+ .Where(path => !string.IsNullOrWhiteSpace(path))
+ .Select(NormalizePath)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList();
+ if (incoming.Count == 0)
+ {
+ return [];
+ }
+
+ var incomingSet = incoming.ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var changed = new List();
+ foreach (WidgetConfig widget in mapped)
+ {
+ if (ReferenceEquals(widget, target))
+ {
+ continue;
+ }
+
+ IReadOnlyList members = GetMembers(widget);
+ if (members.Any(incomingSet.Contains) &&
+ SetMembers(widget, members.Where(member => !incomingSet.Contains(member))))
+ {
+ changed.Add(widget.Id);
+ }
+ }
+
+ if (SetMembers(target, GetMembers(target).Concat(incoming)))
+ {
+ changed.Add(target.Id);
+ }
+
+ return changed;
+ }
+
+ /// Removes a path (and, for a deleted folder, nothing below it is tracked) from every widget.
+ public static IReadOnlyList RemovePath(IEnumerable widgets, string path)
+ {
+ string normalized = NormalizePath(path);
+ var changed = new List();
+ foreach (WidgetConfig widget in MappedWidgets(widgets))
+ {
+ IReadOnlyList members = GetMembers(widget);
+ if (members.Any(member => string.Equals(member, normalized, StringComparison.OrdinalIgnoreCase)) &&
+ SetMembers(widget, members.Where(member => !string.Equals(member, normalized, StringComparison.OrdinalIgnoreCase))))
+ {
+ changed.Add(widget.Id);
+ }
+ }
+
+ return changed;
+ }
+
+ /// A rename outside or inside DeskBox keeps the entry in the same widget, at the same position.
+ public static IReadOnlyList RenamePath(IEnumerable widgets, string oldPath, string newPath)
+ {
+ string oldNormalized = NormalizePath(oldPath);
+ string newNormalized = NormalizePath(newPath);
+ var changed = new List();
+ foreach (WidgetConfig widget in MappedWidgets(widgets))
+ {
+ IReadOnlyList members = GetMembers(widget);
+ if (!members.Any(member => string.Equals(member, oldNormalized, StringComparison.OrdinalIgnoreCase)))
+ {
+ continue;
+ }
+
+ if (SetMembers(widget, members.Select(member =>
+ string.Equals(member, oldNormalized, StringComparison.OrdinalIgnoreCase) ? newNormalized : member)))
+ {
+ changed.Add(widget.Id);
+ }
+ }
+
+ return changed;
+ }
+
+ /// Drops members whose entry no longer exists (offline deletes, crash, Explorer-side moves).
+ public static IReadOnlyList Prune(IEnumerable widgets, Func exists)
+ {
+ var changed = new List();
+ foreach (WidgetConfig widget in MappedWidgets(widgets))
+ {
+ IReadOnlyList members = GetMembers(widget);
+ var kept = members.Where(exists).ToList();
+ if (kept.Count != members.Count && SetMembers(widget, kept))
+ {
+ changed.Add(widget.Id);
+ }
+ }
+
+ return changed;
+ }
+
+ public static IReadOnlyList FindUnassigned(
+ IEnumerable widgets,
+ IEnumerable desktopEntries)
+ {
+ var assigned = MappedWidgets(widgets)
+ .SelectMany(GetMembers)
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+ return desktopEntries
+ .Where(path => !string.IsNullOrWhiteSpace(path))
+ .Select(NormalizePath)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Where(path => !assigned.Contains(path))
+ .ToList();
+ }
+
+ ///
+ /// The mapped widget a classified entry routes to: the first widget
+ /// collecting the same category, otherwise the 「其他」 widget. Null means
+ /// the caller has to create an 「其他」 widget first.
+ ///
+ public static WidgetConfig? ResolveTarget(IEnumerable widgets, string categoryId)
+ {
+ List mapped = MappedWidgets(widgets).Where(widget => !widget.IsDisabled).ToList();
+ return mapped.FirstOrDefault(widget => string.Equals(
+ MappedOrganizeWidgetMetadata.GetCategory(widget), categoryId, StringComparison.Ordinal)) ??
+ mapped.FirstOrDefault(widget => string.Equals(
+ MappedOrganizeWidgetMetadata.GetCategory(widget),
+ DesktopOrganizationCategoryIds.Other,
+ StringComparison.Ordinal));
+ }
+
+ ///
+ /// Category of a desktop entry for mapped routing. Folders have no
+ /// extension-based category and land in 「其他」.
+ ///
+ public static string Classify(DesktopOrganizationClassifier classifier, string path, bool isDirectory) =>
+ isDirectory ? DesktopOrganizationCategoryIds.Other : classifier.Classify(path).CategoryId;
+
+ ///
+ /// Groups unassigned entries by their routed widget. Entries whose route
+ /// needs a missing 「其他」 widget are returned under null.
+ ///
+ public static IReadOnlyDictionary> PlanAssignments(
+ IEnumerable widgets,
+ IEnumerable<(string Path, string CategoryId)> entries,
+ out List needsOtherWidget)
+ {
+ List snapshot = widgets.ToList();
+ var result = new Dictionary>(StringComparer.Ordinal);
+ needsOtherWidget = [];
+ foreach ((string path, string categoryId) in entries)
+ {
+ WidgetConfig? target = ResolveTarget(snapshot, categoryId);
+ if (target is null)
+ {
+ needsOtherWidget.Add(path);
+ continue;
+ }
+
+ if (!result.TryGetValue(target.Id, out List? list))
+ {
+ list = [];
+ result.Add(target.Id, list);
+ }
+
+ list.Add(path);
+ }
+
+ return result;
+ }
+}
diff --git a/src/DeskBox/Services/MappedOrganizeService.cs b/src/DeskBox/Services/MappedOrganizeService.cs
new file mode 100644
index 000000000..6e1a87dce
--- /dev/null
+++ b/src/DeskBox/Services/MappedOrganizeService.cs
@@ -0,0 +1,804 @@
+using DeskBox.Models;
+using Microsoft.UI.Dispatching;
+
+namespace DeskBox.Services;
+
+///
+/// Runtime owner of 「映射整理」 (virtual desktop organize): creates the
+/// mapped widgets, keeps membership in sync with the Desktop folders, routes
+/// new desktop entries, and hides the native desktop icons while at least one
+/// mapped widget exists. Files are never moved, renamed or deleted here.
+///
+/// Threading: every membership mutation runs on the UI dispatcher (the same
+/// thread that owns ); file-system
+/// watcher callbacks only marshal paths onto it.
+///
+public sealed class MappedOrganizeService : IDisposable
+{
+ private const string StateFileName = "mapped-organize.state";
+ private const string AutoAssignKey = "autoAssignNewItems";
+ private const string IconsHiddenKey = "desktopIconsHiddenByDeskBox";
+ private static readonly TimeSpan IconWatchdogInterval = TimeSpan.FromSeconds(4);
+ private static readonly TimeSpan ExpectedIncomingLifetime = TimeSpan.FromMinutes(2);
+
+ private static readonly HashSet TransientExtensions = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ".crdownload", ".part", ".partial", ".download", ".tmp", ".opdownload"
+ };
+
+ private readonly SettingsService _settingsService;
+ private readonly WidgetManager _widgetManager;
+ private readonly LocalizationService _localizationService;
+ private readonly DispatcherQueue _dispatcherQueue;
+ private readonly DesktopOrganizationClassifier _classifier = new();
+ private readonly string _statePath;
+ private readonly List _watchers = [];
+ private readonly Dictionary _expectedIncoming =
+ new(StringComparer.OrdinalIgnoreCase);
+ private readonly HashSet _pendingNewEntries = new(StringComparer.OrdinalIgnoreCase);
+ private DispatcherQueueTimer? _iconWatchdog;
+ private bool _autoAssignNewItems = true;
+ private bool _iconsHiddenByDeskBox;
+ private bool _pendingFlushScheduled;
+ private bool _isDisposed;
+
+ public MappedOrganizeService(
+ SettingsService settingsService,
+ WidgetManager widgetManager,
+ LocalizationService localizationService,
+ DispatcherQueue dispatcherQueue,
+ string? stateDirectory = null)
+ {
+ _settingsService = settingsService;
+ _widgetManager = widgetManager;
+ _localizationService = localizationService;
+ _dispatcherQueue = dispatcherQueue;
+ _statePath = Path.Combine(
+ stateDirectory ?? DeskBoxDataPathService.Current.DataDirectory,
+ StateFileName);
+ }
+
+ /// Process-wide instance set by the App host once widgets are restored.
+ public static MappedOrganizeService? Current { get; internal set; }
+
+ ///
+ /// Raised on the UI thread with the ids of the mapped widgets whose
+ /// membership changed. Static so widget view-models restored before the
+ /// service exists can subscribe at construction.
+ ///
+ public static event Action>? MembershipChanged;
+
+ public bool AutoAssignNewItems => _autoAssignNewItems;
+
+ public bool HasMappedWidgets => LiveMappedWidgets().Any();
+
+ public bool IsMappedWidget(string widgetId) =>
+ LiveMappedWidgets().Any(widget => string.Equals(widget.Id, widgetId, StringComparison.Ordinal));
+
+ /// Whether is a member of the widget (used by the widget's folder loader).
+ public bool IsMember(string widgetId, string path)
+ {
+ WidgetConfig? widget = FindMappedWidget(widgetId);
+ return widget is not null && MappedOrganizeMembership.IsMember(widget, path);
+ }
+
+ public IReadOnlySet GetMemberSet(string widgetId)
+ {
+ WidgetConfig? widget = FindMappedWidget(widgetId);
+ return widget is null
+ ? new HashSet(StringComparer.OrdinalIgnoreCase)
+ : MappedOrganizeMembership.GetMembers(widget).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Startup: load the durable flags, repair state after a crash, start the
+ /// watchers and apply the icon state. Safe to call once.
+ ///
+ public void Initialize()
+ {
+ LoadState();
+ bool hadMappedWidgets = HasMappedWidgets;
+ if (_iconsHiddenByDeskBox && !hadMappedWidgets)
+ {
+ App.Log("[MappedOrganize] Startup found a stale hidden-icons marker without mapped widgets; restoring icons.");
+ }
+
+ if (hadMappedWidgets)
+ {
+ IReadOnlyList pruned = MappedOrganizeMembership.Prune(
+ _settingsService.Settings.WidgetLayout.Widgets,
+ path => File.Exists(path) || Directory.Exists(path));
+ if (pruned.Count > 0)
+ {
+ _settingsService.SaveDebounced();
+ }
+
+ StartWatchers();
+ }
+
+ _widgetManager.WidgetRemoved += OnWidgetRemoved;
+ ApplyIconState();
+ if (hadMappedWidgets && _autoAssignNewItems)
+ {
+ _ = AssignUnassignedAsync(createOtherWidget: true);
+ }
+ }
+
+ /// Shutdown: always give the native icons back. Membership stays for the next start.
+ public void Shutdown()
+ {
+ if (_isDisposed)
+ {
+ return;
+ }
+
+ StopWatchers();
+ _iconWatchdog?.Stop();
+ _iconWatchdog = null;
+ RestoreIconsForExit();
+ }
+
+ /// Best-effort restore usable from ProcessExit / fatal paths.
+ public void RestoreIconsForExit()
+ {
+ try
+ {
+ DesktopIconVisibilityService.Apply(hidden: false);
+ _iconsHiddenByDeskBox = false;
+ SaveState();
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Restoring desktop icons on exit failed: {ex.Message}");
+ }
+ }
+
+ public void SetAutoAssignNewItems(bool enabled)
+ {
+ if (_autoAssignNewItems == enabled)
+ {
+ return;
+ }
+
+ _autoAssignNewItems = enabled;
+ SaveState();
+ if (enabled && HasMappedWidgets)
+ {
+ _ = AssignUnassignedAsync(createOtherWidget: true);
+ }
+ }
+
+ ///
+ /// Executes the preview in mapped mode: one mapped widget per category
+ /// group (re-using an existing mapped widget of that category), membership
+ /// written, files untouched.
+ ///
+ public async Task ApplyGroupsAsync(IReadOnlyList groups)
+ {
+ var created = new List<(WidgetConfig Config, DesktopOrganizationRect? Bounds)>();
+ var touched = new HashSet(StringComparer.Ordinal);
+ int assignedCount = 0;
+ foreach (MappedOrganizeGroup group in groups.Where(group => group.Paths.Count > 0))
+ {
+ WidgetConfig? target = LiveMappedWidgets().FirstOrDefault(widget => string.Equals(
+ MappedOrganizeWidgetMetadata.GetCategory(widget), group.CategoryId, StringComparison.Ordinal));
+ if (target is null)
+ {
+ target = CreateMappedConfig(group.CategoryId, group.DisplayName);
+ created.Add((target, group.PlannedBounds));
+ _widgetManager.AddMappedOrganizeConfig(target, group.PlannedBounds);
+ }
+
+ foreach (string id in MappedOrganizeMembership.Assign(_settingsService.Settings.WidgetLayout.Widgets, target.Id, group.Paths))
+ {
+ touched.Add(id);
+ }
+
+ assignedCount += group.Paths.Count;
+ }
+
+ await _settingsService.SaveAsync();
+ foreach ((WidgetConfig config, _) in created)
+ {
+ await _widgetManager.ShowMappedOrganizeWidgetAsync(config);
+ touched.Remove(config.Id);
+ }
+
+ StartWatchers();
+ ApplyIconState();
+ RaiseMembershipChanged(touched);
+ if (_autoAssignNewItems)
+ {
+ // Everything the preview left out (folders, retained buckets,
+ // hidden-by-choice) would be invisible once the native icons are
+ // hidden, so it is routed by the same rules right away.
+ await AssignUnassignedAsync(createOtherWidget: true);
+ }
+
+ return assignedCount;
+ }
+
+ /// 「一键整理」: routes every unassigned desktop entry.
+ public Task OrganizeNowAsync() => AssignUnassignedAsync(createOtherWidget: true);
+
+ ///
+ /// Drag between mapped widgets or a drop of desktop entries onto a mapped
+ /// widget: only membership changes. Returns the paths that were desktop
+ /// entries (and therefore handled); other paths are left to the caller.
+ ///
+ public IReadOnlyList AssignDesktopPaths(string widgetId, IEnumerable paths)
+ {
+ var desktopPaths = paths.Where(IsDesktopEntryPath).ToList();
+ if (desktopPaths.Count == 0)
+ {
+ return [];
+ }
+
+ IReadOnlyList changed = MappedOrganizeMembership.Assign(
+ _settingsService.Settings.WidgetLayout.Widgets, widgetId, desktopPaths);
+ if (changed.Count > 0)
+ {
+ _settingsService.SaveDebounced();
+ RaiseMembershipChanged(changed);
+ }
+
+ return desktopPaths;
+ }
+
+ ///
+ /// Entries the drop moves INTO the Desktop folder for a mapped widget land
+ /// in that widget instead of following the routing rules.
+ ///
+ public void ExpectIncoming(string widgetId, IEnumerable sourcePaths)
+ {
+ DateTimeOffset expires = DateTimeOffset.UtcNow + ExpectedIncomingLifetime;
+ foreach (string source in sourcePaths)
+ {
+ string name = Path.GetFileName(Path.TrimEndingDirectorySeparator(source));
+ if (!string.IsNullOrWhiteSpace(name))
+ {
+ _expectedIncoming[name] = (widgetId, expires);
+ }
+ }
+ }
+
+ /// Turns the mode off: dissolves every mapped widget (membership only) and restores the icons.
+ public async Task DissolveAllAsync()
+ {
+ foreach (WidgetConfig widget in LiveMappedWidgets().ToList())
+ {
+ await _widgetManager.RemoveWidgetAsync(widget.Id);
+ }
+
+ ApplyIconState();
+ }
+
+ public static bool IsDesktopEntryPath(string path)
+ {
+ if (string.IsNullOrWhiteSpace(path))
+ {
+ return false;
+ }
+
+ try
+ {
+ string parent = Path.GetDirectoryName(MappedOrganizeMembership.NormalizePath(path)) ?? string.Empty;
+ var (userDesktop, publicDesktop) = FileService.GetDesktopPaths();
+ return PathEquals(parent, userDesktop) || PathEquals(parent, publicDesktop);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_isDisposed)
+ {
+ return;
+ }
+
+ Shutdown();
+ _widgetManager.WidgetRemoved -= OnWidgetRemoved;
+ _isDisposed = true;
+ }
+
+ private async Task AssignUnassignedAsync(bool createOtherWidget, IReadOnlyCollection? onlyPaths = null)
+ {
+ if (_isDisposed || !HasMappedWidgets)
+ {
+ return 0;
+ }
+
+ List<(string Path, bool IsDirectory)> entries = await Task.Run(() => EnumerateDesktopEntries(onlyPaths));
+ IReadOnlyList unassigned = MappedOrganizeMembership.FindUnassigned(
+ _settingsService.Settings.WidgetLayout.Widgets,
+ entries.Select(entry => entry.Path));
+ if (unassigned.Count == 0)
+ {
+ return 0;
+ }
+
+ var isDirectory = entries.ToDictionary(entry => MappedOrganizeMembership.NormalizePath(entry.Path), entry => entry.IsDirectory, StringComparer.OrdinalIgnoreCase);
+ var touched = new HashSet(StringComparer.Ordinal);
+ var routed = new List<(string Path, string CategoryId)>();
+ foreach (string path in unassigned)
+ {
+ if (TryTakeExpectedIncoming(path, out string widgetId) && IsMappedWidget(widgetId))
+ {
+ touched.UnionWith(MappedOrganizeMembership.Assign(_settingsService.Settings.WidgetLayout.Widgets, widgetId, [path]));
+ continue;
+ }
+
+ routed.Add((path, MappedOrganizeMembership.Classify(
+ _classifier, path, isDirectory.TryGetValue(path, out bool directory) && directory)));
+ }
+
+ var plan = MappedOrganizeMembership.PlanAssignments(_settingsService.Settings.WidgetLayout.Widgets, routed, out List needsOther);
+ foreach ((string widgetId, List paths) in plan)
+ {
+ touched.UnionWith(MappedOrganizeMembership.Assign(_settingsService.Settings.WidgetLayout.Widgets, widgetId, paths));
+ }
+
+ WidgetConfig? createdOther = null;
+ if (needsOther.Count > 0 && createOtherWidget)
+ {
+ createdOther = CreateMappedConfig(
+ DesktopOrganizationCategoryIds.Other,
+ _localizationService.T("DesktopOrganization.Category.Other"));
+ _widgetManager.AddMappedOrganizeConfig(createdOther, null);
+ MappedOrganizeMembership.Assign(_settingsService.Settings.WidgetLayout.Widgets, createdOther.Id, needsOther);
+ }
+
+ if (touched.Count == 0 && createdOther is null)
+ {
+ return 0;
+ }
+
+ await _settingsService.SaveAsync();
+ if (createdOther is not null)
+ {
+ await _widgetManager.ShowMappedOrganizeWidgetAsync(createdOther);
+ }
+
+ RaiseMembershipChanged(touched);
+ return unassigned.Count - (createOtherWidget ? 0 : needsOther.Count);
+ }
+
+ private static List<(string Path, bool IsDirectory)> EnumerateDesktopEntries(IReadOnlyCollection? onlyPaths)
+ {
+ var result = new List<(string, bool)>();
+ IEnumerable candidates;
+ if (onlyPaths is not null)
+ {
+ candidates = onlyPaths;
+ }
+ else
+ {
+ var (userDesktop, publicDesktop) = FileService.GetDesktopPaths();
+ candidates = SafeEnumerate(userDesktop).Concat(SafeEnumerate(publicDesktop));
+ }
+
+ foreach (string path in candidates)
+ {
+ try
+ {
+ var info = new FileInfo(path);
+ FileAttributes attributes = File.GetAttributes(path);
+ if ((attributes & (FileAttributes.Hidden | FileAttributes.System)) != 0 ||
+ TransientExtensions.Contains(info.Extension) ||
+ string.Equals(info.Name, "desktop.ini", StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ result.Add((path, (attributes & FileAttributes.Directory) != 0));
+ }
+ catch (Exception)
+ {
+ // Vanished or inaccessible: the watcher reports the outcome.
+ }
+ }
+
+ return result;
+ }
+
+ private static IEnumerable SafeEnumerate(string directory)
+ {
+ if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory))
+ {
+ return [];
+ }
+
+ try
+ {
+ return Directory.EnumerateFileSystemEntries(directory).ToList();
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Enumerating '{directory}' failed: {ex.Message}");
+ return [];
+ }
+ }
+
+ private WidgetConfig CreateMappedConfig(string categoryId, string displayName)
+ {
+ var (userDesktop, _) = FileService.GetDesktopPaths();
+ var config = new WidgetConfig
+ {
+ Name = string.IsNullOrWhiteSpace(displayName) ? categoryId : displayName,
+ IsDefaultTitle = false,
+ WidgetKind = WidgetKind.File,
+ MappedFolderPath = Path.TrimEndingDirectorySeparator(Path.GetFullPath(userDesktop)),
+ FollowsDefaultStoragePath = false,
+ BoundsCoordinateVersion = WidgetConfig.CurrentBoundsCoordinateVersion,
+ Width = _settingsService.Settings.WidgetShell.DefaultWidgetWidth,
+ Height = _settingsService.Settings.WidgetShell.DefaultWidgetHeight,
+ IsVisible = true
+ };
+ MappedOrganizeWidgetMetadata.Mark(config, categoryId);
+ return config;
+ }
+
+ private IEnumerable LiveMappedWidgets() =>
+ MappedOrganizeMembership.MappedWidgets(_settingsService.Settings.WidgetLayout.Widgets)
+ .Where(widget => !_widgetManager.IsWidgetPendingDeletion(widget.Id));
+
+ private WidgetConfig? FindMappedWidget(string widgetId) =>
+ LiveMappedWidgets().FirstOrDefault(widget => string.Equals(widget.Id, widgetId, StringComparison.Ordinal));
+
+ private bool TryTakeExpectedIncoming(string path, out string widgetId)
+ {
+ widgetId = string.Empty;
+ string name = Path.GetFileName(path);
+ if (!_expectedIncoming.TryGetValue(name, out var expected))
+ {
+ return false;
+ }
+
+ _expectedIncoming.Remove(name);
+ if (expected.Expires < DateTimeOffset.UtcNow)
+ {
+ return false;
+ }
+
+ widgetId = expected.WidgetId;
+ return true;
+ }
+
+ private void OnWidgetRemoved(string widgetId)
+ {
+ // The removed widget's membership lived in its own config, which is
+ // already gone: dissolving never touches files. Remaining mapped
+ // widgets pick up the now-unassigned entries; with none left the
+ // native desktop icons come back.
+ Enqueue(async () =>
+ {
+ ApplyIconState();
+ if (HasMappedWidgets)
+ {
+ if (_autoAssignNewItems)
+ {
+ await AssignUnassignedAsync(createOtherWidget: true);
+ }
+ }
+ else
+ {
+ StopWatchers();
+ }
+ });
+ }
+
+ private void ApplyIconState()
+ {
+ bool shouldHide = HasMappedWidgets;
+ if (shouldHide && !_iconsHiddenByDeskBox)
+ {
+ // Durable marker first: a crash after hiding must be recoverable.
+ _iconsHiddenByDeskBox = true;
+ SaveState();
+ }
+
+ DesktopIconVisibilityService.Apply(shouldHide);
+ if (!shouldHide && _iconsHiddenByDeskBox)
+ {
+ _iconsHiddenByDeskBox = false;
+ SaveState();
+ }
+
+ if (shouldHide)
+ {
+ EnsureIconWatchdog();
+ }
+ else
+ {
+ _iconWatchdog?.Stop();
+ }
+ }
+
+ private void EnsureIconWatchdog()
+ {
+ if (_iconWatchdog is null)
+ {
+ _iconWatchdog = _dispatcherQueue.CreateTimer();
+ _iconWatchdog.Interval = IconWatchdogInterval;
+ _iconWatchdog.IsRepeating = true;
+ _iconWatchdog.Tick += (_, _) =>
+ {
+ // Explorer restarts recreate a visible list view.
+ if (!_isDisposed && HasMappedWidgets)
+ {
+ DesktopIconVisibilityService.Apply(hidden: true);
+ }
+ };
+ }
+
+ if (!_iconWatchdog.IsRunning)
+ {
+ _iconWatchdog.Start();
+ }
+ }
+
+ private void StartWatchers()
+ {
+ if (_watchers.Count > 0)
+ {
+ return;
+ }
+
+ var (userDesktop, publicDesktop) = FileService.GetDesktopPaths();
+ foreach (string directory in new[] { userDesktop, publicDesktop }
+ .Where(directory => !string.IsNullOrWhiteSpace(directory) && Directory.Exists(directory))
+ .Distinct(StringComparer.OrdinalIgnoreCase))
+ {
+ try
+ {
+ var watcher = new FileSystemWatcher(directory)
+ {
+ IncludeSubdirectories = false,
+ NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName,
+ InternalBufferSize = 64 * 1024
+ };
+ watcher.Created += (_, e) => Enqueue(() => OnEntryCreated(e.FullPath));
+ watcher.Deleted += (_, e) => Enqueue(() => OnEntryDeleted(e.FullPath));
+ watcher.Renamed += (_, e) => Enqueue(() => OnEntryRenamed(e.OldFullPath, e.FullPath));
+ watcher.Error += (_, e) =>
+ {
+ App.Log($"[MappedOrganize] Desktop watcher error: {e.GetException().Message}");
+ Enqueue(() =>
+ {
+ if (MappedOrganizeMembership.Prune(_settingsService.Settings.WidgetLayout.Widgets,
+ path => File.Exists(path) || Directory.Exists(path)) is { Count: > 0 } changed)
+ {
+ _settingsService.SaveDebounced();
+ RaiseMembershipChanged(changed);
+ }
+
+ return _autoAssignNewItems ? AssignUnassignedAsync(createOtherWidget: true) : Task.CompletedTask;
+ });
+ };
+ watcher.EnableRaisingEvents = true;
+ _watchers.Add(watcher);
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Could not watch '{directory}': {ex.Message}");
+ }
+ }
+ }
+
+ private void StopWatchers()
+ {
+ foreach (FileSystemWatcher watcher in _watchers)
+ {
+ try
+ {
+ watcher.EnableRaisingEvents = false;
+ watcher.Dispose();
+ }
+ catch (Exception)
+ {
+ // Disposal is best effort.
+ }
+ }
+
+ _watchers.Clear();
+ }
+
+ private Task OnEntryCreated(string path)
+ {
+ if (!_autoAssignNewItems || !HasMappedWidgets)
+ {
+ return Task.CompletedTask;
+ }
+
+ _pendingNewEntries.Add(path);
+ SchedulePendingFlush();
+ return Task.CompletedTask;
+ }
+
+ private Task OnEntryDeleted(string path)
+ {
+ _pendingNewEntries.Remove(path);
+ IReadOnlyList changed = MappedOrganizeMembership.RemovePath(_settingsService.Settings.WidgetLayout.Widgets, path);
+ if (changed.Count > 0)
+ {
+ _settingsService.SaveDebounced();
+ RaiseMembershipChanged(changed);
+ }
+
+ return Task.CompletedTask;
+ }
+
+ private Task OnEntryRenamed(string oldPath, string newPath)
+ {
+ _pendingNewEntries.Remove(oldPath);
+ IReadOnlyList changed = MappedOrganizeMembership.RenamePath(_settingsService.Settings.WidgetLayout.Widgets, oldPath, newPath);
+ if (changed.Count > 0)
+ {
+ _settingsService.SaveDebounced();
+ RaiseMembershipChanged(changed);
+ return Task.CompletedTask;
+ }
+
+ // A download finishing (x.crdownload -> x.zip) is a new visible entry.
+ return OnEntryCreated(newPath);
+ }
+
+ private void SchedulePendingFlush()
+ {
+ if (_pendingFlushScheduled)
+ {
+ return;
+ }
+
+ _pendingFlushScheduled = true;
+ int delaySeconds = Math.Clamp(_settingsService.Settings.DesktopOrganization.DesktopAutoOrganizationDelaySeconds, 2, 600);
+ _ = Task.Run(async () =>
+ {
+ // Same settle delay as automatic organization, then one more
+ // second to see that the size stopped changing.
+ await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
+ Enqueue(FlushPendingAsync);
+ });
+ }
+
+ private async Task FlushPendingAsync()
+ {
+ _pendingFlushScheduled = false;
+ if (_pendingNewEntries.Count == 0 || _isDisposed)
+ {
+ return;
+ }
+
+ string[] batch = _pendingNewEntries.ToArray();
+ _pendingNewEntries.Clear();
+ string[] stable = await Task.Run(async () =>
+ {
+ var sizes = batch.ToDictionary(path => path, TryGetLength, StringComparer.OrdinalIgnoreCase);
+ await Task.Delay(TimeSpan.FromSeconds(1));
+ return batch.Where(path => (File.Exists(path) || Directory.Exists(path)) && sizes[path] == TryGetLength(path)).ToArray();
+ });
+ foreach (string unstable in batch.Except(stable, StringComparer.OrdinalIgnoreCase)
+ .Where(path => File.Exists(path)))
+ {
+ _pendingNewEntries.Add(unstable);
+ }
+
+ if (_pendingNewEntries.Count > 0)
+ {
+ SchedulePendingFlush();
+ }
+
+ if (stable.Length > 0)
+ {
+ await AssignUnassignedAsync(createOtherWidget: true, stable);
+ }
+ }
+
+ private static long TryGetLength(string path)
+ {
+ try
+ {
+ return File.Exists(path) ? new FileInfo(path).Length : -1;
+ }
+ catch (Exception)
+ {
+ return -2;
+ }
+ }
+
+ private void RaiseMembershipChanged(IEnumerable widgetIds)
+ {
+ var ids = widgetIds.ToHashSet(StringComparer.Ordinal);
+ if (ids.Count == 0)
+ {
+ return;
+ }
+
+ MembershipChanged?.Invoke(ids);
+ }
+
+ private void Enqueue(Func work)
+ {
+ if (_isDisposed)
+ {
+ return;
+ }
+
+ _dispatcherQueue.TryEnqueue(async () =>
+ {
+ try
+ {
+ await work();
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Background step failed: {ex}");
+ }
+ });
+ }
+
+ private void LoadState()
+ {
+ try
+ {
+ if (!File.Exists(_statePath))
+ {
+ return;
+ }
+
+ foreach (string line in File.ReadAllLines(_statePath))
+ {
+ int separator = line.IndexOf('=');
+ if (separator <= 0)
+ {
+ continue;
+ }
+
+ string key = line[..separator].Trim();
+ bool value = string.Equals(line[(separator + 1)..].Trim(), "true", StringComparison.OrdinalIgnoreCase);
+ if (string.Equals(key, AutoAssignKey, StringComparison.Ordinal))
+ {
+ _autoAssignNewItems = value;
+ }
+ else if (string.Equals(key, IconsHiddenKey, StringComparison.Ordinal))
+ {
+ _iconsHiddenByDeskBox = value;
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Could not read state: {ex.Message}");
+ }
+ }
+
+ private void SaveState()
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(_statePath)!);
+ string temporary = _statePath + ".tmp";
+ File.WriteAllLines(temporary,
+ [
+ $"{AutoAssignKey}={(_autoAssignNewItems ? "true" : "false")}",
+ $"{IconsHiddenKey}={(_iconsHiddenByDeskBox ? "true" : "false")}"
+ ]);
+ File.Move(temporary, _statePath, overwrite: true);
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Could not write state: {ex.Message}");
+ }
+ }
+
+ private static bool PathEquals(string left, string right) =>
+ !string.IsNullOrWhiteSpace(left) &&
+ !string.IsNullOrWhiteSpace(right) &&
+ string.Equals(
+ Path.TrimEndingDirectorySeparator(Path.GetFullPath(left)),
+ Path.TrimEndingDirectorySeparator(Path.GetFullPath(right)),
+ StringComparison.OrdinalIgnoreCase);
+}
diff --git a/src/DeskBox/Services/WidgetManager.MappedOrganize.cs b/src/DeskBox/Services/WidgetManager.MappedOrganize.cs
new file mode 100644
index 000000000..d146d65f3
--- /dev/null
+++ b/src/DeskBox/Services/WidgetManager.MappedOrganize.cs
@@ -0,0 +1,31 @@
+using DeskBox.Models;
+using Windows.Graphics;
+
+namespace DeskBox.Services;
+
+///
+/// Fork feature 「映射整理」: widget-manager entry points used by
+/// . Mapped widgets intentionally share the
+/// Desktop as their folder, so they are added like organizer-created widgets
+/// (no folder-conflict check, no mapped-folder desktop shortcut).
+///
+public sealed partial class WidgetManager
+{
+ internal void AddMappedOrganizeConfig(WidgetConfig config, DesktopOrganizationRect? plannedBounds)
+ {
+ RectInt32? explicitBounds = plannedBounds is { } bounds
+ ? new RectInt32(
+ (int)Math.Round(bounds.X),
+ (int)Math.Round(bounds.Y),
+ Math.Max(1, (int)Math.Round(bounds.Width)),
+ Math.Max(1, (int)Math.Round(bounds.Height)))
+ : null;
+ ApplyNewWidgetPlacement(config, new NewWidgetPlacementContext(explicitBounds));
+ _settingsService.Settings.WidgetLayout.Widgets.Add(config);
+ }
+
+ internal Task ShowMappedOrganizeWidgetAsync(WidgetConfig config) =>
+ ShowWidgetAsync(config.Id, reveal: true, autoRestoreOnReveal: false);
+
+ internal bool IsWidgetPendingDeletion(string widgetId) => IsDeleted(widgetId);
+}
diff --git a/src/DeskBox/Services/WidgetManager.cs b/src/DeskBox/Services/WidgetManager.cs
index d77c5a0f8..4f3fb3498 100644
--- a/src/DeskBox/Services/WidgetManager.cs
+++ b/src/DeskBox/Services/WidgetManager.cs
@@ -2687,7 +2687,8 @@ window.CurrentContent is FileWidgetContentAdapter surface &&
private void SyncMappedWidgetShortcut(WidgetConfig config, string? displayNameOverride = null)
{
if (config.FollowsDefaultStoragePath ||
- string.IsNullOrWhiteSpace(config.MappedFolderPath))
+ string.IsNullOrWhiteSpace(config.MappedFolderPath) ||
+ MappedOrganizeWidgetMetadata.IsMappedOrganize(config))
{
RemoveMappedWidgetShortcut(config);
return;
diff --git a/src/DeskBox/Strings/ar-SA.json b/src/DeskBox/Strings/ar-SA.json
index bffaaa8c3..2734cb84f 100644
--- a/src/DeskBox/Strings/ar-SA.json
+++ b/src/DeskBox/Strings/ar-SA.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "هذه القطعة لا تقبل أي أنواع ملفات حتى الآن. أضف واحدًا قبل تمكينه.",
"DesktopOrganization.FilePreview.More": "{0} ملفات أخرى",
"DesktopOrganization.Preview.Title": "تأكيد تنظيم سطح المكتب",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "سيتم تنظيم {0} عنصرًا في {1} أداة، بما في ذلك {2} أداة جديدة.",
"DesktopOrganization.Preview.MoveNotice": "الجذر الافتراضي لعناصر واجهة المستخدم الجديدة: {0}. الهدف الدقيق لكل فئة مذكور أعلاه.",
"DesktopOrganization.Preview.Confirm": "تنظيم {0} ملفًا",
diff --git a/src/DeskBox/Strings/bn-BD.json b/src/DeskBox/Strings/bn-BD.json
index dd5358629..4066e5d35 100644
--- a/src/DeskBox/Strings/bn-BD.json
+++ b/src/DeskBox/Strings/bn-BD.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "এই উইজেটটি এখনও কোনো ফাইল প্রকার গ্রহণ করে না। এটি সক্রিয় করার আগে একটি যোগ করুন।",
"DesktopOrganization.FilePreview.More": "{0} আরও ফাইল",
"DesktopOrganization.Preview.Title": "ডেস্কটপ গোছানো নিশ্চিত করুন",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0} আইটেমগুলিকে {1} উইজেটে সংগঠিত করা হবে, {2} নতুন উইজেট সহ।",
"DesktopOrganization.Preview.MoveNotice": "নতুন উইজেটগুলির জন্য ডিফল্ট রুট: {0}। প্রতিটি বিভাগের জন্য সঠিক লক্ষ্য উপরে তালিকাভুক্ত করা হয়েছে।",
"DesktopOrganization.Preview.Confirm": "{0} ফাইলগুলি সংগঠিত করুন",
diff --git a/src/DeskBox/Strings/de-DE.json b/src/DeskBox/Strings/de-DE.json
index f9941923d..3a2b5d9b8 100644
--- a/src/DeskBox/Strings/de-DE.json
+++ b/src/DeskBox/Strings/de-DE.json
@@ -2238,6 +2238,12 @@
"DesktopOrganization.Rule.TransferAction": "Ziel ändern",
"DesktopOrganization.FilePreview.More": "{0} weitere Dateien",
"DesktopOrganization.Preview.Title": "Desktop-Organisation bestätigen",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0} Elemente werden in {1} Widgets organisiert, davon {2} neu.",
"DesktopOrganization.Preview.MoveNotice": "Standardstamm für neue Widgets: {0}. Die tatsächlichen Ziele stehen oben.",
"DesktopOrganization.Preview.Confirm": "{0} Dateien organisieren",
diff --git a/src/DeskBox/Strings/en-US.json b/src/DeskBox/Strings/en-US.json
index 0aa28fb30..262a4e752 100644
--- a/src/DeskBox/Strings/en-US.json
+++ b/src/DeskBox/Strings/en-US.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "This widget does not accept any file types yet. Add one before enabling it.",
"DesktopOrganization.FilePreview.More": "{0} more files",
"DesktopOrganization.Preview.Title": "Confirm desktop organization",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0} items will be organized into {1} widgets, including {2} new widgets.",
"DesktopOrganization.Preview.MoveNotice": "Default root for new widgets: {0}. The exact target for every category is listed above.",
"DesktopOrganization.Preview.Confirm": "Organize {0} files",
diff --git a/src/DeskBox/Strings/es-ES.json b/src/DeskBox/Strings/es-ES.json
index c4a8c9b81..1e5e0ad00 100644
--- a/src/DeskBox/Strings/es-ES.json
+++ b/src/DeskBox/Strings/es-ES.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "Este widget aún no acepta ningún tipo de archivo. Añade uno antes de habilitarlo.",
"DesktopOrganization.FilePreview.More": "{0} archivos más",
"DesktopOrganization.Preview.Title": "Confirmar la organización del escritorio",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "Se organizarán {0} elementos en {1} widgets, incluidos {2} nuevos.",
"DesktopOrganization.Preview.MoveNotice": "Raíz predeterminada para nuevos widgets: {0}. El objetivo exacto para cada categoría se enumera arriba.",
"DesktopOrganization.Preview.Confirm": "Organizar {0} archivos",
diff --git a/src/DeskBox/Strings/fr-FR.json b/src/DeskBox/Strings/fr-FR.json
index f19d324fb..e75857ccd 100644
--- a/src/DeskBox/Strings/fr-FR.json
+++ b/src/DeskBox/Strings/fr-FR.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "Ce widget n'accepte aucun type de fichier pour l'instant. Ajoutez-en un avant de l’activer.",
"DesktopOrganization.FilePreview.More": "{0} fichiers de plus",
"DesktopOrganization.Preview.Title": "Confirmer l'organisation du bureau",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "Les {0} éléments seront organisés en {1} widgets, dont {2} nouveaux.",
"DesktopOrganization.Preview.MoveNotice": "Racine par défaut pour les nouveaux widgets : {0}. L’objectif exact pour chaque catégorie est indiqué ci-dessus.",
"DesktopOrganization.Preview.Confirm": "Organiser {0} fichiers",
diff --git a/src/DeskBox/Strings/hi-IN.json b/src/DeskBox/Strings/hi-IN.json
index df8bf11b5..cfc4eb4bd 100644
--- a/src/DeskBox/Strings/hi-IN.json
+++ b/src/DeskBox/Strings/hi-IN.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "यह विजेट अभी तक किसी भी फ़ाइल प्रकार को स्वीकार नहीं करता है। इसे सक्षम करने से पहले एक जोड़ें।",
"DesktopOrganization.FilePreview.More": "{0} अधिक फ़ाइलें",
"DesktopOrganization.Preview.Title": "डेस्कटॉप संगठन की पुष्टि करें",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0} आइटम को {1} विजेट में व्यवस्थित किया जाएगा, जिसमें {2} नए विजेट भी शामिल होंगे।",
"DesktopOrganization.Preview.MoveNotice": "नए विजेट के लिए डिफ़ॉल्ट रूट: {0}। प्रत्येक श्रेणी के लिए सटीक लक्ष्य ऊपर सूचीबद्ध है।",
"DesktopOrganization.Preview.Confirm": "{0} फ़ाइलें व्यवस्थित करें",
diff --git a/src/DeskBox/Strings/ja-JP.json b/src/DeskBox/Strings/ja-JP.json
index d5828751a..03f1bc29d 100644
--- a/src/DeskBox/Strings/ja-JP.json
+++ b/src/DeskBox/Strings/ja-JP.json
@@ -2238,6 +2238,12 @@
"DesktopOrganization.Rule.TransferAction": "整理先を変更",
"DesktopOrganization.FilePreview.More": "ほか {0} ファイル",
"DesktopOrganization.Preview.Title": "デスクトップ整理の確認",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0} 項目を {1} 個のウィジェットへ整理し、そのうち {2} 個を新規作成します。",
"DesktopOrganization.Preview.MoveNotice": "新しいウィジェットの既定ルート: {0}。分類ごとの実際の移動先は上に表示されています。",
"DesktopOrganization.Preview.Confirm": "{0} ファイルを整理",
diff --git a/src/DeskBox/Strings/ko-KR.json b/src/DeskBox/Strings/ko-KR.json
index 86747ed53..76235f6d8 100644
--- a/src/DeskBox/Strings/ko-KR.json
+++ b/src/DeskBox/Strings/ko-KR.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "이 위젯은 아직 아무 파일 형식도 받지 않습니다. 추가한 뒤에 사용할 수 있습니다.",
"DesktopOrganization.FilePreview.More": "파일 {0}개 더 있음",
"DesktopOrganization.Preview.Title": "바탕 화면 정리 확인",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0}개 항목을 {1}개 위젯으로 정리하며 이 가운데 {2}개는 새로 만듭니다.",
"DesktopOrganization.Preview.MoveNotice": "새 위젯의 기본 저장 루트: {0}. 각 파일 범주의 실제 대상도 위에 함께 표시됩니다.",
"DesktopOrganization.Preview.Confirm": "파일 {0}개 정리",
diff --git a/src/DeskBox/Strings/pt-BR.json b/src/DeskBox/Strings/pt-BR.json
index 89625fff5..4c18e38e0 100644
--- a/src/DeskBox/Strings/pt-BR.json
+++ b/src/DeskBox/Strings/pt-BR.json
@@ -2238,6 +2238,12 @@
"DesktopOrganization.Rule.TransferAction": "Alterar destino",
"DesktopOrganization.FilePreview.More": "Mais {0} arquivos",
"DesktopOrganization.Preview.Title": "Confirmar organização",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "{0} itens serão organizados em {1} widgets, incluindo {2} novos.",
"DesktopOrganization.Preview.MoveNotice": "Raiz padrão para novos widgets: {0}. Os destinos reais estão listados acima.",
"DesktopOrganization.Preview.Confirm": "Organizar {0} arquivos",
diff --git a/src/DeskBox/Strings/ru-RU.json b/src/DeskBox/Strings/ru-RU.json
index 24d1d84ea..829dc337a 100644
--- a/src/DeskBox/Strings/ru-RU.json
+++ b/src/DeskBox/Strings/ru-RU.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "Этот виджет пока не принимает никакие типы файлов. Добавьте его, прежде чем включать.",
"DesktopOrganization.FilePreview.More": "Ещё файлов: {0}",
"DesktopOrganization.Preview.Title": "Подтверждение организации рабочего стола",
+ "MappedOrganize.Preview.MapOnly": "Map only, don't move files",
+ "MappedOrganize.Preview.MapOnlyDescription": "Files stay in the Desktop folder and widgets only record which items they show. The native desktop icons are hidden while mapped widgets exist and come back when the last one is dissolved or DeskBox exits.",
+ "MappedOrganize.Result.Success": "Mapped {0} items into {1} widgets. The files stay in the Desktop folder.",
+ "MappedOrganize.Menu.OrganizeNow": "Organize now",
+ "MappedOrganize.Menu.AutoAssign": "Auto-sort new desktop files",
+ "MappedOrganize.Menu.DissolveAll": "Exit mapped organize (restore desktop icons)",
"DesktopOrganization.Preview.Summary": "Будет упорядочено элементов: {0}, задействовано виджетов: {1}, из них новых: {2}.",
"DesktopOrganization.Preview.MoveNotice": "Корень по умолчанию для новых виджетов: {0}. Точная цель для каждой категории указана выше.",
"DesktopOrganization.Preview.Confirm": "Упорядочить файлы ({0})",
diff --git a/src/DeskBox/Strings/zh-CN.json b/src/DeskBox/Strings/zh-CN.json
index 08189b3f6..cc3e2c5fa 100644
--- a/src/DeskBox/Strings/zh-CN.json
+++ b/src/DeskBox/Strings/zh-CN.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "这个格子还没有接收任何文件类型,添加后即可启用。",
"DesktopOrganization.FilePreview.More": "还有 {0} 个文件",
"DesktopOrganization.Preview.Title": "确认桌面整理",
+ "MappedOrganize.Preview.MapOnly": "只映射,不移动文件",
+ "MappedOrganize.Preview.MapOnlyDescription": "文件保留在桌面文件夹中,格子只记录归属。存在映射格子时会隐藏系统桌面图标,解散最后一个映射格子或退出 DeskBox 时恢复。",
+ "MappedOrganize.Result.Success": "已将 {0} 个项目映射到 {1} 个格子,文件仍在桌面文件夹中。",
+ "MappedOrganize.Menu.OrganizeNow": "一键整理",
+ "MappedOrganize.Menu.AutoAssign": "自动归类新文件",
+ "MappedOrganize.Menu.DissolveAll": "退出映射整理(恢复桌面图标)",
"DesktopOrganization.Preview.Summary": "将整理 {0} 个项目,使用 {1} 个格子,其中新建 {2} 个。",
"DesktopOrganization.Preview.MoveNotice": "新建格子的默认收纳根目录: {0}。上方同时列出了每一类文件的实际目标。",
"DesktopOrganization.Preview.Confirm": "整理 {0} 个文件",
diff --git a/src/DeskBox/Strings/zh-TW.json b/src/DeskBox/Strings/zh-TW.json
index cc76ebb85..05f1c373e 100644
--- a/src/DeskBox/Strings/zh-TW.json
+++ b/src/DeskBox/Strings/zh-TW.json
@@ -2263,6 +2263,12 @@
"DesktopOrganization.Rule.NoTypesBody": "這個小工具還沒有接收任何檔案類型,新增後即可啟用。",
"DesktopOrganization.FilePreview.More": "還有 {0} 個檔案",
"DesktopOrganization.Preview.Title": "確認桌面整理",
+ "MappedOrganize.Preview.MapOnly": "只映射,不移動檔案",
+ "MappedOrganize.Preview.MapOnlyDescription": "檔案保留在桌面資料夾中,格子只記錄歸屬。存在映射格子時會隱藏系統桌面圖示,解散最後一個映射格子或結束 DeskBox 時恢復。",
+ "MappedOrganize.Result.Success": "已將 {0} 個項目映射到 {1} 個格子,檔案仍在桌面資料夾中。",
+ "MappedOrganize.Menu.OrganizeNow": "一鍵整理",
+ "MappedOrganize.Menu.AutoAssign": "自動歸類新檔案",
+ "MappedOrganize.Menu.DissolveAll": "結束映射整理(恢復桌面圖示)",
"DesktopOrganization.Preview.Summary": "將整理 {0} 個項目,使用 {1} 個小工具,其中建立 {2} 個。",
"DesktopOrganization.Preview.MoveNotice": "建立小工具的預設收納根目錄:{0}。上方同時列出了每一類檔案的實際目標。",
"DesktopOrganization.Preview.Confirm": "整理 {0} 個檔案",
diff --git a/src/DeskBox/ViewModels/WidgetViewModel.ItemHydration.cs b/src/DeskBox/ViewModels/WidgetViewModel.ItemHydration.cs
index 69c0a735b..d1e2bb3ce 100644
--- a/src/DeskBox/ViewModels/WidgetViewModel.ItemHydration.cs
+++ b/src/DeskBox/ViewModels/WidgetViewModel.ItemHydration.cs
@@ -114,6 +114,7 @@ private async Task LoadFolderContentsAsync(
.OrderBy(item => !item.IsFolder)
.ThenBy(item => item.Name, NaturalStringComparer.CurrentCultureIgnoreCase)
.ToList();
+ items = ApplyMappedOrganizeFilter(items);
}
else
{
diff --git a/src/DeskBox/ViewModels/WidgetViewModel.MappedOrganize.cs b/src/DeskBox/ViewModels/WidgetViewModel.MappedOrganize.cs
new file mode 100644
index 000000000..a48c59d94
--- /dev/null
+++ b/src/DeskBox/ViewModels/WidgetViewModel.MappedOrganize.cs
@@ -0,0 +1,110 @@
+using DeskBox.Models;
+using DeskBox.Services;
+
+namespace DeskBox.ViewModels;
+
+///
+/// Fork feature 「映射整理」: a mapped-organize widget maps the Desktop but only
+/// lists the desktop entries recorded as its members. Everything else (open,
+/// rename, delete, shell menus, hydration) is the ordinary folder pipeline
+/// acting on the real files. See docs/architecture/mapped-organize.md.
+///
+public partial class WidgetViewModel
+{
+ private bool _mappedOrganizeSubscribed;
+
+ public bool IsMappedOrganizeWidget => MappedOrganizeWidgetMetadata.IsMappedOrganize(Config);
+
+ private void AttachMappedOrganize()
+ {
+ if (_mappedOrganizeSubscribed)
+ {
+ return;
+ }
+
+ MappedOrganizeService.MembershipChanged += OnMappedOrganizeMembershipChanged;
+ _mappedOrganizeSubscribed = true;
+ }
+
+ private void DetachMappedOrganize()
+ {
+ if (!_mappedOrganizeSubscribed)
+ {
+ return;
+ }
+
+ MappedOrganizeService.MembershipChanged -= OnMappedOrganizeMembershipChanged;
+ _mappedOrganizeSubscribed = false;
+ }
+
+ private void OnMappedOrganizeMembershipChanged(IReadOnlyCollection widgetIds)
+ {
+ if (_isDisposed || !IsMappedOrganizeWidget || !widgetIds.Contains(Config.Id))
+ {
+ return;
+ }
+
+ _dispatcherQueue.TryEnqueue(async () =>
+ {
+ try
+ {
+ if (!_isDisposed)
+ {
+ await RefreshFolderContentsAsync();
+ }
+ }
+ catch (Exception ex)
+ {
+ App.Log($"[MappedOrganize] Refresh after membership change failed widget={Config.Id}: {ex.Message}");
+ }
+ });
+ }
+
+ /// Desktop snapshot → only this widget's members (no-op for ordinary widgets).
+ private IReadOnlyList ApplyMappedOrganizeFilter(IReadOnlyList items)
+ {
+ if (!IsMappedOrganizeWidget)
+ {
+ return items;
+ }
+
+ var members = MappedOrganizeMembership.GetMembers(Config).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ return items
+ .Where(item => !string.IsNullOrWhiteSpace(item.Path) &&
+ members.Contains(MappedOrganizeMembership.NormalizePath(item.Path)))
+ .ToList();
+ }
+
+ /// Incremental watcher upserts: a desktop entry shows only when it is a member.
+ private bool IsHiddenByMappedOrganize(string path)
+ {
+ return IsMappedOrganizeWidget &&
+ MappedOrganizeService.IsDesktopEntryPath(path) &&
+ !MappedOrganizeMembership.IsMember(Config, path);
+ }
+
+ ///
+ /// Drops onto a mapped widget: desktop entries (including drags from
+ /// another mapped widget) only change membership; anything else follows
+ /// the normal import into the Desktop folder and is then claimed by this
+ /// widget when it appears there. Returns the paths still to import.
+ ///
+ private List ClaimMappedOrganizeDrop(List paths, out List claimed)
+ {
+ claimed = [];
+ if (!IsMappedOrganizeWidget || MappedOrganizeService.Current is not { } service)
+ {
+ return paths;
+ }
+
+ claimed = service.AssignDesktopPaths(Config.Id, paths).ToList();
+ var claimedSet = claimed.ToHashSet(StringComparer.OrdinalIgnoreCase);
+ List remaining = paths.Where(path => !claimedSet.Contains(path)).ToList();
+ if (remaining.Count > 0)
+ {
+ service.ExpectIncoming(Config.Id, remaining);
+ }
+
+ return remaining;
+ }
+}
diff --git a/src/DeskBox/ViewModels/WidgetViewModel.Operations.cs b/src/DeskBox/ViewModels/WidgetViewModel.Operations.cs
index 47a61e84b..f65dc2f38 100644
--- a/src/DeskBox/ViewModels/WidgetViewModel.Operations.cs
+++ b/src/DeskBox/ViewModels/WidgetViewModel.Operations.cs
@@ -71,6 +71,13 @@ public async Task> ImportPathsAsync(
return [];
}
+ normalizedPaths = ClaimMappedOrganizeDrop(normalizedPaths, out List mappedClaimed);
+ if (normalizedPaths.Count == 0)
+ {
+ LastImportSkippedUndisplayableCount = 0;
+ return mappedClaimed;
+ }
+
// Entries the widget item list can never represent (hidden files)
// must not be moved into managed storage: the folder would hold an
// invisible file no tile can show. The probe does filesystem I/O, so
diff --git a/src/DeskBox/ViewModels/WidgetViewModel.SortingAndWatchers.cs b/src/DeskBox/ViewModels/WidgetViewModel.SortingAndWatchers.cs
index a32e80bdb..b8e2518aa 100644
--- a/src/DeskBox/ViewModels/WidgetViewModel.SortingAndWatchers.cs
+++ b/src/DeskBox/ViewModels/WidgetViewModel.SortingAndWatchers.cs
@@ -656,6 +656,12 @@ private async Task UpsertFolderItemAsync(
string path,
int? preferredManualIndex = null)
{
+ if (IsHiddenByMappedOrganize(path))
+ {
+ RemoveItemByPath(path);
+ return false;
+ }
+
var item = await _fileService.TryCreateWidgetItemAsync(
path,
hideShortcutArrowOverlay: _hideShortcutArrowOverlay,
diff --git a/src/DeskBox/ViewModels/WidgetViewModel.cs b/src/DeskBox/ViewModels/WidgetViewModel.cs
index b69180381..d9ebcfb28 100644
--- a/src/DeskBox/ViewModels/WidgetViewModel.cs
+++ b/src/DeskBox/ViewModels/WidgetViewModel.cs
@@ -416,6 +416,7 @@ public WidgetViewModel(
_localizationService.LanguageChanged += OnLanguageChanged;
InitializeStacks();
AttachRenderWindowTracking();
+ AttachMappedOrganize();
}
public WidgetViewModel(
@@ -456,6 +457,7 @@ public void Dispose()
// short-lived after this point and the waiter exits via _isDisposed.
_settingsService.SettingsChanged -= OnSettingsChanged;
_localizationService.LanguageChanged -= OnLanguageChanged;
+ DetachMappedOrganize();
}
public void SuspendBackgroundActivity()
diff --git a/tests/DeskBox.Tests/MappedOrganizeMembershipTests.cs b/tests/DeskBox.Tests/MappedOrganizeMembershipTests.cs
new file mode 100644
index 000000000..ef51f3086
--- /dev/null
+++ b/tests/DeskBox.Tests/MappedOrganizeMembershipTests.cs
@@ -0,0 +1,162 @@
+using DeskBox.Models;
+using DeskBox.Services;
+
+namespace DeskBox.Tests;
+
+public sealed class MappedOrganizeMembershipTests
+{
+ private static readonly string Desktop = Path.Combine(Path.GetTempPath(), "deskbox-mapped-tests", "Desktop");
+
+ private static string D(string name) => Path.Combine(Desktop, name);
+
+ private static WidgetConfig Mapped(string id, string categoryId)
+ {
+ var widget = new WidgetConfig { Id = id, Name = id, WidgetKind = WidgetKind.File, MappedFolderPath = Desktop };
+ MappedOrganizeWidgetMetadata.Mark(widget, categoryId);
+ return widget;
+ }
+
+ [Fact]
+ public void Mark_IdentifiesMappedWidgets_AndOrdinaryWidgetsStayOrdinary()
+ {
+ var mapped = Mapped("a", DesktopOrganizationCategoryIds.Images);
+ var ordinary = new WidgetConfig { Id = "b", MappedFolderPath = Desktop };
+
+ Assert.True(MappedOrganizeWidgetMetadata.IsMappedOrganize(mapped));
+ Assert.False(MappedOrganizeWidgetMetadata.IsMappedOrganize(ordinary));
+ Assert.Equal(DesktopOrganizationCategoryIds.Images, MappedOrganizeWidgetMetadata.GetCategory(mapped));
+ Assert.Empty(MappedOrganizeMembership.GetMembers(mapped));
+ }
+
+ [Fact]
+ public void Assign_IsExclusive_AndOnlyChangesMembership()
+ {
+ var images = Mapped("images", DesktopOrganizationCategoryIds.Images);
+ var other = Mapped("other", DesktopOrganizationCategoryIds.Other);
+ var widgets = new List { images, other };
+
+ MappedOrganizeMembership.Assign(widgets, "other", [D("a.png"), D("b.txt")]);
+ IReadOnlyList changed = MappedOrganizeMembership.Assign(widgets, "images", [D("a.png")]);
+
+ Assert.Equal(new[] { "other", "images" }, changed);
+ Assert.Equal(new[] { D("a.png") }, MappedOrganizeMembership.GetMembers(images));
+ Assert.Equal(new[] { D("b.txt") }, MappedOrganizeMembership.GetMembers(other));
+ Assert.Same(images, MappedOrganizeMembership.FindOwner(widgets, D("A.PNG")));
+ }
+
+ [Fact]
+ public void Assign_IgnoresUnknownOrOrdinaryTargets_AndDeduplicates()
+ {
+ var images = Mapped("images", DesktopOrganizationCategoryIds.Images);
+ var ordinary = new WidgetConfig { Id = "folder", MappedFolderPath = Desktop };
+ var widgets = new List { images, ordinary };
+
+ Assert.Empty(MappedOrganizeMembership.Assign(widgets, "folder", [D("x.png")]));
+ Assert.Empty(MappedOrganizeMembership.Assign(widgets, "missing", [D("x.png")]));
+
+ MappedOrganizeMembership.Assign(widgets, "images", [D("x.png"), D("X.png"), D("x.png")]);
+ Assert.Single(MappedOrganizeMembership.GetMembers(images));
+ Assert.Empty(MappedOrganizeMembership.Assign(widgets, "images", [D("x.png")]));
+ }
+
+ [Fact]
+ public void Rename_KeepsEntryInSameWidgetAndPosition()
+ {
+ var docs = Mapped("docs", DesktopOrganizationCategoryIds.Documents);
+ var widgets = new List { docs };
+ MappedOrganizeMembership.Assign(widgets, "docs", [D("1.txt"), D("2.txt"), D("3.txt")]);
+
+ IReadOnlyList changed = MappedOrganizeMembership.RenamePath(widgets, D("2.txt"), D("renamed.txt"));
+
+ Assert.Equal(new[] { "docs" }, changed);
+ Assert.Equal(new[] { D("1.txt"), D("renamed.txt"), D("3.txt") }, MappedOrganizeMembership.GetMembers(docs));
+ Assert.Empty(MappedOrganizeMembership.RenamePath(widgets, D("unknown.txt"), D("y.txt")));
+ }
+
+ [Fact]
+ public void RemoveAndPrune_DropOnlyMissingEntries()
+ {
+ var docs = Mapped("docs", DesktopOrganizationCategoryIds.Documents);
+ var widgets = new List { docs };
+ MappedOrganizeMembership.Assign(widgets, "docs", [D("keep.txt"), D("gone.txt"), D("deleted.txt")]);
+
+ Assert.Equal(new[] { "docs" }, MappedOrganizeMembership.RemovePath(widgets, D("deleted.txt")));
+ Assert.Equal(new[] { "docs" }, MappedOrganizeMembership.Prune(widgets, path => !path.EndsWith("gone.txt", StringComparison.Ordinal)));
+ Assert.Equal(new[] { D("keep.txt") }, MappedOrganizeMembership.GetMembers(docs));
+ Assert.Empty(MappedOrganizeMembership.Prune(widgets, _ => true));
+ }
+
+ [Fact]
+ public void FindUnassigned_ReturnsDesktopEntriesWithoutOwner()
+ {
+ var docs = Mapped("docs", DesktopOrganizationCategoryIds.Documents);
+ var widgets = new List { docs };
+ MappedOrganizeMembership.Assign(widgets, "docs", [D("a.txt")]);
+
+ IReadOnlyList unassigned = MappedOrganizeMembership.FindUnassigned(
+ widgets, [D("a.txt"), D("b.png"), D("B.PNG"), D("c.lnk")]);
+
+ Assert.Equal(new[] { D("b.png"), D("c.lnk") }, unassigned);
+ }
+
+ [Fact]
+ public void ResolveTarget_PrefersCategory_ThenOther_ThenNull()
+ {
+ var images = Mapped("images", DesktopOrganizationCategoryIds.Images);
+ var other = Mapped("other", DesktopOrganizationCategoryIds.Other);
+
+ Assert.Same(images, MappedOrganizeMembership.ResolveTarget([images, other], DesktopOrganizationCategoryIds.Images));
+ Assert.Same(other, MappedOrganizeMembership.ResolveTarget([images, other], DesktopOrganizationCategoryIds.Packages));
+ Assert.Null(MappedOrganizeMembership.ResolveTarget([images], DesktopOrganizationCategoryIds.Packages));
+ }
+
+ [Fact]
+ public void PlanAssignments_UsesClassifierCategories_AndReportsMissingOther()
+ {
+ var classifier = new DesktopOrganizationClassifier();
+ var images = Mapped("images", DesktopOrganizationCategoryIds.Images);
+ var docs = Mapped("docs", DesktopOrganizationCategoryIds.Documents);
+ var entries = new[]
+ {
+ (D("photo.jpg"), MappedOrganizeMembership.Classify(classifier, D("photo.jpg"), isDirectory: false)),
+ (D("report.pdf"), MappedOrganizeMembership.Classify(classifier, D("report.pdf"), isDirectory: false)),
+ (D("setup.exe"), MappedOrganizeMembership.Classify(classifier, D("setup.exe"), isDirectory: false)),
+ (D("Folder"), MappedOrganizeMembership.Classify(classifier, D("Folder"), isDirectory: true))
+ };
+
+ var plan = MappedOrganizeMembership.PlanAssignments([images, docs], entries, out List needsOther);
+
+ Assert.Equal(new[] { D("photo.jpg") }, plan["images"]);
+ Assert.Equal(new[] { D("report.pdf") }, plan["docs"]);
+ Assert.Equal(new[] { D("setup.exe"), D("Folder") }, needsOther);
+ }
+
+ [Fact]
+ public void Membership_RoundTripsThroughWidgetMetadata()
+ {
+ var widget = Mapped("w", DesktopOrganizationCategoryIds.Media);
+ MappedOrganizeMembership.SetMembers(widget, [D("song.mp3"), D("clip.mp4")]);
+
+ var copy = new WidgetConfig { Metadata = new Dictionary(widget.Metadata) };
+
+ Assert.True(MappedOrganizeWidgetMetadata.IsMappedOrganize(copy));
+ Assert.Equal(new[] { D("song.mp3"), D("clip.mp4") }, MappedOrganizeMembership.GetMembers(copy));
+ Assert.True(MappedOrganizeMembership.IsMember(copy, D("SONG.mp3")));
+ }
+
+ [Fact]
+ public void OrdinaryOrganization_NeverRoutesToMappedWidgets()
+ {
+ var mapped = Mapped("mapped", DesktopOrganizationCategoryIds.Images);
+ var rule = new DesktopOrganizationRule
+ {
+ TargetWidgetId = "mapped",
+ CategoryIds = [DesktopOrganizationCategoryIds.Images]
+ };
+ var item = new DesktopOrganizationFileSnapshot(
+ D("a.png"), "a.png", ".png", 1, DateTime.UtcNow,
+ DesktopOrganizationCategoryIds.Images, null, DesktopOrganizationExclusionReason.None);
+
+ Assert.Null(new DesktopOrganizationRuleResolver().Resolve(item, [rule], [mapped]));
+ }
+}
From 27784e02a889567a7a3795460bba335f03b6d962 Mon Sep 17 00:00:00 2001
From: GOXF <131693427+GOXF@users.noreply.github.com>
Date: Sun, 8 Nov 2026 03:58:49 +0000
Subject: [PATCH 2/2] fix(mapped-organize): write state file in place (no
File.Move outside file-safety domains)
---
src/DeskBox/Services/MappedOrganizeService.cs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/DeskBox/Services/MappedOrganizeService.cs b/src/DeskBox/Services/MappedOrganizeService.cs
index 6e1a87dce..3609de57a 100644
--- a/src/DeskBox/Services/MappedOrganizeService.cs
+++ b/src/DeskBox/Services/MappedOrganizeService.cs
@@ -780,13 +780,13 @@ private void SaveState()
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_statePath)!);
- string temporary = _statePath + ".tmp";
- File.WriteAllLines(temporary,
+ // Two short lines; a torn write reads back as defaults (auto on,
+ // marker off) and Explorer never persists the hidden list view.
+ File.WriteAllLines(_statePath,
[
$"{AutoAssignKey}={(_autoAssignNewItems ? "true" : "false")}",
$"{IconsHiddenKey}={(_iconsHiddenByDeskBox ? "true" : "false")}"
]);
- File.Move(temporary, _statePath, overwrite: true);
}
catch (Exception ex)
{