diff --git a/docs/architecture/mapped-organize.md b/docs/architecture/mapped-organize.md index 3399645d9..5e2e3335c 100644 --- a/docs/architecture/mapped-organize.md +++ b/docs/architecture/mapped-organize.md @@ -82,11 +82,29 @@ Ordinary organization never targets mapped widgets: they are filtered out in The item menu row 「移回桌面」 reads 「放回桌面」 in mapped widgets and calls `MappedOrganizeService.KeepOnDesktop` (single and multi-select): membership removed, attribute restored, path recorded in `data/mapped-organize.kept` so -automatic sorting and 「一键整理」 skip it (follows renames, dropped on delete). +automatic sorting of new files and the mapped widget's quick 「一键整理」 skip +it (follows renames, dropped on delete). Dragging it into a mapped widget or confirming a preview that maps it clears the mark. Entries deselected in a confirmed mapped preview are kept the same way. 「退出映射整理」 clears the list. +### 重新整理桌面 + +「放回桌面」 entries are re-sorted by the organize preview, not put back where +they came from: in 「只映射」 mode the preview lists them like any other +desktop entry (sorted into their category by the normal rules, ticked by +default — including folders / large files, which the scanner otherwise only +offers as opt-in: `IncludeKeptOnDesktopItems`, one call in +`DesktopOrganizationTaskView.ScanAsync`, pure rule +`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 +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). + ### 拖到桌面 = 放回桌面 Dragging items out of a mapped widget and releasing them on the system desktop @@ -104,6 +122,25 @@ moved to the release point through the desktop's `IFolderView` centred on the cursor, the rest in a column; skipped when 自动排列图标 is on. Drops on other folders / widgets and move-mode widgets keep upstream behaviour. +Robustness (fix/mapped-drag-and-reorganize): the gesture is recorded at +`Items_DragStarting` (`BeginMappedDragTracking`, one call): mapped or not, +its paths, and a background `MappedDragReleaseTracker` that polls the +physical buttons (`GetAsyncKeyState`, 8 ms) and probes the desktop **at the +instant of release** (pure state machine `MappedDragReleaseTracking`). The +completion-time probe was unreliable: by then Explorer has processed the +drop, its desktop thread can be busy (the upstream LVM_HITTEST then times out +and "failed" was read as "on an icon"), and with 「显示隐藏的项目」 on, the +dragged item's own faded icon can sit under the cursor. The probe is now +three-state (`DesktopListViewProbeNativeMethods`: blank / icon + label / +failed); an icon only blocks when its label is not one of the dragged +entries, a failed hit test does not block (put-back paths are re-checked to +still exist). The decision runs once per gesture: from drag completion, or +from the release when WinUI reports completion before the release (stack +popover closing) or never (1.5 s grace). Every refusal logs +`[MappedOrganize] DragToDesktop skip reason= … target= icon= chain=`; +success logs `DragToDesktop put back`, the release `DragToDesktop released`, +the start `DragToDesktop tracking`. + ## Multi-monitor / sleep Mapped widgets are normal widgets, so the existing monitor binding, @@ -122,7 +159,11 @@ topology profiles and wake recovery apply unchanged. `FileSurfaceContent.SelectionAndMenus.cs` (blank menu call, item-menu localizer, 「放回桌面」 interception). * `FileSurfaceContent.xaml.cs`: one `TryPutBackMappedDragOnDesktop` call in - `CompleteDragItemsSession` (拖到桌面 = 放回桌面). + `CompleteDragItemsSession` and one `BeginMappedDragTracking` call in + `Items_DragStarting` (拖到桌面 = 放回桌面). +* `ContentWidgetWindow.Commands.cs`: one `AppendMappedOrganizeMoreMenuItems` + call in `CreateMoreFlyout`; `DesktopOrganizationTaskView.xaml.cs`: one + `IncludeKeptOnDesktopItems` call in `ScanAsync` (重新整理桌面). * `FileService.cs`: DeskBox-hidden members stay displayable (3 conditions). * `DesktopAutoOrganizationWatcher.cs`: 只映射 hand-off (one block). * `DesktopOrganizationSettingsSection.xaml`: one host panel for the mode card. @@ -145,7 +186,9 @@ topology profiles and wake recovery apply unchanged. attribute DeskBox set (NTFS carries it along); membership and the hidden ledger are cleaned up by the desktop watcher, but the file stays hidden at the destination. -* 拖到桌面 = 放回桌面: a drop onto an existing desktop icon is not treated as - put-back; icon placement needs 自动排列图标 off (网格对齐 still snaps it). +* 拖到桌面 = 放回桌面: a drop onto another desktop icon is not treated as + put-back (one whose label equals a dragged entry's name is); icon + placement needs 自动排列图标 off (网格对齐 still snaps it). Touch / pen + drags have no button to track and fall back to the completion-time probe. * Not runtime-verified on a real desktop in this change (CI builds and runs unit tests only). diff --git a/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs b/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs index 7a6463db7..2427b9cbf 100644 --- a/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs +++ b/src/DeskBox/Controls/DesktopOrganizationTaskView.MappedOrganize.cs @@ -15,6 +15,47 @@ namespace DeskBox.Controls; public sealed partial class DesktopOrganizationTaskView { private bool _organizeModeInitialized; + private readonly HashSet _keptOnDesktopOptInsApplied = new(StringComparer.OrdinalIgnoreCase); + + /// + /// 「重新整理桌面」: 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. + /// + private void IncludeKeptOnDesktopItems(DesktopOrganizationPlan scanned, bool freshPreview) + { + try + { + if (freshPreview) + { + _keptOnDesktopOptInsApplied.Clear(); + } + + if (MappedOrganizeService.Current is not { } service || + !ForkOrganizeModePolicy.ConfirmMapsInsteadOfMoving(ForkOrganizeModeSettings.Load())) + { + return; + } + + IReadOnlyCollection kept = service.KeptOnDesktopSnapshot(); + if (kept.Count == 0) + { + return; + } + + IReadOnlyList optIns = MappedOrganizeReorganizePolicy.SelectKeptOptIns( + scanned.SourceItems.Select(item => (item.SourcePath, item.CanOptIn)), + kept, + _keptOnDesktopOptInsApplied); + _optionalIncludedPaths.UnionWith(optIns); + App.Log($"[MappedOrganize] Preview: {kept.Count} kept-on-desktop entries, {optIns.Count} opted in."); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Preview could not include kept-on-desktop entries: {ex.Message}"); + } + } private void OrganizeModeLink_Loaded(object sender, RoutedEventArgs e) { diff --git a/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml.cs b/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml.cs index 5b70c81df..8d657230e 100644 --- a/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml.cs +++ b/src/DeskBox/Controls/DesktopOrganizationTaskView.xaml.cs @@ -105,6 +105,7 @@ private async Task ScanAsync(bool preserveSelection = false) var coordinator = Coordinator; DesktopOrganizationPlan scanned = await coordinator.BuildPlanAsync(false, cts.Token); if (cts.IsCancellationRequested || generation != _scanGeneration) return; + IncludeKeptOnDesktopItems(scanned, freshPreview: previous is null); // GOXF fork: 「放回桌面」 items are re-sorted by the preview. DesktopOrganizationPreviewReconciliation? changes = previous is null ? null : DesktopOrganizationPreviewReconciliation.Calculate(previous.SourceItems, scanned.SourceItems, _excludedSourcePaths, _optionalIncludedPaths, _newPaths); diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs index 5ee107ea2..fb61ebbd9 100644 --- a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs +++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs @@ -1,6 +1,8 @@ using DeskBox.Models; using DeskBox.Platform; using DeskBox.Services; +using Microsoft.UI.Dispatching; +using Windows.ApplicationModel.DataTransfer; namespace DeskBox.Controls.WidgetContents; @@ -9,63 +11,286 @@ namespace DeskBox.Controls.WidgetContents; /// them on the system desktop is 「放回桌面」. The items already live in the /// desktop folder, so for Explorer that drop is a same-folder move (nothing /// happens) and they would stay hidden and mapped; DeskBox recognises the -/// drop from the release point instead. Drops on a desktop icon, on other -/// folders, on other widgets, and every drag out of a move-mode widget keep -/// the upstream behaviour. +/// drop from the release point instead. Drops on another desktop icon, on +/// other folders, on other widgets, and every drag out of a move-mode widget +/// keep the upstream behaviour. +/// +/// The gesture is remembered when it starts (, +/// one call in Items_DragStarting): whether it came from a mapped widget, its +/// paths, and a background tracker that reads the release point the moment +/// the button goes up. The decision runs once per gesture, from drag +/// completion, or — when WinUI never reports the completion, or reports it +/// before the release (stack popover closing mid-drag) — from the release. +/// Every refusal is logged as [MappedOrganize] DragToDesktop skip reason=…. /// public sealed partial class FileSurfaceContent { - private const int VirtualKeyLeftButton = 0x01; - private const int VirtualKeyRightButton = 0x02; - private const int VirtualKeyEscape = 0x1B; + private const int MappedDragVirtualKeyLeftButton = 0x01; + private const int MappedDragVirtualKeyRightButton = 0x02; + private const int MappedDragVirtualKeyEscape = 0x1B; + private static readonly TimeSpan MappedDragCompletionGrace = TimeSpan.FromMilliseconds(1500); - /// Returns true when the completed drag was turned into 「放回桌面」. - private bool TryPutBackMappedDragOnDesktop(string[] draggedPaths, bool handledInternally) + private MappedDragSession? _mappedDrag; + + private sealed class MappedDragSession(string sessionId, string[] paths, MappedDragReleaseTracker tracker) + { + public string SessionId { get; } = sessionId; + + public string[] Paths { get; } = paths; + + public MappedDragReleaseTracker Tracker { get; } = tracker; + + public bool Decided { get; set; } + + public bool HandledInternally { get; set; } + + public bool CompletionSeen { get; set; } + } + + /// Called from Items_DragStarting once the drag package is prepared. + private void BeginMappedDragTracking(string? sessionId, IReadOnlyList paths) + { + MappedDragSession? previous = _mappedDrag; + _mappedDrag = null; + previous?.Tracker.Stop(); + try + { + if (string.IsNullOrEmpty(sessionId) || paths.Count == 0 || !ViewModel.IsMappedOrganizeWidget) + { + return; + } + + DispatcherQueue queue = DispatcherQueue; + var tracker = new MappedDragReleaseTracker(sessionId); + var session = new MappedDragSession(sessionId, paths.ToArray(), tracker); + _mappedDrag = session; + tracker.Finished += finished => queue.TryEnqueue(() => OnMappedDragTrackerFinished(session)); + tracker.Start(); + App.Log( + $"[MappedOrganize] DragToDesktop tracking widget={WidgetId} session={sessionId} " + + $"paths={paths.Count} buttons(L={Win32Helper.IsKeyDown(MappedDragVirtualKeyLeftButton)}," + + $"R={Win32Helper.IsKeyDown(MappedDragVirtualKeyRightButton)})"); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] DragToDesktop tracking failed to start: {ex.Message}"); + } + } + + /// + /// Drag completion hook (CompleteDragItemsSession). Returns true when the + /// completed drag was turned into 「放回桌面」. + /// + private bool TryPutBackMappedDragOnDesktop( + string[] draggedPaths, + bool handledInternally, + string? dragSessionId, + DataPackageOperation dropResult) + { + try + { + MappedDragSession? session = _mappedDrag; + if (session is not null && !string.Equals(session.SessionId, dragSessionId, StringComparison.Ordinal)) + { + session = null; + } + + if (session is null && !ViewModel.IsMappedOrganizeWidget) + { + // Ordinary (move-mode) widget: upstream drag-out, nothing to log. + return false; + } + + if (session is { Decided: true }) + { + LogMappedDragSkip("already-decided", dragSessionId, "completion", dropResult); + return false; + } + + if (session is not null && session.Tracker.State == MappedDragReleaseState.Pending) + { + // Completion before the button went up: the stack popover + // closed mid-drag. The release decides once it happens. + session.HandledInternally |= handledInternally; + session.CompletionSeen = true; + LogMappedDragSkip("completion-before-release (deferred to release)", dragSessionId, "completion", dropResult); + return false; + } + + return DecideMappedDragPutBack(session, draggedPaths, handledInternally, dragSessionId, "completion", dropResult); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] DragToDesktop failed: {ex}"); + return false; + } + } + + private void OnMappedDragTrackerFinished(MappedDragSession session) + { + if (_isDisposed || session.Decided || session.Tracker.State != MappedDragReleaseState.Released) + { + return; + } + + if (session.CompletionSeen) + { + // The completion arrived early (button still held) and deferred. + DecideMappedDragPutBack(session, [], session.HandledInternally, session.SessionId, "release-after-completion", DataPackageOperation.None); + return; + } + + // Normally DropCompleted follows within milliseconds and decides. If + // it never comes (container recycled, popover detached) the release + // decides on its own after a short grace. + DispatcherQueue queue = DispatcherQueue; + _ = Task.Delay(MappedDragCompletionGrace).ContinueWith( + _ => queue.TryEnqueue(() => + { + if (_isDisposed || session.Decided) + { + return; + } + + bool handled = session.HandledInternally || + (string.Equals(_activeDragSessionId, session.SessionId, StringComparison.Ordinal) && + _activeDragHandledAsStackMembership); + App.Log( + $"[MappedOrganize] DragToDesktop completion not reported {MappedDragCompletionGrace.TotalMilliseconds}ms " + + $"after release; deciding from the release session={session.SessionId}"); + DecideMappedDragPutBack(session, [], handled, session.SessionId, "release", DataPackageOperation.None); + }), + TaskScheduler.Default); + } + + private bool DecideMappedDragPutBack( + MappedDragSession? session, + string[] completionPaths, + bool handledInternally, + string? dragSessionId, + string trigger, + DataPackageOperation dropResult) { - if (handledInternally || - draggedPaths.Length == 0 || - !ViewModel.IsMappedOrganizeWidget || - MappedOrganizeService.Current is not { } service || - !Win32Helper.GetCursorPos(out Win32Helper.POINT cursor)) + if (session is not null) + { + session.Decided = true; + session.Tracker.Stop(); + handledInternally |= session.HandledInternally; + if (ReferenceEquals(_mappedDrag, session)) + { + _mappedDrag = null; + } + } + + string[] paths = completionPaths.Length > 0 ? completionPaths : session?.Paths ?? []; + bool isMapped = session is not null || ViewModel.IsMappedOrganizeWidget; + if (paths.Length == 0) + { + LogMappedDragSkip("no-dragged-paths", dragSessionId, trigger, dropResult); + return false; + } + + if (MappedOrganizeService.Current is not { } service) { + LogMappedDragSkip("service-unavailable", dragSessionId, trigger, dropResult); return false; } - MappedDesktopDropPoint drop = MappedDragToDesktopTarget.Probe(cursor); - if (!MappedDragToDesktopPolicy.ShouldPutBack( - isMappedWidget: true, - handledInternally, - drop.Kind, - drop.OnIcon, - mouseButtonDown: Win32Helper.IsKeyDown(VirtualKeyLeftButton) || Win32Helper.IsKeyDown(VirtualKeyRightButton), - escapePressed: Win32Helper.IsKeyDown(VirtualKeyEscape))) + MappedDesktopDropPoint drop; + Win32Helper.POINT point; + bool mouseButtonDown = false; + bool escapePressed = false; + string pointSource; + if (session?.Tracker.State == MappedDragReleaseState.Cancelled) { + LogMappedDragSkip("escape-pressed (tracker)", dragSessionId, trigger, dropResult); return false; } - IReadOnlyList paths = MappedDragToDesktopPolicy.ComputePutBackPaths( - draggedPaths, + if (session is not null && session.Tracker.TryGetRelease(out point, out drop)) + { + pointSource = "release"; + if (drop.IconHit == MappedDragIconHit.Failed) + { + // Explorer was busy at the instant of release; it has had + // time to settle by now. + MappedDesktopDropPoint retry = MappedDragToDesktopTarget.Probe(point); + if (retry.Kind != MappedDragDropTargetKind.NotDesktop && retry.IconHit != MappedDragIconHit.Failed) + { + drop = retry; + pointSource = "release+reprobe"; + } + } + } + else + { + if (!Win32Helper.GetCursorPos(out point)) + { + LogMappedDragSkip("no-cursor-position", dragSessionId, trigger, dropResult); + return false; + } + + pointSource = $"cursor-at-{trigger} (tracker={session?.Tracker.State.ToString() ?? "none"})"; + drop = MappedDragToDesktopTarget.Probe(point); + mouseButtonDown = Win32Helper.IsKeyDown(MappedDragVirtualKeyLeftButton) || + Win32Helper.IsKeyDown(MappedDragVirtualKeyRightButton); + escapePressed = Win32Helper.IsKeyDown(MappedDragVirtualKeyEscape); + } + + MappedDragPutBackDecision decision = MappedDragToDesktopPolicy.Evaluate( + isMapped, + handledInternally, + drop.Kind, + drop.IconHit, + drop.IconText, + paths, + mouseButtonDown, + escapePressed); + string where = $"at={point.X},{point.Y} point={pointSource} {drop.Describe()}"; + if (!decision.PutBack) + { + LogMappedDragSkip(decision.Reason, dragSessionId, trigger, dropResult, where); + return false; + } + + IReadOnlyList putBack = MappedDragToDesktopPolicy.ComputePutBackPaths( + paths, path => File.Exists(path) || Directory.Exists(path), MappedOrganizeService.IsDesktopEntryPath); - if (paths.Count == 0) + if (putBack.Count == 0) { + LogMappedDragSkip("no-existing-desktop-paths", dragSessionId, trigger, dropResult, where); return false; } - int kept = service.KeepOnDesktop(paths); + int kept = service.KeepOnDesktop(putBack); App.Log( - $"[MappedOrganize] Drag to desktop: put back {kept}/{draggedPaths.Length} " + - $"widget={WidgetId} target={drop.Kind} at={cursor.X},{cursor.Y}."); + $"[MappedOrganize] DragToDesktop put back {kept}/{paths.Length} widget={WidgetId} " + + $"session={dragSessionId} trigger={trigger} why={decision.Reason} dropResult={dropResult} {where}"); if (kept <= 0) { + LogMappedDragSkip("keep-on-desktop-changed-nothing", dragSessionId, trigger, dropResult, where); return false; } - MappedDragToDesktopPlacement.PlaceInBackground(paths, drop); + MappedDragToDesktopPlacement.PlaceInBackground(putBack, drop); ShowFeedback(new WidgetFeedbackRequest( ForkOrganizeModeText.Format(ForkOrganizeModeText.Key.KeptOnDesktopFormat, kept), WidgetFeedbackSeverity.Success, "mapped-keep-desktop")); return true; } + + private void LogMappedDragSkip( + string reason, + string? dragSessionId, + string trigger, + DataPackageOperation dropResult, + string? where = null) + { + App.Log( + $"[MappedOrganize] DragToDesktop skip reason={reason} widget={WidgetId} session={dragSessionId} " + + $"trigger={trigger} dropResult={dropResult} mapped={ViewModel.IsMappedOrganizeWidget}" + + (where is null ? string.Empty : $" {where}")); + } } diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs index 4ae84e39e..02ac3179f 100644 --- a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs +++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedOrganize.cs @@ -36,6 +36,19 @@ private bool TryKeepMappedItemsOnDesktop(IReadOnlyList items) return true; } + /// 「重新整理桌面」: opens the organize preview (放回桌面 items included, see MappedOrganizeReorganizePolicy). + internal static void OpenMappedReorganizePreview() + { + try + { + App.Current.ShowDesktopOrganizationWindow(); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Opening the organize preview failed: {ex.Message}"); + } + } + private void AddMappedOrganizeMenuItems(MenuFlyout flyout) { if (!ViewModel.IsMappedOrganizeWidget || MappedOrganizeService.Current is not { } service) @@ -53,6 +66,18 @@ private void AddMappedOrganizeMenuItems(MenuFlyout flyout) }; 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); + var autoAssign = new ToggleMenuFlyoutItem { Text = T("MappedOrganize.Menu.AutoAssign"), diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs index 66a7ce82e..472a196e0 100644 --- a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs +++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs @@ -1531,6 +1531,8 @@ draggedItem is null ? "no-item" } _activeDragSourcePaths = result.SourcePaths.ToArray(); + // GOXF fork: remember a mapped widget's drag for 「拖到桌面 = 放回桌面」. + BeginMappedDragTracking(_activeDragSessionId, _activeDragSourcePaths); _activeDragHasStorageItems = result.HasStorageItems; // Windows 10 collapses the advertised set to a single effect — // Explorer there prompts for every multi-effect drop regardless of @@ -1666,7 +1668,7 @@ private void CompleteDragItemsSession( } // GOXF fork: a mapped widget's drag released on the desktop is 「放回桌面」. - if (TryPutBackMappedDragOnDesktop(movedPaths, handledAsStackMembership)) + if (TryPutBackMappedDragOnDesktop(movedPaths, handledAsStackMembership, dragSessionId, dropResult)) { return; } diff --git a/src/DeskBox/Platform/DesktopListViewProbeNativeMethods.cs b/src/DeskBox/Platform/DesktopListViewProbeNativeMethods.cs new file mode 100644 index 000000000..b9be1b4f8 --- /dev/null +++ b/src/DeskBox/Platform/DesktopListViewProbeNativeMethods.cs @@ -0,0 +1,219 @@ +using System.Runtime.InteropServices; + +namespace DeskBox.Platform; + +/// Result of . +internal readonly record struct DesktopListViewHit(bool Succeeded, int ItemIndex, string? ItemText, string? Failure) +{ + internal static DesktopListViewHit Fail(string failure) => new(false, -1, null, failure); +} + +/// +/// GOXF fork, 「拖到桌面 = 放回桌面」: a three-state hit test of the desktop +/// list view (blank / which icon / could not tell). The upstream +/// DesktopBlankHitTest folds "icon" and "hit test failed" into one +/// false; this probe keeps them apart and also reads the label of the +/// icon that was hit (LVM_GETITEMTEXTW), so a drop on the dragged entry's own +/// (visible-hidden) icon is not mistaken for a drop on a folder. Same +/// cross-process technique as upstream: LVM_* messages carry process-local +/// pointers, so the structures live in memory allocated inside Explorer. +/// +internal static class DesktopListViewProbeNativeMethods +{ + private const uint ProcessVmOperation = 0x0008; + private const uint ProcessVmRead = 0x0010; + private const uint ProcessVmWrite = 0x0020; + private const uint MemCommit = 0x1000; + private const uint MemReserve = 0x2000; + private const uint MemRelease = 0x8000; + private const uint PageReadWrite = 0x04; + private const uint ListViewFirst = 0x1000; + private const uint ListViewHitTestMessage = ListViewFirst + 18; + private const uint ListViewGetItemTextW = ListViewFirst + 115; + private const uint ListViewItemFlagText = 0x0001; + private const uint SendMessageAbortIfHung = 0x0002; + private const uint TimeoutMilliseconds = 150; + private const int TextCapacity = 260; + + internal static DesktopListViewHit HitTest(IntPtr listView, Win32Helper.POINT screenPoint) + { + if (listView == IntPtr.Zero) + { + return DesktopListViewHit.Fail("no-list-view"); + } + + Win32Helper.POINT clientPoint = screenPoint; + if (!Win32Helper.ScreenToClient(listView, ref clientPoint)) + { + return DesktopListViewHit.Fail("screen-to-client"); + } + + Win32Helper.GetWindowThreadProcessId(listView, out uint processId); + if (processId == 0) + { + return DesktopListViewHit.Fail("no-process"); + } + + IntPtr process = RemoteProcessMemoryNativeMethods.OpenProcess( + ProcessVmOperation | ProcessVmRead | ProcessVmWrite, + false, + processId); + if (process == IntPtr.Zero) + { + return DesktopListViewHit.Fail($"open-process err={Marshal.GetLastPInvokeError()}"); + } + + int hitSize = Marshal.SizeOf(); + int itemSize = Marshal.SizeOf(); + int textBytes = TextCapacity * sizeof(char); + int totalSize = hitSize + itemSize + textBytes; + IntPtr local = IntPtr.Zero; + IntPtr remote = IntPtr.Zero; + try + { + local = Marshal.AllocHGlobal(totalSize); + remote = RemoteProcessMemoryNativeMethods.VirtualAllocEx( + process, + IntPtr.Zero, + (UIntPtr)totalSize, + MemCommit | MemReserve, + PageReadWrite); + if (remote == IntPtr.Zero) + { + return DesktopListViewHit.Fail($"alloc err={Marshal.GetLastPInvokeError()}"); + } + + var hit = new ListViewHitTestInfo + { + Point = clientPoint, + ItemIndex = -1, + SubItemIndex = -1, + GroupIndex = -1, + }; + Marshal.StructureToPtr(hit, local, false); + if (!RemoteProcessMemoryNativeMethods.WriteProcessMemory(process, remote, local, (UIntPtr)hitSize, out _)) + { + return DesktopListViewHit.Fail("write-hit"); + } + + if (Win32Helper.SendMessageTimeout( + listView, + ListViewHitTestMessage, + UIntPtr.Zero, + remote, + SendMessageAbortIfHung, + TimeoutMilliseconds, + out _) == IntPtr.Zero) + { + return DesktopListViewHit.Fail($"hit-test-timeout err={Marshal.GetLastPInvokeError()}"); + } + + if (!RemoteProcessMemoryNativeMethods.ReadProcessMemory(process, remote, local, (UIntPtr)hitSize, out _)) + { + return DesktopListViewHit.Fail("read-hit"); + } + + hit = Marshal.PtrToStructure(local); + if (hit.ItemIndex < 0) + { + return new DesktopListViewHit(true, -1, null, null); + } + + return new DesktopListViewHit(true, hit.ItemIndex, ReadItemText(process, listView, local, remote, hit.ItemIndex, hitSize, itemSize), null); + } + finally + { + if (remote != IntPtr.Zero) + { + RemoteProcessMemoryNativeMethods.VirtualFreeEx(process, remote, UIntPtr.Zero, MemRelease); + } + + if (local != IntPtr.Zero) + { + Marshal.FreeHGlobal(local); + } + + RemoteProcessMemoryNativeMethods.CloseHandle(process); + } + } + + /// Best effort: null when the label cannot be read (the caller then treats the icon as another entry). + private static string? ReadItemText( + IntPtr process, + IntPtr listView, + IntPtr local, + IntPtr remote, + int index, + int hitSize, + int itemSize) + { + IntPtr localItem = IntPtr.Add(local, hitSize); + IntPtr remoteItem = IntPtr.Add(remote, hitSize); + IntPtr localText = IntPtr.Add(localItem, itemSize); + IntPtr remoteText = IntPtr.Add(remoteItem, itemSize); + var item = new ListViewItem + { + Mask = ListViewItemFlagText, + Item = index, + Text = remoteText, + TextMax = TextCapacity, + }; + Marshal.StructureToPtr(item, localItem, false); + if (!RemoteProcessMemoryNativeMethods.WriteProcessMemory(process, remoteItem, localItem, (UIntPtr)itemSize, out _)) + { + return null; + } + + if (Win32Helper.SendMessageTimeout( + listView, + ListViewGetItemTextW, + (UIntPtr)(uint)index, + remoteItem, + SendMessageAbortIfHung, + TimeoutMilliseconds, + out UIntPtr length) == IntPtr.Zero) + { + return null; + } + + int chars = (int)Math.Min((ulong)length, (ulong)(TextCapacity - 1)); + if (chars <= 0 || + !RemoteProcessMemoryNativeMethods.ReadProcessMemory(process, remoteText, localText, (UIntPtr)(chars * sizeof(char)), out _)) + { + return null; + } + + return Marshal.PtrToStringUni(localText, chars); + } + + [StructLayout(LayoutKind.Sequential)] + private struct ListViewHitTestInfo + { + public Win32Helper.POINT Point; + public uint Flags; + public int ItemIndex; + public int SubItemIndex; + public int GroupIndex; + } + + /// LVITEMW (only the fields up to iGroup; Explorer reads mask / iSubItem / pszText / cchTextMax). + [StructLayout(LayoutKind.Sequential)] + private struct ListViewItem + { + public uint Mask; + public int Item; + public int SubItem; + public uint State; + public uint StateMask; + public IntPtr Text; + public int TextMax; + public int Image; + public IntPtr Param; + public int Indent; + public int GroupId; + public uint Columns; + public IntPtr ColumnsPointer; + public IntPtr ColumnFormats; + public int Group; + } +} diff --git a/src/DeskBox/Services/ForkOrganizeModeSettings.cs b/src/DeskBox/Services/ForkOrganizeModeSettings.cs index d98fc6b6c..45615cd06 100644 --- a/src/DeskBox/Services/ForkOrganizeModeSettings.cs +++ b/src/DeskBox/Services/ForkOrganizeModeSettings.cs @@ -206,6 +206,7 @@ public enum Key PreviewTooltipMapOnly, MenuKeepOnDesktop, KeptOnDesktopFormat, + MenuReorganizeDesktop, } /// UI-culture lookup lives in Helpers/ForkOrganizeModeText.Culture.cs (no App globals in Services). @@ -260,9 +261,10 @@ 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. They won't be sorted automatically again."), + "已将 {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"), _ => key.ToString(), }; } diff --git a/src/DeskBox/Services/MappedDragReleaseTracker.cs b/src/DeskBox/Services/MappedDragReleaseTracker.cs new file mode 100644 index 000000000..1ebae85fa --- /dev/null +++ b/src/DeskBox/Services/MappedDragReleaseTracker.cs @@ -0,0 +1,210 @@ +using DeskBox.Platform; + +namespace DeskBox.Services; + +/// Where a mapped-widget drag gesture stands, as seen from the physical mouse buttons. +public enum MappedDragReleaseState +{ + /// A button is (or may still be) held: the drop has not happened yet. + Pending, + + /// The held button went up: this is the drop point. + Released, + + /// Esc was seen during the gesture (OLE cancels the drag on Esc). + Cancelled, + + /// No mouse button was ever seen down (touch / pen drag): nothing to track. + Untracked, +} + +/// +/// GOXF fork, 「拖到桌面 = 放回桌面」: pure state machine fed with polled +/// button / Esc samples. Lets DeskBox read the release point at the moment of +/// release instead of when WinUI reports the drag completed: by then Explorer +/// has already processed the drop (its desktop thread may be busy and the +/// list-view hit test times out, or it has moved a visible-hidden copy of the +/// dragged icon under the cursor), and a stack popover closing mid-drag +/// completes the session while the button is still held. +/// +public sealed class MappedDragReleaseTracking +{ + private readonly TimeSpan _buttonGrace; + + public MappedDragReleaseTracking(TimeSpan? buttonGrace = null) + { + _buttonGrace = buttonGrace ?? TimeSpan.FromMilliseconds(400); + } + + public MappedDragReleaseState State { get; private set; } = MappedDragReleaseState.Pending; + + public bool SawButtonDown { get; private set; } + + /// Feeds one sample; returns the (possibly final) state. + public MappedDragReleaseState Observe(TimeSpan elapsed, bool buttonDown, bool escapeDown) + { + if (State != MappedDragReleaseState.Pending) + { + return State; + } + + if (escapeDown && (buttonDown || SawButtonDown)) + { + State = MappedDragReleaseState.Cancelled; + return State; + } + + if (buttonDown) + { + SawButtonDown = true; + return State; + } + + if (SawButtonDown) + { + State = MappedDragReleaseState.Released; + } + else if (elapsed >= _buttonGrace) + { + State = MappedDragReleaseState.Untracked; + } + + return State; + } +} + +/// +/// Background poller behind : samples +/// the physical buttons every few milliseconds while a mapped-widget drag +/// runs and probes the desktop at the release point right away (Win32 only, +/// no UI-thread work). is raised on the poller thread. +/// +internal sealed class MappedDragReleaseTracker +{ + private const int VirtualKeyLeftButton = 0x01; + private const int VirtualKeyRightButton = 0x02; + private const int VirtualKeyEscape = 0x1B; + private static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(8); + private static readonly TimeSpan MaxLifetime = TimeSpan.FromMinutes(10); + + private readonly MappedDragReleaseTracking _tracking = new(); + private readonly object _gate = new(); + private volatile bool _stopRequested; + private MappedDragReleaseState _state = MappedDragReleaseState.Pending; + private Win32Helper.POINT _releasePoint; + private MappedDesktopDropPoint _releaseProbe = MappedDesktopDropPoint.None; + + internal MappedDragReleaseTracker(string sessionId) + { + SessionId = sessionId; + } + + internal string SessionId { get; } + + internal event Action? Finished; + + internal MappedDragReleaseState State + { + get + { + lock (_gate) + { + return _state; + } + } + } + + internal bool TryGetRelease(out Win32Helper.POINT point, out MappedDesktopDropPoint probe) + { + lock (_gate) + { + point = _releasePoint; + probe = _releaseProbe; + return _state == MappedDragReleaseState.Released; + } + } + + internal void Start() + { + try + { + var thread = new Thread(Run) + { + IsBackground = true, + Name = "DeskBox mapped drag release", + }; + thread.Start(); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] DragToDesktop release tracker could not start: {ex.Message}"); + Finish(MappedDragReleaseState.Untracked, default, MappedDesktopDropPoint.None); + } + } + + internal void Stop() => _stopRequested = true; + + private void Run() + { + var clock = System.Diagnostics.Stopwatch.StartNew(); + try + { + while (!_stopRequested && clock.Elapsed < MaxLifetime) + { + bool buttonDown = Win32Helper.IsKeyDown(VirtualKeyLeftButton) || Win32Helper.IsKeyDown(VirtualKeyRightButton); + bool escapeDown = Win32Helper.IsKeyDown(VirtualKeyEscape); + MappedDragReleaseState state = _tracking.Observe(clock.Elapsed, buttonDown, escapeDown); + if (state == MappedDragReleaseState.Released) + { + if (!Win32Helper.GetCursorPos(out Win32Helper.POINT point)) + { + Finish(MappedDragReleaseState.Untracked, default, MappedDesktopDropPoint.None); + return; + } + + MappedDesktopDropPoint probe = MappedDragToDesktopTarget.Probe(point); + App.Log( + $"[MappedOrganize] DragToDesktop released session={SessionId} at={point.X},{point.Y} " + + $"after={clock.ElapsedMilliseconds}ms {probe.Describe()}"); + Finish(state, point, probe); + return; + } + + if (state != MappedDragReleaseState.Pending) + { + App.Log($"[MappedOrganize] DragToDesktop tracker session={SessionId} state={state} after={clock.ElapsedMilliseconds}ms"); + Finish(state, default, MappedDesktopDropPoint.None); + return; + } + + Thread.Sleep(PollInterval); + } + + Finish(MappedDragReleaseState.Untracked, default, MappedDesktopDropPoint.None); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] DragToDesktop release tracker failed: {ex.Message}"); + Finish(MappedDragReleaseState.Untracked, default, MappedDesktopDropPoint.None); + } + } + + private void Finish(MappedDragReleaseState state, Win32Helper.POINT point, MappedDesktopDropPoint probe) + { + lock (_gate) + { + _state = state; + _releasePoint = point; + _releaseProbe = probe; + } + + try + { + Finished?.Invoke(this); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] DragToDesktop tracker callback failed: {ex.Message}"); + } + } +} diff --git a/src/DeskBox/Services/MappedDragToDesktopPolicy.cs b/src/DeskBox/Services/MappedDragToDesktopPolicy.cs index 3831cb13c..fb45a272f 100644 --- a/src/DeskBox/Services/MappedDragToDesktopPolicy.cs +++ b/src/DeskBox/Services/MappedDragToDesktopPolicy.cs @@ -13,6 +13,22 @@ public enum MappedDragDropTargetKind DesktopHost, } +/// What the desktop list view reported under the release point. +public enum MappedDragIconHit +{ + /// Blank desktop (no icon under the point), or no icon list there at all. + Blank, + + /// An icon is under the point (its display text may be known). + Item, + + /// The cross-process hit test could not run (Explorer busy, access denied, timeout). + Failed, +} + +/// A 「放回桌面」 verdict plus the reason logged as [MappedOrganize] DragToDesktop skip reason=…. +public readonly record struct MappedDragPutBackDecision(bool PutBack, string Reason); + /// /// GOXF fork, 「映射整理」: pure decisions for 「从映射格子拖到桌面 = 放回桌面」. /// A mapped item already lives in the desktop folder, so Explorer treats a drop @@ -94,12 +110,105 @@ public static bool ShouldPutBack( bool droppedOnIcon, bool mouseButtonDown = false, bool escapePressed = false) => - isMappedWidget && - !handledInternally && - target != MappedDragDropTargetKind.NotDesktop && - !droppedOnIcon && - !mouseButtonDown && - !escapePressed; + Evaluate( + isMappedWidget, + handledInternally, + target, + droppedOnIcon ? MappedDragIconHit.Item : MappedDragIconHit.Blank, + iconText: null, + draggedPaths: [], + mouseButtonDown, + escapePressed).PutBack; + + /// + /// Full verdict with a reason for the diagnostics log. An icon under the + /// release point only blocks 「放回桌面」 when it is another entry: with + /// 「显示隐藏的项目」 on, the dragged (hidden) entry itself is listed and + /// Explorer may already have moved it under the cursor. A hit test that + /// could not run does not block either: every put-back path is re-checked + /// to still exist on the desktop, so a real move into a folder icon drops + /// out there. + /// + public static MappedDragPutBackDecision Evaluate( + bool isMappedWidget, + bool handledInternally, + MappedDragDropTargetKind target, + MappedDragIconHit iconHit, + string? iconText, + IReadOnlyCollection draggedPaths, + bool mouseButtonDown, + bool escapePressed) + { + if (!isMappedWidget) + { + return new(false, "not-mapped-widget"); + } + + if (handledInternally) + { + return new(false, "handled-internally"); + } + + if (escapePressed) + { + return new(false, "escape-pressed"); + } + + if (mouseButtonDown) + { + return new(false, "mouse-button-down"); + } + + if (target == MappedDragDropTargetKind.NotDesktop) + { + return new(false, "not-desktop"); + } + + if (iconHit == MappedDragIconHit.Item) + { + return IsDraggedItemText(iconText, draggedPaths) + ? new(true, "own-icon") + : new(false, "on-other-icon"); + } + + return new(true, iconHit == MappedDragIconHit.Failed ? "hit-test-failed" : "blank"); + } + + /// + /// Whether the desktop label is one of the + /// dragged entries: the label is the file name, or the name without its + /// extension (extensions hidden, .lnk / .url always). + /// + public static bool IsDraggedItemText(string? iconText, IEnumerable? draggedPaths) + { + if (string.IsNullOrWhiteSpace(iconText) || draggedPaths is null) + { + return false; + } + + string label = iconText.Trim(); + foreach (string path in draggedPaths) + { + if (string.IsNullOrWhiteSpace(path)) + { + continue; + } + + string name = Path.GetFileName(Path.TrimEndingDirectorySeparator(path.Trim())); + if (name.Length == 0) + { + continue; + } + + if (string.Equals(label, name, StringComparison.OrdinalIgnoreCase) || + string.Equals(label, Path.GetFileNameWithoutExtension(name), StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } /// /// The entries to put back: dragged paths that still exist and sit directly diff --git a/src/DeskBox/Services/MappedDragToDesktopTarget.cs b/src/DeskBox/Services/MappedDragToDesktopTarget.cs index c51cc9927..4a3cc1711 100644 --- a/src/DeskBox/Services/MappedDragToDesktopTarget.cs +++ b/src/DeskBox/Services/MappedDragToDesktopTarget.cs @@ -6,15 +6,25 @@ namespace DeskBox.Services; /// Where a mapped-widget drag was released, resolved against the live desktop windows. internal readonly record struct MappedDesktopDropPoint( MappedDragDropTargetKind Kind, - bool OnIcon, + MappedDragIconHit IconHit, + string? IconText, IntPtr ListView, int ClientX, int ClientY, int AreaTopClient, - int AreaBottomClient) + int AreaBottomClient, + string Chain = "", + string? HitFailure = null) { internal static MappedDesktopDropPoint None { get; } = - new(MappedDragDropTargetKind.NotDesktop, false, IntPtr.Zero, 0, 0, 0, 0); + new(MappedDragDropTargetKind.NotDesktop, MappedDragIconHit.Blank, null, IntPtr.Zero, 0, 0, 0, 0); + + /// One-line diagnostics for [MappedOrganize] DragToDesktop … log lines. + internal string Describe() => + $"target={Kind} icon={IconHit}" + + (IconText is null ? string.Empty : $" iconText='{IconText}'") + + (HitFailure is null ? string.Empty : $" hitFailure={HitFailure}") + + $" chain='{Chain}'"; } /// @@ -22,12 +32,17 @@ internal readonly record struct MappedDesktopDropPoint( /// Reads the window under the release point (every monitor: the desktop list /// view spans the virtual screen, and Windows 11 may host it under WorkerW), /// classifies it with , -/// and tells blank desktop apart from an icon with the upstream -/// . +/// and tells blank desktop, an icon (with its label) and a failed hit test +/// apart with . The shell drag +/// image (SysDragImage) can still sit under the cursor at the instant of +/// release; the probe waits briefly for it to go away. /// internal static class MappedDragToDesktopTarget { private const int MaxAncestorDepth = 16; + private const int DragImageRetries = 4; + + private static readonly string[] OverlayClasses = ["SysDragImage", "DragImageWindow"]; internal static MappedDesktopDropPoint Probe(Win32Helper.POINT screenPoint) { @@ -45,9 +60,15 @@ internal static MappedDesktopDropPoint Probe(Win32Helper.POINT screenPoint) private static MappedDesktopDropPoint ProbeCore(Win32Helper.POINT screenPoint) { IntPtr hit = Win32Helper.WindowFromPoint(screenPoint); + for (int retry = 0; hit != IntPtr.Zero && retry < DragImageRetries && IsOverlay(hit); retry++) + { + Thread.Sleep(25); + hit = Win32Helper.WindowFromPoint(screenPoint); + } + if (hit == IntPtr.Zero) { - return MappedDesktopDropPoint.None; + return MappedDesktopDropPoint.None with { Chain = "" }; } var chain = new List(); @@ -94,9 +115,12 @@ private static MappedDesktopDropPoint ProbeCore(Win32Helper.POINT screenPoint) } MappedDragDropTargetKind kind = MappedDragToDesktopPolicy.ClassifyTarget(chain, ownedByDeskBox, ownedByShell); + string chainText = string.Join(">", chain) + + (ownedByDeskBox ? " [DeskBox]" : string.Empty) + + (ownedByShell ? string.Empty : " [not shell]"); if (kind == MappedDragDropTargetKind.NotDesktop) { - return MappedDesktopDropPoint.None; + return MappedDesktopDropPoint.None with { Chain = chainText }; } if (listView == IntPtr.Zero && defView != IntPtr.Zero) @@ -104,10 +128,23 @@ private static MappedDesktopDropPoint ProbeCore(Win32Helper.POINT screenPoint) listView = Win32Helper.FindWindowEx(defView, IntPtr.Zero, "SysListView32", null); } - // DesktopBlankHitTest answers false both for an icon and for a failed - // hit test; either way the drop is left to the upstream handling. - bool onIcon = kind == MappedDragDropTargetKind.DesktopIconList && - !DesktopBlankHitTest.IsBlankDesktopPoint(screenPoint); + MappedDragIconHit iconHit = MappedDragIconHit.Blank; + string? iconText = null; + string? hitFailure = null; + if (kind == MappedDragDropTargetKind.DesktopIconList) + { + DesktopListViewHit listHit = DesktopListViewProbeNativeMethods.HitTest(listView, screenPoint); + if (!listHit.Succeeded) + { + iconHit = MappedDragIconHit.Failed; + hitFailure = listHit.Failure; + } + else if (listHit.ItemIndex >= 0) + { + iconHit = MappedDragIconHit.Item; + iconText = listHit.ItemText; + } + } int clientX = screenPoint.X; int clientY = screenPoint.Y; @@ -134,7 +171,15 @@ private static MappedDesktopDropPoint ProbeCore(Win32Helper.POINT screenPoint) areaBottom = work.Bottom + offsetY; } - return new MappedDesktopDropPoint(kind, onIcon, listView, clientX, clientY, areaTop, areaBottom); + return new MappedDesktopDropPoint( + kind, iconHit, iconText, listView, clientX, clientY, areaTop, areaBottom, chainText, hitFailure); + } + + private static bool IsOverlay(IntPtr window) + { + IntPtr root = Win32Helper.GetAncestor(window, Win32Helper.GA_ROOT); + string className = ClassOf(root == IntPtr.Zero ? window : root); + return OverlayClasses.Any(overlay => string.Equals(overlay, className, StringComparison.OrdinalIgnoreCase)); } private static string ClassOf(IntPtr window) diff --git a/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs b/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs new file mode 100644 index 000000000..99f5c1a7e --- /dev/null +++ b/src/DeskBox/Services/MappedOrganizeReorganizePolicy.cs @@ -0,0 +1,100 @@ +using DeskBox.Models; + +namespace DeskBox.Services; + +/// +/// 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 +/// entry: sorted into their category by the normal rules and selected by +/// default; confirming maps them and clears the mark +/// (), unticking keeps it. +/// Pure helpers, unit-tested. +/// +public static class MappedOrganizeReorganizePolicy +{ + /// + /// Kept entries the preview must opt in on its own: those the scanner + /// leaves out only for an opt-in reason (folder, large file, batch limit), + /// which would otherwise start unticked. Each path is opted in once per + /// preview ( is updated), so a later + /// refresh does not re-tick what the user unticked. + /// + public static IReadOnlyList SelectKeptOptIns( + IEnumerable<(string Path, bool CanOptIn)> scannedItems, + IReadOnlyCollection kept, + ISet alreadyApplied) + { + ArgumentNullException.ThrowIfNull(alreadyApplied); + if (scannedItems is null || kept is null || kept.Count == 0) + { + return []; + } + + var keptSet = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string path in kept) + { + if (!string.IsNullOrWhiteSpace(path)) + { + keptSet.Add(MappedOrganizeMembership.NormalizePath(path)); + } + } + + var result = new List(); + foreach ((string path, bool canOptIn) in scannedItems) + { + if (!canOptIn || string.IsNullOrWhiteSpace(path)) + { + continue; + } + + string normalized = MappedOrganizeMembership.NormalizePath(path); + if (keptSet.Contains(normalized) && alreadyApplied.Add(normalized)) + { + result.Add(path); + } + } + + return result; + } + + /// + /// 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( + WidgetConfig? config, + IEnumerable? widgets, + IEnumerable? groups) + { + if (config is null) + { + return false; + } + + if (MappedOrganizeWidgetMetadata.IsMappedOrganize(config)) + { + return true; + } + + if (widgets is null || groups is null) + { + return false; + } + + WidgetGroupConfig? group = groups.FirstOrDefault(candidate => + candidate?.MemberIds is { } members && + members.Contains(config.Id, StringComparer.Ordinal)); + if (group is null) + { + return false; + } + + var memberIds = group.MemberIds.ToHashSet(StringComparer.Ordinal); + return widgets.Any(widget => + widget is not null && + memberIds.Contains(widget.Id) && + MappedOrganizeWidgetMetadata.IsMappedOrganize(widget)); + } +} diff --git a/src/DeskBox/Services/MappedOrganizeService.Visibility.cs b/src/DeskBox/Services/MappedOrganizeService.Visibility.cs index 83f945540..927169267 100644 --- a/src/DeskBox/Services/MappedOrganizeService.Visibility.cs +++ b/src/DeskBox/Services/MappedOrganizeService.Visibility.cs @@ -13,6 +13,9 @@ public sealed partial class MappedOrganizeService private DesktopOrganizeMode _mode = DesktopOrganizeMode.MoveToWidgets; private volatile bool _restoredForExit; + /// Entries currently marked 「放回桌面」 (copy; UI thread). + public IReadOnlyCollection KeptOnDesktopSnapshot() => _keptOnDesktop.ToArray(); + /// The organize mode the main process last applied. public DesktopOrganizeMode Mode => _mode; diff --git a/src/DeskBox/Views/ContentWidgetWindow.Commands.cs b/src/DeskBox/Views/ContentWidgetWindow.Commands.cs index 371c6aef6..9da5ddec1 100644 --- a/src/DeskBox/Views/ContentWidgetWindow.Commands.cs +++ b/src/DeskBox/Views/ContentWidgetWindow.Commands.cs @@ -460,6 +460,8 @@ private MenuFlyout CreateMoreFlyout() SetFileWidgetFolderOpenBehaviorOverride)); } + AppendMappedOrganizeMoreMenuItems(flyout); // GOXF fork: 「重新整理桌面」 + WidgetGroupMenuBuilder.Append( flyout, _config, diff --git a/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs b/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs new file mode 100644 index 000000000..8a53ed24a --- /dev/null +++ b/src/DeskBox/Views/ContentWidgetWindow.MappedOrganize.cs @@ -0,0 +1,46 @@ +using DeskBox.Controls.WidgetContents; +using DeskBox.Services; +using Microsoft.UI.Xaml.Controls; + +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 +/// (). +/// +public sealed partial class ContentWidgetWindow +{ + private void AppendMappedOrganizeMoreMenuItems(MenuFlyout flyout) + { + try + { + if (MappedOrganizeService.Current is null || + !MappedOrganizeReorganizePolicy.ShouldOfferReorganize( + _config, + App.Current.SettingsService.Settings.WidgetLayout.Widgets, + App.Current.SettingsService.Settings.WidgetLayout.WidgetGroups)) + { + return; + } + + var reorganize = new MenuFlyoutItem + { + Text = ForkOrganizeModeText.Get(ForkOrganizeModeText.Key.MenuReorganizeDesktop), + Icon = new FontIcon { Glyph = "\uE8B1" } + }; + reorganize.Click += (_, _) => + { + flyout.Hide(); + FileSurfaceContent.OpenMappedReorganizePreview(); + }; + flyout.Items.Add(new MenuFlyoutSeparator()); + flyout.Items.Add(reorganize); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Title menu entry failed: {ex.Message}"); + } + } +} diff --git a/tests/DeskBox.Tests/MappedDragToDesktopTests.cs b/tests/DeskBox.Tests/MappedDragToDesktopTests.cs index 269c55f53..541b19ad4 100644 --- a/tests/DeskBox.Tests/MappedDragToDesktopTests.cs +++ b/tests/DeskBox.Tests/MappedDragToDesktopTests.cs @@ -155,6 +155,110 @@ public void ComputeIconOrigins_WithoutWorkAreaKeepsOneColumn() Assert.Equal(new (int X, int Y)[] { (60, 50), (60, 150) }, origins.ToArray()); } + // ---- full verdict with diagnostics reason ---- + + private static readonly string[] Dragged = [Path.Combine(Desktop, "report.docx"), Path.Combine(Desktop, "Chrome.lnk")]; + + [Theory] + [InlineData(false, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Blank, null, false, false, false, "not-mapped-widget")] + [InlineData(true, true, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Blank, null, false, false, false, "handled-internally")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Blank, null, false, true, false, "escape-pressed")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Blank, null, true, false, false, "mouse-button-down")] + [InlineData(true, false, MappedDragDropTargetKind.NotDesktop, MappedDragIconHit.Blank, null, false, false, false, "not-desktop")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Item, "Projects", false, false, false, "on-other-icon")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Item, null, false, false, false, "on-other-icon")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Blank, null, false, false, true, "blank")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopHost, MappedDragIconHit.Blank, null, false, false, true, "blank")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Failed, null, false, false, true, "hit-test-failed")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Item, "report", false, false, true, "own-icon")] + [InlineData(true, false, MappedDragDropTargetKind.DesktopIconList, MappedDragIconHit.Item, "Chrome", false, false, true, "own-icon")] + public void Evaluate_ReportsAReasonForEveryOutcome( + bool mapped, + bool handled, + MappedDragDropTargetKind target, + MappedDragIconHit hit, + string? iconText, + bool buttonDown, + bool escape, + bool expectedPutBack, + string expectedReason) + { + MappedDragPutBackDecision decision = MappedDragToDesktopPolicy.Evaluate( + mapped, handled, target, hit, iconText, Dragged, buttonDown, escape); + + Assert.Equal(expectedPutBack, decision.PutBack); + Assert.Equal(expectedReason, decision.Reason); + } + + [Theory] + [InlineData("report.docx", true)] + [InlineData("REPORT", true)] + [InlineData(" report ", true)] + [InlineData("Chrome", true)] + [InlineData("Chrome.lnk", true)] + [InlineData("report.pdf", false)] + [InlineData("Recycle Bin", false)] + [InlineData("", false)] + [InlineData(null, false)] + public void IsDraggedItemText_MatchesNameWithOrWithoutExtension(string? label, bool expected) + { + Assert.Equal(expected, MappedDragToDesktopPolicy.IsDraggedItemText(label, Dragged)); + } + + [Fact] + public void IsDraggedItemText_HandlesFoldersAndEmptyInput() + { + Assert.True(MappedDragToDesktopPolicy.IsDraggedItemText("Folder", [Path.Combine(Desktop, "Folder") + Path.DirectorySeparatorChar])); + Assert.False(MappedDragToDesktopPolicy.IsDraggedItemText("Folder", null)); + Assert.False(MappedDragToDesktopPolicy.IsDraggedItemText("Folder", ["", " "])); + } + + // ---- release tracking ---- + + private static readonly TimeSpan T0 = TimeSpan.Zero; + private static readonly TimeSpan T1 = TimeSpan.FromMilliseconds(50); + private static readonly TimeSpan T2 = TimeSpan.FromMilliseconds(900); + + [Fact] + public void ReleaseTracking_ReleasesWhenTheHeldButtonGoesUp() + { + var tracking = new MappedDragReleaseTracking(); + Assert.Equal(MappedDragReleaseState.Pending, tracking.Observe(T0, buttonDown: true, escapeDown: false)); + Assert.Equal(MappedDragReleaseState.Pending, tracking.Observe(T1, buttonDown: true, escapeDown: false)); + Assert.Equal(MappedDragReleaseState.Released, tracking.Observe(T2, buttonDown: false, escapeDown: false)); + Assert.True(tracking.SawButtonDown); + + // Final: later samples do not change it. + Assert.Equal(MappedDragReleaseState.Released, tracking.Observe(T2, buttonDown: true, escapeDown: true)); + } + + [Fact] + public void ReleaseTracking_EscapeDuringTheDragCancels() + { + var tracking = new MappedDragReleaseTracking(); + tracking.Observe(T0, buttonDown: true, escapeDown: false); + Assert.Equal(MappedDragReleaseState.Cancelled, tracking.Observe(T1, buttonDown: true, escapeDown: true)); + } + + [Fact] + public void ReleaseTracking_EscapeBeforeAnyButtonIsIgnored() + { + var tracking = new MappedDragReleaseTracking(); + Assert.Equal(MappedDragReleaseState.Pending, tracking.Observe(T0, buttonDown: false, escapeDown: true)); + Assert.Equal(MappedDragReleaseState.Pending, tracking.Observe(T1, buttonDown: true, escapeDown: false)); + Assert.Equal(MappedDragReleaseState.Released, tracking.Observe(T2, buttonDown: false, escapeDown: false)); + } + + [Fact] + public void ReleaseTracking_WithoutAnyButtonGivesUpAfterTheGrace() + { + // Touch / pen drags never press a mouse button: completion decides. + var tracking = new MappedDragReleaseTracking(TimeSpan.FromMilliseconds(400)); + Assert.Equal(MappedDragReleaseState.Pending, tracking.Observe(T1, buttonDown: false, escapeDown: false)); + Assert.Equal(MappedDragReleaseState.Untracked, tracking.Observe(T2, buttonDown: false, escapeDown: false)); + Assert.False(tracking.SawButtonDown); + } + // ---- wiring ---- [Fact] @@ -162,11 +266,19 @@ public void DragCompletion_RoutesMappedDesktopDropsToPutBack() { string surface = File.ReadAllText(TestPaths.FromRepository( "src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs")); - Assert.Contains("TryPutBackMappedDragOnDesktop(movedPaths, handledAsStackMembership)", surface, StringComparison.Ordinal); + Assert.Contains( + "TryPutBackMappedDragOnDesktop(movedPaths, handledAsStackMembership, dragSessionId, dropResult)", + surface, + StringComparison.Ordinal); + Assert.Contains( + "BeginMappedDragTracking(_activeDragSessionId, _activeDragSourcePaths);", + surface, + StringComparison.Ordinal); string hook = File.ReadAllText(TestPaths.FromRepository( "src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs")); - Assert.Contains("service.KeepOnDesktop(paths)", hook, StringComparison.Ordinal); + Assert.Contains("service.KeepOnDesktop(putBack)", hook, StringComparison.Ordinal); Assert.Contains("ViewModel.IsMappedOrganizeWidget", hook, StringComparison.Ordinal); + Assert.Contains("DragToDesktop skip reason=", hook, StringComparison.Ordinal); } } diff --git a/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs b/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs new file mode 100644 index 000000000..d70d2e86b --- /dev/null +++ b/tests/DeskBox.Tests/MappedOrganizeReorganizeTests.cs @@ -0,0 +1,116 @@ +using DeskBox.Models; +using DeskBox.Services; + +namespace DeskBox.Tests; + +/// GOXF fork: 「重新整理桌面」 — 放回桌面 items are re-sorted by the organize preview. +public sealed class MappedOrganizeReorganizeTests +{ + private static readonly string Desktop = Path.Combine(Path.GetTempPath(), "deskbox-fork-reorganize-tests", "Desktop"); + + private static string D(string name) => MappedOrganizeMembership.NormalizePath(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; + } + + private static WidgetConfig Plain(string id) => + new() { Id = id, Name = id, WidgetKind = WidgetKind.File, MappedFolderPath = Path.Combine(Desktop, "..", id) }; + + [Fact] + public void SelectKeptOptIns_OptsInKeptEntriesTheScannerOnlyOffers() + { + var applied = new HashSet(StringComparer.OrdinalIgnoreCase); + (string, bool)[] scanned = + [ + (D("KeptFolder"), true), // kept folder: opt-in only → tick it + (D("kept.png"), false), // kept file: already ticked by the normal rules + (D("OtherFolder"), true), // not kept: stays the user's choice + (D("big.iso"), true), // kept large file → tick it + ]; + + IReadOnlyList optIns = MappedOrganizeReorganizePolicy.SelectKeptOptIns( + scanned, + [D("keptfolder"), D("kept.png"), D("BIG.iso")], + applied); + + Assert.Equal(new[] { D("KeptFolder"), D("big.iso") }, optIns.ToArray()); + } + + [Fact] + public void SelectKeptOptIns_AppliesEachPathOncePerPreview() + { + var applied = new HashSet(StringComparer.OrdinalIgnoreCase); + (string, bool)[] scanned = [(D("KeptFolder"), true)]; + + Assert.Single(MappedOrganizeReorganizePolicy.SelectKeptOptIns(scanned, [D("KeptFolder")], applied)); + // Refresh after the user unticked it: not re-ticked. + Assert.Empty(MappedOrganizeReorganizePolicy.SelectKeptOptIns(scanned, [D("KeptFolder")], applied)); + } + + [Fact] + public void SelectKeptOptIns_HandlesEmptyInput() + { + var applied = new HashSet(StringComparer.OrdinalIgnoreCase); + Assert.Empty(MappedOrganizeReorganizePolicy.SelectKeptOptIns([(D("a"), true)], [], applied)); + Assert.Empty(MappedOrganizeReorganizePolicy.SelectKeptOptIns([], [D("a")], applied)); + Assert.Empty(MappedOrganizeReorganizePolicy.SelectKeptOptIns([("", true), (" ", true)], [D("a")], applied)); + } + + [Fact] + public void KeptEntries_SkipAutomaticSorting_ButAConfirmedPreviewClearsTheMark() + { + // Automatic sorting / quick 一键整理 keep skipping 放回桌面 entries… + var images = Mapped("images", DesktopOrganizationCategoryIds.Images); + var widgets = new List { images }; + var kept = new HashSet(StringComparer.OrdinalIgnoreCase); + MappedOrganizeKeepList.Keep(kept, [D("a.png")]); + IReadOnlyList unassigned = MappedOrganizeMembership.FindUnassigned(widgets, [D("a.png"), D("b.png")]); + Assert.Equal(new[] { D("b.png") }, MappedOrganizeKeepList.FilterUnassigned(unassigned, kept)); + + // …while the preview's confirmed groups release the mark and map them. + Assert.True(MappedOrganizeKeepList.Release(kept, [D("A.PNG")])); + MappedOrganizeMembership.Assign(widgets, "images", [D("a.png")]); + Assert.Empty(kept); + Assert.Contains(D("a.png"), MappedOrganizeMembership.GetMembers(images)); + } + + [Fact] + public void ShouldOfferReorganize_ForMappedWidgetsAndTheirTabGroups() + { + WidgetConfig mapped = Mapped("m", DesktopOrganizationCategoryIds.Images); + WidgetConfig tabMate = Plain("tab"); + WidgetConfig loner = Plain("loner"); + var widgets = new List { mapped, tabMate, loner }; + var groups = new List + { + new() { Id = "g", MemberIds = ["m", "tab"] }, + }; + + Assert.True(MappedOrganizeReorganizePolicy.ShouldOfferReorganize(mapped, widgets, groups)); + Assert.True(MappedOrganizeReorganizePolicy.ShouldOfferReorganize(tabMate, widgets, groups)); + Assert.False(MappedOrganizeReorganizePolicy.ShouldOfferReorganize(loner, widgets, groups)); + Assert.False(MappedOrganizeReorganizePolicy.ShouldOfferReorganize(null, widgets, groups)); + Assert.True(MappedOrganizeReorganizePolicy.ShouldOfferReorganize(mapped, null, null)); + Assert.False(MappedOrganizeReorganizePolicy.ShouldOfferReorganize(tabMate, widgets, null)); + } + + [Fact] + public void Wiring_MenusAndPreviewHook() + { + string preview = File.ReadAllText(TestPaths.FromRepository("src/DeskBox/Controls/DesktopOrganizationTaskView.xaml.cs")); + Assert.Contains("IncludeKeptOnDesktopItems(scanned, freshPreview: previous is null);", preview, StringComparison.Ordinal); + + 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); + + Assert.Equal("重新整理桌面", ForkOrganizeModeText.Get(LocalizationService.LanguageChinese, ForkOrganizeModeText.Key.MenuReorganizeDesktop)); + Assert.Equal("Reorganize desktop", ForkOrganizeModeText.Get("en-US", ForkOrganizeModeText.Key.MenuReorganizeDesktop)); + } +}