Skip to content
Merged
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
90 changes: 90 additions & 0 deletions docs/architecture/mapped-organize.md
Original file line number Diff line number Diff line change
@@ -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).
45 changes: 45 additions & 0 deletions src/DeskBox/App.MappedOrganize.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using DeskBox.Services;

namespace DeskBox;

/// <summary>Fork feature 「映射整理」: host lifecycle (start after widget restore, always restore icons on exit).</summary>
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;
}
}
3 changes: 3 additions & 0 deletions src/DeskBox/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1551,6 +1551,7 @@
try
{
await widgetManager.RestoreWidgetsAsync();
InitializeMappedOrganize(widgetManager);
}
catch (Exception ex)
{
Expand All @@ -1559,6 +1560,7 @@
// blocking startup.
Log($"[Startup] Optional step 'restore-widgets' failed: {ex}");
RecordStartupDegradation("restore-widgets", ex.ToString());
InitializeMappedOrganize(widgetManager);
if (startupDesktopLayerReadinessTask is not null)
{
startupDesktopLayerReadinessTask = null;
Expand Down Expand Up @@ -2782,7 +2784,7 @@
return null;
}

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

Check warning on line 2787 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 2787 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 @@ -6785,6 +6787,7 @@
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", () =>
Expand Down
5 changes: 5 additions & 0 deletions src/DeskBox/Controls/DesktopOrganizationTaskView.Actions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ private async void ExecuteButton_Click(object sender, RoutedEventArgs e)
return;
}

if (await TryRunMappedOrganizeAsync(previewPlan))
{
return;
}

DesktopOrganizationPlan plan;
try
{
Expand Down
116 changes: 116 additions & 0 deletions src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using DeskBox.Models;
using DeskBox.Services;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;

namespace DeskBox.Controls;

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

/// <summary>Returns true when the mapped path handled the confirm click.</summary>
private async Task<bool> 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<MappedOrganizeGroup> 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;
}
}
2 changes: 2 additions & 0 deletions src/DeskBox/Controls/DesktopOrganizationTaskView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,8 @@
<Grid ColumnDefinitions="*,Auto,Auto,Auto,Auto" ColumnSpacing="8">
<TextBlock x:Name="FooterSummaryText" VerticalAlignment="Center" TextWrapping="Wrap"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
<CheckBox x:Name="MapOnlyCheckBox" Grid.Column="1" MinWidth="0" VerticalAlignment="Center"
Loaded="MapOnlyCheckBox_Loaded" />
<Button x:Name="UndoButton" Grid.Column="1" Click="UndoButton_Click" Visibility="Collapsed" />
<Button x:Name="AbandonUndoButton" Grid.Column="2" Click="AbandonUndoButton_Click" Visibility="Collapsed" />
<Button x:Name="CancelButton" Grid.Column="3" Click="CancelButton_Click" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using DeskBox.Services;
using Microsoft.UI.Xaml.Controls;

namespace DeskBox.Controls.WidgetContents;

/// <summary>Fork feature 「映射整理」: blank-area menu entries of a mapped-organize widget.</summary>
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,7 @@ private MenuFlyout CreateContentAreaFlyout()
}
};
flyout.Items.Add(openFolder);
AddMappedOrganizeMenuItems(flyout);

if (hostItems.CloseWidgetItem is not null)
{
Expand Down
Loading
Loading