Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions WtProgram/Desktop.fs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,27 @@ type GroupChoicesShown = {
module SwitchActivation =
let shouldRetry previous target current = current=previous && current<>target

module GroupSnapshot =
/// Keep optimistically added HWNDs until the group STA finishes their queued add,
/// so an earlier tab's order update cannot hide a later tab from discovery scans.
let mergeOrder (current:List2<IntPtr>) (order:List2<IntPtr>) (isPending:IntPtr -> bool) =
let extras =
current.list
|> List.filter(fun hwnd -> isPending hwnd && not (order.contains((=) hwnd)))
if extras.IsEmpty then order else List2(order.list @ extras)

type GroupInfo(enableSuperBar, settings:ISettings, desktopDispatcher:IDispatcher, ?taskbarPlugin:unit -> IPlugin) as this =
let Cell = CellScope(true, true)
let windowsCell = Cell.create(List2())
let stagedAdds = Collections.Generic.Dictionary<IntPtr,obj>()
let pendingAdds = Collections.Generic.Dictionary<IntPtr,obj>()
let isPendingAdd hwnd = pendingAdds.ContainsKey hwnd || stagedAdds.ContainsKey hwnd
let finishPendingAdd hwnd (token:obj) (dropOnMiss:bool) =
match pendingAdds.TryGetValue hwnd with
| true, current when obj.ReferenceEquals(current, token) ->
pendingAdds.Remove hwnd |> ignore
if dropOnMiss then windowsCell.map(fun windows -> windows.where((<>) hwnd))
| _ -> ()
let mutable _isExited = 0
let shownChoicesChangedEvent = Event<unit>()
let initialAppearance = ThemeService.currentAppearance()
Expand All @@ -71,13 +88,15 @@ type GroupInfo(enableSuperBar, settings:ISettings, desktopDispatcher:IDispatcher
// Insertion and restart restoration can reorder tabs before the added notification.
let publishOrder() =
let order = _group.lorder
desktopDispatcher.Post(fun () -> windowsCell.set order)
desktopDispatcher.Post(fun () ->
windowsCell.set (GroupSnapshot.mergeOrder windowsCell.value order isPendingAdd))
_group.added.Add(fun _ -> publishOrder())
_group.moved.Add(fun _ -> publishOrder())

_group.removed.Add <| fun hwnd ->
desktopDispatcher.Post <| fun() ->
windowsCell.map <| fun l -> l.where((<>) hwnd)
if not (isPendingAdd hwnd) then
windowsCell.map <| fun l -> l.where((<>) hwnd)

do _group.foregroundChanged.Add(fun () ->
TaskbarPreviewTrace.write "group-foreground" (WinUserApi.GetForegroundWindow()) "" (sprintf "top=%d" (_group.topWindow.ToInt64())))
Expand Down Expand Up @@ -182,11 +201,16 @@ type GroupInfo(enableSuperBar, settings:ISettings, desktopDispatcher:IDispatcher
// must not introduce a duplicate in the optimistic desktop snapshot either.
if not (windowsCell.value.contains((=) hwnd)) then
windowsCell.map <| fun l -> l.append hwnd
let token = obj()
pendingAdds.[hwnd] <- token
// Still queue the operation: a preceding asynchronous remove may not
// have updated this snapshot yet, and remove-then-add must reattach it.
VirtualDesktop.groupingDesktopId hwnd |> ignore
this.invokeGroup <| fun() -> StartupTrace.measure "group.add" (fun () -> this.group.addWindow(hwnd, withDelay))
this.invokeGroup <| fun() ->
try StartupTrace.measure "group.add" (fun () -> this.group.addWindow(hwnd, withDelay))
finally desktopDispatcher.Post(fun () -> finishPendingAdd hwnd token false)
member private this.removeWindow hwnd =
pendingAdds.Remove hwnd |> ignore
if stagedAdds.Remove hwnd then
windowsCell.map(fun windows -> windows.where((<>)hwnd))
this.invokeGroup <| fun() -> this.group.removeWindow(hwnd)
Expand All @@ -206,10 +230,14 @@ type GroupInfo(enableSuperBar, settings:ISettings, desktopDispatcher:IDispatcher
match stagedAdds.TryGetValue hwnd with
| true,current when obj.ReferenceEquals(current,token) ->
stagedAdds.Remove hwnd |> ignore
let addToken = obj()
pendingAdds.[hwnd] <- addToken
this.invokeGroup(fun () ->
let added = not this.isExited && WinUserApi.IsWindow hwnd
if added then this.group.addWindow(hwnd,false)
else desktopDispatcher.Post(fun () -> windowsCell.map(fun windows -> windows.where((<>)hwnd)))
try
if added then this.group.addWindow(hwnd,false)
finally
desktopDispatcher.Post(fun () -> finishPendingAdd hwnd addToken (not added))
afterAdd |> Option.iter(fun action -> action added))
| _ -> afterAdd |> Option.iter(fun action -> this.invokeGroup(fun () -> action false))
subscription <- Some(source.exited.Subscribe(fun () -> desktopDispatcher.Post attach))
Expand Down
87 changes: 57 additions & 30 deletions WtProgram/TabShadow.fs
Original file line number Diff line number Diff line change
Expand Up @@ -29,44 +29,58 @@ module TabShadow =
let mutable horizontal = Array.empty<float>
let mutable prefix = Array.empty<int>
let mutable pixels = Array.empty<byte>
let mutable colMinY = Array.empty<int>
let mutable colMaxY = Array.empty<int>
member _.Render(width, height, mask:byte[], padding, direction, ?allSides:bool) =
let w = width + padding * 2
let allSides = defaultArg allSides false
let h = height + padding * (if allSides then 2 else 1)
if horizontal.Length < w*h then horizontal <- Array.zeroCreate (max (w*h) (horizontal.Length*2))
if prefix.Length < width+1 then prefix <- Array.zeroCreate (width+1)
if pixels.Length < w*4 then pixels <- Array.zeroCreate (w*4)
if colMinY.Length < w then colMinY <- Array.zeroCreate w
if colMaxY.Length < w then colMaxY <- Array.zeroCreate w
Array.Clear(horizontal,0,w*h)
for x in 0 .. w - 1 do
colMinY.[x] <- h
colMaxY.[x] <- -1
let sigma = float padding / 3.0
let weights = Array.init (padding * 2 + 1) (fun i ->
let d = float (i - padding)
exp (-d * d / (2.0 * sigma * sigma)))
let total = Array.sum weights
let kernel = weights |> Array.map (fun v -> v / total)
let sample x y =
let sx = x - padding
let sy = y - padding
if sx < 0 || sx >= width || sy < 0 || sy >= height then 0.0
else
let row = if direction=TabDown then height-1-sy else sy
float mask.[row * width + sx] / 255.0
let mutable solid = 0.0
for weight in kernel do solid <- solid + weight
let fullSum = 255 * kernel.Length
let mutable globalMinY = h
let mutable globalMaxY = -1
for y in padding .. padding + height - 1 do
let sy = y-padding
let row = if direction=TabDown then height-1-sy else sy
let sy = y - padding
let rowBase = (if direction=TabDown then height-1-sy else sy) * width
prefix.[0] <- 0
for x in 0..width-1 do prefix.[x+1] <- prefix.[x] + int mask.[row*width+x]
for x in 0 .. w - 1 do
let left,right = max 0 (x-padding*2),min width (x+1)
let sum = prefix.[right]-prefix.[min width left]
let mutable v = if sum=255*kernel.Length then solid else 0.0
// Long opaque or empty runs need no convolution. At edges,
// preserve the original kernel and summation order exactly.
if sum<>0 && sum<>255*kernel.Length then
for k in -padding .. padding do
v <- v + sample (x + k) y * kernel.[k + padding]
horizontal.[y * w + x] <- v
for x in 0 .. width - 1 do prefix.[x+1] <- prefix.[x] + int mask.[rowBase + x]
if prefix.[width] > 0 then
if y < globalMinY then globalMinY <- y
globalMaxY <- y
let rowOffset = y * w
for x in 0 .. w - 1 do
let left,right = max 0 (x-padding*2), min width (x+1)
let sum = prefix.[right] - prefix.[min width left]
if sum <> 0 then
let mutable v = if sum = fullSum then solid else 0.0
// Long opaque or empty runs need no convolution. At edges,
// preserve the original kernel and summation order exactly.
if sum <> fullSum then
let kStart = max -padding (padding - x)
let kEnd = min padding (padding + width - 1 - x)
for k in kStart .. kEnd do
let m = mask.[rowBase + (x + k - padding)]
if m <> 0uy then
v <- v + (float m / 255.0) * kernel.[k + padding]
horizontal.[rowOffset + x] <- v
if y < colMinY.[x] then colMinY.[x] <- y
colMaxY.[x] <- y
let bitmap = new Bitmap(w, h, PixelFormat.Format32bppArgb)
let data = bitmap.LockBits(Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
// Fade the side tails into the window junction. No bottom shadow row.
Expand All @@ -75,16 +89,29 @@ module TabShadow =
for y in 0 .. h - 1 do
Array.Clear(pixels,0,w*4)
let fade = if allSides then 1.0 else min 1.0 (float (h - 1 - y) / float fadeHeight)
for x in 0 .. w - 1 do
// The helper is owned by (and above) the strip; cut the tabs out.
let exterior = 1.0 - sample x y
if exterior>0.0 && fade>0.0 then
let mutable v = 0.0
for k in -padding .. padding do
let sy = y + k
if sy >= 0 && sy < h then
v <- v + horizontal.[sy * w + x] * kernel.[k + padding]
pixels.[x * 4 + 3] <- byte (Math.Round(64.0 * v * exterior * fade))
if fade > 0.0 && globalMaxY >= 0 && y + padding >= globalMinY && y - padding <= globalMaxY then
let inMaskY = y >= padding && y < padding + height
let maskRowBase =
if inMaskY then (if direction=TabDown then height-1-(y-padding) else y-padding) * width
else 0
for x in 0 .. w - 1 do
let maxY = colMaxY.[x]
if maxY >= 0 && y + padding >= colMinY.[x] && y - padding <= maxY then
// The helper is owned by (and above) the strip; cut the tabs out.
let sx = x - padding
let maskAlpha =
if inMaskY && sx >= 0 && sx < width then mask.[maskRowBase + sx]
else 0uy
if maskAlpha < 255uy then
let exterior = if maskAlpha = 0uy then 1.0 else 1.0 - float maskAlpha / 255.0
let kStart = max -padding (colMinY.[x] - y)
let kEnd = min padding (maxY - y)
let mutable v = 0.0
for k in kStart .. kEnd do
let hv = horizontal.[(y + k) * w + x]
if hv <> 0.0 then
v <- v + hv * kernel.[k + padding]
pixels.[x * 4 + 3] <- byte (Math.Round(64.0 * v * exterior * fade))
let targetY = if direction=TabDown then h-1-y else y
Marshal.Copy(pixels, 0, IntPtr.Add(data.Scan0, targetY * data.Stride), w * 4)
finally
Expand Down
43 changes: 42 additions & 1 deletion tests/GroupLifecycle.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ open Bemo.Json
let check condition message = if not condition then failwith message
/// Checks the state it saw rather than asking again, which can catch a later change.
let pumpUntil description predicate =
let timeoutMs = if TestInit.isCoverage then 20000L else 5000L
let clock = Diagnostics.Stopwatch.StartNew()
let mutable satisfied = predicate()
while not satisfied && clock.ElapsedMilliseconds < 5000L do
while not satisfied && clock.ElapsedMilliseconds < timeoutMs do
Application.DoEvents()
Thread.Sleep(5)
satisfied <- predicate()
Expand All @@ -28,6 +29,12 @@ let main() =
check (SwitchActivation.shouldRetry 1n 2n 1n) "An unchanged foreground should allow one switcher retry"
check (not(SwitchActivation.shouldRetry 1n 2n 2n)) "A completed activation must not be repeated"
check (not(SwitchActivation.shouldRetry 1n 2n 3n)) "A switcher retry must not steal focus from another window"
check ((GroupSnapshot.mergeOrder (List2([1n;2n])) (List2([1n])) ((=) 2n)).list = [1n;2n])
"An earlier tab's order update hid a pending optimistic add"
check ((GroupSnapshot.mergeOrder (List2([1n;2n])) (List2([1n])) (fun _ -> false)).list = [1n])
"A non-pending tab survived an authoritative order update"
check ((GroupSnapshot.mergeOrder (List2([1n;2n])) (List2([2n;1n])) ((=) 2n)).list = [2n;1n])
"Merging pending adds duplicated a tab already in the group's order"
let press = POINT(100,100)
check (BrowserTabDrag.moved press (POINT(450,200))) "A completed browser drag lost its displacement"
check (not (BrowserTabDrag.moved press press)) "A browser click looked like a drag"
Expand Down Expand Up @@ -178,6 +185,40 @@ let main() =
pumpUntil "Icon-default fixture did not exit" (fun () -> iconDefaults.isExited)
let nativeOrder info = onGroup info (fun group -> group.lorder.list)
let publicOrder (info:GroupInfo) = (info :> IGroup).windows.list
// An earlier tab's publishOrder must not hide a second window still queued on the group STA.
do
let pendingGroup = desktopApi.createGroup(false) :?> GroupInfo
use firstWin = new Form(ShowInTaskbar=false,StartPosition=FormStartPosition.Manual,Location=Drawing.Point(-20000,-20000))
use secondWin = new Form(ShowInTaskbar=false,StartPosition=FormStartPosition.Manual,Location=Drawing.Point(-20000,-20000))
use entered = new ManualResetEventSlim(false)
use release = new ManualResetEventSlim(false)
use afterFirst = new ManualResetEventSlim(false)
use releaseSecond = new ManualResetEventSlim(false)
try
pendingGroup.invokeGroup(fun () ->
entered.Set()
release.Wait(5000) |> ignore)
pumpUntil "Pending-add fixture did not reach the STA gate" (fun () -> entered.IsSet)
(pendingGroup :> IGroup).addWindow(firstWin.Handle,false)
pendingGroup.invokeGroup(fun () ->
afterFirst.Set()
releaseSecond.Wait(5000) |> ignore)
(pendingGroup :> IGroup).addWindow(secondWin.Handle,false)
release.Set()
pumpUntil "Pending-add fixture did not finish the first add" (fun () -> afterFirst.IsSet)
// Pump firstWin's posted publishOrder([firstWin]) while secondWin is still blocked behind releaseSecond.
for _ in 1..20 do Application.DoEvents(); Thread.Sleep(5)
check (publicOrder pendingGroup = [firstWin.Handle;secondWin.Handle])
(sprintf "publishOrder dropped a pending add: %A" (publicOrder pendingGroup))
releaseSecond.Set()
pumpUntil "Pending-add fixture did not attach both windows" (fun () ->
nativeOrder pendingGroup = [firstWin.Handle;secondWin.Handle] &&
publicOrder pendingGroup = [firstWin.Handle;secondWin.Handle])
finally
release.Set()
releaseSecond.Set()
(pendingGroup :> IGroup).destroy()
pumpUntil "Pending-add fixture did not exit" (fun () -> pendingGroup.isExited)
let checkStripOwner info =
onGroup info (fun group ->
let owner = WinUserApi.GetWindow(group.hwnd, GetWindowConstants.GW_OWNER)
Expand Down
15 changes: 9 additions & 6 deletions tests/GroupOperations.fsx
Original file line number Diff line number Diff line change
Expand Up @@ -1426,17 +1426,20 @@ let main() =
let followerForm = forms.[handles |> List.findIndex((=)follower)]
for command in [ShowWindowCommands.SW_SHOWMAXIMIZED;ShowWindowCommands.SW_SHOWNOACTIVATE] do
onHelper(fun () -> OS().windowFromHwnd(source).showWindow(command))
// Drain placement's strip/shadow refresh on the group STA before arming the
// follower pause, so an async shadow sync cannot restack the owner chain mid-check.
onGroup(fun group ->
let top = OS().windowFromHwnd(source)
let field = typeof<WindowGroup>.GetFields(flags) |> Array.find(fun field -> field.Name="placement")
let cell = field.GetValue(group)
cell.GetType().GetMethod("set").Invoke(cell,[|box (Some(top.bounds,top.placement,top.visibleBounds))|]) |> ignore)
onGroup ignore
use entered = new ManualResetEventSlim(false)
use resume = new ManualResetEventSlim(false)
onHelper(fun () -> followerForm.HoldNextPositionChanged(source,entered,resume))
let focused = WinUserApi.GetForegroundWindow()
try
onGroup(fun group ->
let top = OS().windowFromHwnd(source)
let field = typeof<WindowGroup>.GetFields(flags) |> Array.find(fun field -> field.Name="placement")
let cell = field.GetValue(group)
cell.GetType().GetMethod("set").Invoke(cell,[|box (Some(top.bounds,top.placement,top.visibleBounds))|]) |> ignore
invoke "updatePlacements" group [||] |> ignore)
onGroup(fun group -> invoke "updatePlacements" group [||] |> ignore)
check (entered.Wait(10000)) "Follower placement did not enter its stacking-correction phase"
let topmost () =
let pid = Diagnostics.Process.GetCurrentProcess().Id
Expand Down
Loading