diff --git a/Directory.Build.targets b/Directory.Build.targets index 3aa08a0e8..22509ad87 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -30,4 +30,56 @@ $(ForkBaseVersion).$(ForkRevision) $(ForkBaseVersion).$(ForkRevision) + + + + true + + + + + + + + + + + + + $([System.Text.RegularExpressions.Regex]::Match('$(ForkGitShaRaw)', '[0-9a-fA-F]{40,64}').Value) + $(ForkGitBranchRaw.Trim()) + + + + + + diff --git a/docs/architecture/mapped-organize.md b/docs/architecture/mapped-organize.md index 87e546191..3399645d9 100644 --- a/docs/architecture/mapped-organize.md +++ b/docs/architecture/mapped-organize.md @@ -87,6 +87,23 @@ 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. +### 拖到桌面 = 放回桌面 + +Dragging items out of a mapped widget and releasing them on the system desktop +(any monitor) runs the same `KeepOnDesktop`. Explorer sees that drop as a +same-folder move (a no-op), so DeskBox decides it at drag completion +(`FileSurfaceContent.MappedDragToDesktop.cs`, hooked once in +`CompleteDragItemsSession`): the window under the cursor must be the shell +desktop (`SHELLDLL_DefView`/`SysListView32` under `Progman`/`WorkerW`, shell +process, not a DeskBox window — `MappedDragToDesktopPolicy.ClassifyTarget`), +the point must be blank desktop (upstream `DesktopBlankHitTest`; a drop on a +folder / Recycle Bin icon stays a real move), no mouse button / Esc held, and +DeskBox must not have handled the drop itself. The put-back entries are then +moved to the release point through the desktop's `IFolderView` +(`SelectAndPositionItems`, `DesktopIconPlacementNativeMethods`), first icon +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. + ## Multi-monitor / sleep Mapped widgets are normal widgets, so the existing monitor binding, @@ -104,6 +121,8 @@ topology profiles and wake recovery apply unchanged. * `DesktopOrganizationTaskView.xaml` (+ `.Actions.cs` one call), `FileSurfaceContent.SelectionAndMenus.cs` (blank menu call, item-menu localizer, 「放回桌面」 interception). +* `FileSurfaceContent.xaml.cs`: one `TryPutBackMappedDragOnDesktop` call in + `CompleteDragItemsSession` (拖到桌面 = 放回桌面). * `FileService.cs`: DeskBox-hidden members stay displayable (3 conditions). * `DesktopAutoOrganizationWatcher.cs`: 只映射 hand-off (one block). * `DesktopOrganizationSettingsSection.xaml`: one host panel for the mode card. @@ -122,5 +141,11 @@ topology profiles and wake recovery apply unchanged. (grouping is per category). * The auto/manual switch for mapped widgets stays in the mapped widget's blank-area menu. +* Moving / copying a mapped item out to another folder keeps the Hidden + attribute DeskBox set (NTFS carries it along); membership and the hidden + ledger are cleaned up by the desktop watcher, but the file stays hidden at + the destination. +* 拖到桌面 = 放回桌面: a drop onto an existing desktop icon is not treated as + put-back; icon placement needs 自动排列图标 off (网格对齐 still snaps it). * Not runtime-verified on a real desktop in this change (CI builds and runs unit tests only). diff --git a/scripts/fork-dev-update.ps1 b/scripts/fork-dev-update.ps1 new file mode 100644 index 000000000..617c13322 --- /dev/null +++ b/scripts/fork-dev-update.ps1 @@ -0,0 +1,72 @@ +# GOXF fork:拉取最新测试代码,本地编译并运行 DeskBox(Debug) +# 用法:在仓库根目录右键「使用 PowerShell 运行」,或: +# powershell -ExecutionPolicy Bypass -File .\scripts\fork-dev-update.ps1 [-Branch dev] +# DeskBox 本地测试版的「更新并重启」也会调用本脚本(带 -GraceSeconds,先等 DeskBox 自己退出)。 +# 出错时窗口不会自动关闭,按回车后关闭。 +param( + [string]$Branch = "dev", + [int]$GraceSeconds = 0 +) +$ErrorActionPreference = "Stop" + +try { + Set-Location (Split-Path $PSScriptRoot -Parent) + + Write-Host "==> 关闭正在运行的 DeskBox" -ForegroundColor Cyan + if ($GraceSeconds -gt 0) { + Wait-Process -Name DeskBox -Timeout $GraceSeconds -ErrorAction SilentlyContinue + } + Get-Process DeskBox -ErrorAction SilentlyContinue | Stop-Process -Force + Start-Sleep -Seconds 1 + + Write-Host "==> 拉取 origin/$Branch" -ForegroundColor Cyan + git fetch origin $Branch + if ($LASTEXITCODE -ne 0) { throw "git fetch 失败" } + git checkout -B $Branch "origin/$Branch" + if ($LASTEXITCODE -ne 0) { throw "git checkout 失败(本地是否有未提交的改动?)" } + git log -1 --format="当前提交:%h %s (%cr)" + + $props = @("-p:Platform=x64", "-p:RuntimeIdentifier=win-x64", "-p:WindowsAppSDKSelfContained=true") + + if (-not (dotnet nuget list source | Select-String "nuget.org")) { + Write-Host "==> 添加 nuget.org 包源" -ForegroundColor Cyan + dotnet nuget add source "https://api.nuget.org/v3/index.json" -n nuget.org + } + Write-Host "==> 还原依赖" -ForegroundColor Cyan + dotnet restore .\DeskBox.sln @props + if ($LASTEXITCODE -ne 0) { throw "restore 失败" } + + Write-Host "==> 编译 Debug" -ForegroundColor Cyan + dotnet build .\src\DeskBox\DeskBox.csproj -c Debug --no-restore @props -v:minimal + if ($LASTEXITCODE -ne 0) { throw "编译失败" } + + $exe = Get-ChildItem .\src\DeskBox\bin -Recurse -Filter DeskBox.exe | Sort-Object LastWriteTime -Descending | Select-Object -First 1 + if (-not $exe) { throw "没找到 DeskBox.exe" } + + # 桌面快捷方式「DeskBox 开发版.lnk」→ 刚编译的 DeskBox.exe(失败不影响启动) + try { + $desktop = [Environment]::GetFolderPath('Desktop') + $lnkPath = Join-Path $desktop "DeskBox 开发版.lnk" + $shell = New-Object -ComObject WScript.Shell + $lnk = $shell.CreateShortcut($lnkPath) + $lnk.TargetPath = $exe.FullName + $lnk.WorkingDirectory = $exe.DirectoryName + $lnk.IconLocation = "$($exe.FullName),0" + $lnk.Description = "DeskBox 本地开发版(dev 分支 Debug 构建)" + $lnk.Save() + Write-Host "==> 已更新桌面快捷方式:$lnkPath" -ForegroundColor Cyan + } + catch { + Write-Host "!! 创建桌面快捷方式失败(不影响运行):$($_.Exception.Message)" -ForegroundColor Yellow + } + + Write-Host "==> 启动 $($exe.FullName)" -ForegroundColor Green + Start-Process $exe.FullName +} +catch { + Write-Host "" + Write-Host "!! 更新失败:$($_.Exception.Message)" -ForegroundColor Red + Write-Host " 修复后可重新运行:powershell -ExecutionPolicy Bypass -File .\scripts\fork-dev-update.ps1" -ForegroundColor Yellow + Read-Host "按回车关闭窗口" + exit 1 +} diff --git a/src/DeskBox/App.ForkDevUpdate.cs b/src/DeskBox/App.ForkDevUpdate.cs new file mode 100644 index 000000000..07b73a4cc --- /dev/null +++ b/src/DeskBox/App.ForkDevUpdate.cs @@ -0,0 +1,114 @@ +using DeskBox.Services; +using H.NotifyIcon.Core; + +namespace DeskBox; + +/// +/// GOXF/DeskBox fork: background loop of the local-test-build update channel. +/// Only runs for a local dev build (): +/// shortly after startup and then every 30 minutes it asks GitHub for the tip +/// of GOXF/DeskBox's dev branch and, once per new commit, shows the same +/// style of update toast (tray balloon as fallback) the regular updater +/// uses. Clicking it opens About, where "update and restart" lives. +/// +public partial class App +{ + private string? _forkDevUpdateNotifiedSha; + + private void ScheduleForkDevUpdateCheck() + { + ForkDevBuild? build = ForkDevBuildInfo.Current; + if (build is null) + { + return; + } + + Log($"[DevUpdate] Local dev build {build.ShortSha} ({build.Branch}) at {build.RepositoryRoot}"); + _ = Task.Run(() => ForkDevUpdateLoopAsync(IsStartupMode ? TimeSpan.FromSeconds(60) : TimeSpan.FromSeconds(15))); + } + + private async Task ForkDevUpdateLoopAsync(TimeSpan initialDelay) + { + DateTimeOffset nextCheckAt = DateTimeOffset.Now + initialDelay; + while (!IsShuttingDown) + { + // Wall-clock deadline, re-evaluated after every wake (timers + // pause during sleep), same as the regular update loop. + TimeSpan remaining = nextCheckAt - DateTimeOffset.Now; + if (remaining > TimeSpan.Zero) + { + await Task.Delay(remaining < TimeSpan.FromMinutes(5) ? remaining : TimeSpan.FromMinutes(5)); + continue; + } + + try + { + ForkDevUpdateInfo? info = await ForkDevUpdateService.CheckAsync(); + if (info is { HasUpdate: true } && !IsShuttingDown) + { + Log($"[DevUpdate] dev has {info.RemoteShortSha} (local {info.LocalShortSha})"); + UiDispatcherQueue?.TryEnqueue(() => ShowForkDevUpdateNotification(info)); + } + } + catch (Exception ex) + { + Log($"[DevUpdate] Background check crashed: {ex.GetType().Name}"); + } + + nextCheckAt = DateTimeOffset.Now + ForkDevUpdateService.CheckInterval; + } + } + + private void ShowForkDevUpdateNotification(ForkDevUpdateInfo info) + { + if (IsShuttingDown || + string.Equals(_forkDevUpdateNotifiedSha, info.RemoteSha, StringComparison.Ordinal) || + !SettingsService.Settings.Core.ShowUpdateToastNotification) + { + return; + } + + (string title, string message) = ForkDevUpdateService.FormatNotification(LocalizationService.CurrentCultureName, info); + // {type=update} without an action opens Settings → About, where the + // "update and restart" button is. + var openAboutArguments = new Dictionary + { + ["type"] = "update" + }; + if (_nativeNotificationService?.TryShow( + title, + message, + openAboutArguments, + options: new NativeAppNotificationOptions( + Tag: "dev-update-available", + Group: "update")) == true) + { + _forkDevUpdateNotifiedSha = info.RemoteSha; + return; + } + + if (_trayIcon is null) + { + return; + } + + try + { + _trayIcon.ShowNotification( + title, + message, + NotificationIcon.Info, + customIconHandle: null, + largeIcon: true, + sound: false, + respectQuietTime: true, + realtime: false, + timeout: TimeSpan.FromSeconds(8)); + _forkDevUpdateNotifiedSha = info.RemoteSha; + } + catch (Exception ex) + { + Log($"[DevUpdate] Tray notification failed: {ex.Message}"); + } + } +} diff --git a/src/DeskBox/App.xaml.cs b/src/DeskBox/App.xaml.cs index dc973b810..723f45f6b 100644 --- a/src/DeskBox/App.xaml.cs +++ b/src/DeskBox/App.xaml.cs @@ -1769,6 +1769,7 @@ await RunOptionalStartupStepAsync( () => ShowReleaseNotesAfterUpdateOnce()); RunOptionalStartupStep("background-update-check", ScheduleBackgroundUpdateCheck); + RunOptionalStartupStep("fork-dev-update-check", ScheduleForkDevUpdateCheck); // GOXF fork: local dev builds only RunOptionalStartupStep( "update-installer-prune", // Interface-typed property: pruning only exists on the diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs new file mode 100644 index 000000000..5ee107ea2 --- /dev/null +++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs @@ -0,0 +1,71 @@ +using DeskBox.Models; +using DeskBox.Platform; +using DeskBox.Services; + +namespace DeskBox.Controls.WidgetContents; + +/// +/// GOXF fork, 「映射整理」: dragging items out of a mapped widget and dropping +/// 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. +/// +public sealed partial class FileSurfaceContent +{ + private const int VirtualKeyLeftButton = 0x01; + private const int VirtualKeyRightButton = 0x02; + private const int VirtualKeyEscape = 0x1B; + + /// Returns true when the completed drag was turned into 「放回桌面」. + private bool TryPutBackMappedDragOnDesktop(string[] draggedPaths, bool handledInternally) + { + if (handledInternally || + draggedPaths.Length == 0 || + !ViewModel.IsMappedOrganizeWidget || + MappedOrganizeService.Current is not { } service || + !Win32Helper.GetCursorPos(out Win32Helper.POINT cursor)) + { + 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))) + { + return false; + } + + IReadOnlyList paths = MappedDragToDesktopPolicy.ComputePutBackPaths( + draggedPaths, + path => File.Exists(path) || Directory.Exists(path), + MappedOrganizeService.IsDesktopEntryPath); + if (paths.Count == 0) + { + return false; + } + + int kept = service.KeepOnDesktop(paths); + App.Log( + $"[MappedOrganize] Drag to desktop: put back {kept}/{draggedPaths.Length} " + + $"widget={WidgetId} target={drop.Kind} at={cursor.X},{cursor.Y}."); + if (kept <= 0) + { + return false; + } + + MappedDragToDesktopPlacement.PlaceInBackground(paths, drop); + ShowFeedback(new WidgetFeedbackRequest( + ForkOrganizeModeText.Format(ForkOrganizeModeText.Key.KeptOnDesktopFormat, kept), + WidgetFeedbackSeverity.Success, + "mapped-keep-desktop")); + return true; + } +} diff --git a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs index d45156974..66a7ce82e 100644 --- a/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs +++ b/src/DeskBox/Controls/WidgetContents/FileSurfaceContent.xaml.cs @@ -1665,6 +1665,12 @@ private void CompleteDragItemsSession( return; } + // GOXF fork: a mapped widget's drag released on the desktop is 「放回桌面」. + if (TryPutBackMappedDragOnDesktop(movedPaths, handledAsStackMembership)) + { + return; + } + bool allowReleaseRecovery = ShouldRecoverUnhandledSourceDrop( dropResult, handledAsStackMembership); if (allowReleaseRecovery && fromStackPopover && diff --git a/src/DeskBox/Platform/DesktopIconPlacementNativeMethods.cs b/src/DeskBox/Platform/DesktopIconPlacementNativeMethods.cs new file mode 100644 index 000000000..60d7cac0a --- /dev/null +++ b/src/DeskBox/Platform/DesktopIconPlacementNativeMethods.cs @@ -0,0 +1,347 @@ +using System.Runtime.InteropServices; + +namespace DeskBox.Platform; + +/// +/// GOXF fork, 「映射整理」: moves desktop icons to a given spot through the +/// desktop's own IFolderView (IShellWindows.FindWindowSW(SWC_DESKTOP) → +/// IServiceProvider(SID_STopLevelBrowser) → IShellBrowser.QueryActiveShellView +/// → IFolderView.SelectAndPositionItems), the documented shell route for +/// positioning desktop items. Vtable slots are called through unmanaged +/// function pointers (no RCW, NativeAOT-safe); slot numbers follow +/// shobjidl_core.h / exdisp.h / servprov.h and count IUnknown as 0-2. +/// Must run on an STA thread. Every call is best effort. +/// +internal static unsafe partial class DesktopIconPlacementNativeMethods +{ + internal readonly record struct ViewInfo(int SpacingX, int SpacingY, bool AutoArrange); + + private const uint ClsctxInprocServer = 0x1; + private const uint ClsctxLocalServer = 0x4; + private const ushort VtI4 = 3; + private const int CsidlDesktop = 0; + private const int SwcDesktop = 8; + private const int SwfoNeedDispatch = 1; + private const uint SvgioAllView = 2; + private const uint ShgdnForParsing = 0x8000; + private const uint SvsiPositionItem = 0x80; + private const int ShcneUpdateItem = 0x2000; + private const uint ShcnfPathW = 0x0005; + + // IShellWindows (IDispatch: 3-6) 7 get_Count, 8 Item, 9 _NewEnum, 10 Register, + // 11 RegisterPending, 12 Revoke, 13 OnNavigate, 14 OnActivated, 15 FindWindowSW. + private const int ShellWindowsFindWindowSwSlot = 15; + + // IServiceProvider 3 QueryService. + private const int ServiceProviderQueryServiceSlot = 3; + + // IShellBrowser (IOleWindow: 3-4) 5 InsertMenusSB ... 15 QueryActiveShellView. + private const int ShellBrowserQueryActiveShellViewSlot = 15; + + // IFolderView 3 GetCurrentViewMode, 4 SetCurrentViewMode, 5 GetFolder, 6 Item, + // 7 ItemCount, 8 Items, 9 GetSelectionMarkedItem, 10 GetFocusedItem, + // 11 GetItemPosition, 12 GetSpacing, 13 GetDefaultSpacing, 14 GetAutoArrange, + // 15 SelectItem, 16 SelectAndPositionItems. + private const int FolderViewGetFolderSlot = 5; + private const int FolderViewItemSlot = 6; + private const int FolderViewItemCountSlot = 7; + private const int FolderViewGetSpacingSlot = 12; + private const int FolderViewGetAutoArrangeSlot = 14; + private const int FolderViewSelectAndPositionItemsSlot = 16; + + // IShellFolder 3 ParseDisplayName ... 11 GetDisplayNameOf. + private const int ShellFolderGetDisplayNameOfSlot = 11; + + // STRRET is a UINT followed by a 260-byte union (pointer aligned). + private const int StrRetSize = 272; + private const int PathBufferChars = 1024; + + private static readonly Guid ClsidShellWindows = new("9BA05972-F6A8-11CF-A442-00A0C90A8F39"); + private static readonly Guid IidShellWindows = new("85CB6900-4D95-11CF-960C-0080C7F4EE85"); + private static readonly Guid IidServiceProvider = new("6D5140C1-7436-11CE-8034-00AA006009FA"); + private static readonly Guid SidTopLevelBrowser = new("4C96BE40-915C-11CF-99D3-00AA004AE837"); + private static readonly Guid IidShellBrowser = new("000214E2-0000-0000-C000-000000000046"); + private static readonly Guid IidFolderView = new("CDE725B0-CCC9-4519-917E-325D72FAB4CE"); + private static readonly Guid IidShellFolder = new("000214E6-0000-0000-C000-000000000046"); + + [LibraryImport("ole32.dll")] + private static partial int CoCreateInstance(ref Guid clsid, IntPtr outer, uint context, ref Guid iid, out IntPtr instance); + + [LibraryImport("ole32.dll")] + private static partial void CoTaskMemFree(IntPtr memory); + + [LibraryImport("shlwapi.dll", EntryPoint = "StrRetToBufW")] + private static partial int StrRetToBuf(IntPtr strRet, IntPtr pidl, IntPtr buffer, uint bufferChars); + + [LibraryImport("shell32.dll", EntryPoint = "SHChangeNotify", StringMarshalling = StringMarshalling.Utf16)] + private static partial void SHChangeNotifyPath(int eventId, uint flags, string path, IntPtr item2); + + /// Asks the shell to re-read entries whose attributes DeskBox just changed. + internal static void NotifyUpdated(IEnumerable paths) + { + foreach (string path in paths) + { + try + { + SHChangeNotifyPath(ShcneUpdateItem, ShcnfPathW, path, IntPtr.Zero); + } + catch (Exception) + { + // Best effort. + } + } + } + + /// Reads the desktop view's icon spacing and auto-arrange state. + internal static bool TryGetViewInfo(out ViewInfo info) + { + info = default; + IntPtr view = AcquireDesktopFolderView(); + if (view == IntPtr.Zero) + { + return false; + } + + try + { + Win32Helper.POINT spacing = default; + int hr = ((delegate* unmanaged[Stdcall])Slot(view, FolderViewGetSpacingSlot))(view, &spacing); + int autoArrange = ((delegate* unmanaged[Stdcall])Slot(view, FolderViewGetAutoArrangeSlot))(view); + info = new ViewInfo(hr >= 0 ? spacing.X : 0, hr >= 0 ? spacing.Y : 0, autoArrange == 0); + return true; + } + finally + { + Marshal.Release(view); + } + } + + /// + /// Positions the desktop items whose parsing paths match + /// at the matching client-coordinate origins. Returns how many items were + /// found in the view and positioned (0 when the view is not ready yet). + /// + internal static int TryPositionItems(IReadOnlyList paths, IReadOnlyList<(int X, int Y)> origins) + { + if (paths.Count == 0 || paths.Count != origins.Count) + { + return 0; + } + + IntPtr view = AcquireDesktopFolderView(); + if (view == IntPtr.Zero) + { + return 0; + } + + IntPtr folder = IntPtr.Zero; + var pidls = new IntPtr[paths.Count]; + IntPtr strRet = IntPtr.Zero; + IntPtr buffer = IntPtr.Zero; + try + { + Guid iidFolder = IidShellFolder; + int hr = ((delegate* unmanaged[Stdcall])Slot(view, FolderViewGetFolderSlot))(view, &iidFolder, &folder); + if (hr < 0 || folder == IntPtr.Zero) + { + return 0; + } + + int count = 0; + hr = ((delegate* unmanaged[Stdcall])Slot(view, FolderViewItemCountSlot))(view, SvgioAllView, &count); + if (hr < 0 || count <= 0) + { + return 0; + } + + var wanted = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (int i = 0; i < paths.Count; i++) + { + wanted.TryAdd(Normalize(paths[i]), i); + } + + strRet = Marshal.AllocHGlobal(StrRetSize); + buffer = Marshal.AllocHGlobal(PathBufferChars * sizeof(char)); + int found = 0; + for (int index = 0; index < count && found < wanted.Count; index++) + { + IntPtr pidl = IntPtr.Zero; + hr = ((delegate* unmanaged[Stdcall])Slot(view, FolderViewItemSlot))(view, index, &pidl); + if (hr < 0 || pidl == IntPtr.Zero) + { + continue; + } + + string? parsingName = GetParsingName(folder, pidl, strRet, buffer); + if (parsingName is not null && + wanted.TryGetValue(Normalize(parsingName), out int slot) && + pidls[slot] == IntPtr.Zero) + { + pidls[slot] = pidl; + found++; + } + else + { + CoTaskMemFree(pidl); + } + } + + if (found == 0) + { + return 0; + } + + var foundPidls = new IntPtr[found]; + var foundPoints = new Win32Helper.POINT[found]; + int next = 0; + for (int i = 0; i < pidls.Length; i++) + { + if (pidls[i] != IntPtr.Zero) + { + foundPidls[next] = pidls[i]; + foundPoints[next] = new Win32Helper.POINT { X = origins[i].X, Y = origins[i].Y }; + next++; + } + } + + fixed (IntPtr* pidlArray = foundPidls) + fixed (Win32Helper.POINT* pointArray = foundPoints) + { + hr = ((delegate* unmanaged[Stdcall])Slot(view, FolderViewSelectAndPositionItemsSlot))( + view, (uint)found, pidlArray, pointArray, SvsiPositionItem); + } + + return hr >= 0 ? found : 0; + } + finally + { + foreach (IntPtr pidl in pidls) + { + if (pidl != IntPtr.Zero) + { + CoTaskMemFree(pidl); + } + } + + if (strRet != IntPtr.Zero) + { + Marshal.FreeHGlobal(strRet); + } + + if (buffer != IntPtr.Zero) + { + Marshal.FreeHGlobal(buffer); + } + + if (folder != IntPtr.Zero) + { + Marshal.Release(folder); + } + + Marshal.Release(view); + } + } + + private static string? GetParsingName(IntPtr folder, IntPtr pidl, IntPtr strRet, IntPtr buffer) + { + new Span((void*)strRet, StrRetSize).Clear(); + int hr = ((delegate* unmanaged[Stdcall])Slot(folder, ShellFolderGetDisplayNameOfSlot))( + folder, pidl, ShgdnForParsing, strRet); + if (hr < 0) + { + return null; + } + + // StrRetToBuf frees an STRRET_WSTR allocation itself. + return StrRetToBuf(strRet, pidl, buffer, PathBufferChars) >= 0 + ? Marshal.PtrToStringUni(buffer) + : null; + } + + private static IntPtr AcquireDesktopFolderView() + { + IntPtr shellWindows = IntPtr.Zero; + IntPtr dispatch = IntPtr.Zero; + IntPtr serviceProvider = IntPtr.Zero; + IntPtr browser = IntPtr.Zero; + IntPtr shellView = IntPtr.Zero; + try + { + Guid clsid = ClsidShellWindows; + Guid iid = IidShellWindows; + if (CoCreateInstance(ref clsid, IntPtr.Zero, ClsctxLocalServer | ClsctxInprocServer, ref iid, out shellWindows) < 0 || + shellWindows == IntPtr.Zero) + { + return IntPtr.Zero; + } + + // VARIANT is 16 bytes on 32-bit and 24 bytes on 64-bit; 24 covers both. + byte* location = stackalloc byte[24]; + byte* empty = stackalloc byte[24]; + new Span(location, 24).Clear(); + new Span(empty, 24).Clear(); + *(ushort*)location = VtI4; + *(int*)(location + 8) = CsidlDesktop; + int hwnd = 0; + int hr = ((delegate* unmanaged[Stdcall])Slot(shellWindows, ShellWindowsFindWindowSwSlot))( + shellWindows, location, empty, SwcDesktop, &hwnd, SwfoNeedDispatch, &dispatch); + if (hr != 0 || dispatch == IntPtr.Zero) + { + return IntPtr.Zero; + } + + Guid iidServiceProvider = IidServiceProvider; + if (ComVtable.QueryInterface(dispatch, ref iidServiceProvider, out serviceProvider) < 0 || serviceProvider == IntPtr.Zero) + { + return IntPtr.Zero; + } + + Guid sid = SidTopLevelBrowser; + Guid iidBrowser = IidShellBrowser; + hr = ((delegate* unmanaged[Stdcall])Slot(serviceProvider, ServiceProviderQueryServiceSlot))( + serviceProvider, &sid, &iidBrowser, &browser); + if (hr < 0 || browser == IntPtr.Zero) + { + return IntPtr.Zero; + } + + hr = ((delegate* unmanaged[Stdcall])Slot(browser, ShellBrowserQueryActiveShellViewSlot))(browser, &shellView); + if (hr < 0 || shellView == IntPtr.Zero) + { + return IntPtr.Zero; + } + + Guid iidFolderView = IidFolderView; + return ComVtable.QueryInterface(shellView, ref iidFolderView, out IntPtr folderView) >= 0 ? folderView : IntPtr.Zero; + } + catch (Exception) + { + return IntPtr.Zero; + } + finally + { + foreach (IntPtr unknown in new[] { shellView, browser, serviceProvider, dispatch, shellWindows }) + { + if (unknown != IntPtr.Zero) + { + Marshal.Release(unknown); + } + } + } + } + + private static IntPtr Slot(IntPtr comObject, int slot) => + ((IntPtr*)*(IntPtr*)comObject)[slot]; + + private static string Normalize(string path) + { + try + { + return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + } + catch (Exception) + { + return path; + } + } +} diff --git a/src/DeskBox/Services/ForkDevBuildInfo.cs b/src/DeskBox/Services/ForkDevBuildInfo.cs new file mode 100644 index 000000000..9b7e4fa42 --- /dev/null +++ b/src/DeskBox/Services/ForkDevBuildInfo.cs @@ -0,0 +1,265 @@ +using System.Reflection; +using System.Text.RegularExpressions; + +namespace DeskBox.Services; + +/// +/// GOXF/DeskBox fork: identifies a *local development build* — a DeskBox.exe +/// compiled inside a git clone of the fork by scripts/fork-dev-update.ps1 — +/// and the git commit it was built from. Installed builds (Program Files, +/// %LOCALAPPDATA%\Programs, …) never sit inside such a clone, so every +/// local-test-channel feature stays off for them. +/// +/// The commit sha / branch are embedded at build time by +/// Directory.Build.targets (AssemblyMetadata "ForkGitSha" / "ForkGitBranch", +/// Debug builds only). When they are missing the sha is read from the +/// clone's .git directory at runtime. +/// +public sealed record ForkDevBuild(string RepositoryRoot, string LocalSha, string Branch) +{ + public string ScriptPath => Path.Combine(RepositoryRoot, ForkDevBuildInfo.ScriptRelativePath); + public string ShortSha => ForkDevBuildInfo.ShortSha(LocalSha); +} + +public static partial class ForkDevBuildInfo +{ + public static readonly string ScriptRelativePath = Path.Combine("scripts", "fork-dev-update.ps1"); + public const string DevBranch = "dev"; + public const string ShaMetadataKey = "ForkGitSha"; + public const string BranchMetadataKey = "ForkGitBranch"; + + private static readonly Lazy s_current = new(DetectCurrent); + + /// The running process' local dev build, or null for every installed build. + public static ForkDevBuild? Current => s_current.Value; + + public static bool IsLocalDevBuild => Current is not null; + + private static ForkDevBuild? DetectCurrent() + { + try + { + return Detect(AppContext.BaseDirectory, typeof(ForkDevBuildInfo).Assembly); + } + catch (Exception ex) + { + App.Log($"[DevUpdate] Local build detection failed: {ex.GetType().Name}"); + return null; + } + } + + internal static ForkDevBuild? Detect(string? executableDirectory, Assembly? assembly) + { + string? root = FindRepositoryRoot(executableDirectory); + if (root is null) + { + return null; + } + + string? sha = NormalizeSha(GetAssemblyMetadata(assembly, ShaMetadataKey)); + string? branch = GetAssemblyMetadata(assembly, BranchMetadataKey); + if (sha is null) + { + (sha, string? headBranch) = ReadHeadFromGitDirectory(root); + branch ??= headBranch; + } + + return sha is null + ? null + : new ForkDevBuild(root, sha, string.IsNullOrWhiteSpace(branch) ? string.Empty : branch.Trim()); + } + + /// + /// Walks up from (the exe folder) to the + /// first directory that holds BOTH a ".git" entry (directory, or file for + /// worktrees) and scripts/fork-dev-update.ps1. Null when none exists. + /// + public static string? FindRepositoryRoot(string? startDirectory) + { + if (string.IsNullOrWhiteSpace(startDirectory)) + { + return null; + } + + DirectoryInfo? current; + try + { + current = new DirectoryInfo(Path.GetFullPath(startDirectory)); + } + catch (Exception) + { + return null; + } + + for (int depth = 0; current is not null && depth < 32; depth++, current = current.Parent) + { + string gitPath = Path.Combine(current.FullName, ".git"); + if ((Directory.Exists(gitPath) || File.Exists(gitPath)) && + File.Exists(Path.Combine(current.FullName, ScriptRelativePath))) + { + return current.FullName; + } + } + + return null; + } + + private static string? GetAssemblyMetadata(Assembly? assembly, string key) + { + if (assembly is null) + { + return null; + } + + foreach (AssemblyMetadataAttribute attribute in assembly.GetCustomAttributes()) + { + if (string.Equals(attribute.Key, key, StringComparison.Ordinal) && + !string.IsNullOrWhiteSpace(attribute.Value)) + { + return attribute.Value.Trim(); + } + } + + return null; + } + + /// + /// Reads HEAD from the clone: "ref: refs/heads/x" → loose ref file or + /// packed-refs; a detached HEAD is the sha itself. Handles a ".git" file + /// ("gitdir: …") for worktrees, where refs live in the common dir. + /// + internal static (string? Sha, string? Branch) ReadHeadFromGitDirectory(string repositoryRoot) + { + try + { + string? gitDir = ResolveGitDirectory(repositoryRoot); + if (gitDir is null) + { + return (null, null); + } + + string headPath = Path.Combine(gitDir, "HEAD"); + if (!File.Exists(headPath)) + { + return (null, null); + } + + string head = File.ReadAllText(headPath).Trim(); + if (!head.StartsWith("ref:", StringComparison.Ordinal)) + { + return (NormalizeSha(head), null); + } + + string refName = head[4..].Trim(); + string? branch = refName.StartsWith("refs/heads/", StringComparison.Ordinal) + ? refName["refs/heads/".Length..] + : null; + + string commonDir = gitDir; + string commonDirFile = Path.Combine(gitDir, "commondir"); + if (File.Exists(commonDirFile)) + { + string relative = File.ReadAllText(commonDirFile).Trim(); + commonDir = Path.GetFullPath(Path.Combine(gitDir, relative)); + } + + foreach (string dir in new[] { gitDir, commonDir }) + { + string loose = Path.Combine(dir, refName.Replace('/', Path.DirectorySeparatorChar)); + if (File.Exists(loose)) + { + string? looseSha = NormalizeSha(File.ReadAllText(loose)); + if (looseSha is not null) + { + return (looseSha, branch); + } + } + } + + string packed = Path.Combine(commonDir, "packed-refs"); + if (File.Exists(packed)) + { + foreach (string line in File.ReadLines(packed)) + { + int space = line.IndexOf(' '); + if (space > 0 && string.Equals(line[(space + 1)..].Trim(), refName, StringComparison.Ordinal)) + { + return (NormalizeSha(line[..space]), branch); + } + } + } + + return (null, branch); + } + catch (Exception) + { + return (null, null); + } + } + + private static string? ResolveGitDirectory(string repositoryRoot) + { + string gitPath = Path.Combine(repositoryRoot, ".git"); + if (Directory.Exists(gitPath)) + { + return gitPath; + } + + if (File.Exists(gitPath)) + { + string content = File.ReadAllText(gitPath).Trim(); + if (content.StartsWith("gitdir:", StringComparison.OrdinalIgnoreCase)) + { + string target = content["gitdir:".Length..].Trim(); + string full = Path.GetFullPath(Path.IsPathRooted(target) ? target : Path.Combine(repositoryRoot, target)); + return Directory.Exists(full) ? full : null; + } + } + + return null; + } + + [GeneratedRegex("^[0-9a-f]{7,64}$")] + private static partial Regex ShaPattern(); + + /// Lower-cased hex sha (7–64 chars), or null when the text is not one. + public static string? NormalizeSha(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + + string trimmed = value.Trim().ToLowerInvariant(); + return ShaPattern().IsMatch(trimmed) ? trimmed : null; + } + + public static string ShortSha(string? sha) + { + string? normalized = NormalizeSha(sha); + if (normalized is null) + { + return string.Empty; + } + + return normalized.Length > 7 ? normalized[..7] : normalized; + } + + /// + /// True when the remote tip differs from the local build's commit. A + /// short local sha (prefix) that matches the remote counts as the same + /// commit. Unknown / malformed shas never report an update. + /// + public static bool IsRemoteNewer(string? localSha, string? remoteSha) + { + string? local = NormalizeSha(localSha); + string? remote = NormalizeSha(remoteSha); + if (local is null || remote is null) + { + return false; + } + + return !(remote.StartsWith(local, StringComparison.Ordinal) || + local.StartsWith(remote, StringComparison.Ordinal)); + } +} diff --git a/src/DeskBox/Services/ForkDevUpdateService.cs b/src/DeskBox/Services/ForkDevUpdateService.cs new file mode 100644 index 000000000..da9c53917 --- /dev/null +++ b/src/DeskBox/Services/ForkDevUpdateService.cs @@ -0,0 +1,239 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace DeskBox.Services; + +/// Latest dev-branch commit compared against the local dev build. +public sealed record ForkDevUpdateInfo( + string LocalSha, + string RemoteSha, + string RemoteTitle, + bool HasUpdate) +{ + public string LocalShortSha => ForkDevBuildInfo.ShortSha(LocalSha); + public string RemoteShortSha => ForkDevBuildInfo.ShortSha(RemoteSha); +} + +/// +/// GOXF/DeskBox fork: "local test build" update channel. Only active for a +/// local dev build; asks GitHub +/// (anonymous) for the tip of GOXF/DeskBox's dev branch and, on request, +/// hands over to scripts/fork-dev-update.ps1 (pull → Debug build → relaunch). +/// Every network failure yields null: this channel never surfaces errors. +/// +public static class ForkDevUpdateService +{ + public const string DevBranchCommitApiUrl = "https://api.github.com/repos/GOXF/DeskBox/commits/dev"; + public static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(30); + + private static readonly HttpClient s_httpClient = CreateHttpClient(); + + private static HttpClient CreateHttpClient() + { + var client = new HttpClient + { + Timeout = TimeSpan.FromSeconds(10) + }; + client.DefaultRequestHeaders.UserAgent.ParseAdd($"DeskBox-dev/{AppUpdateService.GetCurrentAppVersion()}"); + client.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json"); + return client; + } + + /// Null when this is not a local dev build or the check failed. + public static Task CheckAsync(CancellationToken cancellationToken = default) + { + ForkDevBuild? build = ForkDevBuildInfo.Current; + return build is null + ? Task.FromResult(null) + : CheckAsync(build.LocalSha, s_httpClient, DevBranchCommitApiUrl, cancellationToken); + } + + internal static async Task CheckAsync( + string localSha, + HttpClient httpClient, + string commitApiUrl, + CancellationToken cancellationToken) + { + try + { + using var response = await httpClient.GetAsync(commitApiUrl, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + return null; + } + + string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + return ParseCommit(localSha, json); + } + catch (Exception ex) + { + App.Log($"[DevUpdate] dev branch check skipped: {ex.GetType().Name}"); + return null; + } + } + + /// Parses GET /repos/{o}/{r}/commits/{ref}: "sha" + first line of "commit.message". + internal static ForkDevUpdateInfo? ParseCommit(string localSha, string json) + { + try + { + using var document = JsonDocument.Parse(json); + JsonElement root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("sha", out JsonElement shaElement) || + shaElement.ValueKind != JsonValueKind.String) + { + return null; + } + + string? remoteSha = ForkDevBuildInfo.NormalizeSha(shaElement.GetString()); + string? local = ForkDevBuildInfo.NormalizeSha(localSha); + if (remoteSha is null || local is null) + { + return null; + } + + string title = string.Empty; + if (root.TryGetProperty("commit", out JsonElement commit) && + commit.ValueKind == JsonValueKind.Object && + commit.TryGetProperty("message", out JsonElement message) && + message.ValueKind == JsonValueKind.String) + { + title = FirstLine(message.GetString()); + } + + return new ForkDevUpdateInfo(local, remoteSha, title, ForkDevBuildInfo.IsRemoteNewer(local, remoteSha)); + } + catch (JsonException) + { + return null; + } + } + + private static string FirstLine(string? text) + { + if (string.IsNullOrEmpty(text)) + { + return string.Empty; + } + + int newline = text.IndexOfAny(['\r', '\n']); + string line = (newline >= 0 ? text[..newline] : text).Trim(); + return line.Length > 120 ? line[..119] + "…" : line; + } + + /// + /// powershell.exe arguments for the update script. -GraceSeconds lets + /// DeskBox finish its own clean shutdown before the script force-kills + /// whatever is left. + /// + internal static ProcessStartInfo BuildScriptStartInfo(ForkDevBuild build) + { + var startInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + // Shell-execute => its own visible console window, independent of + // DeskBox's lifetime, so the build progress stays on screen. + UseShellExecute = true, + WorkingDirectory = build.RepositoryRoot, + Arguments = $"-NoProfile -ExecutionPolicy Bypass -File \"{build.ScriptPath}\" -Branch {ForkDevBuildInfo.DevBranch} -GraceSeconds 15", + }; + return startInfo; + } + + /// Starts the update script in its own window. The caller then exits DeskBox. + public static bool TryStartUpdateScript(out string? error) + { + error = null; + ForkDevBuild? build = ForkDevBuildInfo.Current; + if (build is null) + { + error = "not a local dev build"; + return false; + } + + if (!File.Exists(build.ScriptPath)) + { + error = $"missing {build.ScriptPath}"; + return false; + } + + try + { + using Process? process = Process.Start(BuildScriptStartInfo(build)); + if (process is null) + { + error = "powershell.exe did not start"; + return false; + } + + App.Log($"[DevUpdate] Update script started (pid {process.Id}) from {build.RepositoryRoot}"); + return true; + } + catch (Exception ex) + { + error = ex.Message; + App.Log($"[DevUpdate] Update script failed to start: {ex}"); + return false; + } + } + + internal static string FormatStatus(string? cultureName, ForkDevUpdateInfo info) + { + bool zhHans = cultureName == LocalizationService.LanguageChinese; + bool zhHant = cultureName == LocalizationService.LanguageChineseTraditional; + string title = string.IsNullOrWhiteSpace(info.RemoteTitle) ? string.Empty : " " + info.RemoteTitle; + if (info.HasUpdate) + { + return zhHans + ? $"本地测试版:当前 {info.LocalShortSha},有新提交 {info.RemoteShortSha}{title}" + : zhHant + ? $"本地測試版:目前 {info.LocalShortSha},有新提交 {info.RemoteShortSha}{title}" + : $"Local test build: current {info.LocalShortSha}, new commit {info.RemoteShortSha}{title}"; + } + + return zhHans + ? $"本地测试版:当前 {info.LocalShortSha},已是 dev 最新提交" + : zhHant + ? $"本地測試版:目前 {info.LocalShortSha},已是 dev 最新提交" + : $"Local test build: current {info.LocalShortSha}, up to date with dev"; + } + + internal static string FormatLocalOnlyStatus(string? cultureName, string localShortSha) + { + return cultureName switch + { + LocalizationService.LanguageChinese => $"本地测试版:当前 {localShortSha}(暂未取到 dev 最新提交)", + LocalizationService.LanguageChineseTraditional => $"本地測試版:目前 {localShortSha}(暫未取得 dev 最新提交)", + _ => $"Local test build: current {localShortSha} (dev tip not fetched yet)", + }; + } + + internal static string FormatUpdateButton(string? cultureName) => cultureName switch + { + LocalizationService.LanguageChinese => "更新并重启", + LocalizationService.LanguageChineseTraditional => "更新並重新啟動", + _ => "Update and restart", + }; + + internal static (string Title, string Message) FormatNotification(string? cultureName, ForkDevUpdateInfo info) + { + string title = string.IsNullOrWhiteSpace(info.RemoteTitle) ? string.Empty : " " + info.RemoteTitle; + return cultureName switch + { + LocalizationService.LanguageChinese => + ("DeskBox 本地测试版有新提交", $"dev 有新提交 {info.RemoteShortSha}{title}(当前 {info.LocalShortSha})。在 设置 → 关于 → 更新详情 点「更新并重启」。"), + LocalizationService.LanguageChineseTraditional => + ("DeskBox 本地測試版有新提交", $"dev 有新提交 {info.RemoteShortSha}{title}(目前 {info.LocalShortSha})。在 設定 → 關於 → 更新詳情 點「更新並重新啟動」。"), + _ => + ("DeskBox local test build: new commit", $"dev has {info.RemoteShortSha}{title} (current {info.LocalShortSha}). Settings → About → Update details → Update and restart."), + }; + } + + internal static string FormatStartFailed(string? cultureName, string? error) => cultureName switch + { + LocalizationService.LanguageChinese => $"无法启动更新脚本:{error}", + LocalizationService.LanguageChineseTraditional => $"無法啟動更新腳本:{error}", + _ => $"Could not start the update script: {error}", + }; +} diff --git a/src/DeskBox/Services/MappedDragToDesktopPlacement.cs b/src/DeskBox/Services/MappedDragToDesktopPlacement.cs new file mode 100644 index 000000000..ffdccf5aa --- /dev/null +++ b/src/DeskBox/Services/MappedDragToDesktopPlacement.cs @@ -0,0 +1,84 @@ +using DeskBox.Platform; + +namespace DeskBox.Services; + +/// +/// GOXF fork, 「映射整理」: after 「拖到桌面 = 放回桌面」 un-hides the entries, +/// moves their desktop icons to where the drag was released. Explorer adds a +/// newly visible entry asynchronously, so a short-lived STA worker polls the +/// desktop view for a few seconds. Skipped when the desktop uses 自动排列图标 +/// (the shell ignores positions then); best effort throughout. +/// +internal static class MappedDragToDesktopPlacement +{ + private const int Attempts = 15; + private static readonly TimeSpan AttemptDelay = TimeSpan.FromMilliseconds(200); + + internal static void PlaceInBackground(IReadOnlyList paths, MappedDesktopDropPoint drop) + { + if (paths.Count == 0 || drop.ListView == IntPtr.Zero) + { + return; + } + + string[] snapshot = paths.ToArray(); + try + { + var thread = new Thread(() => Run(snapshot, drop)) + { + IsBackground = true, + Name = "DeskBox mapped drag placement", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Could not start desktop icon placement: {ex.Message}"); + } + } + + private static void Run(string[] paths, MappedDesktopDropPoint drop) + { + try + { + DesktopIconPlacementNativeMethods.NotifyUpdated(paths); + if (!DesktopIconPlacementNativeMethods.TryGetViewInfo(out DesktopIconPlacementNativeMethods.ViewInfo info)) + { + App.Log("[MappedOrganize] Desktop view unavailable; put-back icons keep the shell's position."); + return; + } + + if (info.AutoArrange) + { + App.Log("[MappedOrganize] Desktop auto-arrange is on; put-back icons keep the shell's position."); + return; + } + + IReadOnlyList<(int X, int Y)> origins = MappedDragToDesktopPolicy.ComputeIconOrigins( + drop.ClientX, + drop.ClientY, + info.SpacingX, + info.SpacingY, + paths.Length, + drop.AreaTopClient, + drop.AreaBottomClient); + int positioned = 0; + for (int attempt = 0; attempt < Attempts; attempt++) + { + Thread.Sleep(AttemptDelay); + positioned = Math.Max(positioned, DesktopIconPlacementNativeMethods.TryPositionItems(paths, origins)); + if (positioned >= paths.Length) + { + break; + } + } + + App.Log($"[MappedOrganize] Positioned {positioned}/{paths.Length} put-back icons at the drop point."); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Desktop icon placement failed: {ex.Message}"); + } + } +} diff --git a/src/DeskBox/Services/MappedDragToDesktopPolicy.cs b/src/DeskBox/Services/MappedDragToDesktopPolicy.cs new file mode 100644 index 000000000..3831cb13c --- /dev/null +++ b/src/DeskBox/Services/MappedDragToDesktopPolicy.cs @@ -0,0 +1,192 @@ +namespace DeskBox.Services; + +/// Where a drag released from a mapped widget landed, as far as 「放回桌面」 cares. +public enum MappedDragDropTargetKind +{ + /// Anything that is not the shell desktop (another app, a folder window, the taskbar, DeskBox itself). + NotDesktop, + + /// The desktop icon list (SHELLDLL_DefView / SysListView32 inside Progman or WorkerW). + DesktopIconList, + + /// The desktop host window itself (Progman / WorkerW, e.g. wallpaper area without a list view). + DesktopHost, +} + +/// +/// GOXF fork, 「映射整理」: pure decisions for 「从映射格子拖到桌面 = 放回桌面」. +/// A mapped item already lives in the desktop folder, so Explorer treats a drop +/// on the desktop as a same-folder move (a no-op) and the item would stay hidden +/// and stay in the widget. DeskBox therefore recognises that drop itself and +/// runs 「放回桌面」. The native probing lives in ; +/// everything here is testable without a desktop. +/// +public static class MappedDragToDesktopPolicy +{ + private const int DefaultSpacingX = 75; + private const int DefaultSpacingY = 100; + + private static readonly string[] TaskbarClasses = + [ + "Shell_TrayWnd", + "Shell_SecondaryTrayWnd", + "NotifyIconOverflowWindow", + "TopLevelWindowForOverflowXamlIsland", + ]; + + /// + /// Classifies the window under the release point from its class chain + /// (the hit window first, then each parent up to the root). A window owned + /// by DeskBox itself is never the desktop, even when a widget is bedded + /// into WorkerW; a window outside the shell process is rejected too. + /// + public static MappedDragDropTargetKind ClassifyTarget( + IReadOnlyList classChain, + bool ownedByDeskBox, + bool ownedByShell) + { + if (classChain is null || classChain.Count == 0 || ownedByDeskBox || !ownedByShell) + { + return MappedDragDropTargetKind.NotDesktop; + } + + bool hasDefView = false; + bool hasHost = false; + foreach (string className in classChain) + { + if (string.IsNullOrEmpty(className)) + { + continue; + } + + if (TaskbarClasses.Any(taskbar => string.Equals(taskbar, className, StringComparison.OrdinalIgnoreCase))) + { + return MappedDragDropTargetKind.NotDesktop; + } + + hasDefView |= string.Equals(className, "SHELLDLL_DefView", StringComparison.OrdinalIgnoreCase); + hasHost |= string.Equals(className, "Progman", StringComparison.OrdinalIgnoreCase) || + string.Equals(className, "WorkerW", StringComparison.OrdinalIgnoreCase); + } + + if (hasDefView) + { + // SHELLDLL_DefView also hosts the file list of every Explorer + // folder window; only the one under Progman/WorkerW is the desktop. + return hasHost ? MappedDragDropTargetKind.DesktopIconList : MappedDragDropTargetKind.NotDesktop; + } + + return hasHost ? MappedDragDropTargetKind.DesktopHost : MappedDragDropTargetKind.NotDesktop; + } + + /// + /// Whether a completed drag should become 「放回桌面」: it came from a mapped + /// widget, DeskBox did not handle the drop itself, it landed on the desktop, + /// and not on an existing icon (a drop on a folder / the Recycle Bin icon is + /// a real move, which the upstream drag-out handling keeps doing). A drag + /// cancelled with Esc, or a completion reported while a mouse button is + /// still held (the stack popover closing mid-drag), is not a drop. + /// + public static bool ShouldPutBack( + bool isMappedWidget, + bool handledInternally, + MappedDragDropTargetKind target, + bool droppedOnIcon, + bool mouseButtonDown = false, + bool escapePressed = false) => + isMappedWidget && + !handledInternally && + target != MappedDragDropTargetKind.NotDesktop && + !droppedOnIcon && + !mouseButtonDown && + !escapePressed; + + /// + /// The entries to put back: dragged paths that still exist and sit directly + /// in a desktop folder, normalised and de-duplicated (multi-selection drags + /// carry every selected path; a stack drag carries none). + /// + public static IReadOnlyList ComputePutBackPaths( + IEnumerable? draggedPaths, + Func exists, + Func isDesktopEntry) + { + ArgumentNullException.ThrowIfNull(exists); + ArgumentNullException.ThrowIfNull(isDesktopEntry); + if (draggedPaths is null) + { + return []; + } + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var result = new List(); + foreach (string raw in draggedPaths) + { + if (string.IsNullOrWhiteSpace(raw)) + { + continue; + } + + string path; + try + { + path = MappedOrganizeMembership.NormalizePath(raw); + } + catch (Exception) + { + continue; + } + + if (path.Length == 0 || !isDesktopEntry(path) || !exists(path) || !seen.Add(path)) + { + continue; + } + + result.Add(path); + } + + return result; + } + + /// + /// Top-left positions (desktop list-view client coordinates) for the icons + /// put back by one drop: the first is centred on the release point, the + /// rest follow below it in a column and wrap into the next column at the + /// bottom of the work area — the same column-first order as the desktop. + /// + public static IReadOnlyList<(int X, int Y)> ComputeIconOrigins( + int dropX, + int dropY, + int spacingX, + int spacingY, + int count, + int areaTop, + int areaBottom) + { + if (count <= 0) + { + return []; + } + + int sx = spacingX > 0 ? spacingX : DefaultSpacingX; + int sy = spacingY > 0 ? spacingY : DefaultSpacingY; + int x0 = dropX - (sx / 2); + int y0 = dropY - (sy / 2); + bool hasArea = areaBottom - areaTop >= sy; + if (hasArea) + { + y0 = Math.Clamp(y0, areaTop, areaBottom - sy); + } + + int rows = hasArea ? Math.Max(1, (areaBottom - y0) / sy) : count; + var origins = new List<(int X, int Y)>(count); + for (int i = 0; i < count; i++) + { + int column = i / rows; + int row = i % rows; + origins.Add((x0 + (column * sx), y0 + (row * sy))); + } + + return origins; + } +} diff --git a/src/DeskBox/Services/MappedDragToDesktopTarget.cs b/src/DeskBox/Services/MappedDragToDesktopTarget.cs new file mode 100644 index 000000000..c51cc9927 --- /dev/null +++ b/src/DeskBox/Services/MappedDragToDesktopTarget.cs @@ -0,0 +1,145 @@ +using System.Text; +using DeskBox.Platform; + +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, + IntPtr ListView, + int ClientX, + int ClientY, + int AreaTopClient, + int AreaBottomClient) +{ + internal static MappedDesktopDropPoint None { get; } = + new(MappedDragDropTargetKind.NotDesktop, false, IntPtr.Zero, 0, 0, 0, 0); +} + +/// +/// GOXF fork, 「映射整理」: native probe behind 「从映射格子拖到桌面 = 放回桌面」. +/// 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 +/// . +/// +internal static class MappedDragToDesktopTarget +{ + private const int MaxAncestorDepth = 16; + + internal static MappedDesktopDropPoint Probe(Win32Helper.POINT screenPoint) + { + try + { + return ProbeCore(screenPoint); + } + catch (Exception ex) + { + App.Log($"[MappedOrganize] Desktop drop probe failed: {ex.Message}"); + return MappedDesktopDropPoint.None; + } + } + + private static MappedDesktopDropPoint ProbeCore(Win32Helper.POINT screenPoint) + { + IntPtr hit = Win32Helper.WindowFromPoint(screenPoint); + if (hit == IntPtr.Zero) + { + return MappedDesktopDropPoint.None; + } + + var chain = new List(); + IntPtr listView = IntPtr.Zero; + IntPtr defView = IntPtr.Zero; + IntPtr current = hit; + for (int depth = 0; current != IntPtr.Zero && depth < MaxAncestorDepth; depth++) + { + string className = ClassOf(current); + chain.Add(className); + if (listView == IntPtr.Zero && string.Equals(className, "SysListView32", StringComparison.Ordinal)) + { + listView = current; + } + + if (defView == IntPtr.Zero && string.Equals(className, "SHELLDLL_DefView", StringComparison.Ordinal)) + { + defView = current; + } + + current = Win32Helper.GetParent(current); + } + + IntPtr root = Win32Helper.GetAncestor(hit, Win32Helper.GA_ROOT); + if (root != IntPtr.Zero) + { + chain.Add(ClassOf(root)); + } + + uint currentProcess = (uint)Environment.ProcessId; + Win32Helper.GetWindowThreadProcessId(hit, out uint hitProcess); + Win32Helper.GetWindowThreadProcessId(root == IntPtr.Zero ? hit : root, out uint rootProcess); + bool ownedByDeskBox = hitProcess == currentProcess || rootProcess == currentProcess; + + // Same identity rule as the upstream desktop probes: compare with the + // shell window's process, and keep the class verdict while Explorer is + // restarting (GetShellWindow returns zero). + bool ownedByShell = true; + IntPtr shellWindow = Win32Helper.GetShellWindow(); + if (shellWindow != IntPtr.Zero) + { + Win32Helper.GetWindowThreadProcessId(shellWindow, out uint shellProcess); + ownedByShell = shellProcess == 0 || rootProcess == 0 || shellProcess == rootProcess; + } + + MappedDragDropTargetKind kind = MappedDragToDesktopPolicy.ClassifyTarget(chain, ownedByDeskBox, ownedByShell); + if (kind == MappedDragDropTargetKind.NotDesktop) + { + return MappedDesktopDropPoint.None; + } + + if (listView == IntPtr.Zero && defView != IntPtr.Zero) + { + 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); + + int clientX = screenPoint.X; + int clientY = screenPoint.Y; + if (listView != IntPtr.Zero) + { + Win32Helper.POINT client = screenPoint; + if (Win32Helper.ScreenToClient(listView, ref client)) + { + clientX = client.X; + clientY = client.Y; + } + else + { + listView = IntPtr.Zero; + } + } + + int offsetY = clientY - screenPoint.Y; + int areaTop = 0; + int areaBottom = 0; + if (Win32Helper.TryGetMonitorWorkArea(screenPoint.X, screenPoint.Y, out _, out Win32Helper.RECT work)) + { + areaTop = work.Top + offsetY; + areaBottom = work.Bottom + offsetY; + } + + return new MappedDesktopDropPoint(kind, onIcon, listView, clientX, clientY, areaTop, areaBottom); + } + + private static string ClassOf(IntPtr window) + { + var buffer = new StringBuilder(256); + return Win32Helper.GetClassName(window, buffer, buffer.Capacity) > 0 ? buffer.ToString() : string.Empty; + } +} diff --git a/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs b/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs index e24fab359..b70996b6f 100644 --- a/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs +++ b/src/DeskBox/ViewModels/SettingsViewModel.AboutAndUpdates.cs @@ -312,6 +312,7 @@ public async Task CheckForUpdatesAsync() _updateOperationCts?.Cancel(); _updateOperationCts = new CancellationTokenSource(); StartUpstreamReleaseCheck(); // GOXF fork: informational, never awaited + StartForkDevUpdateCheck(); // GOXF fork: local dev builds only, never awaited IsCheckingForUpdates = true; UpdateStatusText = _localizationService.T("Settings.Update.Status.Checking"); UpdateDetailText = _localizationService.T("Settings.Update.Detail.Checking"); diff --git a/src/DeskBox/ViewModels/SettingsViewModel.ForkDevUpdate.cs b/src/DeskBox/ViewModels/SettingsViewModel.ForkDevUpdate.cs new file mode 100644 index 000000000..15d23afd9 --- /dev/null +++ b/src/DeskBox/ViewModels/SettingsViewModel.ForkDevUpdate.cs @@ -0,0 +1,111 @@ +using DeskBox.Services; +using Microsoft.UI.Xaml; + +namespace DeskBox.ViewModels; + +/// +/// GOXF/DeskBox fork: "local test build" line + "update and restart" button +/// under About → Update details. Visible only for a local dev build (exe +/// inside a clone that has scripts/fork-dev-update.ps1); installed builds +/// never show it. Bound with x:Bind, so the AOT bindable-property list +/// (pinned by upstream tests) is untouched. Text lives in code for the same +/// merge-conflict reason as SettingsViewModel.ForkUpstream.cs. +/// +public partial class SettingsViewModel +{ + private ForkDevUpdateInfo? _forkDevUpdateInfo; + private int _forkDevUpdateCheckInFlight; + private int _forkDevUpdateCheckStarted; + + public Visibility ForkDevUpdateVisibility + { + get + { + // First render of the About section starts one check; the + // explicit "check for updates" path re-runs it. + if (ForkDevBuildInfo.IsLocalDevBuild && + Interlocked.Exchange(ref _forkDevUpdateCheckStarted, 1) == 0) + { + StartForkDevUpdateCheck(); + } + + return ForkDevBuildInfo.IsLocalDevBuild ? Visibility.Visible : Visibility.Collapsed; + } + } + + public string ForkDevUpdateStatusText + { + get + { + ForkDevBuild? build = ForkDevBuildInfo.Current; + if (build is null) + { + return string.Empty; + } + + return _forkDevUpdateInfo is { } info + ? ForkDevUpdateService.FormatStatus(_localizationService.CurrentCultureName, info) + : ForkDevUpdateService.FormatLocalOnlyStatus(_localizationService.CurrentCultureName, build.ShortSha); + } + } + + public Visibility ForkDevUpdateButtonVisibility => + _forkDevUpdateInfo is { HasUpdate: true } ? Visibility.Visible : Visibility.Collapsed; + + public string ForkDevUpdateButtonText => + ForkDevUpdateService.FormatUpdateButton(_localizationService.CurrentCultureName); + + /// Fire-and-forget; never awaited by the regular update flow. + private void StartForkDevUpdateCheck() + { + if (!ForkDevBuildInfo.IsLocalDevBuild || + Interlocked.Exchange(ref _forkDevUpdateCheckInFlight, 1) == 1) + { + return; + } + + Interlocked.Exchange(ref _forkDevUpdateCheckStarted, 1); + _ = RunForkDevUpdateCheckAsync(); + } + + private async Task RunForkDevUpdateCheckAsync() + { + try + { + ForkDevUpdateInfo? info = await ForkDevUpdateService.CheckAsync().ConfigureAwait(false); + if (info is not null) + { + SetForkDevUpdateInfo(info); + } + } + catch (Exception ex) + { + App.Log($"[DevUpdate] Settings check failed: {ex.GetType().Name}"); + } + finally + { + Volatile.Write(ref _forkDevUpdateCheckInFlight, 0); + } + } + + private void SetForkDevUpdateInfo(ForkDevUpdateInfo info) + { + if (_uiDispatcherQueue is { } queue && !queue.HasThreadAccess) + { + queue.TryEnqueue(() => SetForkDevUpdateInfo(info)); + return; + } + + _forkDevUpdateInfo = info; + OnPropertyChanged(nameof(ForkDevUpdateStatusText)); + OnPropertyChanged(nameof(ForkDevUpdateButtonVisibility)); + } + + /// Starts scripts/fork-dev-update.ps1; the window then shuts DeskBox down. + public bool StartForkDevUpdateScript(out string message) + { + bool started = ForkDevUpdateService.TryStartUpdateScript(out string? error); + message = started ? string.Empty : ForkDevUpdateService.FormatStartFailed(_localizationService.CurrentCultureName, error); + return started; + } +} diff --git a/src/DeskBox/Views/SettingsWindow.ForkDevUpdate.cs b/src/DeskBox/Views/SettingsWindow.ForkDevUpdate.cs new file mode 100644 index 000000000..907f492ab --- /dev/null +++ b/src/DeskBox/Views/SettingsWindow.ForkDevUpdate.cs @@ -0,0 +1,34 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; + +namespace DeskBox.Views; + +/// +/// GOXF/DeskBox fork: "update and restart" for a local dev build. Starts +/// scripts/fork-dev-update.ps1 in its own visible window (pull dev → Debug +/// build → relaunch), then shuts DeskBox down the same way an installer +/// update does so the script can replace the binaries. +/// +public sealed partial class SettingsWindow +{ + private async void ForkDevUpdateButton_Click(object sender, RoutedEventArgs e) + { + if (sender is Button button) + { + button.IsEnabled = false; + } + + if (!ViewModel.StartForkDevUpdateScript(out string message)) + { + if (sender is Button failedButton) + { + failedButton.IsEnabled = true; + } + + await ShowInfoDialogAsync(ViewModel.ForkDevUpdateButtonText, message); + return; + } + + await _appActions.ShutdownForUpdateAsync(); + } +} diff --git a/src/DeskBox/Views/SettingsWindow.xaml b/src/DeskBox/Views/SettingsWindow.xaml index 640c87550..6f676fbf3 100644 --- a/src/DeskBox/Views/SettingsWindow.xaml +++ b/src/DeskBox/Views/SettingsWindow.xaml @@ -3409,6 +3409,23 @@ Text="DeskBox" /> Text="{x:Bind UpstreamReleaseNoticeText, Mode=OneWay}" Visibility="{x:Bind UpstreamReleaseNoticeVisibility, Mode=OneWay}" TextWrapping="Wrap" /> + + + + + +/// GOXF/DeskBox fork: local-test-build update channel. Only a DeskBox.exe +/// built inside a clone (".git" + scripts/fork-dev-update.ps1 above the exe +/// folder) enables it; it compares the build's commit with the tip of dev. +/// +public sealed class ForkDevUpdateTests : IDisposable +{ + private const string LocalSha = "1111111aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string RemoteSha = "2222222bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private readonly string _tempRoot = Path.Combine(Path.GetTempPath(), "DeskBox.Tests", "dev-update-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + try + { + if (Directory.Exists(_tempRoot)) + { + Directory.Delete(_tempRoot, recursive: true); + } + } + catch (IOException) + { + } + } + + private string CreateClone(string name, bool gitAsFile = false, bool withScript = true) + { + string root = Path.Combine(_tempRoot, name); + Directory.CreateDirectory(root); + if (gitAsFile) + { + string worktreeGitDir = Path.Combine(_tempRoot, name + "-gitdir"); + Directory.CreateDirectory(worktreeGitDir); + File.WriteAllText(Path.Combine(root, ".git"), "gitdir: " + worktreeGitDir); + } + else + { + Directory.CreateDirectory(Path.Combine(root, ".git")); + } + + if (withScript) + { + Directory.CreateDirectory(Path.Combine(root, "scripts")); + File.WriteAllText(Path.Combine(root, "scripts", "fork-dev-update.ps1"), "# test"); + } + + return root; + } + + private static string CreateBinDirectory(string root) + { + string bin = Path.Combine(root, "src", "DeskBox", "bin", "x64", "Debug", "net10.0-windows10.0.22621.0", "win-x64"); + Directory.CreateDirectory(bin); + return bin; + } + + [Fact] + public void FindRepositoryRoot_WalksUpFromTheExeFolderToTheClone() + { + string root = CreateClone("clone"); + string bin = CreateBinDirectory(root); + + Assert.Equal(Path.GetFullPath(root), ForkDevBuildInfo.FindRepositoryRoot(bin)); + } + + [Fact] + public void FindRepositoryRoot_AcceptsAWorktreeGitFile() + { + string root = CreateClone("worktree", gitAsFile: true); + + Assert.Equal(Path.GetFullPath(root), ForkDevBuildInfo.FindRepositoryRoot(CreateBinDirectory(root))); + } + + [Fact] + public void FindRepositoryRoot_RequiresBothGitAndTheUpdateScript() + { + string noScript = CreateClone("no-script", withScript: false); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(CreateBinDirectory(noScript))); + + string noGit = Path.Combine(_tempRoot, "no-git"); + Directory.CreateDirectory(Path.Combine(noGit, "scripts")); + File.WriteAllText(Path.Combine(noGit, "scripts", "fork-dev-update.ps1"), "# test"); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(CreateBinDirectory(noGit))); + } + + [Fact] + public void InstalledBuild_IsNotALocalDevBuild() + { + string installDir = Path.Combine(_tempRoot, "Program Files", "DeskBox"); + Directory.CreateDirectory(installDir); + File.WriteAllText(Path.Combine(installDir, "DeskBox.exe"), string.Empty); + + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(installDir)); + Assert.Null(ForkDevBuildInfo.Detect(installDir, typeof(ForkDevBuildInfo).Assembly)); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(null)); + Assert.Null(ForkDevBuildInfo.FindRepositoryRoot(" ")); + } + + [Fact] + public void Detect_FallsBackToTheGitHeadWhenNothingIsEmbedded() + { + string root = CreateClone("loose-ref"); + File.WriteAllText(Path.Combine(root, ".git", "HEAD"), "ref: refs/heads/dev\n"); + Directory.CreateDirectory(Path.Combine(root, ".git", "refs", "heads")); + File.WriteAllText(Path.Combine(root, ".git", "refs", "heads", "dev"), LocalSha.ToUpperInvariant() + "\n"); + + ForkDevBuild? build = ForkDevBuildInfo.Detect(CreateBinDirectory(root), assembly: null); + + Assert.NotNull(build); + Assert.Equal(Path.GetFullPath(root), build!.RepositoryRoot); + Assert.Equal(LocalSha, build.LocalSha); + Assert.Equal("dev", build.Branch); + Assert.Equal("1111111", build.ShortSha); + Assert.Equal(Path.Combine(Path.GetFullPath(root), "scripts", "fork-dev-update.ps1"), build.ScriptPath); + } + + [Fact] + public void ReadHeadFromGitDirectory_ReadsPackedRefsAndDetachedHead() + { + string packed = CreateClone("packed"); + File.WriteAllText(Path.Combine(packed, ".git", "HEAD"), "ref: refs/heads/dev\n"); + File.WriteAllText( + Path.Combine(packed, ".git", "packed-refs"), + "# pack-refs with: peeled fully-peeled sorted\n" + + RemoteSha + " refs/heads/custom\n" + + LocalSha + " refs/heads/dev\n"); + Assert.Equal((LocalSha, "dev"), ForkDevBuildInfo.ReadHeadFromGitDirectory(packed)); + + string detached = CreateClone("detached"); + File.WriteAllText(Path.Combine(detached, ".git", "HEAD"), RemoteSha + "\n"); + Assert.Equal((RemoteSha, (string?)null), ForkDevBuildInfo.ReadHeadFromGitDirectory(detached)); + + string empty = CreateClone("empty"); + Assert.Null(ForkDevBuildInfo.ReadHeadFromGitDirectory(empty).Sha); + } + + [Theory] + [InlineData(LocalSha, RemoteSha, true)] + [InlineData(LocalSha, LocalSha, false)] + [InlineData("1111111", LocalSha, false)] + [InlineData("1111111AAAA", LocalSha, false)] + [InlineData(LocalSha, "1111111", false)] + [InlineData(null, RemoteSha, false)] + [InlineData(LocalSha, null, false)] + [InlineData("not-a-sha", RemoteSha, false)] + [InlineData(LocalSha, "zzzzzzzz", false)] + public void IsRemoteNewer_ComparesShasSafely(string? local, string? remote, bool expected) + { + Assert.Equal(expected, ForkDevBuildInfo.IsRemoteNewer(local, remote)); + } + + [Fact] + public void ParseCommit_ReadsShaAndFirstMessageLine() + { + string json = $$""" + { + "sha": "{{RemoteSha}}", + "commit": { "message": "feat: 本地测试版更新通道\n\n详细说明" } + } + """; + + ForkDevUpdateInfo? info = ForkDevUpdateService.ParseCommit(LocalSha, json); + + Assert.NotNull(info); + Assert.True(info!.HasUpdate); + Assert.Equal("2222222", info.RemoteShortSha); + Assert.Equal("1111111", info.LocalShortSha); + Assert.Equal("feat: 本地测试版更新通道", info.RemoteTitle); + Assert.Equal( + "本地测试版:当前 1111111,有新提交 2222222 feat: 本地测试版更新通道", + ForkDevUpdateService.FormatStatus(LocalizationService.LanguageChinese, info)); + } + + [Fact] + public void ParseCommit_SameShaIsUpToDateAndMalformedIsNull() + { + ForkDevUpdateInfo? same = ForkDevUpdateService.ParseCommit(LocalSha, $$"""{ "sha": "{{LocalSha}}" }"""); + Assert.NotNull(same); + Assert.False(same!.HasUpdate); + Assert.Contains("已是 dev 最新提交", ForkDevUpdateService.FormatStatus(LocalizationService.LanguageChinese, same)); + + Assert.Null(ForkDevUpdateService.ParseCommit(LocalSha, "not json")); + Assert.Null(ForkDevUpdateService.ParseCommit(LocalSha, "[]")); + Assert.Null(ForkDevUpdateService.ParseCommit(LocalSha, """{ "message": "Not Found" }""")); + Assert.Null(ForkDevUpdateService.ParseCommit("", $$"""{ "sha": "{{RemoteSha}}" }""")); + } + + [Fact] + public async Task CheckAsync_QueriesTheDevBranchAndFailsSilently() + { + var requested = new List(); + using var ok = new HttpClient(new StubHandler(request => + { + requested.Add(request.RequestUri!.ToString()); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent($$"""{ "sha": "{{RemoteSha}}", "commit": { "message": "fix: x" } }""", Encoding.UTF8, "application/json") + }; + })); + ForkDevUpdateInfo? info = await ForkDevUpdateService.CheckAsync(LocalSha, ok, ForkDevUpdateService.DevBranchCommitApiUrl, CancellationToken.None); + Assert.Equal(new[] { "https://api.github.com/repos/GOXF/DeskBox/commits/dev" }, requested); + Assert.True(info!.HasUpdate); + + using var rateLimited = new HttpClient(new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.Forbidden))); + Assert.Null(await ForkDevUpdateService.CheckAsync(LocalSha, rateLimited, ForkDevUpdateService.DevBranchCommitApiUrl, CancellationToken.None)); + + using var offline = new HttpClient(new StubHandler(_ => throw new HttpRequestException("offline"))); + Assert.Null(await ForkDevUpdateService.CheckAsync(LocalSha, offline, ForkDevUpdateService.DevBranchCommitApiUrl, CancellationToken.None)); + } + + [Fact] + public void BuildScriptStartInfo_RunsTheRepoScriptInAVisibleWindow() + { + string root = CreateClone("script"); + var build = new ForkDevBuild(Path.GetFullPath(root), LocalSha, "dev"); + + var startInfo = ForkDevUpdateService.BuildScriptStartInfo(build); + + Assert.Equal("powershell.exe", startInfo.FileName); + Assert.True(startInfo.UseShellExecute); + Assert.Equal(build.RepositoryRoot, startInfo.WorkingDirectory); + Assert.Contains("-ExecutionPolicy Bypass", startInfo.Arguments, StringComparison.Ordinal); + Assert.Contains($"-File \"{build.ScriptPath}\"", startInfo.Arguments, StringComparison.Ordinal); + Assert.Contains("-Branch dev", startInfo.Arguments, StringComparison.Ordinal); + } + + private sealed class StubHandler(Func handler) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(handler(request)); + } + } +} diff --git a/tests/DeskBox.Tests/MappedDragToDesktopTests.cs b/tests/DeskBox.Tests/MappedDragToDesktopTests.cs new file mode 100644 index 000000000..269c55f53 --- /dev/null +++ b/tests/DeskBox.Tests/MappedDragToDesktopTests.cs @@ -0,0 +1,172 @@ +using DeskBox.Services; + +namespace DeskBox.Tests; + +/// GOXF fork: 「从映射格子拖到桌面 = 放回桌面」 pure decisions. +public sealed class MappedDragToDesktopTests +{ + private static readonly string Desktop = Path.Combine(Path.GetTempPath(), "deskbox-fork-drag-tests", "Desktop"); + private static readonly string Elsewhere = Path.Combine(Path.GetTempPath(), "deskbox-fork-drag-tests", "Docs"); + + private static string D(string name) => MappedOrganizeMembership.NormalizePath(Path.Combine(Desktop, name)); + + private static bool IsDesktopEntry(string path) => + string.Equals(Path.GetDirectoryName(MappedOrganizeMembership.NormalizePath(path)), MappedOrganizeMembership.NormalizePath(Desktop), StringComparison.OrdinalIgnoreCase); + + // ---- target window class chain ---- + + [Theory] + [InlineData(MappedDragDropTargetKind.DesktopIconList, "SysListView32>SHELLDLL_DefView>Progman")] + [InlineData(MappedDragDropTargetKind.DesktopIconList, "SysListView32>SHELLDLL_DefView>WorkerW")] + [InlineData(MappedDragDropTargetKind.DesktopIconList, "SHELLDLL_DefView>Progman")] + [InlineData(MappedDragDropTargetKind.DesktopIconList, "syslistview32>shelldll_defview>workerw")] + [InlineData(MappedDragDropTargetKind.DesktopHost, "WorkerW")] + [InlineData(MappedDragDropTargetKind.DesktopHost, "Progman")] + public void ClassifyTarget_AcceptsShellDesktop(MappedDragDropTargetKind expected, string chain) + { + Assert.Equal(expected, MappedDragToDesktopPolicy.ClassifyTarget(chain.Split('>'), ownedByDeskBox: false, ownedByShell: true)); + } + + [Theory] + [InlineData("SysListView32>SHELLDLL_DefView>DUIViewWndClassName>CabinetWClass")] // Explorer folder window + [InlineData("SysListView32")] // third-party list view + [InlineData("Shell_TrayWnd")] + [InlineData("MSTaskSwWClass>ReBarWindow32>Shell_TrayWnd")] + [InlineData("Shell_SecondaryTrayWnd")] + [InlineData("WinUIDesktopWin32WindowClass")] + [InlineData("")] + public void ClassifyTarget_RejectsOtherWindows(string chain) + { + Assert.Equal( + MappedDragDropTargetKind.NotDesktop, + MappedDragToDesktopPolicy.ClassifyTarget(chain.Split('>'), ownedByDeskBox: false, ownedByShell: true)); + } + + [Fact] + public void ClassifyTarget_RejectsDeskBoxWindowsBeddedIntoWorkerW() + { + Assert.Equal( + MappedDragDropTargetKind.NotDesktop, + MappedDragToDesktopPolicy.ClassifyTarget(new[] { "WinUIDesktopWin32WindowClass", "WorkerW" }, ownedByDeskBox: true, ownedByShell: true)); + } + + [Fact] + public void ClassifyTarget_RejectsWindowsOutsideTheShellProcess() + { + Assert.Equal( + MappedDragDropTargetKind.NotDesktop, + MappedDragToDesktopPolicy.ClassifyTarget(new[] { "SysListView32", "SHELLDLL_DefView", "WorkerW" }, ownedByDeskBox: false, ownedByShell: false)); + } + + [Fact] + public void ClassifyTarget_RejectsEmptyChain() + { + Assert.Equal(MappedDragDropTargetKind.NotDesktop, MappedDragToDesktopPolicy.ClassifyTarget(Array.Empty(), false, true)); + } + + // ---- when a drop becomes 「放回桌面」 ---- + + [Fact] + public void ShouldPutBack_OnlyForMappedWidgetDropsOnBlankDesktop() + { + Assert.True(MappedDragToDesktopPolicy.ShouldPutBack(true, false, MappedDragDropTargetKind.DesktopIconList, false)); + Assert.True(MappedDragToDesktopPolicy.ShouldPutBack(true, false, MappedDragDropTargetKind.DesktopHost, false)); + + // Move-mode widget keeps the upstream drag-out. + Assert.False(MappedDragToDesktopPolicy.ShouldPutBack(false, false, MappedDragDropTargetKind.DesktopIconList, false)); + // DeskBox handled the drop (another widget / reorder). + Assert.False(MappedDragToDesktopPolicy.ShouldPutBack(true, true, MappedDragDropTargetKind.DesktopIconList, false)); + // Another folder / app. + Assert.False(MappedDragToDesktopPolicy.ShouldPutBack(true, false, MappedDragDropTargetKind.NotDesktop, false)); + // On a desktop icon (folder, Recycle Bin): real move, upstream path. + Assert.False(MappedDragToDesktopPolicy.ShouldPutBack(true, false, MappedDragDropTargetKind.DesktopIconList, true)); + } + + [Fact] + public void ShouldPutBack_IgnoresCancelledOrUnfinishedDrags() + { + Assert.False(MappedDragToDesktopPolicy.ShouldPutBack(true, false, MappedDragDropTargetKind.DesktopIconList, false, mouseButtonDown: true)); + Assert.False(MappedDragToDesktopPolicy.ShouldPutBack(true, false, MappedDragDropTargetKind.DesktopIconList, false, escapePressed: true)); + } + + // ---- which paths are put back ---- + + [Fact] + public void ComputePutBackPaths_KeepsExistingDesktopEntriesOnceInOrder() + { + var existing = new HashSet(StringComparer.OrdinalIgnoreCase) { D("a.txt"), D("Folder"), D("c.lnk") }; + string[] dragged = + [ + Path.Combine(Desktop, "a.txt"), + Path.Combine(Desktop, "Folder") + Path.DirectorySeparatorChar, + Path.Combine(Desktop, "A.TXT"), + Path.Combine(Desktop, "gone.txt"), + Path.Combine(Elsewhere, "c.lnk"), + Path.Combine(Desktop, "c.lnk"), + "", + " ", + ]; + + IReadOnlyList result = MappedDragToDesktopPolicy.ComputePutBackPaths(dragged, existing.Contains, IsDesktopEntry); + + Assert.Equal(new[] { D("a.txt"), D("Folder"), D("c.lnk") }, result.ToArray()); + } + + [Fact] + public void ComputePutBackPaths_HandlesEmptyInput() + { + Assert.Empty(MappedDragToDesktopPolicy.ComputePutBackPaths(null, _ => true, _ => true)); + Assert.Empty(MappedDragToDesktopPolicy.ComputePutBackPaths(Array.Empty(), _ => true, _ => true)); + } + + // ---- icon positions ---- + + [Fact] + public void ComputeIconOrigins_CentresFirstIconAndStacksTheRestInAColumn() + { + IReadOnlyList<(int X, int Y)> origins = MappedDragToDesktopPolicy.ComputeIconOrigins(500, 300, 80, 100, 3, 0, 1040); + + Assert.Equal(new (int X, int Y)[] { (460, 250), (460, 350), (460, 450) }, origins.ToArray()); + } + + [Fact] + public void ComputeIconOrigins_WrapsIntoNextColumnAtWorkAreaBottom() + { + // Rows that fit below y0=850 within bottom 1040: (1040-850)/100 = 1. + IReadOnlyList<(int X, int Y)> origins = MappedDragToDesktopPolicy.ComputeIconOrigins(500, 900, 80, 100, 3, 0, 1040); + + Assert.Equal(new (int X, int Y)[] { (460, 850), (540, 850), (620, 850) }, origins.ToArray()); + } + + [Fact] + public void ComputeIconOrigins_ClampsIntoWorkAreaAndDefaultsSpacing() + { + IReadOnlyList<(int X, int Y)> origins = MappedDragToDesktopPolicy.ComputeIconOrigins(10, 1030, 0, 0, 1, 0, 1040); + + Assert.Equal(new (int X, int Y)[] { (10 - 37, 940) }, origins.ToArray()); + Assert.Empty(MappedDragToDesktopPolicy.ComputeIconOrigins(0, 0, 80, 100, 0, 0, 1040)); + } + + [Fact] + public void ComputeIconOrigins_WithoutWorkAreaKeepsOneColumn() + { + IReadOnlyList<(int X, int Y)> origins = MappedDragToDesktopPolicy.ComputeIconOrigins(100, 100, 80, 100, 2, 0, 0); + + Assert.Equal(new (int X, int Y)[] { (60, 50), (60, 150) }, origins.ToArray()); + } + + // ---- wiring ---- + + [Fact] + 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); + + string hook = File.ReadAllText(TestPaths.FromRepository( + "src/DeskBox/Controls/WidgetContents/FileSurfaceContent.MappedDragToDesktop.cs")); + Assert.Contains("service.KeepOnDesktop(paths)", hook, StringComparison.Ordinal); + Assert.Contains("ViewModel.IsMappedOrganizeWidget", hook, StringComparison.Ordinal); + } +}