From b4af2cfe984b65930bb3f47a505a7f275c69c615 Mon Sep 17 00:00:00 2001 From: GOXF <131693427+GOXF@users.noreply.github.com> Date: Sun, 8 Nov 2026 08:30:30 +0000 Subject: [PATCH] =?UTF-8?q?feat(=E6=95=B4=E7=90=86=E6=A1=8C=E9=9D=A2):=20?= =?UTF-8?q?=E4=B8=80=E9=94=AE=E6=95=B4=E7=90=86=EF=BC=8C=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E5=BC=B9=E5=87=BA=E9=A2=84=E8=A7=88=20+=20=E5=90=8C=E7=B1=BB?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=96=B0=E5=BB=BA=E9=87=8D=E5=A4=8D=E6=A0=BC?= =?UTF-8?q?=E5=AD=90=EF=BC=88=E5=A6=82=E4=B8=A4=E4=B8=AA=E3=80=8C=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E3=80=8D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 一键整理 - 托盘「整理桌面…」、设置「一键整理桌面」/文件格子「整理桌面」按钮(ISettingsAppActions in-process 实现)、映射格子空白处「一键整理」、标题栏「…」「一键整理桌面」(原「重新整理桌面」) 直接执行整理,不再打开预览(无 待整理/留在桌面 区分);完成后发通知(移动模式带「撤销」)。 - 按全局「整理方式」:移动到格子 = 执行预览的默认方案(同一事务/历史/撤销); 只映射 = 先清除所有「放回桌面」标记,文件夹/大文件也一并映射,项优先进同类映射格子, 其余按规划分组,最后按「一键整理」规则兜底。 - 有中断待恢复的整理、预览窗口已打开或宿主未就绪时改为打开预览。 - 旧预览保留为「整理预览…」:托盘菜单、映射格子空白处菜单、标题栏「…」菜单。 - 自动归类新文件仍跳过「放回桌面」项(不变)。 重复「其他」 - 原因:上次整理创建的「其他」格子规则只含当时的分类([Other]);单个项目的分类(如 1 个视频/Media) 被并入「其他」桶后匹配不到规则,规划器就又提议「新建'其他'」。 - 修复:DesktopOrganizationCategoryReuse —— 新建桶前先复用规则含该分类的格子(尊重排除扩展名), 其次复用同名格子;映射分组也按分类、再按名称复用已有映射格子(ApplyGroupsAsync)。 上游文件改动:App.Tray.cs 2 行、InProcessSettingsAppActions.cs 1 行、DesktopOrganizationPlanner.cs 1 块。 不改 Strings/*.json(文案内联在 ForkOrganizeModeText)。新增 ForkOneClickOrganizeTests。 --- docs/architecture/mapped-organize.md | 57 ++++- src/DeskBox/App.ForkOneClickOrganize.cs | 199 +++++++++++++++ src/DeskBox/App.Tray.cs | 3 +- ...ktopOrganizationTaskView.MappedOrganize.cs | 2 +- .../FileSurfaceContent.MappedOrganize.cs | 47 ++-- .../DesktopOrganizationCategoryReuse.cs | 80 ++++++ .../Services/DesktopOrganizationPlanner.cs | 13 + src/DeskBox/Services/ForkOneClickOrganize.cs | 229 ++++++++++++++++++ .../Services/ForkOrganizeModeSettings.cs | 42 +++- .../Services/InProcessSettingsAppActions.cs | 3 +- .../MappedOrganizeReorganizePolicy.cs | 8 +- .../MappedOrganizeService.Visibility.cs | 25 ++ src/DeskBox/Services/MappedOrganizeService.cs | 5 +- .../ContentWidgetWindow.MappedOrganize.cs | 9 +- .../ForkOneClickOrganizeTests.cs | 212 ++++++++++++++++ .../MappedOrganizeReorganizeTests.cs | 9 +- 16 files changed, 898 insertions(+), 45 deletions(-) create mode 100644 src/DeskBox/App.ForkOneClickOrganize.cs create mode 100644 src/DeskBox/Services/DesktopOrganizationCategoryReuse.cs create mode 100644 src/DeskBox/Services/ForkOneClickOrganize.cs create mode 100644 tests/DeskBox.Tests/ForkOneClickOrganizeTests.cs diff --git a/docs/architecture/mapped-organize.md b/docs/architecture/mapped-organize.md index 5e2e3335c..7294f24f6 100644 --- a/docs/architecture/mapped-organize.md +++ b/docs/architecture/mapped-organize.md @@ -99,11 +99,54 @@ offers as opt-in: `IncludeKeptOnDesktopItems`, one call in `MappedOrganizeReorganizePolicy.SelectKeptOptIns`, once per preview so a refresh does not re-tick what the user unticked). Confirming maps them and clears the mark (`ApplyGroupsAsync`); unticked entries stay kept. Entry -points: 「重新整理桌面」 in a mapped widget's blank-area menu and in the +points: 「整理预览…」 in a mapped widget's blank-area menu, in the title-bar 「…」 menu of a mapped widget or of a tab group holding one (`ContentWidgetWindow.MappedOrganize.cs`, one call in `CreateMoreFlyout`; -`MappedOrganizeReorganizePolicy.ShouldOfferReorganize`). Both open the -organize window (an already open window keeps its preview; 刷新 rescans). +`MappedOrganizeReorganizePolicy.ShouldOfferReorganize`) and in the tray menu. +The one-click organize below includes 「放回桌面」 entries without a preview. + +### 一键整理桌面 (one click, replaces opening the preview) + +「整理桌面」 finishes in one click; the preview with its 待整理 / 留在桌面 split +is no longer the default. Entries that now run `ForkOneClickOrganizer` +(`Services/ForkOneClickOrganize.cs`, host glue `App.ForkOneClickOrganize.cs`): +the tray 「整理桌面…」 (`OpenDesktopOrganizationFromTray`), the settings +buttons 「一键整理桌面」 (桌面整理) and 「整理桌面」 (文件格子) through +`InProcessSettingsAppActions.ShowDesktopOrganizationWindow` (IPC unchanged), +the mapped widget's blank-area 「一键整理」 and the title-bar 「…」 +「一键整理桌面」 (formerly 「重新整理桌面」). + +* 移动到格子: the preview's untouched default plan is executed + (`BuildPlanAsync` → `CreateExecutionPlan(plan, [])` → `ExecuteAsync`), so + history, 撤销 and recovery are the same; opt-in kinds (folders, large files) + stay on the desktop as in the preview. +* 只映射: every 「放回桌面」 mark is cleared first + (`ReleaseAllKeptOnDesktop`), the plan includes all opt-in kinds (nothing + moves), entries go to the mapped widget of their own category when one + exists, otherwise to the planner's bucket + (`ForkOneClickOrganizePolicy.BuildMappedGroups`), then 「一键整理」 routing + sweeps the rest. +* Result: a notification (with 撤销 when files were moved). A pending + interrupted organize, an open preview or a host that is not ready opens the + preview instead. +* The preview stays reachable as 「整理预览…」 (tray menu, mapped widget + blank-area menu, title-bar 「…」 menu). +* Automatic sorting of new files still skips 「放回桌面」 entries. + +### Same category → same widget (duplicate 「其他」 fix) + +Cause: a widget created by an earlier organize gets a rule for the +categories it received (e.g. 「其他」 = [Other]). A category with a single +item (e.g. one video, Media) is merged into the 「其他」 bucket by +`MergeSmallAndOverflowCategories`; that item matches no rule, so the planner +proposed a second, new 「其他」. `DesktopOrganizationCategoryReuse` (one call in +`DesktopOrganizationPlanner.CreatePlan`) now lets a bucket join the widget of +an enabled rule listing its category (unless the rule excludes one of the +bucket's extensions), else a widget whose name equals the bucket's name. +Mapped groups likewise join an existing mapped widget by category, else by +name (`ForkOneClickOrganizePolicy.FindMappedTarget` in `ApplyGroupsAsync`). +Limit: in 只映射 mode a real-folder (moved-files) widget named 「其他」 can't +receive mapped entries, so it still sits next to the mapped 「其他」. ### 拖到桌面 = 放回桌面 @@ -164,6 +207,12 @@ topology profiles and wake recovery apply unchanged. * `ContentWidgetWindow.Commands.cs`: one `AppendMappedOrganizeMoreMenuItems` call in `CreateMoreFlyout`; `DesktopOrganizationTaskView.xaml.cs`: one `IncludeKeptOnDesktopItems` call in `ScanAsync` (重新整理桌面). +* `App.Tray.cs`: `OpenDesktopOrganizationFromTray` runs the one-click organize, + one `CreateForkOrganizePreviewTrayItem` line (整理预览…). +* `Services/InProcessSettingsAppActions.cs`: `ShowDesktopOrganizationWindow` + → `OrganizeDesktopOneClick` (one click from the settings buttons). +* `DesktopOrganizationPlanner.cs`: one `DesktopOrganizationCategoryReuse` block + in `CreatePlan` (no duplicate same-category widget). * `FileService.cs`: DeskBox-hidden members stay displayable (3 conditions). * `DesktopAutoOrganizationWatcher.cs`: 只映射 hand-off (one block). * `DesktopOrganizationSettingsSection.xaml`: one host panel for the mode card. @@ -175,6 +224,8 @@ topology profiles and wake recovery apply unchanged. * Manual mode: new desktop files stay unassigned (visible on the desktop) until 「一键整理」. +* The tray item keeps the upstream text 「整理桌面…」 (upstream string; its + ellipsis is now slightly misleading). * Public Desktop entries need admin rights to change attributes; when that fails they stay visible on the desktop as well as in the widget. * Hidden entries are also hidden in File Explorer's Desktop folder view. diff --git a/src/DeskBox/App.ForkOneClickOrganize.cs b/src/DeskBox/App.ForkOneClickOrganize.cs new file mode 100644 index 000000000..b15f8b53d --- /dev/null +++ b/src/DeskBox/App.ForkOneClickOrganize.cs @@ -0,0 +1,199 @@ +using DeskBox.Services; +using H.NotifyIcon.Core; +using Microsoft.UI.Xaml.Controls; + +namespace DeskBox; + +/// +/// GOXF fork: 「整理桌面」 finishes in one click. The tray item, the settings +/// buttons (一键整理桌面 / 整理桌面, via ISettingsAppActions) and the mapped +/// widgets' menus run directly and report +/// with a notification (with 撤销 when files were moved); the old preview +/// window stays available as 「整理预览…」 in the tray menu and the mapped +/// widgets' menus. +/// +public partial class App +{ + private int _forkOneClickOrganizeRunning; + + /// One-click organize (fire and forget; safe from any thread). + public void OrganizeDesktopOneClick(IntPtr ownerHwnd = default) + { + if (UiDispatcherQueue is { HasThreadAccess: false } dispatcherQueue) + { + dispatcherQueue.TryEnqueue(() => OrganizeDesktopOneClick(ownerHwnd)); + return; + } + + _ = OrganizeDesktopOneClickAsync(ownerHwnd); + } + + /// The previous behavior of 「整理桌面」: the organize preview window. + public void OpenDesktopOrganizationPreview(IntPtr ownerHwnd = default) + { + try + { + CancelBackgroundMemoryCleanup(); + ShowDesktopOrganizationWindow(ownerHwnd); + } + catch (Exception ex) + { + Log($"[OneClickOrganize] Opening the organize preview failed: {ex.Message}"); + } + } + + private async Task OrganizeDesktopOneClickAsync(IntPtr ownerHwnd) + { + if (Interlocked.Exchange(ref _forkOneClickOrganizeRunning, 1) == 1) + { + Log("[OneClickOrganize] Already running; ignored."); + return; + } + + try + { + CancelBackgroundMemoryCleanup(); + if (WidgetManager is not { } widgetManager || _desktopOrganizationWindow is not null) + { + // Not ready yet, or a preview is open: finish in the preview. + OpenDesktopOrganizationPreview(ownerHwnd); + return; + } + + var coordinator = new DesktopOrganizationCoordinator( + SettingsService, + FileService, + widgetManager, + OrganizerService, + LocalizationService); + var organizer = new ForkOneClickOrganizer(coordinator, MappedOrganizeService.Current, ResolveForkCategoryName); + ForkOneClickOrganizeResult result = await organizer.RunAsync(ownerHwnd); + Log($"[OneClickOrganize] mode={result.Mode} outcome={result.Outcome} organized={result.OrganizedCount} retained={result.RetainedCount}"); + if (result.Outcome == ForkOneClickOrganizeOutcome.NeedsPreview) + { + OpenDesktopOrganizationPreview(ownerHwnd); + return; + } + + ShowForkOneClickOrganizeNotification(result); + if (result.Outcome == ForkOneClickOrganizeOutcome.Organized) + { + _settingsWindow?.RefreshDesktopOrganizationState(); + _ = PushSettingsIpcEventAsync(SettingsIpcMethods.HostDesktopOrgRefresh, null); + } + } + catch (Exception ex) + { + Log($"[OneClickOrganize] Failed: {ex}"); + ShowForkOrganizeNotice( + ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.OneClickFailedTitle), + ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.OneClickFailedBody), + historyId: null); + } + finally + { + Interlocked.Exchange(ref _forkOneClickOrganizeRunning, 0); + ScheduleLightMemoryCleanup(completedHeavyOperation: true); + } + } + + private string ResolveForkCategoryName(string categoryId) + { + string key = $"DesktopOrganization.Category.{categoryId}"; + string localized = LocalizationService.T(key); + return string.IsNullOrWhiteSpace(localized) || string.Equals(localized, key, StringComparison.Ordinal) + ? categoryId + : localized; + } + + private void ShowForkOneClickOrganizeNotification(ForkOneClickOrganizeResult result) + { + if (result.Outcome == ForkOneClickOrganizeOutcome.NothingToOrganize) + { + ShowForkOrganizeNotice( + ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.OneClickNothingTitle), + ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.OneClickNothingBody), + historyId: null); + return; + } + + string separator = LocalizationService.CurrentCultureName.StartsWith("zh", StringComparison.OrdinalIgnoreCase) ? "、" : ", "; + string targets = string.Join(separator, (result.TargetNames ?? []).Take(4)); + string body = result.RetainedCount > 0 + ? ForkOrganizeModeText.Format(ForkOrganizeModeText.Key.OneClickPartialFormat, result.OrganizedCount, result.RetainedCount) + : ForkOrganizeModeText.Format(ForkOrganizeModeText.Key.OneClickDoneFormat, result.OrganizedCount, + targets.Length > 0 ? targets : ForkOrganizeModeText.ModeName(result.Mode)); + ShowForkOrganizeNotice( + ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.OneClickDoneTitle), + body, + result.UndoHistoryId); + } + + private void ShowForkOrganizeNotice(string title, string message, string? historyId) + { + if (IsShuttingDown) + { + return; + } + + var arguments = new Dictionary { ["type"] = "desktop-organization" }; + var actions = new List(); + if (!string.IsNullOrWhiteSpace(historyId)) + { + arguments["historyId"] = historyId; + actions.Add(new NativeAppNotificationAction( + LocalizationService.T("DesktopOrganization.Notification.Undo"), + new Dictionary + { + ["type"] = "desktop-organization", + ["action"] = "undo", + ["historyId"] = historyId + })); + } + + if (_nativeNotificationService?.TryShow( + title, + message, + arguments, + actions.Count > 0 ? actions : null, + options: new NativeAppNotificationOptions( + Tag: "fork-one-click-organize", + Group: DesktopOrganizationNotificationGroup)) == true) + { + return; + } + + try + { + _trayIcon?.ShowNotification( + title, + message, + NotificationIcon.Info, + customIconHandle: null, + largeIcon: true, + sound: false, + respectQuietTime: true, + realtime: false, + timeout: TimeSpan.FromSeconds(6)); + } + catch (Exception ex) + { + Log($"[OneClickOrganize] Tray notification failed: {ex.Message}"); + } + } + + /// Tray: 「整理预览…」 right below 「整理桌面…」 (which is one click now). + private MenuFlyoutItem CreateForkOrganizePreviewTrayItem(MenuFlyout contextMenu) + { + var item = new MenuFlyoutItem + { + Text = ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.MenuOrganizePreview), + Width = TrayMenuItemWidth, + Icon = new FontIcon { Glyph = "\uE8A1" } + }; + AttachTrayMenuItemInteraction( + item, + () => RunTraySettingsActionAsync(contextMenu, () => OpenDesktopOrganizationPreview())); + return item; + } +} diff --git a/src/DeskBox/App.Tray.cs b/src/DeskBox/App.Tray.cs index bdcb6af4e..d5b856d77 100644 --- a/src/DeskBox/App.Tray.cs +++ b/src/DeskBox/App.Tray.cs @@ -115,6 +115,7 @@ private void CreateTrayIcon() _trayCreateWidgetItems.Clear(); contextMenu.Items.Add(organizeDesktopItem); + contextMenu.Items.Add(CreateForkOrganizePreviewTrayItem(contextMenu)); // GOXF fork: 「整理预览…」 contextMenu.Items.Add(new MenuFlyoutSeparator()); foreach (var descriptor in new WidgetContentFactory(LocalizationService).GetCreateEntryDescriptors()) { @@ -1501,7 +1502,7 @@ private void OpenFeatureWidgetsFromTray() private void OpenDesktopOrganizationFromTray() { CancelBackgroundMemoryCleanup(); - ShowDesktopOrganizationWindow(); + OrganizeDesktopOneClick(); // GOXF fork: one click; the preview is 「整理预览…」 } private void OpenAboutSettingsFromTray() diff --git a/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs b/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs index 2427b9cbf..fef40009d 100644 --- a/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs +++ b/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs @@ -18,7 +18,7 @@ public sealed partial class DesktopOrganizationTaskView private readonly HashSet _keptOnDesktopOptInsApplied = new(StringComparer.OrdinalIgnoreCase); /// - /// 「重新整理桌面」: in 「只映射」 mode, entries put back on the desktop are + /// 「整理预览…」: in 「只映射」 mode, entries put back on the desktop are /// sorted by the normal rules and start ticked, including the kinds the /// scanner only offers as opt-in (folders, large files). Confirming maps /// them and clears the 「放回桌面」 mark; unticking keeps it. diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs index 02ac3179f..09a8874cb 100644 --- a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs +++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs @@ -36,19 +36,41 @@ private bool TryKeepMappedItemsOnDesktop(IReadOnlyList items) return true; } - /// 「重新整理桌面」: opens the organize preview (放回桌面 items included, see MappedOrganizeReorganizePolicy). - internal static void OpenMappedReorganizePreview() + /// + /// 「一键整理」 (blank menu) and 「一键整理桌面」 (title 「…」 menu): organize the + /// whole desktop in one click by the global 「整理方式」, 「放回桌面」 entries + /// included (see ForkOneClickOrganizer). + /// + internal static void RunOneClickOrganize() { try { - App.Current.ShowDesktopOrganizationWindow(); + App.Current.OrganizeDesktopOneClick(); } catch (Exception ex) { - App.Log($"[MappedOrganize] Opening the organize preview failed: {ex.Message}"); + App.Log($"[MappedOrganize] One-click organize failed to start: {ex.Message}"); } } + /// 「整理预览…」: the old organize preview window, kept as a secondary entry. + internal static void OpenOrganizePreview() => App.Current.OpenDesktopOrganizationPreview(); + + internal static MenuFlyoutItem CreateOrganizePreviewMenuItem(MenuFlyout flyout) + { + var preview = new MenuFlyoutItem + { + Text = ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.MenuOrganizePreview), + Icon = new FontIcon { Glyph = "\uE8A1" } + }; + preview.Click += (_, _) => + { + flyout.Hide(); + OpenOrganizePreview(); + }; + return preview; + } + private void AddMappedOrganizeMenuItems(MenuFlyout flyout) { if (!ViewModel.IsMappedOrganizeWidget || MappedOrganizeService.Current is not { } service) @@ -59,24 +81,13 @@ private void AddMappedOrganizeMenuItems(MenuFlyout flyout) flyout.Items.Add(new MenuFlyoutSeparator()); MenuFlyoutItem organizeNow = CreateMenuItem("MappedOrganize.Menu.OrganizeNow", "\uE8CB"); - organizeNow.Click += async (_, _) => + organizeNow.Click += (_, _) => { flyout.Hide(); - await RunAsync(() => service.OrganizeNowAsync()); + RunOneClickOrganize(); }; flyout.Items.Add(organizeNow); - - var reorganize = new MenuFlyoutItem - { - Text = ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.MenuReorganizeDesktop), - Icon = new FontIcon { Glyph = "\uE8B1" } - }; - reorganize.Click += (_, _) => - { - flyout.Hide(); - OpenMappedReorganizePreview(); - }; - flyout.Items.Add(reorganize); + flyout.Items.Add(CreateOrganizePreviewMenuItem(flyout)); var autoAssign = new ToggleMenuFlyoutItem { diff --git a/src/DeskBox/Services/DesktopOrganizationCategoryReuse.cs b/src/DeskBox/Services/DesktopOrganizationCategoryReuse.cs new file mode 100644 index 000000000..c7aa97e3b --- /dev/null +++ b/src/DeskBox/Services/DesktopOrganizationCategoryReuse.cs @@ -0,0 +1,80 @@ +using DeskBox.Models; + +namespace DeskBox.Services; + +/// +/// GOXF fork: before the planner proposes a NEW widget for a category bucket, +/// it looks for an existing widget that already stands for that category, so +/// one category never ends up in two same-named widgets (e.g. two 「其他」). +/// +/// Why it happened: a widget created by an earlier organize gets a rule for +/// the categories it received (say [Other]). Later, a category with a single +/// item (say one video, Media) is merged into the 「其他」 bucket by +/// ; the Media item matches no rule, +/// so the planner proposed a second, new 「其他」 widget next to the existing +/// one that holds the folders. +/// +/// A bucket reuses, in order: the widget of an enabled rule that lists the +/// bucket's category (unless the rule excludes one of the bucket's +/// extensions), then a widget whose name equals the bucket's display name. +/// Only widgets the rule resolver could target qualify (file widgets with a +/// folder, not disabled, not mapped-organize). Pure; unit-tested. +/// +public static class DesktopOrganizationCategoryReuse +{ + public static WidgetConfig? FindExistingWidget( + string categoryId, + string displayName, + IEnumerable bucketExtensions, + IReadOnlyCollection widgets, + IReadOnlyCollection rules) + { + if (string.IsNullOrWhiteSpace(categoryId) || widgets is null || widgets.Count == 0) + { + return null; + } + + var eligible = widgets + .Where(IsEligibleTarget) + .ToDictionary(widget => widget.Id, StringComparer.Ordinal); + if (eligible.Count == 0) + { + return null; + } + + var extensions = (bucketExtensions ?? []) + .Select(DesktopOrganizationClassifier.NormalizeExtension) + .Where(extension => !string.IsNullOrEmpty(extension)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + WidgetConfig? byRule = (rules ?? []) + .Where(rule => + rule is not null && + rule.IsEnabled && + eligible.ContainsKey(rule.TargetWidgetId ?? string.Empty) && + rule.CategoryIds.Contains(categoryId, StringComparer.Ordinal) && + !rule.ExcludedExtensions + .Select(DesktopOrganizationClassifier.NormalizeExtension) + .Any(extensions.Contains)) + .OrderBy(rule => rule.Id, StringComparer.Ordinal) + .Select(rule => eligible[rule.TargetWidgetId]) + .FirstOrDefault(); + if (byRule is not null) + { + return byRule; + } + + string name = displayName?.Trim() ?? string.Empty; + return name.Length == 0 + ? null + : eligible.Values.FirstOrDefault(widget => + string.Equals(widget.Name?.Trim(), name, StringComparison.OrdinalIgnoreCase)); + } + + private static bool IsEligibleTarget(WidgetConfig? widget) => + widget is not null && + widget.WidgetKind == WidgetKind.File && + !widget.IsDisabled && + !string.IsNullOrWhiteSpace(widget.MappedFolderPath) && + !MappedOrganizeWidgetMetadata.IsMappedOrganize(widget); +} diff --git a/src/DeskBox/Services/DesktopOrganizationPlanner.cs b/src/DeskBox/Services/DesktopOrganizationPlanner.cs index 07d958bfe..317e5a847 100644 --- a/src/DeskBox/Services/DesktopOrganizationPlanner.cs +++ b/src/DeskBox/Services/DesktopOrganizationPlanner.cs @@ -83,6 +83,19 @@ public DesktopOrganizationPlan CreatePlan( } string displayName = categoryDisplayNameResolver(categoryId); + // GOXF fork: a bucket whose category (or name) already has a widget joins it instead of a second one. + if (DesktopOrganizationCategoryReuse.FindExistingWidget(categoryId, displayName, items.Select(item => item.Extension), widgets, rules) is { } reuse) + { + if (!targets.TryGetValue(reuse.Id, out MutableTarget? reused)) + { + reused = new MutableTarget(reuse.Id, categoryId, reuse.Id, reuse.Name, Path.GetFullPath(reuse.MappedFolderPath!), createsWidget: false); + targets.Add(reuse.Id, reused); + } + + reused.Items.AddRange(items); + continue; + } + string directory = FileService.GetAvailablePath( Path.Combine(normalizedRoot, SanitizeFolderName(displayName)), reservedDirectories); diff --git a/src/DeskBox/Services/ForkOneClickOrganize.cs b/src/DeskBox/Services/ForkOneClickOrganize.cs new file mode 100644 index 000000000..bca975d41 --- /dev/null +++ b/src/DeskBox/Services/ForkOneClickOrganize.cs @@ -0,0 +1,229 @@ +using DeskBox.Models; + +namespace DeskBox.Services; + +public enum ForkOneClickOrganizeOutcome +{ + Organized, + NothingToOrganize, + + /// The preview has to take over (an interrupted organize must be recovered there first, or the mapped service is not up yet). + NeedsPreview, +} + +public sealed record ForkOneClickOrganizeResult( + ForkOneClickOrganizeOutcome Outcome, + DesktopOrganizeMode Mode, + int OrganizedCount = 0, + int RetainedCount = 0, + string? UndoHistoryId = null, + IReadOnlyList? TargetNames = null); + +/// +/// GOXF fork: 「整理桌面」 in one click. The desktop / tray / settings entries no +/// longer open the preview with its 待整理 / 留在桌面 split; they organize right +/// away by the global 「整理方式」 (fork-organize.json): +/// +/// 移动到格子: the preview's default plan (same rules, same defaults, +/// same transaction, history and undo) is executed directly. +/// 只映射: every visible desktop entry is mapped, folders / large files +/// included (nothing is moved), and 「放回桌面」 marks are cleared first, so +/// put-back entries are organized too. Entries go to the mapped widget of +/// their own category when one exists, otherwise to the planner's bucket; +/// an existing mapped widget of the same category or name is always reused. +/// +/// The old preview stays reachable (「整理预览…」 in the tray menu and the +/// mapped widgets' menus). Automatic sorting of new files still respects +/// 「放回桌面」. +/// +public sealed class ForkOneClickOrganizer +{ + private readonly DesktopOrganizationCoordinator _coordinator; + private readonly MappedOrganizeService? _mapped; + private readonly Func _categoryName; + + public ForkOneClickOrganizer( + DesktopOrganizationCoordinator coordinator, + MappedOrganizeService? mapped, + Func categoryName) + { + _coordinator = coordinator; + _mapped = mapped; + _categoryName = categoryName; + } + + public async Task RunAsync( + IntPtr ownerWindowHandle = default, + CancellationToken cancellationToken = default) + { + DesktopOrganizeMode mode = ForkOrganizeModeSettings.Load(); + if (_coordinator.HasPendingRecovery) + { + return new ForkOneClickOrganizeResult(ForkOneClickOrganizeOutcome.NeedsPreview, mode); + } + + if (ForkOrganizeModePolicy.ConfirmMapsInsteadOfMoving(mode)) + { + return _mapped is null + ? new ForkOneClickOrganizeResult(ForkOneClickOrganizeOutcome.NeedsPreview, mode) + : await RunMappedAsync(_mapped, mode, cancellationToken); + } + + return await RunMoveAsync(mode, ownerWindowHandle, cancellationToken); + } + + private async Task RunMoveAsync( + DesktopOrganizeMode mode, + IntPtr ownerWindowHandle, + CancellationToken cancellationToken) + { + DesktopOrganizationPlan preview = await _coordinator.BuildPlanAsync(false, cancellationToken); + if (preview.EligibleItemCount == 0) + { + return new ForkOneClickOrganizeResult(ForkOneClickOrganizeOutcome.NothingToOrganize, mode); + } + + // No selections: every bucket ticked, default destinations — exactly + // what 「开始整理」 does on an untouched preview. + DesktopOrganizationPlan plan = _coordinator.CreateExecutionPlan(preview, []); + if (plan.EligibleItemCount == 0) + { + return new ForkOneClickOrganizeResult(ForkOneClickOrganizeOutcome.NothingToOrganize, mode); + } + + DesktopOrganizationExecutionResult result = + await _coordinator.ExecuteAsync(plan, progress: null, cancellationToken, ownerWindowHandle); + return new ForkOneClickOrganizeResult( + ForkOneClickOrganizeOutcome.Organized, + mode, + result.CompletedItems.Count, + result.RetainedItems.Count, + result.History.CanUndo ? result.History.Id : null, + plan.Targets.Select(target => target.SuggestedDisplayName) + .Where(name => !string.IsNullOrWhiteSpace(name)) + .Distinct(StringComparer.CurrentCultureIgnoreCase) + .ToList()); + } + + private async Task RunMappedAsync( + MappedOrganizeService mapped, + DesktopOrganizeMode mode, + CancellationToken cancellationToken) + { + mapped.ReleaseAllKeptOnDesktop(); + DesktopOrganizationPlan scanned = await _coordinator.BuildPlanAsync(includeSlowItems: true, cancellationToken); + IReadOnlyList optIns = ForkOneClickOrganizePolicy.SelectOptIns(scanned.SourceItems); + DesktopOrganizationPlan plan = optIns.Count > 0 + ? _coordinator.CreatePreviewPlanWithOptionalItems(scanned, optIns) + : scanned; + IReadOnlyList groups = ForkOneClickOrganizePolicy.BuildMappedGroups( + plan.Targets, + mapped.MappedCategoryIds(), + _categoryName); + + int count = groups.Count > 0 ? await mapped.ApplyGroupsAsync(groups) : 0; + // Whatever the plan did not list (public desktop, overflow) follows + // the same routing as 「一键整理」, also with automatic sorting off. + count += await mapped.OrganizeNowAsync(); + return count > 0 + ? new ForkOneClickOrganizeResult( + ForkOneClickOrganizeOutcome.Organized, + mode, + count, + TargetNames: groups.Select(group => group.DisplayName).ToList()) + : new ForkOneClickOrganizeResult(ForkOneClickOrganizeOutcome.NothingToOrganize, mode); + } +} + +/// Pure decisions of the one-click organize (unit-tested in ForkOneClickOrganizeTests). +public static class ForkOneClickOrganizePolicy +{ + /// In 「只映射」 nothing is moved, so the opt-in kinds (folders, large files, batch overflow) are organized too. + public static IReadOnlyList SelectOptIns(IEnumerable? items) => + (items ?? []) + .Where(item => item.CanOptIn && !string.IsNullOrWhiteSpace(item.SourcePath)) + .Select(item => item.SourcePath) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + /// + /// Turns planner buckets into mapped groups. An entry whose own category + /// already has a mapped widget goes there (a lone new .png joins 「图片」 + /// instead of being merged into 「其他」); otherwise it follows its bucket. + /// One group per category, in first-seen order. + /// + public static IReadOnlyList BuildMappedGroups( + IEnumerable? targets, + IReadOnlyCollection? mappedCategoryIds, + Func categoryName) + { + var mapped = new HashSet(mappedCategoryIds ?? [], StringComparer.Ordinal); + var order = new List(); + var paths = new Dictionary>(StringComparer.Ordinal); + var bounds = new Dictionary(StringComparer.Ordinal); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (DesktopOrganizationTargetPlan target in targets ?? []) + { + foreach (DesktopOrganizationFileSnapshot item in target.Items) + { + if (string.IsNullOrWhiteSpace(item.SourcePath) || !seen.Add(item.SourcePath)) + { + continue; + } + + string categoryId = mapped.Contains(item.CategoryId) ? item.CategoryId : target.CategoryId; + if (string.IsNullOrWhiteSpace(categoryId)) + { + categoryId = DesktopOrganizationCategoryIds.Other; + } + + if (!paths.TryGetValue(categoryId, out List? list)) + { + list = []; + paths.Add(categoryId, list); + order.Add(categoryId); + } + + if (!bounds.ContainsKey(categoryId) && + string.Equals(target.CategoryId, categoryId, StringComparison.Ordinal)) + { + bounds[categoryId] = target.PlannedBounds; + } + + list.Add(item.SourcePath); + } + } + + return order + .Select(categoryId => new MappedOrganizeGroup( + categoryId, + categoryName(categoryId), + bounds.TryGetValue(categoryId, out DesktopOrganizationRect? rect) ? rect : null, + paths[categoryId])) + .ToList(); + } + + /// + /// The mapped widget a group joins: same category first, then same name + /// (trimmed, case-insensitive). Null means a new mapped widget is needed. + /// + public static WidgetConfig? FindMappedTarget( + IEnumerable? mappedWidgets, + string categoryId, + string? displayName) + { + List widgets = (mappedWidgets ?? []).Where(widget => widget is not null).ToList(); + WidgetConfig? byCategory = widgets.FirstOrDefault(widget => string.Equals( + MappedOrganizeWidgetMetadata.GetCategory(widget), categoryId, StringComparison.Ordinal)); + if (byCategory is not null) + { + return byCategory; + } + + string name = displayName?.Trim() ?? string.Empty; + return name.Length == 0 + ? null + : widgets.FirstOrDefault(widget => + string.Equals(widget.Name?.Trim(), name, StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/src/DeskBox/Services/ForkOrganizeModeSettings.cs b/src/DeskBox/Services/ForkOrganizeModeSettings.cs index 45615cd06..33b563fb9 100644 --- a/src/DeskBox/Services/ForkOrganizeModeSettings.cs +++ b/src/DeskBox/Services/ForkOrganizeModeSettings.cs @@ -207,6 +207,14 @@ public enum Key MenuKeepOnDesktop, KeptOnDesktopFormat, MenuReorganizeDesktop, + MenuOrganizePreview, + OneClickDoneTitle, + OneClickDoneFormat, + OneClickPartialFormat, + OneClickNothingTitle, + OneClickNothingBody, + OneClickFailedTitle, + OneClickFailedBody, } /// UI-culture lookup lives in Helpers/ForkOrganizeModeText.Culture.cs (no App globals in Services). @@ -221,9 +229,9 @@ public static string Get(string? cultureName, Key key) { Key.SettingTitle => Pick("整理方式", "整理方式", "Organize mode"), Key.SettingDescription => Pick( - "「开始整理」和自动整理新文件按此方式执行。", - "「開始整理」和自動整理新檔案按此方式執行。", - "Used by Start organizing and by automatic organization of new files."), + "一键整理桌面、整理预览和自动整理新文件按此方式执行。", + "一鍵整理桌面、整理預覽和自動整理新檔案按此方式執行。", + "Used by Organize desktop, the organize preview and automatic organization of new files."), Key.OptionMove => Pick("移动到格子", "移動到格子", "Move into widgets"), Key.OptionMapOnly => Pick("只映射,不移动文件", "只映射,不移動檔案", "Map only, don't move files"), Key.MapOnlyNote => Pick( @@ -261,10 +269,30 @@ public static string Get(string? cultureName, Key key) "Start organizing only creates mapped widgets: files stay in the Desktop folder and mapped items are hidden on the desktop. Change it under Settings → Desktop organization → Organize mode."), Key.MenuKeepOnDesktop => Pick("放回桌面", "放回桌面", "Put back on desktop"), Key.KeptOnDesktopFormat => Pick( - "已将 {0} 个项目放回桌面,自动归类不会再收回它们;需要时可用「重新整理桌面」按规则重新整理。", - "已將 {0} 個項目放回桌面,自動歸類不會再收回它們;需要時可用「重新整理桌面」按規則重新整理。", - "Put {0} items back on the desktop. Automatic sorting leaves them there; use Reorganize desktop to sort them by the rules again."), - Key.MenuReorganizeDesktop => Pick("重新整理桌面", "重新整理桌面", "Reorganize desktop"), + "已将 {0} 个项目放回桌面,自动归类不会再收回它们;点「一键整理」会把它们一并整理进格子。", + "已將 {0} 個項目放回桌面,自動歸類不會再收回它們;點「一鍵整理」會把它們一併整理進格子。", + "Put {0} items back on the desktop. Automatic sorting leaves them there; Organize desktop sorts them into widgets again."), + Key.MenuReorganizeDesktop => Pick("一键整理桌面", "一鍵整理桌面", "Organize desktop"), + Key.MenuOrganizePreview => Pick("整理预览…", "整理預覽…", "Organize with preview…"), + Key.OneClickDoneTitle => Pick("桌面已整理", "桌面已整理", "Desktop organized"), + Key.OneClickDoneFormat => Pick( + "已整理 {0} 个项目({1})。", + "已整理 {0} 個項目({1})。", + "Organized {0} items ({1})."), + Key.OneClickPartialFormat => Pick( + "已整理 {0} 个项目,{1} 个项目未能整理(可在「整理预览…」中查看)。", + "已整理 {0} 個項目,{1} 個項目未能整理(可在「整理預覽…」中查看)。", + "Organized {0} items; {1} items couldn't be organized (see Organize with preview…)."), + Key.OneClickNothingTitle => Pick("桌面已经很整洁", "桌面已經很整潔", "Desktop is already tidy"), + Key.OneClickNothingBody => Pick( + "没有需要整理的项目。", + "沒有需要整理的項目。", + "There is nothing to organize."), + Key.OneClickFailedTitle => Pick("整理桌面失败", "整理桌面失敗", "Couldn't organize the desktop"), + Key.OneClickFailedBody => Pick( + "可以从托盘菜单「整理预览…」打开预览重试。", + "可以從系統匣選單「整理預覽…」開啟預覽重試。", + "Open Organize with preview… from the tray menu to try again."), _ => key.ToString(), }; } diff --git a/src/DeskBox/Services/InProcessSettingsAppActions.cs b/src/DeskBox/Services/InProcessSettingsAppActions.cs index 993da72fc..938721caa 100644 --- a/src/DeskBox/Services/InProcessSettingsAppActions.cs +++ b/src/DeskBox/Services/InProcessSettingsAppActions.cs @@ -51,8 +51,9 @@ public bool TryRelaunchAsExplorerUser(string arguments) => public void ShowOnboarding(bool resumeProgress = false) => _app.ShowOnboarding(resumeProgress); + // GOXF fork: the settings 「一键整理桌面」 / 「整理桌面」 buttons organize in one click. public void ShowDesktopOrganizationWindow(nint ownerWindowHandle = 0) => - _app.ShowDesktopOrganizationWindow((IntPtr)ownerWindowHandle); + _app.OrganizeDesktopOneClick((IntPtr)ownerWindowHandle); public void OpenReleaseNotesWindow( AppUpdateManifest? manifest, diff --git a/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs b/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs index 99f5c1a7e..83360326a 100644 --- a/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs +++ b/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs @@ -3,10 +3,10 @@ namespace DeskBox.Services; /// -/// GOXF fork, 「映射整理」 → 「重新整理桌面」: entries put back on the desktop +/// GOXF fork, 「映射整理」 → 「整理预览…」: entries put back on the desktop /// (「放回桌面」, see ) are skipped by -/// automatic sorting of new files and by the mapped widget's quick -/// 「一键整理」, but the organize preview treats them like any other desktop +/// automatic sorting of new files (the one-click 「一键整理」 clears the marks +/// and organizes them, see ForkOneClickOrganizer), and the organize preview treats them like any other desktop /// entry: sorted into their category by the normal rules and selected by /// default; confirming maps them and clears the mark /// (), unticking keeps it. @@ -60,7 +60,7 @@ public static IReadOnlyList SelectKeptOptIns( } /// - /// Whether a widget's menus offer 「重新整理桌面」: the widget is a mapped + /// Whether a widget's menus offer 「一键整理桌面」 / 「整理预览…」: the widget is a mapped /// widget, or it is a member of a tab group that holds one. /// public static bool ShouldOfferReorganize( diff --git a/src/DeskBox/Services/MappedOrganizeService.Visibility.cs b/src/DeskBox/Services/MappedOrganizeService.Visibility.cs index 927169267..373cb31ae 100644 --- a/src/DeskBox/Services/MappedOrganizeService.Visibility.cs +++ b/src/DeskBox/Services/MappedOrganizeService.Visibility.cs @@ -1,3 +1,5 @@ +using DeskBox.Models; + namespace DeskBox.Services; /// @@ -16,6 +18,29 @@ public sealed partial class MappedOrganizeService /// Entries currently marked 「放回桌面」 (copy; UI thread). public IReadOnlyCollection KeptOnDesktopSnapshot() => _keptOnDesktop.ToArray(); + /// + /// One-click 「整理桌面」: clears every 「放回桌面」 mark so those entries are + /// organized like any other desktop entry. Returns how many were cleared. + /// + public int ReleaseAllKeptOnDesktop() + { + int count = _keptOnDesktop.Count; + if (count > 0) + { + _keptOnDesktop.Clear(); + SaveKeptOnDesktop(); + App.Log($"[MappedOrganize] One-click organize released {count} kept-on-desktop entries."); + } + + return count; + } + + /// Categories that already have a (live) mapped widget. + public IReadOnlyCollection MappedCategoryIds() => + LiveMappedWidgets() + .Select(MappedOrganizeWidgetMetadata.GetCategory) + .ToHashSet(StringComparer.Ordinal); + /// The organize mode the main process last applied. public DesktopOrganizeMode Mode => _mode; diff --git a/src/DeskBox/Services/MappedOrganizeService.cs b/src/DeskBox/Services/MappedOrganizeService.cs index b575117dc..6b52d66bd 100644 --- a/src/DeskBox/Services/MappedOrganizeService.cs +++ b/src/DeskBox/Services/MappedOrganizeService.cs @@ -223,8 +223,9 @@ public async Task ApplyGroupsAsync( 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)); + // Same category, else same name: never a second mapped widget for one category. + WidgetConfig? target = ForkOneClickOrganizePolicy.FindMappedTarget( + LiveMappedWidgets(), group.CategoryId, group.DisplayName); if (target is null) { target = CreateMappedConfig(group.CategoryId, group.DisplayName); diff --git a/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs b/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs index 8a53ed24a..4f5b24492 100644 --- a/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs +++ b/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs @@ -6,9 +6,9 @@ namespace DeskBox.Views; /// /// GOXF fork, 「映射整理」: the title-bar 「…」 menu of a mapped widget — or of a -/// tab group holding one — offers 「重新整理桌面」, which opens the organize -/// preview where 「放回桌面」 items are sorted by the rules again -/// (). +/// tab group holding one — offers 「一键整理桌面」 (one click, 「放回桌面」 items +/// included, see ForkOneClickOrganizer) and 「整理预览…」 (the old preview). +/// Visibility: . /// public sealed partial class ContentWidgetWindow { @@ -33,10 +33,11 @@ private void AppendMappedOrganizeMoreMenuItems(MenuFlyout flyout) reorganize.Click += (_, _) => { flyout.Hide(); - FileSurfaceContent.OpenMappedReorganizePreview(); + FileSurfaceContent.RunOneClickOrganize(); }; flyout.Items.Add(new MenuFlyoutSeparator()); flyout.Items.Add(reorganize); + flyout.Items.Add(FileSurfaceContent.CreateOrganizePreviewMenuItem(flyout)); } catch (Exception ex) { diff --git a/tests/DeskBox.Tests/ForkOneClickOrganizeTests.cs b/tests/DeskBox.Tests/ForkOneClickOrganizeTests.cs new file mode 100644 index 000000000..5e9d9ded1 --- /dev/null +++ b/tests/DeskBox.Tests/ForkOneClickOrganizeTests.cs @@ -0,0 +1,212 @@ +using DeskBox.Models; +using DeskBox.Services; + +namespace DeskBox.Tests; + +/// GOXF fork: one-click 「整理桌面」 and the duplicate 「其他」 fix. +public sealed class ForkOneClickOrganizeTests +{ + private static readonly string Root = Path.Combine(Path.GetTempPath(), "deskbox-fork-one-click-tests"); + private static readonly string Desktop = Path.Combine(Root, "Desktop"); + + private static string D(string name) => Path.Combine(Desktop, name); + + private static DesktopOrganizationFileSnapshot Item( + string name, + string categoryId, + DesktopOrganizationExclusionReason reason = DesktopOrganizationExclusionReason.None, + bool isDirectory = false) => + new(D(name), name, DesktopOrganizationClassifier.NormalizeExtension(Path.GetExtension(name)), 1, + DateTime.UtcNow, categoryId, null, reason, isDirectory); + + private static WidgetConfig Folder(string id, string name) => + new() { Id = id, Name = name, WidgetKind = WidgetKind.File, MappedFolderPath = Path.Combine(Root, "storage", id) }; + + private static WidgetConfig Mapped(string id, string name, string categoryId) + { + var widget = new WidgetConfig { Id = id, Name = name, WidgetKind = WidgetKind.File, MappedFolderPath = Desktop }; + MappedOrganizeWidgetMetadata.Mark(widget, categoryId); + return widget; + } + + private static string Name(string categoryId) => categoryId switch + { + DesktopOrganizationCategoryIds.Other => "其他", + DesktopOrganizationCategoryIds.Images => "图片", + _ => categoryId, + }; + + private static DesktopOrganizationPlan Plan( + IReadOnlyCollection widgets, + IReadOnlyCollection rules, + params DesktopOrganizationFileSnapshot[] items) => + new DesktopOrganizationPlanner(new DesktopOrganizationRuleResolver()).CreatePlan( + new DesktopOrganizationScanResult { DesktopPath = Desktop, Items = items.ToList() }, + Path.Combine(Root, "storage"), + widgets, + rules, + Name); + + [Fact] + public void Planner_LoneItemMergedIntoOther_JoinsTheExistingOtherWidget() + { + // The reported case: an earlier organize created 「其他」 with a rule for + // [Other]; folders match it, a single video (Media) is merged into the + // 「其他」 bucket and used to produce a second, new 「其他」 card. + WidgetConfig other = Folder("other", "其他"); + var rule = new DesktopOrganizationRule { TargetWidgetId = "other", CategoryIds = [DesktopOrganizationCategoryIds.Other] }; + + DesktopOrganizationPlan plan = Plan([other], [rule], + Item("HarkHubGo-2.0.41.x", DesktopOrganizationCategoryIds.Other), + Item("notes.xyz", DesktopOrganizationCategoryIds.Other), + Item("video_2026-10-21.mp4", DesktopOrganizationCategoryIds.Media)); + + DesktopOrganizationTargetPlan target = Assert.Single(plan.Targets); + Assert.False(target.CreatesWidget); + Assert.Equal("other", target.TargetWidgetId); + Assert.Equal(3, target.Items.Count); + } + + [Fact] + public void Planner_OtherBucketWithoutRuleMatches_StillReusesTheRuleWidget() + { + WidgetConfig other = Folder("other", "Misc"); + var rule = new DesktopOrganizationRule { TargetWidgetId = "other", CategoryIds = [DesktopOrganizationCategoryIds.Other] }; + + DesktopOrganizationPlan plan = Plan([other], [rule], Item("clip.mp4", DesktopOrganizationCategoryIds.Media)); + + DesktopOrganizationTargetPlan target = Assert.Single(plan.Targets); + Assert.False(target.CreatesWidget); + Assert.Equal("other", target.TargetWidgetId); + } + + [Fact] + public void Planner_SameNamedWidget_IsReusedInsteadOfASecondOne() + { + WidgetConfig images = Folder("img", "图片"); + + DesktopOrganizationPlan plan = Plan([images], [], + Item("a.png", DesktopOrganizationCategoryIds.Images), + Item("b.png", DesktopOrganizationCategoryIds.Images)); + + DesktopOrganizationTargetPlan target = Assert.Single(plan.Targets); + Assert.Equal("img", target.TargetWidgetId); + Assert.False(target.CreatesWidget); + } + + [Fact] + public void CategoryReuse_RespectsExcludedExtensionsDisabledAndMappedWidgets() + { + WidgetConfig other = Folder("other", "Misc"); + var rule = new DesktopOrganizationRule + { + TargetWidgetId = "other", + CategoryIds = [DesktopOrganizationCategoryIds.Other], + ExcludedExtensions = [".mp4"] + }; + Assert.Null(DesktopOrganizationCategoryReuse.FindExistingWidget( + DesktopOrganizationCategoryIds.Other, "其他", [".mp4"], [other], [rule])); + Assert.Same(other, DesktopOrganizationCategoryReuse.FindExistingWidget( + DesktopOrganizationCategoryIds.Other, "其他", [".xyz"], [other], [rule])); + + WidgetConfig disabled = Folder("off", "其他"); + disabled.IsDisabled = true; + Assert.Null(DesktopOrganizationCategoryReuse.FindExistingWidget( + DesktopOrganizationCategoryIds.Other, "其他", [], [disabled], [])); + + // A mapped widget can't receive moved files. + Assert.Null(DesktopOrganizationCategoryReuse.FindExistingWidget( + DesktopOrganizationCategoryIds.Other, "其他", [], [Mapped("m", "其他", DesktopOrganizationCategoryIds.Other)], [])); + Assert.Null(DesktopOrganizationCategoryReuse.FindExistingWidget( + DesktopOrganizationCategoryIds.Other, "其他", [], [], [])); + } + + [Fact] + public void BuildMappedGroups_UsesOwnCategoryWidgetElseBucket_OneGroupPerCategory() + { + var targets = new List + { + new() + { + SourceBucketId = "category:Other", + CategoryId = DesktopOrganizationCategoryIds.Other, + Items = + [ + Item("lone.png", DesktopOrganizationCategoryIds.Images), // 图片 is mapped → joins it + Item("clip.mp4", DesktopOrganizationCategoryIds.Media), // no mapped 媒体 → stays in 其他 + Item("Folder", DesktopOrganizationCategoryIds.Other, DesktopOrganizationExclusionReason.None, isDirectory: true), + ] + }, + new() + { + SourceBucketId = "existing-real-other", + CategoryId = DesktopOrganizationCategoryIds.Other, + Items = [Item("x.dat", DesktopOrganizationCategoryIds.Other), Item("clip.mp4", DesktopOrganizationCategoryIds.Media)] + }, + }; + + IReadOnlyList groups = ForkOneClickOrganizePolicy.BuildMappedGroups( + targets, [DesktopOrganizationCategoryIds.Images], Name); + + Assert.Equal(2, groups.Count); + MappedOrganizeGroup other = Assert.Single(groups, group => group.CategoryId == DesktopOrganizationCategoryIds.Other); + Assert.Equal("其他", other.DisplayName); + Assert.Equal(new[] { D("clip.mp4"), D("Folder"), D("x.dat") }, other.Paths.ToArray()); + MappedOrganizeGroup images = Assert.Single(groups, group => group.CategoryId == DesktopOrganizationCategoryIds.Images); + Assert.Equal(new[] { D("lone.png") }, images.Paths.ToArray()); + Assert.Empty(ForkOneClickOrganizePolicy.BuildMappedGroups(null, null, Name)); + } + + [Fact] + public void FindMappedTarget_ByCategoryThenByName() + { + WidgetConfig images = Mapped("img", "图片", DesktopOrganizationCategoryIds.Images); + WidgetConfig renamedOther = Mapped("oth", " 其他 ", "Custom"); + + Assert.Same(images, ForkOneClickOrganizePolicy.FindMappedTarget([renamedOther, images], DesktopOrganizationCategoryIds.Images, "Pictures")); + Assert.Same(renamedOther, ForkOneClickOrganizePolicy.FindMappedTarget([images, renamedOther], DesktopOrganizationCategoryIds.Other, "其他")); + Assert.Null(ForkOneClickOrganizePolicy.FindMappedTarget([images], DesktopOrganizationCategoryIds.Documents, "文档")); + Assert.Null(ForkOneClickOrganizePolicy.FindMappedTarget(null, DesktopOrganizationCategoryIds.Other, null)); + } + + [Fact] + public void SelectOptIns_TakesFoldersLargeFilesAndOverflowOnly() + { + IReadOnlyList optIns = ForkOneClickOrganizePolicy.SelectOptIns( + [ + Item("Folder", DesktopOrganizationCategoryIds.Other, DesktopOrganizationExclusionReason.Folder, isDirectory: true), + Item("big.iso", DesktopOrganizationCategoryIds.Packages, DesktopOrganizationExclusionReason.SlowItem), + Item("more.png", DesktopOrganizationCategoryIds.Images, DesktopOrganizationExclusionReason.BatchLimit), + Item("hidden.txt", DesktopOrganizationCategoryIds.Documents, DesktopOrganizationExclusionReason.HiddenOrSystem), + Item("ok.png", DesktopOrganizationCategoryIds.Images), + ]); + + Assert.Equal(new[] { D("Folder"), D("big.iso"), D("more.png") }, optIns.ToArray()); + Assert.Empty(ForkOneClickOrganizePolicy.SelectOptIns(null)); + } + + [Fact] + public void Wiring_EntriesRunOneClickAndThePreviewStaysReachable() + { + string tray = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/App.Tray.cs")); + Assert.Contains("OrganizeDesktopOneClick();", tray, StringComparison.Ordinal); + Assert.Contains("CreateForkOrganizePreviewTrayItem(contextMenu)", tray, StringComparison.Ordinal); + + string settingsActions = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Services/InProcessSettingsAppActions.cs")); + Assert.Contains("_app.OrganizeDesktopOneClick(", settingsActions, StringComparison.Ordinal); + + string blankMenu = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs")); + Assert.Contains("RunOneClickOrganize();", blankMenu, StringComparison.Ordinal); + Assert.Contains("CreateOrganizePreviewMenuItem(flyout)", blankMenu, StringComparison.Ordinal); + + string titleMenu = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs")); + Assert.Contains("FileSurfaceContent.RunOneClickOrganize();", titleMenu, StringComparison.Ordinal); + Assert.Contains("FileSurfaceContent.CreateOrganizePreviewMenuItem(flyout)", titleMenu, StringComparison.Ordinal); + + string planner = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Services/DesktopOrganizationPlanner.cs")); + Assert.Contains("DesktopOrganizationCategoryReuse.FindExistingWidget(", planner, StringComparison.Ordinal); + + Assert.Equal("一键整理桌面", ForkOrganizeModeText.Get(LocalizationService.LanguageChinese, ForkOrganizeModeText.Key.MenuReorganizeDesktop)); + Assert.Equal("整理预览…", ForkOrganizeModeText.Get(LocalizationService.LanguageChinese, ForkOrganizeModeText.Key.MenuOrganizePreview)); + } +} diff --git a/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs b/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs index d70d2e86b..0fcc6d67c 100644 --- a/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs +++ b/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs @@ -107,10 +107,11 @@ public void Wiring_MenusAndPreviewHook() string titleMenu = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Views/ContentWidgetWindow.Commands.cs")); Assert.Contains("AppendMappedOrganizeMoreMenuItems(flyout);", titleMenu, StringComparison.Ordinal); - string blankMenu = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs")); - Assert.Contains("ForkOrganizeModeText.Key.MenuReorganizeDesktop", blankMenu, StringComparison.Ordinal); + // 「重新整理桌面」 became the one-click 「一键整理桌面」 (ForkOneClickOrganizeTests). + string titleMenuFork = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs")); + Assert.Contains("ForkOrganizeModeText.Key.MenuReorganizeDesktop", titleMenuFork, StringComparison.Ordinal); - Assert.Equal("重新整理桌面", ForkOrganizeModeText.Get(LocalizationService.LanguageChinese, ForkOrganizeModeText.Key.MenuReorganizeDesktop)); - Assert.Equal("Reorganize desktop", ForkOrganizeModeText.Get("en-US", ForkOrganizeModeText.Key.MenuReorganizeDesktop)); + Assert.Equal("一键整理桌面", ForkOrganizeModeText.Get(LocalizationService.LanguageChinese, ForkOrganizeModeText.Key.MenuReorganizeDesktop)); + Assert.Equal("Organize desktop", ForkOrganizeModeText.Get("en-US", ForkOrganizeModeText.Key.MenuReorganizeDesktop)); } }