From 51b39a573dcc528e05b819063fe3ce72c9d01d95 Mon Sep 17 00:00:00 2001 From: leafOfTree Date: Sun, 29 Nov 2026 10:08:25 +0800 Subject: [PATCH] Unify window selection and add batch closing --- WtProgram/Commands.fs | 4 +- .../ManagerViewService/SettingsEditors.fs | 28 ++++ WtProgram/Program.fs | 1 + WtProgram/Shared/Strings.fs | 7 + WtProgram/SplitPanePicker.fs | 21 ++- WtProgram/SplitViewChrome.fs | 5 +- WtProgram/TabSearch.fs | 85 +++++++--- WtProgram/TabStripDecorator.fs | 4 +- tests/Architecture.fsx | 10 ++ tests/CommandPalette.fsx | 146 +++++++++++++++++- 10 files changed, 283 insertions(+), 28 deletions(-) diff --git a/WtProgram/Commands.fs b/WtProgram/Commands.fs index 064163cd..12121554 100644 --- a/WtProgram/Commands.fs +++ b/WtProgram/Commands.fs @@ -481,7 +481,7 @@ module Commands = match Services.tryGet() with | Some picker when not entries.IsEmpty -> let mutable target : IGroup option = None - picker.showForMerge(owner,prompt,entries,fun hwnd -> + picker.showForMerge(owner,prompt,tr Strings.TabMenu.createGroupCount,entries,fun hwnd -> if WinUserApi.IsWindow hwnd then let group = match target with @@ -494,6 +494,8 @@ module Commands = Services.desktop.addExistingWindow(group.hwnd,hwnd)) | Some _ -> Notice.show prompt (tr Strings.TabMenu.splitNoWindows) | None -> ()) with scope=Everywhere } + { plain "close-windows" { caption=Strings.TabMenu.closeWindows; description=Strings.TabMenu.closeWindows; keywords=Strings.Commands.closeAllTabs.keywords } TabCommands always (fun owner -> + Services.tryGet() |> Option.iter(fun picker -> picker.show(owner,Services.program.windowCandidates None))) with scope=Everywhere } plain "add-existing-window" Strings.Commands.addExisting GroupCommands hasGroup (onGroup(fun g -> g.run AddExistingWindow)) plain "sort-tabs" Strings.Commands.sortTabs TabCommands hasOtherTabs (onGroup(fun g -> g.run SortTabs)) plain "close-other-tabs" Strings.Commands.closeOtherTabs TabCommands hasOtherTabs (onTab(fun g hwnd -> g.run(CloseOtherTabs hwnd))) diff --git a/WtProgram/ManagerViewService/SettingsEditors.fs b/WtProgram/ManagerViewService/SettingsEditors.fs index 32fc14d5..ffae6e10 100644 --- a/WtProgram/ManagerViewService/SettingsEditors.fs +++ b/WtProgram/ManagerViewService/SettingsEditors.fs @@ -21,6 +21,7 @@ type SettingsActionButton() as this = let mutable mousePressed = false let mutable keyPressed = false let mutable kind = SettingsButtonKind.Standard + let mutable shortcutText = "" /// A − or + drawn as strokes on the button's middle: as text, the font's ascent and side /// bearings set them a pixel or two off it. let mutable sign : char option = None @@ -29,6 +30,8 @@ type SettingsActionButton() as this = this.FlatAppearance.BorderSize <- 0 this.SetStyle(ControlStyles.UserPaint ||| ControlStyles.OptimizedDoubleBuffer ||| ControlStyles.AllPaintingInWmPaint,true) member this.Kind with get() = kind and set value = kind <- value; this.Invalidate() + /// An optional keyboard hint, separate from the action label. + member this.ShortcutText with get() = shortcutText and set value = shortcutText <- value; this.Invalidate() /// '−' or '+', drawn in place of the text, which stays for screen readers. member this.Sign with get() = defaultArg sign ' ' and set (value:char) = sign <- (if value='−' || value='+' then Some value else None); this.Invalidate() /// Held down by the mouse while over the button, or by Space, as a click is about to happen. @@ -117,6 +120,31 @@ type SettingsActionButton() as this = if symbol='+' then let down = 2*arm+h%2 e.Graphics.FillRectangle(ink,(w-stroke)/2,(h-down)/2,stroke,down) + | None when shortcutText<>"" -> + use hintFont = new Font(this.Font.FontFamily,this.Font.SizeInPoints*0.9f,FontStyle.Regular,GraphicsUnit.Point) + let padding = Dpi.scale 8 + let gap = Dpi.scale 4 + let capHeight = min (Dpi.scale 20) (this.Height-Dpi.scale 8) + let keys = shortcutText.Split([|'+'|],StringSplitOptions.RemoveEmptyEntries) |> Array.map(fun key -> key.Trim()) + let flags = TextFormatFlags.NoPrefix ||| TextFormatFlags.NoPadding ||| TextFormatFlags.SingleLine + let widths = keys |> Array.map(fun key -> max capHeight (TextRenderer.MeasureText(key,hintFont,Size.Empty,flags).Width+Dpi.scale 10)) + let hintWidth = Array.sum widths + max 0 (keys.Length-1)*gap + let mutable x = this.Width-padding-hintWidth + let textBounds = Rectangle(Dpi.scale 10,0,max 0 (x-Dpi.scale 18),this.Height) + TextRenderer.DrawText(e.Graphics,this.Text,this.Font,textBounds,textColor, + TextFormatFlags.NoPrefix ||| TextFormatFlags.VerticalCenter ||| TextFormatFlags.SingleLine ||| TextFormatFlags.EndEllipsis) + let capColor = if highContrast then fillColor else mix fillColor textColor (if this.Enabled then 0.16f else 0.07f) + use capFill = new SolidBrush(capColor) + for key,width in Array.zip keys widths do + let bounds = Rectangle(x,(this.Height-capHeight)/2,width,capHeight) + use cap = SettingsShapes.rounded (RectangleF(float32 bounds.X,float32 bounds.Y,float32 bounds.Width,float32 bounds.Height)) (float32 (Dpi.scale 4)) + e.Graphics.FillPath(capFill,cap) + if highContrast then + use border = new Pen(textColor) + e.Graphics.DrawPath(border,cap) + TextRenderer.DrawText(e.Graphics,key,hintFont,bounds,textColor, + flags ||| TextFormatFlags.HorizontalCenter ||| TextFormatFlags.VerticalCenter) + x <- x+width+gap | None -> TextRenderer.DrawText(e.Graphics,this.Text,this.Font,this.ClientRectangle,textColor, TextFormatFlags.NoPrefix ||| TextFormatFlags.HorizontalCenter ||| TextFormatFlags.VerticalCenter ||| TextFormatFlags.EndEllipsis) diff --git a/WtProgram/Program.fs b/WtProgram/Program.fs index 57b754c8..6a8e9687 100644 --- a/WtProgram/Program.fs +++ b/WtProgram/Program.fs @@ -2023,6 +2023,7 @@ type Program(lifetime:LifetimeScope, ?settings:Settings) as this = Services.register(DispatchedManagerView(ManagerViewService(), dispatcher) :> IManagerView) // Not dispatched: it builds its drop-down on the group thread that opens it. Services.register(SplitPanePicker() :> ISplitPanePicker) + Services.register(SplitPanePicker() :> IWindowClosePicker) SettingsAlert.install() plugins.iter(fun plugin -> match plugin with diff --git a/WtProgram/Shared/Strings.fs b/WtProgram/Shared/Strings.fs index 053c931e..b02a6300 100644 --- a/WtProgram/Shared/Strings.fs +++ b/WtProgram/Shared/Strings.fs @@ -90,6 +90,13 @@ module Strings = let pickToggle = { en="Toggle"; zh="增减选择"; ja="選択切替"; ar="تبديل"; ko="선택 전환" } let pickMultiple = { en="Multi-select"; zh="多选"; ja="複数選択"; ar="تحديد متعدد"; ko="다중 선택" } let pickRange = { en="Range"; zh="连续选择"; ja="範囲選択"; ar="تحديد نطاق"; ko="범위 선택" } + let closeWindows = { en="Close windows…"; zh="关闭窗口…"; ja="ウィンドウを閉じる…"; ar="إغلاق النوافذ…"; ko="창 닫기…" } + let addSelectedCount = { en="Add selected ({0})"; zh="添加所选({0})"; ja="選択を追加 ({0})"; ar="إضافة المحدد ({0})"; ko="선택한 창 추가 ({0})" } + let createGroupCount = { en="New group ({0})"; zh="新建分组({0})"; ja="新しいグループ ({0})"; ar="مجموعة جديدة ({0})"; ko="새 그룹 ({0})" } + let addToWindowGroup = { en="Add to the group containing: {0}"; zh="添加到此窗口所在的组:{0}"; ja="このウィンドウのグループに追加:{0}"; ar="إضافة إلى مجموعة النافذة: {0}"; ko="이 창이 속한 그룹에 추가: {0}" } + let closeSelectedCount = { en="Close selected ({0})"; zh="关闭所选({0})"; ja="選択を閉じる ({0})"; ar="إغلاق المحدد ({0})"; ko="선택한 창 닫기 ({0})" } + let selectionHidden = { en="{0} selected outside these results"; zh="其中 {0} 个不在当前结果中"; ja="選択した {0} 件は検索結果外です"; ar="{0} محددة خارج هذه النتائج"; ko="선택한 창 중 {0}개가 검색 결과 밖에 있음" } + let pinnedProtected = { en="Pinned — protected"; zh="已固定 · 受保护"; ja="固定済み・保護中"; ar="مثبتة — محمية"; ko="고정됨 · 보호됨" } let confirmSelection = { en="Confirm"; zh="确认"; ja="確定"; ar="تأكيد"; ko="확인" } let addExisting = { en="Add an existing window"; zh="添加已有窗口"; ja="既存のウィンドウを追加"; ar="إضافة نافذة موجودة"; ko="기존 창 추가" } let splitSearch = { en="Type a title or app name to fill the pane"; zh="输入标题或应用名,放入这个窗格"; ja="タイトルやアプリ名を入力してペインに配置"; ar="اكتب عنوانًا أو اسم تطبيق لملء الجزء"; ko="제목이나 앱 이름을 입력해 창 영역 채우기" } diff --git a/WtProgram/SplitPanePicker.fs b/WtProgram/SplitPanePicker.fs index c7427b04..b88f9a24 100644 --- a/WtProgram/SplitPanePicker.fs +++ b/WtProgram/SplitPanePicker.fs @@ -22,9 +22,26 @@ type SplitPanePicker() = let search = TabSearchForm(entries,[],pick=choose,within=within,prompt=prompt, rows=rows,width=width) search.Show() + interface IWindowClosePicker with + member _.show(owner,windows) = + let identity hwnd = + let mutable pid = 0 + let tid = WinUserApi.GetWindowThreadProcessId(hwnd,&pid) + pid,tid + let identities = windows |> List.map(fun (hwnd,_,_) -> hwnd,identity hwnd) |> Map.ofList + let close selected = + for hwnd in selected do + if WinUserApi.IsWindow hwnd && not(PinnedTabs.contains hwnd) && identity hwnd=identities.[hwnd] then + OS().windowFromHwnd(hwnd).close() + let search = TabSearchForm(SplitPaneList.entries windows,[],pickMany=close, + confirmText=(fun count -> String.Format(tr Strings.TabMenu.closeSelectedCount,count)), + blocked=PinnedTabs.contains,prompt=tr Strings.TabMenu.closeWindows,screen=Screen.FromHandle(owner)) + search.Show() interface ISplitPanePicker with member _.show(owner,_,windows,choose) = open' (owner.RectangleToScreen(owner.ClientRectangle)) (tr Strings.TabMenu.splitSearch) windows choose - member _.showForMerge(strip,prompt,windows,choose) = - let search = TabSearchForm(SplitPaneList.entries windows,[],pickMany=List.iter choose,prompt=prompt,screen=Screen.FromHandle(strip)) + member _.showForMerge(strip,prompt,confirmText,windows,choose) = + let search = TabSearchForm(SplitPaneList.entries windows,[],pickMany=List.iter choose, + confirmText=(fun count -> String.Format(confirmText,count)), + prompt=prompt,screen=Screen.FromHandle(strip)) search.Show() member _.showWithin(within,prompt,windows,choose) = open' within prompt windows choose diff --git a/WtProgram/SplitViewChrome.fs b/WtProgram/SplitViewChrome.fs index 5a21bad9..bc4000ac 100644 --- a/WtProgram/SplitViewChrome.fs +++ b/WtProgram/SplitViewChrome.fs @@ -48,10 +48,13 @@ module SplitMenu = /// Lists windows for a pane to take. Registered by the program with the settings window's /// drop-down; the picker builds its controls on the calling thread. +type IWindowClosePicker = + abstract member show : owner:IntPtr * windows:(IntPtr * string * string) list -> unit + type ISplitPanePicker = /// Opens below `anchor`, on screen; `choose` receives the window picked. abstract member show : owner:Control * anchor:Rectangle * windows:(IntPtr * string * string) list * choose:(IntPtr -> unit) -> unit - abstract member showForMerge : strip:IntPtr * prompt:string * windows:(IntPtr * string * string) list * choose:(IntPtr -> unit) -> unit + abstract member showForMerge : strip:IntPtr * prompt:string * confirmText:string * windows:(IntPtr * string * string) list * choose:(IntPtr -> unit) -> unit /// Opens over `within`, on screen, as for a group about to split. abstract member showWithin : within:Rectangle * prompt:string * windows:(IntPtr * string * string) list * choose:(IntPtr -> unit) -> unit diff --git a/WtProgram/TabSearch.fs b/WtProgram/TabSearch.fs index ea877de5..d30673e8 100644 --- a/WtProgram/TabSearch.fs +++ b/WtProgram/TabSearch.fs @@ -233,6 +233,9 @@ module TabSearch = /// Lists groups one after another, the most recently used first, each in its tab order. /// zorder gives each window's place in the z-order, 0 at the top. let arrange (zorder:IntPtr -> int) (active:IntPtr) (groups:TabSearchEntry list list) = + // Group membership can overlap while a window transfers between group threads. + let seen = Collections.Generic.HashSet() + let groups = groups |> List.map(List.filter(fun entry -> seen.Add entry.hwnd)) let used (entry:TabSearchEntry) = if entry.hwnd=active then Int32.MaxValue else zorder entry.hwnd let recency = groups |> List.concat |> List.sortBy used |> List.mapi(fun index entry -> entry.hwnd,index) |> Map.ofList @@ -327,7 +330,7 @@ module private TabSearchNative = /// width: how many rows show and how wide it is, in logical pixels; pages: the pages beside the /// windows, or in their place with windows false; scope: the one to open on. type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISettings, - ?pick:IntPtr -> unit, ?pickMany:IntPtr list -> unit, ?within:Rectangle, ?prompt:string, ?rows:int, ?width:int, + ?pick:IntPtr -> unit, ?pickMany:IntPtr list -> unit, ?confirmText:int -> string, ?blocked:IntPtr -> bool, ?within:Rectangle, ?prompt:string, ?rows:int, ?width:int, ?pages:PalettePage list, ?scope:PaletteScope, ?windows:bool, ?screen:Screen, ?windowShortcut:TabSearchEntry -> ShortcutAssignment option, ?windowShortcutText:TabSearchEntry -> string) = let rowHeight = TabSearchMetrics.rowHeight @@ -341,7 +344,9 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti let pages = defaultArg pages [] let requested = scope let pick = defaultArg pick (fun hwnd -> OS().windowFromHwnd(hwnd).setForegroundOrRestore(false)) - let mutable marked : Set option = None + let explicitSelection = confirmText.IsSome + let blocked = defaultArg blocked (fun _ -> false) + let mutable marked : Set option = if explicitSelection then Some Set.empty else None let mutable rangeAnchor : IntPtr option = None let area = match within with @@ -361,6 +366,7 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti let items = tabs |> List.map(fun entry -> let item = TreeListItem(entry.title,Values=[|"";TabSearch.source entry|]) + item.Dimmed <- blocked entry.hwnd match ImgHelper.knownWindowIcon (OS().windowFromHwnd entry.hwnd) with | Some icon -> item.Icon <- icon | None -> item.Glyph <- WindowGlyph @@ -494,7 +500,7 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti | (caption,_,_,_)::_ -> let bounds,key = breadcrumb() TextRenderer.DrawText(g,caption,SettingsUi.bodyFont(),bounds,p.text, - TextFormatFlags.NoPrefix ||| TextFormatFlags.SingleLine ||| TextFormatFlags.VerticalCenter ||| TextFormatFlags.EndEllipsis) + TextFormatFlags.NoPrefix ||| TextFormatFlags.VerticalCenter ||| (if explicitSelection then TextFormatFlags.WordBreak else TextFormatFlags.SingleLine ||| TextFormatFlags.EndEllipsis)) // A chevron a little shorter than the text's capitals, in the margin before the names. let s = float32(Dpi.scaleF 3.5) let cx,cy = float32(Dpi.scale 3)+s/2.0f,float32 scopeHeight/2.0f @@ -522,13 +528,20 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti key |> Option.iter(fun cap -> drawKey cap "Tab") } let pickerHints multiSelect = let click = tr Strings.TabMenu.click - [ (if multiSelect then tr Strings.TabMenu.pickToggle else tr Strings.TabMenu.pickAdd),click - tr Strings.TabMenu.pickMultiple,"Ctrl+"+click - tr Strings.TabMenu.pickRange,"Shift+"+click ] + if explicitSelection then + [ tr Strings.TabMenu.pickToggle,click + tr Strings.TabMenu.pickRange,"Shift+"+click ] + else + [ (if multiSelect then tr Strings.TabMenu.pickToggle else tr Strings.TabMenu.pickAdd),click + tr Strings.TabMenu.pickMultiple,"Ctrl+"+click + tr Strings.TabMenu.pickRange,"Shift+"+click ] let pickerHintText multiSelect = pickerHints multiSelect |> List.map(fun (label,keys) -> keys+" "+label) |> String.concat " · " let hintRowHeight = Dpi.scale (if pickMany.IsSome then 24 else 28) - let confirmWidth = Dpi.scale 76 + let confirmWidth = + match confirmText with + | Some label -> max (Dpi.scale 120) (TextRenderer.MeasureText(label 9999,SettingsUi.bodyFont()).Width+TextRenderer.MeasureText("Ctrl + ↵",SettingsUi.bodyFont()).Width+Dpi.scale 36) + | None -> Dpi.scale 76 /// Keep each gesture beside its caption when the footer needs another line. let hintGap = 4 let hintJoinPadding = 4 // Two logical pixels on each side of the plus sign. @@ -556,13 +569,15 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti if pickMany.IsSome then let width = min (Dpi.scale (defaultArg width 640)) (area.Width-Dpi.scale 32)-2*padding use g = Graphics.FromHwnd(IntPtr.Zero) - layoutHints g false (width-confirmWidth) |> snd + let height = layoutHints g explicitSelection (width-confirmWidth-Dpi.scale 8) |> snd + if explicitSelection then max (Dpi.scale 28) height else height elif pages.IsEmpty && (tabs |> List.forall(fun entry -> (windowShortcut entry).IsNone)) then 0 else hintRowHeight + let mutable hiddenSelectionCount = 0 let mutable footerNote : (string * bool) option = pickMany |> Option.map(fun _ -> pickerHintText false,false) let confirm = pickMany |> Option.map(fun _ -> - new SettingsActionButton(Text=tr Strings.TabMenu.confirmSelection,Kind=SettingsButtonKind.Primary, - Dock=DockStyle.Right,Width=confirmWidth,Enabled=false,Visible=false)) + new SettingsActionButton(Text=(confirmText |> Option.map(fun label -> label 0) |> Option.defaultValue (tr Strings.TabMenu.confirmSelection)),Kind=SettingsButtonKind.Primary, + Dock=(if explicitSelection then DockStyle.None else DockStyle.Right),Width=confirmWidth,Enabled=false,Visible=explicitSelection)) let footer = { new Panel(Dock=DockStyle.Bottom,Height=footerHeight,BackColor=palette.surface) with override this.OnPaint(e) = @@ -583,13 +598,15 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti (if SystemInformation.HighContrast then SystemColors.WindowText else p.accentText), TextFormatFlags.NoPrefix ||| TextFormatFlags.SingleLine ||| TextFormatFlags.VerticalCenter) match footerNote with - | Some _ when pickMany.IsSome -> + | Some _ when pickMany.IsSome && (not explicitSelection || hiddenSelectionCount=0) -> let hints,height = layoutHints g marked.IsSome hintLeft let top = (this.ClientSize.Height-height)/2 for caption,keys,bounds,capLeft in hints do - let label = Rectangle(bounds.X,bounds.Y+top,bounds.Width,bounds.Height) + // Share the text box with the caps so DPI rounding cannot shift their baselines. + let capTop = bounds.Y+top+(hintRowHeight-keyHeight())/2 + let label = Rectangle(bounds.X,capTop,bounds.Width,keyHeight()) TextRenderer.DrawText(g,caption,keyFont,label,p.text,captionFlags) - KeyCaps.drawWithJoinPadding hintJoinPadding g keyFont capLeft (label.Top+(hintRowHeight-keyHeight())/2) (keyHeight()) keys p |> ignore + KeyCaps.drawWithJoinPadding hintJoinPadding g keyFont capLeft capTop (keyHeight()) keys p |> ignore | Some(text,refused) -> // Red only for a refusal; where a key came from is just news. let color = @@ -598,10 +615,16 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti elif ThemeService.currentIsDark() then Color.FromRGB(0xFF99A4) else Color.FromRGB(0xC42B1C) let left = Dpi.scale 4 TextRenderer.DrawText(g,text,keyFont,Rectangle(left,0,max 0 (hintLeft-Dpi.scale 16-left),this.ClientSize.Height),color, - TextFormatFlags.NoPrefix ||| TextFormatFlags.SingleLine ||| TextFormatFlags.VerticalCenter ||| TextFormatFlags.EndEllipsis) + TextFormatFlags.NoPrefix ||| TextFormatFlags.VerticalCenter ||| (if explicitSelection then TextFormatFlags.WordBreak else TextFormatFlags.SingleLine ||| TextFormatFlags.EndEllipsis)) | None -> () } do confirm |> Option.iter(fun button -> footer.Controls.Add button + if explicitSelection then + button.ShortcutText <- "Ctrl + ↵" + button.AccessibleDescription <- "Ctrl+Enter" + footer.Layout.Add(fun _ -> + let height = Dpi.scale 28 + button.SetBounds(footer.ClientSize.Width-button.Width,(footer.ClientSize.Height-height)/2,button.Width,height)) footer.AccessibleName <- pickerHintText false) let setFooterNote note = footerNote <- note @@ -717,8 +740,21 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti /// so leaving without choosing puts the ticked value back. let mutable previewOptions : CommandChoice list = [] let mutable previewed = false + do if explicitSelection then list.RowSelection <- Some(fun _ -> false) /// The list's choice being set by the palette itself, not moved by the user. let mutable selecting = false + let updateSelectionNote() = + if explicitSelection then + let selected = defaultArg marked Set.empty + let visible = list.Roots |> Seq.map(fun row -> pickIds.Value.[row]) |> Set.ofSeq + let hidden = Set.difference selected visible |> Set.count + hiddenSelectionCount <- hidden + let hint = if hidden=0 then pickerHintText true else String.Format(tr Strings.TabMenu.selectionHidden,hidden) + setFooterNote (Some(hint,false)) + footer.AccessibleName <- hint + confirm |> Option.iter(fun button -> + button.Text <- confirmText.Value selected.Count + button.Enabled <- not selected.IsEmpty) let apply() = // The line under the box: the scopes to go round, or the way back from a command's // choices. The palette's one page has neither until a command leaves a choice. @@ -753,7 +789,9 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti | key,detail -> { detail=detail; switch=None; swatch=None; shortcut=key; dropdown=false; small=false } | _ -> { detail=TabSearch.source entry; switch=None; swatch=None; shortcut=""; dropdown=false; small=false } let text (aside:PaletteAside) = aside.detail - let asides = shown |> Array.map(fun (_,entry) -> aside entry) + let asides = shown |> Array.map(fun (_,entry) -> + let value = aside entry + if blocked entry.hwnd then { value with detail=value.detail+" · "+tr Strings.TabMenu.pinnedProtected } else value) // Titles reclaim the fixed app column's spare space, including after filtering. let measure (aside:PaletteAside) = let value = text aside @@ -789,6 +827,7 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti list.Roots.Clear() list.Roots.AddRange(Array.map fst shown) list.Rebuild() + updateSelectionNote() let chosen = // The row chosen before, while the same rows are listed again for a value that changed. keptRow |> Option.bind(fun hwnd -> shown |> Array.tryFind(fun (_,candidate) -> candidate.hwnd=hwnd)) @@ -839,7 +878,9 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti // A queued group activation must start after the popup releases foreground. form.Hide() run() - | None,Some _,Some choose,Some selected -> items |> Array.choose(fun (_,entry) -> if selected.Contains entry.hwnd then Some entry.hwnd else None) |> List.ofArray |> choose + | None,Some _,Some choose,Some selected -> + form.Hide() + items |> Array.choose(fun (_,entry) -> if selected.Contains entry.hwnd then Some entry.hwnd else None) |> List.ofArray |> choose | None,Some hwnd,Some choose,None -> choose [hwnd] | None,_,_,_ -> chosen |> Option.iter(fun hwnd -> // A queued group activation must start after the popup releases foreground. @@ -1088,13 +1129,15 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti let a = rangeAnchor |> Option.bind(fun id -> Array.tryFindIndex ((=) id) rows) |> Option.defaultValue 0 let b = Array.findIndex ((=) hwnd) rows rangeAnchor <- Some rows.[a] - let range = Set.ofArray rows.[min a b..max a b] + // Protected rows do not participate when toggling a complete range off. + let range = Set.ofArray rows.[min a b..max a b] |> Set.filter(blocked >> not) if toggleFullRange && Set.isSubset range selected then Set.difference selected range else Set.union selected range else rangeAnchor <- Some hwnd if not ctrl then Set.singleton hwnd elif selected.Contains hwnd then selected.Remove hwnd else selected.Add hwnd + let next = next |> Set.filter(blocked >> not) marked <- Some next list.RowSelection <- Some(fun row -> next.Contains(pickIds.Value.[row])) confirm |> Option.iter(fun button -> @@ -1103,6 +1146,7 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti let hint = pickerHintText true footer.AccessibleName <- hint setFooterNote (Some(hint,false)) + updateSelectionNote() list.Invalidate() let activate (target:TreeListItem) = if not closed && pickMany.IsSome && marked.IsSome then @@ -1268,6 +1312,10 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti | Keys.PageUp -> move -visibleRows; true | Keys.Enter when e.Alt -> beginAssign(); true | Keys.Enter when asking.IsSome -> answer(); true + | Keys.Enter when explicitSelection && e.Control -> activate list.SelectedItem; true + | Keys.Enter when explicitSelection && not e.Shift -> + if not (isNull list.SelectedItem) && not list.SelectedItem.Dimmed then selectWindow list.SelectedItem Keys.Control true + true | Keys.Enter when pickMany.IsSome && (e.Control || e.Shift) -> if not (isNull list.SelectedItem) then selectWindow list.SelectedItem e.Modifiers true true @@ -1348,7 +1396,8 @@ type TabSearchForm(tabs:TabSearchEntry list, group:IntPtr list, ?settings:ISetti if e.Button=MouseButtons.Left && not closed then list.ItemAt(e.Location) |> Option.iter(fun row -> let keys = Control.ModifierKeys - if pickMany.IsSome && (keys &&& (Keys.Control ||| Keys.Shift))<>Keys.None then selectWindow row keys true + if row.Dimmed then () + elif pickMany.IsSome && (keys &&& (Keys.Control ||| Keys.Shift))<>Keys.None then selectWindow row keys true elif marked.IsSome then selectWindow row Keys.Control true else activate row) list.MouseClick.Add clickRow diff --git a/WtProgram/TabStripDecorator.fs b/WtProgram/TabStripDecorator.fs index fe6a7d86..6497b107 100755 --- a/WtProgram/TabStripDecorator.fs +++ b/WtProgram/TabStripDecorator.fs @@ -515,12 +515,12 @@ type TabStripDecorator(group:WindowGroup) as this = | None -> () member private this.pickExistingWindow() = - let prompt = tr Strings.TabMenu.addExisting + let prompt = String.Format(tr Strings.TabMenu.addToWindowGroup,group.tabName group.topWindow) let entries = Services.program.windowCandidates (Some this.ts.hwnd) match Services.tryGet() with | Some picker when not entries.IsEmpty -> let target = this.ts.hwnd - picker.showForMerge(target,prompt,entries,fun hwnd -> Services.desktop.addExistingWindow(target,hwnd)) + picker.showForMerge(target,prompt,tr Strings.TabMenu.addSelectedCount,entries,fun hwnd -> Services.desktop.addExistingWindow(target,hwnd)) | Some _ -> Notice.show prompt (tr Strings.TabMenu.splitNoWindows) | None -> () diff --git a/tests/Architecture.fsx b/tests/Architecture.fsx index ecbf7150..9ad1f4d1 100644 --- a/tests/Architecture.fsx +++ b/tests/Architecture.fsx @@ -1077,6 +1077,11 @@ let main() = let entries = TabSearch.tabs (fun _ -> None) untabbed.Handle [[notesWindow.Handle;untabbed.Handle]] check (entries |> List.filter(fun entry -> entry.hwnd=untabbed.Handle) |> List.length = 1) "Global search duplicated a grouped window" + let repeated = TabSearch.tabs (fun _ -> None) untabbed.Handle + [[notesWindow.Handle;untabbed.Handle;untabbed.Handle];[notesWindow.Handle;untabbed.Handle]] + for hwnd in [notesWindow.Handle;untabbed.Handle] do + check (repeated |> List.filter(fun entry -> entry.hwnd=hwnd) |> List.length = 1) + "Native discovery must deduplicate repeated membership before any picker receives candidates" let entries = TabSearch.tabs (fun _ -> None) notesWindow.Handle [[notesWindow.Handle]] check (entries |> List.exists(fun entry -> entry.hwnd=untabbed.Handle)) "Global search omitted an app without tabs" check (entries |> List.exists(fun entry -> entry.hwnd=notesWindow.Handle)) "Global search omitted a grouped tab" @@ -1254,6 +1259,11 @@ let main() = let mutable switched = IntPtr.Zero let duplicateA = {mail with title="Home - File Explorer"} let duplicateB = {notes with title="Home - File Explorer"} + let overlapping = TabSearch.arrange (fun hwnd -> if hwnd=duplicateA.hwnd then 0 else 1) duplicateA.hwnd + [[duplicateA;duplicateB;duplicateB];[duplicateB;duplicateA]] + check (overlapping.Length=2 && overlapping |> List.map(fun entry -> entry.hwnd) |> Set.ofList |> Set.count = 2) + "Overlapping groups must list each HWND once without collapsing distinct windows with identical titles" + check ((List.last overlapping).hwnd=duplicateA.hwnd) "Deduplication must keep the active window last" let existingForms = Application.OpenForms |> Seq.cast
|> Seq.toList let switching = TabSearchForm([duplicateA;duplicateB],[],pick=(fun hwnd -> check (switchingHost |> Option.exists(fun host -> not host.Visible)) "Switch windows activated before hiding its popup" diff --git a/tests/CommandPalette.fsx b/tests/CommandPalette.fsx index 4b63bf4e..71afb88d 100644 --- a/tests/CommandPalette.fsx +++ b/tests/CommandPalette.fsx @@ -136,13 +136,16 @@ let main() = member _.show() = calls.Enqueue "settings" member _.show(view:SettingsViewType) = calls.Enqueue(sprintf "settings %A" view) member _.showSetting id = calls.Enqueue("setting "+id)}) + let closeRequests = ResizeArray() + Services.register({new IWindowClosePicker with + member _.show(owner,windows) = closeRequests.Add(owner,windows)}) let picks = ConcurrentQueue() Services.register({new ISplitPanePicker with member _.show(_,_,windows,_) = picks.Enqueue windows.Length member _.showWithin(_,_,windows,_) = picks.Enqueue windows.Length - member _.showForMerge(strip,prompt,windows,choose) = + member _.showForMerge(strip,prompt,confirmText,windows,choose) = check (WinUserApi.IsWindow strip) "The merge picker needs its originating tab strip" - check (prompt=tr Strings.TabMenu.addExisting || prompt=tr Strings.GroupEditor.newGroup) "Wrong prompt for the merge picker" + check (confirmText=tr Strings.TabMenu.addSelectedCount || confirmText=tr Strings.TabMenu.createGroupCount) "Wrong confirmation action for the merge picker" windows |> List.tryHead |> Option.iter(fun (hwnd,_,_) -> choose hwnd)}) // Groups whose taskbar button would be the real one get a stand-in, as no taskbar is needed here. let noTaskbar() = {new IPlugin with member _.init() = ()} @@ -204,7 +207,7 @@ let main() = let needsSplit = set ["split-focus-left";"split-focus-right";"split-focus-up";"split-focus-down";"split-focus-other";"split-swap";"split-equalize";"split-turn";"split-close-pane";"split-end"] let needsTab = set [TabCommands;GroupCommands;SplitCommands] // Listed with the tab and group commands, but open a box wherever the user is. - let anywhere = set ["search-tabs";"switch-groups";"command-palette";"edit-groups";"new-group"] + let anywhere = set ["close-windows";"search-tabs";"switch-groups";"command-palette";"edit-groups";"new-group"] // Dimmed while there is no workspace to choose. let needsWorkspace = set ["restore-workspace-named";"delete-workspace"] // Open a system dialog and wait on the user: listed, but not run unattended. @@ -724,6 +727,10 @@ let main() = pumpUntil "Adding the picked window" (fun () -> onGroupOf active (fun g -> g.windows.contains picked) && onGroup groupB (fun g -> not (g.windows.contains picked))) note (onGroup groupB (fun g -> g.windows.contains sibling)) "Picking one window moved another tab from its group") + attempt "close-windows" (fun () -> + runDone "close-windows" active + note (closeRequests |> Seq.exists(fun (owner,windows) -> owner=active && windows=candidates)) "Close command did not open the picker with all candidates" + note ((Commands.find "close-windows").Value.scope=Everywhere) "Close picker must be available without a tab") attempt "new-group" (fun () -> let picked = hwndOf "Delta" candidates <- [picked,"Delta","app"] @@ -1293,7 +1300,7 @@ let main() = for screen in Screen.AllScreens do use strip = new Form(StartPosition=FormStartPosition.Manual,Bounds=Rectangle(screen.WorkingArea.Location,Size(100,50))) let before = Application.OpenForms |> Seq.cast |> Seq.toArray - (SplitPanePicker() :> ISplitPanePicker).showForMerge(strip.Handle,"Pick",[(1n,"Window","App")],ignore) + (SplitPanePicker() :> ISplitPanePicker).showForMerge(strip.Handle,"Pick",tr Strings.TabMenu.addSelectedCount,[(1n,"Window","App")],ignore) let popup = Application.OpenForms |> Seq.cast |> Seq.find(fun f -> f.Visible && not(Array.contains f before)) check (Screen.FromHandle(popup.Handle).DeviceName=screen.DeviceName) "Merge picker opened on another strip's monitor" popup.Close() @@ -1384,6 +1391,137 @@ let main() = check (picked.IsEmpty && confirm.Enabled) "Clearing all checks must not restore single-click activation" confirm.PerformClick() check (picked=[1n]) "Confirmation should add only the marked windows" + for label in [Strings.TabMenu.addSelectedCount;Strings.TabMenu.createGroupCount] do + let mutable merged = [] + let showMerge() = + (SplitPanePicker() :> ISplitPanePicker).showForMerge(active,"Pick",tr label, + [(1n,"First","App");(2n,"Second","App")],fun hwnd -> merged <- merged@[hwnd]) + let rows = pickerRows() + let button = rows.FindForm().Controls |> Seq.cast |> Seq.collect(fun c -> c.Controls |> Seq.cast) + |> Seq.pick(function :? SettingsActionButton as b -> Some b | _ -> None) + rows,button + let rows,button = showMerge() + check (button.Visible && not button.Enabled && button.Text=String.Format(tr label,0)) "Merge must begin with an empty selection and visible action" + click rows (Dpi.scale 60) (height/2) + check (merged.IsEmpty && button.Text=String.Format(tr label,1)) "First merge click must select without executing" + let press key = typeof.GetMethod("OnKeyDown",Reflection.BindingFlags.Instance ||| Reflection.BindingFlags.NonPublic).Invoke(rows,[|box (KeyEventArgs(key))|]) |> ignore + press Keys.Enter + check (not button.Enabled && merged.IsEmpty) "Merge Enter must toggle the marked row" + press Keys.Enter + press Keys.Down + press Keys.Enter + check (button.Text=String.Format(tr label,2) && merged.IsEmpty) "Merge keyboard selection must accumulate before confirmation" + press (Keys.Control ||| Keys.Enter) + check (merged=[1n;2n]) "Merge Ctrl+Enter must submit the selected windows" + merged <- [] + let rows,button = showMerge() + click rows (Dpi.scale 60) (height/2) + rows.FindForm().Close() + check merged.IsEmpty "Cancelling merge must not create or change a group" + let rows,button = showMerge() + click rows (Dpi.scale 60) (height/2) + button.PerformClick() + check (merged=[1n]) "Merge confirmation must allow just one window" + // The three actions share the same keyboard, filtering and confirmation contract. + for label in [Strings.TabMenu.addSelectedCount;Strings.TabMenu.createGroupCount;Strings.TabMenu.closeSelectedCount] do + let mutable submitted = [] + let mutable submissions = 0 + let picker = TabSearchForm(candidates,[],confirmText=(fun count -> String.Format(tr label,count)), + pickMany=(fun ids -> submitted <- ids; submissions <- submissions+1)) + picker.Show() + let rows = pickerRows() + picker.Press(Keys.Control ||| Keys.Enter) + check (submissions=0 && rows.FindForm().Visible) "Empty keyboard confirmation must leave every picker open" + click rows (Dpi.scale 60) (height/2) + picker.ChooseRow(1n) + picker.Press(Keys.Enter) + check (not(rows.RowSelection.Value rows.Roots.[0]) && submissions=0) "Click and Enter must toggle the same selection without executing" + picker.Press(Keys.Enter) + picker.ChooseRow(3n) + picker.Press(Keys.Shift ||| Keys.Enter) + check ([0..2] |> List.forall(fun i -> rows.RowSelection.Value rows.Roots.[i])) "Shift+Enter must select the visible range in every picker" + picker.Query <- "6" + check (picker.FooterNote=Some(String.Format(tr Strings.TabMenu.selectionHidden,3))) "Search must retain and disclose hidden selections for every action" + picker.Press(Keys.Enter) + picker.Query <- "" + check ([0;1;2;5] |> List.forall(fun i -> rows.RowSelection.Value rows.Roots.[i])) "Clearing search must restore the same selection marks" + picker.Query <- "no matching window" + check (picker.Results.IsEmpty && picker.FooterNote=Some(String.Format(tr Strings.TabMenu.selectionHidden,4))) "Empty search results must preserve all selections" + picker.Press(Keys.Enter) + check (submissions=0) "Enter with no results must not submit hidden selections" + picker.Press(Keys.Control ||| Keys.Enter) + check (submitted=[1n;2n;3n;6n] && submissions=1) "Ctrl+Enter must submit hidden and visible selections exactly once" + submitted <- [] + let single = TabSearchForm(candidates,[],confirmText=(fun count -> String.Format(tr label,count)),pickMany=(fun ids -> submitted <- ids)) + single.Show() + single.ChooseRow(2n) + single.Press(Keys.Enter) + single.Press(Keys.Control ||| Keys.Enter) + check (submitted=[2n]) "Every action must allow keyboard confirmation of one window" + submitted <- [] + let cancel = TabSearchForm(candidates,[],confirmText=(fun count -> String.Format(tr label,count)),pickMany=(fun ids -> submitted <- ids)) + cancel.Show() + cancel.Press(Keys.Enter) + cancel.Query <- "no matching window" + cancel.Press(Keys.Escape) + check submitted.IsEmpty "Escape must cancel hidden selections for every action" + picked <- [] + let closing = TabSearchForm(candidates,[],pickMany=(fun ids -> picked <- ids),confirmText=(fun n -> sprintf "Close (%d)" n),blocked=((=) 3n)) + closing.Show() + let closeRows = pickerRows() + let closeButton = closeRows.FindForm().Controls |> Seq.cast |> Seq.collect(fun c -> c.Controls |> Seq.cast) + |> Seq.pick(function :? SettingsActionButton as b -> Some b | _ -> None) + check (closeButton.Visible && not closeButton.Enabled && closeButton.Text="Close (0)") "Close picker must start with no selection and visible disabled confirmation" + check (closeButton.Height=Dpi.scale 28 && closeButton.Top=(closeButton.Parent.ClientSize.Height-closeButton.Height)/2) "Close confirmation must retain compact height and stay vertically centered" + check (closing.FooterNote.Value.Contains(tr Strings.TabMenu.click) && closing.FooterNote.Value.Contains("Shift+")) "Close picker must retain click and range hints" + closing.Accept() + check (picked.IsEmpty && closeRows.FindForm().Visible) "Enter must not close an unmarked window" + click closeRows (Dpi.scale 60) (height/2) + check (picked.IsEmpty && closeButton.Text="Close (1)") "First click must only select a close target" + closing.SelectWindow(3n,Keys.Shift) + check (closeButton.Text="Close (2)") "Range selection must exclude protected windows" + closing.SelectWindow(3n,Keys.Shift) + check (closeButton.Text="Close (0)" && not closeButton.Enabled) "Repeating a range across protected rows must clear all selectable rows" + closing.SelectWindow(3n,Keys.Shift) + check (closeButton.Text="Close (2)") "A cleared protected range must be selectable again" + closing.ChooseRow(2n) + closing.Press(Keys.Enter) + check (picked.IsEmpty && closeButton.Text="Close (1)") "Enter must unmark the current window without closing" + closing.Press(Keys.Enter) + check (picked.IsEmpty && closeButton.Text="Close (2)") "Enter must mark the current window without submitting" + closing.ChooseRow(3n) + closing.Press(Keys.Enter) + check (closeButton.Text="Close (2)") "Enter must not mark a protected window" + closing.Query <- "6" + check (closing.FooterNote=Some(String.Format(tr Strings.TabMenu.selectionHidden,2))) "Filtered-out selections must remain counted and disclosed" + closing.SelectWindow(6n,Keys.Control) + closing.Press(Keys.Control ||| Keys.Enter) + check (picked=[1n;2n;6n]) "Close confirmation must include hidden selections and exclude protected windows" + picked <- [] + let cancelled = TabSearchForm(candidates,[],pickMany=(fun ids -> picked <- ids),confirmText=string) + cancelled.Show() + cancelled.SelectWindow(1n,Keys.Control) + cancelled.Press(Keys.Escape) + check picked.IsEmpty "Escape must not submit close targets" + use closable = new Form(Text="Close fixture") + use refusing = new Form(Text="Unsaved fixture") + use protectedWindow = new Form(Text="Pinned fixture") + use stale = new Form(Text="Gone fixture") + for form in [closable;refusing;protectedWindow;stale] do form.Show() + refusing.FormClosing.Add(fun e -> e.Cancel <- true) + PinnedTabs.set protectedWindow.Handle true + let closeTargets = [closable;refusing;protectedWindow;stale] |> List.map(fun form -> form.Handle,form.Text,"fixture") + (SplitPanePicker() :> IWindowClosePicker).show(active,closeTargets) + let nativeRows = pickerRows() + let nativeButton = nativeRows.FindForm().Controls |> Seq.cast |> Seq.collect(fun c -> c.Controls |> Seq.cast) + |> Seq.pick(function :? SettingsActionButton as b -> Some b | _ -> None) + for index in 0..3 do click nativeRows (Dpi.scale 60) (index*height+height/2) + check (not closable.IsDisposed && not(nativeRows.RowSelection.Value nativeRows.Roots.[2])) "Close picker must defer closing and block pinned windows" + stale.Dispose() + nativeButton.PerformClick() + pump 100 + check (closable.IsDisposed && not refusing.IsDisposed && not protectedWindow.IsDisposed) "Normal close must honor application cancellation and pinned protection" + PinnedTabs.set protectedWindow.Handle false let search = TabSearchForm(entries,[active],settings=api) search.Show() pump 100