packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Frame/Hit.hs

{-# OPTIONS_HADDOCK not-home #-}

-- | Hit tests against the node arena: finding a widget's node, testing a point
-- against a node's rect and clip, and deciding which nodes the modals and
-- floating panels leave reachable by the pointer.
module NanoUI.Internal.Frame.Hit
  ( findNodeByWidgetId
  , withWidgetNode
  , nodeInSubtree
  , widgetIdInSubtree
  , overlayHitAllowed
  , overlayHitRoot
  , topmostOverlayAtMouse
  , topmostFloating
  , widgetOverlayAllowed
  , widgetInModal
  , nodePointVisible
  , nodeClippedHit
  , nodeInteractionHit
  , takesPointer
  , passesPointer
  , reachedAt
  , reachedWidgetAt
  , reachedHit
  , innermostHit
  , topmostHit
  , innermostNodeAt
  )
where

import Control.Applicative ((<|>))
import Control.Monad ((<=<))
import Control.Monad.Trans.Maybe (MaybeT (..))
import Data.Maybe (isJust)
import Data.Primitive.PrimArray (readPrimArray)
import NanoUI.Internal.Context
import NanoUI.Internal.Id (WidgetId)
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Monad (ifM, (<&&>))
import NanoUI.Internal.Style (PointerMode (..))
import NanoUI.Internal.Types (Rect (..), V2 (..), rectContains)
import NanoUI.Internal.WidgetText (containerFlagInert, hasFlag)

-- | The node that carries widget id @wid@ in this frame's arena. 'Nothing' for
-- @WidgetId 0@ and for a widget the view has not declared this frame. When
-- several nodes carry the id, this is the one most recently indexed under it.
-- Widget interaction code calls this rather than 'lookupNodeByWidgetId':
-- keeping the lookup out of line allocates less per widget.
findNodeByWidgetId :: Context -> WidgetId -> IO (Maybe NodeIdx)
findNodeByWidgetId ctx wid = lookupNodeByWidgetId (ctxNodeArena ctx) wid

-- | Run the callback on a widget's current node, or return the supplied
-- default when the id has no node.
{-# INLINE withWidgetNode #-}
withWidgetNode :: Context -> WidgetId -> a -> (NodeIdx -> IO a) -> IO a
withWidgetNode ctx wid def k = findNodeByWidgetId ctx wid >>= maybe (pure def) k

-- | Whether node @idx@ is node @top@ or one of its descendants.
nodeInSubtree :: Context -> NodeIdx -> NodeIdx -> IO Bool
nodeInSubtree ctx idx top =
  isJust
    <$> walkAncestors
      (ctxNodeArena ctx)
      idx
      (\i -> pure (if i == top then Just () else Nothing))

-- | Whether the node of widget @wid@ is node @root@ or one of its
-- descendants. 'False' when the widget has no node this frame. The root is a
-- node index, so a caller that tests many widgets looks it up once.
widgetIdInSubtree :: Context -> NodeIdx -> WidgetId -> IO Bool
widgetIdInSubtree ctx root wid = withWidgetNode ctx wid False (\idx -> nodeInSubtree ctx idx root)

-- | The floating panel that the pointer at @mouse@ is confined to, for
-- 'overlayHitAllowed'. While a modal is open it is the top modal, or a panel
-- inside it under the point that is painted over it there: a popup, or a
-- window off the modal's rect (paint puts windows under modals). Otherwise
-- it is the topmost window or popup under the point. 'Nothing' anywhere
-- else. A caller that tests many nodes looks it up once.
overlayHitRoot :: Context -> V2 -> IO (Maybe NodeIdx)
overlayHitRoot ctx@Context {ctxNodeArena = na} mouse = do
  -- Most frames have no floating panel, and then nothing needs looking up.
  floating <- floatingNodeCount na
  if floating <= 0
    then pure Nothing
    else do
      over <- topmostOverlayAtMouse ctx mouse
      topModalNode na >>= \case
        Nothing -> pure over
        -- Searching the whole modal would find whatever it holds under a
        -- popup of its own (a context menu over a row) before the popup.
        Just modal -> case over of
          Just o -> do
            inside <- nodeInSubtree ctx o modal
            under <- ((/= NodePopup) <$> getNodeType na o) <&&> (rectContains <$> getNodeRect na modal <*> pure mouse)
            pure (Just (if inside && not under then o else modal))
          Nothing -> pure (Just modal)

-- | Whether the pointer can reach node @idx@ past the floating panels: every
-- node can when the 'overlayHitRoot' is 'Nothing', otherwise only the nodes
-- inside it and not inside another panel declared in it (a window in a
-- modal, painted under the modal). Strict in the index, which the per-node hit
-- loops then pass unboxed: boxed, it cost every pointer node an allocation a
-- frame.
overlayHitAllowed :: Context -> Maybe NodeIdx -> NodeIdx -> IO Bool
overlayHitAllowed ctx top !idx = maybe (pure True) (nodeInPanel ctx idx) top

-- | Whether node @idx@ is floating panel @panel@ or inside it, and not inside
-- another panel declared in it.
nodeInPanel :: Context -> NodeIdx -> NodeIdx -> IO Bool
nodeInPanel Context {ctxNodeArena = na} idx panel =
  (== Just True) <$> walkAncestors na idx (\i -> if i == panel then pure (Just True) else stop <$> getNodeType na i)
 where
  stop nt = if isFloatingNode nt then Just False else Nothing

-- | The interactive window or popup on top at @mouse@, skipping 'PointerPass'
-- floating panels such as tooltips. The frame paints every popup over every
-- window, so a popup whose rect holds the point wins; among panels of one
-- kind, the last in arena order.
topmostOverlayAtMouse :: Context -> V2 -> IO (Maybe NodeIdx)
topmostOverlayAtMouse ctx mouse =
  runMaybeT $
    MaybeT (topmostPointerFloating ctx (== NodePopup) (`rectContains` mouse))
      <|> MaybeT (topmostPointerFloating ctx (== NodeWindow) (`rectContains` mouse))

topmostPointerFloating :: Context -> (NodeType -> Bool) -> (Rect -> Bool) -> IO (Maybe NodeIdx)
topmostPointerFloating Context {ctxNodeArena = na} wanted at =
  findClassNodeRevM na FloatingNodes $ \idx ->
    (wanted <$> getNodeType na idx)
      <&&> ((/= PointerPass) <$> getPointerMode na idx)
      <&&> (at <$> getNodeRect na idx)

-- | The last floating node in arena order whose type satisfies @wanted@ and
-- whose rect satisfies @at@. The frame paints the panels of one type in arena
-- order, so among them the last one is on top.
topmostFloating :: Context -> (NodeType -> Bool) -> (Rect -> Bool) -> IO (Maybe NodeIdx)
topmostFloating ctx wanted at =
  findClassNodeRevM (ctxNodeArena ctx) FloatingNodes $ \idx ->
    (wanted <$> getNodeType (ctxNodeArena ctx) idx) <&&> (at <$> getNodeRect (ctxNodeArena ctx) idx)

-- | Whether widget @wid@ is reachable past modals: always with no modal
-- open, otherwise only inside the top modal. Only a reachable widget shows
-- its own dropdown or menu, or takes focus.
widgetOverlayAllowed :: Context -> WidgetId -> IO Bool
widgetOverlayAllowed ctx wid = do
  top <- topModalNode (ctxNodeArena ctx)
  widgetInModal ctx top wid

-- | 'widgetOverlayAllowed' with the top modal ('topModalNode') supplied by
-- the caller, which looks it up once when it tests many widgets.
widgetInModal :: Context -> Maybe NodeIdx -> WidgetId -> IO Bool
widgetInModal ctx top wid = maybe (pure True) (\modal -> widgetIdInSubtree ctx modal wid) top

-- | Whether @mouse@ is on the visible part of node @idx@: inside its non-empty
-- rect, and inside its clip rect when it has one. An empty clip (a viewport
-- entirely outside its parent's) contains no point. It reads this frame's
-- solved geometry, which is complete once
-- 'NanoUI.Internal.Frame.Scroll.applyScrollOffsets' has run.
{-# INLINE nodePointVisible #-}
nodePointVisible :: Context -> NodeIdx -> V2 -> IO Bool
nodePointVisible ctx idx (V2 mx my) = do
  a <- arenaArrays (ctxNodeArena ctx)
  let !geom = naArrGeom a
      !gOff = idx * geomStride
  !vx <- readPrimArray geom gOff
  !vy <- readPrimArray geom (gOff + 1)
  !vw <- readPrimArray geom (gOff + 2)
  !vh <- readPrimArray geom (gOff + 3)
  if not (vw > 0 && vh > 0 && mx >= vx && mx <= vx + vw && my >= vy && my <= vy + vh)
    then pure False
    else do
      !cx <- readPrimArray geom (gOff + 4)
      !cy <- readPrimArray geom (gOff + 5)
      !cw <- readPrimArray geom (gOff + 6)
      !ch <- readPrimArray geom (gOff + 7)
      pure $!
        if cw > 0 && ch > 0
          then mx >= cx && mx <= cx + cw && my >= cy && my <= cy + ch
          else not (cw < 0)

-- | 'nodePointVisible' with the rect supplied by the caller, for a widget
-- whose hit rect differs from its node's rect. A node whose clip is unset, as
-- before 'NanoUI.Internal.Frame.Scroll.applyScrollOffsets' has run in a
-- frame, is tested against the clip recorded for its widget id on the
-- previous frame. An empty clip, live or recorded, contains no point.
{-# INLINE nodeClippedHit #-}
nodeClippedHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool
nodeClippedHit ctx@Context {ctxNodeArena = na} idx rect mouse =
  pure (rectContains rect mouse) <&&> do
    mLive <- getClipBounds na idx
    mClip <- case mLive of
      Just _ -> pure mLive
      Nothing -> getPrevClipRect ctx =<< getWidgetId na idx
    pure (maybe True (`rectContains` mouse) mClip)

-- | The hit test widgets use while the view runs, when this frame's layout is
-- not solved. @rect@ is the widget's rect from the previous frame
-- ('NanoUI.Internal.Context.getPrevRect'). The point must be inside it, and
-- inside the clip the widget was painted in on the previous frame
-- ('NanoUI.Internal.Context.getPrevClipRect'). That clip already holds every
-- scroll viewport, clipping container, panel and enclosing widget up to the
-- widget's floating panel, so content scrolled or cut out of view takes no
-- input there. A widget with no recorded clip is not constrained by one. The
-- node's own clip rect is not read: it is not set until
-- 'NanoUI.Internal.Frame.Scroll.applyScrollOffsets' runs.
{-# INLINE nodeInteractionHit #-}
nodeInteractionHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool
nodeInteractionHit ctx@Context {ctxNodeArena = na} idx rect mouse
  | not (rectContains rect mouse) = pure False
  | idx <= 0 = pure True
  | otherwise = maybe True (`rectContains` mouse) <$> (getPrevClipRect ctx =<< getWidgetId na idx)

-- | Whether node @idx@ takes the pointer when drawn on top ('PointerMode'):
-- widgets do by default, 'PointerBlock' nodes always, 'PointerPass' nodes
-- never.
{-# INLINE takesPointer #-}
takesPointer :: NodeArena -> NodeIdx -> IO Bool
takesPointer na idx =
  getPointerMode na idx >>= \case
    PointerAuto -> isWidgetNode <$> getNodeType na idx
    PointerBlock -> pure True
    PointerPass -> pure False

-- | Whether node @idx@ passes the pointer through ('PointerPass', set on it
-- or on an ancestor). Such a node takes no hover or presses.
{-# INLINE passesPointer #-}
passesPointer :: NodeArena -> NodeIdx -> IO Bool
passesPointer na idx = (== PointerPass) <$> getPointerMode na idx

-- | Whether node @idx@ takes the pointer ('takesPointer') and @mouse@ is on
-- its visible part ('nodePointVisible'), where floating panels leave it
-- reachable ('overlayHitAllowed', with @top@ from 'overlayHitRoot').
pointerHitAt :: Context -> Maybe NodeIdx -> V2 -> NodeIdx -> IO Bool
pointerHitAt ctx@Context {ctxNodeArena = na} top mouse idx =
  takesPointer na idx
    <&&> nodePointVisible ctx idx mouse
    <&&> overlayHitAllowed ctx top idx

-- | The node the pointer at @mouse@ reaches, as hover finds it:
-- 'reachedHit' over the nodes there that take the pointer ('pointerHitAt').
{-# INLINE reachedAt #-}
reachedAt :: Context -> V2 -> IO (Maybe NodeIdx)
reachedAt ctx mouse = do
  top <- overlayHitRoot ctx mouse
  reachedHit ctx (pointerHitAt ctx top mouse)

-- | The widget node the pointer at @mouse@ reaches ('reachedAt'). 'Nothing'
-- if it reaches a 'PointerBlock' node with no widget of its own there.
reachedWidgetAt :: Context -> V2 -> IO (Maybe NodeIdx)
reachedWidgetAt ctx@Context {ctxNodeArena = na} mouse = maybe (pure Nothing) widget =<< reachedAt ctx mouse
 where
  widget idx = (\nt -> if isWidgetNode nt then Just idx else Nothing) <$> getNodeType na idx

-- | The node a pointer hit lands on: the first node in arena order that
-- @hits@, or a later one that layers or a pinned node draw over it
-- ('topmostHit'), then the innermost widget inside that ('innermostHit'). A
-- 'PointerBlock' node with no widget of its own under the pointer is itself
-- the result. 'Nothing' if nothing hits. Inlined so the search calls a known
-- @hits@ and does not box node indices.
{-# INLINE reachedHit #-}
reachedHit :: Context -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
reachedHit ctx hits =
  traverse (innermostHit ctx hits <=< topmostHit ctx hits) =<< findClassNodeM (ctxNodeArena ctx) PointerNodes hits

-- | The widget a pointer hit on widget @idx@ lands on: its first enabled
-- descendant widget that @hits@, painted over it, and so on inward, skipping
-- inert containers ('containerFlagInert'). A 'PointerBlock' descendant that
-- @hits@ with no such widget inside it is itself the result, so nothing
-- drawn beneath it is reached.
innermostHit :: Context -> (NodeIdx -> IO Bool) -> NodeIdx -> IO NodeIdx
innermostHit ctx@Context {ctxNodeArena = na} hits idx =
  maybe (pure idx) (innermostHit ctx hits) =<< firstHitIn idx
 where
  -- Depth first from the child drawn on top, past widgets that miss.
  firstHitIn i = firstChildOnTopJustM na i $ \d -> do
    nt <- getNodeType na d
    inert <- pure (nt == NodeContainer) <&&> (hasFlag containerFlagInert <$> getStyleIdx na d)
    if inert
      then pure Nothing
      else
        ifM
          (pure (isWidgetNode nt) <&&> hits d <&&> (not <$> (isDisabled ctx =<< getWidgetId na d)))
          (pure (Just d))
          (firstHitIn d >>= maybe (blocking d) (pure . Just))
  blocking d = ifM (((== PointerBlock) <$> getPointerMode na d) <&&> hits d) (pure (Just d)) (pure Nothing)

-- | The topmost node among those that @hits@, given @first@, the first hit
-- in arena order. Paint draws earlier siblings over later ones, so this is
-- @first@ unless layers or a pinned node draw a later hit over it
-- ('drawnOver'). A hit nested inside another does not count as over it
-- here; see 'innermostHit'.
topmostHit :: Context -> (NodeIdx -> IO Bool) -> NodeIdx -> IO NodeIdx
topmostHit Context {ctxNodeArena = na} hits first = do
  layered <- layeredNodeCount na
  if layered == 0 then pure first else foldClassNodesM na PointerNodes over first
 where
  over top i
    | i <= first = pure top
    | otherwise = ifM (hits i <&&> drawnOver na i top) (pure i) (pure top)

-- | The node drawn on top at a point: the last node in paint order that
-- @step@ reports hit. Paint draws children over their parent, in
-- 'forChildrenInPaintOrder_' order, and each floating panel as a layer of its
-- own over the page: windows, then modals, then popups, each kind in arena
-- order. The search covers the floating panel @top@ and the panels declared
-- inside it, or with 'Nothing' the page: node 0, the one root the frame lays
-- out and paints, unless the view has no page and node 0 is a panel.
--
-- @step s idx@ tests node @idx@, reached with state @s@ (a layer's root with
-- @s0@): whether it is hit, and the state to search its children with, or
-- 'Nothing' when none of them can be hit. The result carries the state the
-- node was reached with.
innermostNodeAt :: Context -> Maybe NodeIdx -> (s -> NodeIdx -> IO (Bool, Maybe s)) -> s -> IO (Maybe (NodeIdx, s))
innermostNodeAt ctx@Context {ctxNodeArena = na} top step s0 = do
  roots <- case top of
    Nothing -> do
      count <- arenaCount na
      page <- if count > 0 then not . isFloatingNode <$> getNodeType na 0 else pure False
      pure [0 | page]
    Just panel -> do
      -- Newest first, so each kind's panels come out topmost first.
      inside <- foldClassNodesM na FloatingNodes (\acc i -> ifM (pure (i >= panel) <&&> nodeInSubtree ctx i panel) ((: acc) . (,i) <$> getNodeType na i) (pure acc)) []
      pure [i | nt <- [NodePopup, NodeModal, NodeWindow], (t, i) <- inside, t == nt]
  foldr (\root rest -> search s0 root >>= maybe rest (pure . Just)) (pure Nothing) roots
 where
  -- The topmost child first ('firstChildOnTopJustM'), so the first hit
  -- found in a subtree is the one drawn last.
  search s idx = do
    (hit, inner) <- step s idx
    deeper <- maybe (pure Nothing) (\s' -> firstChildOnTopJustM na idx (search s')) inner
    pure (deeper <|> if hit then Just (idx, s) else Nothing)