nano-ui-0.2.0.0: lib/NanoUI/Internal/Frame/Scroll.hs
-- | Scroll input: offsets baked into the arena, wheel routing, and scrollbar
-- thumb drags and track jumps.
module NanoUI.Internal.Frame.Scroll
( applyScrollOffsets
, updateScrollWheel
, updateScrollDrag
, refreshScrollBarHover
, probeScrollBarHover
, scrollBarsFor
, scrollBarLayout
, ScrollBarLayout (..)
)
where
import Control.Monad (forM, forM_, join, unless, when)
import Data.Foldable (find)
import Data.Functor ((<&>))
import Data.IORef (newIORef, readIORef, writeIORef)
import Data.Maybe (fromMaybe, isJust)
import Data.Primitive.PrimArray (readPrimArray)
import NanoUI.Internal.Context
import NanoUI.Internal.Frame.Hit (overlayHitAllowed, overlayHitRoot, passesPointer)
import NanoUI.Internal.Frame.Node (childPaintClip, readScrollNode)
import NanoUI.Internal.Layout.ScrollGeometry
import NanoUI.Internal.Frame.TextArea (TextAreaBars (..), textAreaBarLayouts, textAreaScrollGeom)
import NanoUI.Internal.Id (WidgetId (..))
import NanoUI.Internal.Font (ScrollBarSlot (..))
import NanoUI.Internal.Monad (ifM, (<&&>))
import NanoUI.Internal.Input
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Layout.Solve (scrollBarSlotOf)
import NanoUI.Internal.Style (Flow (..), Padding (..), PointerMode (..))
import NanoUI.Internal.Types (Rect (..), Size (..), V2 (..), rectContains, rectInflate, rectIntersect, rectUnion, writeRectAt)
import NanoUI.Internal.WidgetText (containerFlagClip, hasFlag)
-- | Offset every node by its enclosing scrollers and set its clip. The root
-- clips to the window, as in paint, so a root smaller than its content still
-- draws the overflow.
applyScrollOffsets :: Context -> Size -> IO ()
applyScrollOffsets ctx (Size w h) = do
beginScrollMetrics ctx
-- A frame that added no widgets has no root to walk.
count <- arenaCount (ctxNodeArena ctx)
when (count > 0) $ do
a <- arenaArrays (ctxNodeArena ctx)
transformSubtree ctx a 0 0 0 0 0 w h
-- | Walk a subtree applying accumulated scroll offsets and writing each node's
-- clip rect. Kept unboxed over coordinates and clip bounds so non-scrolling
-- leaves and plain containers allocate nothing.
transformSubtree :: Context -> NodeArenaArrays -> NodeIdx -> Float -> Float -> Float -> Float -> Float -> Float -> IO ()
transformSubtree ctx a !idx !scrollX !scrollY !pcx !pcy !pcw !pch = do
nt <- readTagEnum a idx TagNodeType
let !geom = naArrGeom a
!gOff = idx * geomStride
!lx <- readPrimArray geom gOff
!ly <- readPrimArray geom (gOff + 1)
!vw <- readPrimArray geom (gOff + 2)
!vh <- readPrimArray geom (gOff + 3)
let !floating = isFloatingNode nt
!sx = if floating then 0 else scrollX
!sy = if floating then 0 else scrollY
!vx = lx + sx
!vy = ly + sy
-- With no offset on either axis the placed rect equals the laid-out one, so
-- the write is a no-op; a floating node always takes that path.
unless (sx == 0 && sy == 0) $ writeRectAt geom gOff vx vy vw vh
kids <- readTree a idx TreeFirstChild
if floating
then do
-- A floating node is painted in its own rect, wherever it was declared.
writeClipRectRaw a idx vx vy vw vh
unless (kids < 0) $ descendSubtree ctx a kids 0 0 vx vy vw vh
else if kids < 0 && not (isScrollNode nt || nt == NodePanel)
then writeClipRectRaw a idx pcx pcy pcw pch
else case nt of
NodeContainer -> do
writeClipRectRaw a idx pcx pcy pcw pch
si <- readStyleIdx a idx
if hasFlag containerFlagClip si
then do
let !x0 = max pcx vx
!y0 = max pcy vy
!x1 = min (pcx + pcw) (vx + vw)
!y1 = min (pcy + pch) (vy + vh)
if x1 > x0 && y1 > y0
then descendSubtree ctx a kids sx sy x0 y0 (x1 - x0) (y1 - y0)
else descendSubtree ctx a kids sx sy vx vy 0 0
else descendSubtree ctx a kids sx sy pcx pcy pcw pch
_ -> transformSpecialNode ctx a idx nt kids sx sy vx vy vw vh pcx pcy pcw pch
descendSubtree :: Context -> NodeArenaArrays -> NodeIdx -> Float -> Float -> Float -> Float -> Float -> Float -> IO ()
descendSubtree ctx a !first !sx !sy !ccx !ccy !ccw !cch = go first
where
go !ci
| ci < 0 = pure ()
| otherwise = do
transformSubtree ctx a ci sx sy ccx ccy ccw cch
ns <- readTree a ci TreeNextSibling
go ns
-- | Scroll containers, panels, and widgets with children: compute their inner
-- clip via 'childPaintClip' and update scroll offsets out of line from the
-- zero-allocation container/leaf fast path.
{-# NOINLINE transformSpecialNode #-}
transformSpecialNode ::
Context -> NodeArenaArrays -> NodeIdx -> NodeType -> NodeIdx ->
Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> IO ()
transformSpecialNode ctx a !idx nt !kids !sx !sy !vx !vy !vw !vh !pcx !pcy !pcw !pch = do
let !rect = Rect vx vy vw vh
!records = isScrollNode nt || nt == NodePanel
mClip <- childPaintClip ctx idx nt rect
case mClip of
Nothing -> do
writeClipRectRaw a idx pcx pcy pcw pch
if isScrollNode nt
then do
(dx, dy) <- updateScrollNodeOffset ctx a idx rect
unless (kids < 0) $ descendSubtree ctx a kids (sx - dx) (sy - dy) pcx pcy pcw pch
else unless (kids < 0) $ descendSubtree ctx a kids sx sy pcx pcy pcw pch
Just (Rect rx ry rw rh) -> do
let !x0 = max pcx rx
!y0 = max pcy ry
!x1 = min (pcx + pcw) (rx + rw)
!y1 = min (pcy + pch) (ry + rh)
!hit = x1 > x0 && y1 > y0
!icx = if hit then x0 else rx
!icy = if hit then y0 else ry
!icw = if hit then x1 - x0 else 0
!ich = if hit then y1 - y0 else 0
if records
then writeClipRectRaw a idx icx icy icw ich
else writeClipRectRaw a idx pcx pcy pcw pch
if isScrollNode nt
then do
(dx, dy) <- updateScrollNodeOffset ctx a idx rect
unless (kids < 0) $ descendSubtree ctx a kids (sx - dx) (sy - dy) icx icy icw ich
else unless (kids < 0) $ descendSubtree ctx a kids sx sy icx icy icw ich
-- | Record a scroll container's solved geometry and clamp its offset, returning
-- the effective @(dx, dy)@ offset to subtract from its children. Kept out of
-- line from 'transformSubtree' so non-scrolling nodes keep a tiny loop body.
{-# NOINLINE updateScrollNodeOffset #-}
updateScrollNodeOffset :: Context -> NodeArenaArrays -> NodeIdx -> Rect -> IO (Float, Float)
updateScrollNodeOffset ctx a idx rect = do
(axes, viewport, range) <- scrollNodeGeometry ctx idx rect
wid <- WidgetId . fromIntegral <$> readTree a idx TreeWidgetId
-- The only pass that sees a scroller's placed geometry. Everything
-- that scrolls one between frames reads it back from here.
owner <- cacheScrollMetrics ctx wid axes viewport range
when owner $ applyPendingScrollOffset ctx wid axes
-- An offset set outright before this layout, or left over from
-- content that has since shrunk, is held to the range the content
-- has now, on the axes this scroller owns. Only the node that owns the
-- id this frame holds it: another with the same id (a table's frozen
-- pane, whose range lacks the body's bar lane) would hold the body short
-- of its end.
cur@(V2 cx cy) <- getScrollOffsetIn ctx wid axes
let
V2 hx hy = clampScrollOffset range cur
held = case axes of
ScrollAxisY -> V2 cx hy
ScrollAxisX -> V2 hx cy
ScrollAxisXY -> V2 hx hy
V2 ox oy = if owner then held else cur
-- A 1D scroller moves its content on its own axis only: the other
-- slot can hold an offset for one sharing its id (a frozen pane
-- follows its table's body down, not across).
(dx, dy) = case axes of
ScrollAxisY -> (0, oy)
ScrollAxisX -> (ox, 0)
ScrollAxisXY -> (ox, oy)
when (owner && held /= cur) $ setScrollOffsetIn ctx wid axes held
when owner $ placeScrollContent ctx wid dx dy
pure (dx, dy)
-- | Axes, content viewport and reachable offset range of the scroll container
-- at @idx@ placed at @rect@, in window axes. Shared by the mouse wheel and
-- the scroll-offset transform pass; scroll commands read what the latter
-- publishes ('cacheScrollMetrics').
scrollNodeGeometry :: Context -> NodeIdx -> Rect -> IO (ScrollAxes, Rect, V2)
scrollNodeGeometry ctx idx (Rect x y w h) = do
sn@ScrollNode {snPad = pad, snContentMain = contentMain} <-
readScrollNode (ctxNodeArena ctx) idx
let
viewport = scrollNodeViewport sn x y w h
rangeW content = scrollAxisRange content (rectW viewport) (padR pad)
rangeH = scrollAxisRange contentMain (rectH viewport) (padB pad)
pure $
if sn2D sn
then (ScrollAxisXY, viewport, V2 (rangeW (snContentW sn)) rangeH)
else case snDir sn of
DirColumn -> (ScrollAxisY, viewport, V2 0 rangeH)
DirRow -> (ScrollAxisX, viewport, V2 (rangeW contentMain) 0)
updateScrollWheel :: Context -> Input -> IO ()
updateScrollWheel ctx inp = do
let
scroll@(V2 wheelX wheelY) = inputScroll inp
-- A wheel over an open dropdown or the text-edit menu never gets here: the
-- combo widget scrolls its own list, and the scroller under it stays put.
when (wheelY /= 0 || wheelX /= 0) $ do
mNode <- findScrollNodeUnderMouse ctx (inputWindowSize inp) (inputMousePos inp)
forM_ mNode $ \idx -> do
wid <- getWidgetId (ctxNodeArena ctx) idx
V2 rangeX rangeY <- applyScrollWheelDelta ctx wid scroll
-- Pass on only the axes this scroller cannot move. A bare one, a tab
-- strip, pages on the vertical wheel itself and passes on nothing.
nt <- getNodeType (ctxNodeArena ctx) idx
bare <- if isScrollNode nt then scrollBare . snConfig <$> readScrollNode (ctxNodeArena ctx) idx else pure False
unless bare $
applyCrossAxisScroll ctx idx (inputMousePos inp) (V2 (if rangeX > 0 then 0 else wheelX) (if rangeY > 0 then 0 else wheelY))
-- Nested 2D: apply the unused axis to a paired scroller that runs the other
-- way, or either way when one of the two is 2D: the nearest one above in the
-- same panel, else one inside, under @mouse@ if one is. Do not walk past a
-- panel or a floating node (window, modal, popup) into the page scroller.
applyCrossAxisScroll :: Context -> NodeIdx -> V2 -> V2 -> IO ()
applyCrossAxisScroll ctx@Context {ctxNodeArena = na} idx mouse scroll = do
dir <- getDirection na idx
let is2D i = isScrollStyle2D <$> getStyleIdx na i
self2D <- getNodeType na idx >>= \nt -> if nt == NodeTextArea then pure True else is2D idx
let
crosses i
| self2D = pure True
| otherwise = (||) <$> is2D i <*> ((/= dir) <$> getDirection na i)
crossWid under i = do
nt <- getNodeType na i
hit <- pure (isScrollNode nt) <&&> crosses i <&&> (if under then rectContains <$> getNodeRect na i <*> pure mouse else pure True)
if hit then Just <$> getWidgetId na i else pure Nothing
above i = do
nt <- getNodeType na i
if nt == NodePanel || isFloatingNode nt
then pure (Just Nothing)
else fmap Just <$> crossWid False i
-- Only subtrees holding a scroller can hold a cross one, and a floating
-- node's scrollers are its own.
inside under i = firstChildJustM na i $ \ci ->
ifM
((not . isFloatingNode <$> getNodeType na ci) <&&> hasScrollerBelow na ci)
(crossWid under ci >>= maybe (inside under ci) (pure . Just))
(pure Nothing)
parent <- getParent na idx
up <- join <$> walkAncestors na parent above
-- One under the pointer whose content fits takes the axis as a no-op,
-- rather than one elsewhere on the page.
target <- maybe (inside True idx >>= maybe (inside False idx) (pure . Just)) (pure . Just) up
forM_ target $ \wid -> applyScrollWheelDelta ctx wid scroll
-- | Node owning scroller @wid@: its text area, or the first scroll container
-- with that id that the predicate does not rule out (table slave panes share
-- an id with their master). Thumb drags use the chrome predicate, since a
-- hidden bar has no lane to grab; the wheel uses the wider one, since a
-- hidden bar still scrolls.
scrollOwnerNode ::
(ScrollConfig -> Bool -> DirTag -> Bool)
-> Context
-> WidgetId
-> IO (Maybe NodeIdx)
scrollOwnerNode suppressed Context {ctxNodeArena = na} wid =
findClassNodeM na ScrollableNodes $ \idx -> do
nt <- getNodeType na idx
((== wid) <$> getWidgetId na idx)
<&&> if nt == NodeTextArea
then pure True
else (\sn -> not (suppressed (snConfig sn) (sn2D sn) (snDir sn))) <$> readScrollNode na idx
-- | Axes and offset range of the node the wheel moves for scroller @wid@,
-- 'Nothing' when it has no node.
wheelAxesRange :: Context -> WidgetId -> IO (Maybe (ScrollAxes, V2))
wheelAxesRange ctx@Context {ctxNodeArena = na} wid = do
-- A node whose bar shows comes first: a table's frozen pane shares its
-- body's id with a hidden bar and a range of one axis, and would clamp the
-- body's horizontal wheel away.
mIdx <-
scrollOwnerNode (\cfg _ dir -> scrollChromeSuppressed cfg dir) ctx wid
>>= maybe (scrollOwnerNode scrollWheelSuppressed ctx wid) (pure . Just)
forM mIdx $ \idx -> do
nt <- getNodeType na idx
if nt == NodeTextArea
then (ScrollAxisXY,) . tabRange . snd <$> textAreaScrollGeom ctx idx
else do
rect <- getNodeRect na idx
(axes, _, range) <- scrollNodeGeometry ctx idx rect
pure (axes, range)
-- | Scroll @wid@ by the wheel and return its offset range, zero when it has
-- no node.
applyScrollWheelDelta :: Context -> WidgetId -> V2 -> IO V2
applyScrollWheelDelta ctx wid (V2 wheelX wheelY) = do
mGeom <- wheelAxesRange ctx wid
fmap (fromMaybe (V2 0 0)) . forM mGeom $ \(axes, range) -> do
step <- resolveScrollStep ctx wid
cur <- getScrollOffsetIn ctx wid axes
-- Notches land on where the scroller is headed, not on where it is, so
-- a flick mid-glide adds to the throw instead of restarting it.
base@(V2 baseX baseY) <- scrollTargetOffset ctx wid cur
let
next = clampScrollOffset range (V2 (baseX + wheelX * step) (baseY + wheelY * step))
unless (next == base && next == cur) $
applyScrollTarget ctx wid axes next ScrollSmooth
pure range
findScrollNodeUnderMouse :: Context -> Size -> V2 -> IO (Maybe NodeIdx)
findScrollNodeUnderMouse ctx (Size w h) mouse = do
count <- arenaCount (ctxNodeArena ctx)
if count <= 0
then pure Nothing
else do
-- Start where the pointer is confined: the open modal (or a panel
-- inside it), else the window or popup under it. Off a modal's rect
-- the wheel then finds nothing, as the content behind it is blocked.
top <- overlayHitRoot ctx mouse
-- The page root clips to the window, as 'applyScrollOffsets' clips it,
-- so a scroller in the root's overflow takes the wheel where it is
-- drawn; a floating panel clips to itself.
rect <- maybe (pure (Rect 0 0 w h)) (getNodeRect (ctxNodeArena ctx)) top
layered <- (> 0) <$> layeredNodeCount (ctxNodeArena ctx)
queryScrollTarget ctx layered mouse rect (fromMaybe 0 top) <&> \case
WheelTo idx -> Just idx
_ -> Nothing
-- | Result of wheel hit testing on a subtree.
data WheelHit
= WheelMiss
-- ^ Nothing in the subtree takes the wheel here.
| WheelBlocked
-- ^ A 'PointerBlock' node without a scroller is on top here. Nodes
-- beneath it do not get the wheel, but an enclosing scroller still does.
| WheelTo !NodeIdx
-- ^ This scroller takes the wheel.
-- | Wheel target at @mouse@ in the subtree at @idx@: the topmost matching
-- child result, else @idx@ itself if it is a scroller under the pointer. Where
-- children can overlap (@layered@ is set and this node is 'Layered' or has a
-- pinned descendant), they are tested topmost first ('firstChildOnTopJustM')
-- so a scroller pinned over another wins; otherwise children are tested in
-- arena sibling order.
queryScrollTarget :: Context -> Bool -> V2 -> Rect -> NodeIdx -> IO WheelHit
queryScrollTarget ctx@Context {ctxNodeArena = na} layered mouse parentClip idx = do
nt <- getNodeType na idx
scrollHitClip ctx idx nt parentClip >>= \case
Nothing -> pure WheelMiss
Just (clip, kidsClip) -> do
overlapping <-
pure layered <&&> ((||) <$> ((== Layered) <$> getFlow na idx) <*> hasPinnedBelow na idx)
-- Skip subtrees that contain no scroller, text area, or 'PointerBlock' node.
let answered c = ifM (hasScrollerBelow na c) (query c) (pure Nothing)
query c =
queryScrollTarget ctx layered mouse kidsClip c <&> \case
WheelMiss -> Nothing
hit -> Just hit
inner <-
fromMaybe WheelMiss <$> (if overlapping then firstChildOnTopJustM else firstChildJustM) na idx answered
case inner of
WheelTo _ -> pure inner
_ -> ifM (scrollHitSelf ctx idx nt mouse clip) (pure (WheelTo idx)) $ do
blocks <-
pure layered
<&&> ((== PointerBlock) <$> getPointerMode na idx)
<&&> (rectContains <$> getNodeRect na idx <*> pure mouse)
<&&> pure (rectContains clip mouse)
pure (if blocks then WheelBlocked else inner)
-- | Whether node @idx@ takes the wheel at @mouse@: a scroll container whose
-- viewport or bar lanes contain it, or a text area, with something to scroll.
-- A scroller whose content fits leaves the wheel to the one around it. A
-- 'PointerPass' node never takes it.
scrollHitSelf :: Context -> NodeIdx -> NodeType -> V2 -> Rect -> IO Bool
scrollHitSelf ctx@Context {ctxNodeArena = na} idx nt mouse clip
| nt == NodeTextArea =
takes <&&> do
(field, bars) <- textAreaScrollGeom ctx idx
pure (rectContains clip mouse && rectContains field mouse && (tabVertical bars || tabHorizontal bars))
| isScrollNode nt =
pure (rectContains clip mouse) <&&> takes <&&> do
(_, _, V2 rx ry) <- scrollNodeGeometry ctx idx =<< getNodeRect na idx
-- Without a range of its own, the range the wheel moves: a table's
-- frozen pane has none, and its body, which shares its id, does.
if rx > 0 || ry > 0
then pure True
else do
wid <- getWidgetId na idx
maybe False (\(_, V2 wx wy) -> wx > 0 || wy > 0) <$> wheelAxesRange ctx wid
| otherwise = pure False
where
takes = not <$> passesPointer na idx
-- The clip node @idx@ takes the wheel in, and the one its children do, as
-- paint clips them: a scroller takes it over its viewport and bar lanes, and
-- its children over the viewport alone; other containers give their children
-- the clip 'childPaintClip' says.
scrollHitClip :: Context -> NodeIdx -> NodeType -> Rect -> IO (Maybe (Rect, Rect))
scrollHitClip ctx@Context {ctxNodeArena = na} idx nt parentClip
| isScrollNode nt = do
Rect x y w h <- getNodeRect na idx
sn <- readScrollNode na idx
let
lane d = scrollChromeLane (snSlot sn) d x y w h (snPad sn)
viewport = scrollNodeViewport sn x y w h
hit
| sn2D sn = rectUnion viewport (rectUnion (lane DirColumn) (lane DirRow))
| otherwise = rectUnion viewport (lane (snDir sn))
-- Empty when the viewport is clipped away, so no child takes it.
kids = fromMaybe (Rect x y 0 0) (rectIntersect parentClip viewport)
pure ((,kids) <$> rectIntersect parentClip hit)
| isContainerNode nt =
fmap (\c -> (c, c)) . maybe (Just parentClip) (rectIntersect parentClip)
<$> (childPaintClip ctx idx nt =<< getNodeRect na idx)
| otherwise = pure (Just (parentClip, parentClip))
-- | Scrollbar layouts of the scroller at @idx@ (id @wid@), each paired with a
-- setter for that axis's offset that skips unchanged values. Covers text
-- areas and native 2D and 1D scroll containers; a 1D scroller with suppressed
-- chrome has none.
scrollBarsFor ::
Context -> NodeIdx -> WidgetId -> IO [(DirTag, ScrollBarLayout, Float -> IO ())]
scrollBarsFor ctx@Context {ctxNodeArena = na} idx wid = do
nt <- getNodeType na idx
-- A 1D scroller's offset is its stored y, whichever way it runs.
V2 curX curY <- getScrollOffset2D ctx wid
let
setMain new = when (new /= curY) (setScrollOffset ctx wid new)
setX new = when (new /= curX) (setScrollOffset2D ctx wid (V2 new curY))
bar dir mLayout set = [(dir, layout, set) | Just layout <- [mLayout]]
bars twoD (mV, mH) = bar DirColumn mV setMain ++ bar DirRow mH (if twoD then setX else setMain)
if nt == NodeTextArea
then (\(field, tab) -> bars True (textAreaBarLayouts field tab curX curY)) <$> textAreaScrollGeom ctx idx
else do
Rect x y w h <- getNodeRect na idx
sn <- readScrollNode na idx
pure (bars (sn2D sn) (scrollNodeBars sn x y w h curX curY))
-- | Bars of scroller @wid@ a thumb drag can grab. A hidden bar has no lane
-- to grab.
grabbableBars :: Context -> WidgetId -> IO [(DirTag, ScrollBarLayout, Float -> IO ())]
grabbableBars ctx wid =
maybe (pure []) (\idx -> scrollBarsFor ctx idx wid)
=<< scrollOwnerNode (\cfg _ dir -> scrollChromeSuppressed cfg dir) ctx wid
updateScrollDrag :: Context -> Input -> IO ()
updateScrollDrag ctx inp
| releasedIn MouseLeft inp =
modifyInteraction ctx (\s -> s {isScrollDrag = Nothing})
| otherwise = do
mDrag <- getsInteraction ctx isScrollDrag
case mDrag of
Just (wid, dragDir, grabOff)
| heldIn MouseLeft inp -> do
bars <- grabbableBars ctx wid
forM_ bars $ \(dir, layout, setOffset) ->
when (dir == dragDir) $
setOffset (scrollOffsetFromThumb dir layout grabOff (inputMousePos inp))
| otherwise ->
-- Release was lost (e.g. focus loss or overlay routing); clear
-- the drag so 'needsRedraw' does not spin idle frames forever.
modifyInteraction ctx (\s -> s {isScrollDrag = Nothing})
Nothing | pressedIn MouseLeft inp -> tryStartScrollDrag ctx inp
_ -> pure ()
-- | Grab a thumb, or jump the thumb's center to a track press and keep
-- dragging from there.
tryStartScrollDrag :: Context -> Input -> IO ()
tryStartScrollDrag ctx inp = do
let
mouse = inputMousePos inp
mIdx <- findScrollNodeUnderMouse ctx (inputWindowSize inp) mouse
forM_ mIdx $ \hitIdx -> do
wid <- getWidgetId (ctxNodeArena ctx) hitIdx
bars <- grabbableBars ctx wid
forM_ (find (\(_, l, _) -> onScrollBar mouse l) bars) $ \(dir, layout, setOffset) -> do
let
Rect tx ty tw th = sbThumb layout
along (V2 mx my) = if dir == DirColumn then my else mx
onThumb = rectContains (sbThumb layout) mouse
grab = if onThumb then along mouse - along (V2 tx ty) else along (V2 tw th) / 2
unless onThumb $ setOffset (scrollOffsetFromThumb dir layout grab mouse)
modifyInteraction ctx (\s -> s {isScrollDrag = Just (wid, dir, grab)})
-- | The scrollbar whose thumb is being dragged, else the one under the
-- pointer, as 'isScrollHover' holds it. While the button is down for any
-- other gesture there is none. The search visits only the pointer nodes, so
-- a frame pays no walk of the whole tree.
probeScrollBarHover :: Context -> Input -> IO (Maybe (WidgetId, DirTag, Rect))
probeScrollBarHover ctx@Context {ctxNodeArena = na} inp = do
mDrag <- getsInteraction ctx isScrollDrag
case mDrag of
Just (wid, dir, _) -> barWhere wid (\(d, _, _) -> d == dir) <$> grabbableBars ctx wid
Nothing
| heldIn MouseLeft inp || not (rectContains (Rect 0 0 winW winH) mouse) -> pure Nothing
| otherwise -> do
scCount <- scrollableNodeCount na
if scCount <= 0
then pure Nothing
else do
top <- overlayHitRoot ctx mouse
hitRef <- newIORef Nothing
let candidate idx = do
nt <- getNodeType na idx
let isScroll = isScrollNode nt
Rect rx ry rw rh <- getNodeRect na idx
-- A ScrollBarWindow bar sits outside the scroller's rect in
-- the enclosing window's padding, so expand its hit bounds.
pad <- if isScroll then (\s -> if s == ScrollBarWindow then 10 else 0) <$> scrollBarSlotOf na idx else pure 0
pure (rectContains (Rect rx ry (rw + pad) (rh + pad)) mouse)
<&&> do
-- A scroller's own clip is its viewport, short of its
-- bars; the clip around it is its parent's, cut to what
-- the parent gives its children (a clip container's
-- rect), which only a scroller or panel parent records.
owner <- if isScroll then getParent na idx else pure idx
let inside = maybe True (`rectContains` mouse)
if owner < 0
then pure True
else
(inside <$> getClipBounds na owner)
<&&> if owner == idx
then pure True
else do
ont <- getNodeType na owner
inside <$> (childPaintClip ctx owner ont =<< getNodeRect na owner)
<&&> overlayHitAllowed ctx top idx
<&&> do
wid <- getWidgetId na idx
hit <- barWhere wid (\(_, l, _) -> onScrollBar mouse l) <$> scrollBarsFor ctx idx wid
writeIORef hitRef hit
pure (isJust hit)
_ <- findClassNodeM na ScrollableNodes candidate
readIORef hitRef
where
mouse = inputMousePos inp
Size winW winH = inputWindowSize inp
barWhere wid p bars = (\(dir, l, _) -> (wid, dir, sbTrack l)) <$> find p bars
-- | Record the scrollbar the pointer is on ('probeScrollBarHover') and
-- repaint the bars it left and entered. Runs after layout.
refreshScrollBarHover :: Context -> Input -> IO ()
refreshScrollBarHover ctx inp = do
old <- getsInteraction ctx isScrollHover
new <- probeScrollBarHover ctx inp
unless (new == old) $ do
let bar (wid, dir, _) = (wid, dir)
-- The track's antialiased edge reaches a pixel past it.
damageBar (_, _, track) = damageRect ctx (rectInflate 1 track)
when (fmap bar old /= fmap bar new) $ mapM_ damageBar old >> mapM_ damageBar new
modifyInteraction ctx (\s -> s {isScrollHover = new})