packages feed

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

-- | The pointer and keyboard steps that 'NanoUI.Internal.Frame.runFrame' runs around
-- the view: recording where a press landed, choosing the active and hot
-- widgets, turning a release into a click, and moving keyboard focus.
-- 'armPointerPress', 'recordCoveredWidgets' and 'recordFocusKind' run before
-- the view, against the previous frame's layout. The rest run after layout,
-- so their hit tests use this frame's solved rects, where the view had only
-- the previous frame's. Also the checks the backend runs between frames:
-- whether input needs a frame, and the gestures and panels in progress.
module NanoUI.Internal.Frame.Input
  ( finalizeTabFocus
  , refreshHover
  , armPointerPress
  , disarmPointerPress
  , pressTargets
  , armPointerTarget
  , finalizePointerRelease
  , finalizeTextInputFocus
  , finalizeSelectFocus
  , finalizeDrawingFocus
  , finalizeScrollFocus
  , finalizeFocusRequest
  , PressTargets (..)
  , targetsAt
  , constrainFocusToModal
  , recordFocusKind
  , needsRedraw
  , pointerDragActive
  , textFieldActive
  , floatingPanelActive
  , floatingWindowOpen
  , probeHotId
  , recordCoveredWidgets
  ) where

import Control.Monad (filterM, guard, mfilter, unless, when)
import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
import Data.Map.Strict qualified as M
import Data.Foldable (for_)
import Data.Functor ((<&>))
import Data.IntSet qualified as IS
import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe)
import NanoUI.Internal.Context
import NanoUI.Internal.Frame.Hit
import NanoUI.Internal.Frame.Scroll (probeScrollBarHover)
import NanoUI.Internal.Frame.Select (dropdownOwnerAt, focusedComboNode, openSelectNode)
import NanoUI.Internal.Frame.TextArea (collapseTextFieldSelection)
import NanoUI.Internal.Frame.TextInput (nodeTextFieldGeom)
import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)
import NanoUI.Internal.Input
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Layout.ScrollGeometry (decodeScrollConfig, scrollFocusable)
import NanoUI.Internal.Monad (ifM, mfilterM, unlessM, whenM, (<&&>))
import NanoUI.Internal.Types (DamageBounds (..), Rect (..), V2 (..), defaultDamageSlop, rectFullyInside)
import NanoUI.Internal.WidgetText (ButtonKind (..), buttonKindOf, hasFlag, textInputFlagSelectable)
import NanoUI.Internal.Widgets.Shortcut (focusTakesChord)

-- | On Tab (Shift+Tab goes backwards), move keyboard focus to 'tabTarget',
-- show the focus ring and scroll the widget into view ('revealWidget').
-- Moving focus blurs the old widget
-- ('blurFocus'). A Tab consumed by the focused widget
-- ('NanoUI.Internal.Context.markTabConsumed'), or one it claims
-- ('focusTakesChord': 'KeysAll', or 'KeysOnly' naming the chord), moves
-- nothing.
finalizeTabFocus :: Context -> Input -> IO ()
finalizeTabFocus ctx inp =
  whenM (pure (inputKeysElem KeyTab (inputKeys inp)) <&&> (not <$> tabConsumed ctx) <&&> (not . claimed <$> getsInteraction ctx isFocusKind)) $ do
    cur <- readIORef (ctxFocusId ctx)
    next <- tabTarget ctx cur (modShift (inputModifiers inp))
    when (hashWidgetId next /= 0) $ do
      -- Tab can reveal the focus ring without changing the focused rectangle.
      -- Damage that case explicitly; geometry comparison cannot detect it.
      wasVisible <- readIORef (ctxFocusVisible ctx)
      when (next == cur && not wasVisible) $
        damageWidget ctx next (DamageInflated defaultDamageSlop)
      when (next /= cur) (blurFocus ctx cur)
      writeIORef (ctxFocusId ctx) next
      writeIORef (ctxFocusVisible ctx) True
      revealWidget ctx next
      markDirty ctx
  where
    claimed kind = focusTakesChord kind (inputModifiers inp) KeyTab

-- | Scroll each scroller around widget @wid@, innermost first, just far
-- enough to show it whole ('ScrollNearest'), as when Tab moves focus there.
-- Reads this frame's placed rects and the metrics the offset pass published,
-- so the scroll shows on the next frame.
revealWidget :: Context -> WidgetId -> IO ()
revealWidget ctx@Context {ctxNodeArena = na} wid =
  withWidgetNode ctx wid () $ \idx -> do
    r <- getNodeRect na idx
    getParent na idx >>= reveal r
  where
    reveal r@(Rect rx ry rw rh) i = when (i >= 0) $ do
      nt <- getNodeType na i
      -- A floating panel does not move with the scrollers it is declared in.
      unless (isFloatingNode nt) $ do
        sid <- getWidgetId na i
        metrics <- if isScrollNode nt then readScrollMetrics ctx sid else pure Nothing
        r' <- case metrics of
          Just ScrollMetrics {scrollViewport = view@(Rect vx vy _ _), scrollOffset = V2 ox oy}
            | not (rectFullyInside r view) -> do
                scrollRectIntoView ctx sid (Rect (rx - vx + ox) (ry - vy + oy) rw rh) ScrollNearest ScrollInstant
                -- An outer scroller shows the widget where this one moved it.
                V2 nx ny <- maybe (V2 ox oy) scrollOffset <$> readScrollMetrics ctx sid
                pure (Rect (rx + ox - nx) (ry + oy - ny) rw rh)
          _ -> pure r
        getParent na i >>= reveal r'

-- | Where Tab moves focus from @cur@ (backwards when @back@), stepping
-- through 'tabStops' and wrapping at both ends. @WidgetId 0@ if there are
-- none.
tabTarget :: Context -> WidgetId -> Bool -> IO WidgetId
tabTarget ctx cur back = (\stops -> tabNext cur stops back) <$> tabStops ctx

-- | Tab stops in declaration order: the widgets that called
-- 'NanoUI.Internal.Context.registerFocusable' during the view. While a
-- modal is open, only those inside the top modal.
tabStops :: Context -> IO [WidgetId]
tabStops ctx = do
  -- The modal's root is looked up once for the whole list. Each widget then
  -- costs one walk up its ancestors.
  top <- topModalNode (ctxNodeArena ctx)
  filterM (widgetInModal ctx top) . filter (/= WidgetId 0) =<< getFocusables ctx

-- | Whether @w@ is one of the 'tabStops', without building them: one scan
-- of the registered ids and one walk up @w@'s ancestors.
isTabStop :: Context -> WidgetId -> IO Bool
isTabStop ctx w
  | w == WidgetId 0 = pure False
  | otherwise = isFocusable ctx w <&&> widgetOverlayAllowed ctx w

-- | Whether @wid@ is a menu row or a menu-bar title. Their hover highlight
-- switches on and off at once, so 'refreshHover' runs no animation for them.
isMenuButtonWidget :: Context -> WidgetId -> IO Bool
isMenuButtonWidget ctx wid =
  withWidgetNode ctx wid False $ \idx ->
    ((== NodeButton) <$> getNodeType (ctxNodeArena ctx) idx)
      <&&> ((\si -> let k = buttonKindOf si in k == ButtonMenu || k == ButtonMenuBar) <$> getStyleIdx (ctxNodeArena ctx) idx)

-- | Find the hot widget in this frame's layout and store it in 'ctxHotId' and
-- 'ctxLastHotId'. Runs after layout and before painting. When the hot widget
-- changes, the hover animation of the widget that lost the pointer runs from
-- 1 to 0, and that of the widget that gained it from 0 to 1, each over 0.12
-- seconds. The painter blends a widget's hover colour by that value. While a
-- widget holds the left button, no other one is hot, as no other is hovered
-- ('NanoUI.Internal.Widgets.Node.resolveInteraction'), so a drag lights up
-- nothing it crosses.
refreshHover :: Context -> Input -> IO ()
refreshHover ctx inp = do
  prevHot <- readIORef (ctxLastHotId ctx)
  probed <- probeHotId ctx (inputMousePos inp)
  active <- readIORef (ctxActiveId ctx)
  let newHot
        | heldIn MouseLeft inp && hashWidgetId active /= 0 && probed /= active = WidgetId 0
        | otherwise = probed
  writeIORef (ctxHotId ctx) newHot
  writeIORef (ctxLastHotId ctx) newHot
  when (prevHot /= newHot) $ do
    prevMenu <- isMenuButtonWidget ctx prevHot
    newMenu <- isMenuButtonWidget ctx newHot
    -- A widget the view no longer declares has nothing to fade: starting its
    -- fade-out would repaint the window and pace frames for nothing.
    prevShown <- isJust <$> findNodeByWidgetId ctx prevHot
    when (hashWidgetId prevHot /= 0 && prevShown && not prevMenu) $ startAnimation ctx prevHot 1 0 0.12
    when (hashWidgetId newHot /= 0 && not newMenu) $ startAnimation ctx newHot 0 1 0.12

-- | Capture the press point and the node it reached ('PressPoint') in the
-- frame the user saw, before the arena is rebuilt. A click belongs to the
-- reached widget and its ancestors whatever moves under the pointer later;
-- passive content still bubbles to mouse areas. 'disarmPointerPress' clears
-- releases.
armPointerPress :: Context -> Input -> IO ()
armPointerPress ctx inp =
  when (anyButtonPressed inp) $ do
    let here = inputMousePos inp
    pp <- getsInteraction ctx isPointerRoute >>= \case
      RouteLayer _ ->
        reachedAt ctx here >>= \case
          Nothing -> pure (PressPoint here Nothing IS.empty)
          Just i -> PressPoint here <$> (Just <$> getWidgetId (ctxNodeArena ctx) i) <*> reachedIds ctx here i
      _ -> pure (PressPoint here (Just (WidgetId 0)) IS.empty)
    modifyIORef' (ctxPressPos ctx) $ \m -> foldr (`M.insert` pp) m (buttonsToList (inputButtonsPressed inp))
    -- A pointer press hides the keyboard focus ring.
    when (pressedIn MouseLeft inp) $ writeIORef (ctxFocusVisible ctx) False

-- | Forget the press point of each button that came up this frame. Runs after
-- the view, which compares the release with the press point.
disarmPointerPress :: Context -> Input -> IO ()
disarmPointerPress ctx inp =
  when (anyButtonReleased inp) $
    modifyIORef' (ctxPressPos ctx) $ \m -> foldr M.delete m (buttonsToList (inputButtonsReleased inp))

-- | What a left press landed on, for the steps that act on it: the
-- interactive widget, the text field or text area, and the select under the
-- pointer, all 'Nothing' on a frame without a press; and whether the
-- interactive widget is another one drawn inside the text field or over it.
-- The select is set only when it is the interactive widget.
data PressTargets = PressTargets
  { ptInteractive :: !(Maybe WidgetId)
  , ptTextField :: !(Maybe WidgetId)
  , ptSelect :: !(Maybe WidgetId)
  , ptFieldControl :: !Bool
  , ptBlocked :: !Bool
  }

-- | The 'PressTargets' of this frame's left press ('targetsAt'). Runs after
-- layout, like the steps.
pressTargets :: Context -> Input -> IO PressTargets
pressTargets ctx inp
  | not (pressedIn MouseLeft inp) = pure none
  | otherwise = targetsAt ctx (inputMousePos inp)

-- | The widgets a press at @mouse@ would land on, found in one pass over the
-- arena instead of one per step. A node's hit test does not depend on which
-- step asks, so each node is tested at most once, and the pass stops once
-- every target is found. Each is the first match in arena order, which is
-- declaration order. The painter draws siblings from the last declared to the
-- first, so where two overlap the earlier one is on top, unless a stack or
-- pinned child draws a later match over it ('topmostHit', which then takes
-- one more pass per target). A widget drawn
-- inside the interactive one, such as a control among its adornments, is on
-- top of it and takes the press ('innermostHit'). When a stack or pinned
-- node could draw a 'PointerBlock' node on top, a first pass checks whether
-- it takes the press; if so there are no targets.
targetsAt :: Context -> V2 -> IO PressTargets
targetsAt ctx@Context {ctxNodeArena = na} mouse = do
  top <- overlayHitRoot ctx mouse
  let under idx = getNodeType na idx >>= \nt -> widgetUnderMouse ctx top mouse nt idx
  -- A 'PointerBlock' node on top with no widget of its own under the press
  -- blocks it: nothing beneath is pressed or focused. Only stacks and
  -- pinned nodes draw one node over another.
  layered <- layeredNodeCount na
  let takerUnder idx = takesPointer na idx <&&> under idx
      blocking idx = not . isWidgetNode <$> getNodeType na idx
  blocked <-
    if layered == 0
      then pure False
      else maybe (pure False) blocking =<< reachedHit ctx takerUnder
  if blocked then pure none {ptBlocked = True} else pressTargetsAt ctx under

-- | 'targetsAt' once no blocking node took the press. @under@ is the press
-- hit test.
pressTargetsAt :: Context -> (NodeIdx -> IO Bool) -> IO PressTargets
pressTargetsAt ctx@Context {ctxNodeArena = na} under = do
  found <- newIORef none
  _ <- findClassNodeM na PointerNodes $ \idx -> do
    nt <- getNodeType na idx
    PressTargets i t s _ _ <- readIORef found
    let wantI = isNothing i && isWidgetNode nt
        wantT = isNothing t && (nt == NodeTextInput || nt == NodeTextArea)
        wantS = isNothing s && nt == NodeSelect
    pure (wantI || wantT || wantS) <&&> under idx <&&> do
      wid <- getWidgetId na idx
      let topmost kind = topmostHit ctx (\d -> (kind <$> getNodeType na d) <&&> under d) idx
          topmostId want kind = if want then getWidgetId na =<< topmost kind else pure wid
      inner <- if wantI then getWidgetId na =<< innermostHit ctx under =<< topmost isWidgetNode else pure wid
      fieldWid <- topmostId wantT (\k -> k == NodeTextInput || k == NodeTextArea)
      selectWid <- topmostId wantS (== NodeSelect)
      let pick want hit cur = if want then Just hit else cur
          !r =
            PressTargets
              (if wantI then Just inner else i)
              (pick wantT fieldWid t)
              (pick wantS selectWid s)
              False
              False
      writeIORef found r
      pure (isJust (ptInteractive r) && isJust (ptTextField r) && isJust (ptSelect r))
  -- Another widget under the press is drawn inside the field or select, or
  -- over it. The field then takes the press only as the control's
  -- ('ptFieldControl'), and the select takes none.
  PressTargets i t s _ _ <- readIORef found
  pure (PressTargets i t (mfilter (\w -> Just w == i) s) (isJust t && t /= i) False)

none :: PressTargets
none = PressTargets Nothing Nothing Nothing False False

-- | On a left press, make the interactive widget under the pointer the active
-- widget, unless it is disabled. Runs before the view, against the layout the
-- user saw, so a widget that first appears in the press's frame does not
-- become active. 'pressTargets' searches the arena in the same order as
-- hover ('refreshHover'), so where widgets overlap both pick the one on top.
armPointerTarget :: Context -> PressTargets -> IO ()
armPointerTarget ctx targets =
  enabledTarget ctx (ptInteractive targets) >>= mapM_ (writeIORef (ctxActiveId ctx))

-- | Whether a press at @mouse@ lands on node @idx@ of type @nt@: the point is
-- in its hit rect ('widgetHitRect') and clip, floating panels and modals
-- leave it reachable ('overlayHitAllowed', with @top@ from
-- 'overlayHitRoot'), and the node does not pass the pointer through
-- ('passesPointer').
{-# INLINE widgetUnderMouse #-}
widgetUnderMouse :: Context -> Maybe NodeIdx -> V2 -> NodeType -> NodeIdx -> IO Bool
widgetUnderMouse ctx top mouse nt idx = do
  Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx
  rect <- widgetHitRect ctx nt idx x y w h
  nodeClippedHit ctx idx rect mouse
    <&&> overlayHitAllowed ctx top idx
    <&&> (not <$> passesPointer (ctxNodeArena ctx) idx)

-- | The rect a press on node @idx@ must land in: a text field's box
-- ('nodeTextFieldGeom'), else the node rect.
widgetHitRect :: Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO Rect
widgetHitRect ctx nt idx x y w h = case nt of
  NodeTextInput -> fst <$> nodeTextFieldGeom ctx idx x y w h
  -- Only a text field's box is smaller than its node.
  _ -> pure (Rect x y w h)

-- | Clear the active widget on a left release. Runs after layout. The view
-- judged the release against the layout the user saw, so a widget that
-- moved under the pointer in the release's own frame is not clicked: the
-- user did not see it there.
--
-- A release on the widget's solved rect also sets its hover animation to 1,
-- so it paints as fully hovered at once.
finalizePointerRelease :: Context -> Input -> IO ()
finalizePointerRelease ctx@Context {ctxNodeArena = na} inp =
  when (releasedIn MouseLeft inp) $ do
    let mouse = inputMousePos inp
    active <- readIORef (ctxActiveId ctx)
    when (hashWidgetId active /= 0) $ do
      -- Whether the pointer came up over the widget is decided by the first
      -- node with its id, in arena order.
      releasedOver <-
        findNodeM na (fmap (== active) . getWidgetId na)
          >>= traverse (\idx -> getNodeRect na idx >>= \rect -> nodeClippedHit ctx idx rect mouse)
      writeIORef (ctxActiveId ctx) (WidgetId 0)
      when (releasedOver == Just True) $
        setAnimationValue ctx active 1

-- | Focus the enabled text field under a left press using solved geometry.
-- A press elsewhere clears focus, collapses the prior selection, and closes
-- its edit menu. Menu/dropdown presses are removed from the supplied layer
-- input so the owning field keeps focus until the pick is processed.
-- A press on a control drawn inside a text field, or on a widget drawn over
-- it, keeps that field focused if it already was; otherwise the press clears
-- focus like any press outside a field.
-- A press on a menu row or menu-bar title keeps the field's selection, so a
-- menu command such as Cut ('NanoUI.Widgets.TextField.runTextCommand'),
-- which focuses the field again, acts on it.
finalizeTextInputFocus :: Context -> Input -> PressTargets -> IO ()
finalizeTextInputFocus ctx inp targets =
  when (pressedIn MouseLeft inp) $ do
    prevFocus <- readIORef (ctxFocusId ctx)
    mFocused <-
      if ptFieldControl targets
        then pure (mfilter (== prevFocus) (ptTextField targets))
        else enabledTarget ctx (ptTextField targets)
    case mFocused of
      Nothing -> do
        when (prevFocus /= WidgetId 0) $ markDirty ctx
        onMenu <- maybe (pure False) (isMenuButtonWidget ctx) (ptInteractive targets)
        unless onMenu $ collapseTextFieldSelection ctx prevFocus
        writeIORef (ctxFocusId ctx) (WidgetId 0)
        -- A press on a menu row, the edit menu's own among them, leaves the
        -- menu to the release that picks the row.
        unless onMenu $ modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing})
      Just wid -> focusWidget ctx wid

-- | On a left press on an enabled select's field, give the select keyboard
-- focus, whether the press opens or closes it. Runs after
-- 'finalizeTextInputFocus', which has cleared focus for a press outside every
-- text field.
finalizeSelectFocus :: Context -> PressTargets -> IO ()
finalizeSelectFocus ctx targets =
  enabledTarget ctx (ptSelect targets) >>= mapM_ (focusWidget ctx)

-- | On a left press on an enabled custom widget that takes focus
-- ('NanoUI.Widgets.Custom.widgetFocusable'), such as a knob or a focusable
-- canvas, give it keyboard focus. The press hides the focus ring, as for a
-- text field.
finalizeDrawingFocus :: Context -> PressTargets -> IO ()
finalizeDrawingFocus ctx targets =
  enabledTarget ctx (ptInteractive targets) >>= mapM_ (\wid ->
    whenM (withWidgetNode ctx wid False (fmap (== NodeDrawing) . getNodeType (ctxNodeArena ctx)) <&&> isFocusable ctx wid) $
      focusWidget ctx wid)

-- | On a left press that did not focus a text field, select, or focusable
-- drawing, focus the innermost enabled focusable scroll container
-- ('NanoUI.scrollFocusable') under the pointer.
finalizeScrollFocus :: Context -> Input -> PressTargets -> IO ()
finalizeScrollFocus ctx@Context {ctxNodeArena = na} inp targets =
  when (pressedIn MouseLeft inp && not (ptBlocked targets)) $ do
    cur <- readIORef (ctxFocusId ctx)
    when (hashWidgetId cur == 0) $ do
      let mouse = inputMousePos inp
      top <- overlayHitRoot ctx mouse
      let hit idx =
            ((== NodeScrollContainer) <$> getNodeType na idx)
              <&&> (scrollFocusable . decodeScrollConfig <$> getStyleIdx na idx)
              <&&> do
                wid <- getWidgetId na idx
                pure (hashWidgetId wid /= 0)
                  <&&> widgetUnderMouse ctx top mouse NodeScrollContainer idx
                  <&&> isFocusable ctx wid
                  <&&> (not <$> isDisabled ctx wid)
      findClassNodeRevM na ScrollableNodes hit >>= mapM_ (\idx -> getWidgetId na idx >>= focusWidget ctx)

-- | Apply the view's last focus request this frame
-- ('NanoUI.Internal.Monad.requestFocus', 'NanoUI.Internal.Monad.focusNext',
-- 'NanoUI.Internal.Monad.focusPrevious',
-- 'NanoUI.Internal.Monad.clearFocus'). Runs after the pointer steps and
-- before 'constrainFocusToModal' and 'finalizeTabFocus', so a Tab in the
-- same frame continues from the newly focused widget.
--
-- 'FocusNowhere' clears focus, and 'FocusNext' and 'FocusPrevious' go where
-- Tab would ('tabTarget'). 'FocusOn' succeeds only for one of the
-- 'tabStops', never a disabled widget; otherwise the request is dropped.
-- Moving focus behaves like a press elsewhere ('blurFocus'). The new
-- widget shows the focus ring and scrolls into view ('revealWidget').
-- Requesting the focused widget changes
-- nothing, including the ring.
finalizeFocusRequest :: Context -> IO ()
finalizeFocusRequest ctx =
  readIORef (ctxFocusRequest ctx) >>= mapM_ (\req -> do
    writeIORef (ctxFocusRequest ctx) Nothing
    prev <- readIORef (ctxFocusId ctx)
    let step back = mfilter (/= WidgetId 0) . Just <$> tabTarget ctx prev back
    target <- case req of
      -- Requesting the focused widget changes nothing, so a view that asks
      -- every frame builds no list.
      FocusOn w
        | w == prev -> pure Nothing
        | otherwise -> (w <$) . guard <$> isTabStop ctx w
      FocusNowhere -> pure (Just (WidgetId 0))
      FocusNext -> step False
      FocusPrevious -> step True
    for_ (mfilter (/= prev) target) $ \wid -> do
      blurFocus ctx prev
      -- The damage pass repaints both widgets, since the focused id moved.
      writeIORef (ctxFocusId ctx) wid
      when (hashWidgetId wid /= 0) $ do
        writeIORef (ctxFocusVisible ctx) True
        revealWidget ctx wid
      markDirty ctx)

-- | What moving focus off @prev@ does, as a press elsewhere would: the old
-- field collapses its selection, and the text-field menu and any open
-- dropdown close.
blurFocus :: Context -> WidgetId -> IO ()
blurFocus ctx prev = do
  collapseTextFieldSelection ctx prev
  modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing})
  store <- getStore ctx
  when (anySelectOpen store) $ setStore ctx (closeSelects store)

-- | Give @wid@ keyboard focus, repainting when focus moved.
focusWidget :: Context -> WidgetId -> IO ()
focusWidget ctx wid = do
  prev <- readIORef (ctxFocusId ctx)
  writeIORef (ctxFocusId ctx) wid
  when (prev /= wid) $ markDirty ctx

-- | The pressed widget, unless it is disabled. A disabled field counts as
-- nothing here, so a press on it takes focus away from the field that had it
-- and gives it to no other.
enabledTarget :: Context -> Maybe WidgetId -> IO (Maybe WidgetId)
enabledTarget ctx = mfilterM (fmap not . isDisabled ctx)

-- | Next focus id, or previous with Shift, wrapping at both ends. An unknown
-- current id selects the first entry, or the last going backwards; an empty
-- list returns @WidgetId 0@.
tabNext :: WidgetId -> [WidgetId] -> Bool -> WidgetId
tabNext cur ids shift =
  fromMaybe (WidgetId 0) . listToMaybe $ case break (== cur) ids of
    (_, []) -> if shift then reverse ids else ids
    (before, _ : after)
      | shift -> reverse (if null before then ids else before)
      | otherwise -> after ++ ids

-- | Take keyboard focus away from display-only content, a widget outside
-- the top modal, or a widget this frame did not declare, and close a
-- select's dropdown or a field's edit menu whose owner the top modal hides or
-- this frame did not declare. Either would otherwise keep Escape reserved
-- ('escapeReserved') and repaint on every pointer move with nothing to show.
-- The frame runs this after the pointer steps, which can move focus, and
-- before 'finalizeTabFocus'.
constrainFocusToModal :: Context -> IO ()
constrainFocusToModal ctx = do
  focus <- readIORef (ctxFocusId ctx)
  when (hashWidgetId focus /= 0) $
    unlessM (declared focus <&&> widgetOverlayAllowed ctx focus <&&> (not <$> isInert ctx focus) <&&> (not <$> isDisabled ctx focus)) $
      writeIORef (ctxFocusId ctx) (WidgetId 0)
  getsInteraction ctx isTextInputMenu >>= mapM_ (\m ->
    unlessM (declared (textInputMenuWidget m) <&&> widgetOverlayAllowed ctx (textInputMenuWidget m)) $ do
      modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing})
      markDirty ctx)
  store <- getStore ctx
  when (anySelectOpen store) $
    openSelectNode ctx store >>= \case
      Nothing -> setStore ctx (closeSelects store) >> markDirty ctx
      Just idx -> do
        wid <- getWidgetId (ctxNodeArena ctx) idx
        unlessM (widgetOverlayAllowed ctx wid) $ setStore ctx (closeSelects store)
 where
  -- Ids are positional, so another widget can land on a vanished one's id:
  -- what counts is that a focusable widget holds it this frame.
  declared = isFocusable ctx

-- | Record in 'isFocusKind' what kind of widget has keyboard focus and which
-- keys it claims ('KeyClaim'), and in 'isFocusCombo' whether it is a combo
-- box showing its list, from last frame's nodes. Runs before the view
-- rebuilds them, so a shortcut declared before the focused widget still sees
-- it. @ime@: an input method owns the focused field's keys this frame
-- ('NanoUI.Internal.Frame.TextInput.claimComposition').
recordFocusKind :: Context -> Bool -> IO ()
recordFocusKind ctx ime = do
  focus <- readIORef (ctxFocusId ctx)
  disabled <- isDisabled ctx focus
  inert <- isInert ctx focus
  kind <-
    if hashWidgetId focus == 0 || disabled || inert
      then pure FocusNone
      else if ime
        then pure FocusComposing
        else withWidgetNode ctx focus FocusNone $ \idx -> do
          let si = getStyleIdx (ctxNodeArena ctx) idx
          getNodeType (ctxNodeArena ctx) idx >>= \case
            NodeTextInput -> si <&> \s -> if hasFlag textInputFlagSelectable s then FocusTextSelectable else FocusTextLine
            NodeTextArea -> pure (FocusControl KeysType)
            -- A tree row moves with the arrows; any other button activates.
            NodeButton -> si <&> \s -> FocusControl (if buttonKindOf s == ButtonRow then KeysNavigate else KeysActivate)
            NodeDrawing -> FocusControl . maybe KeysNone cdrKeys <$> lookupCustomDrawing ctx focus
            NodeScrollContainer -> pure (FocusControl KeysNavigate)
            _ -> pure (FocusControl KeysNavigate)
  combo <- if kind == FocusTextLine then isJust <$> focusedComboNode ctx else pure False
  was <- getsInteraction ctx isFocusKind
  wasCombo <- getsInteraction ctx isFocusCombo
  when (kind /= was || combo /= wasCombo) $ modifyInteraction ctx (\s -> s {isFocusKind = kind, isFocusCombo = combo})

-- | Whether state or input changes require a frame. Arguments are previous
-- and current input. Tests hover only after pointer motion; timed wake
-- deadlines are handled separately by the session runner.
needsRedraw :: Context -> Input -> Input -> IO Bool
needsRedraw ctx prev inp = do
  dirty <- isDirty ctx
  anim <- anyAnimating ctx
  drag <- getsInteraction ctx (\s -> isJust (isScrollDrag s) || isJust (isWindowDrag s))
  overlay <- overlayMenuOpen ctx
  -- The layout overlay highlights whatever node the pointer is over.
  explain <- getExplainLayout ctx
  let moved = inputMousePos prev /= inputMousePos inp
  if dirty
    || anim
    || inputInteracted prev inp
    || inputWindowRedraw inp
    || inputPointerHeld inp
    || drag
    || (overlay && moved)
    || (explain && moved)
    then pure True
    else
      -- Idle: hover can only change when the pointer moved since the frame
      -- whose hover state we still hold. Skip the O(n) hot probe otherwise.
      pure moved <&&> do
        -- A pointer-tracking widget redraws on every move over it; other
        -- widgets redraw only when hover enters or leaves.
        lastHot <- readIORef (ctxLastHotId ctx)
        tracked <-
          if hashWidgetId lastHot == 0
            then pure False
            else maybe False cdrTracked <$> lookupCustomDrawing ctx lastHot
        hotMoved <- if tracked then pure True else (/= lastHot) <$> probeHotId ctx (inputMousePos inp)
        -- A scrollbar is not a widget but brightens on hover. A tooltip
        -- target need not be a widget either, and a tooltip that follows
        -- the pointer moves with it.
        if hotMoved
          then pure True
          else ifM scrollBarHoverMoved (pure True) (hoverZoneCrossed ctx (inputMousePos prev) (inputMousePos inp))
  where
    bar = fmap (\(wid, dir, _) -> (wid, dir))
    scrollBarHoverMoved =
      (/=) <$> (bar <$> getsInteraction ctx isScrollHover) <*> (bar <$> probeScrollBarHover ctx inp)

-- | Whether a window, scrollbar, resize, slider, or colour-picker gesture
-- is active. Text-selection drags are tracked separately.
pointerDragActive :: Context -> IO Bool
pointerDragActive ctx = do
  gesture <- getsInteraction ctx $ \s ->
    isJust (isWindowDrag s) || isJust (isScrollDrag s) || isJust (isWindowResize s)
  sliderOrPicker <- focusedNodeIs ctx ctxActiveId (\nt -> nt == NodeSlider || nt == NodeColorPicker)
  pure (gesture || sliderOrPicker)

-- | Whether the node of the widget id held in @ref@ satisfies @p@.
focusedNodeIs :: Context -> (Context -> IORef WidgetId) -> (NodeType -> Bool) -> IO Bool
focusedNodeIs ctx ref p = do
  wid <- readIORef (ref ctx)
  withWidgetNode ctx wid False $ \idx -> p <$> getNodeType (ctxNodeArena ctx) idx

-- Select dropdown is open. Its hover is not a widget id, so while one is up
-- every pointer move needs a frame. A focused combo (a search-style field
-- carrying options) also owns an open dropdown.
overlayMenuOpen :: Context -> IO Bool
overlayMenuOpen ctx = do
  store <- getStore ctx
  if anySelectOpen store
    then pure True
    else isJust <$> focusedComboNode ctx

-- | Focused text field or its context menu. Typing reaches it as input events,
-- which wake the loop by themselves, so focus alone keeps nothing running.
textFieldActive :: Context -> IO Bool
textFieldActive ctx =
  ifM (isJust <$> getsInteraction ctx isTextInputMenu) (pure True) $
    focusedNodeIs ctx ctxFocusId (\nt -> nt == NodeTextInput || nt == NodeTextArea)

-- | Whether modal state or the current arena contains a floating panel,
-- including windows and popups.
floatingPanelActive :: Context -> IO Bool
floatingPanelActive ctx =
  (||) <$> modalActive ctx <*> ((> 0) <$> floatingNodeCount (ctxNodeArena ctx))

-- | Whether the arena contains any floating window.
floatingWindowOpen :: Context -> IO Bool
floatingWindowOpen ctx = isJust <$> topmostFloating ctx (== NodeWindow) (const True)

probeHotId :: Context -> V2 -> IO WidgetId
probeHotId ctx@Context {ctxNodeArena = na} mouse = do
  -- A press that started on a menu or dropdown suppresses widget hover.
  offLayers <- pointerHeldOffLayers ctx
  if offLayers
    then pure (WidgetId 0)
    else do
      mOverlay <- dropdownOwnerAt ctx mouse
      case mOverlay of
        Just wid -> pure wid
        Nothing -> maybe (pure (WidgetId 0)) (getWidgetId na) =<< reachedWidgetAt ctx mouse

-- | Record in 'ctxPointerReach' which nodes the pointer reaches in the frame
-- the user saw: where stacks or pinned nodes overlap, the topmost node under
-- the pointer that takes it ('reachedAt', as hover finds it) and its
-- ancestors. Every other node under the pointer, widget or not, is covered.
--
-- Runs before the view, against last frame's layout. During the view each
-- widget hit-tests its rect in that layout
-- ('NanoUI.Internal.Widgets.Node.resolveInteraction'), and a covered one
-- gets neither hover nor presses. Nothing is covered when the pointer is on
-- a menu or dropdown (which routes it away from every layer), when nothing
-- under it takes the pointer, or when the layout has no stack or pinned node
-- ('layeredNodeCount'), since then nodes only overlap their ancestors.
recordCoveredWidgets :: Context -> PointerRoute -> Input -> IO ()
recordCoveredWidgets ctx@Context {ctxNodeArena = na} route inp = do
  layered <- layeredNodeCount na
  reach <- case route of
    RouteLayer _ | layered > 0 -> traverse (reachedIds ctx mouse) =<< reachedAt ctx mouse
    _ -> pure Nothing
  -- Most frames have nothing covered before or after, and write nothing.
  old <- readIORef (ctxPointerReach ctx)
  unless (isNothing old && isNothing reach) $
    writeIORef (ctxPointerReach ctx) $! reach
 where
  mouse = inputMousePos inp

-- | The keys of node @i@, reached at @mouse@ ('reachedAt'), and of its
-- ancestors. A node reached with no widget of its own under the pointer (a
-- 'PointerBlock' container) covers nothing it contains there: the tagged
-- containers under the pointer inside it (a mouse area, a drop target) are
-- reached too.
reachedIds :: Context -> V2 -> NodeIdx -> IO IS.IntSet
reachedIds ctx@Context {ctxNodeArena = na} mouse i = do
  up <- idsUpFrom IS.empty i
  nt <- getNodeType na i
  if isWidgetNode nt then pure up else idsDownFrom up i
 where
  idsDownFrom !acc j = foldPlacedChildrenM na j step acc
   where
    step a d =
      ifM
        (nodePointVisible ctx d mouse)
        (getWidgetId na d >>= \wid -> idsDownFrom (if hashWidgetId wid == 0 then a else IS.insert (intKey wid) a) d)
        (pure a)
  -- Ids of node @i@ and its ancestors. A node sharing one of these ids is
  -- not covered either.
  idsUpFrom !acc j
    | j < 0 = pure acc
    | otherwise = do
        wid <- getWidgetId na j
        let acc' = if hashWidgetId wid == 0 then acc else IS.insert (intKey wid) acc
        getParent na j >>= idsUpFrom acc'