packages feed

nano-ui 0.1.0.1 → 0.2.0.0

raw patch · 307 files changed

+71594/−39399 lines, 307 filesdep +QuickCheckdep +directorydep +exceptionsdep −hashtablesdep −hexmldep ~basedep ~bytestringdep ~containersPVP ok

version bump matches the API change (PVP)

Dependencies added: QuickCheck, directory, exceptions, filepath, monad-control, nano-svg, transformers, transformers-base, unliftio-core

Dependencies removed: hashtables, hexml

Dependency ranges changed: base, bytestring, containers, effectful, effectful-core, inspection-testing, nothunks

API changes (from Hackage documentation)

- NanoUI: AxisH :: GridAxis
- NanoUI: AxisV :: GridAxis
- NanoUI: Base16 :: Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Base16
- NanoUI: CustomWidgetSpec :: Layout -> Maybe CustomMeasureFn -> CustomDrawBuild -> Int -> Maybe (CustomDrawContext -> UiCursorKind) -> Bool -> Float -> (Response -> CustomDrawContext -> Input -> (Response, a)) -> CustomWidgetSpec a
- NanoUI: DamageClip :: Rect -> Damage
- NanoUI: DamageCustom :: (Rect -> Rect) -> DamageBounds
- NanoUI: DamageExact :: Rect -> DamageBounds
- NanoUI: DamageFull :: Damage
- NanoUI: DamageInflated :: Float -> DamageBounds
- NanoUI: DamageNone :: DamageBounds
- NanoUI: DamageSelf :: DamageBounds
- NanoUI: DamageUnion :: DamageBounds -> DamageBounds -> DamageBounds
- NanoUI: DrawImageRect :: Rect -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp
- NanoUI: DrawText :: Float -> Float -> Float -> Float -> Text -> Color -> DrawOp
- NanoUI: DrawTextStyled :: Float -> Float -> TextFont -> Text -> Color -> DrawOp
- NanoUI: FillCircle :: Float -> Float -> Float -> Color -> DrawOp
- NanoUI: FillQuadGradient :: Rect -> Color -> Color -> Color -> Color -> DrawOp
- NanoUI: FillRect :: Rect -> Color -> DrawOp
- NanoUI: FillRoundedRect :: Rect -> Float -> Color -> DrawOp
- NanoUI: FillTriangle :: Float -> Float -> Float -> Float -> Float -> Float -> Color -> DrawOp
- NanoUI: FontBackend :: (Text -> IO FontMetrics) -> (Text -> IO (Maybe ShapedGlyphs)) -> (Char -> IO (Maybe GlyphQuad)) -> FontBackend
- NanoUI: FontDanger :: FontVariant
- NanoUI: FontHeading :: FontVariant
- NanoUI: FontMetrics :: Float -> Float -> Float -> (Char -> Float) -> (Char -> Char -> Float) -> (Text -> Maybe ShapedText) -> (Char -> Maybe GlyphQuad) -> Maybe FontBackend -> FontMetrics
- NanoUI: FontMuted :: FontVariant
- NanoUI: GlyphQuad :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> GlyphQuad
- NanoUI: Layout :: Direction -> Sizing -> Sizing -> Padding -> Float -> AlignX -> AlignY -> Float -> Float -> Float -> Float -> FontVariant -> Int -> Float -> Float -> Maybe Color -> FontWeight -> FontStyle -> TextDecoration -> Layout
- NanoUI: PaneGridConfig :: (Layout -> Layout) -> Float -> Float -> Float -> Float -> (Word64 -> PaneGridCtx es -> Eff es PaneView) -> PaneGridConfig (es :: [Effect])
- NanoUI: PaneGridCtx :: Word64 -> Rect -> Bool -> Bool -> Bool -> (GridAxis -> Eff es Word64) -> Eff es () -> Eff es () -> Eff es () -> PaneGridCtx (es :: [Effect])
- NanoUI: PaneGridResponse :: Bool -> Int -> [Word64] -> Word64 -> Word64 -> PaneGridResponse
- NanoUI: PaneView :: Text -> Bool -> Maybe Rect -> PaneView
- NanoUI: ScrollBarList :: ScrollBarSlot
- NanoUI: ScrollBarPage :: ScrollBarSlot
- NanoUI: ScrollBarWindow :: ScrollBarSlot
- NanoUI: SearchFieldConfig :: Text -> Float -> Layout -> SearchFieldConfig
- NanoUI: ShapedGlyphs :: PrimArray Float -> ShapedGlyphs
- NanoUI: ShapedText :: Float -> Float -> PrimArray Float -> ShapedText
- NanoUI: Stroke :: Float -> Float -> Float -> Float -> Float -> Color -> DrawOp
- NanoUI: StrokeCircle :: Float -> Float -> Float -> Float -> Color -> DrawOp
- NanoUI: StrokeLineAA :: Float -> Float -> Float -> Float -> Float -> Color -> DrawOp
- NanoUI: StrokeRoundedRect :: Rect -> Float -> Float -> Color -> DrawOp
- NanoUI: [base00] :: Base16 -> Color
- NanoUI: [base01] :: Base16 -> Color
- NanoUI: [base02] :: Base16 -> Color
- NanoUI: [base03] :: Base16 -> Color
- NanoUI: [base04] :: Base16 -> Color
- NanoUI: [base05] :: Base16 -> Color
- NanoUI: [base06] :: Base16 -> Color
- NanoUI: [base07] :: Base16 -> Color
- NanoUI: [base08] :: Base16 -> Color
- NanoUI: [base09] :: Base16 -> Color
- NanoUI: [base0A] :: Base16 -> Color
- NanoUI: [base0B] :: Base16 -> Color
- NanoUI: [base0C] :: Base16 -> Color
- NanoUI: [base0D] :: Base16 -> Color
- NanoUI: [base0E] :: Base16 -> Color
- NanoUI: [base0F] :: Base16 -> Color
- NanoUI: [cfgAnchor] :: PopupConfig -> PopupAnchor
- NanoUI: [cfgDismissable] :: PopupConfig -> Bool
- NanoUI: [cfgOffset] :: PopupConfig -> Float
- NanoUI: [cfgPlacement] :: PopupConfig -> PopupPlacement
- NanoUI: [fbDrawGlyph] :: FontBackend -> Char -> IO (Maybe GlyphQuad)
- NanoUI: [fbDrawShaped] :: FontBackend -> Text -> IO (Maybe ShapedGlyphs)
- NanoUI: [fbPrepare] :: FontBackend -> Text -> IO FontMetrics
- NanoUI: [fmAdvance] :: FontMetrics -> Char -> Float
- NanoUI: [fmAscent] :: FontMetrics -> Float
- NanoUI: [fmBackend] :: FontMetrics -> Maybe FontBackend
- NanoUI: [fmGlyph] :: FontMetrics -> Char -> Maybe GlyphQuad
- NanoUI: [fmKerning] :: FontMetrics -> Char -> Char -> Float
- NanoUI: [fmLineHeight] :: FontMetrics -> Float
- NanoUI: [fmShape] :: FontMetrics -> Text -> Maybe ShapedText
- NanoUI: [fmSnapScale] :: FontMetrics -> Float
- NanoUI: [gqH] :: GlyphQuad -> Float
- NanoUI: [gqU0] :: GlyphQuad -> Float
- NanoUI: [gqU1] :: GlyphQuad -> Float
- NanoUI: [gqV0] :: GlyphQuad -> Float
- NanoUI: [gqV1] :: GlyphQuad -> Float
- NanoUI: [gqW] :: GlyphQuad -> Float
- NanoUI: [gqX] :: GlyphQuad -> Float
- NanoUI: [gqY] :: GlyphQuad -> Float
- NanoUI: [inputMouseDown] :: Input -> Bool
- NanoUI: [inputMousePressed] :: Input -> Bool
- NanoUI: [inputMouseReleased] :: Input -> Bool
- NanoUI: [inputMouseRightDown] :: Input -> Bool
- NanoUI: [inputMouseRightPressed] :: Input -> Bool
- NanoUI: [inputMouseRightReleased] :: Input -> Bool
- NanoUI: [layoutAlignX] :: Layout -> AlignX
- NanoUI: [layoutAlignY] :: Layout -> AlignY
- NanoUI: [layoutDirection] :: Layout -> Direction
- NanoUI: [layoutFontColor] :: Layout -> Maybe Color
- NanoUI: [layoutFontSize] :: Layout -> Float
- NanoUI: [layoutFontStyle] :: Layout -> FontStyle
- NanoUI: [layoutFontVariant] :: Layout -> FontVariant
- NanoUI: [layoutFontWeight] :: Layout -> FontWeight
- NanoUI: [layoutGap] :: Layout -> Float
- NanoUI: [layoutGridCols] :: Layout -> Int
- NanoUI: [layoutGridMinColW] :: Layout -> Float
- NanoUI: [layoutHeight] :: Layout -> Sizing
- NanoUI: [layoutMaxH] :: Layout -> Float
- NanoUI: [layoutMaxW] :: Layout -> Float
- NanoUI: [layoutMinH] :: Layout -> Float
- NanoUI: [layoutMinW] :: Layout -> Float
- NanoUI: [layoutPadding] :: Layout -> Padding
- NanoUI: [layoutTextDecoration] :: Layout -> TextDecoration
- NanoUI: [layoutWidth] :: Layout -> Sizing
- NanoUI: [pgEdgeBand] :: PaneGridConfig (es :: [Effect]) -> Float
- NanoUI: [pgLayout] :: PaneGridConfig (es :: [Effect]) -> Layout -> Layout
- NanoUI: [pgLeeway] :: PaneGridConfig (es :: [Effect]) -> Float
- NanoUI: [pgMinSize] :: PaneGridConfig (es :: [Effect]) -> Float
- NanoUI: [pgSpacing] :: PaneGridConfig (es :: [Effect]) -> Float
- NanoUI: [pgViewPane] :: PaneGridConfig (es :: [Effect]) -> Word64 -> PaneGridCtx es -> Eff es PaneView
- NanoUI: [pgcClose] :: PaneGridCtx (es :: [Effect]) -> Eff es ()
- NanoUI: [pgcDndActive] :: PaneGridCtx (es :: [Effect]) -> Bool
- NanoUI: [pgcDragging] :: PaneGridCtx (es :: [Effect]) -> Bool
- NanoUI: [pgcMaximize] :: PaneGridCtx (es :: [Effect]) -> Eff es ()
- NanoUI: [pgcMaximized] :: PaneGridCtx (es :: [Effect]) -> Bool
- NanoUI: [pgcPaneId] :: PaneGridCtx (es :: [Effect]) -> Word64
- NanoUI: [pgcRect] :: PaneGridCtx (es :: [Effect]) -> Rect
- NanoUI: [pgcRestore] :: PaneGridCtx (es :: [Effect]) -> Eff es ()
- NanoUI: [pgcSplit] :: PaneGridCtx (es :: [Effect]) -> GridAxis -> Eff es Word64
- NanoUI: [pgrChanged] :: PaneGridResponse -> Bool
- NanoUI: [pgrFocusedPane] :: PaneGridResponse -> Word64
- NanoUI: [pgrMaximizedPane] :: PaneGridResponse -> Word64
- NanoUI: [pgrPaneCount] :: PaneGridResponse -> Int
- NanoUI: [pgrPanes] :: PaneGridResponse -> [Word64]
- NanoUI: [pvDragPick] :: PaneView -> Maybe Rect
- NanoUI: [pvDraggable] :: PaneView -> Bool
- NanoUI: [pvTitle] :: PaneView -> Text
- NanoUI: [rawRespPressed] :: Response -> Bool
- NanoUI: [rawRespRightClicked] :: Response -> Bool
- NanoUI: [rawRespRightPressed] :: Response -> Bool
- NanoUI: [sfcDebounceMs] :: SearchFieldConfig -> Float
- NanoUI: [sfcLayout] :: SearchFieldConfig -> Layout
- NanoUI: [sfcPlaceholder] :: SearchFieldConfig -> Text
- NanoUI: [stAdvance] :: ShapedText -> Float
- NanoUI: [stCarets] :: ShapedText -> PrimArray Float
- NanoUI: [stInkEnd] :: ShapedText -> Float
- NanoUI: [widgetContent] :: CustomWidgetSpec a -> Int
- NanoUI: [widgetCursor] :: CustomWidgetSpec a -> Maybe (CustomDrawContext -> UiCursorKind)
- NanoUI: [widgetDamageSlop] :: CustomWidgetSpec a -> Float
- NanoUI: [widgetDraw] :: CustomWidgetSpec a -> CustomDrawBuild
- NanoUI: [widgetFocusable] :: CustomWidgetSpec a -> Bool
- NanoUI: [widgetInteract] :: CustomWidgetSpec a -> Response -> CustomDrawContext -> Input -> (Response, a)
- NanoUI: [widgetLayout] :: CustomWidgetSpec a -> Layout
- NanoUI: [widgetMeasure] :: CustomWidgetSpec a -> Maybe CustomMeasureFn
- NanoUI: alignMid :: Layout -> Layout
- NanoUI: appendDropEvent :: DropEvent -> SmallArray DropEvent -> SmallArray DropEvent
- NanoUI: appendInputKey :: Key -> SmallArray Key -> SmallArray Key
- NanoUI: askCompact :: forall a (es :: [Effect]). (Typeable a, Ui :> es) => Eff es (Maybe a)
- NanoUI: base16TomorrowLight :: Base16
- NanoUI: base16TomorrowNight :: Base16
- NanoUI: boundedRadio :: forall a (es :: [Effect]). (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es a
- NanoUI: boundedRadio' :: forall a (es :: [Effect]). (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es (Response, a)
- NanoUI: boundedSelect :: forall a (es :: [Effect]). (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es a
- NanoUI: boundedSelect' :: forall a (es :: [Effect]). (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es (Response, a)
- NanoUI: burstNextIds :: forall (es :: [Effect]). Ui :> es => Int -> Eff es ()
- NanoUI: colorToWord32 :: Color -> Word32
- NanoUI: compactHost :: Typeable a => Context -> a -> IO (Compact a)
- NanoUI: customWidget :: forall (es :: [Effect]) a. Ui :> es => CustomWidgetSpec a -> Eff es (Response, a)
- NanoUI: customWidgetWithId :: forall (es :: [Effect]) a. Ui :> es => WidgetId -> CustomWidgetSpec a -> Eff es (Response, a)
- NanoUI: damageFullNow :: forall (es :: [Effect]). Ui :> es => Eff es ()
- NanoUI: damageGroupNow :: forall (es :: [Effect]). Ui :> es => [WidgetId] -> DamageBounds -> Eff es ()
- NanoUI: damageKeyNow :: forall (es :: [Effect]). Ui :> es => Int -> DamageBounds -> Eff es ()
- NanoUI: damageRectNow :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es ()
- NanoUI: damageWidgetNow :: forall (es :: [Effect]). Ui :> es => WidgetId -> DamageBounds -> Eff es ()
- NanoUI: data Base16
- NanoUI: data Compact a
- NanoUI: data CustomWidgetSpec a
- NanoUI: data Damage
- NanoUI: data DamageBounds
- NanoUI: data DrawOp
- NanoUI: data FontBackend
- NanoUI: data GlyphQuad
- NanoUI: data GridAxis
- NanoUI: data IdContext
- NanoUI: data Inline
- NanoUI: data PaneGridConfig (es :: [Effect])
- NanoUI: data PaneGridCtx (es :: [Effect])
- NanoUI: data PaneGridResponse
- NanoUI: data PaneView
- NanoUI: data ScrollBarSlot
- NanoUI: data SearchFieldConfig
- NanoUI: data ShapedText
- NanoUI: data Ui (a :: Type -> Type) b
- NanoUI: defaultCustomWidgetSpec :: CustomWidgetSpec ()
- NanoUI: defaultDamageSlop :: Float
- NanoUI: defaultPaneGridConfig :: forall (es :: [Effect]). PaneGridConfig es
- NanoUI: defaultSearchFieldConfig :: SearchFieldConfig
- NanoUI: drawGlyph :: FontMetrics -> Char -> IO (Maybe GlyphQuad)
- NanoUI: drawShaped :: FontMetrics -> Text -> IO (Maybe ShapedGlyphs)
- NanoUI: drawTextBox :: FontMetrics -> Float -> Float -> Float -> Float -> Text -> Rect
- NanoUI: drawing :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> Eff es Response
- NanoUI: drawingCached :: forall (es :: [Effect]). Ui :> es => Double -> Double -> Float -> Int -> (Layout -> Layout) -> IO Layout -> DrawingBuild -> Eff es Response
- NanoUI: drawingVersioned :: forall (es :: [Effect]). Ui :> es => Int -> (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> Eff es Response
- NanoUI: emphasis :: Text -> Inline
- NanoUI: emptyDropEvents :: SmallArray DropEvent
- NanoUI: emptyInput :: Input
- NanoUI: emptyInputKeys :: SmallArray Key
- NanoUI: foldInputKeys :: (a -> Key -> a) -> a -> SmallArray Key -> a
- NanoUI: fromComponents :: Animatable a => [Float] -> a
- NanoUI: getScrollOffset :: Context -> WidgetId -> IO Float
- NanoUI: getScrollOffset2D :: Context -> WidgetId -> IO V2
- NanoUI: getScrollStep :: Context -> WidgetId -> IO Float
- NanoUI: getTheme :: Context -> IO Theme
- NanoUI: haloDamageSlop :: Float
- NanoUI: hashWidgetId :: WidgetId -> Word64
- NanoUI: hstack :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f (Eff es ()) -> Eff es ()
- NanoUI: hyperlink :: Text -> Text -> Inline
- NanoUI: initialIdContext :: IdContext
- NanoUI: inlineCode :: Text -> Inline
- NanoUI: inlineText :: Text -> Inline
- NanoUI: inlineWith :: (Layout -> Layout) -> Text -> Inline
- NanoUI: inputInteracted :: Input -> Input -> Bool
- NanoUI: inputKeysElem :: Key -> SmallArray Key -> Bool
- NanoUI: inputKeysFromList :: [Key] -> SmallArray Key
- NanoUI: inputKeysNull :: SmallArray Key -> Bool
- NanoUI: inputPointerHeld :: Input -> Bool
- NanoUI: keyed :: forall k (es :: [Effect]) a. (Hashable k, Ui :> es) => k -> Eff es a -> Eff es a
- NanoUI: keyedTag :: forall (es :: [Effect]) a. Ui :> es => Word64 -> Eff es a -> Eff es a
- NanoUI: lineWidthIO :: FontMetrics -> Text -> IO Float
- NanoUI: measureTextIO :: FontMetrics -> Text -> IO (Float, Float)
- NanoUI: mix64 :: Word64 -> Word64 -> Word64
- NanoUI: mixFnv :: Word64 -> Word64 -> Word64
- NanoUI: monospaceMetrics :: Float -> FontMetrics
- NanoUI: newtype ShapedGlyphs
- NanoUI: nextId :: forall (es :: [Effect]). Ui :> es => Eff es WidgetId
- NanoUI: onGrid :: Float -> Float -> Float
- NanoUI: paneGrid :: forall (es :: [Effect]). Ui :> es => PaneGridConfig es -> Eff es PaneGridResponse
- NanoUI: prepareFontMetrics :: FontMetrics -> Text -> IO FontMetrics
- NanoUI: prepareFontMetricsMany :: FontMetrics -> [Text] -> IO FontMetrics
- NanoUI: resolveDamageRect :: DamageBounds -> Rect -> Rect
- NanoUI: restyle :: (Layout -> Layout) -> Inline -> Inline
- NanoUI: richText :: forall (es :: [Effect]). Ui :> es => [Inline] -> Eff es (Maybe Text)
- NanoUI: richText' :: forall (es :: [Effect]). Ui :> es => [Inline] -> Eff es (Response, Maybe Text)
- NanoUI: richTextWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [Inline] -> Eff es (Maybe Text)
- NanoUI: richTextWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [Inline] -> Eff es (Response, Maybe Text)
- NanoUI: roundHalfUp :: Float -> Int
- NanoUI: runCanvas :: CanvasM a -> SmallArray DrawOp
- NanoUI: runNanoUI :: Context -> Input -> NanoUI a -> IO a
- NanoUI: runTextCommand :: forall (es :: [Effect]). Ui :> es => WidgetId -> TextCommand -> Eff es ()
- NanoUI: runUi :: forall (es :: [Effect]) a. IOE :> es => Context -> Input -> Eff (Ui ': es) a -> Eff es a
- NanoUI: scaleFontMetrics :: Float -> FontMetrics -> FontMetrics
- NanoUI: scrollArea :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es (WidgetId, a)
- NanoUI: scrollArea2D :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es (WidgetId, a)
- NanoUI: scrollBarGutter :: ScrollBarSlot -> Float -> Float
- NanoUI: scrollBarThumbColor :: Style -> Theme -> Color
- NanoUI: scrollBarTrackColor :: Style -> Theme -> Color
- NanoUI: scrollBarWidth :: Float
- NanoUI: scrollGliding :: Context -> WidgetId -> IO Bool
- NanoUI: searchField :: forall (es :: [Effect]). Ui :> es => Text -> Text -> Eff es Text
- NanoUI: searchField' :: forall (es :: [Effect]). Ui :> es => Text -> Text -> Eff es (Response, Text)
- NanoUI: searchFieldConfigured :: forall (es :: [Effect]). Ui :> es => SearchFieldConfig -> Text -> Eff es Text
- NanoUI: searchFieldConfigured' :: forall (es :: [Effect]). Ui :> es => SearchFieldConfig -> Text -> Eff es (Response, Text)
- NanoUI: setChanged :: Bool -> Response -> Response
- NanoUI: setClicked :: Bool -> Response -> Response
- NanoUI: setScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()
- NanoUI: setSubmitted :: Bool -> Response -> Response
- NanoUI: setUiTheme :: forall (es :: [Effect]). Ui :> es => Theme -> Eff es ()
- NanoUI: shiftDrawOp :: Float -> Float -> DrawOp -> DrawOp
- NanoUI: sliderDamageSlop :: Float
- NanoUI: strong :: Text -> Inline
- NanoUI: textCanRedo :: forall (es :: [Effect]). Ui :> es => WidgetId -> Eff es Bool
- NanoUI: textCanUndo :: forall (es :: [Effect]). Ui :> es => WidgetId -> Eff es Bool
- NanoUI: themeFromBase16 :: Base16 -> Theme
- NanoUI: themeFromBase16Dark :: Base16 -> Theme
- NanoUI: themeFromBase16Light :: Base16 -> Theme
- NanoUI: toComponents :: Animatable a => a -> [Float]
- NanoUI: tomorrowMidnightMinDarkTheme :: Theme
- NanoUI: tomorrowMinLightTheme :: Theme
- NanoUI: tomorrowNightMinDarkTheme :: Theme
- NanoUI: treeItemPadding :: FontMetrics -> (Float, Float)
- NanoUI: type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp
- NanoUI: type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)
- NanoUI: type DrawingBuild = Rect -> SmallArray DrawOp
- NanoUI: type NanoUI = Eff '[Ui, IOE]
- NanoUI: uiIO :: forall (es :: [Effect]) a. Ui :> es => IO a -> Eff es a
- NanoUI: useContextMenu :: forall (es :: [Effect]). Ui :> es => Eff es (Bool, V2, V2 -> Eff es (), Eff es ())
- NanoUI: useDrag2D :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es Drag2D
- NanoUI: useEnum :: forall a (es :: [Effect]). (Enum a, Ui :> es) => a -> Eff es (a, a -> Eff es ())
- NanoUI: useFlag :: forall (es :: [Effect]). Ui :> es => Bool -> Eff es (Bool, Bool -> Eff es ())
- NanoUI: useFloat :: forall (es :: [Effect]). Ui :> es => Float -> Eff es (Float, Float -> Eff es ())
- NanoUI: useInt :: forall (es :: [Effect]). Ui :> es => Int -> Eff es (Int, Int -> Eff es ())
- NanoUI: useState :: forall a (es :: [Effect]). (Typeable a, Eq a, Ui :> es) => a -> Eff es (a, a -> Eff es ())
- NanoUI: useTableSort :: forall (es :: [Effect]). Ui :> es => SortCol -> Eff es (SortCol, SortCol -> Eff es ())
- NanoUI: useText :: forall (es :: [Effect]). Ui :> es => Text -> Eff es (Text, Text -> Eff es ())
- NanoUI: useToggle :: forall (es :: [Effect]). Ui :> es => Bool -> Eff es (Bool, Eff es ())
- NanoUI: useWheelDelta :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es (Float, Float)
- NanoUI: vstack :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f (Eff es ()) -> Eff es ()
- NanoUI: widgetContentInset :: FontMetrics -> (Float, Float)
- NanoUI: widgetId :: HasCallStack => WidgetId
- NanoUI: widgetPadding :: FontMetrics -> (Float, Float)
- NanoUI: window :: forall (es :: [Effect]) a. Ui :> es => Bool -> Text -> Eff es a -> Eff es (Response, Maybe a)
- NanoUI: windowMargin :: Float
- NanoUI: windowPad :: Padding
- NanoUI: withTheme :: Context -> Theme -> IO Context
- NanoUI.Context: AnimationState :: IntMap Animation -> IntMap Float -> Bool -> Bool -> IntMap Int -> AnimationState
- NanoUI.Context: Context :: NodeArena -> DrawArena -> IORef WidgetId -> IORef WidgetId -> IORef WidgetId -> IORef WidgetId -> IORef WidgetId -> IORef (Maybe V2) -> IORef (Maybe V2) -> IORef WidgetId -> IORef Bool -> IORef WidgetStore -> IORef DamageState -> IORef OverlayState -> IORef AnimationState -> IORef ScrollState -> IORef DrawingCacheState -> IORef IdContext -> FontMetrics -> FontMetrics -> (Text -> IO (Float, Float)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Maybe (IORef (HashMap MeasureCacheKey (Float, Float))) -> IORef (IntMap SpanCacheEntry) -> IORef (IntMap WidgetTextCacheEntry) -> IORef (Maybe (LayoutCache, Size, Int)) -> IORef Int -> MetricSource -> IORef (Maybe MetricSource) -> IORef Bool -> Bool -> IORef Theme -> IORef ThemeScopes -> IORef [Int] -> IORef [FrameMsg] -> IORef (MutablePrimArray RealWorld WidgetId) -> IORef Int -> SpanArena -> SpanArena -> IORef InteractionState -> IO (Maybe Text) -> (Text -> IO Bool) -> ImageAtlas -> IORef (Maybe (IO ())) -> IORef (Map TypeRep Dynamic) -> IORef Layout -> Context
- NanoUI.Context: CustomDrawContext :: Bool -> Bool -> Bool -> Bool -> Bool -> Theme -> FontMetrics -> CustomDrawContext
- NanoUI.Context: CustomDrawingEntry :: Int -> CustomDrawBuild -> CustomDrawingEntry
- NanoUI.Context: DamageState :: Bool -> Damage -> [DamageRequest] -> Size -> IntMap Rect -> IntMap Rect -> IntMap Text -> DamageState
- NanoUI.Context: DrawFitCache :: Double -> Double -> Float -> Int -> Layout -> Layout -> DrawFitCache
- NanoUI.Context: DrawingCacheState :: IntMap PopupConfig -> IntMap DrawingEntry -> IntMap CustomDrawingEntry -> IntMap CustomMeasureFn -> IntMap (CustomDrawContext -> UiCursorKind) -> IntMap Float -> IntMap DrawOpCacheEntry -> IntMap CustomDrawOpCacheEntry -> IntMap DrawFitCache -> DrawingCacheState
- NanoUI.Context: DrawingEntry :: Int -> DrawingBuild -> DrawingEntry
- NanoUI.Context: EaseAnim :: Float -> Float -> Float -> Float -> Ease -> Float -> Float -> Animation
- NanoUI.Context: EaseCubicBezier :: Float -> Float -> Float -> Float -> Ease
- NanoUI.Context: EaseInCubic :: Ease
- NanoUI.Context: EaseInOutCubic :: Ease
- NanoUI.Context: EaseInOutQuad :: Ease
- NanoUI.Context: EaseInQuad :: Ease
- NanoUI.Context: EaseLinear :: Ease
- NanoUI.Context: EaseOutBack :: Ease
- NanoUI.Context: EaseOutCubic :: Ease
- NanoUI.Context: EaseOutQuad :: Ease
- NanoUI.Context: InteractionState :: Maybe (WidgetId, DirTag, Float) -> Maybe TextInputDrag -> Maybe TextFieldClickCell -> Maybe TextInputMenu -> Maybe (WidgetId, TextCommand) -> Bool -> Maybe (WidgetId, Rect) -> Bool -> Maybe (WidgetId, Float, Float) -> Maybe WindowResizeDrag -> InteractionState
- NanoUI.Context: OverlayState :: Bool -> Bool -> Int -> Bool -> IntMap Rect -> [Int] -> Maybe (V2, Maybe WidgetId) -> Maybe WidgetId -> Bool -> OverlayState
- NanoUI.Context: ReqFull :: DamageRequest
- NanoUI.Context: ReqKey :: Int -> DamageBounds -> DamageRequest
- NanoUI.Context: ReqPeers :: [WidgetId] -> DamageBounds -> DamageRequest
- NanoUI.Context: ReqRect :: Rect -> DamageRequest
- NanoUI.Context: ReqWidget :: WidgetId -> DamageBounds -> DamageRequest
- NanoUI.Context: ResizeE :: WindowResizeEdge
- NanoUI.Context: ResizeN :: WindowResizeEdge
- NanoUI.Context: ResizeNE :: WindowResizeEdge
- NanoUI.Context: ResizeNW :: WindowResizeEdge
- NanoUI.Context: ResizeS :: WindowResizeEdge
- NanoUI.Context: ResizeSE :: WindowResizeEdge
- NanoUI.Context: ResizeSW :: WindowResizeEdge
- NanoUI.Context: ResizeW :: WindowResizeEdge
- NanoUI.Context: ScrollAxisX :: ScrollAxes
- NanoUI.Context: ScrollAxisXY :: ScrollAxes
- NanoUI.Context: ScrollAxisY :: ScrollAxes
- NanoUI.Context: ScrollCenter :: ScrollAlign
- NanoUI.Context: ScrollEnd :: ScrollAlign
- NanoUI.Context: ScrollInstant :: ScrollBehavior
- NanoUI.Context: ScrollMetrics :: Rect -> V2 -> V2 -> ScrollAxes -> ScrollMetrics
- NanoUI.Context: ScrollNearest :: ScrollAlign
- NanoUI.Context: ScrollSmooth :: ScrollBehavior
- NanoUI.Context: ScrollStart :: ScrollAlign
- NanoUI.Context: ScrollTuning :: Float -> Float -> ScrollTuning
- NanoUI.Context: SlotAnchor :: Slot
- NanoUI.Context: SlotColorBase :: Slot
- NanoUI.Context: SlotComboCommitted :: Slot
- NanoUI.Context: SlotComboContentW :: Slot
- NanoUI.Context: SlotComboCount :: Slot
- NanoUI.Context: SlotComboDrag :: Slot
- NanoUI.Context: SlotComboDragOff :: Slot
- NanoUI.Context: SlotComboFocus :: Slot
- NanoUI.Context: SlotComboHighlight :: Slot
- NanoUI.Context: SlotComboLive :: Slot
- NanoUI.Context: SlotComboScroll :: Slot
- NanoUI.Context: SlotComboScrollX :: Slot
- NanoUI.Context: SlotCursor :: Slot
- NanoUI.Context: SlotDrag :: Slot
- NanoUI.Context: SlotDragW :: Slot
- NanoUI.Context: SlotDrop :: Slot
- NanoUI.Context: SlotDropPos :: Slot
- NanoUI.Context: SlotMenuOpen :: Slot
- NanoUI.Context: SlotMenuPos :: Slot
- NanoUI.Context: SlotNumericHeld :: Slot
- NanoUI.Context: SlotNumericRepeat :: Slot
- NanoUI.Context: SlotPaneFocus :: Slot
- NanoUI.Context: SlotPaneGest :: Slot
- NanoUI.Context: SlotPaneGrab :: Slot
- NanoUI.Context: SlotPaneMax :: Slot
- NanoUI.Context: SlotPaneNext :: Slot
- NanoUI.Context: SlotPaneResize :: Slot
- NanoUI.Context: SlotScrollAxes :: Slot
- NanoUI.Context: SlotScrollCfg :: Slot
- NanoUI.Context: SlotScrollContent :: Slot
- NanoUI.Context: SlotScrollCross :: Slot
- NanoUI.Context: SlotScrollLinkX :: Slot
- NanoUI.Context: SlotScrollLinkY :: Slot
- NanoUI.Context: SlotScrollOff :: Slot
- NanoUI.Context: SlotScrollRange :: Slot
- NanoUI.Context: SlotScrollStep :: Slot
- NanoUI.Context: SlotScrollViewPos :: Slot
- NanoUI.Context: SlotScrollViewSize :: Slot
- NanoUI.Context: SlotSearchAge :: Slot
- NanoUI.Context: SlotSearchCommitted :: Slot
- NanoUI.Context: SlotSeen :: Slot
- NanoUI.Context: SlotTextAreaAnchorCol :: Slot
- NanoUI.Context: SlotTextAreaAnchorRow :: Slot
- NanoUI.Context: SlotTextAreaBuffer :: Slot
- NanoUI.Context: SlotTextAreaChanged :: Slot
- NanoUI.Context: SlotTextAreaCol :: Slot
- NanoUI.Context: SlotTextAreaContentFont :: Slot
- NanoUI.Context: SlotTextAreaContentH :: Slot
- NanoUI.Context: SlotTextAreaContentW :: Slot
- NanoUI.Context: SlotTextAreaPrefCol :: Slot
- NanoUI.Context: SlotTextAreaRow :: Slot
- NanoUI.Context: SlotTextAreaScroll :: Slot
- NanoUI.Context: SlotTextAreaViewport :: Slot
- NanoUI.Context: SlotTextAreaWidths :: Slot
- NanoUI.Context: SlotTextHistory :: Slot
- NanoUI.Context: SlotTextInputScroll :: Slot
- NanoUI.Context: SlotTextMode :: Slot
- NanoUI.Context: SlotWinSize :: Slot
- NanoUI.Context: SpanCacheEntry :: Text -> Color -> Color -> Int -> Float -> Int -> Int -> Rect -> Float -> Bool -> [(Rect, Text, Color, Color)] -> SpanCacheEntry
- NanoUI.Context: SpringAnim :: Float -> Float -> Float -> SpringParams -> Animation
- NanoUI.Context: SpringParams :: Float -> Float -> Float -> SpringParams
- NanoUI.Context: TextFieldClickCell :: WidgetId -> Int -> Int -> Int -> Bool -> TextFieldClickCell
- NanoUI.Context: TextInputDrag :: WidgetId -> Int -> Int -> Int -> Bool -> Int -> TextInputDrag
- NanoUI.Context: TextInputMenu :: WidgetId -> Rect -> TextInputMenu
- NanoUI.Context: WidgetStore :: Word64 -> Int -> IntMap Int -> IntMap Float -> IntMap Double -> IntMap (Float, Float) -> IntMap Text -> IntMap IntSet -> IntMap [Float] -> IntMap [Int] -> IntMap Dynamic -> WidgetStore
- NanoUI.Context: WidgetTextCacheEntry :: Int -> Int -> Float -> Text -> Float -> Float -> Int -> Maybe WidgetTextPlacement -> WidgetTextCacheEntry
- NanoUI.Context: WidgetTextPlacement :: Text -> Float -> Float -> Float -> Float -> WidgetTextPlacement
- NanoUI.Context: WindowResizeDrag :: WidgetId -> WindowResizeEdge -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> WindowResizeDrag
- NanoUI.Context: [FrameMsg] :: forall a. Typeable a => a -> FrameMsg
- NanoUI.Context: [asAnimRest] :: AnimationState -> IntMap Float
- NanoUI.Context: [asAnimSettled] :: AnimationState -> Bool
- NanoUI.Context: [asAnimations] :: AnimationState -> IntMap Animation
- NanoUI.Context: [asAnyAnimating] :: AnimationState -> Bool
- NanoUI.Context: [asRectless] :: AnimationState -> IntMap Int
- NanoUI.Context: [cdcActive] :: CustomDrawContext -> Bool
- NanoUI.Context: [cdcDisabled] :: CustomDrawContext -> Bool
- NanoUI.Context: [cdcFocused] :: CustomDrawContext -> Bool
- NanoUI.Context: [cdcFont] :: CustomDrawContext -> FontMetrics
- NanoUI.Context: [cdcHovered] :: CustomDrawContext -> Bool
- NanoUI.Context: [cdcPressed] :: CustomDrawContext -> Bool
- NanoUI.Context: [cdcTheme] :: CustomDrawContext -> Theme
- NanoUI.Context: [cdrBuild] :: CustomDrawingEntry -> CustomDrawBuild
- NanoUI.Context: [cdrContent] :: CustomDrawingEntry -> Int
- NanoUI.Context: [ctxActiveId] :: Context -> IORef WidgetId
- NanoUI.Context: [ctxAnimationState] :: Context -> IORef AnimationState
- NanoUI.Context: [ctxClickedId] :: Context -> IORef WidgetId
- NanoUI.Context: [ctxClipboardGet] :: Context -> IO (Maybe Text)
- NanoUI.Context: [ctxClipboardSet] :: Context -> Text -> IO Bool
- NanoUI.Context: [ctxContainerStack] :: Context -> IORef [Int]
- NanoUI.Context: [ctxDamageState] :: Context -> IORef DamageState
- NanoUI.Context: [ctxDefaultLayout] :: Context -> IORef Layout
- NanoUI.Context: [ctxDrawArena] :: Context -> DrawArena
- NanoUI.Context: [ctxDrawingCache] :: Context -> IORef DrawingCacheState
- NanoUI.Context: [ctxExternalText] :: Context -> Bool
- NanoUI.Context: [ctxFocusId] :: Context -> IORef WidgetId
- NanoUI.Context: [ctxFocusVisible] :: Context -> IORef Bool
- NanoUI.Context: [ctxFocusablesCount] :: Context -> IORef Int
- NanoUI.Context: [ctxFocusables] :: Context -> IORef (MutablePrimArray RealWorld WidgetId)
- NanoUI.Context: [ctxFontMetrics] :: Context -> FontMetrics
- NanoUI.Context: [ctxHost] :: Context -> IORef (Map TypeRep Dynamic)
- NanoUI.Context: [ctxHotId] :: Context -> IORef WidgetId
- NanoUI.Context: [ctxIdContext] :: Context -> IORef IdContext
- NanoUI.Context: [ctxImageAtlas] :: Context -> ImageAtlas
- NanoUI.Context: [ctxInteractionState] :: Context -> IORef InteractionState
- NanoUI.Context: [ctxLastHotId] :: Context -> IORef WidgetId
- NanoUI.Context: [ctxLastMetricSource] :: Context -> IORef (Maybe MetricSource)
- NanoUI.Context: [ctxLayoutCache] :: Context -> IORef (Maybe (LayoutCache, Size, Int))
- NanoUI.Context: [ctxMeasureCache] :: Context -> Maybe (IORef (HashMap MeasureCacheKey (Float, Float)))
- NanoUI.Context: [ctxMeasureText] :: Context -> Text -> IO (Float, Float)
- NanoUI.Context: [ctxMessages] :: Context -> IORef [FrameMsg]
- NanoUI.Context: [ctxMetricGen] :: Context -> IORef Int
- NanoUI.Context: [ctxMetricSource] :: Context -> MetricSource
- NanoUI.Context: [ctxMonoFontMetrics] :: Context -> FontMetrics
- NanoUI.Context: [ctxNodeArena] :: Context -> NodeArena
- NanoUI.Context: [ctxOverlayState] :: Context -> IORef OverlayState
- NanoUI.Context: [ctxPaintFull] :: Context -> IORef Bool
- NanoUI.Context: [ctxPressPos] :: Context -> IORef (Maybe V2)
- NanoUI.Context: [ctxReleaseClickedId] :: Context -> IORef WidgetId
- NanoUI.Context: [ctxResolveFont] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)
- NanoUI.Context: [ctxResolveMeasure] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)
- NanoUI.Context: [ctxRightPressPos] :: Context -> IORef (Maybe V2)
- NanoUI.Context: [ctxScrollState] :: Context -> IORef ScrollState
- NanoUI.Context: [ctxSpanBase] :: Context -> SpanArena
- NanoUI.Context: [ctxSpanCache] :: Context -> IORef (IntMap SpanCacheEntry)
- NanoUI.Context: [ctxSpanOverlay] :: Context -> SpanArena
- NanoUI.Context: [ctxStore] :: Context -> IORef WidgetStore
- NanoUI.Context: [ctxThemeScopes] :: Context -> IORef ThemeScopes
- NanoUI.Context: [ctxTheme] :: Context -> IORef Theme
- NanoUI.Context: [ctxWakeLoop] :: Context -> IORef (Maybe (IO ()))
- NanoUI.Context: [ctxWidgetTextCache] :: Context -> IORef (IntMap WidgetTextCacheEntry)
- NanoUI.Context: [dcsCustomCursors] :: DrawingCacheState -> IntMap (CustomDrawContext -> UiCursorKind)
- NanoUI.Context: [dcsCustomDamageSlop] :: DrawingCacheState -> IntMap Float
- NanoUI.Context: [dcsCustomDrawOpCache] :: DrawingCacheState -> IntMap CustomDrawOpCacheEntry
- NanoUI.Context: [dcsCustomDrawings] :: DrawingCacheState -> IntMap CustomDrawingEntry
- NanoUI.Context: [dcsCustomMeasures] :: DrawingCacheState -> IntMap CustomMeasureFn
- NanoUI.Context: [dcsDrawFitCache] :: DrawingCacheState -> IntMap DrawFitCache
- NanoUI.Context: [dcsDrawOpCache] :: DrawingCacheState -> IntMap DrawOpCacheEntry
- NanoUI.Context: [dcsDrawings] :: DrawingCacheState -> IntMap DrawingEntry
- NanoUI.Context: [dcsPopupConfigs] :: DrawingCacheState -> IntMap PopupConfig
- NanoUI.Context: [deBuild] :: DrawingEntry -> DrawingBuild
- NanoUI.Context: [deContent] :: DrawingEntry -> Int
- NanoUI.Context: [dfcContent] :: DrawFitCache -> Int
- NanoUI.Context: [dfcDh] :: DrawFitCache -> Double
- NanoUI.Context: [dfcDw] :: DrawFitCache -> Double
- NanoUI.Context: [dfcIn] :: DrawFitCache -> Layout
- NanoUI.Context: [dfcLh] :: DrawFitCache -> Float
- NanoUI.Context: [dfcOut] :: DrawFitCache -> Layout
- NanoUI.Context: [dsDamage] :: DamageState -> Damage
- NanoUI.Context: [dsDirty] :: DamageState -> Bool
- NanoUI.Context: [dsLastWindowSize] :: DamageState -> Size
- NanoUI.Context: [dsPrevClips] :: DamageState -> IntMap Rect
- NanoUI.Context: [dsPrevNodeTexts] :: DamageState -> IntMap Text
- NanoUI.Context: [dsPrevRects] :: DamageState -> IntMap Rect
- NanoUI.Context: [dsRequests] :: DamageState -> [DamageRequest]
- NanoUI.Context: [isMenuPointerGesture] :: InteractionState -> Bool
- NanoUI.Context: [isOpenSelectDrop] :: InteractionState -> Maybe (WidgetId, Rect)
- NanoUI.Context: [isScrollDrag] :: InteractionState -> Maybe (WidgetId, DirTag, Float)
- NanoUI.Context: [isSelectDropPress] :: InteractionState -> Bool
- NanoUI.Context: [isTextEditLastAction] :: InteractionState -> Maybe (WidgetId, TextCommand)
- NanoUI.Context: [isTextFieldClickCell] :: InteractionState -> Maybe TextFieldClickCell
- NanoUI.Context: [isTextInputDrag] :: InteractionState -> Maybe TextInputDrag
- NanoUI.Context: [isTextInputMenu] :: InteractionState -> Maybe TextInputMenu
- NanoUI.Context: [isWindowDrag] :: InteractionState -> Maybe (WidgetId, Float, Float)
- NanoUI.Context: [isWindowResize] :: InteractionState -> Maybe WindowResizeDrag
- NanoUI.Context: [osCurrentFloatingId] :: OverlayState -> Maybe WidgetId
- NanoUI.Context: [osEscapeConsumed] :: OverlayState -> Bool
- NanoUI.Context: [osLastPointerBlocked] :: OverlayState -> Bool
- NanoUI.Context: [osModalActive] :: OverlayState -> Bool
- NanoUI.Context: [osModalDepth] :: OverlayState -> Int
- NanoUI.Context: [osModalWasActive] :: OverlayState -> Bool
- NanoUI.Context: [osPrevFloatingOrder] :: OverlayState -> [Int]
- NanoUI.Context: [osPrevFloatingRects] :: OverlayState -> IntMap Rect
- NanoUI.Context: [osTopmostCache] :: OverlayState -> Maybe (V2, Maybe WidgetId)
- NanoUI.Context: [sceAlign] :: SpanCacheEntry -> Int
- NanoUI.Context: [sceBg] :: SpanCacheEntry -> Color
- NanoUI.Context: [sceEffMaxW] :: SpanCacheEntry -> Float
- NanoUI.Context: [sceFg] :: SpanCacheEntry -> Color
- NanoUI.Context: [sceFontSize] :: SpanCacheEntry -> Float
- NanoUI.Context: [sceRect] :: SpanCacheEntry -> Rect
- NanoUI.Context: [sceRowChild] :: SpanCacheEntry -> Bool
- NanoUI.Context: [sceSpans] :: SpanCacheEntry -> [(Rect, Text, Color, Color)]
- NanoUI.Context: [sceStyle] :: SpanCacheEntry -> Int
- NanoUI.Context: [sceText] :: SpanCacheEntry -> Text
- NanoUI.Context: [sceWidthTag] :: SpanCacheEntry -> Int
- NanoUI.Context: [scrollAxes] :: ScrollMetrics -> ScrollAxes
- NanoUI.Context: [scrollOffset] :: ScrollMetrics -> V2
- NanoUI.Context: [scrollRange] :: ScrollMetrics -> V2
- NanoUI.Context: [scrollSmoothTime] :: ScrollTuning -> Float
- NanoUI.Context: [scrollViewport] :: ScrollMetrics -> Rect
- NanoUI.Context: [scrollWheelStep] :: ScrollTuning -> Float
- NanoUI.Context: [springDamping] :: SpringParams -> Float
- NanoUI.Context: [springMass] :: SpringParams -> Float
- NanoUI.Context: [springStiffness] :: SpringParams -> Float
- NanoUI.Context: [storeDouble] :: WidgetStore -> IntMap Double
- NanoUI.Context: [storeDyn] :: WidgetStore -> IntMap Dynamic
- NanoUI.Context: [storeFloatList] :: WidgetStore -> IntMap [Float]
- NanoUI.Context: [storeFloat] :: WidgetStore -> IntMap Float
- NanoUI.Context: [storeIntList] :: WidgetStore -> IntMap [Int]
- NanoUI.Context: [storeIntSet] :: WidgetStore -> IntMap IntSet
- NanoUI.Context: [storeInt] :: WidgetStore -> IntMap Int
- NanoUI.Context: [storeMirrorGen] :: WidgetStore -> Word64
- NanoUI.Context: [storeOpenSelect] :: WidgetStore -> Int
- NanoUI.Context: [storePoint] :: WidgetStore -> IntMap (Float, Float)
- NanoUI.Context: [storeText] :: WidgetStore -> IntMap Text
- NanoUI.Context: [textFieldClickCol] :: TextFieldClickCell -> Int
- NanoUI.Context: [textFieldClickFlat] :: TextFieldClickCell -> Int
- NanoUI.Context: [textFieldClickMultiline] :: TextFieldClickCell -> Bool
- NanoUI.Context: [textFieldClickRow] :: TextFieldClickCell -> Int
- NanoUI.Context: [textFieldClickWidget] :: TextFieldClickCell -> WidgetId
- NanoUI.Context: [textInputDragAnchorCol] :: TextInputDrag -> Int
- NanoUI.Context: [textInputDragAnchorRow] :: TextInputDrag -> Int
- NanoUI.Context: [textInputDragAnchor] :: TextInputDrag -> Int
- NanoUI.Context: [textInputDragClicks] :: TextInputDrag -> Int
- NanoUI.Context: [textInputDragMultiline] :: TextInputDrag -> Bool
- NanoUI.Context: [textInputDragWidget] :: TextInputDrag -> WidgetId
- NanoUI.Context: [textInputMenuRect] :: TextInputMenu -> Rect
- NanoUI.Context: [textInputMenuWidget] :: TextInputMenu -> WidgetId
- NanoUI.Context: [wrdEdge] :: WindowResizeDrag -> WindowResizeEdge
- NanoUI.Context: [wrdGrabX] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdGrabY] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdMaxH] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdMaxW] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdMinH] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdMinW] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdStartH] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdStartW] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdStartX] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdStartY] :: WindowResizeDrag -> Float
- NanoUI.Context: [wrdWidget] :: WindowResizeDrag -> WidgetId
- NanoUI.Context: [wtcAlign] :: WidgetTextCacheEntry -> Int
- NanoUI.Context: [wtcFontSize] :: WidgetTextCacheEntry -> Float
- NanoUI.Context: [wtcHeight] :: WidgetTextCacheEntry -> Float
- NanoUI.Context: [wtcNodeType] :: WidgetTextCacheEntry -> Int
- NanoUI.Context: [wtcPlacement] :: WidgetTextCacheEntry -> Maybe WidgetTextPlacement
- NanoUI.Context: [wtcStyle] :: WidgetTextCacheEntry -> Int
- NanoUI.Context: [wtcText] :: WidgetTextCacheEntry -> Text
- NanoUI.Context: [wtcWidth] :: WidgetTextCacheEntry -> Float
- NanoUI.Context: adoptStoreFloat :: Context -> WidgetId -> Int -> Float -> IO Float
- NanoUI.Context: adoptStoreInt :: Context -> WidgetId -> Int -> Int -> IO Int
- NanoUI.Context: adoptStoreText :: Context -> WidgetId -> Int -> Text -> IO Text
- NanoUI.Context: animInProgress :: Animation -> Bool
- NanoUI.Context: anyAnimating :: Context -> IO Bool
- NanoUI.Context: anySelectOpen :: WidgetStore -> Bool
- NanoUI.Context: applyEase :: Ease -> Float -> Float
- NanoUI.Context: applyScrollTarget :: Context -> WidgetId -> ScrollAxes -> V2 -> ScrollBehavior -> IO ()
- NanoUI.Context: approxEq :: Float -> Float -> Bool
- NanoUI.Context: armMenuPointerCapture :: Context -> Input -> IO ()
- NanoUI.Context: askHostIO :: Typeable a => Context -> IO (Maybe a)
- NanoUI.Context: atlasSnapshot :: Context -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))
- NanoUI.Context: atlasTextureId :: Int
- NanoUI.Context: beginFrameModal :: Context -> IO ()
- NanoUI.Context: beginModal :: Context -> IO ()
- NanoUI.Context: beginScrollMetrics :: Context -> IO ()
- NanoUI.Context: beginThemeScopes :: Context -> Bool -> IO ()
- NanoUI.Context: boolInt :: Bool -> Int
- NanoUI.Context: bumpMirror :: WidgetStore -> WidgetStore
- NanoUI.Context: cacheScrollMetrics :: Context -> WidgetId -> ScrollAxes -> Rect -> V2 -> IO ()
- NanoUI.Context: cachedCustomDrawingOps :: Context -> WidgetId -> Int -> Rect -> CustomDrawContext -> CustomDrawBuild -> IO (SmallArray DrawOp)
- NanoUI.Context: cachedDrawingOps :: Context -> WidgetId -> Int -> Rect -> DrawingBuild -> IO (SmallArray DrawOp)
- NanoUI.Context: cachedWidgetLayout :: Context -> WidgetId -> Double -> Double -> Float -> Int -> Layout -> IO Layout -> IO Layout
- NanoUI.Context: cancelScrollGlide :: Context -> WidgetId -> IO ()
- NanoUI.Context: clampScrollOffset :: V2 -> V2 -> V2
- NanoUI.Context: clearDirty :: Context -> IO ()
- NanoUI.Context: clearMeasureCache :: Context -> IO ()
- NanoUI.Context: closeSelects :: WidgetStore -> WidgetStore
- NanoUI.Context: currentTheme :: Context -> IO Theme
- NanoUI.Context: damageFull :: Context -> IO ()
- NanoUI.Context: damageKey :: Context -> Int -> DamageBounds -> IO ()
- NanoUI.Context: damagePeers :: Context -> [WidgetId] -> DamageBounds -> IO ()
- NanoUI.Context: damageRect :: Context -> Rect -> IO ()
- NanoUI.Context: damageWidget :: Context -> WidgetId -> DamageBounds -> IO ()
- NanoUI.Context: data Animation
- NanoUI.Context: data AnimationState
- NanoUI.Context: data Context
- NanoUI.Context: data CustomDrawContext
- NanoUI.Context: data CustomDrawingEntry
- NanoUI.Context: data DamageRequest
- NanoUI.Context: data DamageState
- NanoUI.Context: data DrawFitCache
- NanoUI.Context: data DrawingCacheState
- NanoUI.Context: data DrawingEntry
- NanoUI.Context: data Ease
- NanoUI.Context: data FrameMsg
- NanoUI.Context: data InteractionState
- NanoUI.Context: data OverlayState
- NanoUI.Context: data ScrollAlign
- NanoUI.Context: data ScrollAxes
- NanoUI.Context: data ScrollBehavior
- NanoUI.Context: data ScrollMetrics
- NanoUI.Context: data ScrollTuning
- NanoUI.Context: data Slot
- NanoUI.Context: data SpanCacheEntry
- NanoUI.Context: data SpringParams
- NanoUI.Context: data TextFieldClickCell
- NanoUI.Context: data TextInputDrag
- NanoUI.Context: data TextInputMenu
- NanoUI.Context: data WidgetStore
- NanoUI.Context: data WidgetTextCacheEntry
- NanoUI.Context: data WidgetTextPlacement
- NanoUI.Context: data WindowResizeDrag
- NanoUI.Context: data WindowResizeEdge
- NanoUI.Context: decodeMessages :: (Foldable f, Typeable a) => f FrameMsg -> [a]
- NanoUI.Context: defaultScrollConfig :: ScrollConfig
- NanoUI.Context: defaultScrollTuning :: ScrollTuning
- NanoUI.Context: drainMessages :: Context -> IO [FrameMsg]
- NanoUI.Context: drawingOpsStale :: Context -> WidgetId -> Int -> Rect -> IO Bool
- NanoUI.Context: easeSameSpec :: Animation -> Ease -> Float -> Float -> Float -> Bool
- NanoUI.Context: enableMeasureCache :: Context -> IO Context
- NanoUI.Context: endModal :: Context -> IO ()
- NanoUI.Context: ensureMetricCaches :: Context -> IO ()
- NanoUI.Context: getAnimRectless :: Context -> IO (IntMap Int)
- NanoUI.Context: getAnimRest :: Context -> IO (IntMap Float)
- NanoUI.Context: getAnimationValue :: Context -> WidgetId -> IO Float
- NanoUI.Context: getFocusId :: Context -> IO WidgetId
- NanoUI.Context: getFocusVisible :: Context -> IO Bool
- NanoUI.Context: getFocusables :: Context -> IO [WidgetId]
- NanoUI.Context: getHotId :: Context -> IO WidgetId
- NanoUI.Context: getLiveAnimations :: Context -> IO (IntMap Animation)
- NanoUI.Context: getMenuPointerGesture :: Context -> IO Bool
- NanoUI.Context: getPrevClipRect :: Context -> WidgetId -> IO (Maybe Rect)
- NanoUI.Context: getPrevRect :: Context -> WidgetId -> IO (Maybe Rect)
- NanoUI.Context: getScrollDrag :: Context -> IO (Maybe (WidgetId, DirTag, Float))
- NanoUI.Context: getScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)
- NanoUI.Context: getScrollOffset :: Context -> WidgetId -> IO Float
- NanoUI.Context: getScrollOffset2D :: Context -> WidgetId -> IO V2
- NanoUI.Context: getScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> IO V2
- NanoUI.Context: getScrollStep :: Context -> WidgetId -> IO Float
- NanoUI.Context: getScrollTuning :: Context -> IO ScrollTuning
- NanoUI.Context: getStore :: Context -> IO WidgetStore
- NanoUI.Context: getStoreBool :: Context -> WidgetId -> Bool -> IO Bool
- NanoUI.Context: getTextInputMenu :: Context -> IO (Maybe TextInputMenu)
- NanoUI.Context: getTheme :: Context -> IO Theme
- NanoUI.Context: getWindowDrag :: Context -> IO (Maybe (WidgetId, Float, Float))
- NanoUI.Context: getWindowResize :: Context -> IO (Maybe WindowResizeDrag)
- NanoUI.Context: getsDamage :: Context -> (DamageState -> a) -> IO a
- NanoUI.Context: getsInteraction :: Context -> (InteractionState -> a) -> IO a
- NanoUI.Context: getsOverlay :: Context -> (OverlayState -> a) -> IO a
- NanoUI.Context: hasCustomLayoutInputs :: Context -> IO Bool
- NanoUI.Context: initialAnimationState :: AnimationState
- NanoUI.Context: initialDamageState :: DamageState
- NanoUI.Context: initialDrawingCacheState :: DrawingCacheState
- NanoUI.Context: initialInteractionState :: InteractionState
- NanoUI.Context: initialOverlayState :: OverlayState
- NanoUI.Context: initialScrollState :: ScrollState
- NanoUI.Context: intBool :: Int -> Bool
- NanoUI.Context: intKey :: WidgetId -> Int
- NanoUI.Context: isDirty :: Context -> IO Bool
- NanoUI.Context: isDisabled :: Context -> WidgetId -> IO Bool
- NanoUI.Context: isSelectOpen :: WidgetStore -> Int -> Bool
- NanoUI.Context: linkScrollAxes :: Context -> WidgetId -> WidgetId -> IO ()
- NanoUI.Context: lookupAnimation :: Context -> WidgetId -> IO (Maybe Animation)
- NanoUI.Context: lookupCustomCursor :: Context -> WidgetId -> IO (Maybe (CustomDrawContext -> UiCursorKind))
- NanoUI.Context: lookupCustomDamageSlop :: Context -> WidgetId -> IO (Maybe Float)
- NanoUI.Context: lookupCustomDrawing :: Context -> WidgetId -> IO (Maybe CustomDrawingEntry)
- NanoUI.Context: lookupCustomMeasure :: Context -> WidgetId -> IO (Maybe CustomMeasureFn)
- NanoUI.Context: lookupDrawFitEnvelope :: Context -> WidgetId -> Float -> Int -> Layout -> IO (Maybe (Double, Double))
- NanoUI.Context: lookupDrawing :: Context -> WidgetId -> IO (Maybe DrawingEntry)
- NanoUI.Context: lookupImageUv :: Context -> ImageId -> IO (Maybe (Float, Float, Float, Float))
- NanoUI.Context: lookupPopupConfig :: Context -> WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))
- NanoUI.Context: markDirty :: Context -> IO ()
- NanoUI.Context: markEscapeConsumed :: Context -> IO ()
- NanoUI.Context: modalActive :: Context -> IO Bool
- NanoUI.Context: modalDamageFlip :: Context -> IO Bool
- NanoUI.Context: modifyDamage :: Context -> (DamageState -> DamageState) -> IO ()
- NanoUI.Context: modifyInteraction :: Context -> (InteractionState -> InteractionState) -> IO ()
- NanoUI.Context: modifyOverlay :: Context -> (OverlayState -> OverlayState) -> IO ()
- NanoUI.Context: modifyStore :: Context -> (WidgetStore -> WidgetStore) -> IO ()
- NanoUI.Context: newContext :: IO Context
- NanoUI.Context: newPixelHostContext :: IO Context
- NanoUI.Context: newThemeScopes :: IO ThemeScopes
- NanoUI.Context: nodeTheme :: Context -> NodeIdx -> IO Theme
- NanoUI.Context: overlayConsumesQuit :: Context -> Input -> IO Bool
- NanoUI.Context: pointerBlockedByModal :: Context -> IO Bool
- NanoUI.Context: pointerBlockedByOverlay :: Context -> V2 -> IO Bool
- NanoUI.Context: presetBouncy :: SpringParams
- NanoUI.Context: presetSmooth :: SpringParams
- NanoUI.Context: presetStiff :: SpringParams
- NanoUI.Context: pruneAnimRest :: Context -> (Int -> Bool) -> IO ()
- NanoUI.Context: pruneDrawOpCache :: Context -> IO ()
- NanoUI.Context: pushMessage :: Context -> FrameMsg -> IO ()
- NanoUI.Context: pushThemeScope :: Context -> Bool -> Theme -> Theme -> IO Int
- NanoUI.Context: recordStoreFloat :: Context -> Int -> Float -> IO ()
- NanoUI.Context: recordStoreInt :: Context -> Int -> Int -> IO ()
- NanoUI.Context: recordStoreText :: Context -> Int -> Text -> IO ()
- NanoUI.Context: reduceMessages :: (Foldable f, Typeable msg) => (msg -> model -> model) -> model -> f FrameMsg -> model
- NanoUI.Context: reduceUpdates :: (Foldable f, Typeable model) => model -> f FrameMsg -> model
- NanoUI.Context: refreshCustomDrawingOps :: Context -> WidgetId -> Int -> Rect -> CustomDrawContext -> CustomDrawBuild -> IO Bool
- NanoUI.Context: registerCustomCursor :: Context -> WidgetId -> (CustomDrawContext -> UiCursorKind) -> IO ()
- NanoUI.Context: registerCustomDamageSlop :: Context -> WidgetId -> Float -> IO ()
- NanoUI.Context: registerCustomDrawing :: Context -> WidgetId -> Int -> CustomDrawBuild -> IO ()
- NanoUI.Context: registerCustomMeasure :: Context -> WidgetId -> CustomMeasureFn -> IO ()
- NanoUI.Context: registerDrawing :: Context -> WidgetId -> Int -> DrawingBuild -> IO ()
- NanoUI.Context: registerFocusable :: Context -> WidgetId -> IO ()
- NanoUI.Context: registerImage :: Context -> ImageId -> Int -> Int -> ByteString -> IO Bool
- NanoUI.Context: registerImages :: Foldable f => Context -> f (ImageId, Int, Int, ByteString) -> IO Bool
- NanoUI.Context: registerPopupConfig :: Context -> WidgetId -> PopupAnchor -> PopupPlacement -> Float -> IO ()
- NanoUI.Context: requestDamage :: Context -> DamageRequest -> IO ()
- NanoUI.Context: resetDrawingScopeCache :: Context -> IO ()
- NanoUI.Context: resolveScrollStep :: Context -> WidgetId -> IO Float
- NanoUI.Context: scopeRawTheme :: Context -> Int -> IO Theme
- NanoUI.Context: scopeTheme :: Context -> Int -> IO Theme
- NanoUI.Context: scrollBy :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
- NanoUI.Context: scrollGliding :: Context -> WidgetId -> IO Bool
- NanoUI.Context: scrollIntoView :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()
- NanoUI.Context: scrollPages :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
- NanoUI.Context: scrollRectIntoView :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()
- NanoUI.Context: scrollTargetOffset :: Context -> WidgetId -> V2 -> IO V2
- NanoUI.Context: scrollTo :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
- NanoUI.Context: scrollToEnd :: Context -> WidgetId -> ScrollBehavior -> IO ()
- NanoUI.Context: scrollToStart :: Context -> WidgetId -> ScrollBehavior -> IO ()
- NanoUI.Context: seedFloatingPanel :: Context -> WidgetId -> Rect -> IO ()
- NanoUI.Context: setAnimRectless :: Context -> IntMap Int -> IO ()
- NanoUI.Context: setAnimationValue :: Context -> WidgetId -> Float -> IO ()
- NanoUI.Context: setDrawExternalText :: Context -> Bool -> IO ()
- NanoUI.Context: setDrawSnapScale :: Context -> Float -> IO ()
- NanoUI.Context: setDrawSquareGeometry :: Context -> Bool -> IO ()
- NanoUI.Context: setHost :: Typeable a => Context -> a -> IO ()
- NanoUI.Context: setMenuPointerGesture :: Context -> Bool -> IO ()
- NanoUI.Context: setScrollConfig :: Context -> WidgetId -> ScrollConfig -> IO ()
- NanoUI.Context: setScrollOffset :: Context -> WidgetId -> Float -> IO ()
- NanoUI.Context: setScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()
- NanoUI.Context: setScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> V2 -> IO ()
- NanoUI.Context: setScrollStep :: Context -> WidgetId -> Float -> IO ()
- NanoUI.Context: setScrollTuning :: Context -> ScrollTuning -> IO ()
- NanoUI.Context: setSelectOpen :: WidgetStore -> Int -> Bool -> WidgetStore
- NanoUI.Context: setStore :: Context -> WidgetStore -> IO ()
- NanoUI.Context: setTextInputDrag :: Context -> Maybe TextInputDrag -> IO ()
- NanoUI.Context: setTextInputMenu :: Context -> Maybe TextInputMenu -> IO ()
- NanoUI.Context: setTheme :: Context -> Theme -> IO ()
- NanoUI.Context: setWakeLoop :: Context -> IO () -> IO ()
- NanoUI.Context: slotKey :: Slot -> Int -> Int
- NanoUI.Context: startAnimation :: Context -> WidgetId -> Float -> Float -> Float -> IO ()
- NanoUI.Context: startAnimationEase :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> IO ()
- NanoUI.Context: startAnimationEaseDelay :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> Float -> IO ()
- NanoUI.Context: startSpring :: Context -> WidgetId -> SpringParams -> Float -> IO ()
- NanoUI.Context: stepScrollGlides :: Context -> Float -> IO ()
- NanoUI.Context: takeAnimSettled :: Context -> IO Bool
- NanoUI.Context: takeDamage :: Context -> IO Damage
- NanoUI.Context: takeTextEditLastAction :: Context -> IO (Maybe (WidgetId, TextCommand))
- NanoUI.Context: textInputEditActive :: Context -> IO Bool
- NanoUI.Context: themeScopesChanged :: Context -> IO Bool
- NanoUI.Context: tickAnimations :: Context -> Float -> IO ()
- NanoUI.Context: type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp
- NanoUI.Context: type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)
- NanoUI.Context: type MeasureCacheKey = (Text, Float)
- NanoUI.Context: widgetTheme :: Context -> WidgetId -> IO Theme
- NanoUI.Context: withClipboard :: Context -> IO (Maybe Text) -> (Text -> IO Bool) -> Context
- NanoUI.Context: withExternalText :: Context -> Bool -> Context
- NanoUI.Context: withFontMetrics :: Context -> FontMetrics -> Context
- NanoUI.Context: withFontResolver :: Context -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Context
- NanoUI.Context: withMeasureText :: Context -> (Text -> IO (Float, Float)) -> Context
- NanoUI.Context: withMonoFontMetrics :: Context -> FontMetrics -> Context
- NanoUI.Context: withTheme :: Context -> Theme -> IO Context
- NanoUI.Context: wrapMeasureCache :: Float -> Context -> (Text -> IO (Float, Float)) -> Context
- NanoUI.Context: writeStoreBool :: Context -> WidgetId -> Bool -> IO ()
- NanoUI.Context: writeStoreFloat :: Context -> WidgetId -> Int -> Float -> IO ()
- NanoUI.Context: writeStoreInt :: Context -> WidgetId -> Int -> Int -> IO ()
- NanoUI.Context.Types: AnimationState :: IntMap Animation -> IntMap Float -> Bool -> Bool -> IntMap Int -> AnimationState
- NanoUI.Context.Types: Context :: NodeArena -> DrawArena -> IORef WidgetId -> IORef WidgetId -> IORef WidgetId -> IORef WidgetId -> IORef WidgetId -> IORef (Maybe V2) -> IORef (Maybe V2) -> IORef WidgetId -> IORef Bool -> IORef WidgetStore -> IORef DamageState -> IORef OverlayState -> IORef AnimationState -> IORef ScrollState -> IORef DrawingCacheState -> IORef IdContext -> FontMetrics -> FontMetrics -> (Text -> IO (Float, Float)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Maybe (IORef (HashMap MeasureCacheKey (Float, Float))) -> IORef (IntMap SpanCacheEntry) -> IORef (IntMap WidgetTextCacheEntry) -> IORef (Maybe (LayoutCache, Size, Int)) -> IORef Int -> MetricSource -> IORef (Maybe MetricSource) -> IORef Bool -> Bool -> IORef Theme -> IORef ThemeScopes -> IORef [Int] -> IORef [FrameMsg] -> IORef (MutablePrimArray RealWorld WidgetId) -> IORef Int -> SpanArena -> SpanArena -> IORef InteractionState -> IO (Maybe Text) -> (Text -> IO Bool) -> ImageAtlas -> IORef (Maybe (IO ())) -> IORef (Map TypeRep Dynamic) -> IORef Layout -> Context
- NanoUI.Context.Types: CustomDrawContext :: Bool -> Bool -> Bool -> Bool -> Bool -> Theme -> FontMetrics -> CustomDrawContext
- NanoUI.Context.Types: CustomDrawOpCacheEntry :: Int -> Rect -> Bool -> Bool -> Bool -> Bool -> Int -> SmallArray DrawOp -> CustomDrawOpCacheEntry
- NanoUI.Context.Types: CustomDrawingEntry :: Int -> CustomDrawBuild -> CustomDrawingEntry
- NanoUI.Context.Types: DamageState :: Bool -> Damage -> [DamageRequest] -> Size -> IntMap Rect -> IntMap Rect -> IntMap Text -> DamageState
- NanoUI.Context.Types: DrawFitCache :: Double -> Double -> Float -> Int -> Layout -> Layout -> DrawFitCache
- NanoUI.Context.Types: DrawOpCacheEntry :: Int -> Rect -> SmallArray DrawOp -> DrawOpCacheEntry
- NanoUI.Context.Types: DrawingCacheState :: IntMap PopupConfig -> IntMap DrawingEntry -> IntMap CustomDrawingEntry -> IntMap CustomMeasureFn -> IntMap (CustomDrawContext -> UiCursorKind) -> IntMap Float -> IntMap DrawOpCacheEntry -> IntMap CustomDrawOpCacheEntry -> IntMap DrawFitCache -> DrawingCacheState
- NanoUI.Context.Types: DrawingEntry :: Int -> DrawingBuild -> DrawingEntry
- NanoUI.Context.Types: InitialMetricSource :: MetricSource
- NanoUI.Context.Types: InteractionState :: Maybe (WidgetId, DirTag, Float) -> Maybe TextInputDrag -> Maybe TextFieldClickCell -> Maybe TextInputMenu -> Maybe (WidgetId, TextCommand) -> Bool -> Maybe (WidgetId, Rect) -> Bool -> Maybe (WidgetId, Float, Float) -> Maybe WindowResizeDrag -> InteractionState
- NanoUI.Context.Types: MetricSource :: FontMetrics -> FontMetrics -> (Text -> IO (Float, Float)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> MetricSource
- NanoUI.Context.Types: OverlayState :: Bool -> Bool -> Int -> Bool -> IntMap Rect -> [Int] -> Maybe (V2, Maybe WidgetId) -> Maybe WidgetId -> Bool -> OverlayState
- NanoUI.Context.Types: PopupConfig :: PopupAnchor -> PopupPlacement -> Float -> PopupConfig
- NanoUI.Context.Types: ReqFull :: DamageRequest
- NanoUI.Context.Types: ReqKey :: Int -> DamageBounds -> DamageRequest
- NanoUI.Context.Types: ReqPeers :: [WidgetId] -> DamageBounds -> DamageRequest
- NanoUI.Context.Types: ReqRect :: Rect -> DamageRequest
- NanoUI.Context.Types: ReqWidget :: WidgetId -> DamageBounds -> DamageRequest
- NanoUI.Context.Types: ResizeE :: WindowResizeEdge
- NanoUI.Context.Types: ResizeN :: WindowResizeEdge
- NanoUI.Context.Types: ResizeNE :: WindowResizeEdge
- NanoUI.Context.Types: ResizeNW :: WindowResizeEdge
- NanoUI.Context.Types: ResizeS :: WindowResizeEdge
- NanoUI.Context.Types: ResizeSE :: WindowResizeEdge
- NanoUI.Context.Types: ResizeSW :: WindowResizeEdge
- NanoUI.Context.Types: ResizeW :: WindowResizeEdge
- NanoUI.Context.Types: ScrollAxisX :: ScrollAxes
- NanoUI.Context.Types: ScrollAxisXY :: ScrollAxes
- NanoUI.Context.Types: ScrollAxisY :: ScrollAxes
- NanoUI.Context.Types: ScrollGlide :: WidgetId -> V2 -> ScrollAxes -> ScrollGlide
- NanoUI.Context.Types: ScrollState :: ScrollTuning -> IntMap ScrollGlide -> IntSet -> ScrollState
- NanoUI.Context.Types: ScrollTuning :: Float -> Float -> ScrollTuning
- NanoUI.Context.Types: SpanCacheEntry :: Text -> Color -> Color -> Int -> Float -> Int -> Int -> Rect -> Float -> Bool -> [(Rect, Text, Color, Color)] -> SpanCacheEntry
- NanoUI.Context.Types: TextFieldClickCell :: WidgetId -> Int -> Int -> Int -> Bool -> TextFieldClickCell
- NanoUI.Context.Types: TextInputDrag :: WidgetId -> Int -> Int -> Int -> Bool -> Int -> TextInputDrag
- NanoUI.Context.Types: TextInputMenu :: WidgetId -> Rect -> TextInputMenu
- NanoUI.Context.Types: ThemeScopes :: Int -> SmallMutableArray RealWorld Theme -> SmallMutableArray RealWorld Theme -> Int -> SmallMutableArray RealWorld Theme -> SmallMutableArray RealWorld Theme -> Bool -> Bool -> Word64 -> ThemeScopes
- NanoUI.Context.Types: WidgetTextCacheEntry :: Int -> Int -> Float -> Text -> Float -> Float -> Int -> Maybe WidgetTextPlacement -> WidgetTextCacheEntry
- NanoUI.Context.Types: WidgetTextPlacement :: Text -> Float -> Float -> Float -> Float -> WidgetTextPlacement
- NanoUI.Context.Types: WindowResizeDrag :: WidgetId -> WindowResizeEdge -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> WindowResizeDrag
- NanoUI.Context.Types: [FrameMsg] :: forall a. Typeable a => a -> FrameMsg
- NanoUI.Context.Types: [asAnimRest] :: AnimationState -> IntMap Float
- NanoUI.Context.Types: [asAnimSettled] :: AnimationState -> Bool
- NanoUI.Context.Types: [asAnimations] :: AnimationState -> IntMap Animation
- NanoUI.Context.Types: [asAnyAnimating] :: AnimationState -> Bool
- NanoUI.Context.Types: [asRectless] :: AnimationState -> IntMap Int
- NanoUI.Context.Types: [cdcActive] :: CustomDrawContext -> Bool
- NanoUI.Context.Types: [cdcDisabled] :: CustomDrawContext -> Bool
- NanoUI.Context.Types: [cdcFocused] :: CustomDrawContext -> Bool
- NanoUI.Context.Types: [cdcFont] :: CustomDrawContext -> FontMetrics
- NanoUI.Context.Types: [cdcHovered] :: CustomDrawContext -> Bool
- NanoUI.Context.Types: [cdcPressed] :: CustomDrawContext -> Bool
- NanoUI.Context.Types: [cdcTheme] :: CustomDrawContext -> Theme
- NanoUI.Context.Types: [cdeBounds] :: CustomDrawOpCacheEntry -> Rect
- NanoUI.Context.Types: [cdeContent] :: CustomDrawOpCacheEntry -> Int
- NanoUI.Context.Types: [cdeDisabled] :: CustomDrawOpCacheEntry -> Bool
- NanoUI.Context.Types: [cdeFocused] :: CustomDrawOpCacheEntry -> Bool
- NanoUI.Context.Types: [cdeGen] :: CustomDrawOpCacheEntry -> Int
- NanoUI.Context.Types: [cdeHovered] :: CustomDrawOpCacheEntry -> Bool
- NanoUI.Context.Types: [cdeOps] :: CustomDrawOpCacheEntry -> SmallArray DrawOp
- NanoUI.Context.Types: [cdePressed] :: CustomDrawOpCacheEntry -> Bool
- NanoUI.Context.Types: [cdrBuild] :: CustomDrawingEntry -> CustomDrawBuild
- NanoUI.Context.Types: [cdrContent] :: CustomDrawingEntry -> Int
- NanoUI.Context.Types: [ctxActiveId] :: Context -> IORef WidgetId
- NanoUI.Context.Types: [ctxAnimationState] :: Context -> IORef AnimationState
- NanoUI.Context.Types: [ctxClickedId] :: Context -> IORef WidgetId
- NanoUI.Context.Types: [ctxClipboardGet] :: Context -> IO (Maybe Text)
- NanoUI.Context.Types: [ctxClipboardSet] :: Context -> Text -> IO Bool
- NanoUI.Context.Types: [ctxContainerStack] :: Context -> IORef [Int]
- NanoUI.Context.Types: [ctxDamageState] :: Context -> IORef DamageState
- NanoUI.Context.Types: [ctxDefaultLayout] :: Context -> IORef Layout
- NanoUI.Context.Types: [ctxDrawArena] :: Context -> DrawArena
- NanoUI.Context.Types: [ctxDrawingCache] :: Context -> IORef DrawingCacheState
- NanoUI.Context.Types: [ctxExternalText] :: Context -> Bool
- NanoUI.Context.Types: [ctxFocusId] :: Context -> IORef WidgetId
- NanoUI.Context.Types: [ctxFocusVisible] :: Context -> IORef Bool
- NanoUI.Context.Types: [ctxFocusablesCount] :: Context -> IORef Int
- NanoUI.Context.Types: [ctxFocusables] :: Context -> IORef (MutablePrimArray RealWorld WidgetId)
- NanoUI.Context.Types: [ctxFontMetrics] :: Context -> FontMetrics
- NanoUI.Context.Types: [ctxHost] :: Context -> IORef (Map TypeRep Dynamic)
- NanoUI.Context.Types: [ctxHotId] :: Context -> IORef WidgetId
- NanoUI.Context.Types: [ctxIdContext] :: Context -> IORef IdContext
- NanoUI.Context.Types: [ctxImageAtlas] :: Context -> ImageAtlas
- NanoUI.Context.Types: [ctxInteractionState] :: Context -> IORef InteractionState
- NanoUI.Context.Types: [ctxLastHotId] :: Context -> IORef WidgetId
- NanoUI.Context.Types: [ctxLastMetricSource] :: Context -> IORef (Maybe MetricSource)
- NanoUI.Context.Types: [ctxLayoutCache] :: Context -> IORef (Maybe (LayoutCache, Size, Int))
- NanoUI.Context.Types: [ctxMeasureCache] :: Context -> Maybe (IORef (HashMap MeasureCacheKey (Float, Float)))
- NanoUI.Context.Types: [ctxMeasureText] :: Context -> Text -> IO (Float, Float)
- NanoUI.Context.Types: [ctxMessages] :: Context -> IORef [FrameMsg]
- NanoUI.Context.Types: [ctxMetricGen] :: Context -> IORef Int
- NanoUI.Context.Types: [ctxMetricSource] :: Context -> MetricSource
- NanoUI.Context.Types: [ctxMonoFontMetrics] :: Context -> FontMetrics
- NanoUI.Context.Types: [ctxNodeArena] :: Context -> NodeArena
- NanoUI.Context.Types: [ctxOverlayState] :: Context -> IORef OverlayState
- NanoUI.Context.Types: [ctxPaintFull] :: Context -> IORef Bool
- NanoUI.Context.Types: [ctxPressPos] :: Context -> IORef (Maybe V2)
- NanoUI.Context.Types: [ctxReleaseClickedId] :: Context -> IORef WidgetId
- NanoUI.Context.Types: [ctxResolveFont] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)
- NanoUI.Context.Types: [ctxResolveMeasure] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)
- NanoUI.Context.Types: [ctxRightPressPos] :: Context -> IORef (Maybe V2)
- NanoUI.Context.Types: [ctxScrollState] :: Context -> IORef ScrollState
- NanoUI.Context.Types: [ctxSpanBase] :: Context -> SpanArena
- NanoUI.Context.Types: [ctxSpanCache] :: Context -> IORef (IntMap SpanCacheEntry)
- NanoUI.Context.Types: [ctxSpanOverlay] :: Context -> SpanArena
- NanoUI.Context.Types: [ctxStore] :: Context -> IORef WidgetStore
- NanoUI.Context.Types: [ctxThemeScopes] :: Context -> IORef ThemeScopes
- NanoUI.Context.Types: [ctxTheme] :: Context -> IORef Theme
- NanoUI.Context.Types: [ctxWakeLoop] :: Context -> IORef (Maybe (IO ()))
- NanoUI.Context.Types: [ctxWidgetTextCache] :: Context -> IORef (IntMap WidgetTextCacheEntry)
- NanoUI.Context.Types: [dcsCustomCursors] :: DrawingCacheState -> IntMap (CustomDrawContext -> UiCursorKind)
- NanoUI.Context.Types: [dcsCustomDamageSlop] :: DrawingCacheState -> IntMap Float
- NanoUI.Context.Types: [dcsCustomDrawOpCache] :: DrawingCacheState -> IntMap CustomDrawOpCacheEntry
- NanoUI.Context.Types: [dcsCustomDrawings] :: DrawingCacheState -> IntMap CustomDrawingEntry
- NanoUI.Context.Types: [dcsCustomMeasures] :: DrawingCacheState -> IntMap CustomMeasureFn
- NanoUI.Context.Types: [dcsDrawFitCache] :: DrawingCacheState -> IntMap DrawFitCache
- NanoUI.Context.Types: [dcsDrawOpCache] :: DrawingCacheState -> IntMap DrawOpCacheEntry
- NanoUI.Context.Types: [dcsDrawings] :: DrawingCacheState -> IntMap DrawingEntry
- NanoUI.Context.Types: [dcsPopupConfigs] :: DrawingCacheState -> IntMap PopupConfig
- NanoUI.Context.Types: [deBuild] :: DrawingEntry -> DrawingBuild
- NanoUI.Context.Types: [deContent] :: DrawingEntry -> Int
- NanoUI.Context.Types: [dfcContent] :: DrawFitCache -> Int
- NanoUI.Context.Types: [dfcDh] :: DrawFitCache -> Double
- NanoUI.Context.Types: [dfcDw] :: DrawFitCache -> Double
- NanoUI.Context.Types: [dfcIn] :: DrawFitCache -> Layout
- NanoUI.Context.Types: [dfcLh] :: DrawFitCache -> Float
- NanoUI.Context.Types: [dfcOut] :: DrawFitCache -> Layout
- NanoUI.Context.Types: [doeBounds] :: DrawOpCacheEntry -> Rect
- NanoUI.Context.Types: [doeContent] :: DrawOpCacheEntry -> Int
- NanoUI.Context.Types: [doeOps] :: DrawOpCacheEntry -> SmallArray DrawOp
- NanoUI.Context.Types: [dsDamage] :: DamageState -> Damage
- NanoUI.Context.Types: [dsDirty] :: DamageState -> Bool
- NanoUI.Context.Types: [dsLastWindowSize] :: DamageState -> Size
- NanoUI.Context.Types: [dsPrevClips] :: DamageState -> IntMap Rect
- NanoUI.Context.Types: [dsPrevNodeTexts] :: DamageState -> IntMap Text
- NanoUI.Context.Types: [dsPrevRects] :: DamageState -> IntMap Rect
- NanoUI.Context.Types: [dsRequests] :: DamageState -> [DamageRequest]
- NanoUI.Context.Types: [isMenuPointerGesture] :: InteractionState -> Bool
- NanoUI.Context.Types: [isOpenSelectDrop] :: InteractionState -> Maybe (WidgetId, Rect)
- NanoUI.Context.Types: [isScrollDrag] :: InteractionState -> Maybe (WidgetId, DirTag, Float)
- NanoUI.Context.Types: [isSelectDropPress] :: InteractionState -> Bool
- NanoUI.Context.Types: [isTextEditLastAction] :: InteractionState -> Maybe (WidgetId, TextCommand)
- NanoUI.Context.Types: [isTextFieldClickCell] :: InteractionState -> Maybe TextFieldClickCell
- NanoUI.Context.Types: [isTextInputDrag] :: InteractionState -> Maybe TextInputDrag
- NanoUI.Context.Types: [isTextInputMenu] :: InteractionState -> Maybe TextInputMenu
- NanoUI.Context.Types: [isWindowDrag] :: InteractionState -> Maybe (WidgetId, Float, Float)
- NanoUI.Context.Types: [isWindowResize] :: InteractionState -> Maybe WindowResizeDrag
- NanoUI.Context.Types: [osCurrentFloatingId] :: OverlayState -> Maybe WidgetId
- NanoUI.Context.Types: [osEscapeConsumed] :: OverlayState -> Bool
- NanoUI.Context.Types: [osLastPointerBlocked] :: OverlayState -> Bool
- NanoUI.Context.Types: [osModalActive] :: OverlayState -> Bool
- NanoUI.Context.Types: [osModalDepth] :: OverlayState -> Int
- NanoUI.Context.Types: [osModalWasActive] :: OverlayState -> Bool
- NanoUI.Context.Types: [osPrevFloatingOrder] :: OverlayState -> [Int]
- NanoUI.Context.Types: [osPrevFloatingRects] :: OverlayState -> IntMap Rect
- NanoUI.Context.Types: [osTopmostCache] :: OverlayState -> Maybe (V2, Maybe WidgetId)
- NanoUI.Context.Types: [pcAnchor] :: PopupConfig -> PopupAnchor
- NanoUI.Context.Types: [pcOffset] :: PopupConfig -> Float
- NanoUI.Context.Types: [pcPlacement] :: PopupConfig -> PopupPlacement
- NanoUI.Context.Types: [sceAlign] :: SpanCacheEntry -> Int
- NanoUI.Context.Types: [sceBg] :: SpanCacheEntry -> Color
- NanoUI.Context.Types: [sceEffMaxW] :: SpanCacheEntry -> Float
- NanoUI.Context.Types: [sceFg] :: SpanCacheEntry -> Color
- NanoUI.Context.Types: [sceFontSize] :: SpanCacheEntry -> Float
- NanoUI.Context.Types: [sceRect] :: SpanCacheEntry -> Rect
- NanoUI.Context.Types: [sceRowChild] :: SpanCacheEntry -> Bool
- NanoUI.Context.Types: [sceSpans] :: SpanCacheEntry -> [(Rect, Text, Color, Color)]
- NanoUI.Context.Types: [sceStyle] :: SpanCacheEntry -> Int
- NanoUI.Context.Types: [sceText] :: SpanCacheEntry -> Text
- NanoUI.Context.Types: [sceWidthTag] :: SpanCacheEntry -> Int
- NanoUI.Context.Types: [scrollSmoothTime] :: ScrollTuning -> Float
- NanoUI.Context.Types: [scrollWheelStep] :: ScrollTuning -> Float
- NanoUI.Context.Types: [sgAxes] :: ScrollGlide -> ScrollAxes
- NanoUI.Context.Types: [sgTarget] :: ScrollGlide -> V2
- NanoUI.Context.Types: [sgWidget] :: ScrollGlide -> WidgetId
- NanoUI.Context.Types: [ssCached] :: ScrollState -> IntSet
- NanoUI.Context.Types: [ssGlides] :: ScrollState -> IntMap ScrollGlide
- NanoUI.Context.Types: [ssTuning] :: ScrollState -> ScrollTuning
- NanoUI.Context.Types: [textFieldClickCol] :: TextFieldClickCell -> Int
- NanoUI.Context.Types: [textFieldClickFlat] :: TextFieldClickCell -> Int
- NanoUI.Context.Types: [textFieldClickMultiline] :: TextFieldClickCell -> Bool
- NanoUI.Context.Types: [textFieldClickRow] :: TextFieldClickCell -> Int
- NanoUI.Context.Types: [textFieldClickWidget] :: TextFieldClickCell -> WidgetId
- NanoUI.Context.Types: [textInputDragAnchorCol] :: TextInputDrag -> Int
- NanoUI.Context.Types: [textInputDragAnchorRow] :: TextInputDrag -> Int
- NanoUI.Context.Types: [textInputDragAnchor] :: TextInputDrag -> Int
- NanoUI.Context.Types: [textInputDragClicks] :: TextInputDrag -> Int
- NanoUI.Context.Types: [textInputDragMultiline] :: TextInputDrag -> Bool
- NanoUI.Context.Types: [textInputDragWidget] :: TextInputDrag -> WidgetId
- NanoUI.Context.Types: [textInputMenuRect] :: TextInputMenu -> Rect
- NanoUI.Context.Types: [textInputMenuWidget] :: TextInputMenu -> WidgetId
- NanoUI.Context.Types: [tsChanged] :: ThemeScopes -> Bool
- NanoUI.Context.Types: [tsCount] :: ThemeScopes -> Int
- NanoUI.Context.Types: [tsDisabled] :: ThemeScopes -> Bool
- NanoUI.Context.Types: [tsPrevCount] :: ThemeScopes -> Int
- NanoUI.Context.Types: [tsPrevRaw] :: ThemeScopes -> SmallMutableArray RealWorld Theme
- NanoUI.Context.Types: [tsPrevSig] :: ThemeScopes -> Word64
- NanoUI.Context.Types: [tsPrev] :: ThemeScopes -> SmallMutableArray RealWorld Theme
- NanoUI.Context.Types: [tsRaw] :: ThemeScopes -> SmallMutableArray RealWorld Theme
- NanoUI.Context.Types: [tsThemes] :: ThemeScopes -> SmallMutableArray RealWorld Theme
- NanoUI.Context.Types: [wrdEdge] :: WindowResizeDrag -> WindowResizeEdge
- NanoUI.Context.Types: [wrdGrabX] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdGrabY] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdMaxH] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdMaxW] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdMinH] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdMinW] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdStartH] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdStartW] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdStartX] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdStartY] :: WindowResizeDrag -> Float
- NanoUI.Context.Types: [wrdWidget] :: WindowResizeDrag -> WidgetId
- NanoUI.Context.Types: [wtcAlign] :: WidgetTextCacheEntry -> Int
- NanoUI.Context.Types: [wtcFontSize] :: WidgetTextCacheEntry -> Float
- NanoUI.Context.Types: [wtcHeight] :: WidgetTextCacheEntry -> Float
- NanoUI.Context.Types: [wtcNodeType] :: WidgetTextCacheEntry -> Int
- NanoUI.Context.Types: [wtcPlacement] :: WidgetTextCacheEntry -> Maybe WidgetTextPlacement
- NanoUI.Context.Types: [wtcStyle] :: WidgetTextCacheEntry -> Int
- NanoUI.Context.Types: [wtcText] :: WidgetTextCacheEntry -> Text
- NanoUI.Context.Types: [wtcWidth] :: WidgetTextCacheEntry -> Float
- NanoUI.Context.Types: data AnimationState
- NanoUI.Context.Types: data Context
- NanoUI.Context.Types: data CustomDrawContext
- NanoUI.Context.Types: data CustomDrawOpCacheEntry
- NanoUI.Context.Types: data CustomDrawingEntry
- NanoUI.Context.Types: data DamageRequest
- NanoUI.Context.Types: data DamageState
- NanoUI.Context.Types: data DrawFitCache
- NanoUI.Context.Types: data DrawOpCacheEntry
- NanoUI.Context.Types: data DrawingCacheState
- NanoUI.Context.Types: data DrawingEntry
- NanoUI.Context.Types: data FrameMsg
- NanoUI.Context.Types: data InteractionState
- NanoUI.Context.Types: data MetricSource
- NanoUI.Context.Types: data OverlayState
- NanoUI.Context.Types: data PopupConfig
- NanoUI.Context.Types: data ScrollAxes
- NanoUI.Context.Types: data ScrollGlide
- NanoUI.Context.Types: data ScrollState
- NanoUI.Context.Types: data ScrollTuning
- NanoUI.Context.Types: data SpanCacheEntry
- NanoUI.Context.Types: data TextFieldClickCell
- NanoUI.Context.Types: data TextInputDrag
- NanoUI.Context.Types: data TextInputMenu
- NanoUI.Context.Types: data ThemeScopes
- NanoUI.Context.Types: data WidgetTextCacheEntry
- NanoUI.Context.Types: data WidgetTextPlacement
- NanoUI.Context.Types: data WindowResizeDrag
- NanoUI.Context.Types: data WindowResizeEdge
- NanoUI.Context.Types: decodeMessages :: (Foldable f, Typeable a) => f FrameMsg -> [a]
- NanoUI.Context.Types: defaultScrollTuning :: ScrollTuning
- NanoUI.Context.Types: initialAnimationState :: AnimationState
- NanoUI.Context.Types: initialDamageState :: DamageState
- NanoUI.Context.Types: initialDrawingCacheState :: DrawingCacheState
- NanoUI.Context.Types: initialInteractionState :: InteractionState
- NanoUI.Context.Types: initialOverlayState :: OverlayState
- NanoUI.Context.Types: initialScrollState :: ScrollState
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.DamageRequest
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.InteractionState
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.ScrollAxes
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.ScrollGlide
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.ScrollTuning
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.TextFieldClickCell
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.TextInputDrag
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.TextInputMenu
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.WindowResizeDrag
- NanoUI.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Context.Types.WindowResizeEdge
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.DamageRequest
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.InteractionState
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.ScrollAxes
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.ScrollGlide
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.ScrollTuning
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.TextFieldClickCell
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.TextInputDrag
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.TextInputMenu
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.WindowResizeDrag
- NanoUI.Context.Types: instance GHC.Internal.Show.Show NanoUI.Context.Types.WindowResizeEdge
- NanoUI.Context.Types: intKey :: WidgetId -> Int
- NanoUI.Context.Types: reduceMessages :: (Foldable f, Typeable msg) => (msg -> model -> model) -> model -> f FrameMsg -> model
- NanoUI.Context.Types: reduceUpdates :: (Foldable f, Typeable model) => model -> f FrameMsg -> model
- NanoUI.Context.Types: type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp
- NanoUI.Context.Types: type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)
- NanoUI.Context.Types: type MeasureCacheKey = (Text, Float)
- NanoUI.Debug: CoreDebugSnapshot :: Double -> Double -> Double -> Double -> Double -> Double -> Word64 -> Word64 -> Int -> Int -> Int -> Float -> Float -> Float -> Float -> RtsStatsSnapshot -> CoreDebugSnapshot
- NanoUI.Debug: DebugSampler :: Double -> Double -> Double -> Double -> Double -> Word64 -> Word64 -> Double -> Double -> Double -> Double -> Int -> Int -> Int -> Word64 -> Double -> DebugSampler
- NanoUI.Debug: RtsStatsSnapshot :: Bool -> Word32 -> Word32 -> Double -> Double -> Double -> Double -> Double -> Word32 -> Double -> Int -> Int -> RtsStatsSnapshot
- NanoUI.Debug: [dbgCmds] :: CoreDebugSnapshot -> Int
- NanoUI.Debug: [dbgFrameMs] :: CoreDebugSnapshot -> Double
- NanoUI.Debug: [dbgIndices] :: CoreDebugSnapshot -> Int
- NanoUI.Debug: [dbgLoopFps] :: CoreDebugSnapshot -> Double
- NanoUI.Debug: [dbgMouseX] :: CoreDebugSnapshot -> Float
- NanoUI.Debug: [dbgMouseY] :: CoreDebugSnapshot -> Float
- NanoUI.Debug: [dbgPresentFps] :: CoreDebugSnapshot -> Double
- NanoUI.Debug: [dbgPresentMs] :: CoreDebugSnapshot -> Double
- NanoUI.Debug: [dbgPresents] :: CoreDebugSnapshot -> Word64
- NanoUI.Debug: [dbgRenderMs] :: CoreDebugSnapshot -> Double
- NanoUI.Debug: [dbgRts] :: CoreDebugSnapshot -> RtsStatsSnapshot
- NanoUI.Debug: [dbgSkips] :: CoreDebugSnapshot -> Word64
- NanoUI.Debug: [dbgUiMs] :: CoreDebugSnapshot -> Double
- NanoUI.Debug: [dbgVerts] :: CoreDebugSnapshot -> Int
- NanoUI.Debug: [dbgWinH] :: CoreDebugSnapshot -> Float
- NanoUI.Debug: [dbgWinW] :: CoreDebugSnapshot -> Float
- NanoUI.Debug: [rtsAllocMb] :: RtsStatsSnapshot -> Double
- NanoUI.Debug: [rtsCaps] :: RtsStatsSnapshot -> Int
- NanoUI.Debug: [rtsCopiedMb] :: RtsStatsSnapshot -> Double
- NanoUI.Debug: [rtsCpus] :: RtsStatsSnapshot -> Int
- NanoUI.Debug: [rtsEnabled] :: RtsStatsSnapshot -> Bool
- NanoUI.Debug: [rtsGcPct] :: RtsStatsSnapshot -> Double
- NanoUI.Debug: [rtsGcs] :: RtsStatsSnapshot -> Word32
- NanoUI.Debug: [rtsLastGcGen] :: RtsStatsSnapshot -> Word32
- NanoUI.Debug: [rtsLastGcMs] :: RtsStatsSnapshot -> Double
- NanoUI.Debug: [rtsLiveMb] :: RtsStatsSnapshot -> Double
- NanoUI.Debug: [rtsMajorGcs] :: RtsStatsSnapshot -> Word32
- NanoUI.Debug: [rtsMaxMemMb] :: RtsStatsSnapshot -> Double
- NanoUI.Debug: [smCmds] :: DebugSampler -> Int
- NanoUI.Debug: [smFrameMs] :: DebugSampler -> Double
- NanoUI.Debug: [smIndices] :: DebugSampler -> Int
- NanoUI.Debug: [smLastDebugT] :: DebugSampler -> Double
- NanoUI.Debug: [smLastPresentT] :: DebugSampler -> Double
- NanoUI.Debug: [smLastQueryT] :: DebugSampler -> Double
- NanoUI.Debug: [smLoopEma] :: DebugSampler -> Double
- NanoUI.Debug: [smPresentEma] :: DebugSampler -> Double
- NanoUI.Debug: [smPresentMs] :: DebugSampler -> Double
- NanoUI.Debug: [smPresents] :: DebugSampler -> Word64
- NanoUI.Debug: [smRatePresents] :: DebugSampler -> Word64
- NanoUI.Debug: [smRateT] :: DebugSampler -> Double
- NanoUI.Debug: [smRenderMs] :: DebugSampler -> Double
- NanoUI.Debug: [smSkips] :: DebugSampler -> Word64
- NanoUI.Debug: [smUiMs] :: DebugSampler -> Double
- NanoUI.Debug: [smVerts] :: DebugSampler -> Int
- NanoUI.Debug: blend :: Double -> Double -> Double
- NanoUI.Debug: data CoreDebugSnapshot
- NanoUI.Debug: data DebugSampler
- NanoUI.Debug: data RtsStatsSnapshot
- NanoUI.Debug: debugRefreshDue :: DebugSamplerRef -> IO Bool
- NanoUI.Debug: debugRefreshSec :: Double
- NanoUI.Debug: emptyCoreDebugSnapshot :: CoreDebugSnapshot
- NanoUI.Debug: formatCoreRtsRows :: CoreDebugSnapshot -> [(Text, Text)]
- NanoUI.Debug: formatDrawRows :: CoreDebugSnapshot -> [(Text, Text)]
- NanoUI.Debug: formatFpsRows :: CoreDebugSnapshot -> [(Text, Text)]
- NanoUI.Debug: instance GHC.Internal.Classes.Eq NanoUI.Debug.CoreDebugSnapshot
- NanoUI.Debug: instance GHC.Internal.Classes.Eq NanoUI.Debug.RtsStatsSnapshot
- NanoUI.Debug: instance GHC.Internal.Show.Show NanoUI.Debug.CoreDebugSnapshot
- NanoUI.Debug: instance GHC.Internal.Show.Show NanoUI.Debug.RtsStatsSnapshot
- NanoUI.Debug: isDebugActive :: DebugSamplerRef -> IO Bool
- NanoUI.Debug: newDebugSampler :: IO DebugSamplerRef
- NanoUI.Debug: noteDebugLoop :: DebugSamplerRef -> Float -> IO ()
- NanoUI.Debug: noteDebugPresent :: DebugSamplerRef -> Double -> Double -> Double -> Double -> Int -> Int -> Int -> IO ()
- NanoUI.Debug: noteDebugSkip :: DebugSamplerRef -> IO ()
- NanoUI.Debug: readRtsSnapshot :: IO RtsStatsSnapshot
- NanoUI.Debug: refreshDebugSnapshot :: DebugSamplerRef -> IORef s -> (CoreDebugSnapshot -> IO s) -> IO s
- NanoUI.Debug: type DebugSamplerRef = IORef DebugSampler
- NanoUI.Emit: button :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => Text -> msg -> Eff es ()
- NanoUI.Emit: checkbox :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => Text -> Bool -> (Bool -> msg) -> Eff es ()
- NanoUI.Emit: emit :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => msg -> Eff es ()
- NanoUI.Emit: radio :: forall f msg (es :: [Effect]). (Foldable f, Typeable msg, Ui :> es) => f Text -> Int -> (Int -> msg) -> Eff es ()
- NanoUI.Emit: select :: forall f msg (es :: [Effect]). (Foldable f, Typeable msg, Ui :> es) => f Text -> Int -> (Int -> msg) -> Eff es ()
- NanoUI.Emit: slider :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => Float -> Float -> Float -> (Float -> msg) -> Eff es ()
- NanoUI.Emit: tabs :: forall f a msg (es :: [Effect]). (Foldable f, Eq a, Typeable msg, Ui :> es) => a -> f (Tab a (Eff es ())) -> (a -> msg) -> Eff es ()
- NanoUI.Emit: textArea :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => Text -> (Text -> msg) -> Eff es ()
- NanoUI.Emit: textInput :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => Text -> (Text -> msg) -> Eff es ()
- NanoUI.Frame.Hit: findNodeByKey :: Context -> Int -> IO (Maybe NodeIdx)
- NanoUI.Frame.Hit: findNodeByWidgetId :: Context -> WidgetId -> IO (Maybe NodeIdx)
- NanoUI.Frame.Hit: modalTreeOpen :: Context -> IO Bool
- NanoUI.Frame.Hit: nodeClippedHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool
- NanoUI.Frame.Hit: nodeInSubtree :: Context -> NodeIdx -> NodeIdx -> IO Bool
- NanoUI.Frame.Hit: nodeInteractionHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool
- NanoUI.Frame.Hit: nodePointVisible :: Context -> NodeIdx -> V2 -> IO Bool
- NanoUI.Frame.Hit: overlayHitAllowed :: Context -> NodeIdx -> V2 -> IO Bool
- NanoUI.Frame.Hit: scrollHitRect :: Context -> WidgetId -> IO (Maybe Rect)
- NanoUI.Frame.Hit: topmostModalAtMouse :: Context -> V2 -> IO (Maybe NodeIdx)
- NanoUI.Frame.Hit: topmostOverlayAtMouse :: Context -> V2 -> IO (Maybe NodeIdx)
- NanoUI.Frame.Hit: widgetIdInSubtree :: Context -> NodeIdx -> WidgetId -> IO Bool
- NanoUI.Frame.Hit: widgetOverlayAllowed :: Context -> WidgetId -> IO Bool
- NanoUI.Frame.TextEdit: TextAreaHit :: NodeIdx -> Rect -> Float -> Float -> Float -> Float -> Float -> Float -> TextAreaHit
- NanoUI.Frame.TextEdit: TextAreaScrollBarLayouts :: Maybe ScrollBarLayout -> Maybe ScrollBarLayout -> TextAreaScrollBarLayouts
- NanoUI.Frame.TextEdit: [tahContentX] :: TextAreaHit -> Float
- NanoUI.Frame.TextEdit: [tahFieldRect] :: TextAreaHit -> Rect
- NanoUI.Frame.TextEdit: [tahLineH] :: TextAreaHit -> Float
- NanoUI.Frame.TextEdit: [tahNodeIdx] :: TextAreaHit -> NodeIdx
- NanoUI.Frame.TextEdit: [tahWidgetH] :: TextAreaHit -> Float
- NanoUI.Frame.TextEdit: [tahWidgetW] :: TextAreaHit -> Float
- NanoUI.Frame.TextEdit: [tahWidgetX] :: TextAreaHit -> Float
- NanoUI.Frame.TextEdit: [tahWidgetY] :: TextAreaHit -> Float
- NanoUI.Frame.TextEdit: [tasbHorizontal] :: TextAreaScrollBarLayouts -> Maybe ScrollBarLayout
- NanoUI.Frame.TextEdit: [tasbVertical] :: TextAreaScrollBarLayouts -> Maybe ScrollBarLayout
- NanoUI.Frame.TextEdit: applyTextFieldMenuAction :: Context -> WidgetId -> Int -> IO ()
- NanoUI.Frame.TextEdit: collapseTextFieldSelection :: Context -> WidgetId -> IO ()
- NanoUI.Frame.TextEdit: data TextAreaHit
- NanoUI.Frame.TextEdit: data TextAreaScrollBarLayouts
- NanoUI.Frame.TextEdit: finalizeTextFieldMouse :: Context -> Input -> IO ()
- NanoUI.Frame.TextEdit: normalizeTextFieldClicks :: Context -> WidgetId -> Int -> Int -> Int -> Bool -> Int -> IO Int
- NanoUI.Frame.TextEdit: resolveTextAreaFont :: Context -> NodeIdx -> IO FontMetrics
- NanoUI.Frame.TextEdit: textAreaBarLane :: Float
- NanoUI.Frame.TextEdit: textAreaContentMetrics :: Context -> NodeIdx -> IO (Float, Float)
- NanoUI.Frame.TextEdit: textAreaHScrollBarLayout :: FontMetrics -> Rect -> Float -> Float -> Maybe ScrollBarLayout
- NanoUI.Frame.TextEdit: textAreaHitForWidget :: Context -> WidgetId -> IO (Maybe TextAreaHit)
- NanoUI.Frame.TextEdit: textAreaLineHeight :: FontMetrics -> Float
- NanoUI.Frame.TextEdit: textAreaScrollBarLayout :: FontMetrics -> Rect -> Float -> Float -> Maybe ScrollBarLayout
- NanoUI.Frame.TextEdit: textAreaScrollBarLayouts :: FontMetrics -> Rect -> Float -> Float -> Float -> Float -> TextAreaScrollBarLayouts
- NanoUI.Frame.TextEdit: textEditMenuRectAt :: Float -> Float -> Float -> Size -> Rect
- NanoUI.Frame.TextEdit: textEditMenuWidth :: Context -> IO Float
- NanoUI.Frame.TextEdit: textWordBounds :: Text -> Int -> (Int, Int)
- NanoUI.Frame.Window: ResizeE :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeN :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeNE :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeNW :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeS :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeSE :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeSW :: WindowResizeEdge
- NanoUI.Frame.Window: ResizeW :: WindowResizeEdge
- NanoUI.Frame.Window: contextMeasurers :: Context -> Measurers
- NanoUI.Frame.Window: data WindowResizeEdge
- NanoUI.Frame.Window: lookupWindowPos :: Context -> WidgetId -> IO (Maybe (Float, Float))
- NanoUI.Frame.Window: lookupWindowSize :: Context -> WidgetId -> IO (Maybe (Float, Float))
- NanoUI.Frame.Window: persistWindowPositions :: Context -> IO ()
- NanoUI.Frame.Window: updateWindowDrag :: Context -> Input -> IO Bool
- NanoUI.Frame.Window: updateWindowResize :: Context -> Input -> Float -> Float -> IO Bool
- NanoUI.Frame.Window: windowResizeCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)
- NanoUI.Id: IdContext :: Word64 -> Word64 -> IdContext
- NanoUI.Id: WidgetId :: Word64 -> WidgetId
- NanoUI.Id: [currentId] :: IdContext -> Word64
- NanoUI.Id: [siblingId] :: IdContext -> Word64
- NanoUI.Id: data IdContext
- NanoUI.Id: enterKeyed :: Word64 -> IdContext -> (IdContext, IdContext)
- NanoUI.Id: enterScope :: Word64 -> IdContext -> (IdContext, IdContext)
- NanoUI.Id: fnv1a :: String -> Word64
- NanoUI.Id: hashWidgetId :: WidgetId -> Word64
- NanoUI.Id: idContextWidgetId :: IdContext -> WidgetId
- NanoUI.Id: initialIdContext :: IdContext
- NanoUI.Id: instance Data.Hashable.Class.Hashable NanoUI.Id.WidgetId
- NanoUI.Id: instance Data.Primitive.Types.Prim NanoUI.Id.WidgetId
- NanoUI.Id: instance GHC.Internal.Classes.Eq NanoUI.Id.IdContext
- NanoUI.Id: instance GHC.Internal.Classes.Eq NanoUI.Id.WidgetId
- NanoUI.Id: instance GHC.Internal.Classes.Ord NanoUI.Id.WidgetId
- NanoUI.Id: instance GHC.Internal.Show.Show NanoUI.Id.IdContext
- NanoUI.Id: instance GHC.Internal.Show.Show NanoUI.Id.WidgetId
- NanoUI.Id: mix64 :: Word64 -> Word64 -> Word64
- NanoUI.Id: mixFnv :: Word64 -> Word64 -> Word64
- NanoUI.Id: newtype WidgetId
- NanoUI.Id: scopeTag :: Word64
- NanoUI.Id: widgetId :: HasCallStack => WidgetId
- NanoUI.Input: [inputMouseDown] :: Input -> Bool
- NanoUI.Input: [inputMousePressed] :: Input -> Bool
- NanoUI.Input: [inputMouseReleased] :: Input -> Bool
- NanoUI.Input: [inputMouseRightDown] :: Input -> Bool
- NanoUI.Input: [inputMouseRightPressed] :: Input -> Bool
- NanoUI.Input: [inputMouseRightReleased] :: Input -> Bool
- NanoUI.Input: emptyDropEvents :: SmallArray DropEvent
- NanoUI.Input: emptyInputKeys :: SmallArray Key
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.DropEvent
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.DropType
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.Input
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.Key
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.Modifiers
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.MouseButton
- NanoUI.Input: instance GHC.Internal.Classes.Eq NanoUI.Input.UiCursorKind
- NanoUI.Input: instance GHC.Internal.Enum.Bounded NanoUI.Input.Key
- NanoUI.Input: instance GHC.Internal.Enum.Enum NanoUI.Input.Key
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.DropEvent
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.DropType
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.Input
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.Key
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.Modifiers
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.MouseButton
- NanoUI.Input: instance GHC.Internal.Show.Show NanoUI.Input.UiCursorKind
- NanoUI.Input: isHardQuitInput :: Input -> Bool
- NanoUI.Input: splitFrame :: (a -> Bool) -> [a] -> ([a], [a])
- NanoUI.Input: stripInteractionInput :: Input -> Input
- NanoUI.Layout.Arena: AxisSnapshot :: MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Float -> AxisSnapshot
- NanoUI.Layout.Arena: DirColumn :: DirTag
- NanoUI.Layout.Arena: DirRow :: DirTag
- NanoUI.Layout.Arena: FlexScratch :: Int -> MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> FlexScratch
- NanoUI.Layout.Arena: LayoutCache :: Int -> Int -> NodeArenaArrays -> LayoutCache
- NanoUI.Layout.Arena: NodeArena :: IORef Int -> IORef Int -> IORef NodeArenaArrays -> IORef (Maybe NodeArenaArrays) -> IORef FlexScratch -> IORef Int -> IORef (MutableArray RealWorld (Maybe AxisSnapshot)) -> IORef Word32 -> IORef WidthMemo -> IORef WidthMemo -> IORef Word32 -> IORef (BasicHashTable WidgetId Word64) -> IORef Int -> IORef Word64 -> IORef Int -> IORef Int -> NodeArena
- NanoUI.Layout.Arena: NodeArenaArrays :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Word8 -> MutablePrimArray RealWorld Int -> MutableArray RealWorld Text -> MutableArray RealWorld [Text] -> MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Int -> NodeArenaArrays
- NanoUI.Layout.Arena: NodeBox :: NodeType
- NanoUI.Layout.Arena: NodeButton :: NodeType
- NanoUI.Layout.Arena: NodeCheckbox :: NodeType
- NanoUI.Layout.Arena: NodeColorPicker :: NodeType
- NanoUI.Layout.Arena: NodeContainer :: NodeType
- NanoUI.Layout.Arena: NodeDrawing :: NodeType
- NanoUI.Layout.Arena: NodeImage :: NodeType
- NanoUI.Layout.Arena: NodeModal :: NodeType
- NanoUI.Layout.Arena: NodePanel :: NodeType
- NanoUI.Layout.Arena: NodePopup :: NodeType
- NanoUI.Layout.Arena: NodeRadio :: NodeType
- NanoUI.Layout.Arena: NodeScrollContainer :: NodeType
- NanoUI.Layout.Arena: NodeSelect :: NodeType
- NanoUI.Layout.Arena: NodeSeparator :: NodeType
- NanoUI.Layout.Arena: NodeSlider :: NodeType
- NanoUI.Layout.Arena: NodeSpacer :: NodeType
- NanoUI.Layout.Arena: NodeText :: NodeType
- NanoUI.Layout.Arena: NodeTextArea :: NodeType
- NanoUI.Layout.Arena: NodeTextInput :: NodeType
- NanoUI.Layout.Arena: NodeTree :: NodeType
- NanoUI.Layout.Arena: NodeWidget :: NodeType
- NanoUI.Layout.Arena: NodeWindow :: NodeType
- NanoUI.Layout.Arena: SizingFit :: SizingTag
- NanoUI.Layout.Arena: SizingFixed :: SizingTag
- NanoUI.Layout.Arena: SizingGrow :: SizingTag
- NanoUI.Layout.Arena: SizingPercent :: SizingTag
- NanoUI.Layout.Arena: SizingShrink :: SizingTag
- NanoUI.Layout.Arena: [asIdx] :: AxisSnapshot -> MutablePrimArray RealWorld Int
- NanoUI.Layout.Arena: [asOut] :: AxisSnapshot -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [fsCap] :: FlexScratch -> Int
- NanoUI.Layout.Arena: [fsH] :: FlexScratch -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [fsIdx] :: FlexScratch -> MutablePrimArray RealWorld Int
- NanoUI.Layout.Arena: [fsOutH] :: FlexScratch -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [fsOutW] :: FlexScratch -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [fsW] :: FlexScratch -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [lcArrays] :: LayoutCache -> NodeArenaArrays
- NanoUI.Layout.Arena: [lcCap] :: LayoutCache -> Int
- NanoUI.Layout.Arena: [lcCount] :: LayoutCache -> Int
- NanoUI.Layout.Arena: [naArrFontColor] :: NodeArenaArrays -> MutablePrimArray RealWorld Int
- NanoUI.Layout.Arena: [naArrGeom] :: NodeArenaArrays -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [naArrOptionsStore] :: NodeArenaArrays -> MutableArray RealWorld [Text]
- NanoUI.Layout.Arena: [naArrScope] :: NodeArenaArrays -> MutablePrimArray RealWorld Int
- NanoUI.Layout.Arena: [naArrStyle] :: NodeArenaArrays -> MutablePrimArray RealWorld Float
- NanoUI.Layout.Arena: [naArrTags] :: NodeArenaArrays -> MutablePrimArray RealWorld Word8
- NanoUI.Layout.Arena: [naArrTextStore] :: NodeArenaArrays -> MutableArray RealWorld Text
- NanoUI.Layout.Arena: [naArrTree] :: NodeArenaArrays -> MutablePrimArray RealWorld Int
- NanoUI.Layout.Arena: [naArraysSnap] :: NodeArena -> IORef (Maybe NodeArenaArrays)
- NanoUI.Layout.Arena: [naArrays] :: NodeArena -> IORef NodeArenaArrays
- NanoUI.Layout.Arena: [naCapacity] :: NodeArena -> IORef Int
- NanoUI.Layout.Arena: [naCount] :: NodeArena -> IORef Int
- NanoUI.Layout.Arena: [naEpoch] :: NodeArena -> IORef Word32
- NanoUI.Layout.Arena: [naFitMemo] :: NodeArena -> IORef WidthMemo
- NanoUI.Layout.Arena: [naFloatingCount] :: NodeArena -> IORef Int
- NanoUI.Layout.Arena: [naFrameTag] :: NodeArena -> IORef Word32
- NanoUI.Layout.Arena: [naIndex] :: NodeArena -> IORef (BasicHashTable WidgetId Word64)
- NanoUI.Layout.Arena: [naScopeSig] :: NodeArena -> IORef Word64
- NanoUI.Layout.Arena: [naScope] :: NodeArena -> IORef Int
- NanoUI.Layout.Arena: [naScratch] :: NodeArena -> IORef FlexScratch
- NanoUI.Layout.Arena: [naSnapCap] :: NodeArena -> IORef Int
- NanoUI.Layout.Arena: [naSnapLevels] :: NodeArena -> IORef (MutableArray RealWorld (Maybe AxisSnapshot))
- NanoUI.Layout.Arena: [naTopModal] :: NodeArena -> IORef Int
- NanoUI.Layout.Arena: [naWrapMemo] :: NodeArena -> IORef WidthMemo
- NanoUI.Layout.Arena: addNode :: NodeArena -> NodeType -> Int -> Direction -> Sizing -> Sizing -> Padding -> Float -> Float -> Float -> Float -> Float -> Float -> AlignX -> AlignY -> IO NodeIdx
- NanoUI.Layout.Arena: addNodeFromLayout :: NodeArena -> NodeType -> Int -> Layout -> IO NodeIdx
- NanoUI.Layout.Arena: arenaArrays :: NodeArena -> IO NodeArenaArrays
- NanoUI.Layout.Arena: arenaCount :: NodeArena -> IO Int
- NanoUI.Layout.Arena: captureLayoutCache :: NodeArena -> LayoutCache -> IO LayoutCache
- NanoUI.Layout.Arena: data AxisSnapshot
- NanoUI.Layout.Arena: data DirTag
- NanoUI.Layout.Arena: data FlexScratch
- NanoUI.Layout.Arena: data LayoutCache
- NanoUI.Layout.Arena: data NodeArena
- NanoUI.Layout.Arena: data NodeArenaArrays
- NanoUI.Layout.Arena: data NodeType
- NanoUI.Layout.Arena: data SizingTag
- NanoUI.Layout.Arena: ensureAxisSnapshot :: NodeArena -> Int -> Int -> IO AxisSnapshot
- NanoUI.Layout.Arena: ensureScratchCapacity :: NodeArena -> Int -> IO FlexScratch
- NanoUI.Layout.Arena: findChildM :: NodeArena -> NodeIdx -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
- NanoUI.Layout.Arena: findNodeM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
- NanoUI.Layout.Arena: findNodeRevM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
- NanoUI.Layout.Arena: floatingNodeCount :: NodeArena -> IO Int
- NanoUI.Layout.Arena: foldFlowChildrenM :: NodeArena -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc
- NanoUI.Layout.Arena: foldNodeRevM :: NodeArena -> (a -> NodeIdx -> IO a) -> a -> IO a
- NanoUI.Layout.Arena: foldNodesM :: NodeArena -> (a -> NodeIdx -> IO a) -> a -> IO a
- NanoUI.Layout.Arena: forChildNodes_ :: NodeArena -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()
- NanoUI.Layout.Arena: forNodes_ :: NodeArena -> (NodeIdx -> IO ()) -> IO ()
- NanoUI.Layout.Arena: geomH :: Int
- NanoUI.Layout.Arena: geomW :: Int
- NanoUI.Layout.Arena: geomX :: Int
- NanoUI.Layout.Arena: geomY :: Int
- NanoUI.Layout.Arena: getAlignX :: NodeArena -> NodeIdx -> IO AlignX
- NanoUI.Layout.Arena: getAlignY :: NodeArena -> NodeIdx -> IO AlignY
- NanoUI.Layout.Arena: getArenaScope :: NodeArena -> IO Int
- NanoUI.Layout.Arena: getChildCount :: NodeArena -> NodeIdx -> IO Int
- NanoUI.Layout.Arena: getClipRect :: NodeArena -> NodeIdx -> IO (Maybe Rect)
- NanoUI.Layout.Arena: getDirection :: NodeArena -> NodeIdx -> IO DirTag
- NanoUI.Layout.Arena: getFirstChild :: NodeArena -> NodeIdx -> IO NodeIdx
- NanoUI.Layout.Arena: getGap :: NodeArena -> NodeIdx -> IO Float
- NanoUI.Layout.Arena: getGridCols :: NodeArena -> NodeIdx -> IO Int
- NanoUI.Layout.Arena: getGridMinColW :: NodeArena -> NodeIdx -> IO Float
- NanoUI.Layout.Arena: getHeightSizing :: NodeArena -> NodeIdx -> IO (SizingTag, Float)
- NanoUI.Layout.Arena: getLayoutRect :: NodeArena -> NodeIdx -> IO (Float, Float, Float, Float)
- NanoUI.Layout.Arena: getMinMax :: NodeArena -> NodeIdx -> IO (Float, Float, Float, Float)
- NanoUI.Layout.Arena: getNextSibling :: NodeArena -> NodeIdx -> IO NodeIdx
- NanoUI.Layout.Arena: getNodeFontColor :: NodeArena -> NodeIdx -> IO (Maybe Color)
- NanoUI.Layout.Arena: getNodeFontSize :: NodeArena -> NodeIdx -> IO Float
- NanoUI.Layout.Arena: getNodeScope :: NodeArena -> NodeIdx -> IO Int
- NanoUI.Layout.Arena: getNodeType :: NodeArena -> NodeIdx -> IO NodeType
- NanoUI.Layout.Arena: getNodeValue :: NodeArena -> NodeIdx -> IO Float
- NanoUI.Layout.Arena: getOptions :: NodeArena -> NodeIdx -> IO [Text]
- NanoUI.Layout.Arena: getPadding :: NodeArena -> NodeIdx -> IO Padding
- NanoUI.Layout.Arena: getParent :: NodeArena -> NodeIdx -> IO NodeIdx
- NanoUI.Layout.Arena: getRect :: NodeArena -> NodeIdx -> IO (Float, Float, Float, Float)
- NanoUI.Layout.Arena: getScopeSignature :: NodeArena -> IO Word64
- NanoUI.Layout.Arena: getScrollContentW :: NodeArena -> NodeIdx -> IO Float
- NanoUI.Layout.Arena: getStyleIdx :: NodeArena -> NodeIdx -> IO Int
- NanoUI.Layout.Arena: getText :: NodeArena -> NodeIdx -> IO Text
- NanoUI.Layout.Arena: getWidgetId :: NodeArena -> NodeIdx -> IO WidgetId
- NanoUI.Layout.Arena: getWidthSizing :: NodeArena -> NodeIdx -> IO (SizingTag, Float)
- NanoUI.Layout.Arena: hasCenteredLabel :: NodeType -> Bool
- NanoUI.Layout.Arena: instance GHC.Internal.Classes.Eq NanoUI.Layout.Arena.DirTag
- NanoUI.Layout.Arena: instance GHC.Internal.Classes.Eq NanoUI.Layout.Arena.NodeType
- NanoUI.Layout.Arena: instance GHC.Internal.Classes.Eq NanoUI.Layout.Arena.SizingTag
- NanoUI.Layout.Arena: instance GHC.Internal.Enum.Bounded NanoUI.Layout.Arena.DirTag
- NanoUI.Layout.Arena: instance GHC.Internal.Enum.Bounded NanoUI.Layout.Arena.NodeType
- NanoUI.Layout.Arena: instance GHC.Internal.Enum.Bounded NanoUI.Layout.Arena.SizingTag
- NanoUI.Layout.Arena: instance GHC.Internal.Enum.Enum NanoUI.Layout.Arena.DirTag
- NanoUI.Layout.Arena: instance GHC.Internal.Enum.Enum NanoUI.Layout.Arena.NodeType
- NanoUI.Layout.Arena: instance GHC.Internal.Enum.Enum NanoUI.Layout.Arena.SizingTag
- NanoUI.Layout.Arena: instance GHC.Internal.Show.Show NanoUI.Layout.Arena.DirTag
- NanoUI.Layout.Arena: instance GHC.Internal.Show.Show NanoUI.Layout.Arena.NodeType
- NanoUI.Layout.Arena: instance GHC.Internal.Show.Show NanoUI.Layout.Arena.SizingTag
- NanoUI.Layout.Arena: isContainerNode :: NodeType -> Bool
- NanoUI.Layout.Arena: isFloatingNode :: NodeType -> Bool
- NanoUI.Layout.Arena: isScrollNode :: NodeType -> Bool
- NanoUI.Layout.Arena: isWidgetNode :: NodeType -> Bool
- NanoUI.Layout.Arena: layoutCacheEligible :: NodeArena -> IO Bool
- NanoUI.Layout.Arena: layoutInputsMatch :: NodeArena -> LayoutCache -> IO Bool
- NanoUI.Layout.Arena: lookupNodeByKey :: NodeArena -> Int -> IO (Maybe NodeIdx)
- NanoUI.Layout.Arena: lookupNodeByWidgetId :: NodeArena -> WidgetId -> IO (Maybe NodeIdx)
- NanoUI.Layout.Arena: memoizeWidth :: NodeArena -> IORef WidthMemo -> NodeIdx -> Float -> IO (Float, Float) -> IO (Float, Float)
- NanoUI.Layout.Arena: newLayoutCache :: Int -> IO LayoutCache
- NanoUI.Layout.Arena: newNodeArena :: IO NodeArena
- NanoUI.Layout.Arena: parentIsRow :: NodeArena -> NodeIdx -> IO Bool
- NanoUI.Layout.Arena: readGeom :: NodeArenaArrays -> NodeIdx -> Int -> IO Float
- NanoUI.Layout.Arena: readStyle :: NodeArenaArrays -> NodeIdx -> Int -> IO Float
- NanoUI.Layout.Arena: readTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> Int -> IO e
- NanoUI.Layout.Arena: readTree :: NodeArenaArrays -> NodeIdx -> Int -> IO Int
- NanoUI.Layout.Arena: resetNodeArena :: NodeArena -> IO ()
- NanoUI.Layout.Arena: restoreLayoutCache :: NodeArena -> LayoutCache -> IO ()
- NanoUI.Layout.Arena: rootAttachParent :: NodeArena -> Int -> IO Int
- NanoUI.Layout.Arena: setArenaScope :: NodeArena -> Int -> IO ()
- NanoUI.Layout.Arena: setClipRect :: NodeArena -> NodeIdx -> Rect -> IO ()
- NanoUI.Layout.Arena: setNodeText :: NodeArena -> NodeIdx -> Text -> IO ()
- NanoUI.Layout.Arena: setNodeValue :: NodeArena -> NodeIdx -> Float -> IO ()
- NanoUI.Layout.Arena: setOptions :: NodeArena -> NodeIdx -> [Text] -> IO ()
- NanoUI.Layout.Arena: setRect :: NodeArena -> NodeIdx -> Float -> Float -> Float -> Float -> IO ()
- NanoUI.Layout.Arena: setScrollContentW :: NodeArena -> NodeIdx -> Float -> IO ()
- NanoUI.Layout.Arena: setStyleIdx :: NodeArena -> NodeIdx -> Int -> IO ()
- NanoUI.Layout.Arena: setWidgetId :: NodeArena -> NodeIdx -> WidgetId -> IO ()
- NanoUI.Layout.Arena: snapshotLayoutRects :: NodeArena -> IO ()
- NanoUI.Layout.Arena: styleGap :: Int
- NanoUI.Layout.Arena: styleGridMinColW :: Int
- NanoUI.Layout.Arena: styleHVal :: Int
- NanoUI.Layout.Arena: styleMaxH :: Int
- NanoUI.Layout.Arena: styleMaxW :: Int
- NanoUI.Layout.Arena: styleMinH :: Int
- NanoUI.Layout.Arena: styleMinW :: Int
- NanoUI.Layout.Arena: stylePadB :: Int
- NanoUI.Layout.Arena: stylePadL :: Int
- NanoUI.Layout.Arena: stylePadR :: Int
- NanoUI.Layout.Arena: stylePadT :: Int
- NanoUI.Layout.Arena: styleWVal :: Int
- NanoUI.Layout.Arena: tagDirection :: Int
- NanoUI.Layout.Arena: tagHSizing :: Int
- NanoUI.Layout.Arena: tagNodeType :: Int
- NanoUI.Layout.Arena: tagScrollBarSlot :: Int
- NanoUI.Layout.Arena: tagWSizing :: Int
- NanoUI.Layout.Arena: topModalNode :: NodeArena -> IO (Maybe NodeIdx)
- NanoUI.Layout.Arena: treeFirstChild :: Int
- NanoUI.Layout.Arena: treeGridCols :: Int
- NanoUI.Layout.Arena: treeNextSibling :: Int
- NanoUI.Layout.Arena: treeParent :: Int
- NanoUI.Layout.Arena: treeStyleIdx :: Int
- NanoUI.Layout.Arena: type NodeIdx = Int
- NanoUI.Layout.Arena: withArenaArraysSnap :: NodeArena -> IO a -> IO a
- NanoUI.Layout.Arena: writeGeom :: NodeArenaArrays -> NodeIdx -> Int -> Float -> IO ()
- NanoUI.Layout.Arena: writeTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> Int -> e -> IO ()
- NanoUI.Layout.Arena: writeTree :: NodeArenaArrays -> NodeIdx -> Int -> Int -> IO ()
- NanoUI.Layout.Solve: Measurers :: FontMetrics -> FontMetrics -> (Text -> IO (Float, Float)) -> FontResolver -> (WidgetId -> IO (Maybe CustomMeasureFn)) -> Measurers
- NanoUI.Layout.Solve: [msFm] :: Measurers -> FontMetrics
- NanoUI.Layout.Solve: [msLookupMeasure] :: Measurers -> WidgetId -> IO (Maybe CustomMeasureFn)
- NanoUI.Layout.Solve: [msMeasure] :: Measurers -> Text -> IO (Float, Float)
- NanoUI.Layout.Solve: [msMonoFm] :: Measurers -> FontMetrics
- NanoUI.Layout.Solve: [msResolveFont] :: Measurers -> FontResolver
- NanoUI.Layout.Solve: computePopupPosition :: Float -> Float -> Float -> Float -> Float -> PopupAnchor -> PopupPlacement -> Float -> (Float, Float)
- NanoUI.Layout.Solve: data Measurers
- NanoUI.Layout.Solve: findAncestorMaxW :: NodeArena -> NodeIdx -> IO Float
- NanoUI.Layout.Solve: placeModals :: NodeArena -> Measurers -> Float -> Float -> IO ()
- NanoUI.Layout.Solve: placePopups :: NodeArena -> Measurers -> Float -> Float -> (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) -> IO ()
- NanoUI.Layout.Solve: placeWindowNode :: NodeArena -> Measurers -> Float -> Float -> NodeIdx -> Float -> Float -> (Float -> (Float, Float)) -> IO ()
- NanoUI.Layout.Solve: placeWindows :: NodeArena -> Measurers -> Float -> Float -> (WidgetId -> IO (Maybe (Float, Float))) -> (WidgetId -> IO (Maybe (Float, Float))) -> IO ()
- NanoUI.Layout.Solve: scrollBarSlotOf :: NodeArena -> NodeIdx -> IO ScrollBarSlot
- NanoUI.Layout.Solve: solveLayout :: NodeArena -> Measurers -> Float -> Float -> IO ()
- NanoUI.Layout.Solve: textWrapCap :: Float -> SizingTag -> Float -> Float
- NanoUI.Layout.Solve: type FontResolver = Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Text -> IO (Float, Float))
- NanoUI.Monad: [FrameMsg] :: forall a. Typeable a => a -> FrameMsg
- NanoUI.Monad: burstNextIds :: forall (es :: [Effect]). Ui :> es => Int -> Eff es ()
- NanoUI.Monad: data FrameMsg
- NanoUI.Monad: data Ui (a :: Type -> Type) b
- NanoUI.Monad: decodeMessages :: (Foldable f, Typeable a) => f FrameMsg -> [a]
- NanoUI.Monad: emit :: forall msg (es :: [Effect]). (Typeable msg, Ui :> es) => msg -> Eff es ()
- NanoUI.Monad: keyed :: forall k (es :: [Effect]) a. (Hashable k, Ui :> es) => k -> Eff es a -> Eff es a
- NanoUI.Monad: reduceMessages :: (Foldable f, Typeable msg) => (msg -> model -> model) -> model -> f FrameMsg -> model
- NanoUI.Monad: reduceUpdates :: (Foldable f, Typeable model) => model -> f FrameMsg -> model
- NanoUI.Monad: runNanoUI :: Context -> Input -> NanoUI a -> IO a
- NanoUI.Monad: runUi :: forall (es :: [Effect]) a. IOE :> es => Context -> Input -> Eff (Ui ': es) a -> Eff es a
- NanoUI.Monad: setUiTheme :: forall (es :: [Effect]). Ui :> es => Theme -> Eff es ()
- NanoUI.Monad: type NanoUI = Eff '[Ui, IOE]
- NanoUI.Monad: uiIO :: forall (es :: [Effect]) a. Ui :> es => IO a -> Eff es a
- NanoUI.Monad: withIdFrame :: forall (es :: [Effect]) a. Ui :> es => (IdContext -> (IdContext, IdContext)) -> Eff es a -> Eff es a
- NanoUI.Runner: [sdIsHardQuit] :: SessionDriver ev -> ev -> Bool
- NanoUI.SIMD: concentricOffsetsSIMD :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> ((Float, Float), (Float, Float), (Float, Float), (Float, Float))
- NanoUI.SIMD: pokeQuadGradientSIMD :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float, Float, Float) -> (Float, Float, Float, Float) -> (Float, Float, Float, Float) -> (Float, Float, Float, Float) -> Word32 -> IO ()
- NanoUI.SIMD: pokeQuadSIMD :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Word32 -> IO ()
- NanoUI.SIMD: pokeVertexSIMD :: Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> IO ()
- NanoUI.Store: SlotAnchor :: Slot
- NanoUI.Store: SlotColorBase :: Slot
- NanoUI.Store: SlotComboCommitted :: Slot
- NanoUI.Store: SlotComboContentW :: Slot
- NanoUI.Store: SlotComboCount :: Slot
- NanoUI.Store: SlotComboDrag :: Slot
- NanoUI.Store: SlotComboDragOff :: Slot
- NanoUI.Store: SlotComboFocus :: Slot
- NanoUI.Store: SlotComboHighlight :: Slot
- NanoUI.Store: SlotComboLive :: Slot
- NanoUI.Store: SlotComboScroll :: Slot
- NanoUI.Store: SlotComboScrollX :: Slot
- NanoUI.Store: SlotCursor :: Slot
- NanoUI.Store: SlotDrag :: Slot
- NanoUI.Store: SlotDragW :: Slot
- NanoUI.Store: SlotDrop :: Slot
- NanoUI.Store: SlotDropPos :: Slot
- NanoUI.Store: SlotMenuOpen :: Slot
- NanoUI.Store: SlotMenuPos :: Slot
- NanoUI.Store: SlotNumericHeld :: Slot
- NanoUI.Store: SlotNumericRepeat :: Slot
- NanoUI.Store: SlotPaneFocus :: Slot
- NanoUI.Store: SlotPaneGest :: Slot
- NanoUI.Store: SlotPaneGrab :: Slot
- NanoUI.Store: SlotPaneMax :: Slot
- NanoUI.Store: SlotPaneNext :: Slot
- NanoUI.Store: SlotPaneResize :: Slot
- NanoUI.Store: SlotScrollAxes :: Slot
- NanoUI.Store: SlotScrollCfg :: Slot
- NanoUI.Store: SlotScrollContent :: Slot
- NanoUI.Store: SlotScrollCross :: Slot
- NanoUI.Store: SlotScrollLinkX :: Slot
- NanoUI.Store: SlotScrollLinkY :: Slot
- NanoUI.Store: SlotScrollOff :: Slot
- NanoUI.Store: SlotScrollRange :: Slot
- NanoUI.Store: SlotScrollStep :: Slot
- NanoUI.Store: SlotScrollViewPos :: Slot
- NanoUI.Store: SlotScrollViewSize :: Slot
- NanoUI.Store: SlotSearchAge :: Slot
- NanoUI.Store: SlotSearchCommitted :: Slot
- NanoUI.Store: SlotSeen :: Slot
- NanoUI.Store: SlotTextAreaAnchorCol :: Slot
- NanoUI.Store: SlotTextAreaAnchorRow :: Slot
- NanoUI.Store: SlotTextAreaBuffer :: Slot
- NanoUI.Store: SlotTextAreaChanged :: Slot
- NanoUI.Store: SlotTextAreaCol :: Slot
- NanoUI.Store: SlotTextAreaContentFont :: Slot
- NanoUI.Store: SlotTextAreaContentH :: Slot
- NanoUI.Store: SlotTextAreaContentW :: Slot
- NanoUI.Store: SlotTextAreaPrefCol :: Slot
- NanoUI.Store: SlotTextAreaRow :: Slot
- NanoUI.Store: SlotTextAreaScroll :: Slot
- NanoUI.Store: SlotTextAreaViewport :: Slot
- NanoUI.Store: SlotTextAreaWidths :: Slot
- NanoUI.Store: SlotTextHistory :: Slot
- NanoUI.Store: SlotTextInputScroll :: Slot
- NanoUI.Store: SlotTextMode :: Slot
- NanoUI.Store: SlotWinSize :: Slot
- NanoUI.Store: WidgetStore :: Word64 -> Int -> IntMap Int -> IntMap Float -> IntMap Double -> IntMap (Float, Float) -> IntMap Text -> IntMap IntSet -> IntMap [Float] -> IntMap [Int] -> IntMap Dynamic -> WidgetStore
- NanoUI.Store: [storeDouble] :: WidgetStore -> IntMap Double
- NanoUI.Store: [storeDyn] :: WidgetStore -> IntMap Dynamic
- NanoUI.Store: [storeFloatList] :: WidgetStore -> IntMap [Float]
- NanoUI.Store: [storeFloat] :: WidgetStore -> IntMap Float
- NanoUI.Store: [storeIntList] :: WidgetStore -> IntMap [Int]
- NanoUI.Store: [storeIntSet] :: WidgetStore -> IntMap IntSet
- NanoUI.Store: [storeInt] :: WidgetStore -> IntMap Int
- NanoUI.Store: [storeMirrorGen] :: WidgetStore -> Word64
- NanoUI.Store: [storeOpenSelect] :: WidgetStore -> Int
- NanoUI.Store: [storePoint] :: WidgetStore -> IntMap (Float, Float)
- NanoUI.Store: [storeText] :: WidgetStore -> IntMap Text
- NanoUI.Store: anySelectOpen :: WidgetStore -> Bool
- NanoUI.Store: boolInt :: Bool -> Int
- NanoUI.Store: bumpMirror :: WidgetStore -> WidgetStore
- NanoUI.Store: closeSelects :: WidgetStore -> WidgetStore
- NanoUI.Store: data Slot
- NanoUI.Store: data WidgetStore
- NanoUI.Store: emptyWidgetStore :: WidgetStore
- NanoUI.Store: eqByPtr :: Eq a => a -> a -> Bool
- NanoUI.Store: instance GHC.Internal.Classes.Eq NanoUI.Store.WidgetStore
- NanoUI.Store: instance GHC.Internal.Enum.Enum NanoUI.Store.Slot
- NanoUI.Store: instance GHC.Internal.Show.Show NanoUI.Store.WidgetStore
- NanoUI.Store: intBool :: Int -> Bool
- NanoUI.Store: isSelectOpen :: WidgetStore -> Int -> Bool
- NanoUI.Store: mirrorStoresChanged :: WidgetStore -> WidgetStore -> Bool
- NanoUI.Store: ptrEq :: a -> a -> Bool
- NanoUI.Store: setSelectOpen :: WidgetStore -> Int -> Bool -> WidgetStore
- NanoUI.Store: slotKey :: Slot -> Int -> Int
- NanoUI.Svg: instance GHC.Internal.Classes.Eq NanoUI.Svg.FillRule
- NanoUI.Svg: instance GHC.Internal.Classes.Eq NanoUI.Svg.LineCap
- NanoUI.Svg: instance GHC.Internal.Classes.Eq NanoUI.Svg.LineJoin
- NanoUI.Svg: instance GHC.Internal.Classes.Eq NanoUI.Svg.Paint
- NanoUI.Testing: DrawImageRect :: Rect -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp
- NanoUI.Testing: LayerSlice :: Int -> Int -> LayerSlice
- NanoUI.Testing: [FrameMsg] :: forall a. Typeable a => a -> FrameMsg
- NanoUI.Testing: [drawLayerSlices] :: DrawData -> PrimArray LayerSlice
- NanoUI.Testing: [sliceCount] :: LayerSlice -> Int
- NanoUI.Testing: [sliceOffset] :: LayerSlice -> Int
- NanoUI.Testing: askCompact :: forall a (es :: [Effect]). (Typeable a, Ui :> es) => Eff es (Maybe a)
- NanoUI.Testing: class (e :: Effect) :> (es :: [Effect])
- NanoUI.Testing: compactHost :: Typeable a => Context -> a -> IO (Compact a)
- NanoUI.Testing: data Compact a
- NanoUI.Testing: data Eff (es :: [Effect]) a
- NanoUI.Testing: data FrameMsg
- NanoUI.Testing: data IOE (a :: Type -> Type) b
- NanoUI.Testing: data LayerSlice
- NanoUI.Testing: data Ui (a :: Type -> Type) b
- NanoUI.Testing: debugPanelOpen :: Context -> IO Bool
- NanoUI.Testing: decodeMessages :: (Foldable f, Typeable a) => f FrameMsg -> [a]
- NanoUI.Testing: getScrollOffset :: Context -> WidgetId -> IO Float
- NanoUI.Testing: getTheme :: Context -> IO Theme
- NanoUI.Testing: reduceMessages :: (Foldable f, Typeable msg) => (msg -> model -> model) -> model -> f FrameMsg -> model
- NanoUI.Testing: reduceUpdates :: (Foldable f, Typeable model) => model -> f FrameMsg -> model
- NanoUI.Testing: runEff :: HasCallStack => Eff '[IOE] a -> IO a
- NanoUI.Testing: runFrameEff :: forall (es :: [Effect]) a. IOE :> es => (forall x. () => Eff es x -> IO x) -> Context -> Input -> Eff (Ui ': es) a -> IO (a, [FrameMsg], DrawData, Bool)
- NanoUI.Testing: runFrameReduce :: (Typeable msg, Eq model) => (msg -> model -> model) -> Context -> Input -> model -> (model -> NanoUI a) -> IO (a, model, [msg], DrawData, Bool)
- NanoUI.Testing: runFrameReduceEff :: forall (es :: [Effect]) msg model a. (IOE :> es, Typeable msg, Eq model) => (forall x. () => Eff es x -> IO x) -> (msg -> model -> model) -> Context -> Input -> model -> (model -> Eff (Ui ': es) a) -> IO (a, model, [msg], DrawData, Bool)
- NanoUI.Testing: setScrollOffset :: Context -> WidgetId -> Float -> IO ()
- NanoUI.Testing: setTheme :: Context -> Theme -> IO ()
- NanoUI.Testing: uiIO :: forall (es :: [Effect]) a. Ui :> es => IO a -> Eff es a
- NanoUI.Testing: withExternalText :: Context -> Bool -> Context
- NanoUI.Testing.Assert: runClickReduce :: (Typeable msg, Eq model) => (msg -> model -> model) -> Context -> Input -> model -> (model -> NanoUI Response) -> V2 -> IO (model, [msg], Bool)
- NanoUI.Testing.Harness: assertScrollGutterPad :: HasCallStack => IORef Int -> Context -> WidgetId -> Response -> Float -> Float -> IO ()
- NanoUI.Testing.Harness: assertWheelTitlePinned :: HasCallStack => IORef Int -> Context -> Input -> NanoUI a -> Text -> Text -> V2 -> Maybe Float -> IO ()
- NanoUI.Testing.Harness: checkIdleFullDamage :: HasCallStack => IORef Int -> Context -> Input -> Input -> NanoUI a -> IO ()
- NanoUI.Testing.Harness: checkLabelAlignEndInk :: IORef Int -> IO ()
- NanoUI.Testing.Harness: windowTitleGrab :: Rect -> V2
- NanoUI.Widgets.Combo: [ciDown] :: ComboInput -> Bool
- NanoUI.Widgets.Combo: [ciEnter] :: ComboInput -> Bool
- NanoUI.Widgets.Combo: [ciEscape] :: ComboInput -> Bool
- NanoUI.Widgets.Combo: [ciKeyDown] :: ComboInput -> Bool
- NanoUI.Widgets.Combo: [ciKeyUp] :: ComboInput -> Bool
- NanoUI.Widgets.Combo: [ciMetrics] :: ComboInput -> FontMetrics
- NanoUI.Widgets.Combo: [ciMouse] :: ComboInput -> V2
- NanoUI.Widgets.Combo: [ciPressed] :: ComboInput -> Bool
- NanoUI.Widgets.Combo: [ciScroll] :: ComboInput -> V2
- NanoUI.Widgets.Combo: instance GHC.Internal.Classes.Eq NanoUI.Widgets.Combo.ComboState
- NanoUI.Widgets.Combo: instance GHC.Internal.Show.Show NanoUI.Widgets.Combo.ComboState
- NanoUI.Widgets.Custom: instance GHC.Internal.Base.Applicative NanoUI.Widgets.Custom.CanvasM
- NanoUI.Widgets.Custom: instance GHC.Internal.Base.Functor NanoUI.Widgets.Custom.CanvasM
- NanoUI.Widgets.Custom: instance GHC.Internal.Base.Monad NanoUI.Widgets.Custom.CanvasM
- NanoUI.Widgets.Custom: mkCustomDrawContext :: Context -> FontMetrics -> WidgetId -> IO CustomDrawContext
- NanoUI.Widgets.Custom: runCanvas :: CanvasM a -> SmallArray DrawOp
- NanoUI.Widgets.Custom: useDrag2D :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es Drag2D
- NanoUI.Widgets.Custom: useWheelDelta :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es (Float, Float)
- NanoUI.Widgets.PaneGrid: PaneGridCtx :: Word64 -> Rect -> Bool -> Bool -> Bool -> (GridAxis -> Eff es Word64) -> Eff es () -> Eff es () -> Eff es () -> PaneGridCtx (es :: [Effect])
- NanoUI.Widgets.PaneGrid: [pgcClose] :: PaneGridCtx (es :: [Effect]) -> Eff es ()
- NanoUI.Widgets.PaneGrid: [pgcDndActive] :: PaneGridCtx (es :: [Effect]) -> Bool
- NanoUI.Widgets.PaneGrid: [pgcDragging] :: PaneGridCtx (es :: [Effect]) -> Bool
- NanoUI.Widgets.PaneGrid: [pgcMaximize] :: PaneGridCtx (es :: [Effect]) -> Eff es ()
- NanoUI.Widgets.PaneGrid: [pgcMaximized] :: PaneGridCtx (es :: [Effect]) -> Bool
- NanoUI.Widgets.PaneGrid: [pgcPaneId] :: PaneGridCtx (es :: [Effect]) -> Word64
- NanoUI.Widgets.PaneGrid: [pgcRect] :: PaneGridCtx (es :: [Effect]) -> Rect
- NanoUI.Widgets.PaneGrid: [pgcRestore] :: PaneGridCtx (es :: [Effect]) -> Eff es ()
- NanoUI.Widgets.PaneGrid: [pgcSplit] :: PaneGridCtx (es :: [Effect]) -> GridAxis -> Eff es Word64
- NanoUI.Widgets.PaneGrid: [pvDragPick] :: PaneView -> Maybe Rect
- NanoUI.Widgets.RichText: instance GHC.Internal.Classes.Eq NanoUI.Widgets.RichText.TokenKind
- NanoUI.Widgets.RichText: instance GHC.Internal.Data.String.IsString NanoUI.Widgets.RichText.Inline
- NanoUI.Widgets.SplitPane: AxisH :: GridAxis
- NanoUI.Widgets.SplitPane: AxisV :: GridAxis
- NanoUI.Widgets.SplitPane: DividerInfo :: Word64 -> GridAxis -> Rect -> Rect -> Float -> DividerInfo
- NanoUI.Widgets.SplitPane: DropSplit :: Word64 -> GridAxis -> Bool -> PaneDrop
- NanoUI.Widgets.SplitPane: DropSwap :: Word64 -> PaneDrop
- NanoUI.Widgets.SplitPane: DropTop :: GridAxis -> Bool -> PaneDrop
- NanoUI.Widgets.SplitPane: Pane :: Word64 -> GridNode
- NanoUI.Widgets.SplitPane: Split :: Word64 -> GridAxis -> Float -> GridNode -> GridNode -> GridNode
- NanoUI.Widgets.SplitPane: [diAxis] :: DividerInfo -> GridAxis
- NanoUI.Widgets.SplitPane: [diBand] :: DividerInfo -> Rect
- NanoUI.Widgets.SplitPane: [diRatio] :: DividerInfo -> Float
- NanoUI.Widgets.SplitPane: [diRegion] :: DividerInfo -> Rect
- NanoUI.Widgets.SplitPane: [diSplitId] :: DividerInfo -> Word64
- NanoUI.Widgets.SplitPane: clampTreeRatio :: GridNode -> Word64 -> Rect -> Float -> Float -> Float -> Float
- NanoUI.Widgets.SplitPane: data DividerInfo
- NanoUI.Widgets.SplitPane: data GridAxis
- NanoUI.Widgets.SplitPane: data GridNode
- NanoUI.Widgets.SplitPane: data PaneDrop
- NanoUI.Widgets.SplitPane: dropPreview :: Float -> Float -> GridNode -> Word64 -> Rect -> PaneDrop -> Maybe (Rect, PaneDrop)
- NanoUI.Widgets.SplitPane: dropTargetForPane :: Rect -> V2 -> Word64 -> PaneDrop
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Widgets.SplitPane.DividerInfo
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Widgets.SplitPane.GridAxis
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Widgets.SplitPane.GridNode
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Widgets.SplitPane.PaneDrop
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Classes.Ord NanoUI.Widgets.SplitPane.GridAxis
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Enum.Bounded NanoUI.Widgets.SplitPane.GridAxis
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Enum.Enum NanoUI.Widgets.SplitPane.GridAxis
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Widgets.SplitPane.DividerInfo
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Widgets.SplitPane.GridAxis
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Widgets.SplitPane.GridNode
- NanoUI.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Widgets.SplitPane.PaneDrop
- NanoUI.Widgets.SplitPane: layoutNode :: Float -> Float -> GridNode -> Rect -> (Map Word64 Rect, [DividerInfo])
- NanoUI.Widgets.SplitPane: mainLen :: GridAxis -> Rect -> Float
- NanoUI.Widgets.SplitPane: mainMins :: GridAxis -> (Float, Float) -> (Float, Float) -> (Float, Float)
- NanoUI.Widgets.SplitPane: paneExist :: GridNode -> Word64 -> Bool
- NanoUI.Widgets.SplitPane: splitLength :: Float -> Float -> Float -> Float -> Float -> Float
- NanoUI.Widgets.SplitPane: subtreeMin :: Float -> Float -> GridNode -> (Float, Float)
- NanoUI.Widgets.SplitPane: topLevelDropTarget :: Float -> Rect -> V2 -> Maybe PaneDrop
- NanoUI.Widgets.SplitPane: treeMovePane :: Word64 -> Word64 -> PaneDrop -> GridNode -> Maybe GridNode
- NanoUI.Widgets.SplitPane: treePanes :: GridNode -> [Word64]
- NanoUI.Widgets.SplitPane: treeRemovePane :: Word64 -> GridNode -> Maybe GridNode
- NanoUI.Widgets.SplitPane: treeSetRatio :: Word64 -> Float -> GridNode -> GridNode
- NanoUI.Widgets.SplitPane: treeSize :: GridNode -> Int
- NanoUI.Widgets.SplitPane: treeSplit :: Word64 -> Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode
- NanoUI.Widgets.TextArea: [buffer] :: TextAreaState -> TextBuffer
- NanoUI.Widgets.TextArea: [history] :: TextAreaState -> EditHistory
- NanoUI.Widgets.TextArea: [lineHeight] :: TextAreaState -> Double
- NanoUI.Widgets.TextArea: [scrollOffset] :: TextAreaState -> (Double, Double)
- NanoUI.Widgets.TextArea: [selectionAnchor] :: TextAreaState -> Cursor
- NanoUI.Widgets.TextArea: [viewportSize] :: TextAreaState -> (Double, Double)
- NanoUI.Widgets.TextArea: applyTextAreaCommand :: Context -> WidgetId -> TextCommand -> IO ()
- NanoUI.Widgets.TextArea: instance GHC.Internal.Show.Show NanoUI.Widgets.TextArea.TextAreaState
- NanoUI.Widgets.TextArea: loadTextAreaState :: WidgetStore -> Int -> Text -> TextAreaState
- NanoUI.Widgets.TextArea: loadTextAreaStateWithBuffer :: WidgetStore -> Int -> TextBuffer -> TextAreaState
- NanoUI.Widgets.TextArea: saveTextAreaState :: Int -> Text -> TextAreaState -> WidgetStore -> WidgetStore
- NanoUI.Widgets.TextArea: textAreaEditor :: TextAreaState -> Editor
- NanoUI.Widgets.TextEditor: editorModeCode :: EditorMode -> Int
- NanoUI.Widgets.TextEditor: editorModeFromCode :: Int -> Maybe EditorMode
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Classes.Eq NanoUI.Widgets.TextEditor.EditGroup
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Classes.Eq NanoUI.Widgets.TextEditor.EditHistory
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Classes.Eq NanoUI.Widgets.TextEditor.EditKind
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Classes.Eq NanoUI.Widgets.TextEditor.EditorMode
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Classes.Eq NanoUI.Widgets.TextEditor.StoredEdit
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Show.Show NanoUI.Widgets.TextEditor.EditGroup
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Show.Show NanoUI.Widgets.TextEditor.EditHistory
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Show.Show NanoUI.Widgets.TextEditor.EditKind
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Show.Show NanoUI.Widgets.TextEditor.EditorMode
- NanoUI.Widgets.TextEditor: instance GHC.Internal.Show.Show NanoUI.Widgets.TextEditor.StoredEdit
- NanoUI.Widgets.TextField: applyTextFieldCommand :: Context -> WidgetId -> TextCommand -> IO ()
- NanoUI.Widgets.TextField: textFieldHistory :: Context -> WidgetId -> IO EditHistory
- NanoUI.Widgets.TextField: textFieldMode :: Context -> WidgetId -> IO (Maybe EditorMode)
+ NanoUI: ($dmpokeUniformAt) :: (Uniforms u, Generic u, GUniforms (Rep u)) => u -> MutableByteArray RealWorld -> Int -> Int -> IO Int
+ NanoUI: ($dmuniformFieldsAt) :: (Uniforms u, GUniforms (Rep u)) => Proxy u -> Text -> Int -> (Int, [UniformField])
+ NanoUI: Accent :: Tone
+ NanoUI: AppearanceDark :: Appearance
+ NanoUI: AppearanceLight :: Appearance
+ NanoUI: BecameHidden :: VisibilityEvent
+ NanoUI: BecameVisible :: VisibilityEvent
+ NanoUI: ButtonConfig :: LayoutModifier -> Adornments -> ButtonConfig
+ NanoUI: CanvasConfig :: LayoutModifier -> Int -> Bool -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind) -> Bool -> KeyClaim -> CanvasConfig
+ NanoUI: Cell :: Maybe SortKey -> Text -> Maybe (NanoUI ()) -> Cell
+ NanoUI: ColorEffect :: ShaderKind
+ NanoUI: Composition :: Text -> Int -> Int -> Composition
+ NanoUI: Danger :: Tone
+ NanoUI: DistortionEffect :: ShaderKind
+ NanoUI: Drag :: a -> V2 -> V2 -> DragPhase -> Drag a
+ NanoUI: DragAxisX :: DragAxis
+ NanoUI: DragAxisY :: DragAxis
+ NanoUI: DragCancelled :: DragPhase
+ NanoUI: DragReleased :: DragPhase
+ NanoUI: DragStarted :: DragPhase
+ NanoUI: Dragging :: DragPhase
+ NanoUI: ExplainedNode :: Text -> Maybe WidgetId -> Int -> Rect -> Padding -> Sizing -> Sizing -> V2 -> V2 -> Float -> Direction -> Flow -> Maybe V2 -> PointerMode -> ExplainedNode
+ NanoUI: FitContain :: ContentFit
+ NanoUI: FitCover :: ContentFit
+ NanoUI: FitFill :: ContentFit
+ NanoUI: FitNone :: ContentFit
+ NanoUI: FitScaleDown :: ContentFit
+ NanoUI: Fullscreen :: WindowMode
+ NanoUI: Hidden :: WindowMode
+ NanoUI: ImageConfig :: (Layout -> Layout) -> ContentFit -> AlignX -> AlignY -> Float -> Rotation -> Maybe Rect -> Float -> ImageConfig
+ NanoUI: ImageDraw :: Rect -> ImageId -> Rect -> Float -> Color -> Float -> ImageDraw
+ NanoUI: InputNormal :: InputPurpose
+ NanoUI: InputNumeric :: InputPurpose
+ NanoUI: InputSecure :: InputPurpose
+ NanoUI: KeyCapsLock :: Key
+ NanoUI: KeyChar :: Char -> Key
+ NanoUI: KeyF :: Int -> Key
+ NanoUI: KeyInsert :: Key
+ NanoUI: KeyMenu :: Key
+ NanoUI: KeyNav :: Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> KeyNav
+ NanoUI: KeyNumLock :: Key
+ NanoUI: KeyPageDown :: Key
+ NanoUI: KeyPageUp :: Key
+ NanoUI: KeyPause :: Key
+ NanoUI: KeyPrintScreen :: Key
+ NanoUI: KeyScrollLock :: Key
+ NanoUI: KeySpace :: Key
+ NanoUI: LayerEffect :: ShaderKind
+ NanoUI: Layered :: Flow
+ NanoUI: Line :: Flow
+ NanoUI: ListNav :: Maybe Int -> Bool -> Bool -> ListNav
+ NanoUI: MouseBack :: MouseButton
+ NanoUI: MouseForward :: MouseButton
+ NanoUI: MouseLeft :: MouseButton
+ NanoUI: MouseMiddle :: MouseButton
+ NanoUI: MouseOther :: Int -> MouseButton
+ NanoUI: MouseRight :: MouseButton
+ NanoUI: Muted :: Tone
+ NanoUI: NavNoScroll :: ListNavScroll
+ NanoUI: NavRowRect :: (Int -> Rect) -> ListNavScroll
+ NanoUI: NavUniformRow :: Float -> ListNavScroll
+ NanoUI: Reorder :: [Int] -> [Int] -> Maybe Int -> Bool -> Reorder
+ NanoUI: RotateFloating :: Float -> Rotation
+ NanoUI: RotateSolid :: Float -> Rotation
+ NanoUI: Screenshot :: RgbaPixels -> Float -> Screenshot
+ NanoUI: ScrollAlways :: ScrollPolicy
+ NanoUI: ScrollAuto :: ScrollPolicy
+ NanoUI: ScrollConfig :: ScrollPolicy -> ScrollPolicy -> Bool -> Bool -> ScrollConfig
+ NanoUI: ScrollHidden :: ScrollPolicy
+ NanoUI: ScrollNone :: ScrollPolicy
+ NanoUI: ScrollOverlay :: ScrollPolicy
+ NanoUI: SearchInputConfig :: Text -> Float -> LayoutModifier -> SearchInputConfig
+ NanoUI: SensorConfig :: Float -> Double -> (Layout -> Layout) -> SensorConfig
+ NanoUI: ShaderCapabilities :: Bool -> Bool -> ShaderCapabilities
+ NanoUI: ShaderConfig :: LayoutModifier -> Float -> Color -> Color -> ShaderConfig
+ NanoUI: SideBottom :: Side
+ NanoUI: SideLeft :: Side
+ NanoUI: SideRight :: Side
+ NanoUI: SideTop :: Side
+ NanoUI: SortInt :: Int64 -> SortKey
+ NanoUI: SortNum :: Double -> SortKey
+ NanoUI: SortText :: Text -> SortKey
+ NanoUI: Success :: Tone
+ NanoUI: Surface :: ShaderKind
+ NanoUI: TaskDone :: a -> TaskStatus a
+ NanoUI: TaskFailed :: SomeException -> Maybe a -> TaskStatus a
+ NanoUI: TaskRunning :: Maybe a -> TaskStatus a
+ NanoUI: TooltipConfig :: Double -> Double -> PopupPlacement -> Float -> TooltipConfig
+ NanoUI: UiCursorAlias :: UiCursorKind
+ NanoUI: UiCursorAllScroll :: UiCursorKind
+ NanoUI: UiCursorCell :: UiCursorKind
+ NanoUI: UiCursorColResize :: UiCursorKind
+ NanoUI: UiCursorContextMenu :: UiCursorKind
+ NanoUI: UiCursorCopy :: UiCursorKind
+ NanoUI: UiCursorCrosshair :: UiCursorKind
+ NanoUI: UiCursorDefault :: UiCursorKind
+ NanoUI: UiCursorEResize :: UiCursorKind
+ NanoUI: UiCursorEwResize :: UiCursorKind
+ NanoUI: UiCursorGrab :: UiCursorKind
+ NanoUI: UiCursorGrabbing :: UiCursorKind
+ NanoUI: UiCursorHelp :: UiCursorKind
+ NanoUI: UiCursorHidden :: UiCursorKind
+ NanoUI: UiCursorMove :: UiCursorKind
+ NanoUI: UiCursorNResize :: UiCursorKind
+ NanoUI: UiCursorNeResize :: UiCursorKind
+ NanoUI: UiCursorNeswResize :: UiCursorKind
+ NanoUI: UiCursorNotAllowed :: UiCursorKind
+ NanoUI: UiCursorNsResize :: UiCursorKind
+ NanoUI: UiCursorNwResize :: UiCursorKind
+ NanoUI: UiCursorNwseResize :: UiCursorKind
+ NanoUI: UiCursorPointer :: UiCursorKind
+ NanoUI: UiCursorProgress :: UiCursorKind
+ NanoUI: UiCursorRowResize :: UiCursorKind
+ NanoUI: UiCursorSResize :: UiCursorKind
+ NanoUI: UiCursorSeResize :: UiCursorKind
+ NanoUI: UiCursorSwResize :: UiCursorKind
+ NanoUI: UiCursorText :: UiCursorKind
+ NanoUI: UiCursorWResize :: UiCursorKind
+ NanoUI: UiCursorWait :: UiCursorKind
+ NanoUI: UiCursorZoomIn :: UiCursorKind
+ NanoUI: UiCursorZoomOut :: UiCursorKind
+ NanoUI: V3 :: Float -> Float -> Float -> V3
+ NanoUI: V4 :: Float -> Float -> Float -> Float -> V4
+ NanoUI: Visibility :: Bool -> Maybe VisibilityEvent -> Rect -> Rect -> Visibility
+ NanoUI: Warning :: Tone
+ NanoUI: WindowCapabilities :: Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> WindowCapabilities
+ NanoUI: WindowPositionAt :: Int -> Int -> WindowPosition
+ NanoUI: WindowPositionCentered :: WindowPosition
+ NanoUI: WindowPositionDefault :: WindowPosition
+ NanoUI: WindowSettings :: Text -> Size -> WindowPosition -> Maybe Size -> Maybe Size -> Maybe RgbaPixels -> Bool -> WindowMode -> Bool -> Float -> Bool -> WindowSettings
+ NanoUI: WindowState :: Size -> Float -> Maybe (Int, Int) -> Bool -> Bool -> Bool -> Bool -> Bool -> WindowState
+ NanoUI: Windowed :: WindowMode
+ NanoUI: Wrap :: Flow
+ NanoUI: [bcAdornments] :: ButtonConfig -> Adornments
+ NanoUI: [bcLayout] :: ButtonConfig -> LayoutModifier
+ NanoUI: [canvasContent] :: CanvasConfig -> Int
+ NanoUI: [canvasCursor] :: CanvasConfig -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind)
+ NanoUI: [canvasFocusable] :: CanvasConfig -> Bool
+ NanoUI: [canvasKeys] :: CanvasConfig -> KeyClaim
+ NanoUI: [canvasLayout] :: CanvasConfig -> LayoutModifier
+ NanoUI: [canvasTrackPointer] :: CanvasConfig -> Bool
+ NanoUI: [capNodeEffects] :: ShaderCapabilities -> Bool
+ NanoUI: [capSurfaceShaders] :: ShaderCapabilities -> Bool
+ NanoUI: [cellKey] :: Cell -> Maybe SortKey
+ NanoUI: [cellText] :: Cell -> Text
+ NanoUI: [cellView] :: Cell -> Maybe (NanoUI ())
+ NanoUI: [compositionCursor] :: Composition -> Int
+ NanoUI: [compositionSelection] :: Composition -> Int
+ NanoUI: [compositionText] :: Composition -> Text
+ NanoUI: [dragAt] :: Drag a -> V2
+ NanoUI: [dragFrom] :: Drag a -> V2
+ NanoUI: [dragPayload] :: Drag a -> a
+ NanoUI: [dragPhase] :: Drag a -> DragPhase
+ NanoUI: [explainedDepth] :: ExplainedNode -> Int
+ NanoUI: [explainedDirection] :: ExplainedNode -> Direction
+ NanoUI: [explainedFlow] :: ExplainedNode -> Flow
+ NanoUI: [explainedGap] :: ExplainedNode -> Float
+ NanoUI: [explainedHeight] :: ExplainedNode -> Sizing
+ NanoUI: [explainedKind] :: ExplainedNode -> Text
+ NanoUI: [explainedMax] :: ExplainedNode -> V2
+ NanoUI: [explainedMin] :: ExplainedNode -> V2
+ NanoUI: [explainedPadding] :: ExplainedNode -> Padding
+ NanoUI: [explainedPin] :: ExplainedNode -> Maybe V2
+ NanoUI: [explainedPointer] :: ExplainedNode -> PointerMode
+ NanoUI: [explainedRect] :: ExplainedNode -> Rect
+ NanoUI: [explainedWidget] :: ExplainedNode -> Maybe WidgetId
+ NanoUI: [explainedWidth] :: ExplainedNode -> Sizing
+ NanoUI: [icAlignX] :: ImageConfig -> AlignX
+ NanoUI: [icAlignY] :: ImageConfig -> AlignY
+ NanoUI: [icCrop] :: ImageConfig -> Maybe Rect
+ NanoUI: [icFit] :: ImageConfig -> ContentFit
+ NanoUI: [icLayout] :: ImageConfig -> Layout -> Layout
+ NanoUI: [icOpacity] :: ImageConfig -> Float
+ NanoUI: [icRotation] :: ImageConfig -> Rotation
+ NanoUI: [icScale] :: ImageConfig -> Float
+ NanoUI: [imageAngle] :: ImageDraw -> Float
+ NanoUI: [imageId] :: ImageDraw -> ImageId
+ NanoUI: [imageOpacity] :: ImageDraw -> Float
+ NanoUI: [imageRect] :: ImageDraw -> Rect
+ NanoUI: [imageTint] :: ImageDraw -> Color
+ NanoUI: [imageUV] :: ImageDraw -> Rect
+ NanoUI: [inputButtonsHeld] :: Input -> MouseButtons
+ NanoUI: [inputButtonsPressed] :: Input -> MouseButtons
+ NanoUI: [inputButtonsReleased] :: Input -> MouseButtons
+ NanoUI: [inputComposition] :: Input -> Maybe Composition
+ NanoUI: [inputKeysHeld] :: Input -> SmallArray Key
+ NanoUI: [inputKeysNew] :: Input -> SmallArray Key
+ NanoUI: [inputKeysReleased] :: Input -> SmallArray Key
+ NanoUI: [knDown] :: KeyNav -> Bool
+ NanoUI: [knEnter] :: KeyNav -> Bool
+ NanoUI: [knLeft] :: KeyNav -> Bool
+ NanoUI: [knRight] :: KeyNav -> Bool
+ NanoUI: [knSpace] :: KeyNav -> Bool
+ NanoUI: [knUp] :: KeyNav -> Bool
+ NanoUI: [lnActivated] :: ListNav -> Bool
+ NanoUI: [lnChanged] :: ListNav -> Bool
+ NanoUI: [lnIndex] :: ListNav -> Maybe Int
+ NanoUI: [modSuper] :: Modifiers -> Bool
+ NanoUI: [popupAnchor] :: PopupConfig -> PopupAnchor
+ NanoUI: [popupDismissable] :: PopupConfig -> Bool
+ NanoUI: [popupOffset] :: PopupConfig -> Float
+ NanoUI: [popupPlacement] :: PopupConfig -> PopupPlacement
+ NanoUI: [rawRespClickedWith] :: Response -> MouseButtons
+ NanoUI: [rawRespHeld] :: Response -> MouseButtons
+ NanoUI: [reorderDragging] :: Reorder -> Maybe Int
+ NanoUI: [reorderMoved] :: Reorder -> Bool
+ NanoUI: [reorderOrder] :: Reorder -> [Int]
+ NanoUI: [reorderPreview] :: Reorder -> [Int]
+ NanoUI: [scCornerRadius] :: ShaderConfig -> Float
+ NanoUI: [scFallback] :: ShaderConfig -> Color
+ NanoUI: [scLayout] :: ShaderConfig -> LayoutModifier
+ NanoUI: [scTint] :: ShaderConfig -> Color
+ NanoUI: [screenshotPixels] :: Screenshot -> RgbaPixels
+ NanoUI: [screenshotScale] :: Screenshot -> Float
+ NanoUI: [scrollBare] :: ScrollConfig -> Bool
+ NanoUI: [scrollFocusable] :: ScrollConfig -> Bool
+ NanoUI: [scrollPolicyX] :: ScrollConfig -> ScrollPolicy
+ NanoUI: [scrollPolicyY] :: ScrollConfig -> ScrollPolicy
+ NanoUI: [sensorAnticipate] :: SensorConfig -> Float
+ NanoUI: [sensorDelay] :: SensorConfig -> Double
+ NanoUI: [sensorLayout] :: SensorConfig -> Layout -> Layout
+ NanoUI: [sicDebounceMs] :: SearchInputConfig -> Float
+ NanoUI: [sicLayout] :: SearchInputConfig -> LayoutModifier
+ NanoUI: [sicPlaceholder] :: SearchInputConfig -> Text
+ NanoUI: [styleBorderSides] :: Style -> Word8
+ NanoUI: [tabAdornments] :: Tab a body -> Adornments
+ NanoUI: [tabHeaders] :: TabResponse a -> [(a, Response)]
+ NanoUI: [tabStripRect] :: TabResponse a -> Rect
+ NanoUI: [tableBare] :: TableConfig -> Bool
+ NanoUI: [tableSqueeze] :: TableConfig -> Bool
+ NanoUI: [tabsTrailing] :: TabsConfig -> NanoUI ()
+ NanoUI: [textFontTabular] :: TextFont -> Bool
+ NanoUI: [themeDanger] :: Theme -> Color
+ NanoUI: [themePage] :: Theme -> Maybe Color
+ NanoUI: [themePopup] :: Theme -> Style
+ NanoUI: [themeSuccess] :: Theme -> Color
+ NanoUI: [themeWarning] :: Theme -> Color
+ NanoUI: [ticAdornments] :: TextInputConfig -> Adornments
+ NanoUI: [tooltipDelay] :: TooltipConfig -> Double
+ NanoUI: [tooltipGap] :: TooltipConfig -> Float
+ NanoUI: [tooltipGrace] :: TooltipConfig -> Double
+ NanoUI: [tooltipPlacement] :: TooltipConfig -> PopupPlacement
+ NanoUI: [v3X] :: V3 -> Float
+ NanoUI: [v3Y] :: V3 -> Float
+ NanoUI: [v3Z] :: V3 -> Float
+ NanoUI: [v4W] :: V4 -> Float
+ NanoUI: [v4X] :: V4 -> Float
+ NanoUI: [v4Y] :: V4 -> Float
+ NanoUI: [v4Z] :: V4 -> Float
+ NanoUI: [visBounds] :: Visibility -> Rect
+ NanoUI: [visEvent] :: Visibility -> Maybe VisibilityEvent
+ NanoUI: [visRect] :: Visibility -> Rect
+ NanoUI: [visVisible] :: Visibility -> Bool
+ NanoUI: [wcIcon] :: WindowCapabilities -> Bool
+ NanoUI: [wcMaximize] :: WindowCapabilities -> Bool
+ NanoUI: [wcMinimize] :: WindowCapabilities -> Bool
+ NanoUI: [wcMode] :: WindowCapabilities -> Bool
+ NanoUI: [wcMove] :: WindowCapabilities -> Bool
+ NanoUI: [wcOpacity] :: WindowCapabilities -> Bool
+ NanoUI: [wcResize] :: WindowCapabilities -> Bool
+ NanoUI: [wcSizeLimits] :: WindowCapabilities -> Bool
+ NanoUI: [wcTitle] :: WindowCapabilities -> Bool
+ NanoUI: [winCloseRequested] :: WindowState -> Bool
+ NanoUI: [winFocused] :: WindowState -> Bool
+ NanoUI: [winFullscreen] :: WindowState -> Bool
+ NanoUI: [winMaximized] :: WindowState -> Bool
+ NanoUI: [winMinimized] :: WindowState -> Bool
+ NanoUI: [winPosition] :: WindowState -> Maybe (Int, Int)
+ NanoUI: [winScale] :: WindowState -> Float
+ NanoUI: [winSize] :: WindowState -> Size
+ NanoUI: [wsExitOnCloseRequest] :: WindowSettings -> Bool
+ NanoUI: [wsIcon] :: WindowSettings -> Maybe RgbaPixels
+ NanoUI: [wsMaxSize] :: WindowSettings -> Maybe Size
+ NanoUI: [wsMinSize] :: WindowSettings -> Maybe Size
+ NanoUI: [wsMode] :: WindowSettings -> WindowMode
+ NanoUI: [wsOpacity] :: WindowSettings -> Float
+ NanoUI: [wsPosition] :: WindowSettings -> WindowPosition
+ NanoUI: [wsResizable] :: WindowSettings -> Bool
+ NanoUI: [wsSize] :: WindowSettings -> Size
+ NanoUI: [wsTitle] :: WindowSettings -> Text
+ NanoUI: [wsTransparent] :: WindowSettings -> Bool
+ NanoUI: alignMiddle :: Layout -> Layout
+ NanoUI: askInput :: NanoUI Input
+ NanoUI: askScreenshot :: NanoUI (IO (Maybe Screenshot))
+ NanoUI: askShaderCapabilities :: NanoUI ShaderCapabilities
+ NanoUI: askWake :: NanoUI (IO ())
+ NanoUI: askWindow :: NanoUI WindowState
+ NanoUI: askWindowCapabilities :: NanoUI WindowCapabilities
+ NanoUI: aspect :: Float -> Layout -> Layout
+ NanoUI: becameHidden :: Visibility -> Bool
+ NanoUI: becameVisible :: Visibility -> Bool
+ NanoUI: borderBottom :: Float -> Color -> Style -> Style
+ NanoUI: borderLeft :: Float -> Color -> Style -> Style
+ NanoUI: borderRight :: Float -> Color -> Style -> Style
+ NanoUI: borderSides :: [Side] -> Style -> Style
+ NanoUI: borderTop :: Float -> Color -> Style -> Style
+ NanoUI: breakAnywhere :: Layout -> Layout
+ NanoUI: buttonConfigured :: ButtonConfig -> Text -> NanoUI Bool
+ NanoUI: buttonConfigured' :: ButtonConfig -> Text -> NanoUI Response
+ NanoUI: buttonContent :: NanoUI () -> NanoUI Bool
+ NanoUI: buttonContent' :: NanoUI () -> NanoUI Response
+ NanoUI: buttonContentWith :: (Layout -> Layout) -> NanoUI () -> NanoUI Bool
+ NanoUI: buttonContentWith' :: (Layout -> Layout) -> NanoUI () -> NanoUI Response
+ NanoUI: buttonGroup :: NanoUI a -> NanoUI a
+ NanoUI: buttonGroupWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a
+ NanoUI: calloutTone :: Tone -> NanoUI a -> NanoUI a
+ NanoUI: calloutToneWith :: Tone -> (Layout -> Layout) -> NanoUI a -> NanoUI a
+ NanoUI: calloutToneWith' :: Tone -> (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: calloutWith' :: Color -> (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: canvasConfigured :: CanvasConfig -> (Rect -> CanvasM ()) -> NanoUI Response
+ NanoUI: cellSort :: Text -> Cell -> Cell
+ NanoUI: cellSortInt :: Integral a => a -> Cell -> Cell
+ NanoUI: cellSortKey :: SortKey -> Cell -> Cell
+ NanoUI: cellSortNum :: RealFloat a => a -> Cell -> Cell
+ NanoUI: cellWidget :: NanoUI () -> Cell
+ NanoUI: cellWidthText :: Text -> Cell -> Cell
+ NanoUI: centerWindow :: NanoUI ()
+ NanoUI: checkboxWith :: (Layout -> Layout) -> Text -> Var Bool -> NanoUI ()
+ NanoUI: checkboxWith' :: (Layout -> Layout) -> Text -> Var Bool -> NanoUI Response
+ NanoUI: class IsNodeEffect (k :: ShaderKind)
+ NanoUI: class Pressable a
+ NanoUI: class ToCell c
+ NanoUI: class Eq u => Uniforms u
+ NanoUI: class VarSlot a
+ NanoUI: clearFocus :: NanoUI ()
+ NanoUI: clipBox :: LayoutModifier -> NanoUI a -> NanoUI a
+ NanoUI: collapsing :: Text -> Var Bool -> NanoUI () -> NanoUI ()
+ NanoUI: collapsingWith :: LayoutModifier -> Text -> Var Bool -> NanoUI () -> NanoUI ()
+ NanoUI: colorBlack :: Color
+ NanoUI: colorHex :: Word32 -> Color
+ NanoUI: colorHexA :: Word32 -> Color
+ NanoUI: colorRGB :: Word8 -> Word8 -> Word8 -> Color
+ NanoUI: colorTransparent :: Color
+ NanoUI: colorWhite :: Color
+ NanoUI: columnWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: constVar :: a -> Var a
+ NanoUI: contentKeyOf :: [KeyPart] -> Int
+ NanoUI: contramapShader :: forall u2 u1 (k :: ShaderKind). (u2 -> u1) -> Shader k u1 -> Shader k u2
+ NanoUI: data Appearance
+ NanoUI: data ButtonConfig
+ NanoUI: data CanvasConfig
+ NanoUI: data Cell
+ NanoUI: data Composition
+ NanoUI: data ContentFit
+ NanoUI: data Drag a
+ NanoUI: data DragAxis
+ NanoUI: data DragHandle a
+ NanoUI: data DragPhase
+ NanoUI: data ExplainedNode
+ NanoUI: data Flow
+ NanoUI: data ImageConfig
+ NanoUI: data ImageDraw
+ NanoUI: data ImageHandle k
+ NanoUI: data InputPurpose
+ NanoUI: data ItemsAlign
+ NanoUI: data Justify
+ NanoUI: data KeyNav
+ NanoUI: data KeyPart
+ NanoUI: data LineAlign
+ NanoUI: data ListNav
+ NanoUI: data ListNavScroll
+ NanoUI: data MouseButton
+ NanoUI: data NanoUI a
+ NanoUI: data PointerMode
+ NanoUI: data Reorder
+ NanoUI: data RgbaPixels
+ NanoUI: data Rotation
+ NanoUI: data Screenshot
+ NanoUI: data ScrollConfig
+ NanoUI: data ScrollPolicy
+ NanoUI: data SearchInputConfig
+ NanoUI: data SensorConfig
+ NanoUI: data Shader (k :: ShaderKind) u
+ NanoUI: data ShaderCapabilities
+ NanoUI: data ShaderConfig
+ NanoUI: data ShaderKind
+ NanoUI: data Side
+ NanoUI: data SortKey
+ NanoUI: data Stream k s
+ NanoUI: data Task k a
+ NanoUI: data TaskStatus a
+ NanoUI: data TextBreak
+ NanoUI: data TextEllipsis
+ NanoUI: data Tone
+ NanoUI: data TooltipConfig
+ NanoUI: data UiCursorKind
+ NanoUI: data V3
+ NanoUI: data V4
+ NanoUI: data Var a
+ NanoUI: data VarMap k a
+ NanoUI: data Visibility
+ NanoUI: data VisibilityEvent
+ NanoUI: data WindowCapabilities
+ NanoUI: data WindowMode
+ NanoUI: data WindowPosition
+ NanoUI: data WindowSettings
+ NanoUI: data WindowState
+ NanoUI: defaultButtonConfig :: ButtonConfig
+ NanoUI: defaultCanvasConfig :: CanvasConfig
+ NanoUI: defaultImageConfig :: ImageConfig
+ NanoUI: defaultLightTheme :: Theme
+ NanoUI: defaultScrollConfig :: ScrollConfig
+ NanoUI: defaultSearchInputConfig :: SearchInputConfig
+ NanoUI: defaultSensorConfig :: SensorConfig
+ NanoUI: defaultShaderConfig :: ShaderConfig
+ NanoUI: defaultThemeFor :: Maybe Appearance -> Theme
+ NanoUI: defaultTooltipConfig :: TooltipConfig
+ NanoUI: defaultWindowSettings :: WindowSettings
+ NanoUI: direction :: Direction -> Layout -> Layout
+ NanoUI: drawContext :: CanvasM CustomDrawContext
+ NanoUI: drawImageWith :: ImageDraw -> CanvasM ()
+ NanoUI: drawPath :: Path -> Color -> CanvasM ()
+ NanoUI: drawPathWith :: FillRule -> Path -> Paint -> CanvasM ()
+ NanoUI: drawStrokePath :: Path -> Float -> Color -> CanvasM ()
+ NanoUI: drawStrokePathWith :: Stroke -> Path -> Paint -> CanvasM ()
+ NanoUI: drawTextClipped :: Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI: drawTextClippedWith :: FontMetrics -> TextFont -> TextEllipsis -> Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI: drawTextWith :: TextFont -> V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI: dropVar :: Hashable k => VarMap k a -> k -> NanoUI ()
+ NanoUI: ellipsisEnd :: Layout -> Layout
+ NanoUI: ellipsisMiddle :: Layout -> Layout
+ NanoUI: ellipsisStart :: Layout -> Layout
+ NanoUI: enumRadioBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()
+ NanoUI: enumRadioBy' :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI Response
+ NanoUI: enumSelectBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()
+ NanoUI: enumSelectBy' :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI Response
+ NanoUI: enumTabBar :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()
+ NanoUI: enumTabBarBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()
+ NanoUI: enumTabBarByConfigured :: (Bounded a, Enum a) => TabsConfig -> (a -> Text) -> Var a -> NanoUI ()
+ NanoUI: enumTabs :: (Bounded a, Enum a, Show a) => Var a -> (a -> NanoUI ()) -> NanoUI ()
+ NanoUI: enumTabsBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> (a -> NanoUI ()) -> NanoUI ()
+ NanoUI: enumTabsByConfigured :: (Bounded a, Enum a) => TabsConfig -> (a -> Text) -> Var a -> (a -> NanoUI ()) -> NanoUI ()
+ NanoUI: explainLayout :: Bool -> NanoUI ()
+ NanoUI: explainScope :: NanoUI a -> NanoUI a
+ NanoUI: explainedNode :: NanoUI (Maybe ExplainedNode)
+ NanoUI: explainingLayout :: NanoUI Bool
+ NanoUI: fitH :: Layout -> Layout
+ NanoUI: fitRect :: ContentFit -> AlignX -> AlignY -> (Float, Float) -> Rect -> Rect
+ NanoUI: fitW :: Layout -> Layout
+ NanoUI: fixUniform :: forall u (k :: ShaderKind). u -> Shader k u -> Shader k ()
+ NanoUI: floatingWindow :: Var Bool -> Text -> NanoUI () -> NanoUI ()
+ NanoUI: floatingWindow' :: Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: floatingWindowWith :: LayoutModifier -> Var Bool -> Text -> NanoUI () -> NanoUI ()
+ NanoUI: floatingWindowWith' :: LayoutModifier -> Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: focusNext :: NanoUI ()
+ NanoUI: focusPrevious :: NanoUI ()
+ NanoUI: focusedKeyPressed :: WidgetId -> Key -> NanoUI Bool
+ NanoUI: focusedKeyPressedOnce :: WidgetId -> Key -> NanoUI Bool
+ NanoUI: followSystemTheme :: (Maybe Appearance -> Theme) -> NanoUI ()
+ NanoUI: fontProportional :: Layout -> Layout
+ NanoUI: fontTabular :: Layout -> Layout
+ NanoUI: fontTone :: Tone -> Layout -> Layout
+ NanoUI: forEachVar :: Hashable k => (a -> k) -> Var [a] -> (Var a -> NanoUI ()) -> NanoUI ()
+ NanoUI: getClipboard :: NanoUI (Maybe Text)
+ NanoUI: gridWith' :: Int -> (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: growH :: Float -> Layout -> Layout
+ NanoUI: growW :: Float -> Layout -> Layout
+ NanoUI: heldIn :: Pressable a => a -> Input -> Bool
+ NanoUI: holdFocus :: WidgetId -> NanoUI ()
+ NanoUI: iconButton :: Svg -> Text -> NanoUI Bool
+ NanoUI: iconButton' :: Svg -> Text -> NanoUI Response
+ NanoUI: imageConfigured :: ImageConfig -> ImageId -> NanoUI ()
+ NanoUI: imageConfigured' :: ImageConfig -> ImageId -> NanoUI Response
+ NanoUI: imageDraw :: Rect -> ImageId -> ImageDraw
+ NanoUI: insertionIndex :: DragAxis -> Rect -> [Rect] -> V2 -> Maybe Int
+ NanoUI: isFocused :: WidgetId -> NanoUI Bool
+ NanoUI: itemsAlign :: ItemsAlign -> Layout -> Layout
+ NanoUI: itemsBaseline :: Layout -> Layout
+ NanoUI: itemsCenter :: Layout -> Layout
+ NanoUI: itemsEnd :: Layout -> Layout
+ NanoUI: itemsStart :: Layout -> Layout
+ NanoUI: itemsStretch :: Layout -> Layout
+ NanoUI: justify :: Justify -> Layout -> Layout
+ NanoUI: justifyBetween :: Layout -> Layout
+ NanoUI: justifyCenter :: Layout -> Layout
+ NanoUI: justifyEnd :: Layout -> Layout
+ NanoUI: justifyStart :: Layout -> Layout
+ NanoUI: keyActivated :: WidgetId -> NanoUI Bool
+ NanoUI: keyHeld :: Key -> NanoUI Bool
+ NanoUI: keyPart :: Hashable a => a -> KeyPart
+ NanoUI: keyPressed :: Key -> NanoUI Bool
+ NanoUI: keyPressedOnce :: Key -> NanoUI Bool
+ NanoUI: keyReleased :: Key -> NanoUI Bool
+ NanoUI: lastRect :: WidgetId -> NanoUI (Maybe Rect)
+ NanoUI: layered :: Layout -> Layout
+ NanoUI: layers :: NanoUI a -> NanoUI a
+ NanoUI: layersWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a
+ NanoUI: layersWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: liftIO :: MonadIO m => IO a -> m a
+ NanoUI: lightDark :: Theme -> Theme -> Maybe Appearance -> Theme
+ NanoUI: lineAlign :: LineAlign -> Layout -> Layout
+ NanoUI: lineGap :: Float -> Layout -> Layout
+ NanoUI: lineWidthUi :: FontMetrics -> Text -> NanoUI Float
+ NanoUI: maximizeWindow :: NanoUI ()
+ NanoUI: menuButtonWith :: (Layout -> Layout) -> Text -> Bool -> NanoUI Bool
+ NanoUI: menuButtonWith' :: (Layout -> Layout) -> Text -> Bool -> NanoUI Response
+ NanoUI: minimizeWindow :: NanoUI ()
+ NanoUI: modJump :: Modifiers -> Bool
+ NanoUI: modMacCommand :: Modifiers -> Bool
+ NanoUI: modPrimary :: Modifiers -> Bool
+ NanoUI: modal' :: Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: modalPanel :: Var Bool -> NanoUI () -> NanoUI ()
+ NanoUI: modalPanel' :: Var Bool -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: modalPanelWith :: (Layout -> Layout) -> Var Bool -> NanoUI () -> NanoUI ()
+ NanoUI: modalPanelWith' :: (Layout -> Layout) -> Var Bool -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: modalWith :: (Layout -> Layout) -> Var Bool -> Text -> NanoUI () -> NanoUI ()
+ NanoUI: modalWith' :: (Layout -> Layout) -> Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: modifyVar :: Eq a => Var a -> (a -> a) -> NanoUI ()
+ NanoUI: modifyVarIO :: Eq a => Var a -> (a -> a) -> IO ()
+ NanoUI: mouseArea :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: mouseHeld :: MouseButton -> NanoUI Bool
+ NanoUI: mousePressed :: MouseButton -> NanoUI Bool
+ NanoUI: mouseReleased :: MouseButton -> NanoUI Bool
+ NanoUI: moveWindow :: Int -> Int -> NanoUI ()
+ NanoUI: nativeWindow :: Var Bool -> WindowSettings -> NanoUI () -> NanoUI ()
+ NanoUI: navStep :: KeyNav -> Int
+ NanoUI: newDrag :: IO (DragHandle a)
+ NanoUI: newImageHandle :: IO (ImageHandle k)
+ NanoUI: newStream :: IO (Stream k s)
+ NanoUI: newTask :: IO (Task k a)
+ NanoUI: newVar :: a -> IO (Var a)
+ NanoUI: newVarMap :: IO (VarMap k a)
+ NanoUI: noModifiers :: Modifiers
+ NanoUI: padBottom :: Float -> Layout -> Layout
+ NanoUI: padLRTB :: Float -> Float -> Float -> Float -> Layout -> Layout
+ NanoUI: padLeft :: Float -> Layout -> Layout
+ NanoUI: padRight :: Float -> Layout -> Layout
+ NanoUI: padTop :: Float -> Layout -> Layout
+ NanoUI: pageBackground :: Theme -> Color
+ NanoUI: pageColor :: Color -> Theme -> Theme
+ NanoUI: panelPage :: Theme -> Theme
+ NanoUI: panelWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: pattern BreakAnywhere :: TextBreak
+ NanoUI: pattern BreakWords :: TextBreak
+ NanoUI: pattern EllipsisEnd :: TextEllipsis
+ NanoUI: pattern EllipsisMiddle :: TextEllipsis
+ NanoUI: pattern EllipsisStart :: TextEllipsis
+ NanoUI: pattern ItemsBaseline :: ItemsAlign
+ NanoUI: pattern ItemsCenter :: ItemsAlign
+ NanoUI: pattern ItemsEnd :: ItemsAlign
+ NanoUI: pattern ItemsStart :: ItemsAlign
+ NanoUI: pattern ItemsStretch :: ItemsAlign
+ NanoUI: pattern JustifyBetween :: Justify
+ NanoUI: pattern JustifyCenter :: Justify
+ NanoUI: pattern JustifyEnd :: Justify
+ NanoUI: pattern JustifyStart :: Justify
+ NanoUI: pattern LinesCenter :: LineAlign
+ NanoUI: pattern LinesEnd :: LineAlign
+ NanoUI: pattern LinesStart :: LineAlign
+ NanoUI: pattern PointerAuto :: PointerMode
+ NanoUI: pattern PointerBlock :: PointerMode
+ NanoUI: pattern PointerPass :: PointerMode
+ NanoUI: percentH :: Float -> Layout -> Layout
+ NanoUI: pinAt :: Float -> Float -> Layout -> Layout
+ NanoUI: pointer :: PointerMode -> Layout -> Layout
+ NanoUI: pokeUniformAt :: Uniforms u => u -> MutableByteArray RealWorld -> Int -> Int -> IO Int
+ NanoUI: popup' :: Var Bool -> PopupConfig -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: popupStyle :: (Style -> Style) -> Theme -> Theme
+ NanoUI: popupWith' :: Var Bool -> PopupConfig -> (Layout -> Layout) -> NanoUI a -> NanoUI (Response, Maybe a)
+ NanoUI: pressedIn :: Pressable a => a -> Input -> Bool
+ NanoUI: pressedOnceIn :: Pressable a => a -> Input -> Bool
+ NanoUI: primaryModifiers :: Modifiers
+ NanoUI: quit :: NanoUI ()
+ NanoUI: readVar :: Var a -> NanoUI a
+ NanoUI: readVarIO :: Var a -> IO a
+ NanoUI: releaseImageRgba :: ImageId -> NanoUI ()
+ NanoUI: releasedIn :: Pressable a => a -> Input -> Bool
+ NanoUI: requestFocus :: WidgetId -> NanoUI ()
+ NanoUI: requestFrame :: NanoUI ()
+ NanoUI: requestScreenshot :: (Maybe Screenshot -> IO ()) -> NanoUI ()
+ NanoUI: resizeWindow :: Size -> NanoUI ()
+ NanoUI: resolveFontUi :: Float -> FontWeight -> FontStyle -> FontVariant -> NanoUI FontMetrics
+ NanoUI: respClickedWith :: HasResponse r => MouseButton -> r -> Bool
+ NanoUI: respHeldWith :: HasResponse r => MouseButton -> r -> Bool
+ NanoUI: responsiveIn :: Float -> (NanoUI a -> NanoUI a) -> (NanoUI a -> NanoUI a) -> NanoUI a -> NanoUI a
+ NanoUI: responsiveRowColIn :: Float -> LayoutModifier -> NanoUI a -> NanoUI a
+ NanoUI: restoreWindow :: NanoUI ()
+ NanoUI: retainVars :: (k -> Bool) -> VarMap k a -> NanoUI ()
+ NanoUI: rgbaBytes :: RgbaPixels -> ByteString
+ NanoUI: rgbaHeight :: RgbaPixels -> Int
+ NanoUI: rgbaPixels :: Int -> Int -> ByteString -> Maybe RgbaPixels
+ NanoUI: rgbaWidth :: RgbaPixels -> Int
+ NanoUI: rotationAngle :: Rotation -> Float
+ NanoUI: rowWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: scroll2DConfig :: ScrollConfig
+ NanoUI: scroll2DWith' :: LayoutModifier -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: scrollConfigured :: ScrollConfig -> LayoutModifier -> NanoUI a -> NanoUI a
+ NanoUI: scrollConfigured' :: ScrollConfig -> LayoutModifier -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: scrollWith' :: LayoutModifier -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: searchInput :: Text -> Var Text -> NanoUI ()
+ NanoUI: searchInput' :: Text -> Var Text -> NanoUI Response
+ NanoUI: searchInputConfigured :: SearchInputConfig -> Var Text -> NanoUI ()
+ NanoUI: searchInputConfigured' :: SearchInputConfig -> Var Text -> NanoUI Response
+ NanoUI: selectableRow :: Bool -> NanoUI () -> NanoUI Bool
+ NanoUI: selectableRow' :: Bool -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: selectableRowWith :: Bool -> LayoutModifier -> NanoUI () -> NanoUI Bool
+ NanoUI: selectableRowWith' :: Bool -> LayoutModifier -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: sensor :: NanoUI a -> NanoUI (Visibility, a)
+ NanoUI: sensorConfigured :: SensorConfig -> NanoUI a -> NanoUI (Visibility, a)
+ NanoUI: sensorWith :: (Layout -> Layout) -> NanoUI a -> NanoUI (Visibility, a)
+ NanoUI: setClipboard :: Text -> NanoUI Bool
+ NanoUI: setWindowIcon :: RgbaPixels -> NanoUI ()
+ NanoUI: setWindowMaxSize :: Maybe Size -> NanoUI ()
+ NanoUI: setWindowMinSize :: Maybe Size -> NanoUI ()
+ NanoUI: setWindowMode :: WindowMode -> NanoUI ()
+ NanoUI: setWindowOpacity :: Float -> NanoUI ()
+ NanoUI: setWindowTitle :: Text -> NanoUI ()
+ NanoUI: shaderBox :: LayoutModifier -> Shader 'Surface u -> u -> NanoUI ()
+ NanoUI: shaderBox' :: LayoutModifier -> Shader 'Surface u -> u -> NanoUI Response
+ NanoUI: shaderConfigured :: ShaderConfig -> Shader 'Surface u -> u -> NanoUI ()
+ NanoUI: shaderConfigured' :: ShaderConfig -> Shader 'Surface u -> u -> NanoUI Response
+ NanoUI: shortcut :: Shortcut -> NanoUI Bool
+ NanoUI: shortcutOnce :: Shortcut -> NanoUI Bool
+ NanoUI: singleLine :: Layout -> Layout
+ NanoUI: spacerH :: Float -> NanoUI ()
+ NanoUI: spacerW :: Float -> NanoUI ()
+ NanoUI: svgIconConfigured :: ImageConfig -> Svg -> NanoUI ()
+ NanoUI: svgIconConfigured' :: ImageConfig -> Svg -> NanoUI Response
+ NanoUI: systemAppearance :: NanoUI (Maybe Appearance)
+ NanoUI: table' :: (Foldable f, ToCell c) => Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI TableResponse
+ NanoUI: tableConfigured' :: (Foldable f, ToCell c) => TableConfig -> (Layout -> Layout) -> Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI TableResponse
+ NanoUI: tableWith' :: (Foldable f, ToCell c) => (Layout -> Layout) -> Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI TableResponse
+ NanoUI: takeEscape :: NanoUI Bool
+ NanoUI: textAreaDocument :: Var TextDocument -> NanoUI ()
+ NanoUI: textAreaDocument' :: Var TextDocument -> NanoUI Response
+ NanoUI: textAreaDocumentWith :: (Layout -> Layout) -> Var TextDocument -> NanoUI ()
+ NanoUI: textAreaDocumentWith' :: (Layout -> Layout) -> Var TextDocument -> NanoUI Response
+ NanoUI: textBreak :: TextBreak -> Layout -> Layout
+ NanoUI: textCell :: Text -> Cell
+ NanoUI: textEllipsis :: TextEllipsis -> Layout -> Layout
+ NanoUI: themeAppearance :: Theme -> Appearance
+ NanoUI: toCell :: ToCell c => c -> Cell
+ NanoUI: toggleButton :: Tone -> Text -> Var Bool -> NanoUI ()
+ NanoUI: toggleButton' :: Tone -> Text -> Var Bool -> NanoUI Response
+ NanoUI: toggleButtonWith :: (Layout -> Layout) -> Tone -> Text -> Var Bool -> NanoUI ()
+ NanoUI: toggleButtonWith' :: (Layout -> Layout) -> Tone -> Text -> Var Bool -> NanoUI Response
+ NanoUI: toggleMaximized :: NanoUI ()
+ NanoUI: tone :: Tone -> Theme -> Theme
+ NanoUI: toneColor :: Theme -> Tone -> Color
+ NanoUI: tooltipConfigured :: HasResponse r => TooltipConfig -> r -> Text -> NanoUI ()
+ NanoUI: tooltipWidgetConfigured :: HasResponse r => TooltipConfig -> r -> NanoUI () -> NanoUI ()
+ NanoUI: traverseChannels :: (Animatable a, Applicative f) => (Int -> Float -> f Float) -> a -> f a
+ NanoUI: truncateTextUi :: FontMetrics -> Float -> Text -> NanoUI Text
+ NanoUI: truncateTextWithUi :: TextEllipsis -> FontMetrics -> Float -> Text -> NanoUI Text
+ NanoUI: uiFontSize :: NanoUI Float
+ NanoUI: uiTime :: NanoUI Double
+ NanoUI: uniformFieldsAt :: Uniforms u => Proxy u -> Text -> Int -> (Int, [UniformField])
+ NanoUI: useDrag :: Eq a => DragHandle a -> [(a, Response)] -> NanoUI (Maybe (Drag a))
+ NanoUI: useDrag2DOn :: HasResponse r => r -> NanoUI Drag2D
+ NanoUI: useEnumVar :: (Bounded a, Enum a, Typeable a) => a -> NanoUI (Var a)
+ NanoUI: useImageRgba :: Eq k => ImageHandle k -> k -> Int -> Int -> ByteString -> NanoUI (Maybe ImageId)
+ NanoUI: useInputMethod :: WidgetId -> InputPurpose -> Rect -> NanoUI (Maybe Composition)
+ NanoUI: useKeyNav :: WidgetId -> NanoUI KeyNav
+ NanoUI: useListNav :: WidgetId -> Int -> Maybe Int -> Float -> NanoUI ListNav
+ NanoUI: useListNavWith :: WidgetId -> Int -> Maybe Int -> ListNavScroll -> NanoUI ListNav
+ NanoUI: useReorder :: [Int] -> [(Int, Response)] -> NanoUI Reorder
+ NanoUI: useScreenshot :: Eq k => Task k (Maybe Screenshot) -> k -> NanoUI (Maybe Screenshot)
+ NanoUI: useStream :: Eq k => Stream k s -> k -> s -> (((s -> s) -> IO ()) -> IO ()) -> NanoUI s
+ NanoUI: useTask :: Eq k => Task k a -> k -> IO a -> NanoUI (Maybe a)
+ NanoUI: useTaskStatus :: Eq k => Task k a -> k -> IO a -> NanoUI (TaskStatus a)
+ NanoUI: useVar :: VarSlot a => a -> NanoUI (Var a)
+ NanoUI: useVisibility :: SensorConfig -> WidgetId -> NanoUI Visibility
+ NanoUI: useWheelDeltaOn :: HasResponse r => r -> NanoUI (Float, Float)
+ NanoUI: varAt :: Hashable k => VarMap k a -> k -> a -> NanoUI (Var a)
+ NanoUI: wakeAfter :: Double -> NanoUI ()
+ NanoUI: warning :: Theme -> Theme
+ NanoUI: withAlpha :: Color -> Float -> Color
+ NanoUI: withClip :: Rect -> CanvasM a -> CanvasM a
+ NanoUI: withContainerQuery :: Eq a => LayoutModifier -> (Size -> a) -> (a -> NanoUI r) -> NanoUI r
+ NanoUI: withContainerSize :: LayoutModifier -> (Size -> NanoUI a) -> NanoUI a
+ NanoUI: withContainerWidth :: LayoutModifier -> (Float -> NanoUI a) -> NanoUI a
+ NanoUI: withCursorShape :: UiCursorKind -> NanoUI a -> NanoUI a
+ NanoUI: withElemVars :: Hashable k => (a -> k) -> Var [a] -> ([a] -> (a -> Var a) -> NanoUI r) -> NanoUI r
+ NanoUI: withShader :: forall (k :: ShaderKind) u a. IsNodeEffect k => Shader k u -> u -> NanoUI a -> NanoUI a
+ NanoUI: withShader' :: forall (k :: ShaderKind) u a. IsNodeEffect k => Shader k u -> u -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: withShaderWith :: forall (k :: ShaderKind) u a. IsNodeEffect k => LayoutModifier -> Shader k u -> u -> NanoUI a -> NanoUI a
+ NanoUI: withShaderWith' :: forall (k :: ShaderKind) u a. IsNodeEffect k => LayoutModifier -> Shader k u -> u -> NanoUI a -> NanoUI (a, Response)
+ NanoUI: withTransform :: Transform -> CanvasM a -> CanvasM a
+ NanoUI: withValue :: a -> (Var a -> NanoUI r) -> NanoUI (r, a)
+ NanoUI: wrap :: Layout -> Layout
+ NanoUI: writeVar :: Eq a => Var a -> a -> NanoUI ()
+ NanoUI: writeVarIO :: Eq a => Var a -> a -> IO ()
+ NanoUI: zoomVar :: (s -> a) -> (a -> s -> s) -> Var s -> Var a
+ NanoUI: zoomVarL :: (forall (f :: Type -> Type). Functor f => (a -> f a) -> s -> f s) -> Var s -> Var a
+ NanoUI.Adornment: Adornments :: [Adornment] -> [Adornment] -> Adornments
+ NanoUI.Adornment: [adornLeading] :: Adornments -> [Adornment]
+ NanoUI.Adornment: [adornTrailing] :: Adornments -> [Adornment]
+ NanoUI.Adornment: affix :: Text -> Adornment
+ NanoUI.Adornment: control :: NanoUI () -> Adornment
+ NanoUI.Adornment: data Adornment
+ NanoUI.Adornment: data Adornments
+ NanoUI.Adornment: icon :: Svg -> Adornment
+ NanoUI.Adornment: iconSized :: Float -> Svg -> Adornment
+ NanoUI.Adornment: leading :: Adornment -> Adornments
+ NanoUI.Adornment: trailing :: Adornment -> Adornments
+ NanoUI.Adornment: view :: NanoUI () -> Adornment
+ NanoUI.Backend: AppearanceDark :: Appearance
+ NanoUI.Backend: AppearanceLight :: Appearance
+ NanoUI.Backend: AtlasRegions :: [(Int, Int, Int, Int)] -> AtlasUpload
+ NanoUI.Backend: AtlasWhole :: AtlasUpload
+ NanoUI.Backend: ChildWindow :: WidgetId -> Var Bool -> WindowSettings -> (Context -> Input -> IO ()) -> ChildWindow
+ NanoUI.Backend: Composition :: Text -> Int -> Int -> Composition
+ NanoUI.Backend: Custom :: Symbol -> Backend
+ NanoUI.Backend: DamageClip :: Rect -> Damage
+ NanoUI.Backend: DamageCustom :: (Rect -> Rect) -> DamageBounds
+ NanoUI.Backend: DamageExact :: Rect -> DamageBounds
+ NanoUI.Backend: DamageFull :: Damage
+ NanoUI.Backend: DamageInflated :: Float -> DamageBounds
+ NanoUI.Backend: DamageNone :: DamageBounds
+ NanoUI.Backend: DamageSelf :: DamageBounds
+ NanoUI.Backend: DamageUnion :: DamageBounds -> DamageBounds -> DamageBounds
+ NanoUI.Backend: DrawCmd :: Float -> Float -> Float -> Float -> Int -> Word32 -> Word32 -> Layer -> Int32 -> DrawCmd
+ NanoUI.Backend: DrawData :: ForeignPtr Word8 -> Int -> ForeignPtr Word8 -> Int -> Vector DrawCmd -> PrimArray Int -> Color -> SmallArray ShaderCall -> ByteArray -> SmallArray EffectSpan -> DrawData
+ NanoUI.Backend: DropBegin :: DropType
+ NanoUI.Backend: DropComplete :: DropType
+ NanoUI.Backend: DropEvent :: DropType -> Maybe V2 -> Text -> DropEvent
+ NanoUI.Backend: DropFile :: DropType
+ NanoUI.Backend: DropPosition :: DropType
+ NanoUI.Backend: DropText :: DropType
+ NanoUI.Backend: EffectDriver :: Float -> Bool -> (SmallArray ShaderCall -> IO (Maybe (SmallArray passHandle))) -> (Int -> Int -> IO (Int, Int, Int)) -> (Int -> IO ()) -> (Int -> Bool -> Float -> Float -> IO Bool) -> IO () -> (Int -> Int -> Int -> Float -> Float -> Maybe Rect -> Int -> Int -> IO ()) -> (Int -> IO ()) -> (passHandle -> ShaderCall -> EffectPassDraw -> Int -> Int -> IO ()) -> EffectDriver passHandle
+ NanoUI.Backend: EffectPassDraw :: Int -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Bool -> Maybe Rect -> EffectPassDraw
+ NanoUI.Backend: EffectSpan :: Int -> Int -> Layer -> Int -> Int -> Rect -> Rect -> V2 -> SmallArray ShaderCall -> EffectSpan
+ NanoUI.Backend: FontBackend :: (Text -> IO FontMetrics) -> (Text -> IO (Maybe ShapedGlyphs)) -> FontBackend
+ NanoUI.Backend: FontMetrics :: Float -> Float -> Float -> (Char -> Float) -> (Char -> Char -> Float) -> (Text -> Maybe ShapedText) -> (Char -> Maybe GlyphQuad) -> Maybe FontBackend -> FontMetrics
+ NanoUI.Backend: GlyphQuad :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> GlyphQuad
+ NanoUI.Backend: Input :: V2 -> MouseButtons -> MouseButtons -> MouseButtons -> Int -> V2 -> SmallArray Key -> SmallArray Key -> SmallArray Key -> SmallArray Key -> Text -> Modifiers -> Size -> Float -> SmallArray DropEvent -> Bool -> Maybe Composition -> Input
+ NanoUI.Backend: InputNormal :: InputPurpose
+ NanoUI.Backend: InputNumeric :: InputPurpose
+ NanoUI.Backend: InputSecure :: InputPurpose
+ NanoUI.Backend: KeyBackspace :: Key
+ NanoUI.Backend: KeyCapsLock :: Key
+ NanoUI.Backend: KeyChar :: Char -> Key
+ NanoUI.Backend: KeyDelete :: Key
+ NanoUI.Backend: KeyDown :: Key
+ NanoUI.Backend: KeyEnd :: Key
+ NanoUI.Backend: KeyEnter :: Key
+ NanoUI.Backend: KeyEscape :: Key
+ NanoUI.Backend: KeyF :: Int -> Key
+ NanoUI.Backend: KeyHome :: Key
+ NanoUI.Backend: KeyInsert :: Key
+ NanoUI.Backend: KeyLeft :: Key
+ NanoUI.Backend: KeyMenu :: Key
+ NanoUI.Backend: KeyNumLock :: Key
+ NanoUI.Backend: KeyPageDown :: Key
+ NanoUI.Backend: KeyPageUp :: Key
+ NanoUI.Backend: KeyPause :: Key
+ NanoUI.Backend: KeyPrintScreen :: Key
+ NanoUI.Backend: KeyRight :: Key
+ NanoUI.Backend: KeyScrollLock :: Key
+ NanoUI.Backend: KeySpace :: Key
+ NanoUI.Backend: KeyTab :: Key
+ NanoUI.Backend: KeyUp :: Key
+ NanoUI.Backend: LayerBackground :: Layer
+ NanoUI.Backend: LayerChrome :: Layer
+ NanoUI.Backend: LayerContent :: Layer
+ NanoUI.Backend: LayerOverlay :: Layer
+ NanoUI.Backend: Layout :: Direction -> Sizing -> Sizing -> Padding -> Float -> PointerMode -> LineAlign -> TextBreak -> TextEllipsis -> AlignX -> AlignY -> ItemsAlign -> Justify -> Word8 -> Float -> Float -> Float -> Float -> FontVariant -> Int -> Float -> Float -> Float -> Float -> Maybe Color -> Maybe Tone -> FontWeight -> FontStyle -> TextDecoration -> Bool -> Bool -> Flow -> Maybe V2 -> Layout
+ NanoUI.Backend: Modifiers :: Bool -> Bool -> Bool -> Bool -> Modifiers
+ NanoUI.Backend: MouseBack :: MouseButton
+ NanoUI.Backend: MouseForward :: MouseButton
+ NanoUI.Backend: MouseLeft :: MouseButton
+ NanoUI.Backend: MouseMiddle :: MouseButton
+ NanoUI.Backend: MouseOther :: Int -> MouseButton
+ NanoUI.Backend: MouseRight :: MouseButton
+ NanoUI.Backend: ScrollBarList :: ScrollBarSlot
+ NanoUI.Backend: ScrollBarPage :: ScrollBarSlot
+ NanoUI.Backend: ScrollBarWindow :: ScrollBarSlot
+ NanoUI.Backend: Sdl :: Backend
+ NanoUI.Backend: ShaderCall :: Word64 -> ShaderProgram -> Int -> Int -> ShaderCall
+ NanoUI.Backend: ShaderCapabilities :: Bool -> Bool -> ShaderCapabilities
+ NanoUI.Backend: ShaderProgram :: Maybe Text -> Maybe Text -> Maybe ByteString -> Maybe Text -> Bool -> [UniformField] -> Int -> ShaderProgram
+ NanoUI.Backend: ShapedGlyphs :: PrimArray Float -> ShapedGlyphs
+ NanoUI.Backend: ShapedText :: Float -> Float -> PrimArray Float -> ShapedText
+ NanoUI.Backend: TextInputArea :: Rect -> Float -> InputPurpose -> TextInputArea
+ NanoUI.Backend: UiCursorAlias :: UiCursorKind
+ NanoUI.Backend: UiCursorAllScroll :: UiCursorKind
+ NanoUI.Backend: UiCursorCell :: UiCursorKind
+ NanoUI.Backend: UiCursorColResize :: UiCursorKind
+ NanoUI.Backend: UiCursorContextMenu :: UiCursorKind
+ NanoUI.Backend: UiCursorCopy :: UiCursorKind
+ NanoUI.Backend: UiCursorCrosshair :: UiCursorKind
+ NanoUI.Backend: UiCursorDefault :: UiCursorKind
+ NanoUI.Backend: UiCursorEResize :: UiCursorKind
+ NanoUI.Backend: UiCursorEwResize :: UiCursorKind
+ NanoUI.Backend: UiCursorGrab :: UiCursorKind
+ NanoUI.Backend: UiCursorGrabbing :: UiCursorKind
+ NanoUI.Backend: UiCursorHelp :: UiCursorKind
+ NanoUI.Backend: UiCursorHidden :: UiCursorKind
+ NanoUI.Backend: UiCursorMove :: UiCursorKind
+ NanoUI.Backend: UiCursorNResize :: UiCursorKind
+ NanoUI.Backend: UiCursorNeResize :: UiCursorKind
+ NanoUI.Backend: UiCursorNeswResize :: UiCursorKind
+ NanoUI.Backend: UiCursorNotAllowed :: UiCursorKind
+ NanoUI.Backend: UiCursorNsResize :: UiCursorKind
+ NanoUI.Backend: UiCursorNwResize :: UiCursorKind
+ NanoUI.Backend: UiCursorNwseResize :: UiCursorKind
+ NanoUI.Backend: UiCursorPointer :: UiCursorKind
+ NanoUI.Backend: UiCursorProgress :: UiCursorKind
+ NanoUI.Backend: UiCursorRowResize :: UiCursorKind
+ NanoUI.Backend: UiCursorSResize :: UiCursorKind
+ NanoUI.Backend: UiCursorSeResize :: UiCursorKind
+ NanoUI.Backend: UiCursorSwResize :: UiCursorKind
+ NanoUI.Backend: UiCursorText :: UiCursorKind
+ NanoUI.Backend: UiCursorWResize :: UiCursorKind
+ NanoUI.Backend: UiCursorWait :: UiCursorKind
+ NanoUI.Backend: UiCursorZoomIn :: UiCursorKind
+ NanoUI.Backend: UiCursorZoomOut :: UiCursorKind
+ NanoUI.Backend: WindowCapabilities :: Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> WindowCapabilities
+ NanoUI.Backend: WindowHost :: WindowCapabilities -> (Text -> IO ()) -> (RgbaPixels -> IO ()) -> (Maybe Size -> IO ()) -> (Maybe Size -> IO ()) -> (Float -> IO ()) -> (WindowMode -> IO ()) -> (Int -> Int -> IO ()) -> IO () -> (Size -> IO ()) -> IO () -> IO () -> IO () -> WindowHost
+ NanoUI.Backend: WindowState :: Size -> Float -> Maybe (Int, Int) -> Bool -> Bool -> Bool -> Bool -> Bool -> WindowState
+ NanoUI.Backend: [SCustom] :: forall (s :: Symbol). SSymbol s -> SBackend ('Custom s)
+ NanoUI.Backend: [SSdl] :: SBackend 'Sdl
+ NanoUI.Backend: [capNodeEffects] :: ShaderCapabilities -> Bool
+ NanoUI.Backend: [capSurfaceShaders] :: ShaderCapabilities -> Bool
+ NanoUI.Backend: [childKey] :: ChildWindow -> WidgetId
+ NanoUI.Backend: [childOpen] :: ChildWindow -> Var Bool
+ NanoUI.Backend: [childRun] :: ChildWindow -> Context -> Input -> IO ()
+ NanoUI.Backend: [childSettings] :: ChildWindow -> WindowSettings
+ NanoUI.Backend: [cmdClipH] :: DrawCmd -> Float
+ NanoUI.Backend: [cmdClipW] :: DrawCmd -> Float
+ NanoUI.Backend: [cmdClipX] :: DrawCmd -> Float
+ NanoUI.Backend: [cmdClipY] :: DrawCmd -> Float
+ NanoUI.Backend: [cmdIndexCount] :: DrawCmd -> Word32
+ NanoUI.Backend: [cmdIndexOffset] :: DrawCmd -> Word32
+ NanoUI.Backend: [cmdLayer] :: DrawCmd -> Layer
+ NanoUI.Backend: [cmdShader] :: DrawCmd -> Int32
+ NanoUI.Backend: [cmdTextureId] :: DrawCmd -> Int
+ NanoUI.Backend: [compositionCursor] :: Composition -> Int
+ NanoUI.Backend: [compositionSelection] :: Composition -> Int
+ NanoUI.Backend: [compositionText] :: Composition -> Text
+ NanoUI.Backend: [drawClear] :: DrawData -> Color
+ NanoUI.Backend: [drawCommands] :: DrawData -> Vector DrawCmd
+ NanoUI.Backend: [drawEffectSpans] :: DrawData -> SmallArray EffectSpan
+ NanoUI.Backend: [drawIndexCount] :: DrawData -> Int
+ NanoUI.Backend: [drawIndices] :: DrawData -> ForeignPtr Word8
+ NanoUI.Backend: [drawLayerOffsets] :: DrawData -> PrimArray Int
+ NanoUI.Backend: [drawShaderCalls] :: DrawData -> SmallArray ShaderCall
+ NanoUI.Backend: [drawUniformBytes] :: DrawData -> ByteArray
+ NanoUI.Backend: [drawVertexCount] :: DrawData -> Int
+ NanoUI.Backend: [drawVertices] :: DrawData -> ForeignPtr Word8
+ NanoUI.Backend: [dropEventData] :: DropEvent -> Text
+ NanoUI.Backend: [dropEventPos] :: DropEvent -> Maybe V2
+ NanoUI.Backend: [dropEventType] :: DropEvent -> DropType
+ NanoUI.Backend: [edAcquireTarget] :: EffectDriver passHandle -> Int -> Int -> IO (Int, Int, Int)
+ NanoUI.Backend: [edAfterSpanContent] :: EffectDriver passHandle -> Int -> IO ()
+ NanoUI.Backend: [edBindTarget] :: EffectDriver passHandle -> Int -> Bool -> Float -> Float -> IO Bool
+ NanoUI.Backend: [edCompositePass] :: EffectDriver passHandle -> passHandle -> ShaderCall -> EffectPassDraw -> Int -> Int -> IO ()
+ NanoUI.Backend: [edEmitPlain] :: EffectDriver passHandle -> Int -> Int -> Int -> Float -> Float -> Maybe Rect -> Int -> Int -> IO ()
+ NanoUI.Backend: [edFlipY] :: EffectDriver passHandle -> Bool
+ NanoUI.Backend: [edFlush] :: EffectDriver passHandle -> IO ()
+ NanoUI.Backend: [edPreparePasses] :: EffectDriver passHandle -> SmallArray ShaderCall -> IO (Maybe (SmallArray passHandle))
+ NanoUI.Backend: [edReleaseTarget] :: EffectDriver passHandle -> Int -> IO ()
+ NanoUI.Backend: [edScale] :: EffectDriver passHandle -> Float
+ NanoUI.Backend: [epdClip] :: EffectPassDraw -> Maybe Rect
+ NanoUI.Backend: [epdDstH] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdDstW] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdDstX] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdDstY] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdIntermediate] :: EffectPassDraw -> Bool
+ NanoUI.Backend: [epdNodeU0] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdNodeUSpan] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdNodeV0] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdNodeVSpan] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdSrcCapH] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdSrcCapW] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdSrcSlot] :: EffectPassDraw -> Int
+ NanoUI.Backend: [epdU0] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdU1] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdV0] :: EffectPassDraw -> Float
+ NanoUI.Backend: [epdV1] :: EffectPassDraw -> Float
+ NanoUI.Backend: [esBounds] :: EffectSpan -> Rect
+ NanoUI.Backend: [esClip] :: EffectSpan -> Rect
+ NanoUI.Backend: [esCmdEnd] :: EffectSpan -> Int
+ NanoUI.Backend: [esCmdStart] :: EffectSpan -> Int
+ NanoUI.Backend: [esId] :: EffectSpan -> Int
+ NanoUI.Backend: [esLayer] :: EffectSpan -> Layer
+ NanoUI.Backend: [esMargin] :: EffectSpan -> V2
+ NanoUI.Backend: [esParent] :: EffectSpan -> Int
+ NanoUI.Backend: [esPasses] :: EffectSpan -> SmallArray ShaderCall
+ NanoUI.Backend: [fbDrawShaped] :: FontBackend -> Text -> IO (Maybe ShapedGlyphs)
+ NanoUI.Backend: [fbPrepare] :: FontBackend -> Text -> IO FontMetrics
+ NanoUI.Backend: [fmAdvance] :: FontMetrics -> Char -> Float
+ NanoUI.Backend: [fmAscent] :: FontMetrics -> Float
+ NanoUI.Backend: [fmBackend] :: FontMetrics -> Maybe FontBackend
+ NanoUI.Backend: [fmGlyph] :: FontMetrics -> Char -> Maybe GlyphQuad
+ NanoUI.Backend: [fmKerning] :: FontMetrics -> Char -> Char -> Float
+ NanoUI.Backend: [fmLineHeight] :: FontMetrics -> Float
+ NanoUI.Backend: [fmShape] :: FontMetrics -> Text -> Maybe ShapedText
+ NanoUI.Backend: [fmSnapScale] :: FontMetrics -> Float
+ NanoUI.Backend: [gqH] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqU0] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqU1] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqV0] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqV1] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqW] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqX] :: GlyphQuad -> Float
+ NanoUI.Backend: [gqY] :: GlyphQuad -> Float
+ NanoUI.Backend: [hostCapabilities] :: WindowHost -> WindowCapabilities
+ NanoUI.Backend: [hostCenter] :: WindowHost -> IO ()
+ NanoUI.Backend: [hostMaximize] :: WindowHost -> IO ()
+ NanoUI.Backend: [hostMinimize] :: WindowHost -> IO ()
+ NanoUI.Backend: [hostMove] :: WindowHost -> Int -> Int -> IO ()
+ NanoUI.Backend: [hostResize] :: WindowHost -> Size -> IO ()
+ NanoUI.Backend: [hostRestore] :: WindowHost -> IO ()
+ NanoUI.Backend: [hostSetIcon] :: WindowHost -> RgbaPixels -> IO ()
+ NanoUI.Backend: [hostSetMaxSize] :: WindowHost -> Maybe Size -> IO ()
+ NanoUI.Backend: [hostSetMinSize] :: WindowHost -> Maybe Size -> IO ()
+ NanoUI.Backend: [hostSetMode] :: WindowHost -> WindowMode -> IO ()
+ NanoUI.Backend: [hostSetOpacity] :: WindowHost -> Float -> IO ()
+ NanoUI.Backend: [hostSetTitle] :: WindowHost -> Text -> IO ()
+ NanoUI.Backend: [inputButtonsHeld] :: Input -> MouseButtons
+ NanoUI.Backend: [inputButtonsPressed] :: Input -> MouseButtons
+ NanoUI.Backend: [inputButtonsReleased] :: Input -> MouseButtons
+ NanoUI.Backend: [inputChars] :: Input -> Text
+ NanoUI.Backend: [inputComposition] :: Input -> Maybe Composition
+ NanoUI.Backend: [inputDeltaTime] :: Input -> Float
+ NanoUI.Backend: [inputDrops] :: Input -> SmallArray DropEvent
+ NanoUI.Backend: [inputKeysHeld] :: Input -> SmallArray Key
+ NanoUI.Backend: [inputKeysNew] :: Input -> SmallArray Key
+ NanoUI.Backend: [inputKeysReleased] :: Input -> SmallArray Key
+ NanoUI.Backend: [inputKeys] :: Input -> SmallArray Key
+ NanoUI.Backend: [inputModifiers] :: Input -> Modifiers
+ NanoUI.Backend: [inputMouseClicks] :: Input -> Int
+ NanoUI.Backend: [inputMousePos] :: Input -> V2
+ NanoUI.Backend: [inputScroll] :: Input -> V2
+ NanoUI.Backend: [inputWindowRedraw] :: Input -> Bool
+ NanoUI.Backend: [inputWindowSize] :: Input -> Size
+ NanoUI.Backend: [layoutAlignExplicit] :: Layout -> Word8
+ NanoUI.Backend: [layoutAlignX] :: Layout -> AlignX
+ NanoUI.Backend: [layoutAlignY] :: Layout -> AlignY
+ NanoUI.Backend: [layoutAspect] :: Layout -> Float
+ NanoUI.Backend: [layoutDirection] :: Layout -> Direction
+ NanoUI.Backend: [layoutEllipsis] :: Layout -> TextEllipsis
+ NanoUI.Backend: [layoutFlow] :: Layout -> Flow
+ NanoUI.Backend: [layoutFontColor] :: Layout -> Maybe Color
+ NanoUI.Backend: [layoutFontSize] :: Layout -> Float
+ NanoUI.Backend: [layoutFontStyle] :: Layout -> FontStyle
+ NanoUI.Backend: [layoutFontTabular] :: Layout -> Bool
+ NanoUI.Backend: [layoutFontTone] :: Layout -> Maybe Tone
+ NanoUI.Backend: [layoutFontVariant] :: Layout -> FontVariant
+ NanoUI.Backend: [layoutFontWeight] :: Layout -> FontWeight
+ NanoUI.Backend: [layoutGap] :: Layout -> Float
+ NanoUI.Backend: [layoutGridCols] :: Layout -> Int
+ NanoUI.Backend: [layoutGridMinColW] :: Layout -> Float
+ NanoUI.Backend: [layoutHeight] :: Layout -> Sizing
+ NanoUI.Backend: [layoutItemsAlign] :: Layout -> ItemsAlign
+ NanoUI.Backend: [layoutJustify] :: Layout -> Justify
+ NanoUI.Backend: [layoutLineAlign] :: Layout -> LineAlign
+ NanoUI.Backend: [layoutLineGap] :: Layout -> Float
+ NanoUI.Backend: [layoutMaxH] :: Layout -> Float
+ NanoUI.Backend: [layoutMaxW] :: Layout -> Float
+ NanoUI.Backend: [layoutMinH] :: Layout -> Float
+ NanoUI.Backend: [layoutMinW] :: Layout -> Float
+ NanoUI.Backend: [layoutPadding] :: Layout -> Padding
+ NanoUI.Backend: [layoutPin] :: Layout -> Maybe V2
+ NanoUI.Backend: [layoutPointer] :: Layout -> PointerMode
+ NanoUI.Backend: [layoutSingleLine] :: Layout -> Bool
+ NanoUI.Backend: [layoutTextBreak] :: Layout -> TextBreak
+ NanoUI.Backend: [layoutTextDecoration] :: Layout -> TextDecoration
+ NanoUI.Backend: [layoutWidth] :: Layout -> Sizing
+ NanoUI.Backend: [modAlt] :: Modifiers -> Bool
+ NanoUI.Backend: [modCtrl] :: Modifiers -> Bool
+ NanoUI.Backend: [modShift] :: Modifiers -> Bool
+ NanoUI.Backend: [modSuper] :: Modifiers -> Bool
+ NanoUI.Backend: [scHash] :: ShaderCall -> Word64
+ NanoUI.Backend: [scProgram] :: ShaderCall -> ShaderProgram
+ NanoUI.Backend: [scUniformLength] :: ShaderCall -> Int
+ NanoUI.Backend: [scUniformOffset] :: ShaderCall -> Int
+ NanoUI.Backend: [spGlsl150] :: ShaderProgram -> Maybe Text
+ NanoUI.Backend: [spGlslEs300] :: ShaderProgram -> Maybe Text
+ NanoUI.Backend: [spMsl] :: ShaderProgram -> Maybe Text
+ NanoUI.Backend: [spNeedsTex] :: ShaderProgram -> Bool
+ NanoUI.Backend: [spSpirv] :: ShaderProgram -> Maybe ByteString
+ NanoUI.Backend: [spUniformBytes] :: ShaderProgram -> Int
+ NanoUI.Backend: [spUniformLayout] :: ShaderProgram -> [UniformField]
+ NanoUI.Backend: [stAdvance] :: ShapedText -> Float
+ NanoUI.Backend: [stCarets] :: ShapedText -> PrimArray Float
+ NanoUI.Backend: [stInkEnd] :: ShapedText -> Float
+ NanoUI.Backend: [textInputAreaCursor] :: TextInputArea -> Float
+ NanoUI.Backend: [textInputAreaPurpose] :: TextInputArea -> InputPurpose
+ NanoUI.Backend: [textInputAreaRect] :: TextInputArea -> Rect
+ NanoUI.Backend: [wcIcon] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcMaximize] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcMinimize] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcMode] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcMove] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcOpacity] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcResize] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcSizeLimits] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [wcTitle] :: WindowCapabilities -> Bool
+ NanoUI.Backend: [winCloseRequested] :: WindowState -> Bool
+ NanoUI.Backend: [winFocused] :: WindowState -> Bool
+ NanoUI.Backend: [winFullscreen] :: WindowState -> Bool
+ NanoUI.Backend: [winMaximized] :: WindowState -> Bool
+ NanoUI.Backend: [winMinimized] :: WindowState -> Bool
+ NanoUI.Backend: [winPosition] :: WindowState -> Maybe (Int, Int)
+ NanoUI.Backend: [winScale] :: WindowState -> Float
+ NanoUI.Backend: [winSize] :: WindowState -> Size
+ NanoUI.Backend: allWindowCapabilities :: WindowCapabilities
+ NanoUI.Backend: answerScreenshots :: Context -> IO (Maybe RgbaPixels) -> IO ()
+ NanoUI.Backend: answerScreenshotsAfter :: Context -> IO (Maybe RgbaPixels) -> IO () -> IO ()
+ NanoUI.Backend: appendDropEvent :: DropEvent -> SmallArray DropEvent -> SmallArray DropEvent
+ NanoUI.Backend: appendInputKey :: Key -> SmallArray Key -> SmallArray Key
+ NanoUI.Backend: applyComposition :: Text -> Int -> Int -> Input -> Input
+ NanoUI.Backend: applyKey :: Key -> Bool -> Input -> Input
+ NanoUI.Backend: applyMouseButton :: MouseButton -> Bool -> Input -> Input
+ NanoUI.Backend: applyPointerLeave :: Input -> Input
+ NanoUI.Backend: askBackendSession :: forall (b :: Backend). SBackend b -> NanoUI (Maybe (BackendSession b))
+ NanoUI.Backend: askCompact :: Host (Compact a) -> NanoUI (Maybe a)
+ NanoUI.Backend: atlasChanges :: Context -> Int -> IO (Maybe (Int, Int, ForeignPtr Word8, Int, AtlasUpload))
+ NanoUI.Backend: atlasSnapshot :: Context -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))
+ NanoUI.Backend: atlasTextureId :: Int
+ NanoUI.Backend: backdropDimTextureId :: Int
+ NanoUI.Backend: backendSession :: forall (b :: Backend). SBackend b -> Context -> IO (Maybe (BackendSession b))
+ NanoUI.Backend: burstNextIds :: Int -> NanoUI ()
+ NanoUI.Backend: buttonsDelete :: MouseButton -> MouseButtons -> MouseButtons
+ NanoUI.Backend: buttonsFromList :: [MouseButton] -> MouseButtons
+ NanoUI.Backend: buttonsInsert :: MouseButton -> MouseButtons -> MouseButtons
+ NanoUI.Backend: buttonsMember :: MouseButton -> MouseButtons -> Bool
+ NanoUI.Backend: buttonsNull :: MouseButtons -> Bool
+ NanoUI.Backend: buttonsToList :: MouseButtons -> [MouseButton]
+ NanoUI.Backend: cancelTasks :: Context -> IO ()
+ NanoUI.Backend: childView :: ChildWindow -> NanoUI ()
+ NanoUI.Backend: childWindows :: Context -> IO [ChildWindow]
+ NanoUI.Backend: clearDirty :: Context -> IO ()
+ NanoUI.Backend: clearEphemeral :: Input -> Input
+ NanoUI.Backend: clearMeasureCache :: Context -> IO ()
+ NanoUI.Backend: clearWindowClose :: Context -> IO ()
+ NanoUI.Backend: clipPixelEdges :: Float -> Rect -> (Int, Int, Int, Int)
+ NanoUI.Backend: closeWindowHost :: Context -> IO ()
+ NanoUI.Backend: cmdEffectiveClip :: Maybe Rect -> DrawCmd -> Maybe (Maybe Rect)
+ NanoUI.Backend: collectRasterSpans :: Context -> Input -> IO ([(Rect, Text, Color, Color, Rect)], [(Rect, Text, Color, Color, Rect)])
+ NanoUI.Backend: colorToWord32 :: Color -> Word32
+ NanoUI.Backend: compactHost :: Host (Compact a) -> a -> IO (Compact a)
+ NanoUI.Backend: cursorFallback :: UiCursorKind -> UiCursorKind
+ NanoUI.Backend: damageFull :: Context -> IO ()
+ NanoUI.Backend: damageFullNow :: NanoUI ()
+ NanoUI.Backend: damageGroupNow :: [WidgetId] -> DamageBounds -> NanoUI ()
+ NanoUI.Backend: damageIsEmpty :: Damage -> Bool
+ NanoUI.Backend: damageKeyNow :: Int -> DamageBounds -> NanoUI ()
+ NanoUI.Backend: damagePieces :: [Rect] -> [Rect]
+ NanoUI.Backend: damageRectNow :: Rect -> NanoUI ()
+ NanoUI.Backend: damageWidgetNow :: WidgetId -> DamageBounds -> NanoUI ()
+ NanoUI.Backend: data Appearance
+ NanoUI.Backend: data AtlasUpload
+ NanoUI.Backend: data Backend
+ NanoUI.Backend: data ChildWindow
+ NanoUI.Backend: data Compact a
+ NanoUI.Backend: data Composition
+ NanoUI.Backend: data Context
+ NanoUI.Backend: data Damage
+ NanoUI.Backend: data DamageBounds
+ NanoUI.Backend: data DrawCmd
+ NanoUI.Backend: data DrawData
+ NanoUI.Backend: data DropEvent
+ NanoUI.Backend: data DropType
+ NanoUI.Backend: data EffectDriver passHandle
+ NanoUI.Backend: data EffectPassDraw
+ NanoUI.Backend: data EffectSpan
+ NanoUI.Backend: data FontBackend
+ NanoUI.Backend: data FontMetrics
+ NanoUI.Backend: data GlyphQuad
+ NanoUI.Backend: data IdContext
+ NanoUI.Backend: data Input
+ NanoUI.Backend: data InputPurpose
+ NanoUI.Backend: data IntGenCache a
+ NanoUI.Backend: data Key
+ NanoUI.Backend: data Layer
+ NanoUI.Backend: data Layout
+ NanoUI.Backend: data Modifiers
+ NanoUI.Backend: data MouseButton
+ NanoUI.Backend: data MouseButtons
+ NanoUI.Backend: data SBackend (b :: Backend)
+ NanoUI.Backend: data ScrollBarSlot
+ NanoUI.Backend: data ShaderCall
+ NanoUI.Backend: data ShaderCapabilities
+ NanoUI.Backend: data ShaderProgram
+ NanoUI.Backend: data ShapedText
+ NanoUI.Backend: data TextInputArea
+ NanoUI.Backend: data UiCursorKind
+ NanoUI.Backend: data WindowCapabilities
+ NanoUI.Backend: data WindowHost
+ NanoUI.Backend: data WindowState
+ NanoUI.Backend: defaultDamageSlop :: Float
+ NanoUI.Backend: defaultWindowHost :: WindowHost
+ NanoUI.Backend: defaultWindowState :: WindowState
+ NanoUI.Backend: drawCmdCount :: DrawData -> Int
+ NanoUI.Backend: drawCmdElems :: DrawData -> [DrawCmd]
+ NanoUI.Backend: drawCmdNull :: DrawData -> Bool
+ NanoUI.Backend: drawGlyph :: FontMetrics -> Char -> IO (Maybe GlyphQuad)
+ NanoUI.Backend: drawShaped :: FontMetrics -> Text -> IO (Maybe ShapedGlyphs)
+ NanoUI.Backend: drawTextBox :: FontMetrics -> Float -> Float -> Float -> Float -> Text -> Rect
+ NanoUI.Backend: emptyEffectSpans :: SmallArray EffectSpan
+ NanoUI.Backend: emptyInput :: Input
+ NanoUI.Backend: emptyShaderCalls :: SmallArray ShaderCall
+ NanoUI.Backend: emptyUniformBytes :: ByteArray
+ NanoUI.Backend: execEffectSpans :: EffectDriver passHandle -> SmallArray EffectSpan -> Int -> Int -> (Int, Int) -> Float -> Float -> Maybe Rect -> Int -> Int -> IO ()
+ NanoUI.Backend: foldInputKeys :: (a -> Key -> a) -> a -> SmallArray Key -> a
+ NanoUI.Backend: followSystemThemeIO :: Context -> (Maybe Appearance -> Theme) -> IO ()
+ NanoUI.Backend: forDrawCmdsInLayer_ :: Layer -> DrawData -> (DrawCmd -> IO ()) -> IO ()
+ NanoUI.Backend: getExplainLayout :: Context -> IO Bool
+ NanoUI.Backend: getExplainedNode :: Context -> IO (Maybe ExplainedNode)
+ NanoUI.Backend: getFocusId :: Context -> IO WidgetId
+ NanoUI.Backend: getShaderCapabilities :: Context -> IO ShaderCapabilities
+ NanoUI.Backend: getSystemAppearance :: Context -> IO (Maybe Appearance)
+ NanoUI.Backend: getThemeIO :: Context -> IO Theme
+ NanoUI.Backend: getWakeAt :: Context -> IO Double
+ NanoUI.Backend: glyphAtlasPages :: Int
+ NanoUI.Backend: glyphAtlasTextureId :: Int
+ NanoUI.Backend: glyphPageTextureId :: Int -> Int
+ NanoUI.Backend: haloDamageSlop :: Float
+ NanoUI.Backend: hashWidgetId :: WidgetId -> Word64
+ NanoUI.Backend: inBoundThread :: IO a -> IO a
+ NanoUI.Backend: indexSize :: Int
+ NanoUI.Backend: initialIdContext :: IdContext
+ NanoUI.Backend: inputInteracted :: Input -> Input -> Bool
+ NanoUI.Backend: inputKeysFromList :: [Key] -> SmallArray Key
+ NanoUI.Backend: inputKeysNull :: SmallArray Key -> Bool
+ NanoUI.Backend: inputPointerHeld :: Input -> Bool
+ NanoUI.Backend: installWindowHost :: Context -> WindowSettings -> WindowHost -> IO ()
+ NanoUI.Backend: intGenCacheInsert :: IntGenCache a -> Int -> a -> IO ()
+ NanoUI.Backend: intGenCacheLookup :: IntGenCache a -> Int -> IO (Maybe a)
+ NanoUI.Backend: intGenCacheSize :: IntGenCache a -> IO Int
+ NanoUI.Backend: intGenCacheStartFrame :: IntGenCache a -> Int -> IO ()
+ NanoUI.Backend: intGenCacheTouch :: IntGenCache a -> Int -> a -> IO ()
+ NanoUI.Backend: isDirty :: Context -> IO Bool
+ NanoUI.Backend: keypadKey :: Bool -> Char -> Maybe Key
+ NanoUI.Backend: lineWidth :: FontMetrics -> Text -> Float
+ NanoUI.Backend: lineWidthIO :: FontMetrics -> Text -> IO Float
+ NanoUI.Backend: markDirty :: Context -> IO ()
+ NanoUI.Backend: measureTextIO :: FontMetrics -> Text -> IO (Float, Float)
+ NanoUI.Backend: mix64 :: Word64 -> Word64 -> Word64
+ NanoUI.Backend: mixFnv :: Word64 -> Word64 -> Word64
+ NanoUI.Backend: modifiersFromBits :: Bits a => a -> a -> a -> a -> a -> Modifiers
+ NanoUI.Backend: monospaceMetrics :: Float -> FontMetrics
+ NanoUI.Backend: mouseButtonNumber :: Int -> MouseButton
+ NanoUI.Backend: newContext :: IO Context
+ NanoUI.Backend: newIntGenCache :: Int -> IO (IntGenCache a)
+ NanoUI.Backend: newPixelContext :: IO Context
+ NanoUI.Backend: newtype ShapedGlyphs
+ NanoUI.Backend: noButtons :: MouseButtons
+ NanoUI.Backend: noModifiers :: Modifiers
+ NanoUI.Backend: noShaderCapabilities :: ShaderCapabilities
+ NanoUI.Backend: noWindowCapabilities :: WindowCapabilities
+ NanoUI.Backend: onGrid :: Float -> Float -> Float
+ NanoUI.Backend: pixelEdges :: Float -> Rect -> (Int, Int, Int, Int)
+ NanoUI.Backend: prepareFontMetrics :: FontMetrics -> Text -> IO FontMetrics
+ NanoUI.Backend: prepareFontMetricsMany :: FontMetrics -> [Text] -> IO FontMetrics
+ NanoUI.Backend: quitRequested :: Context -> IO Bool
+ NanoUI.Backend: registerImage :: Context -> ImageId -> Int -> Int -> ByteString -> IO Bool
+ NanoUI.Backend: registerImages :: Foldable f => Context -> f (ImageId, Int, Int, ByteString) -> IO Bool
+ NanoUI.Backend: releaseAllKeys :: Input -> Input
+ NanoUI.Backend: releaseImage :: Context -> ImageId -> IO ()
+ NanoUI.Backend: reportWindowState :: Context -> WindowState -> IO ()
+ NanoUI.Backend: requestWakeAfter :: Context -> Double -> IO ()
+ NanoUI.Backend: requestWakeAt :: Context -> Double -> IO ()
+ NanoUI.Backend: requestWindowClose :: Context -> IO Bool
+ NanoUI.Backend: resolveDamageRect :: DamageBounds -> Rect -> Rect
+ NanoUI.Backend: roundHalfUp :: Float -> Int
+ NanoUI.Backend: runFrame :: Context -> Input -> NanoUI a -> IO (a, DrawData, Bool)
+ NanoUI.Backend: runNanoUI :: Context -> Input -> NanoUI a -> IO a
+ NanoUI.Backend: scaleFontMetrics :: Float -> FontMetrics -> FontMetrics
+ NanoUI.Backend: scrollBarGutter :: ScrollBarSlot -> Float -> Float
+ NanoUI.Backend: scrollBarThumbColor :: Style -> Theme -> Color
+ NanoUI.Backend: scrollBarThumbHoverColor :: Style -> Theme -> Color
+ NanoUI.Backend: scrollBarTrackColor :: Style -> Theme -> Color
+ NanoUI.Backend: scrollBarWidth :: Float
+ NanoUI.Backend: setBackendSession :: forall (b :: Backend). Context -> SBackend b -> BackendSession b -> IO ()
+ NanoUI.Backend: setDrawPixelScale :: Context -> Float -> IO ()
+ NanoUI.Backend: setExplainLayout :: Context -> Bool -> IO ()
+ NanoUI.Backend: setShaderCapabilities :: Context -> ShaderCapabilities -> IO ()
+ NanoUI.Backend: setSystemAppearance :: Context -> Maybe Appearance -> IO ()
+ NanoUI.Backend: setThemeIO :: Context -> Theme -> IO ()
+ NanoUI.Backend: setWakeLoop :: Context -> IO () -> IO ()
+ NanoUI.Backend: setWakeLoopChecked :: Context -> IO Bool -> IO ()
+ NanoUI.Backend: shiftClip :: Float -> Float -> Maybe Rect -> Maybe Rect
+ NanoUI.Backend: sizeLimitAt :: Float -> (Int, Int) -> Maybe Size -> (Int, Int)
+ NanoUI.Backend: sliderDamageSlop :: Float
+ NanoUI.Backend: snapDamage :: Float -> Damage -> Damage
+ NanoUI.Backend: spanEffectiveClip :: Maybe Rect -> Rect -> Maybe (Maybe Rect)
+ NanoUI.Backend: syncCursorKind :: IORef UiCursorKind -> (Bool -> IO ()) -> (UiCursorKind -> IO ()) -> UiCursorKind -> IO ()
+ NanoUI.Backend: sysUniformBytes :: Int
+ NanoUI.Backend: takeDamage :: Context -> IO Damage
+ NanoUI.Backend: takeDamagePieces :: Context -> IO [Rect]
+ NanoUI.Backend: textInputArea :: Context -> IO (Maybe TextInputArea)
+ NanoUI.Backend: textNodeFontStyle :: Word64 -> FontStyle
+ NanoUI.Backend: textNodeFontTone :: Word64 -> Maybe Tone
+ NanoUI.Backend: textNodeFontVariant :: Word64 -> FontVariant
+ NanoUI.Backend: textNodeFontWeight :: Word64 -> FontWeight
+ NanoUI.Backend: textNodeTextDecoration :: Word64 -> TextDecoration
+ NanoUI.Backend: textureGlyphPage :: Int -> Int
+ NanoUI.Backend: treeItemPadding :: FontMetrics -> (Float, Float)
+ NanoUI.Backend: type family BackendSession (b :: Backend)
+ NanoUI.Backend: uiCursorKind :: Context -> Input -> IO UiCursorKind
+ NanoUI.Backend: uiFontMetrics :: NanoUI FontMetrics
+ NanoUI.Backend: varChangeCount :: IO Word64
+ NanoUI.Backend: vertexSize :: Int
+ NanoUI.Backend: widgetContentInset :: FontMetrics -> (Float, Float)
+ NanoUI.Backend: widgetId :: HasCallStack => WidgetId
+ NanoUI.Backend: widgetPadding :: FontMetrics -> (Float, Float)
+ NanoUI.Backend: windowMargin :: Float
+ NanoUI.Backend: windowPad :: Padding
+ NanoUI.Backend: withBackendSession :: forall (b :: Backend) a. Context -> SBackend b -> BackendSession b -> IO a -> IO a
+ NanoUI.Backend: withClipboard :: Context -> IO (Maybe Text) -> (Text -> IO Bool) -> Context
+ NanoUI.Backend: withEffectUniforms :: ShaderCall -> ByteArray -> EffectPassDraw -> (Ptr Word8 -> Int -> IO a) -> IO a
+ NanoUI.Backend: withFontMetrics :: Context -> FontMetrics -> Context
+ NanoUI.Backend: withFontResolver :: Context -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Context
+ NanoUI.Backend: withFontSize :: Context -> Float -> Context
+ NanoUI.Backend: withMeasureText :: Context -> (Text -> IO (Float, Float)) -> Context
+ NanoUI.Backend: withMonoFontMetrics :: Context -> FontMetrics -> Context
+ NanoUI.Backend: withTheme :: Context -> Theme -> IO Context
+ NanoUI.Backend: wrapMeasureCache :: Float -> Context -> (Text -> IO (Float, Float)) -> Context
+ NanoUI.Chrome: CaptionClose :: CaptionAction
+ NanoUI.Chrome: CaptionConfig :: Float -> Float -> Float -> Maybe Color -> Float -> CaptionConfig
+ NanoUI.Chrome: CaptionMinimize :: CaptionAction
+ NanoUI.Chrome: CaptionToggleMaximize :: CaptionAction
+ NanoUI.Chrome: GlyphClose :: CaptionGlyph
+ NanoUI.Chrome: GlyphMaximize :: CaptionGlyph
+ NanoUI.Chrome: GlyphMinimize :: CaptionGlyph
+ NanoUI.Chrome: GlyphRestore :: CaptionGlyph
+ NanoUI.Chrome: WindowFrame :: Float -> Float -> Color -> WindowFrame
+ NanoUI.Chrome: [capButtonH] :: CaptionConfig -> Float
+ NanoUI.Chrome: [capButtonW] :: CaptionConfig -> Float
+ NanoUI.Chrome: [capCloseColor] :: CaptionConfig -> Maybe Color
+ NanoUI.Chrome: [capCornerRadius] :: CaptionConfig -> Float
+ NanoUI.Chrome: [capGlyphSize] :: CaptionConfig -> Float
+ NanoUI.Chrome: [frameColor] :: WindowFrame -> Color
+ NanoUI.Chrome: [frameRadius] :: WindowFrame -> Float
+ NanoUI.Chrome: [frameWidth] :: WindowFrame -> Float
+ NanoUI.Chrome: captionBarHeight :: Float
+ NanoUI.Chrome: captionButton :: CaptionConfig -> CaptionGlyph -> NanoUI Response
+ NanoUI.Chrome: captionButtons :: Bool -> NanoUI (Maybe CaptionAction, Rect)
+ NanoUI.Chrome: captionButtonsConfigured :: CaptionConfig -> Bool -> NanoUI (Maybe CaptionAction, Rect)
+ NanoUI.Chrome: data CaptionAction
+ NanoUI.Chrome: data CaptionConfig
+ NanoUI.Chrome: data CaptionGlyph
+ NanoUI.Chrome: data WindowFrame
+ NanoUI.Chrome: defaultCaptionConfig :: CaptionConfig
+ NanoUI.Chrome: defaultWindowFrame :: Color -> WindowFrame
+ NanoUI.Chrome: dragSpans :: Rect -> [Rect] -> [Rect]
+ NanoUI.Chrome: windowFrame :: WindowFrame -> NanoUI a -> NanoUI a
+ NanoUI.Effectful: NanoUI :: Eff NanoUIEs a -> NanoUI a
+ NanoUI.Effectful: [unNanoUI] :: NanoUI a -> Eff NanoUIEs a
+ NanoUI.Effectful: data Ui (a :: Type -> Type) b
+ NanoUI.Effectful: embedNanoUI :: forall (es :: [Effect]) a. Ui :> es => NanoUI a -> Eff es a
+ NanoUI.Effectful: newtype NanoUI a
+ NanoUI.Effectful: runFrameEff :: forall (es :: [Effect]) a. IOE :> es => (forall x. () => Eff es x -> IO x) -> Context -> Input -> Eff (Ui ': es) a -> IO (a, DrawData, Bool)
+ NanoUI.Effectful: runUi :: forall (es :: [Effect]) a. IOE :> es => Context -> Input -> Eff (Ui ': es) a -> Eff es a
+ NanoUI.Effectful: type NanoUIEs = '[Ui, IOE]
+ NanoUI.Effectful: withRunInNanoUI :: forall (es :: [Effect]) a. Ui :> es => ((forall r. () => Eff es r -> NanoUI r) -> NanoUI a) -> Eff es a
+ NanoUI.Input: Composition :: Text -> Int -> Int -> Composition
+ NanoUI.Input: InputNormal :: InputPurpose
+ NanoUI.Input: InputNumeric :: InputPurpose
+ NanoUI.Input: InputSecure :: InputPurpose
+ NanoUI.Input: KeyCapsLock :: Key
+ NanoUI.Input: KeyChar :: Char -> Key
+ NanoUI.Input: KeyF :: Int -> Key
+ NanoUI.Input: KeyInsert :: Key
+ NanoUI.Input: KeyMenu :: Key
+ NanoUI.Input: KeyNumLock :: Key
+ NanoUI.Input: KeyPageDown :: Key
+ NanoUI.Input: KeyPageUp :: Key
+ NanoUI.Input: KeyPause :: Key
+ NanoUI.Input: KeyPrintScreen :: Key
+ NanoUI.Input: KeyScrollLock :: Key
+ NanoUI.Input: KeySpace :: Key
+ NanoUI.Input: MouseBack :: MouseButton
+ NanoUI.Input: MouseForward :: MouseButton
+ NanoUI.Input: MouseMiddle :: MouseButton
+ NanoUI.Input: MouseOther :: Int -> MouseButton
+ NanoUI.Input: UiCursorAlias :: UiCursorKind
+ NanoUI.Input: UiCursorAllScroll :: UiCursorKind
+ NanoUI.Input: UiCursorCell :: UiCursorKind
+ NanoUI.Input: UiCursorColResize :: UiCursorKind
+ NanoUI.Input: UiCursorContextMenu :: UiCursorKind
+ NanoUI.Input: UiCursorCopy :: UiCursorKind
+ NanoUI.Input: UiCursorCrosshair :: UiCursorKind
+ NanoUI.Input: UiCursorEResize :: UiCursorKind
+ NanoUI.Input: UiCursorHelp :: UiCursorKind
+ NanoUI.Input: UiCursorHidden :: UiCursorKind
+ NanoUI.Input: UiCursorMove :: UiCursorKind
+ NanoUI.Input: UiCursorNResize :: UiCursorKind
+ NanoUI.Input: UiCursorNeResize :: UiCursorKind
+ NanoUI.Input: UiCursorNotAllowed :: UiCursorKind
+ NanoUI.Input: UiCursorNwResize :: UiCursorKind
+ NanoUI.Input: UiCursorProgress :: UiCursorKind
+ NanoUI.Input: UiCursorRowResize :: UiCursorKind
+ NanoUI.Input: UiCursorSResize :: UiCursorKind
+ NanoUI.Input: UiCursorSeResize :: UiCursorKind
+ NanoUI.Input: UiCursorSwResize :: UiCursorKind
+ NanoUI.Input: UiCursorWResize :: UiCursorKind
+ NanoUI.Input: UiCursorWait :: UiCursorKind
+ NanoUI.Input: UiCursorZoomIn :: UiCursorKind
+ NanoUI.Input: UiCursorZoomOut :: UiCursorKind
+ NanoUI.Input: [compositionCursor] :: Composition -> Int
+ NanoUI.Input: [compositionSelection] :: Composition -> Int
+ NanoUI.Input: [compositionText] :: Composition -> Text
+ NanoUI.Input: [inputButtonsHeld] :: Input -> MouseButtons
+ NanoUI.Input: [inputButtonsPressed] :: Input -> MouseButtons
+ NanoUI.Input: [inputButtonsReleased] :: Input -> MouseButtons
+ NanoUI.Input: [inputComposition] :: Input -> Maybe Composition
+ NanoUI.Input: [inputKeysHeld] :: Input -> SmallArray Key
+ NanoUI.Input: [inputKeysNew] :: Input -> SmallArray Key
+ NanoUI.Input: [inputKeysReleased] :: Input -> SmallArray Key
+ NanoUI.Input: [modSuper] :: Modifiers -> Bool
+ NanoUI.Input: anyButtonPressed :: Input -> Bool
+ NanoUI.Input: anyButtonReleased :: Input -> Bool
+ NanoUI.Input: applyComposition :: Text -> Int -> Int -> Input -> Input
+ NanoUI.Input: applyKey :: Key -> Bool -> Input -> Input
+ NanoUI.Input: applyPointerLeave :: Input -> Input
+ NanoUI.Input: buttonsDelete :: MouseButton -> MouseButtons -> MouseButtons
+ NanoUI.Input: buttonsFromList :: [MouseButton] -> MouseButtons
+ NanoUI.Input: buttonsInsert :: MouseButton -> MouseButtons -> MouseButtons
+ NanoUI.Input: buttonsMember :: MouseButton -> MouseButtons -> Bool
+ NanoUI.Input: buttonsNull :: MouseButtons -> Bool
+ NanoUI.Input: buttonsToList :: MouseButtons -> [MouseButton]
+ NanoUI.Input: class Pressable a
+ NanoUI.Input: data Composition
+ NanoUI.Input: data InputPurpose
+ NanoUI.Input: data MouseButtons
+ NanoUI.Input: heldIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Input: modJump :: Modifiers -> Bool
+ NanoUI.Input: modMacCommand :: Modifiers -> Bool
+ NanoUI.Input: modPrimary :: Modifiers -> Bool
+ NanoUI.Input: mouseButtonNumber :: Int -> MouseButton
+ NanoUI.Input: noButtons :: MouseButtons
+ NanoUI.Input: noModifiers :: Modifiers
+ NanoUI.Input: pressedIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Input: pressedOnceIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Input: primaryModifiers :: Modifiers
+ NanoUI.Input: releaseAllKeys :: Input -> Input
+ NanoUI.Input: releasedIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Internal.Canvas: CanvasEnv :: Maybe Transform -> Float -> CustomDrawContext -> CanvasEnv
+ NanoUI.Internal.Canvas: CanvasM :: (forall s. () => CanvasEnv -> CanvasBuf s -> ST s a) -> CanvasM a
+ NanoUI.Internal.Canvas: ImageDraw :: Rect -> ImageId -> Rect -> Float -> Color -> Float -> ImageDraw
+ NanoUI.Internal.Canvas: [ceContext] :: CanvasEnv -> CustomDrawContext
+ NanoUI.Internal.Canvas: [ceTolerance] :: CanvasEnv -> Float
+ NanoUI.Internal.Canvas: [ceTransform] :: CanvasEnv -> Maybe Transform
+ NanoUI.Internal.Canvas: [imageAngle] :: ImageDraw -> Float
+ NanoUI.Internal.Canvas: [imageId] :: ImageDraw -> ImageId
+ NanoUI.Internal.Canvas: [imageOpacity] :: ImageDraw -> Float
+ NanoUI.Internal.Canvas: [imageRect] :: ImageDraw -> Rect
+ NanoUI.Internal.Canvas: [imageTint] :: ImageDraw -> Color
+ NanoUI.Internal.Canvas: [imageUV] :: ImageDraw -> Rect
+ NanoUI.Internal.Canvas: data CanvasEnv
+ NanoUI.Internal.Canvas: data ImageDraw
+ NanoUI.Internal.Canvas: drawCheckbox :: Theme -> Rect -> Bool -> CanvasM ()
+ NanoUI.Internal.Canvas: drawCircle :: V2 -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawContext :: CanvasM CustomDrawContext
+ NanoUI.Internal.Canvas: drawImage :: Rect -> ImageId -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawImageUV :: Rect -> ImageId -> Float -> Float -> Float -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawImageWith :: ImageDraw -> CanvasM ()
+ NanoUI.Internal.Canvas: drawLinearGradientH :: Rect -> Color -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawLinearGradientV :: Rect -> Color -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawPath :: Path -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawPathWith :: FillRule -> Path -> Paint -> CanvasM ()
+ NanoUI.Internal.Canvas: drawQuadGradient :: Rect -> Color -> Color -> Color -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawRect :: Rect -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawRoundedRect :: Rect -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawStroke :: V2 -> V2 -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawStrokeAA :: V2 -> V2 -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawStrokeCircle :: V2 -> Float -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawStrokePath :: Path -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawStrokePathWith :: Stroke -> Path -> Paint -> CanvasM ()
+ NanoUI.Internal.Canvas: drawStrokeRoundedRect :: Rect -> Float -> Float -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawText :: V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawTextClipped :: Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawTextClippedWith :: FontMetrics -> TextFont -> TextEllipsis -> Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: drawTextWith :: TextFont -> V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Internal.Canvas: emitOp :: DrawOp -> CanvasM ()
+ NanoUI.Internal.Canvas: emitWith :: (Transform -> Float -> [DrawOp]) -> CanvasM ()
+ NanoUI.Internal.Canvas: imageDraw :: Rect -> ImageId -> ImageDraw
+ NanoUI.Internal.Canvas: instance GHC.Internal.Base.Applicative NanoUI.Internal.Canvas.CanvasM
+ NanoUI.Internal.Canvas: instance GHC.Internal.Base.Functor NanoUI.Internal.Canvas.CanvasM
+ NanoUI.Internal.Canvas: instance GHC.Internal.Base.Monad NanoUI.Internal.Canvas.CanvasM
+ NanoUI.Internal.Canvas: newtype CanvasM a
+ NanoUI.Internal.Canvas: runCanvasFor :: CustomDrawContext -> CanvasM a -> SmallArray DrawOp
+ NanoUI.Internal.Canvas: runCanvasScaled :: CustomDrawContext -> Float -> CanvasM a -> SmallArray DrawOp
+ NanoUI.Internal.Canvas: withClip :: Rect -> CanvasM a -> CanvasM a
+ NanoUI.Internal.Canvas: withTransform :: Transform -> CanvasM a -> CanvasM a
+ NanoUI.Internal.Context: AnimationState :: IntMap Animation -> IntMap Float -> IntSet -> Int -> Bool -> IntSet -> IntSet -> IntSet -> IntSet -> AnimationState
+ NanoUI.Internal.Context: AtlasRegions :: [(Int, Int, Int, Int)] -> AtlasUpload
+ NanoUI.Internal.Context: AtlasWhole :: AtlasUpload
+ NanoUI.Internal.Context: Context :: NodeArena -> DrawArena -> IORef WidgetId -> IORef WidgetId -> IORef (Maybe IntSet) -> IORef WidgetId -> IORef WidgetId -> IORef (Map MouseButton PressPoint) -> IORef WidgetId -> IORef Bool -> IORef (Maybe FocusRequest) -> IORef (Maybe InputMethodRequest) -> IORef WidgetStore -> IORef DamageState -> IORef PrevWalk -> IORef (IntMap Int) -> IORef OverlayState -> IORef AnimationState -> IORef ScrollState -> IORef DrawingCacheState -> IORef (MutableArray RealWorld NodeCustom) -> MutablePrimArray RealWorld Word64 -> IdCursor -> MutablePrimArray RealWorld Word64 -> IORef (IntMap SlotVar) -> FontMetrics -> FontMetrics -> Float -> (Text -> IO (Float, Float)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Maybe (IORef MeasureCache) -> IORef WrapCache -> IORef (IntMap SpanCacheEntry) -> IORef (IntMap WidgetTextCacheEntry) -> IORef DerivedCache -> Held -> Host NativeWindow -> Host SomeBackendSession -> Host Sensors -> Host Paragraphs -> IORef (Map (Int, Int, Int, Word32, (Int, Int, Int, Int)) (ImageId, Int, PrimVar RealWorld Int)) -> IORef (Maybe (LayoutCache, Size, Int)) -> IORef Int -> MetricSource -> IORef (Maybe MetricSource) -> IORef Bool -> IORef DrawReuse -> IORef Bool -> IORef ExplainState -> IORef Theme -> IORef ThemeScopes -> IORef (Maybe Appearance) -> IORef (Maybe (Maybe Appearance -> Theme)) -> ContainerStack -> IORef (MutablePrimArray RealWorld WidgetId) -> PrimVar RealWorld Int -> SpanArena -> SpanArena -> IORef InteractionState -> IORef [(Rect, UiCursorKind)] -> IORef [(Int, Int, UiCursorKind)] -> IO (Maybe Text) -> (Text -> IO Bool) -> ImageAtlas -> IORef (Maybe (IO Bool)) -> IORef Bool -> IORef Bool -> IORef (Maybe ThreadId) -> IORef Double -> IORef [ChildWindow] -> IORef ShaderCapabilities -> IORef (Word32, [Int]) -> Context
+ NanoUI.Internal.Context: CustomDrawContext :: Bool -> Bool -> Bool -> Bool -> Bool -> Theme -> FontMetrics -> CustomDrawContext
+ NanoUI.Internal.Context: CustomDrawingEntry :: Int -> CustomDrawBuild -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind) -> Float -> Bool -> KeyClaim -> CustomDrawingEntry
+ NanoUI.Internal.Context: DamageState :: Bool -> Damage -> [Rect] -> [DamageRequest] -> Size -> PrevFrame -> IntMap (IO Bool) -> DamageState
+ NanoUI.Internal.Context: DrawReuse :: Bool -> Maybe (DrawReuseKey, DrawData) -> DrawReuse
+ NanoUI.Internal.Context: DrawReuseKey :: Size -> Float -> Bool -> Bool -> Int -> WidgetId -> Bool -> WidgetId -> WidgetId -> Word64 -> AtlasToken -> Color -> DrawReuseKey
+ NanoUI.Internal.Context: DrawingCacheState :: IntMap PopupConfig -> IntMap DropdownPopup -> IntMap DrawOpCacheEntry -> IntMap CustomDrawOpCacheEntry -> IntMap DrawFitCache -> [HoverZone] -> DrawingCacheState
+ NanoUI.Internal.Context: DrawingEntry :: Int -> DrawingBuild -> DrawingEntry
+ NanoUI.Internal.Context: DropdownPopup :: WidgetId -> Int -> Bool -> Float -> DropdownPopup
+ NanoUI.Internal.Context: EaseAnim :: Float -> Float -> Float -> Float -> Ease -> Float -> Float -> Animation
+ NanoUI.Internal.Context: EaseCubicBezier :: Float -> Float -> Float -> Float -> Ease
+ NanoUI.Internal.Context: EaseInCubic :: Ease
+ NanoUI.Internal.Context: EaseInOutCubic :: Ease
+ NanoUI.Internal.Context: EaseInOutQuad :: Ease
+ NanoUI.Internal.Context: EaseInQuad :: Ease
+ NanoUI.Internal.Context: EaseLinear :: Ease
+ NanoUI.Internal.Context: EaseOutBack :: Ease
+ NanoUI.Internal.Context: EaseOutCubic :: Ease
+ NanoUI.Internal.Context: EaseOutQuad :: Ease
+ NanoUI.Internal.Context: ExplainState :: Bool -> [(Int, [(Rect, Rect, Int)])] -> Maybe (ExplainedNode, Rect) -> [(Int, Int)] -> ExplainState
+ NanoUI.Internal.Context: ExplainedNode :: Text -> Maybe WidgetId -> Int -> Rect -> Padding -> Sizing -> Sizing -> V2 -> V2 -> Float -> Direction -> Flow -> Maybe V2 -> PointerMode -> ExplainedNode
+ NanoUI.Internal.Context: FocusComposing :: FocusKind
+ NanoUI.Internal.Context: FocusControl :: KeyClaim -> FocusKind
+ NanoUI.Internal.Context: FocusNext :: FocusRequest
+ NanoUI.Internal.Context: FocusNone :: FocusKind
+ NanoUI.Internal.Context: FocusNowhere :: FocusRequest
+ NanoUI.Internal.Context: FocusOn :: WidgetId -> FocusRequest
+ NanoUI.Internal.Context: FocusPrevious :: FocusRequest
+ NanoUI.Internal.Context: FocusTextLine :: FocusKind
+ NanoUI.Internal.Context: FocusTextSelectable :: FocusKind
+ NanoUI.Internal.Context: InputMethodRequest :: WidgetId -> Maybe Rect -> InputPurpose -> InputMethodRequest
+ NanoUI.Internal.Context: InteractionState :: Maybe (WidgetId, DirTag, Float) -> Maybe (WidgetId, DirTag, Rect) -> Maybe TextInputDrag -> Maybe TextFieldClickCell -> Maybe TextInputMenu -> Maybe (WidgetId, TextCommand) -> PointerRoute -> Bool -> Maybe (WidgetId, Float, Float) -> Maybe WindowResizeDrag -> Bool -> FocusKind -> Bool -> Maybe (Composition, WidgetId) -> InteractionState
+ NanoUI.Internal.Context: KeysActivate :: KeyClaim
+ NanoUI.Internal.Context: KeysAll :: KeyClaim
+ NanoUI.Internal.Context: KeysNavigate :: KeyClaim
+ NanoUI.Internal.Context: KeysNone :: KeyClaim
+ NanoUI.Internal.Context: KeysOnly :: [Shortcut] -> KeyClaim
+ NanoUI.Internal.Context: KeysReadOnly :: KeyClaim
+ NanoUI.Internal.Context: KeysType :: KeyClaim
+ NanoUI.Internal.Context: NodeCustom :: Word32 -> Maybe DrawingEntry -> Maybe CustomDrawingEntry -> Maybe CustomMeasureFn -> Maybe ShaderNodeEntry -> Maybe ShaderEffectEntry -> NodeCustom
+ NanoUI.Internal.Context: OverlayState :: Bool -> Bool -> Int -> Bool -> Bool -> IntSet -> IntMap Rect -> [Int] -> OverlayState
+ NanoUI.Internal.Context: PressPoint :: V2 -> Maybe WidgetId -> IntSet -> PressPoint
+ NanoUI.Internal.Context: PrevFrame :: IntMap Rect -> IntMap Rect -> IntMap Rect -> IntMap Word64 -> IntMap Rect -> PrevFrame
+ NanoUI.Internal.Context: PrevWalk :: MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Int -> MutableArray RealWorld Rect -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Word64 -> PrimVar RealWorld Int -> IORef (IntMap Rect) -> PrevWalk
+ NanoUI.Internal.Context: RecordedOp :: Layer -> Rect -> Float -> DrawOp -> RecordedOp
+ NanoUI.Internal.Context: ReqFull :: DamageRequest
+ NanoUI.Internal.Context: ReqKey :: Int -> DamageBounds -> DamageRequest
+ NanoUI.Internal.Context: ReqPeers :: [WidgetId] -> DamageBounds -> DamageRequest
+ NanoUI.Internal.Context: ReqRect :: Rect -> DamageRequest
+ NanoUI.Internal.Context: ReqWidget :: WidgetId -> DamageBounds -> DamageRequest
+ NanoUI.Internal.Context: RouteDropdown :: Int -> PointerRoute
+ NanoUI.Internal.Context: RouteLayer :: Int -> PointerRoute
+ NanoUI.Internal.Context: ScrollAxisX :: ScrollAxes
+ NanoUI.Internal.Context: ScrollAxisXY :: ScrollAxes
+ NanoUI.Internal.Context: ScrollAxisY :: ScrollAxes
+ NanoUI.Internal.Context: ScrollCenter :: ScrollAlign
+ NanoUI.Internal.Context: ScrollEnd :: ScrollAlign
+ NanoUI.Internal.Context: ScrollInstant :: ScrollBehavior
+ NanoUI.Internal.Context: ScrollMetrics :: Rect -> V2 -> V2 -> ScrollAxes -> ScrollMetrics
+ NanoUI.Internal.Context: ScrollNearest :: ScrollAlign
+ NanoUI.Internal.Context: ScrollSmooth :: ScrollBehavior
+ NanoUI.Internal.Context: ScrollStart :: ScrollAlign
+ NanoUI.Internal.Context: ScrollTuning :: Float -> Float -> ScrollTuning
+ NanoUI.Internal.Context: SlotAnchor :: Slot
+ NanoUI.Internal.Context: SlotColorBase :: Slot
+ NanoUI.Internal.Context: SlotCursor :: Slot
+ NanoUI.Internal.Context: SlotDrag :: Slot
+ NanoUI.Internal.Context: SlotDragW :: Slot
+ NanoUI.Internal.Context: SlotDrop :: Slot
+ NanoUI.Internal.Context: SlotDropPos :: Slot
+ NanoUI.Internal.Context: SlotMenuOpen :: Slot
+ NanoUI.Internal.Context: SlotMenuPos :: Slot
+ NanoUI.Internal.Context: SlotNumericHeld :: Slot
+ NanoUI.Internal.Context: SlotNumericRepeat :: Slot
+ NanoUI.Internal.Context: SlotScrollAxes :: Slot
+ NanoUI.Internal.Context: SlotScrollContent :: Slot
+ NanoUI.Internal.Context: SlotScrollCross :: Slot
+ NanoUI.Internal.Context: SlotScrollLinkX :: Slot
+ NanoUI.Internal.Context: SlotScrollLinkY :: Slot
+ NanoUI.Internal.Context: SlotScrollPending :: Slot
+ NanoUI.Internal.Context: SlotScrollRange :: Slot
+ NanoUI.Internal.Context: SlotScrollStep :: Slot
+ NanoUI.Internal.Context: SlotSearchAge :: Slot
+ NanoUI.Internal.Context: SlotSearchCommitted :: Slot
+ NanoUI.Internal.Context: SlotSeen :: Slot
+ NanoUI.Internal.Context: SlotTextAreaAnchorCol :: Slot
+ NanoUI.Internal.Context: SlotTextAreaAnchorRow :: Slot
+ NanoUI.Internal.Context: SlotTextAreaBuffer :: Slot
+ NanoUI.Internal.Context: SlotTextAreaChanged :: Slot
+ NanoUI.Internal.Context: SlotTextAreaLineH :: Slot
+ NanoUI.Internal.Context: SlotTextAreaReveal :: Slot
+ NanoUI.Internal.Context: SlotTextAreaScroll :: Slot
+ NanoUI.Internal.Context: SlotTextAreaText :: Slot
+ NanoUI.Internal.Context: SlotTextAreaViewport :: Slot
+ NanoUI.Internal.Context: SlotTextAreaWidths :: Slot
+ NanoUI.Internal.Context: SlotTextHistory :: Slot
+ NanoUI.Internal.Context: SlotTextInputScroll :: Slot
+ NanoUI.Internal.Context: SlotTextMode :: Slot
+ NanoUI.Internal.Context: SlotTooltipShow :: Slot
+ NanoUI.Internal.Context: SlotWinSize :: Slot
+ NanoUI.Internal.Context: SpanCacheEntry :: Text -> Color -> Color -> Word64 -> Float -> Int -> Int -> Rect -> Float -> Float -> Bool -> Float -> FontMetrics -> SpanLines -> [(Rect, Text, Color, Color)] -> SpanCacheEntry
+ NanoUI.Internal.Context: SpanSingle :: Text -> FontMetrics -> SpanLines
+ NanoUI.Internal.Context: SpanWrapped :: [(Text, FontMetrics)] -> SpanLines
+ NanoUI.Internal.Context: SpringAnim :: Float -> Float -> Float -> SpringParams -> Animation
+ NanoUI.Internal.Context: SpringParams :: Float -> Float -> Float -> SpringParams
+ NanoUI.Internal.Context: TextFieldClickCell :: WidgetId -> Cursor -> TextFieldClickCell
+ NanoUI.Internal.Context: TextInputDrag :: WidgetId -> Cursor -> Int -> TextInputDrag
+ NanoUI.Internal.Context: TextInputMenu :: WidgetId -> V2 -> Rect -> TextInputMenu
+ NanoUI.Internal.Context: WidgetStore :: Int -> IntMap Int -> IntMap Float -> IntMap Double -> IntMap V2 -> IntMap Text -> IntMap IntSet -> IntMap TextBuffer -> IntMap TextDocument -> IntMap (Text, TextDocument) -> IntMap TextHistory -> IntMap EditorMode -> IntMap LineWidths -> IntMap GridState -> IntMap TableState -> IntMap ComboState -> IntMap RichSelection -> IntMap Int -> WidgetStore
+ NanoUI.Internal.Context: WidgetTextCacheEntry :: Int -> Word64 -> Float -> Text -> Float -> Float -> Int -> Maybe WidgetTextPlacement -> WidgetTextCacheEntry
+ NanoUI.Internal.Context: WidgetTextPlacement :: Text -> Float -> Float -> Float -> Float -> WidgetTextPlacement
+ NanoUI.Internal.Context: WindowResizeDrag :: WidgetId -> WindowResizeEdge -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> WindowResizeDrag
+ NanoUI.Internal.Context: WindowResizeEdge :: Int -> Int -> WindowResizeEdge
+ NanoUI.Internal.Context: [asAnimRest] :: AnimationState -> IntMap Float
+ NanoUI.Internal.Context: [asAnimSettled] :: AnimationState -> Bool
+ NanoUI.Internal.Context: [asAnimations] :: AnimationState -> IntMap Animation
+ NanoUI.Internal.Context: [asKeepAlive] :: AnimationState -> IntSet
+ NanoUI.Internal.Context: [asKeepTouched] :: AnimationState -> IntSet
+ NanoUI.Internal.Context: [asRestFrames] :: AnimationState -> Int
+ NanoUI.Internal.Context: [asRestHeld] :: AnimationState -> IntSet
+ NanoUI.Internal.Context: [asViewAnims] :: AnimationState -> IntSet
+ NanoUI.Internal.Context: [asViewTouched] :: AnimationState -> IntSet
+ NanoUI.Internal.Context: [cdcActive] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context: [cdcDisabled] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context: [cdcFocused] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context: [cdcFont] :: CustomDrawContext -> FontMetrics
+ NanoUI.Internal.Context: [cdcHovered] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context: [cdcPressed] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context: [cdcTheme] :: CustomDrawContext -> Theme
+ NanoUI.Internal.Context: [cdrBuild] :: CustomDrawingEntry -> CustomDrawBuild
+ NanoUI.Internal.Context: [cdrContent] :: CustomDrawingEntry -> Int
+ NanoUI.Internal.Context: [cdrCursor] :: CustomDrawingEntry -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind)
+ NanoUI.Internal.Context: [cdrDamageSlop] :: CustomDrawingEntry -> Float
+ NanoUI.Internal.Context: [cdrKeys] :: CustomDrawingEntry -> KeyClaim
+ NanoUI.Internal.Context: [cdrTracked] :: CustomDrawingEntry -> Bool
+ NanoUI.Internal.Context: [ctxActiveId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context: [ctxAnimationState] :: Context -> IORef AnimationState
+ NanoUI.Internal.Context: [ctxBackendSession] :: Context -> Host SomeBackendSession
+ NanoUI.Internal.Context: [ctxChildWindows] :: Context -> IORef [ChildWindow]
+ NanoUI.Internal.Context: [ctxClickedId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context: [ctxClipboardGet] :: Context -> IO (Maybe Text)
+ NanoUI.Internal.Context: [ctxClipboardSet] :: Context -> Text -> IO Bool
+ NanoUI.Internal.Context: [ctxContainerStack] :: Context -> ContainerStack
+ NanoUI.Internal.Context: [ctxCursorRegions] :: Context -> IORef [(Int, Int, UiCursorKind)]
+ NanoUI.Internal.Context: [ctxCursorZones] :: Context -> IORef [(Rect, UiCursorKind)]
+ NanoUI.Internal.Context: [ctxCustomPass] :: Context -> MutablePrimArray RealWorld Word64
+ NanoUI.Internal.Context: [ctxDamageState] :: Context -> IORef DamageState
+ NanoUI.Internal.Context: [ctxDamageWanted] :: Context -> IORef Bool
+ NanoUI.Internal.Context: [ctxDerivedCache] :: Context -> IORef DerivedCache
+ NanoUI.Internal.Context: [ctxDrawArena] :: Context -> DrawArena
+ NanoUI.Internal.Context: [ctxDrawReuse] :: Context -> IORef DrawReuse
+ NanoUI.Internal.Context: [ctxDrawingCache] :: Context -> IORef DrawingCacheState
+ NanoUI.Internal.Context: [ctxEffectNodes] :: Context -> IORef (Word32, [Int])
+ NanoUI.Internal.Context: [ctxExplain] :: Context -> IORef ExplainState
+ NanoUI.Internal.Context: [ctxFocusId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context: [ctxFocusRequest] :: Context -> IORef (Maybe FocusRequest)
+ NanoUI.Internal.Context: [ctxFocusVisible] :: Context -> IORef Bool
+ NanoUI.Internal.Context: [ctxFocusablesCount] :: Context -> PrimVar RealWorld Int
+ NanoUI.Internal.Context: [ctxFocusables] :: Context -> IORef (MutablePrimArray RealWorld WidgetId)
+ NanoUI.Internal.Context: [ctxFontMetrics] :: Context -> FontMetrics
+ NanoUI.Internal.Context: [ctxFontSize] :: Context -> Float
+ NanoUI.Internal.Context: [ctxHeld] :: Context -> Held
+ NanoUI.Internal.Context: [ctxHotId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context: [ctxIdCursor] :: Context -> IdCursor
+ NanoUI.Internal.Context: [ctxImageAtlas] :: Context -> ImageAtlas
+ NanoUI.Internal.Context: [ctxInputMethod] :: Context -> IORef (Maybe InputMethodRequest)
+ NanoUI.Internal.Context: [ctxInteractionState] :: Context -> IORef InteractionState
+ NanoUI.Internal.Context: [ctxLastHotId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context: [ctxLastMetricSource] :: Context -> IORef (Maybe MetricSource)
+ NanoUI.Internal.Context: [ctxLayoutCache] :: Context -> IORef (Maybe (LayoutCache, Size, Int))
+ NanoUI.Internal.Context: [ctxLoopThread] :: Context -> IORef (Maybe ThreadId)
+ NanoUI.Internal.Context: [ctxMeasureCache] :: Context -> Maybe (IORef MeasureCache)
+ NanoUI.Internal.Context: [ctxMeasureText] :: Context -> Text -> IO (Float, Float)
+ NanoUI.Internal.Context: [ctxMetricGen] :: Context -> IORef Int
+ NanoUI.Internal.Context: [ctxMetricSource] :: Context -> MetricSource
+ NanoUI.Internal.Context: [ctxMonoFontMetrics] :: Context -> FontMetrics
+ NanoUI.Internal.Context: [ctxNativeWindow] :: Context -> Host NativeWindow
+ NanoUI.Internal.Context: [ctxNodeArena] :: Context -> NodeArena
+ NanoUI.Internal.Context: [ctxNodeCustom] :: Context -> IORef (MutableArray RealWorld NodeCustom)
+ NanoUI.Internal.Context: [ctxOverlayState] :: Context -> IORef OverlayState
+ NanoUI.Internal.Context: [ctxPaintFull] :: Context -> IORef Bool
+ NanoUI.Internal.Context: [ctxParagraphs] :: Context -> Host Paragraphs
+ NanoUI.Internal.Context: [ctxPointerReach] :: Context -> IORef (Maybe IntSet)
+ NanoUI.Internal.Context: [ctxPressPos] :: Context -> IORef (Map MouseButton PressPoint)
+ NanoUI.Internal.Context: [ctxPrevWalk] :: Context -> IORef PrevWalk
+ NanoUI.Internal.Context: [ctxResolveFont] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)
+ NanoUI.Internal.Context: [ctxResolveMeasure] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)
+ NanoUI.Internal.Context: [ctxScrollState] :: Context -> IORef ScrollState
+ NanoUI.Internal.Context: [ctxSensors] :: Context -> Host Sensors
+ NanoUI.Internal.Context: [ctxShaderCaps] :: Context -> IORef ShaderCapabilities
+ NanoUI.Internal.Context: [ctxSpanBase] :: Context -> SpanArena
+ NanoUI.Internal.Context: [ctxSpanCache] :: Context -> IORef (IntMap SpanCacheEntry)
+ NanoUI.Internal.Context: [ctxSpanOverlay] :: Context -> SpanArena
+ NanoUI.Internal.Context: [ctxStoreOwners] :: Context -> IORef (IntMap Int)
+ NanoUI.Internal.Context: [ctxStore] :: Context -> IORef WidgetStore
+ NanoUI.Internal.Context: [ctxSvgRasters] :: Context -> IORef (Map (Int, Int, Int, Word32, (Int, Int, Int, Int)) (ImageId, Int, PrimVar RealWorld Int))
+ NanoUI.Internal.Context: [ctxSystemAppearance] :: Context -> IORef (Maybe Appearance)
+ NanoUI.Internal.Context: [ctxThemeFor] :: Context -> IORef (Maybe (Maybe Appearance -> Theme))
+ NanoUI.Internal.Context: [ctxThemeScopes] :: Context -> IORef ThemeScopes
+ NanoUI.Internal.Context: [ctxTheme] :: Context -> IORef Theme
+ NanoUI.Internal.Context: [ctxVarFrame] :: Context -> MutablePrimArray RealWorld Word64
+ NanoUI.Internal.Context: [ctxVarSlots] :: Context -> IORef (IntMap SlotVar)
+ NanoUI.Internal.Context: [ctxWakeAt] :: Context -> IORef Double
+ NanoUI.Internal.Context: [ctxWakeLoop] :: Context -> IORef (Maybe (IO Bool))
+ NanoUI.Internal.Context: [ctxWakePending] :: Context -> IORef Bool
+ NanoUI.Internal.Context: [ctxWidgetTextCache] :: Context -> IORef (IntMap WidgetTextCacheEntry)
+ NanoUI.Internal.Context: [ctxWoken] :: Context -> IORef Bool
+ NanoUI.Internal.Context: [ctxWrapCache] :: Context -> IORef WrapCache
+ NanoUI.Internal.Context: [dcsCustomDrawOpCache] :: DrawingCacheState -> IntMap CustomDrawOpCacheEntry
+ NanoUI.Internal.Context: [dcsDrawFitCache] :: DrawingCacheState -> IntMap DrawFitCache
+ NanoUI.Internal.Context: [dcsDrawOpCache] :: DrawingCacheState -> IntMap DrawOpCacheEntry
+ NanoUI.Internal.Context: [dcsDropdowns] :: DrawingCacheState -> IntMap DropdownPopup
+ NanoUI.Internal.Context: [dcsHoverZones] :: DrawingCacheState -> [HoverZone]
+ NanoUI.Internal.Context: [dcsPopupConfigs] :: DrawingCacheState -> IntMap PopupConfig
+ NanoUI.Internal.Context: [deBuild] :: DrawingEntry -> DrawingBuild
+ NanoUI.Internal.Context: [deContent] :: DrawingEntry -> Int
+ NanoUI.Internal.Context: [dpCombo] :: DropdownPopup -> Bool
+ NanoUI.Internal.Context: [dpField] :: DropdownPopup -> WidgetId
+ NanoUI.Internal.Context: [dpPicked] :: DropdownPopup -> Int
+ NanoUI.Internal.Context: [dpScrollX] :: DropdownPopup -> Float
+ NanoUI.Internal.Context: [drLast] :: DrawReuse -> Maybe (DrawReuseKey, DrawData)
+ NanoUI.Internal.Context: [drOn] :: DrawReuse -> Bool
+ NanoUI.Internal.Context: [drkActive] :: DrawReuseKey -> WidgetId
+ NanoUI.Internal.Context: [drkArena] :: DrawReuseKey -> Word64
+ NanoUI.Internal.Context: [drkAtlas] :: DrawReuseKey -> AtlasToken
+ NanoUI.Internal.Context: [drkClear] :: DrawReuseKey -> Color
+ NanoUI.Internal.Context: [drkExternalText] :: DrawReuseKey -> Bool
+ NanoUI.Internal.Context: [drkFocusVisible] :: DrawReuseKey -> Bool
+ NanoUI.Internal.Context: [drkFocus] :: DrawReuseKey -> WidgetId
+ NanoUI.Internal.Context: [drkHot] :: DrawReuseKey -> WidgetId
+ NanoUI.Internal.Context: [drkMetricGen] :: DrawReuseKey -> Int
+ NanoUI.Internal.Context: [drkSize] :: DrawReuseKey -> Size
+ NanoUI.Internal.Context: [drkSnapScale] :: DrawReuseKey -> Float
+ NanoUI.Internal.Context: [drkSquareGeometry] :: DrawReuseKey -> Bool
+ NanoUI.Internal.Context: [dsDamagePieces] :: DamageState -> [Rect]
+ NanoUI.Internal.Context: [dsDamage] :: DamageState -> Damage
+ NanoUI.Internal.Context: [dsDirty] :: DamageState -> Bool
+ NanoUI.Internal.Context: [dsLastWindowSize] :: DamageState -> Size
+ NanoUI.Internal.Context: [dsLayoutReads] :: DamageState -> IntMap (IO Bool)
+ NanoUI.Internal.Context: [dsPrev] :: DamageState -> PrevFrame
+ NanoUI.Internal.Context: [dsRequests] :: DamageState -> [DamageRequest]
+ NanoUI.Internal.Context: [esHover] :: ExplainState -> Maybe (ExplainedNode, Rect)
+ NanoUI.Internal.Context: [esLayers] :: ExplainState -> [(Int, [(Rect, Rect, Int)])]
+ NanoUI.Internal.Context: [esOn] :: ExplainState -> Bool
+ NanoUI.Internal.Context: [esScopes] :: ExplainState -> [(Int, Int)]
+ NanoUI.Internal.Context: [explainedDepth] :: ExplainedNode -> Int
+ NanoUI.Internal.Context: [explainedDirection] :: ExplainedNode -> Direction
+ NanoUI.Internal.Context: [explainedFlow] :: ExplainedNode -> Flow
+ NanoUI.Internal.Context: [explainedGap] :: ExplainedNode -> Float
+ NanoUI.Internal.Context: [explainedHeight] :: ExplainedNode -> Sizing
+ NanoUI.Internal.Context: [explainedKind] :: ExplainedNode -> Text
+ NanoUI.Internal.Context: [explainedMax] :: ExplainedNode -> V2
+ NanoUI.Internal.Context: [explainedMin] :: ExplainedNode -> V2
+ NanoUI.Internal.Context: [explainedPadding] :: ExplainedNode -> Padding
+ NanoUI.Internal.Context: [explainedPin] :: ExplainedNode -> Maybe V2
+ NanoUI.Internal.Context: [explainedPointer] :: ExplainedNode -> PointerMode
+ NanoUI.Internal.Context: [explainedRect] :: ExplainedNode -> Rect
+ NanoUI.Internal.Context: [explainedWidget] :: ExplainedNode -> Maybe WidgetId
+ NanoUI.Internal.Context: [explainedWidth] :: ExplainedNode -> Sizing
+ NanoUI.Internal.Context: [imrCaret] :: InputMethodRequest -> Maybe Rect
+ NanoUI.Internal.Context: [imrPurpose] :: InputMethodRequest -> InputPurpose
+ NanoUI.Internal.Context: [imrWidget] :: InputMethodRequest -> WidgetId
+ NanoUI.Internal.Context: [isColumnResize] :: InteractionState -> Bool
+ NanoUI.Internal.Context: [isComposition] :: InteractionState -> Maybe (Composition, WidgetId)
+ NanoUI.Internal.Context: [isFocusCombo] :: InteractionState -> Bool
+ NanoUI.Internal.Context: [isFocusKind] :: InteractionState -> FocusKind
+ NanoUI.Internal.Context: [isPointerHeld] :: InteractionState -> Bool
+ NanoUI.Internal.Context: [isPointerRoute] :: InteractionState -> PointerRoute
+ NanoUI.Internal.Context: [isScrollDrag] :: InteractionState -> Maybe (WidgetId, DirTag, Float)
+ NanoUI.Internal.Context: [isScrollHover] :: InteractionState -> Maybe (WidgetId, DirTag, Rect)
+ NanoUI.Internal.Context: [isTextEditLastAction] :: InteractionState -> Maybe (WidgetId, TextCommand)
+ NanoUI.Internal.Context: [isTextFieldClickCell] :: InteractionState -> Maybe TextFieldClickCell
+ NanoUI.Internal.Context: [isTextInputDrag] :: InteractionState -> Maybe TextInputDrag
+ NanoUI.Internal.Context: [isTextInputMenu] :: InteractionState -> Maybe TextInputMenu
+ NanoUI.Internal.Context: [isWindowDrag] :: InteractionState -> Maybe (WidgetId, Float, Float)
+ NanoUI.Internal.Context: [isWindowResize] :: InteractionState -> Maybe WindowResizeDrag
+ NanoUI.Internal.Context: [ncCustom] :: NodeCustom -> Maybe CustomDrawingEntry
+ NanoUI.Internal.Context: [ncDrawing] :: NodeCustom -> Maybe DrawingEntry
+ NanoUI.Internal.Context: [ncEffect] :: NodeCustom -> Maybe ShaderEffectEntry
+ NanoUI.Internal.Context: [ncEpoch] :: NodeCustom -> Word32
+ NanoUI.Internal.Context: [ncMeasure] :: NodeCustom -> Maybe CustomMeasureFn
+ NanoUI.Internal.Context: [ncShader] :: NodeCustom -> Maybe ShaderNodeEntry
+ NanoUI.Internal.Context: [osEscapeConsumed] :: OverlayState -> Bool
+ NanoUI.Internal.Context: [osKeysTaken] :: OverlayState -> IntSet
+ NanoUI.Internal.Context: [osModalActive] :: OverlayState -> Bool
+ NanoUI.Internal.Context: [osModalDepth] :: OverlayState -> Int
+ NanoUI.Internal.Context: [osModalWasActive] :: OverlayState -> Bool
+ NanoUI.Internal.Context: [osPrevFloatingOrder] :: OverlayState -> [Int]
+ NanoUI.Internal.Context: [osPrevFloatingRects] :: OverlayState -> IntMap Rect
+ NanoUI.Internal.Context: [osTabConsumed] :: OverlayState -> Bool
+ NanoUI.Internal.Context: [pfClips] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context: [pfEffectRects] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context: [pfHashes] :: PrevFrame -> IntMap Word64
+ NanoUI.Internal.Context: [pfOuterClips] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context: [pfRects] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context: [ppOwner] :: PressPoint -> Maybe WidgetId
+ NanoUI.Internal.Context: [ppPos] :: PressPoint -> V2
+ NanoUI.Internal.Context: [ppReached] :: PressPoint -> IntSet
+ NanoUI.Internal.Context: [pwClips] :: PrevWalk -> MutablePrimArray RealWorld Float
+ NanoUI.Internal.Context: [pwFor] :: PrevWalk -> IORef (IntMap Rect)
+ NanoUI.Internal.Context: [pwHashes] :: PrevWalk -> MutablePrimArray RealWorld Word64
+ NanoUI.Internal.Context: [pwKeys] :: PrevWalk -> MutablePrimArray RealWorld Int
+ NanoUI.Internal.Context: [pwRects] :: PrevWalk -> MutableArray RealWorld Rect
+ NanoUI.Internal.Context: [pwTags] :: PrevWalk -> MutablePrimArray RealWorld Int
+ NanoUI.Internal.Context: [pwValid] :: PrevWalk -> PrimVar RealWorld Int
+ NanoUI.Internal.Context: [sceAlign] :: SpanCacheEntry -> Int
+ NanoUI.Internal.Context: [sceBg] :: SpanCacheEntry -> Color
+ NanoUI.Internal.Context: [sceEffMaxW] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context: [sceFg] :: SpanCacheEntry -> Color
+ NanoUI.Internal.Context: [sceFontSize] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context: [sceFont] :: SpanCacheEntry -> FontMetrics
+ NanoUI.Internal.Context: [sceInset] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context: [sceLaidW] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context: [sceLines] :: SpanCacheEntry -> SpanLines
+ NanoUI.Internal.Context: [sceRect] :: SpanCacheEntry -> Rect
+ NanoUI.Internal.Context: [sceRowChild] :: SpanCacheEntry -> Bool
+ NanoUI.Internal.Context: [sceSpans] :: SpanCacheEntry -> [(Rect, Text, Color, Color)]
+ NanoUI.Internal.Context: [sceStyle] :: SpanCacheEntry -> Word64
+ NanoUI.Internal.Context: [sceText] :: SpanCacheEntry -> Text
+ NanoUI.Internal.Context: [sceWidthTag] :: SpanCacheEntry -> Int
+ NanoUI.Internal.Context: [scrollAxes] :: ScrollMetrics -> ScrollAxes
+ NanoUI.Internal.Context: [scrollOffset] :: ScrollMetrics -> V2
+ NanoUI.Internal.Context: [scrollRange] :: ScrollMetrics -> V2
+ NanoUI.Internal.Context: [scrollSmoothTime] :: ScrollTuning -> Float
+ NanoUI.Internal.Context: [scrollViewport] :: ScrollMetrics -> Rect
+ NanoUI.Internal.Context: [scrollWheelStep] :: ScrollTuning -> Float
+ NanoUI.Internal.Context: [springDamping] :: SpringParams -> Float
+ NanoUI.Internal.Context: [springMass] :: SpringParams -> Float
+ NanoUI.Internal.Context: [springStiffness] :: SpringParams -> Float
+ NanoUI.Internal.Context: [storeBuffer] :: WidgetStore -> IntMap TextBuffer
+ NanoUI.Internal.Context: [storeCombo] :: WidgetStore -> IntMap ComboState
+ NanoUI.Internal.Context: [storeDocument] :: WidgetStore -> IntMap TextDocument
+ NanoUI.Internal.Context: [storeDouble] :: WidgetStore -> IntMap Double
+ NanoUI.Internal.Context: [storeEditorMode] :: WidgetStore -> IntMap EditorMode
+ NanoUI.Internal.Context: [storeFloat] :: WidgetStore -> IntMap Float
+ NanoUI.Internal.Context: [storeGrid] :: WidgetStore -> IntMap GridState
+ NanoUI.Internal.Context: [storeHistory] :: WidgetStore -> IntMap TextHistory
+ NanoUI.Internal.Context: [storeIntSet] :: WidgetStore -> IntMap IntSet
+ NanoUI.Internal.Context: [storeInt] :: WidgetStore -> IntMap Int
+ NanoUI.Internal.Context: [storeLineWidths] :: WidgetStore -> IntMap LineWidths
+ NanoUI.Internal.Context: [storeOpenSelect] :: WidgetStore -> Int
+ NanoUI.Internal.Context: [storePoint] :: WidgetStore -> IntMap V2
+ NanoUI.Internal.Context: [storeQuiet] :: WidgetStore -> IntMap Int
+ NanoUI.Internal.Context: [storeRichSelection] :: WidgetStore -> IntMap RichSelection
+ NanoUI.Internal.Context: [storeTableState] :: WidgetStore -> IntMap TableState
+ NanoUI.Internal.Context: [storeTextDocument] :: WidgetStore -> IntMap (Text, TextDocument)
+ NanoUI.Internal.Context: [storeText] :: WidgetStore -> IntMap Text
+ NanoUI.Internal.Context: [textFieldClickAt] :: TextFieldClickCell -> Cursor
+ NanoUI.Internal.Context: [textFieldClickWidget] :: TextFieldClickCell -> WidgetId
+ NanoUI.Internal.Context: [textInputDragAnchor] :: TextInputDrag -> Cursor
+ NanoUI.Internal.Context: [textInputDragClicks] :: TextInputDrag -> Int
+ NanoUI.Internal.Context: [textInputDragWidget] :: TextInputDrag -> WidgetId
+ NanoUI.Internal.Context: [textInputMenuAt] :: TextInputMenu -> V2
+ NanoUI.Internal.Context: [textInputMenuRect] :: TextInputMenu -> Rect
+ NanoUI.Internal.Context: [textInputMenuWidget] :: TextInputMenu -> WidgetId
+ NanoUI.Internal.Context: [wrdEdge] :: WindowResizeDrag -> WindowResizeEdge
+ NanoUI.Internal.Context: [wrdGrabX] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdGrabY] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdMaxH] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdMaxW] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdMinH] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdMinW] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdStartH] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdStartW] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdStartX] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdStartY] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context: [wrdWidget] :: WindowResizeDrag -> WidgetId
+ NanoUI.Internal.Context: [wtcAlign] :: WidgetTextCacheEntry -> Int
+ NanoUI.Internal.Context: [wtcFontSize] :: WidgetTextCacheEntry -> Float
+ NanoUI.Internal.Context: [wtcHeight] :: WidgetTextCacheEntry -> Float
+ NanoUI.Internal.Context: [wtcNodeType] :: WidgetTextCacheEntry -> Int
+ NanoUI.Internal.Context: [wtcPlacement] :: WidgetTextCacheEntry -> Maybe WidgetTextPlacement
+ NanoUI.Internal.Context: [wtcStyle] :: WidgetTextCacheEntry -> Word64
+ NanoUI.Internal.Context: [wtcText] :: WidgetTextCacheEntry -> Text
+ NanoUI.Internal.Context: [wtcWidth] :: WidgetTextCacheEntry -> Float
+ NanoUI.Internal.Context: activeEffectNodes :: Context -> IO [NodeIdx]
+ NanoUI.Internal.Context: adoptSlot :: Eq a => Field a -> Context -> WidgetId -> a -> IO a
+ NanoUI.Internal.Context: anyAnimating :: Context -> IO Bool
+ NanoUI.Internal.Context: anySelectOpen :: WidgetStore -> Bool
+ NanoUI.Internal.Context: applyEase :: Ease -> Float -> Float
+ NanoUI.Internal.Context: applyPendingScrollOffset :: Context -> WidgetId -> ScrollAxes -> IO ()
+ NanoUI.Internal.Context: applyScrollTarget :: Context -> WidgetId -> ScrollAxes -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: approxEq :: Float -> Float -> Bool
+ NanoUI.Internal.Context: askHostIO :: Host a -> IO (Maybe a)
+ NanoUI.Internal.Context: atlasChanges :: Context -> Int -> IO (Maybe (Int, Int, ForeignPtr Word8, Int, AtlasUpload))
+ NanoUI.Internal.Context: atlasSnapshot :: Context -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))
+ NanoUI.Internal.Context: atlasTextureId :: Int
+ NanoUI.Internal.Context: backendSession :: forall (b :: Backend). SBackend b -> Context -> IO (Maybe (BackendSession b))
+ NanoUI.Internal.Context: beginFrameModal :: Context -> IO ()
+ NanoUI.Internal.Context: beginModal :: Context -> IO ()
+ NanoUI.Internal.Context: beginScrollMetrics :: Context -> IO ()
+ NanoUI.Internal.Context: beginThemeScopes :: Context -> Bool -> IO ()
+ NanoUI.Internal.Context: cacheScrollMetrics :: Context -> WidgetId -> ScrollAxes -> Rect -> V2 -> IO Bool
+ NanoUI.Internal.Context: cachedCustomDrawingOps :: Context -> WidgetId -> Int -> Rect -> IO CustomDrawContext -> CustomDrawBuild -> IO (SmallArray DrawOp)
+ NanoUI.Internal.Context: cachedDrawingOps :: Context -> WidgetId -> Int -> Rect -> DrawingBuild -> IO (SmallArray DrawOp)
+ NanoUI.Internal.Context: cachedWidgetLayout :: Context -> WidgetId -> Double -> Double -> Float -> Int -> Layout -> IO Layout -> IO Layout
+ NanoUI.Internal.Context: cachedWrapText :: Context -> Int -> (Text -> IO Float) -> Text -> Float -> IO WrapResult
+ NanoUI.Internal.Context: clampScrollGlide :: Context -> WidgetId -> V2 -> IO ()
+ NanoUI.Internal.Context: clampScrollOffset :: V2 -> V2 -> V2
+ NanoUI.Internal.Context: clearDirty :: Context -> IO ()
+ NanoUI.Internal.Context: clearMeasureCache :: Context -> IO ()
+ NanoUI.Internal.Context: clearWakeAt :: Context -> IO ()
+ NanoUI.Internal.Context: closeSelects :: WidgetStore -> WidgetStore
+ NanoUI.Internal.Context: currentTheme :: Context -> IO Theme
+ NanoUI.Internal.Context: customDrawingOffNode :: Context -> IO Bool
+ NanoUI.Internal.Context: customMeasureHooks :: Context -> IO Word64
+ NanoUI.Internal.Context: damageFull :: Context -> IO ()
+ NanoUI.Internal.Context: damageKey :: Context -> Int -> DamageBounds -> IO ()
+ NanoUI.Internal.Context: damagePeers :: Context -> [WidgetId] -> DamageBounds -> IO ()
+ NanoUI.Internal.Context: damageRect :: Context -> Rect -> IO ()
+ NanoUI.Internal.Context: damageWidget :: Context -> WidgetId -> DamageBounds -> IO ()
+ NanoUI.Internal.Context: data Animation
+ NanoUI.Internal.Context: data AnimationState
+ NanoUI.Internal.Context: data AtlasUpload
+ NanoUI.Internal.Context: data Context
+ NanoUI.Internal.Context: data CustomDrawContext
+ NanoUI.Internal.Context: data CustomDrawingEntry
+ NanoUI.Internal.Context: data DamageRequest
+ NanoUI.Internal.Context: data DamageState
+ NanoUI.Internal.Context: data DrawReuse
+ NanoUI.Internal.Context: data DrawReuseKey
+ NanoUI.Internal.Context: data DrawingCacheState
+ NanoUI.Internal.Context: data DrawingEntry
+ NanoUI.Internal.Context: data DropdownPopup
+ NanoUI.Internal.Context: data Ease
+ NanoUI.Internal.Context: data ExplainState
+ NanoUI.Internal.Context: data ExplainedNode
+ NanoUI.Internal.Context: data FocusKind
+ NanoUI.Internal.Context: data FocusRequest
+ NanoUI.Internal.Context: data Host a
+ NanoUI.Internal.Context: data InputMethodRequest
+ NanoUI.Internal.Context: data InteractionState
+ NanoUI.Internal.Context: data KeyClaim
+ NanoUI.Internal.Context: data NodeCustom
+ NanoUI.Internal.Context: data OverlayState
+ NanoUI.Internal.Context: data PointerRoute
+ NanoUI.Internal.Context: data PressPoint
+ NanoUI.Internal.Context: data PrevFrame
+ NanoUI.Internal.Context: data PrevWalk
+ NanoUI.Internal.Context: data RecordedOp
+ NanoUI.Internal.Context: data ScrollAlign
+ NanoUI.Internal.Context: data ScrollAxes
+ NanoUI.Internal.Context: data ScrollBehavior
+ NanoUI.Internal.Context: data ScrollMetrics
+ NanoUI.Internal.Context: data ScrollTuning
+ NanoUI.Internal.Context: data Slot
+ NanoUI.Internal.Context: data SpanCacheEntry
+ NanoUI.Internal.Context: data SpanLines
+ NanoUI.Internal.Context: data SpringParams
+ NanoUI.Internal.Context: data TextFieldClickCell
+ NanoUI.Internal.Context: data TextInputDrag
+ NanoUI.Internal.Context: data TextInputMenu
+ NanoUI.Internal.Context: data WidgetStore
+ NanoUI.Internal.Context: data WidgetTextCacheEntry
+ NanoUI.Internal.Context: data WidgetTextPlacement
+ NanoUI.Internal.Context: data WindowResizeDrag
+ NanoUI.Internal.Context: data WindowResizeEdge
+ NanoUI.Internal.Context: defaultScrollTuning :: ScrollTuning
+ NanoUI.Internal.Context: drawRecordedOps :: Context -> IO [RecordedOp]
+ NanoUI.Internal.Context: drawingOpsStale :: Context -> WidgetId -> Int -> Rect -> IO Bool
+ NanoUI.Internal.Context: dropdownPopups :: Context -> IO (IntMap DropdownPopup)
+ NanoUI.Internal.Context: easeSameSpec :: Animation -> Ease -> Float -> Float -> Float -> Bool
+ NanoUI.Internal.Context: emptyPrevFrame :: PrevFrame
+ NanoUI.Internal.Context: enableMeasureCache :: Context -> IO Context
+ NanoUI.Internal.Context: endModal :: Context -> IO ()
+ NanoUI.Internal.Context: ensureMetricCaches :: Context -> IO ()
+ NanoUI.Internal.Context: escapeReserved :: Context -> IO Bool
+ NanoUI.Internal.Context: fieldComposition :: Context -> WidgetId -> IO (Maybe Composition)
+ NanoUI.Internal.Context: floatingLayerAt :: Context -> V2 -> IO Int
+ NanoUI.Internal.Context: followSystemTheme :: Context -> (Maybe Appearance -> Theme) -> IO ()
+ NanoUI.Internal.Context: frameNumber :: Context -> IO Int
+ NanoUI.Internal.Context: getAnimationValue :: Context -> WidgetId -> IO Float
+ NanoUI.Internal.Context: getDrawRecordOps :: Context -> IO Bool
+ NanoUI.Internal.Context: getExplainLayout :: Context -> IO Bool
+ NanoUI.Internal.Context: getExplainedNode :: Context -> IO (Maybe ExplainedNode)
+ NanoUI.Internal.Context: getFocusId :: Context -> IO WidgetId
+ NanoUI.Internal.Context: getFocusVisible :: Context -> IO Bool
+ NanoUI.Internal.Context: getFocusables :: Context -> IO [WidgetId]
+ NanoUI.Internal.Context: getHotId :: Context -> IO WidgetId
+ NanoUI.Internal.Context: getPrevClipRect :: Context -> WidgetId -> IO (Maybe Rect)
+ NanoUI.Internal.Context: getPrevRect :: Context -> WidgetId -> IO (Maybe Rect)
+ NanoUI.Internal.Context: getPrevRectAt :: Context -> NodeIdx -> WidgetId -> IO Rect
+ NanoUI.Internal.Context: getScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)
+ NanoUI.Internal.Context: getScrollOffset :: Context -> WidgetId -> IO Float
+ NanoUI.Internal.Context: getScrollOffset2D :: Context -> WidgetId -> IO V2
+ NanoUI.Internal.Context: getScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> IO V2
+ NanoUI.Internal.Context: getScrollStep :: Context -> WidgetId -> IO Float
+ NanoUI.Internal.Context: getScrollTuning :: Context -> IO ScrollTuning
+ NanoUI.Internal.Context: getShaderCapabilities :: Context -> IO ShaderCapabilities
+ NanoUI.Internal.Context: getStore :: Context -> IO WidgetStore
+ NanoUI.Internal.Context: getSystemAppearance :: Context -> IO (Maybe Appearance)
+ NanoUI.Internal.Context: getTheme :: Context -> IO Theme
+ NanoUI.Internal.Context: getViewAnimationValue :: Context -> WidgetId -> IO Float
+ NanoUI.Internal.Context: getWakeAt :: Context -> IO Double
+ NanoUI.Internal.Context: getsDamage :: Context -> (DamageState -> a) -> IO a
+ NanoUI.Internal.Context: getsInteraction :: Context -> (InteractionState -> a) -> IO a
+ NanoUI.Internal.Context: getsOverlay :: Context -> (OverlayState -> a) -> IO a
+ NanoUI.Internal.Context: hostOrInit :: Host a -> IO a -> IO a
+ NanoUI.Internal.Context: hoverZoneCrossed :: Context -> V2 -> V2 -> IO Bool
+ NanoUI.Internal.Context: intBool :: Int -> Bool
+ NanoUI.Internal.Context: intKey :: WidgetId -> Int
+ NanoUI.Internal.Context: isAnimatingKey :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Context: isDirty :: Context -> IO Bool
+ NanoUI.Internal.Context: isDisabled :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Context: isFocusable :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Context: isInert :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Context: isSelectOpen :: WidgetStore -> Int -> Bool
+ NanoUI.Internal.Context: keepAnimationAlive :: Context -> WidgetId -> IO ()
+ NanoUI.Internal.Context: linkScrollAxes :: Context -> WidgetId -> WidgetId -> IO ()
+ NanoUI.Internal.Context: liveAnimationKeys :: Context -> IO IntSet
+ NanoUI.Internal.Context: lookupAnimation :: Context -> WidgetId -> IO (Maybe Animation)
+ NanoUI.Internal.Context: lookupCustomDamageSlop :: Context -> WidgetId -> IO (Maybe Float)
+ NanoUI.Internal.Context: lookupCustomDrawing :: Context -> WidgetId -> IO (Maybe CustomDrawingEntry)
+ NanoUI.Internal.Context: lookupCustomDrawingAt :: Context -> NodeIdx -> IO (Maybe CustomDrawingEntry)
+ NanoUI.Internal.Context: lookupCustomMeasure :: Context -> WidgetId -> IO (Maybe CustomMeasureFn)
+ NanoUI.Internal.Context: lookupCustomMeasureAt :: Context -> NodeIdx -> IO (Maybe CustomMeasureFn)
+ NanoUI.Internal.Context: lookupDrawFitEnvelope :: Context -> WidgetId -> Float -> Int -> Layout -> IO (Maybe (Double, Double))
+ NanoUI.Internal.Context: lookupDrawingAt :: Context -> NodeIdx -> IO (Maybe DrawingEntry)
+ NanoUI.Internal.Context: lookupImageSize :: Context -> ImageId -> IO (Maybe (Int, Int))
+ NanoUI.Internal.Context: lookupImageUv :: Context -> ImageId -> IO (Maybe (Float, Float, Float, Float))
+ NanoUI.Internal.Context: lookupNodeShaderAt :: Context -> NodeIdx -> IO (Maybe ShaderNodeEntry)
+ NanoUI.Internal.Context: lookupPopupConfig :: Context -> WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))
+ NanoUI.Internal.Context: lookupShaderEffectAt :: Context -> NodeIdx -> IO (Maybe ShaderEffectEntry)
+ NanoUI.Internal.Context: markDirty :: Context -> IO ()
+ NanoUI.Internal.Context: markEscapeConsumed :: Context -> IO ()
+ NanoUI.Internal.Context: markTabConsumed :: Context -> IO ()
+ NanoUI.Internal.Context: modalActive :: Context -> IO Bool
+ NanoUI.Internal.Context: modalDamageFlip :: Context -> IO Bool
+ NanoUI.Internal.Context: modifyDamage :: Context -> (DamageState -> DamageState) -> IO ()
+ NanoUI.Internal.Context: modifyInteraction :: Context -> (InteractionState -> InteractionState) -> IO ()
+ NanoUI.Internal.Context: modifyOverlay :: Context -> (OverlayState -> OverlayState) -> IO ()
+ NanoUI.Internal.Context: modifyStore :: Context -> (WidgetStore -> WidgetStore) -> IO ()
+ NanoUI.Internal.Context: newContext :: IO Context
+ NanoUI.Internal.Context: newHost :: IO (Host a)
+ NanoUI.Internal.Context: newPixelContext :: IO Context
+ NanoUI.Internal.Context: newThemeScopes :: IO ThemeScopes
+ NanoUI.Internal.Context: nodeTheme :: Context -> NodeIdx -> IO Theme
+ NanoUI.Internal.Context: overlayConsumesQuit :: Context -> Input -> IO Bool
+ NanoUI.Internal.Context: placeScrollContent :: Context -> WidgetId -> Float -> Float -> IO ()
+ NanoUI.Internal.Context: pointerBlockedByModal :: Context -> IO Bool
+ NanoUI.Internal.Context: pointerCovered :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Context: pointerHeldOffLayers :: Context -> IO Bool
+ NanoUI.Internal.Context: presetBouncy :: SpringParams
+ NanoUI.Internal.Context: presetSmooth :: SpringParams
+ NanoUI.Internal.Context: presetStiff :: SpringParams
+ NanoUI.Internal.Context: pruneDrawOpCache :: Context -> IO ()
+ NanoUI.Internal.Context: publishLayoutSlots :: Context -> SlotWrites -> IO ()
+ NanoUI.Internal.Context: pushThemeScope :: Context -> Bool -> Theme -> IO Int
+ NanoUI.Internal.Context: readScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)
+ NanoUI.Internal.Context: recordLayoutRead :: Context -> Int -> IO Bool -> IO ()
+ NanoUI.Internal.Context: recordSlot :: Eq a => Field a -> Context -> Int -> a -> IO ()
+ NanoUI.Internal.Context: refreshCustomDrawingOps :: Context -> WidgetId -> Int -> Rect -> CustomDrawContext -> CustomDrawBuild -> IO Bool
+ NanoUI.Internal.Context: registerCustomDrawing :: Context -> WidgetId -> Int -> CustomDrawBuild -> IO ()
+ NanoUI.Internal.Context: registerCustomEntry :: Context -> WidgetId -> CustomDrawingEntry -> IO ()
+ NanoUI.Internal.Context: registerCustomMeasure :: Context -> WidgetId -> CustomMeasureFn -> IO ()
+ NanoUI.Internal.Context: registerDrawing :: Context -> WidgetId -> Int -> DrawingBuild -> IO ()
+ NanoUI.Internal.Context: registerDropdownPopup :: Context -> WidgetId -> DropdownPopup -> IO ()
+ NanoUI.Internal.Context: registerFocusable :: Context -> WidgetId -> IO ()
+ NanoUI.Internal.Context: registerHoverZone :: Context -> Bool -> Rect -> IO ()
+ NanoUI.Internal.Context: registerImage :: Context -> ImageId -> Int -> Int -> ByteString -> IO Bool
+ NanoUI.Internal.Context: registerImages :: Foldable f => Context -> f (ImageId, Int, Int, ByteString) -> IO Bool
+ NanoUI.Internal.Context: registerNodeShaderAt :: Context -> NodeIdx -> ShaderNodeEntry -> IO ()
+ NanoUI.Internal.Context: registerPopupConfig :: Context -> WidgetId -> PopupAnchor -> PopupPlacement -> Float -> IO ()
+ NanoUI.Internal.Context: registerShaderEffectAt :: Context -> NodeIdx -> ShaderEffectEntry -> IO ()
+ NanoUI.Internal.Context: releaseImage :: Context -> ImageId -> IO ()
+ NanoUI.Internal.Context: repaintIfOrphan :: Context -> Int -> IO ()
+ NanoUI.Internal.Context: requestDamage :: Context -> DamageRequest -> IO ()
+ NanoUI.Internal.Context: requestInputMethod :: Context -> WidgetId -> Maybe Rect -> InputPurpose -> IO ()
+ NanoUI.Internal.Context: requestWakeAfter :: Context -> Double -> IO ()
+ NanoUI.Internal.Context: requestWakeAt :: Context -> Double -> IO ()
+ NanoUI.Internal.Context: resetDrawingScopeCache :: Context -> IO ()
+ NanoUI.Internal.Context: resolveScrollStep :: Context -> WidgetId -> IO Float
+ NanoUI.Internal.Context: retainedFrameStale :: Bool -> Input -> (Int, Int, Float) -> (Int, Int, Float) -> Bool
+ NanoUI.Internal.Context: routedInput :: Context -> Int -> Input -> IO Input
+ NanoUI.Internal.Context: scopeRawTheme :: Context -> Int -> IO Theme
+ NanoUI.Internal.Context: scopeTheme :: Context -> Int -> IO Theme
+ NanoUI.Internal.Context: scrollBy :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: scrollGliding :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Context: scrollIntoView :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: scrollPages :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: scrollRectIntoView :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: scrollTargetOffset :: Context -> WidgetId -> V2 -> IO V2
+ NanoUI.Internal.Context: scrollTo :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: scrollToEnd :: Context -> WidgetId -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: scrollToStart :: Context -> WidgetId -> ScrollBehavior -> IO ()
+ NanoUI.Internal.Context: setAnimationValue :: Context -> WidgetId -> Float -> IO ()
+ NanoUI.Internal.Context: setBackendSession :: forall (b :: Backend). Context -> SBackend b -> BackendSession b -> IO ()
+ NanoUI.Internal.Context: setDrawExternalText :: Context -> Bool -> IO ()
+ NanoUI.Internal.Context: setDrawPixelScale :: Context -> Float -> IO ()
+ NanoUI.Internal.Context: setDrawRecordOps :: Context -> Bool -> IO ()
+ NanoUI.Internal.Context: setDrawReuse :: Context -> Bool -> IO ()
+ NanoUI.Internal.Context: setDrawSnapScale :: Context -> Float -> IO ()
+ NanoUI.Internal.Context: setDrawSquareGeometry :: Context -> Bool -> IO ()
+ NanoUI.Internal.Context: setExplainLayout :: Context -> Bool -> IO ()
+ NanoUI.Internal.Context: setHost :: Host a -> a -> IO ()
+ NanoUI.Internal.Context: setScrollOffset :: Context -> WidgetId -> Float -> IO ()
+ NanoUI.Internal.Context: setScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()
+ NanoUI.Internal.Context: setScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> V2 -> IO ()
+ NanoUI.Internal.Context: setScrollOffsetPending :: Context -> WidgetId -> V2 -> IO ()
+ NanoUI.Internal.Context: setScrollStep :: Context -> WidgetId -> Float -> IO ()
+ NanoUI.Internal.Context: setScrollTuning :: Context -> ScrollTuning -> IO ()
+ NanoUI.Internal.Context: setSelectOpen :: WidgetStore -> Int -> Bool -> WidgetStore
+ NanoUI.Internal.Context: setShaderCapabilities :: Context -> ShaderCapabilities -> IO ()
+ NanoUI.Internal.Context: setStore :: Context -> WidgetStore -> IO ()
+ NanoUI.Internal.Context: setSystemAppearance :: Context -> Maybe Appearance -> IO ()
+ NanoUI.Internal.Context: setTheme :: Context -> Theme -> IO ()
+ NanoUI.Internal.Context: setThemeInView :: Context -> Theme -> IO ()
+ NanoUI.Internal.Context: setWakeLoop :: Context -> IO () -> IO ()
+ NanoUI.Internal.Context: setWakeLoopChecked :: Context -> IO Bool -> IO ()
+ NanoUI.Internal.Context: settleLayoutReads :: Context -> IO ()
+ NanoUI.Internal.Context: settleViewTheme :: Context -> Theme -> IO ()
+ NanoUI.Internal.Context: slotKey :: Slot -> Int -> Int
+ NanoUI.Internal.Context: startAnimation :: Context -> WidgetId -> Float -> Float -> Float -> IO ()
+ NanoUI.Internal.Context: startAnimationEase :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> IO ()
+ NanoUI.Internal.Context: startAnimationEaseDelay :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> Float -> IO ()
+ NanoUI.Internal.Context: startSpring :: Context -> WidgetId -> SpringParams -> Float -> IO ()
+ NanoUI.Internal.Context: stepScrollGlides :: Context -> Float -> IO ()
+ NanoUI.Internal.Context: tabConsumed :: Context -> IO Bool
+ NanoUI.Internal.Context: takeAnimSettled :: Context -> IO Bool
+ NanoUI.Internal.Context: takeDamage :: Context -> IO Damage
+ NanoUI.Internal.Context: takeDamagePieces :: Context -> IO [Rect]
+ NanoUI.Internal.Context: takeKeyPress :: Context -> Int -> IO Bool
+ NanoUI.Internal.Context: takeTextEditLastAction :: Context -> IO (Maybe (WidgetId, TextCommand))
+ NanoUI.Internal.Context: takeThreadWake :: Context -> IO ()
+ NanoUI.Internal.Context: takeWakes :: Context -> IO ()
+ NanoUI.Internal.Context: textInputEditActive :: Context -> IO Bool
+ NanoUI.Internal.Context: themeScopesChanged :: Context -> IO Bool
+ NanoUI.Internal.Context: tickAnimations :: Context -> Float -> IO ()
+ NanoUI.Internal.Context: traceDamage :: String -> IO ()
+ NanoUI.Internal.Context: type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp
+ NanoUI.Internal.Context: type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)
+ NanoUI.Internal.Context: wakeAction :: Context -> IO ()
+ NanoUI.Internal.Context: wakeFromThread :: Context -> IO ()
+ NanoUI.Internal.Context: widgetTheme :: Context -> WidgetId -> IO Theme
+ NanoUI.Internal.Context: withBackendSession :: forall (b :: Backend) a. Context -> SBackend b -> BackendSession b -> IO a -> IO a
+ NanoUI.Internal.Context: withClipboard :: Context -> IO (Maybe Text) -> (Text -> IO Bool) -> Context
+ NanoUI.Internal.Context: withFontMetrics :: Context -> FontMetrics -> Context
+ NanoUI.Internal.Context: withFontResolver :: Context -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Context
+ NanoUI.Internal.Context: withFontSize :: Context -> Float -> Context
+ NanoUI.Internal.Context: withFramePaint :: Context -> Bool -> Bool -> IO a -> IO a
+ NanoUI.Internal.Context: withImageSlot :: Context -> ImageId -> IO r -> (Int -> Int -> Float -> Float -> Float -> Float -> IO r) -> IO r
+ NanoUI.Internal.Context: withMeasureText :: Context -> (Text -> IO (Float, Float)) -> Context
+ NanoUI.Internal.Context: withMonoFontMetrics :: Context -> FontMetrics -> Context
+ NanoUI.Internal.Context: withTheme :: Context -> Theme -> IO Context
+ NanoUI.Internal.Context: wrapMeasureCache :: Float -> Context -> (Text -> IO (Float, Float)) -> Context
+ NanoUI.Internal.Context: writeSlot :: Eq a => Field a -> Context -> WidgetId -> Int -> a -> IO ()
+ NanoUI.Internal.Context: writeSlots :: Context -> SlotWrites -> IO ()
+ NanoUI.Internal.Context: writeStoreBool :: Context -> WidgetId -> Bool -> IO ()
+ NanoUI.Internal.Context.Types: AnimationState :: IntMap Animation -> IntMap Float -> IntSet -> Int -> Bool -> IntSet -> IntSet -> IntSet -> IntSet -> AnimationState
+ NanoUI.Internal.Context.Types: ChildWindow :: WidgetId -> Var Bool -> WindowSettings -> (Context -> Input -> IO ()) -> ChildWindow
+ NanoUI.Internal.Context.Types: Context :: NodeArena -> DrawArena -> IORef WidgetId -> IORef WidgetId -> IORef (Maybe IntSet) -> IORef WidgetId -> IORef WidgetId -> IORef (Map MouseButton PressPoint) -> IORef WidgetId -> IORef Bool -> IORef (Maybe FocusRequest) -> IORef (Maybe InputMethodRequest) -> IORef WidgetStore -> IORef DamageState -> IORef PrevWalk -> IORef (IntMap Int) -> IORef OverlayState -> IORef AnimationState -> IORef ScrollState -> IORef DrawingCacheState -> IORef (MutableArray RealWorld NodeCustom) -> MutablePrimArray RealWorld Word64 -> IdCursor -> MutablePrimArray RealWorld Word64 -> IORef (IntMap SlotVar) -> FontMetrics -> FontMetrics -> Float -> (Text -> IO (Float, Float)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> Maybe (IORef MeasureCache) -> IORef WrapCache -> IORef (IntMap SpanCacheEntry) -> IORef (IntMap WidgetTextCacheEntry) -> IORef DerivedCache -> Held -> Host NativeWindow -> Host SomeBackendSession -> Host Sensors -> Host Paragraphs -> IORef (Map (Int, Int, Int, Word32, (Int, Int, Int, Int)) (ImageId, Int, PrimVar RealWorld Int)) -> IORef (Maybe (LayoutCache, Size, Int)) -> IORef Int -> MetricSource -> IORef (Maybe MetricSource) -> IORef Bool -> IORef DrawReuse -> IORef Bool -> IORef ExplainState -> IORef Theme -> IORef ThemeScopes -> IORef (Maybe Appearance) -> IORef (Maybe (Maybe Appearance -> Theme)) -> ContainerStack -> IORef (MutablePrimArray RealWorld WidgetId) -> PrimVar RealWorld Int -> SpanArena -> SpanArena -> IORef InteractionState -> IORef [(Rect, UiCursorKind)] -> IORef [(Int, Int, UiCursorKind)] -> IO (Maybe Text) -> (Text -> IO Bool) -> ImageAtlas -> IORef (Maybe (IO Bool)) -> IORef Bool -> IORef Bool -> IORef (Maybe ThreadId) -> IORef Double -> IORef [ChildWindow] -> IORef ShaderCapabilities -> IORef (Word32, [Int]) -> Context
+ NanoUI.Internal.Context.Types: CustomDrawContext :: Bool -> Bool -> Bool -> Bool -> Bool -> Theme -> FontMetrics -> CustomDrawContext
+ NanoUI.Internal.Context.Types: CustomDrawOpCacheEntry :: Int -> Rect -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> SmallArray DrawOp -> CustomDrawOpCacheEntry
+ NanoUI.Internal.Context.Types: CustomDrawingEntry :: Int -> CustomDrawBuild -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind) -> Float -> Bool -> KeyClaim -> CustomDrawingEntry
+ NanoUI.Internal.Context.Types: DamageState :: Bool -> Damage -> [Rect] -> [DamageRequest] -> Size -> PrevFrame -> IntMap (IO Bool) -> DamageState
+ NanoUI.Internal.Context.Types: DrawFitCache :: Double -> Double -> Float -> Int -> Layout -> Layout -> DrawFitCache
+ NanoUI.Internal.Context.Types: DrawOpCacheEntry :: Int -> Rect -> SmallArray DrawOp -> DrawOpCacheEntry
+ NanoUI.Internal.Context.Types: DrawReuse :: Bool -> Maybe (DrawReuseKey, DrawData) -> DrawReuse
+ NanoUI.Internal.Context.Types: DrawReuseKey :: Size -> Float -> Bool -> Bool -> Int -> WidgetId -> Bool -> WidgetId -> WidgetId -> Word64 -> AtlasToken -> Color -> DrawReuseKey
+ NanoUI.Internal.Context.Types: DrawingCacheState :: IntMap PopupConfig -> IntMap DropdownPopup -> IntMap DrawOpCacheEntry -> IntMap CustomDrawOpCacheEntry -> IntMap DrawFitCache -> [HoverZone] -> DrawingCacheState
+ NanoUI.Internal.Context.Types: DrawingEntry :: Int -> DrawingBuild -> DrawingEntry
+ NanoUI.Internal.Context.Types: DropdownPopup :: WidgetId -> Int -> Bool -> Float -> DropdownPopup
+ NanoUI.Internal.Context.Types: ExplainState :: Bool -> [(Int, [(Rect, Rect, Int)])] -> Maybe (ExplainedNode, Rect) -> [(Int, Int)] -> ExplainState
+ NanoUI.Internal.Context.Types: ExplainedNode :: Text -> Maybe WidgetId -> Int -> Rect -> Padding -> Sizing -> Sizing -> V2 -> V2 -> Float -> Direction -> Flow -> Maybe V2 -> PointerMode -> ExplainedNode
+ NanoUI.Internal.Context.Types: FocusComposing :: FocusKind
+ NanoUI.Internal.Context.Types: FocusControl :: KeyClaim -> FocusKind
+ NanoUI.Internal.Context.Types: FocusNext :: FocusRequest
+ NanoUI.Internal.Context.Types: FocusNone :: FocusKind
+ NanoUI.Internal.Context.Types: FocusNowhere :: FocusRequest
+ NanoUI.Internal.Context.Types: FocusOn :: WidgetId -> FocusRequest
+ NanoUI.Internal.Context.Types: FocusPrevious :: FocusRequest
+ NanoUI.Internal.Context.Types: FocusTextLine :: FocusKind
+ NanoUI.Internal.Context.Types: FocusTextSelectable :: FocusKind
+ NanoUI.Internal.Context.Types: GenCache :: HashMap k v -> Int -> HashMap k v -> GenCache k v
+ NanoUI.Internal.Context.Types: HoverZone :: Rect -> Bool -> HoverZone
+ NanoUI.Internal.Context.Types: InitialMetricSource :: MetricSource
+ NanoUI.Internal.Context.Types: InputMethodRequest :: WidgetId -> Maybe Rect -> InputPurpose -> InputMethodRequest
+ NanoUI.Internal.Context.Types: InteractionState :: Maybe (WidgetId, DirTag, Float) -> Maybe (WidgetId, DirTag, Rect) -> Maybe TextInputDrag -> Maybe TextFieldClickCell -> Maybe TextInputMenu -> Maybe (WidgetId, TextCommand) -> PointerRoute -> Bool -> Maybe (WidgetId, Float, Float) -> Maybe WindowResizeDrag -> Bool -> FocusKind -> Bool -> Maybe (Composition, WidgetId) -> InteractionState
+ NanoUI.Internal.Context.Types: KeysActivate :: KeyClaim
+ NanoUI.Internal.Context.Types: KeysAll :: KeyClaim
+ NanoUI.Internal.Context.Types: KeysNavigate :: KeyClaim
+ NanoUI.Internal.Context.Types: KeysNone :: KeyClaim
+ NanoUI.Internal.Context.Types: KeysOnly :: [Shortcut] -> KeyClaim
+ NanoUI.Internal.Context.Types: KeysReadOnly :: KeyClaim
+ NanoUI.Internal.Context.Types: KeysType :: KeyClaim
+ NanoUI.Internal.Context.Types: MetricSource :: FontMetrics -> FontMetrics -> (Text -> IO (Float, Float)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) -> (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) -> MetricSource
+ NanoUI.Internal.Context.Types: NodeCustom :: Word32 -> Maybe DrawingEntry -> Maybe CustomDrawingEntry -> Maybe CustomMeasureFn -> Maybe ShaderNodeEntry -> Maybe ShaderEffectEntry -> NodeCustom
+ NanoUI.Internal.Context.Types: OverlayState :: Bool -> Bool -> Int -> Bool -> Bool -> IntSet -> IntMap Rect -> [Int] -> OverlayState
+ NanoUI.Internal.Context.Types: PopupConfig :: PopupAnchor -> PopupPlacement -> Float -> PopupConfig
+ NanoUI.Internal.Context.Types: PressPoint :: V2 -> Maybe WidgetId -> IntSet -> PressPoint
+ NanoUI.Internal.Context.Types: PrevFrame :: IntMap Rect -> IntMap Rect -> IntMap Rect -> IntMap Word64 -> IntMap Rect -> PrevFrame
+ NanoUI.Internal.Context.Types: PrevWalk :: MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Int -> MutableArray RealWorld Rect -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Word64 -> PrimVar RealWorld Int -> IORef (IntMap Rect) -> PrevWalk
+ NanoUI.Internal.Context.Types: ReqFull :: DamageRequest
+ NanoUI.Internal.Context.Types: ReqKey :: Int -> DamageBounds -> DamageRequest
+ NanoUI.Internal.Context.Types: ReqPeers :: [WidgetId] -> DamageBounds -> DamageRequest
+ NanoUI.Internal.Context.Types: ReqRect :: Rect -> DamageRequest
+ NanoUI.Internal.Context.Types: ReqWidget :: WidgetId -> DamageBounds -> DamageRequest
+ NanoUI.Internal.Context.Types: RouteDropdown :: Int -> PointerRoute
+ NanoUI.Internal.Context.Types: RouteLayer :: Int -> PointerRoute
+ NanoUI.Internal.Context.Types: ScrollAxisX :: ScrollAxes
+ NanoUI.Internal.Context.Types: ScrollAxisXY :: ScrollAxes
+ NanoUI.Internal.Context.Types: ScrollAxisY :: ScrollAxes
+ NanoUI.Internal.Context.Types: ScrollGlide :: WidgetId -> V2 -> ScrollAxes -> ScrollGlide
+ NanoUI.Internal.Context.Types: ScrollState :: ScrollTuning -> IntMap ScrollGlide -> IntSet -> IntMap ScrollView -> ScrollState
+ NanoUI.Internal.Context.Types: ScrollTuning :: Float -> Float -> ScrollTuning
+ NanoUI.Internal.Context.Types: ScrollView :: Rect -> V2 -> ScrollView
+ NanoUI.Internal.Context.Types: SpanCacheEntry :: Text -> Color -> Color -> Word64 -> Float -> Int -> Int -> Rect -> Float -> Float -> Bool -> Float -> FontMetrics -> SpanLines -> [(Rect, Text, Color, Color)] -> SpanCacheEntry
+ NanoUI.Internal.Context.Types: SpanSingle :: Text -> FontMetrics -> SpanLines
+ NanoUI.Internal.Context.Types: SpanWrapped :: [(Text, FontMetrics)] -> SpanLines
+ NanoUI.Internal.Context.Types: TextFieldClickCell :: WidgetId -> Cursor -> TextFieldClickCell
+ NanoUI.Internal.Context.Types: TextInputDrag :: WidgetId -> Cursor -> Int -> TextInputDrag
+ NanoUI.Internal.Context.Types: TextInputMenu :: WidgetId -> V2 -> Rect -> TextInputMenu
+ NanoUI.Internal.Context.Types: ThemeScopes :: Int -> SmallMutableArray RealWorld Theme -> SmallMutableArray RealWorld Theme -> Int -> SmallMutableArray RealWorld Theme -> Bool -> Bool -> Word64 -> ThemeScopes
+ NanoUI.Internal.Context.Types: WidgetTextCacheEntry :: Int -> Word64 -> Float -> Text -> Float -> Float -> Int -> Maybe WidgetTextPlacement -> WidgetTextCacheEntry
+ NanoUI.Internal.Context.Types: WidgetTextPlacement :: Text -> Float -> Float -> Float -> Float -> WidgetTextPlacement
+ NanoUI.Internal.Context.Types: WindowResizeDrag :: WidgetId -> WindowResizeEdge -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> WindowResizeDrag
+ NanoUI.Internal.Context.Types: WindowResizeEdge :: Int -> Int -> WindowResizeEdge
+ NanoUI.Internal.Context.Types: WrapCache :: Int -> GenCache (Text, Int) [WrapResult] -> WrapCache
+ NanoUI.Internal.Context.Types: [asAnimRest] :: AnimationState -> IntMap Float
+ NanoUI.Internal.Context.Types: [asAnimSettled] :: AnimationState -> Bool
+ NanoUI.Internal.Context.Types: [asAnimations] :: AnimationState -> IntMap Animation
+ NanoUI.Internal.Context.Types: [asKeepAlive] :: AnimationState -> IntSet
+ NanoUI.Internal.Context.Types: [asKeepTouched] :: AnimationState -> IntSet
+ NanoUI.Internal.Context.Types: [asRestFrames] :: AnimationState -> Int
+ NanoUI.Internal.Context.Types: [asRestHeld] :: AnimationState -> IntSet
+ NanoUI.Internal.Context.Types: [asViewAnims] :: AnimationState -> IntSet
+ NanoUI.Internal.Context.Types: [asViewTouched] :: AnimationState -> IntSet
+ NanoUI.Internal.Context.Types: [cdcActive] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context.Types: [cdcDisabled] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context.Types: [cdcFocused] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context.Types: [cdcFont] :: CustomDrawContext -> FontMetrics
+ NanoUI.Internal.Context.Types: [cdcHovered] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context.Types: [cdcPressed] :: CustomDrawContext -> Bool
+ NanoUI.Internal.Context.Types: [cdcTheme] :: CustomDrawContext -> Theme
+ NanoUI.Internal.Context.Types: [cdeActive] :: CustomDrawOpCacheEntry -> Bool
+ NanoUI.Internal.Context.Types: [cdeBounds] :: CustomDrawOpCacheEntry -> Rect
+ NanoUI.Internal.Context.Types: [cdeContent] :: CustomDrawOpCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [cdeDisabled] :: CustomDrawOpCacheEntry -> Bool
+ NanoUI.Internal.Context.Types: [cdeFocused] :: CustomDrawOpCacheEntry -> Bool
+ NanoUI.Internal.Context.Types: [cdeGen] :: CustomDrawOpCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [cdeHovered] :: CustomDrawOpCacheEntry -> Bool
+ NanoUI.Internal.Context.Types: [cdeOps] :: CustomDrawOpCacheEntry -> SmallArray DrawOp
+ NanoUI.Internal.Context.Types: [cdePressed] :: CustomDrawOpCacheEntry -> Bool
+ NanoUI.Internal.Context.Types: [cdrBuild] :: CustomDrawingEntry -> CustomDrawBuild
+ NanoUI.Internal.Context.Types: [cdrContent] :: CustomDrawingEntry -> Int
+ NanoUI.Internal.Context.Types: [cdrCursor] :: CustomDrawingEntry -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind)
+ NanoUI.Internal.Context.Types: [cdrDamageSlop] :: CustomDrawingEntry -> Float
+ NanoUI.Internal.Context.Types: [cdrKeys] :: CustomDrawingEntry -> KeyClaim
+ NanoUI.Internal.Context.Types: [cdrTracked] :: CustomDrawingEntry -> Bool
+ NanoUI.Internal.Context.Types: [childKey] :: ChildWindow -> WidgetId
+ NanoUI.Internal.Context.Types: [childOpen] :: ChildWindow -> Var Bool
+ NanoUI.Internal.Context.Types: [childRun] :: ChildWindow -> Context -> Input -> IO ()
+ NanoUI.Internal.Context.Types: [childSettings] :: ChildWindow -> WindowSettings
+ NanoUI.Internal.Context.Types: [ctxActiveId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context.Types: [ctxAnimationState] :: Context -> IORef AnimationState
+ NanoUI.Internal.Context.Types: [ctxBackendSession] :: Context -> Host SomeBackendSession
+ NanoUI.Internal.Context.Types: [ctxChildWindows] :: Context -> IORef [ChildWindow]
+ NanoUI.Internal.Context.Types: [ctxClickedId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context.Types: [ctxClipboardGet] :: Context -> IO (Maybe Text)
+ NanoUI.Internal.Context.Types: [ctxClipboardSet] :: Context -> Text -> IO Bool
+ NanoUI.Internal.Context.Types: [ctxContainerStack] :: Context -> ContainerStack
+ NanoUI.Internal.Context.Types: [ctxCursorRegions] :: Context -> IORef [(Int, Int, UiCursorKind)]
+ NanoUI.Internal.Context.Types: [ctxCursorZones] :: Context -> IORef [(Rect, UiCursorKind)]
+ NanoUI.Internal.Context.Types: [ctxCustomPass] :: Context -> MutablePrimArray RealWorld Word64
+ NanoUI.Internal.Context.Types: [ctxDamageState] :: Context -> IORef DamageState
+ NanoUI.Internal.Context.Types: [ctxDamageWanted] :: Context -> IORef Bool
+ NanoUI.Internal.Context.Types: [ctxDerivedCache] :: Context -> IORef DerivedCache
+ NanoUI.Internal.Context.Types: [ctxDrawArena] :: Context -> DrawArena
+ NanoUI.Internal.Context.Types: [ctxDrawReuse] :: Context -> IORef DrawReuse
+ NanoUI.Internal.Context.Types: [ctxDrawingCache] :: Context -> IORef DrawingCacheState
+ NanoUI.Internal.Context.Types: [ctxEffectNodes] :: Context -> IORef (Word32, [Int])
+ NanoUI.Internal.Context.Types: [ctxExplain] :: Context -> IORef ExplainState
+ NanoUI.Internal.Context.Types: [ctxFocusId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context.Types: [ctxFocusRequest] :: Context -> IORef (Maybe FocusRequest)
+ NanoUI.Internal.Context.Types: [ctxFocusVisible] :: Context -> IORef Bool
+ NanoUI.Internal.Context.Types: [ctxFocusablesCount] :: Context -> PrimVar RealWorld Int
+ NanoUI.Internal.Context.Types: [ctxFocusables] :: Context -> IORef (MutablePrimArray RealWorld WidgetId)
+ NanoUI.Internal.Context.Types: [ctxFontMetrics] :: Context -> FontMetrics
+ NanoUI.Internal.Context.Types: [ctxFontSize] :: Context -> Float
+ NanoUI.Internal.Context.Types: [ctxHeld] :: Context -> Held
+ NanoUI.Internal.Context.Types: [ctxHotId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context.Types: [ctxIdCursor] :: Context -> IdCursor
+ NanoUI.Internal.Context.Types: [ctxImageAtlas] :: Context -> ImageAtlas
+ NanoUI.Internal.Context.Types: [ctxInputMethod] :: Context -> IORef (Maybe InputMethodRequest)
+ NanoUI.Internal.Context.Types: [ctxInteractionState] :: Context -> IORef InteractionState
+ NanoUI.Internal.Context.Types: [ctxLastHotId] :: Context -> IORef WidgetId
+ NanoUI.Internal.Context.Types: [ctxLastMetricSource] :: Context -> IORef (Maybe MetricSource)
+ NanoUI.Internal.Context.Types: [ctxLayoutCache] :: Context -> IORef (Maybe (LayoutCache, Size, Int))
+ NanoUI.Internal.Context.Types: [ctxLoopThread] :: Context -> IORef (Maybe ThreadId)
+ NanoUI.Internal.Context.Types: [ctxMeasureCache] :: Context -> Maybe (IORef MeasureCache)
+ NanoUI.Internal.Context.Types: [ctxMeasureText] :: Context -> Text -> IO (Float, Float)
+ NanoUI.Internal.Context.Types: [ctxMetricGen] :: Context -> IORef Int
+ NanoUI.Internal.Context.Types: [ctxMetricSource] :: Context -> MetricSource
+ NanoUI.Internal.Context.Types: [ctxMonoFontMetrics] :: Context -> FontMetrics
+ NanoUI.Internal.Context.Types: [ctxNativeWindow] :: Context -> Host NativeWindow
+ NanoUI.Internal.Context.Types: [ctxNodeArena] :: Context -> NodeArena
+ NanoUI.Internal.Context.Types: [ctxNodeCustom] :: Context -> IORef (MutableArray RealWorld NodeCustom)
+ NanoUI.Internal.Context.Types: [ctxOverlayState] :: Context -> IORef OverlayState
+ NanoUI.Internal.Context.Types: [ctxPaintFull] :: Context -> IORef Bool
+ NanoUI.Internal.Context.Types: [ctxParagraphs] :: Context -> Host Paragraphs
+ NanoUI.Internal.Context.Types: [ctxPointerReach] :: Context -> IORef (Maybe IntSet)
+ NanoUI.Internal.Context.Types: [ctxPressPos] :: Context -> IORef (Map MouseButton PressPoint)
+ NanoUI.Internal.Context.Types: [ctxPrevWalk] :: Context -> IORef PrevWalk
+ NanoUI.Internal.Context.Types: [ctxResolveFont] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)
+ NanoUI.Internal.Context.Types: [ctxResolveMeasure] :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)
+ NanoUI.Internal.Context.Types: [ctxScrollState] :: Context -> IORef ScrollState
+ NanoUI.Internal.Context.Types: [ctxSensors] :: Context -> Host Sensors
+ NanoUI.Internal.Context.Types: [ctxShaderCaps] :: Context -> IORef ShaderCapabilities
+ NanoUI.Internal.Context.Types: [ctxSpanBase] :: Context -> SpanArena
+ NanoUI.Internal.Context.Types: [ctxSpanCache] :: Context -> IORef (IntMap SpanCacheEntry)
+ NanoUI.Internal.Context.Types: [ctxSpanOverlay] :: Context -> SpanArena
+ NanoUI.Internal.Context.Types: [ctxStoreOwners] :: Context -> IORef (IntMap Int)
+ NanoUI.Internal.Context.Types: [ctxStore] :: Context -> IORef WidgetStore
+ NanoUI.Internal.Context.Types: [ctxSvgRasters] :: Context -> IORef (Map (Int, Int, Int, Word32, (Int, Int, Int, Int)) (ImageId, Int, PrimVar RealWorld Int))
+ NanoUI.Internal.Context.Types: [ctxSystemAppearance] :: Context -> IORef (Maybe Appearance)
+ NanoUI.Internal.Context.Types: [ctxThemeFor] :: Context -> IORef (Maybe (Maybe Appearance -> Theme))
+ NanoUI.Internal.Context.Types: [ctxThemeScopes] :: Context -> IORef ThemeScopes
+ NanoUI.Internal.Context.Types: [ctxTheme] :: Context -> IORef Theme
+ NanoUI.Internal.Context.Types: [ctxVarFrame] :: Context -> MutablePrimArray RealWorld Word64
+ NanoUI.Internal.Context.Types: [ctxVarSlots] :: Context -> IORef (IntMap SlotVar)
+ NanoUI.Internal.Context.Types: [ctxWakeAt] :: Context -> IORef Double
+ NanoUI.Internal.Context.Types: [ctxWakeLoop] :: Context -> IORef (Maybe (IO Bool))
+ NanoUI.Internal.Context.Types: [ctxWakePending] :: Context -> IORef Bool
+ NanoUI.Internal.Context.Types: [ctxWidgetTextCache] :: Context -> IORef (IntMap WidgetTextCacheEntry)
+ NanoUI.Internal.Context.Types: [ctxWoken] :: Context -> IORef Bool
+ NanoUI.Internal.Context.Types: [ctxWrapCache] :: Context -> IORef WrapCache
+ NanoUI.Internal.Context.Types: [dcsCustomDrawOpCache] :: DrawingCacheState -> IntMap CustomDrawOpCacheEntry
+ NanoUI.Internal.Context.Types: [dcsDrawFitCache] :: DrawingCacheState -> IntMap DrawFitCache
+ NanoUI.Internal.Context.Types: [dcsDrawOpCache] :: DrawingCacheState -> IntMap DrawOpCacheEntry
+ NanoUI.Internal.Context.Types: [dcsDropdowns] :: DrawingCacheState -> IntMap DropdownPopup
+ NanoUI.Internal.Context.Types: [dcsHoverZones] :: DrawingCacheState -> [HoverZone]
+ NanoUI.Internal.Context.Types: [dcsPopupConfigs] :: DrawingCacheState -> IntMap PopupConfig
+ NanoUI.Internal.Context.Types: [deBuild] :: DrawingEntry -> DrawingBuild
+ NanoUI.Internal.Context.Types: [deContent] :: DrawingEntry -> Int
+ NanoUI.Internal.Context.Types: [dfcContent] :: DrawFitCache -> Int
+ NanoUI.Internal.Context.Types: [dfcDh] :: DrawFitCache -> Double
+ NanoUI.Internal.Context.Types: [dfcDw] :: DrawFitCache -> Double
+ NanoUI.Internal.Context.Types: [dfcIn] :: DrawFitCache -> Layout
+ NanoUI.Internal.Context.Types: [dfcLh] :: DrawFitCache -> Float
+ NanoUI.Internal.Context.Types: [dfcOut] :: DrawFitCache -> Layout
+ NanoUI.Internal.Context.Types: [doeBounds] :: DrawOpCacheEntry -> Rect
+ NanoUI.Internal.Context.Types: [doeContent] :: DrawOpCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [doeOps] :: DrawOpCacheEntry -> SmallArray DrawOp
+ NanoUI.Internal.Context.Types: [dpCombo] :: DropdownPopup -> Bool
+ NanoUI.Internal.Context.Types: [dpField] :: DropdownPopup -> WidgetId
+ NanoUI.Internal.Context.Types: [dpPicked] :: DropdownPopup -> Int
+ NanoUI.Internal.Context.Types: [dpScrollX] :: DropdownPopup -> Float
+ NanoUI.Internal.Context.Types: [drLast] :: DrawReuse -> Maybe (DrawReuseKey, DrawData)
+ NanoUI.Internal.Context.Types: [drOn] :: DrawReuse -> Bool
+ NanoUI.Internal.Context.Types: [drkActive] :: DrawReuseKey -> WidgetId
+ NanoUI.Internal.Context.Types: [drkArena] :: DrawReuseKey -> Word64
+ NanoUI.Internal.Context.Types: [drkAtlas] :: DrawReuseKey -> AtlasToken
+ NanoUI.Internal.Context.Types: [drkClear] :: DrawReuseKey -> Color
+ NanoUI.Internal.Context.Types: [drkExternalText] :: DrawReuseKey -> Bool
+ NanoUI.Internal.Context.Types: [drkFocusVisible] :: DrawReuseKey -> Bool
+ NanoUI.Internal.Context.Types: [drkFocus] :: DrawReuseKey -> WidgetId
+ NanoUI.Internal.Context.Types: [drkHot] :: DrawReuseKey -> WidgetId
+ NanoUI.Internal.Context.Types: [drkMetricGen] :: DrawReuseKey -> Int
+ NanoUI.Internal.Context.Types: [drkSize] :: DrawReuseKey -> Size
+ NanoUI.Internal.Context.Types: [drkSnapScale] :: DrawReuseKey -> Float
+ NanoUI.Internal.Context.Types: [drkSquareGeometry] :: DrawReuseKey -> Bool
+ NanoUI.Internal.Context.Types: [dsDamagePieces] :: DamageState -> [Rect]
+ NanoUI.Internal.Context.Types: [dsDamage] :: DamageState -> Damage
+ NanoUI.Internal.Context.Types: [dsDirty] :: DamageState -> Bool
+ NanoUI.Internal.Context.Types: [dsLastWindowSize] :: DamageState -> Size
+ NanoUI.Internal.Context.Types: [dsLayoutReads] :: DamageState -> IntMap (IO Bool)
+ NanoUI.Internal.Context.Types: [dsPrev] :: DamageState -> PrevFrame
+ NanoUI.Internal.Context.Types: [dsRequests] :: DamageState -> [DamageRequest]
+ NanoUI.Internal.Context.Types: [esHover] :: ExplainState -> Maybe (ExplainedNode, Rect)
+ NanoUI.Internal.Context.Types: [esLayers] :: ExplainState -> [(Int, [(Rect, Rect, Int)])]
+ NanoUI.Internal.Context.Types: [esOn] :: ExplainState -> Bool
+ NanoUI.Internal.Context.Types: [esScopes] :: ExplainState -> [(Int, Int)]
+ NanoUI.Internal.Context.Types: [explainedDepth] :: ExplainedNode -> Int
+ NanoUI.Internal.Context.Types: [explainedDirection] :: ExplainedNode -> Direction
+ NanoUI.Internal.Context.Types: [explainedFlow] :: ExplainedNode -> Flow
+ NanoUI.Internal.Context.Types: [explainedGap] :: ExplainedNode -> Float
+ NanoUI.Internal.Context.Types: [explainedHeight] :: ExplainedNode -> Sizing
+ NanoUI.Internal.Context.Types: [explainedKind] :: ExplainedNode -> Text
+ NanoUI.Internal.Context.Types: [explainedMax] :: ExplainedNode -> V2
+ NanoUI.Internal.Context.Types: [explainedMin] :: ExplainedNode -> V2
+ NanoUI.Internal.Context.Types: [explainedPadding] :: ExplainedNode -> Padding
+ NanoUI.Internal.Context.Types: [explainedPin] :: ExplainedNode -> Maybe V2
+ NanoUI.Internal.Context.Types: [explainedPointer] :: ExplainedNode -> PointerMode
+ NanoUI.Internal.Context.Types: [explainedRect] :: ExplainedNode -> Rect
+ NanoUI.Internal.Context.Types: [explainedWidget] :: ExplainedNode -> Maybe WidgetId
+ NanoUI.Internal.Context.Types: [explainedWidth] :: ExplainedNode -> Sizing
+ NanoUI.Internal.Context.Types: [imrCaret] :: InputMethodRequest -> Maybe Rect
+ NanoUI.Internal.Context.Types: [imrPurpose] :: InputMethodRequest -> InputPurpose
+ NanoUI.Internal.Context.Types: [imrWidget] :: InputMethodRequest -> WidgetId
+ NanoUI.Internal.Context.Types: [isColumnResize] :: InteractionState -> Bool
+ NanoUI.Internal.Context.Types: [isComposition] :: InteractionState -> Maybe (Composition, WidgetId)
+ NanoUI.Internal.Context.Types: [isFocusCombo] :: InteractionState -> Bool
+ NanoUI.Internal.Context.Types: [isFocusKind] :: InteractionState -> FocusKind
+ NanoUI.Internal.Context.Types: [isPointerHeld] :: InteractionState -> Bool
+ NanoUI.Internal.Context.Types: [isPointerRoute] :: InteractionState -> PointerRoute
+ NanoUI.Internal.Context.Types: [isScrollDrag] :: InteractionState -> Maybe (WidgetId, DirTag, Float)
+ NanoUI.Internal.Context.Types: [isScrollHover] :: InteractionState -> Maybe (WidgetId, DirTag, Rect)
+ NanoUI.Internal.Context.Types: [isTextEditLastAction] :: InteractionState -> Maybe (WidgetId, TextCommand)
+ NanoUI.Internal.Context.Types: [isTextFieldClickCell] :: InteractionState -> Maybe TextFieldClickCell
+ NanoUI.Internal.Context.Types: [isTextInputDrag] :: InteractionState -> Maybe TextInputDrag
+ NanoUI.Internal.Context.Types: [isTextInputMenu] :: InteractionState -> Maybe TextInputMenu
+ NanoUI.Internal.Context.Types: [isWindowDrag] :: InteractionState -> Maybe (WidgetId, Float, Float)
+ NanoUI.Internal.Context.Types: [isWindowResize] :: InteractionState -> Maybe WindowResizeDrag
+ NanoUI.Internal.Context.Types: [ncCustom] :: NodeCustom -> Maybe CustomDrawingEntry
+ NanoUI.Internal.Context.Types: [ncDrawing] :: NodeCustom -> Maybe DrawingEntry
+ NanoUI.Internal.Context.Types: [ncEffect] :: NodeCustom -> Maybe ShaderEffectEntry
+ NanoUI.Internal.Context.Types: [ncEpoch] :: NodeCustom -> Word32
+ NanoUI.Internal.Context.Types: [ncMeasure] :: NodeCustom -> Maybe CustomMeasureFn
+ NanoUI.Internal.Context.Types: [ncShader] :: NodeCustom -> Maybe ShaderNodeEntry
+ NanoUI.Internal.Context.Types: [osEscapeConsumed] :: OverlayState -> Bool
+ NanoUI.Internal.Context.Types: [osKeysTaken] :: OverlayState -> IntSet
+ NanoUI.Internal.Context.Types: [osModalActive] :: OverlayState -> Bool
+ NanoUI.Internal.Context.Types: [osModalDepth] :: OverlayState -> Int
+ NanoUI.Internal.Context.Types: [osModalWasActive] :: OverlayState -> Bool
+ NanoUI.Internal.Context.Types: [osPrevFloatingOrder] :: OverlayState -> [Int]
+ NanoUI.Internal.Context.Types: [osPrevFloatingRects] :: OverlayState -> IntMap Rect
+ NanoUI.Internal.Context.Types: [osTabConsumed] :: OverlayState -> Bool
+ NanoUI.Internal.Context.Types: [pcAnchor] :: PopupConfig -> PopupAnchor
+ NanoUI.Internal.Context.Types: [pcOffset] :: PopupConfig -> Float
+ NanoUI.Internal.Context.Types: [pcPlacement] :: PopupConfig -> PopupPlacement
+ NanoUI.Internal.Context.Types: [pfClips] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context.Types: [pfEffectRects] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context.Types: [pfHashes] :: PrevFrame -> IntMap Word64
+ NanoUI.Internal.Context.Types: [pfOuterClips] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context.Types: [pfRects] :: PrevFrame -> IntMap Rect
+ NanoUI.Internal.Context.Types: [ppOwner] :: PressPoint -> Maybe WidgetId
+ NanoUI.Internal.Context.Types: [ppPos] :: PressPoint -> V2
+ NanoUI.Internal.Context.Types: [ppReached] :: PressPoint -> IntSet
+ NanoUI.Internal.Context.Types: [pwClips] :: PrevWalk -> MutablePrimArray RealWorld Float
+ NanoUI.Internal.Context.Types: [pwFor] :: PrevWalk -> IORef (IntMap Rect)
+ NanoUI.Internal.Context.Types: [pwHashes] :: PrevWalk -> MutablePrimArray RealWorld Word64
+ NanoUI.Internal.Context.Types: [pwKeys] :: PrevWalk -> MutablePrimArray RealWorld Int
+ NanoUI.Internal.Context.Types: [pwRects] :: PrevWalk -> MutableArray RealWorld Rect
+ NanoUI.Internal.Context.Types: [pwTags] :: PrevWalk -> MutablePrimArray RealWorld Int
+ NanoUI.Internal.Context.Types: [pwValid] :: PrevWalk -> PrimVar RealWorld Int
+ NanoUI.Internal.Context.Types: [sceAlign] :: SpanCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [sceBg] :: SpanCacheEntry -> Color
+ NanoUI.Internal.Context.Types: [sceEffMaxW] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context.Types: [sceFg] :: SpanCacheEntry -> Color
+ NanoUI.Internal.Context.Types: [sceFontSize] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context.Types: [sceFont] :: SpanCacheEntry -> FontMetrics
+ NanoUI.Internal.Context.Types: [sceInset] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context.Types: [sceLaidW] :: SpanCacheEntry -> Float
+ NanoUI.Internal.Context.Types: [sceLines] :: SpanCacheEntry -> SpanLines
+ NanoUI.Internal.Context.Types: [sceRect] :: SpanCacheEntry -> Rect
+ NanoUI.Internal.Context.Types: [sceRowChild] :: SpanCacheEntry -> Bool
+ NanoUI.Internal.Context.Types: [sceSpans] :: SpanCacheEntry -> [(Rect, Text, Color, Color)]
+ NanoUI.Internal.Context.Types: [sceStyle] :: SpanCacheEntry -> Word64
+ NanoUI.Internal.Context.Types: [sceText] :: SpanCacheEntry -> Text
+ NanoUI.Internal.Context.Types: [sceWidthTag] :: SpanCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [scrollSmoothTime] :: ScrollTuning -> Float
+ NanoUI.Internal.Context.Types: [scrollWheelStep] :: ScrollTuning -> Float
+ NanoUI.Internal.Context.Types: [sgAxes] :: ScrollGlide -> ScrollAxes
+ NanoUI.Internal.Context.Types: [sgTarget] :: ScrollGlide -> V2
+ NanoUI.Internal.Context.Types: [sgWidget] :: ScrollGlide -> WidgetId
+ NanoUI.Internal.Context.Types: [ssCached] :: ScrollState -> IntSet
+ NanoUI.Internal.Context.Types: [ssGlides] :: ScrollState -> IntMap ScrollGlide
+ NanoUI.Internal.Context.Types: [ssTuning] :: ScrollState -> ScrollTuning
+ NanoUI.Internal.Context.Types: [ssViews] :: ScrollState -> IntMap ScrollView
+ NanoUI.Internal.Context.Types: [svPlaced] :: ScrollView -> V2
+ NanoUI.Internal.Context.Types: [svViewport] :: ScrollView -> Rect
+ NanoUI.Internal.Context.Types: [textFieldClickAt] :: TextFieldClickCell -> Cursor
+ NanoUI.Internal.Context.Types: [textFieldClickWidget] :: TextFieldClickCell -> WidgetId
+ NanoUI.Internal.Context.Types: [textInputDragAnchor] :: TextInputDrag -> Cursor
+ NanoUI.Internal.Context.Types: [textInputDragClicks] :: TextInputDrag -> Int
+ NanoUI.Internal.Context.Types: [textInputDragWidget] :: TextInputDrag -> WidgetId
+ NanoUI.Internal.Context.Types: [textInputMenuAt] :: TextInputMenu -> V2
+ NanoUI.Internal.Context.Types: [textInputMenuRect] :: TextInputMenu -> Rect
+ NanoUI.Internal.Context.Types: [textInputMenuWidget] :: TextInputMenu -> WidgetId
+ NanoUI.Internal.Context.Types: [tsChanged] :: ThemeScopes -> Bool
+ NanoUI.Internal.Context.Types: [tsCount] :: ThemeScopes -> Int
+ NanoUI.Internal.Context.Types: [tsDisabled] :: ThemeScopes -> Bool
+ NanoUI.Internal.Context.Types: [tsPrevCount] :: ThemeScopes -> Int
+ NanoUI.Internal.Context.Types: [tsPrevSig] :: ThemeScopes -> Word64
+ NanoUI.Internal.Context.Types: [tsPrev] :: ThemeScopes -> SmallMutableArray RealWorld Theme
+ NanoUI.Internal.Context.Types: [tsRaw] :: ThemeScopes -> SmallMutableArray RealWorld Theme
+ NanoUI.Internal.Context.Types: [tsThemes] :: ThemeScopes -> SmallMutableArray RealWorld Theme
+ NanoUI.Internal.Context.Types: [wrdEdge] :: WindowResizeDrag -> WindowResizeEdge
+ NanoUI.Internal.Context.Types: [wrdGrabX] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdGrabY] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdMaxH] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdMaxW] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdMinH] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdMinW] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdStartH] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdStartW] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdStartX] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdStartY] :: WindowResizeDrag -> Float
+ NanoUI.Internal.Context.Types: [wrdWidget] :: WindowResizeDrag -> WidgetId
+ NanoUI.Internal.Context.Types: [wtcAlign] :: WidgetTextCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [wtcFontSize] :: WidgetTextCacheEntry -> Float
+ NanoUI.Internal.Context.Types: [wtcHeight] :: WidgetTextCacheEntry -> Float
+ NanoUI.Internal.Context.Types: [wtcNodeType] :: WidgetTextCacheEntry -> Int
+ NanoUI.Internal.Context.Types: [wtcPlacement] :: WidgetTextCacheEntry -> Maybe WidgetTextPlacement
+ NanoUI.Internal.Context.Types: [wtcStyle] :: WidgetTextCacheEntry -> Word64
+ NanoUI.Internal.Context.Types: [wtcText] :: WidgetTextCacheEntry -> Text
+ NanoUI.Internal.Context.Types: [wtcWidth] :: WidgetTextCacheEntry -> Float
+ NanoUI.Internal.Context.Types: cachedGen :: Hashable k => Int -> (k -> Int) -> IORef (GenCache k v) -> k -> IO v -> IO v
+ NanoUI.Internal.Context.Types: customPassWords :: Int
+ NanoUI.Internal.Context.Types: data AnimationState
+ NanoUI.Internal.Context.Types: data ChildWindow
+ NanoUI.Internal.Context.Types: data ContainerStack
+ NanoUI.Internal.Context.Types: data Context
+ NanoUI.Internal.Context.Types: data CustomDrawContext
+ NanoUI.Internal.Context.Types: data CustomDrawOpCacheEntry
+ NanoUI.Internal.Context.Types: data CustomDrawingEntry
+ NanoUI.Internal.Context.Types: data DamageRequest
+ NanoUI.Internal.Context.Types: data DamageState
+ NanoUI.Internal.Context.Types: data DrawFitCache
+ NanoUI.Internal.Context.Types: data DrawOpCacheEntry
+ NanoUI.Internal.Context.Types: data DrawReuse
+ NanoUI.Internal.Context.Types: data DrawReuseKey
+ NanoUI.Internal.Context.Types: data DrawingCacheState
+ NanoUI.Internal.Context.Types: data DrawingEntry
+ NanoUI.Internal.Context.Types: data DropdownPopup
+ NanoUI.Internal.Context.Types: data ExplainState
+ NanoUI.Internal.Context.Types: data ExplainedNode
+ NanoUI.Internal.Context.Types: data FocusKind
+ NanoUI.Internal.Context.Types: data FocusRequest
+ NanoUI.Internal.Context.Types: data GenCache k v
+ NanoUI.Internal.Context.Types: data HoverZone
+ NanoUI.Internal.Context.Types: data InputMethodRequest
+ NanoUI.Internal.Context.Types: data InteractionState
+ NanoUI.Internal.Context.Types: data KeyClaim
+ NanoUI.Internal.Context.Types: data MetricSource
+ NanoUI.Internal.Context.Types: data NodeCustom
+ NanoUI.Internal.Context.Types: data OverlayState
+ NanoUI.Internal.Context.Types: data PointerRoute
+ NanoUI.Internal.Context.Types: data PopupConfig
+ NanoUI.Internal.Context.Types: data PressPoint
+ NanoUI.Internal.Context.Types: data PrevFrame
+ NanoUI.Internal.Context.Types: data PrevWalk
+ NanoUI.Internal.Context.Types: data ScrollAxes
+ NanoUI.Internal.Context.Types: data ScrollGlide
+ NanoUI.Internal.Context.Types: data ScrollState
+ NanoUI.Internal.Context.Types: data ScrollTuning
+ NanoUI.Internal.Context.Types: data ScrollView
+ NanoUI.Internal.Context.Types: data SpanCacheEntry
+ NanoUI.Internal.Context.Types: data SpanLines
+ NanoUI.Internal.Context.Types: data TextFieldClickCell
+ NanoUI.Internal.Context.Types: data TextInputDrag
+ NanoUI.Internal.Context.Types: data TextInputMenu
+ NanoUI.Internal.Context.Types: data ThemeScopes
+ NanoUI.Internal.Context.Types: data WidgetTextCacheEntry
+ NanoUI.Internal.Context.Types: data WidgetTextPlacement
+ NanoUI.Internal.Context.Types: data WindowResizeDrag
+ NanoUI.Internal.Context.Types: data WindowResizeEdge
+ NanoUI.Internal.Context.Types: data WrapCache
+ NanoUI.Internal.Context.Types: defaultScrollTuning :: ScrollTuning
+ NanoUI.Internal.Context.Types: emptyGenCache :: GenCache k v
+ NanoUI.Internal.Context.Types: emptyPrevFrame :: PrevFrame
+ NanoUI.Internal.Context.Types: initialAnimationState :: AnimationState
+ NanoUI.Internal.Context.Types: initialDamageState :: DamageState
+ NanoUI.Internal.Context.Types: initialDrawingCacheState :: DrawingCacheState
+ NanoUI.Internal.Context.Types: initialExplainState :: ExplainState
+ NanoUI.Internal.Context.Types: initialInteractionState :: InteractionState
+ NanoUI.Internal.Context.Types: initialOverlayState :: OverlayState
+ NanoUI.Internal.Context.Types: initialScrollState :: ScrollState
+ NanoUI.Internal.Context.Types: insertGen :: Hashable k => Int -> Int -> k -> v -> GenCache k v -> GenCache k v
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.DamageRequest
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.DrawReuseKey
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.ExplainedNode
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.FocusKind
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.FocusRequest
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.InputMethodRequest
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.InteractionState
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.KeyClaim
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.PointerRoute
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.ScrollAxes
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.ScrollGlide
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.ScrollTuning
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.ScrollView
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.TextFieldClickCell
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.TextInputDrag
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.TextInputMenu
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.WindowResizeDrag
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Context.Types.WindowResizeEdge
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Enum.Enum NanoUI.Internal.Context.Types.ScrollAxes
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.DamageRequest
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.ExplainedNode
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.FocusKind
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.FocusRequest
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.InputMethodRequest
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.InteractionState
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.KeyClaim
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.PointerRoute
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.ScrollAxes
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.ScrollGlide
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.ScrollTuning
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.ScrollView
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.TextFieldClickCell
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.TextInputDrag
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.TextInputMenu
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.WindowResizeDrag
+ NanoUI.Internal.Context.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Context.Types.WindowResizeEdge
+ NanoUI.Internal.Context.Types: intKey :: WidgetId -> Int
+ NanoUI.Internal.Context.Types: newContainerStack :: IO ContainerStack
+ NanoUI.Internal.Context.Types: newPrevWalk :: Int -> IO PrevWalk
+ NanoUI.Internal.Context.Types: noNodeCustom :: NodeCustom
+ NanoUI.Internal.Context.Types: peekContainer :: ContainerStack -> IO Int
+ NanoUI.Internal.Context.Types: popContainer :: ContainerStack -> IO ()
+ NanoUI.Internal.Context.Types: pushContainer :: ContainerStack -> Int -> IO ()
+ NanoUI.Internal.Context.Types: readContainerStack :: ContainerStack -> IO [Int]
+ NanoUI.Internal.Context.Types: resetContainerStack :: ContainerStack -> IO ()
+ NanoUI.Internal.Context.Types: type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp
+ NanoUI.Internal.Context.Types: type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)
+ NanoUI.Internal.Context.Types: type MeasureCache = GenCache (Text, Float) (Float, Float)
+ NanoUI.Internal.Context.Types: writeContainerStack :: ContainerStack -> [Int] -> IO ()
+ NanoUI.Internal.Debug: CoreDebugSnapshot :: Double -> Double -> Double -> Double -> Double -> Double -> Word64 -> Word64 -> Int -> Int -> Int -> Float -> Float -> Float -> Float -> [(Text, Text)] -> CoreDebugSnapshot
+ NanoUI.Internal.Debug: [dbgCmds] :: CoreDebugSnapshot -> Int
+ NanoUI.Internal.Debug: [dbgFrameMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Internal.Debug: [dbgIndices] :: CoreDebugSnapshot -> Int
+ NanoUI.Internal.Debug: [dbgLoopFps] :: CoreDebugSnapshot -> Double
+ NanoUI.Internal.Debug: [dbgMouseX] :: CoreDebugSnapshot -> Float
+ NanoUI.Internal.Debug: [dbgMouseY] :: CoreDebugSnapshot -> Float
+ NanoUI.Internal.Debug: [dbgPresentFps] :: CoreDebugSnapshot -> Double
+ NanoUI.Internal.Debug: [dbgPresentMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Internal.Debug: [dbgPresents] :: CoreDebugSnapshot -> Word64
+ NanoUI.Internal.Debug: [dbgRenderMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Internal.Debug: [dbgRts] :: CoreDebugSnapshot -> [(Text, Text)]
+ NanoUI.Internal.Debug: [dbgSkips] :: CoreDebugSnapshot -> Word64
+ NanoUI.Internal.Debug: [dbgUiMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Internal.Debug: [dbgVerts] :: CoreDebugSnapshot -> Int
+ NanoUI.Internal.Debug: [dbgWinH] :: CoreDebugSnapshot -> Float
+ NanoUI.Internal.Debug: [dbgWinW] :: CoreDebugSnapshot -> Float
+ NanoUI.Internal.Debug: data CoreDebugSnapshot
+ NanoUI.Internal.Debug: debugCadence :: DebugSamplerRef -> IO (Bool, Bool)
+ NanoUI.Internal.Debug: debugRefreshSec :: Double
+ NanoUI.Internal.Debug: emptyCoreDebugSnapshot :: CoreDebugSnapshot
+ NanoUI.Internal.Debug: formatDrawRows :: CoreDebugSnapshot -> [(Text, Text)]
+ NanoUI.Internal.Debug: formatExplainRows :: Maybe ExplainedNode -> [(Text, Text)]
+ NanoUI.Internal.Debug: formatFpsRows :: CoreDebugSnapshot -> [(Text, Text)]
+ NanoUI.Internal.Debug: instance GHC.Internal.Classes.Eq NanoUI.Internal.Debug.CoreDebugSnapshot
+ NanoUI.Internal.Debug: instance GHC.Internal.Show.Show NanoUI.Internal.Debug.CoreDebugSnapshot
+ NanoUI.Internal.Debug: newDebugSampler :: IO DebugSamplerRef
+ NanoUI.Internal.Debug: noteDebugFrame :: DebugSamplerRef -> Double -> Double -> Double -> Double -> DrawData -> IO ()
+ NanoUI.Internal.Debug: noteDebugLoop :: DebugSamplerRef -> Float -> IO ()
+ NanoUI.Internal.Debug: noteDebugSkip :: DebugSamplerRef -> IO ()
+ NanoUI.Internal.Debug: refreshDebugSnapshot :: DebugSamplerRef -> IORef (Maybe s) -> (CoreDebugSnapshot -> IO s) -> IO s
+ NanoUI.Internal.Debug: type DebugSamplerRef = IORef DebugSampler
+ NanoUI.Internal.Frame.Hit: findNodeByWidgetId :: Context -> WidgetId -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: innermostHit :: Context -> (NodeIdx -> IO Bool) -> NodeIdx -> IO NodeIdx
+ NanoUI.Internal.Frame.Hit: innermostNodeAt :: Context -> Maybe NodeIdx -> (s -> NodeIdx -> IO (Bool, Maybe s)) -> s -> IO (Maybe (NodeIdx, s))
+ NanoUI.Internal.Frame.Hit: nodeClippedHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool
+ NanoUI.Internal.Frame.Hit: nodeInSubtree :: Context -> NodeIdx -> NodeIdx -> IO Bool
+ NanoUI.Internal.Frame.Hit: nodeInteractionHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool
+ NanoUI.Internal.Frame.Hit: nodePointVisible :: Context -> NodeIdx -> V2 -> IO Bool
+ NanoUI.Internal.Frame.Hit: overlayHitAllowed :: Context -> Maybe NodeIdx -> NodeIdx -> IO Bool
+ NanoUI.Internal.Frame.Hit: overlayHitRoot :: Context -> V2 -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: passesPointer :: NodeArena -> NodeIdx -> IO Bool
+ NanoUI.Internal.Frame.Hit: reachedAt :: Context -> V2 -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: reachedHit :: Context -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: reachedWidgetAt :: Context -> V2 -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: takesPointer :: NodeArena -> NodeIdx -> IO Bool
+ NanoUI.Internal.Frame.Hit: topmostFloating :: Context -> (NodeType -> Bool) -> (Rect -> Bool) -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: topmostHit :: Context -> (NodeIdx -> IO Bool) -> NodeIdx -> IO NodeIdx
+ NanoUI.Internal.Frame.Hit: topmostOverlayAtMouse :: Context -> V2 -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Frame.Hit: widgetIdInSubtree :: Context -> NodeIdx -> WidgetId -> IO Bool
+ NanoUI.Internal.Frame.Hit: widgetInModal :: Context -> Maybe NodeIdx -> WidgetId -> IO Bool
+ NanoUI.Internal.Frame.Hit: widgetOverlayAllowed :: Context -> WidgetId -> IO Bool
+ NanoUI.Internal.Frame.Hit: withWidgetNode :: Context -> WidgetId -> a -> (NodeIdx -> IO a) -> IO a
+ NanoUI.Internal.Frame.TextArea: TextAreaBars :: Bool -> Bool -> V2 -> Padding -> Padding -> V2 -> TextAreaBars
+ NanoUI.Internal.Frame.TextArea: TextAreaHit :: NodeIdx -> Rect -> Float -> TextAreaHit
+ NanoUI.Internal.Frame.TextArea: TextInputArea :: Rect -> Float -> InputPurpose -> TextInputArea
+ NanoUI.Internal.Frame.TextArea: [tabContent] :: TextAreaBars -> V2
+ NanoUI.Internal.Frame.TextArea: [tabHorizontal] :: TextAreaBars -> Bool
+ NanoUI.Internal.Frame.TextArea: [tabPadH] :: TextAreaBars -> Padding
+ NanoUI.Internal.Frame.TextArea: [tabPadV] :: TextAreaBars -> Padding
+ NanoUI.Internal.Frame.TextArea: [tabRange] :: TextAreaBars -> V2
+ NanoUI.Internal.Frame.TextArea: [tabVertical] :: TextAreaBars -> Bool
+ NanoUI.Internal.Frame.TextArea: [tahFieldRect] :: TextAreaHit -> Rect
+ NanoUI.Internal.Frame.TextArea: [tahLineH] :: TextAreaHit -> Float
+ NanoUI.Internal.Frame.TextArea: [tahNodeIdx] :: TextAreaHit -> NodeIdx
+ NanoUI.Internal.Frame.TextArea: [textInputAreaCursor] :: TextInputArea -> Float
+ NanoUI.Internal.Frame.TextArea: [textInputAreaPurpose] :: TextInputArea -> InputPurpose
+ NanoUI.Internal.Frame.TextArea: [textInputAreaRect] :: TextInputArea -> Rect
+ NanoUI.Internal.Frame.TextArea: collapseTextFieldSelection :: Context -> WidgetId -> IO ()
+ NanoUI.Internal.Frame.TextArea: data TextAreaBars
+ NanoUI.Internal.Frame.TextArea: data TextAreaHit
+ NanoUI.Internal.Frame.TextArea: data TextInputArea
+ NanoUI.Internal.Frame.TextArea: drawTextAreaContentWith :: DrawArena -> Context -> FontMetrics -> NodeIdx -> Float -> Float -> Float -> Float -> Style -> IO ()
+ NanoUI.Internal.Frame.TextArea: finalizeTextFieldMouse :: Context -> Input -> Bool -> IO ()
+ NanoUI.Internal.Frame.TextArea: instance GHC.Internal.Classes.Eq NanoUI.Internal.Frame.TextArea.TextInputArea
+ NanoUI.Internal.Frame.TextArea: instance GHC.Internal.Show.Show NanoUI.Internal.Frame.TextArea.TextInputArea
+ NanoUI.Internal.Frame.TextArea: isMouseOnTextAreaScrollBarAt :: Context -> NodeIdx -> V2 -> IO Bool
+ NanoUI.Internal.Frame.TextArea: resolveTextAreaFont :: Context -> NodeIdx -> IO FontMetrics
+ NanoUI.Internal.Frame.TextArea: textAreaBarLane :: Float
+ NanoUI.Internal.Frame.TextArea: textAreaBarLayouts :: Rect -> TextAreaBars -> Float -> Float -> (Maybe ScrollBarLayout, Maybe ScrollBarLayout)
+ NanoUI.Internal.Frame.TextArea: textAreaBars :: FontMetrics -> Rect -> Float -> Float -> TextAreaBars
+ NanoUI.Internal.Frame.TextArea: textAreaContentMetrics :: Context -> NodeIdx -> IO (Float, Float)
+ NanoUI.Internal.Frame.TextArea: textAreaHitForWidget :: Context -> WidgetId -> IO (Maybe TextAreaHit)
+ NanoUI.Internal.Frame.TextArea: textAreaLineHeight :: FontMetrics -> Float
+ NanoUI.Internal.Frame.TextArea: textAreaScrollGeom :: Context -> NodeIdx -> IO (Rect, TextAreaBars)
+ NanoUI.Internal.Frame.TextArea: textAreaTextPlacements :: Context -> NodeIdx -> Rect -> IO (Rect, [(Text, Float, Float, Float, Float)])
+ NanoUI.Internal.Frame.TextArea: textInputArea :: Context -> IO (Maybe TextInputArea)
+ NanoUI.Internal.Frame.TextArea: textWordBounds :: Text -> Int -> (Int, Int)
+ NanoUI.Internal.Frame.Window: contextMeasurers :: Context -> Measurers
+ NanoUI.Internal.Frame.Window: lookupWindowPos :: Context -> WidgetId -> IO (Maybe (Float, Float))
+ NanoUI.Internal.Frame.Window: lookupWindowSize :: Context -> WidgetId -> IO (Maybe (Float, Float))
+ NanoUI.Internal.Frame.Window: persistWindowPositions :: Context -> IO ()
+ NanoUI.Internal.Frame.Window: updateWindowDrag :: Context -> Input -> IO Bool
+ NanoUI.Internal.Frame.Window: updateWindowResize :: Context -> Input -> Float -> Float -> IO Bool
+ NanoUI.Internal.Frame.Window: windowResizeCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)
+ NanoUI.Internal.Id: IdContext :: Word64 -> Word64 -> Word64 -> IdContext
+ NanoUI.Internal.Id: WidgetId :: Word64 -> WidgetId
+ NanoUI.Internal.Id: [currentId] :: IdContext -> Word64
+ NanoUI.Internal.Id: [siblingId] :: IdContext -> Word64
+ NanoUI.Internal.Id: [varSiblingId] :: IdContext -> Word64
+ NanoUI.Internal.Id: data IdContext
+ NanoUI.Internal.Id: enterKeyed :: Word64 -> IdContext -> (IdContext, IdContext)
+ NanoUI.Internal.Id: enterScope :: Word64 -> IdContext -> (IdContext, IdContext)
+ NanoUI.Internal.Id: hashWidgetId :: WidgetId -> Word64
+ NanoUI.Internal.Id: idContextWidgetId :: IdContext -> WidgetId
+ NanoUI.Internal.Id: initialIdContext :: IdContext
+ NanoUI.Internal.Id: instance Data.Hashable.Class.Hashable NanoUI.Internal.Id.WidgetId
+ NanoUI.Internal.Id: instance Data.Primitive.Types.Prim NanoUI.Internal.Id.WidgetId
+ NanoUI.Internal.Id: instance GHC.Internal.Classes.Eq NanoUI.Internal.Id.IdContext
+ NanoUI.Internal.Id: instance GHC.Internal.Classes.Eq NanoUI.Internal.Id.WidgetId
+ NanoUI.Internal.Id: instance GHC.Internal.Classes.Ord NanoUI.Internal.Id.WidgetId
+ NanoUI.Internal.Id: instance GHC.Internal.Show.Show NanoUI.Internal.Id.IdContext
+ NanoUI.Internal.Id: instance GHC.Internal.Show.Show NanoUI.Internal.Id.WidgetId
+ NanoUI.Internal.Id: keyedTag :: Word64
+ NanoUI.Internal.Id: mix64 :: Word64 -> Word64 -> Word64
+ NanoUI.Internal.Id: mixFnv :: Word64 -> Word64 -> Word64
+ NanoUI.Internal.Id: mkWidgetId :: Word64 -> WidgetId
+ NanoUI.Internal.Id: newtype WidgetId
+ NanoUI.Internal.Id: scopeIdContext :: Word64 -> IdContext
+ NanoUI.Internal.Id: scopeTag :: Word64
+ NanoUI.Internal.Id: widgetId :: HasCallStack => WidgetId
+ NanoUI.Internal.Id.Cursor: data IdCursor
+ NanoUI.Internal.Id.Cursor: newIdCursor :: IdContext -> IO IdCursor
+ NanoUI.Internal.Id.Cursor: peekWidgetId :: IdCursor -> IO WidgetId
+ NanoUI.Internal.Id.Cursor: popIdScope :: IdCursor -> IO ()
+ NanoUI.Internal.Id.Cursor: pushIdScope :: IdCursor -> Word64 -> IO ()
+ NanoUI.Internal.Id.Cursor: pushKeyedIdScope :: IdCursor -> Word64 -> IO ()
+ NanoUI.Internal.Id.Cursor: readIdCursor :: IdCursor -> IO IdContext
+ NanoUI.Internal.Id.Cursor: readIdDepth :: IdCursor -> IO Int
+ NanoUI.Internal.Id.Cursor: resetIdCursor :: IdCursor -> IO ()
+ NanoUI.Internal.Id.Cursor: skipSiblingIds :: IdCursor -> Int -> IO ()
+ NanoUI.Internal.Id.Cursor: takeVarKey :: IdCursor -> IO Int
+ NanoUI.Internal.Id.Cursor: takeWidgetId :: IdCursor -> IO WidgetId
+ NanoUI.Internal.Id.Cursor: writeIdCursor :: IdCursor -> IdContext -> IO ()
+ NanoUI.Internal.Id.Cursor: writeIdDepth :: IdCursor -> Int -> IO ()
+ NanoUI.Internal.Image: FitContain :: ContentFit
+ NanoUI.Internal.Image: FitCover :: ContentFit
+ NanoUI.Internal.Image: FitFill :: ContentFit
+ NanoUI.Internal.Image: FitNone :: ContentFit
+ NanoUI.Internal.Image: FitScaleDown :: ContentFit
+ NanoUI.Internal.Image: ImageConfig :: (Layout -> Layout) -> ContentFit -> AlignX -> AlignY -> Float -> Rotation -> Maybe Rect -> Float -> ImageConfig
+ NanoUI.Internal.Image: ImageDraw :: Rect -> ImageId -> Rect -> Float -> Color -> Float -> ImageDraw
+ NanoUI.Internal.Image: ImageLook :: ContentFit -> AlignX -> AlignY -> Float -> Rotation -> Maybe Rect -> Float -> Color -> ImageLook
+ NanoUI.Internal.Image: RotateFloating :: Float -> Rotation
+ NanoUI.Internal.Image: RotateSolid :: Float -> Rotation
+ NanoUI.Internal.Image: [icAlignX] :: ImageConfig -> AlignX
+ NanoUI.Internal.Image: [icAlignY] :: ImageConfig -> AlignY
+ NanoUI.Internal.Image: [icCrop] :: ImageConfig -> Maybe Rect
+ NanoUI.Internal.Image: [icFit] :: ImageConfig -> ContentFit
+ NanoUI.Internal.Image: [icLayout] :: ImageConfig -> Layout -> Layout
+ NanoUI.Internal.Image: [icOpacity] :: ImageConfig -> Float
+ NanoUI.Internal.Image: [icRotation] :: ImageConfig -> Rotation
+ NanoUI.Internal.Image: [icScale] :: ImageConfig -> Float
+ NanoUI.Internal.Image: [imageAngle] :: ImageDraw -> Float
+ NanoUI.Internal.Image: [imageId] :: ImageDraw -> ImageId
+ NanoUI.Internal.Image: [imageOpacity] :: ImageDraw -> Float
+ NanoUI.Internal.Image: [imageRect] :: ImageDraw -> Rect
+ NanoUI.Internal.Image: [imageTint] :: ImageDraw -> Color
+ NanoUI.Internal.Image: [imageUV] :: ImageDraw -> Rect
+ NanoUI.Internal.Image: [lookAlignX] :: ImageLook -> AlignX
+ NanoUI.Internal.Image: [lookAlignY] :: ImageLook -> AlignY
+ NanoUI.Internal.Image: [lookCrop] :: ImageLook -> Maybe Rect
+ NanoUI.Internal.Image: [lookFit] :: ImageLook -> ContentFit
+ NanoUI.Internal.Image: [lookOpacity] :: ImageLook -> Float
+ NanoUI.Internal.Image: [lookRotation] :: ImageLook -> Rotation
+ NanoUI.Internal.Image: [lookScale] :: ImageLook -> Float
+ NanoUI.Internal.Image: [lookTint] :: ImageLook -> Color
+ NanoUI.Internal.Image: data ContentFit
+ NanoUI.Internal.Image: data ImageConfig
+ NanoUI.Internal.Image: data ImageDraw
+ NanoUI.Internal.Image: data ImageLook
+ NanoUI.Internal.Image: data Rotation
+ NanoUI.Internal.Image: defaultImageConfig :: ImageConfig
+ NanoUI.Internal.Image: fadeBy :: Float -> Color -> Color
+ NanoUI.Internal.Image: fitRect :: ContentFit -> AlignX -> AlignY -> (Float, Float) -> Rect -> Rect
+ NanoUI.Internal.Image: imageDraw :: Rect -> ImageId -> ImageDraw
+ NanoUI.Internal.Image: imageDrawOp :: ImageDraw -> Maybe DrawOp
+ NanoUI.Internal.Image: imageLook :: ImageConfig -> Color -> ImageLook
+ NanoUI.Internal.Image: instance GHC.Internal.Classes.Eq NanoUI.Internal.Image.ContentFit
+ NanoUI.Internal.Image: instance GHC.Internal.Classes.Eq NanoUI.Internal.Image.ImageDraw
+ NanoUI.Internal.Image: instance GHC.Internal.Classes.Eq NanoUI.Internal.Image.ImageLook
+ NanoUI.Internal.Image: instance GHC.Internal.Classes.Eq NanoUI.Internal.Image.Rotation
+ NanoUI.Internal.Image: instance GHC.Internal.Classes.Ord NanoUI.Internal.Image.ContentFit
+ NanoUI.Internal.Image: instance GHC.Internal.Enum.Bounded NanoUI.Internal.Image.ContentFit
+ NanoUI.Internal.Image: instance GHC.Internal.Enum.Enum NanoUI.Internal.Image.ContentFit
+ NanoUI.Internal.Image: instance GHC.Internal.Show.Show NanoUI.Internal.Image.ContentFit
+ NanoUI.Internal.Image: instance GHC.Internal.Show.Show NanoUI.Internal.Image.ImageDraw
+ NanoUI.Internal.Image: instance GHC.Internal.Show.Show NanoUI.Internal.Image.ImageLook
+ NanoUI.Internal.Image: instance GHC.Internal.Show.Show NanoUI.Internal.Image.Rotation
+ NanoUI.Internal.Image: lookSize :: ImageLook -> (Int, Int) -> (Float, Float)
+ NanoUI.Internal.Image: plainLook :: ImageLook -> Bool
+ NanoUI.Internal.Image: rotationAngle :: Rotation -> Float
+ NanoUI.Internal.Image: turnedRect :: ContentFit -> AlignX -> AlignY -> Rotation -> (Float, Float) -> Rect -> Rect
+ NanoUI.Internal.Image: withLookDraw :: ImageLook -> (Int, Int) -> Float -> Rect -> (Bool -> Rect -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()) -> IO ()
+ NanoUI.Internal.Input: Composition :: Text -> Int -> Int -> Composition
+ NanoUI.Internal.Input: DropBegin :: DropType
+ NanoUI.Internal.Input: DropComplete :: DropType
+ NanoUI.Internal.Input: DropEvent :: DropType -> Maybe V2 -> Text -> DropEvent
+ NanoUI.Internal.Input: DropFile :: DropType
+ NanoUI.Internal.Input: DropPosition :: DropType
+ NanoUI.Internal.Input: DropText :: DropType
+ NanoUI.Internal.Input: Input :: V2 -> MouseButtons -> MouseButtons -> MouseButtons -> Int -> V2 -> SmallArray Key -> SmallArray Key -> SmallArray Key -> SmallArray Key -> Text -> Modifiers -> Size -> Float -> SmallArray DropEvent -> Bool -> Maybe Composition -> Input
+ NanoUI.Internal.Input: InputNormal :: InputPurpose
+ NanoUI.Internal.Input: InputNumeric :: InputPurpose
+ NanoUI.Internal.Input: InputSecure :: InputPurpose
+ NanoUI.Internal.Input: KeyBackspace :: Key
+ NanoUI.Internal.Input: KeyCapsLock :: Key
+ NanoUI.Internal.Input: KeyChar :: Char -> Key
+ NanoUI.Internal.Input: KeyDelete :: Key
+ NanoUI.Internal.Input: KeyDown :: Key
+ NanoUI.Internal.Input: KeyEnd :: Key
+ NanoUI.Internal.Input: KeyEnter :: Key
+ NanoUI.Internal.Input: KeyEscape :: Key
+ NanoUI.Internal.Input: KeyF :: Int -> Key
+ NanoUI.Internal.Input: KeyHome :: Key
+ NanoUI.Internal.Input: KeyInsert :: Key
+ NanoUI.Internal.Input: KeyLeft :: Key
+ NanoUI.Internal.Input: KeyMenu :: Key
+ NanoUI.Internal.Input: KeyNumLock :: Key
+ NanoUI.Internal.Input: KeyPageDown :: Key
+ NanoUI.Internal.Input: KeyPageUp :: Key
+ NanoUI.Internal.Input: KeyPause :: Key
+ NanoUI.Internal.Input: KeyPrintScreen :: Key
+ NanoUI.Internal.Input: KeyRight :: Key
+ NanoUI.Internal.Input: KeyScrollLock :: Key
+ NanoUI.Internal.Input: KeySpace :: Key
+ NanoUI.Internal.Input: KeyTab :: Key
+ NanoUI.Internal.Input: KeyUp :: Key
+ NanoUI.Internal.Input: Modifiers :: Bool -> Bool -> Bool -> Bool -> Modifiers
+ NanoUI.Internal.Input: MouseBack :: MouseButton
+ NanoUI.Internal.Input: MouseForward :: MouseButton
+ NanoUI.Internal.Input: MouseLeft :: MouseButton
+ NanoUI.Internal.Input: MouseMiddle :: MouseButton
+ NanoUI.Internal.Input: MouseOther :: Int -> MouseButton
+ NanoUI.Internal.Input: MouseRight :: MouseButton
+ NanoUI.Internal.Input: UiCursorAlias :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorAllScroll :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorCell :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorColResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorContextMenu :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorCopy :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorCrosshair :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorDefault :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorEResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorEwResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorGrab :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorGrabbing :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorHelp :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorHidden :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorMove :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNeResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNeswResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNotAllowed :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNsResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNwResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorNwseResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorPointer :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorProgress :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorRowResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorSResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorSeResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorSwResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorText :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorWResize :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorWait :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorZoomIn :: UiCursorKind
+ NanoUI.Internal.Input: UiCursorZoomOut :: UiCursorKind
+ NanoUI.Internal.Input: [compositionCursor] :: Composition -> Int
+ NanoUI.Internal.Input: [compositionSelection] :: Composition -> Int
+ NanoUI.Internal.Input: [compositionText] :: Composition -> Text
+ NanoUI.Internal.Input: [dropEventData] :: DropEvent -> Text
+ NanoUI.Internal.Input: [dropEventPos] :: DropEvent -> Maybe V2
+ NanoUI.Internal.Input: [dropEventType] :: DropEvent -> DropType
+ NanoUI.Internal.Input: [inputButtonsHeld] :: Input -> MouseButtons
+ NanoUI.Internal.Input: [inputButtonsPressed] :: Input -> MouseButtons
+ NanoUI.Internal.Input: [inputButtonsReleased] :: Input -> MouseButtons
+ NanoUI.Internal.Input: [inputChars] :: Input -> Text
+ NanoUI.Internal.Input: [inputComposition] :: Input -> Maybe Composition
+ NanoUI.Internal.Input: [inputDeltaTime] :: Input -> Float
+ NanoUI.Internal.Input: [inputDrops] :: Input -> SmallArray DropEvent
+ NanoUI.Internal.Input: [inputKeysHeld] :: Input -> SmallArray Key
+ NanoUI.Internal.Input: [inputKeysNew] :: Input -> SmallArray Key
+ NanoUI.Internal.Input: [inputKeysReleased] :: Input -> SmallArray Key
+ NanoUI.Internal.Input: [inputKeys] :: Input -> SmallArray Key
+ NanoUI.Internal.Input: [inputModifiers] :: Input -> Modifiers
+ NanoUI.Internal.Input: [inputMouseClicks] :: Input -> Int
+ NanoUI.Internal.Input: [inputMousePos] :: Input -> V2
+ NanoUI.Internal.Input: [inputScroll] :: Input -> V2
+ NanoUI.Internal.Input: [inputWindowRedraw] :: Input -> Bool
+ NanoUI.Internal.Input: [inputWindowSize] :: Input -> Size
+ NanoUI.Internal.Input: [modAlt] :: Modifiers -> Bool
+ NanoUI.Internal.Input: [modCtrl] :: Modifiers -> Bool
+ NanoUI.Internal.Input: [modShift] :: Modifiers -> Bool
+ NanoUI.Internal.Input: [modSuper] :: Modifiers -> Bool
+ NanoUI.Internal.Input: anyButtonPressed :: Input -> Bool
+ NanoUI.Internal.Input: anyButtonReleased :: Input -> Bool
+ NanoUI.Internal.Input: appendDropEvent :: DropEvent -> SmallArray DropEvent -> SmallArray DropEvent
+ NanoUI.Internal.Input: appendInputKey :: Key -> SmallArray Key -> SmallArray Key
+ NanoUI.Internal.Input: applyComposition :: Text -> Int -> Int -> Input -> Input
+ NanoUI.Internal.Input: applyKey :: Key -> Bool -> Input -> Input
+ NanoUI.Internal.Input: applyMouseButton :: MouseButton -> Bool -> Input -> Input
+ NanoUI.Internal.Input: applyPointerLeave :: Input -> Input
+ NanoUI.Internal.Input: buttonsDelete :: MouseButton -> MouseButtons -> MouseButtons
+ NanoUI.Internal.Input: buttonsFilterM :: Monad m => (MouseButton -> m Bool) -> MouseButtons -> m MouseButtons
+ NanoUI.Internal.Input: buttonsFromList :: [MouseButton] -> MouseButtons
+ NanoUI.Internal.Input: buttonsInsert :: MouseButton -> MouseButtons -> MouseButtons
+ NanoUI.Internal.Input: buttonsMember :: MouseButton -> MouseButtons -> Bool
+ NanoUI.Internal.Input: buttonsNull :: MouseButtons -> Bool
+ NanoUI.Internal.Input: buttonsToList :: MouseButtons -> [MouseButton]
+ NanoUI.Internal.Input: chordModifiers :: Modifiers -> Bool
+ NanoUI.Internal.Input: class Pressable a
+ NanoUI.Internal.Input: clearEphemeral :: Input -> Input
+ NanoUI.Internal.Input: cursorFallback :: UiCursorKind -> UiCursorKind
+ NanoUI.Internal.Input: data Composition
+ NanoUI.Internal.Input: data DropEvent
+ NanoUI.Internal.Input: data DropType
+ NanoUI.Internal.Input: data Input
+ NanoUI.Internal.Input: data InputPurpose
+ NanoUI.Internal.Input: data Key
+ NanoUI.Internal.Input: data Modifiers
+ NanoUI.Internal.Input: data MouseButton
+ NanoUI.Internal.Input: data MouseButtons
+ NanoUI.Internal.Input: data UiCursorKind
+ NanoUI.Internal.Input: emptyInput :: Input
+ NanoUI.Internal.Input: foldInputKeys :: (a -> Key -> a) -> a -> SmallArray Key -> a
+ NanoUI.Internal.Input: grabDragKind :: Bool -> Bool -> Input -> UiCursorKind
+ NanoUI.Internal.Input: grabHoverKind :: Bool -> Input -> UiCursorKind
+ NanoUI.Internal.Input: heldIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Internal.Input: inputInteracted :: Input -> Input -> Bool
+ NanoUI.Internal.Input: inputKeysElem :: Key -> SmallArray Key -> Bool
+ NanoUI.Internal.Input: inputKeysFromList :: [Key] -> SmallArray Key
+ NanoUI.Internal.Input: inputKeysNull :: SmallArray Key -> Bool
+ NanoUI.Internal.Input: inputPointerHeld :: Input -> Bool
+ NanoUI.Internal.Input: instance GHC.Internal.Base.Monoid NanoUI.Internal.Input.Modifiers
+ NanoUI.Internal.Input: instance GHC.Internal.Base.Monoid NanoUI.Internal.Input.MouseButtons
+ NanoUI.Internal.Input: instance GHC.Internal.Base.Semigroup NanoUI.Internal.Input.Modifiers
+ NanoUI.Internal.Input: instance GHC.Internal.Base.Semigroup NanoUI.Internal.Input.MouseButtons
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.Composition
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.DropEvent
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.DropType
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.Input
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.InputPurpose
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.Key
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.Modifiers
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.MouseButton
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.MouseButtons
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Internal.Input.UiCursorKind
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Ord NanoUI.Internal.Input.InputPurpose
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Ord NanoUI.Internal.Input.Key
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Ord NanoUI.Internal.Input.Modifiers
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Ord NanoUI.Internal.Input.MouseButton
+ NanoUI.Internal.Input: instance GHC.Internal.Classes.Ord NanoUI.Internal.Input.UiCursorKind
+ NanoUI.Internal.Input: instance GHC.Internal.Enum.Bounded NanoUI.Internal.Input.InputPurpose
+ NanoUI.Internal.Input: instance GHC.Internal.Enum.Bounded NanoUI.Internal.Input.UiCursorKind
+ NanoUI.Internal.Input: instance GHC.Internal.Enum.Enum NanoUI.Internal.Input.InputPurpose
+ NanoUI.Internal.Input: instance GHC.Internal.Enum.Enum NanoUI.Internal.Input.UiCursorKind
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.Composition
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.DropEvent
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.DropType
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.Input
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.InputPurpose
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.Key
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.Modifiers
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.MouseButton
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.MouseButtons
+ NanoUI.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Internal.Input.UiCursorKind
+ NanoUI.Internal.Input: instance NanoUI.Internal.Input.Pressable NanoUI.Internal.Input.Key
+ NanoUI.Internal.Input: instance NanoUI.Internal.Input.Pressable NanoUI.Internal.Input.MouseButton
+ NanoUI.Internal.Input: isCommandKey :: Modifiers -> Key -> Bool
+ NanoUI.Internal.Input: isHardQuitInput :: Input -> Bool
+ NanoUI.Internal.Input: keypadKey :: Bool -> Char -> Maybe Key
+ NanoUI.Internal.Input: modJump :: Modifiers -> Bool
+ NanoUI.Internal.Input: modMacCommand :: Modifiers -> Bool
+ NanoUI.Internal.Input: modPrimary :: Modifiers -> Bool
+ NanoUI.Internal.Input: modifiersFromBits :: Bits a => a -> a -> a -> a -> a -> Modifiers
+ NanoUI.Internal.Input: mouseButtonNumber :: Int -> MouseButton
+ NanoUI.Internal.Input: noButtons :: MouseButtons
+ NanoUI.Internal.Input: noModifiers :: Modifiers
+ NanoUI.Internal.Input: offWindow :: V2
+ NanoUI.Internal.Input: onMac :: Bool
+ NanoUI.Internal.Input: pressedIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Internal.Input: pressedOnceIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Internal.Input: primaryModifiers :: Modifiers
+ NanoUI.Internal.Input: releaseAllKeys :: Input -> Input
+ NanoUI.Internal.Input: releasedIn :: Pressable a => a -> Input -> Bool
+ NanoUI.Internal.Input: shiftAtMost :: Modifiers -> Bool
+ NanoUI.Internal.Input: stripInteractionInput :: Input -> Input
+ NanoUI.Internal.Input: syncCursorKind :: IORef UiCursorKind -> (Bool -> IO ()) -> (UiCursorKind -> IO ()) -> UiCursorKind -> IO ()
+ NanoUI.Internal.Input: takeFrame :: (Input -> e -> Input) -> (e -> Bool) -> Input -> [e] -> (Input, [e], [e])
+ NanoUI.Internal.Input: withoutPointer :: Input -> Input
+ NanoUI.Internal.Layout.Arena: AdornRows :: NodeIdx -> Float -> NodeIdx -> Float -> Float -> AdornRows
+ NanoUI.Internal.Layout.Arena: AxisSizing :: SizingTag -> Float -> Float -> Float -> AxisSizing
+ NanoUI.Internal.Layout.Arena: AxisSnapshot :: IOArr Int -> IOArr Float -> AxisSnapshot
+ NanoUI.Internal.Layout.Arena: BackdropNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: DirColumn :: DirTag
+ NanoUI.Internal.Layout.Arena: DirRow :: DirTag
+ NanoUI.Internal.Layout.Arena: DrawingNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: FlexScratch :: Int -> IOArr Int -> IOArr Float -> IOArr Float -> IOArr Float -> IOArr Float -> FlexScratch
+ NanoUI.Internal.Layout.Arena: FloatingNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: GeomClipH :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomClipW :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomClipX :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomClipY :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomH :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomLaidW :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomW :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomX :: GeomCol
+ NanoUI.Internal.Layout.Arena: GeomY :: GeomCol
+ NanoUI.Internal.Layout.Arena: ImageNode :: ImageLook -> Float -> Float -> ImageNode
+ NanoUI.Internal.Layout.Arena: LayeredNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: LayoutCache :: Int -> Int -> Word64 -> IntMap CustomMeasureRecord -> Word64 -> IOArr Word64 -> IOArr Float -> IOArr Float -> IOArr Float -> IOArr Float -> IOArr Float -> IOArr Word8 -> IORef (IntMap PlacedFloat) -> LayoutCache
+ NanoUI.Internal.Layout.Arena: NodeArena :: PrimVar RealWorld Int -> PrimVar RealWorld Int -> IORef NodeArenaArrays -> IORef FlexScratch -> IORef (MutableArray RealWorld AxisSnapshot) -> PrimVar RealWorld Word32 -> PrimVar RealWorld Word32 -> IORef IdIndex -> PrimVar RealWorld Int -> PrimVar RealWorld Word64 -> IOArr Word64 -> IOArr Word64 -> IOArr Int -> IORef (MutableArray RealWorld ImageNode) -> IOArr Int -> PrimVar RealWorld Int -> NodeArena
+ NanoUI.Internal.Layout.Arena: NodeArenaArrays :: IOArr Float -> IOArr Float -> IOArr Word8 -> IOArr Int -> IOArr Word64 -> MutableArray RealWorld Text -> MutableArray RealWorld [Text] -> MutableArray RealWorld [Text] -> IOArr Word64 -> IOArr Int -> IOArr Int -> IOArr Word64 -> IOArr Word64 -> IOArr Word64 -> IOArr Word64 -> IOArr Word64 -> IOArr Float -> IOArr Float -> IOArr Float -> IOArr Int -> IOArr Int -> WidthMemo -> WidthMemo -> NodeArenaArrays
+ NanoUI.Internal.Layout.Arena: NodeBox :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeButton :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeColorPicker :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeContainer :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeDrawing :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeImage :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeModal :: NodeType
+ NanoUI.Internal.Layout.Arena: NodePanel :: NodeType
+ NanoUI.Internal.Layout.Arena: NodePopup :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeScrollContainer :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeSelect :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeSeparator :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeShader :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeSlider :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeSpacer :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeText :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeTextArea :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeTextInput :: NodeType
+ NanoUI.Internal.Layout.Arena: NodeWindow :: NodeType
+ NanoUI.Internal.Layout.Arena: PlacedFloat :: Rect -> PrimArray Float -> [(NodeIdx, Float, Float)] -> PlacedFloat
+ NanoUI.Internal.Layout.Arena: PointerNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: ScrollableNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: SizingFit :: SizingTag
+ NanoUI.Internal.Layout.Arena: SizingFixed :: SizingTag
+ NanoUI.Internal.Layout.Arena: SizingGrow :: SizingTag
+ NanoUI.Internal.Layout.Arena: SizingPercent :: SizingTag
+ NanoUI.Internal.Layout.Arena: SizingShrink :: SizingTag
+ NanoUI.Internal.Layout.Arena: StyleAspect :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleFontSize :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleGap :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleGridMinColW :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleHVal :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleLineGap :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleMaxH :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleMaxW :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleMinH :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleMinW :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleNodeValue :: StyleCol
+ NanoUI.Internal.Layout.Arena: StylePadB :: StyleCol
+ NanoUI.Internal.Layout.Arena: StylePadL :: StyleCol
+ NanoUI.Internal.Layout.Arena: StylePadR :: StyleCol
+ NanoUI.Internal.Layout.Arena: StylePadT :: StyleCol
+ NanoUI.Internal.Layout.Arena: StylePinX :: StyleCol
+ NanoUI.Internal.Layout.Arena: StylePinY :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleScrollContentW :: StyleCol
+ NanoUI.Internal.Layout.Arena: StyleWVal :: StyleCol
+ NanoUI.Internal.Layout.Arena: TagAlignX :: TagCol
+ NanoUI.Internal.Layout.Arena: TagAlignY :: TagCol
+ NanoUI.Internal.Layout.Arena: TagBaselineChild :: TagCol
+ NanoUI.Internal.Layout.Arena: TagDirection :: TagCol
+ NanoUI.Internal.Layout.Arena: TagFlow :: TagCol
+ NanoUI.Internal.Layout.Arena: TagHSizing :: TagCol
+ NanoUI.Internal.Layout.Arena: TagHasOptions :: TagCol
+ NanoUI.Internal.Layout.Arena: TagIdSuperseded :: TagCol
+ NanoUI.Internal.Layout.Arena: TagItemsAlign :: TagCol
+ NanoUI.Internal.Layout.Arena: TagJustify :: TagCol
+ NanoUI.Internal.Layout.Arena: TagLineAlign :: TagCol
+ NanoUI.Internal.Layout.Arena: TagNodeType :: TagCol
+ NanoUI.Internal.Layout.Arena: TagPinned :: TagCol
+ NanoUI.Internal.Layout.Arena: TagPinnedBelow :: TagCol
+ NanoUI.Internal.Layout.Arena: TagPointer :: TagCol
+ NanoUI.Internal.Layout.Arena: TagScrollBarSlot :: TagCol
+ NanoUI.Internal.Layout.Arena: TagScrollerBelow :: TagCol
+ NanoUI.Internal.Layout.Arena: TagSteadyHeight :: TagCol
+ NanoUI.Internal.Layout.Arena: TagWSizing :: TagCol
+ NanoUI.Internal.Layout.Arena: TextFieldNodes :: NodeClass
+ NanoUI.Internal.Layout.Arena: TreeChildCount :: TreeCol
+ NanoUI.Internal.Layout.Arena: TreeFirstChild :: TreeCol
+ NanoUI.Internal.Layout.Arena: TreeGridCols :: TreeCol
+ NanoUI.Internal.Layout.Arena: TreeNextSibling :: TreeCol
+ NanoUI.Internal.Layout.Arena: TreeParent :: TreeCol
+ NanoUI.Internal.Layout.Arena: TreeTextIdx :: TreeCol
+ NanoUI.Internal.Layout.Arena: TreeWidgetId :: TreeCol
+ NanoUI.Internal.Layout.Arena: [axMax] :: AxisSizing -> Float
+ NanoUI.Internal.Layout.Arena: [axMin] :: AxisSizing -> Float
+ NanoUI.Internal.Layout.Arena: [axTag] :: AxisSizing -> SizingTag
+ NanoUI.Internal.Layout.Arena: [axVal] :: AxisSizing -> Float
+ NanoUI.Internal.Layout.Arena: [fsCap] :: FlexScratch -> Int
+ NanoUI.Internal.Layout.Arena: [fsGrow] :: FlexScratch -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [fsH] :: FlexScratch -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [fsIdx] :: FlexScratch -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [fsOut] :: FlexScratch -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [fsW] :: FlexScratch -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [inHeight] :: ImageNode -> Float
+ NanoUI.Internal.Layout.Arena: [inLook] :: ImageNode -> ImageLook
+ NanoUI.Internal.Layout.Arena: [inWidth] :: ImageNode -> Float
+ NanoUI.Internal.Layout.Arena: [lcCap] :: LayoutCache -> Int
+ NanoUI.Internal.Layout.Arena: [lcCount] :: LayoutCache -> Int
+ NanoUI.Internal.Layout.Arena: [lcGeom] :: LayoutCache -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [lcMeasureHooks] :: LayoutCache -> Word64
+ NanoUI.Internal.Layout.Arena: [lcMeasured] :: LayoutCache -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [lcMeasures] :: LayoutCache -> IntMap CustomMeasureRecord
+ NanoUI.Internal.Layout.Arena: [lcOffered] :: LayoutCache -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [lcPlaced] :: LayoutCache -> IORef (IntMap PlacedFloat)
+ NanoUI.Internal.Layout.Arena: [lcSig] :: LayoutCache -> Word64
+ NanoUI.Internal.Layout.Arena: [lcStyle] :: LayoutCache -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [lcSub] :: LayoutCache -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [lcTags] :: LayoutCache -> IOArr Word8
+ NanoUI.Internal.Layout.Arena: [lcUnsnapped] :: LayoutCache -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [naArrClassNodes] :: NodeArenaArrays -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naArrFitMemo] :: NodeArenaArrays -> WidthMemo
+ NanoUI.Internal.Layout.Arena: [naArrFontColor] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrGeom] :: NodeArenaArrays -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [naArrImageId] :: NodeArenaArrays -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naArrMeasured] :: NodeArenaArrays -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [naArrOffered] :: NodeArenaArrays -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [naArrOptionsHash] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrOptionsLast] :: NodeArenaArrays -> MutableArray RealWorld [Text]
+ NanoUI.Internal.Layout.Arena: [naArrOptionsStore] :: NodeArenaArrays -> MutableArray RealWorld [Text]
+ NanoUI.Internal.Layout.Arena: [naArrOwnHash] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrPaintHash] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrScope] :: NodeArenaArrays -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naArrSpans] :: NodeArenaArrays -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naArrStyleIdx] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrStyle] :: NodeArenaArrays -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [naArrSubHash] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrTags] :: NodeArenaArrays -> IOArr Word8
+ NanoUI.Internal.Layout.Arena: [naArrTextHash] :: NodeArenaArrays -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naArrTextStore] :: NodeArenaArrays -> MutableArray RealWorld Text
+ NanoUI.Internal.Layout.Arena: [naArrTree] :: NodeArenaArrays -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naArrUnsnapped] :: NodeArenaArrays -> IOArr Float
+ NanoUI.Internal.Layout.Arena: [naArrWrapMemo] :: NodeArenaArrays -> WidthMemo
+ NanoUI.Internal.Layout.Arena: [naArrays] :: NodeArena -> IORef NodeArenaArrays
+ NanoUI.Internal.Layout.Arena: [naCapacity] :: NodeArena -> PrimVar RealWorld Int
+ NanoUI.Internal.Layout.Arena: [naClassCounts] :: NodeArena -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naCount] :: NodeArena -> PrimVar RealWorld Int
+ NanoUI.Internal.Layout.Arena: [naEpoch] :: NodeArena -> PrimVar RealWorld Word32
+ NanoUI.Internal.Layout.Arena: [naFrameTag] :: NodeArena -> PrimVar RealWorld Word32
+ NanoUI.Internal.Layout.Arena: [naHighWater] :: NodeArena -> PrimVar RealWorld Int
+ NanoUI.Internal.Layout.Arena: [naImageCount] :: NodeArena -> IOArr Int
+ NanoUI.Internal.Layout.Arena: [naImages] :: NodeArena -> IORef (MutableArray RealWorld ImageNode)
+ NanoUI.Internal.Layout.Arena: [naIndex] :: NodeArena -> IORef IdIndex
+ NanoUI.Internal.Layout.Arena: [naInputSig] :: NodeArena -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naPaintSig] :: NodeArena -> IOArr Word64
+ NanoUI.Internal.Layout.Arena: [naScopeSig] :: NodeArena -> PrimVar RealWorld Word64
+ NanoUI.Internal.Layout.Arena: [naScope] :: NodeArena -> PrimVar RealWorld Int
+ NanoUI.Internal.Layout.Arena: [naScratch] :: NodeArena -> IORef FlexScratch
+ NanoUI.Internal.Layout.Arena: [naSnapLevels] :: NodeArena -> IORef (MutableArray RealWorld AxisSnapshot)
+ NanoUI.Internal.Layout.Arena: [pfGeom] :: PlacedFloat -> PrimArray Float
+ NanoUI.Internal.Layout.Arena: [pfRect] :: PlacedFloat -> Rect
+ NanoUI.Internal.Layout.Arena: [pfScroll] :: PlacedFloat -> [(NodeIdx, Float, Float)]
+ NanoUI.Internal.Layout.Arena: addNode :: NodeArena -> NodeType -> Int -> Layout -> IO NodeIdx
+ NanoUI.Internal.Layout.Arena: addNodeFromLayout :: NodeArena -> NodeType -> Int -> Layout -> IO NodeIdx
+ NanoUI.Internal.Layout.Arena: adornRows :: NodeArena -> NodeIdx -> IO AdornRows
+ NanoUI.Internal.Layout.Arena: arenaArrays :: NodeArena -> IO NodeArenaArrays
+ NanoUI.Internal.Layout.Arena: arenaCount :: NodeArena -> IO Int
+ NanoUI.Internal.Layout.Arena: axisSizing :: AxisSizing -> Sizing
+ NanoUI.Internal.Layout.Arena: captureLayoutCache :: NodeArena -> LayoutCache -> IO LayoutCache
+ NanoUI.Internal.Layout.Arena: classNodes :: NodeArena -> NodeClass -> IO (Int, Int -> IO NodeIdx)
+ NanoUI.Internal.Layout.Arena: computeSubtreeHashes :: NodeArena -> IO ()
+ NanoUI.Internal.Layout.Arena: data AdornRows
+ NanoUI.Internal.Layout.Arena: data AxisSizing
+ NanoUI.Internal.Layout.Arena: data AxisSnapshot
+ NanoUI.Internal.Layout.Arena: data DirTag
+ NanoUI.Internal.Layout.Arena: data FlexScratch
+ NanoUI.Internal.Layout.Arena: data GeomCol
+ NanoUI.Internal.Layout.Arena: data IdIndex
+ NanoUI.Internal.Layout.Arena: data ImageNode
+ NanoUI.Internal.Layout.Arena: data LayoutCache
+ NanoUI.Internal.Layout.Arena: data NodeArena
+ NanoUI.Internal.Layout.Arena: data NodeArenaArrays
+ NanoUI.Internal.Layout.Arena: data NodeClass
+ NanoUI.Internal.Layout.Arena: data NodeType
+ NanoUI.Internal.Layout.Arena: data PlacedFloat
+ NanoUI.Internal.Layout.Arena: data SizingTag
+ NanoUI.Internal.Layout.Arena: data StyleCol
+ NanoUI.Internal.Layout.Arena: data TagCol
+ NanoUI.Internal.Layout.Arena: data TreeCol
+ NanoUI.Internal.Layout.Arena: data WidthMemo
+ NanoUI.Internal.Layout.Arena: drawnOver :: NodeArena -> NodeIdx -> NodeIdx -> IO Bool
+ NanoUI.Internal.Layout.Arena: effectiveAlignX :: NodeArenaArrays -> ItemsAlign -> NodeIdx -> IO AlignX
+ NanoUI.Internal.Layout.Arena: effectiveAlignY :: NodeArenaArrays -> ItemsAlign -> NodeIdx -> IO AlignY
+ NanoUI.Internal.Layout.Arena: ensureAxisSnapshot :: NodeArena -> Int -> Int -> IO AxisSnapshot
+ NanoUI.Internal.Layout.Arena: ensureScratchCapacity :: NodeArena -> Int -> IO FlexScratch
+ NanoUI.Internal.Layout.Arena: findClassNodeM :: NodeArena -> NodeClass -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: findClassNodeRevM :: NodeArena -> NodeClass -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: findNodeM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: findNodeRevM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: firstChildJustM :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Maybe a)) -> IO (Maybe a)
+ NanoUI.Internal.Layout.Arena: firstChildOnTopJustM :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Maybe a)) -> IO (Maybe a)
+ NanoUI.Internal.Layout.Arena: floatingNodeCount :: NodeArena -> IO Int
+ NanoUI.Internal.Layout.Arena: floatingNodesInPaintOrder :: NodeArena -> IO [NodeIdx]
+ NanoUI.Internal.Layout.Arena: flowChildEnds :: NodeArena -> NodeIdx -> IO (NodeIdx, NodeIdx)
+ NanoUI.Internal.Layout.Arena: flowChildrenInOrder :: NodeArena -> NodeIdx -> IO [NodeIdx]
+ NanoUI.Internal.Layout.Arena: foldClassNodeRevM :: NodeArena -> NodeClass -> (a -> NodeIdx -> IO a) -> a -> IO a
+ NanoUI.Internal.Layout.Arena: foldClassNodesM :: NodeArena -> NodeClass -> (a -> NodeIdx -> IO a) -> a -> IO a
+ NanoUI.Internal.Layout.Arena: foldFlowChildrenM :: NodeArena -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc
+ NanoUI.Internal.Layout.Arena: foldNodesM :: NodeArena -> (a -> NodeIdx -> IO a) -> a -> IO a
+ NanoUI.Internal.Layout.Arena: foldPlacedChildrenM :: NodeArena -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc
+ NanoUI.Internal.Layout.Arena: forChildNodes_ :: NodeArena -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()
+ NanoUI.Internal.Layout.Arena: forChildrenInPaintOrder_ :: NodeArena -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()
+ NanoUI.Internal.Layout.Arena: forClassNodes_ :: NodeArena -> NodeClass -> (NodeIdx -> IO ()) -> IO ()
+ NanoUI.Internal.Layout.Arena: forFloatingNodes_ :: NodeArena -> NodeType -> (NodeIdx -> IO ()) -> IO ()
+ NanoUI.Internal.Layout.Arena: geomStride :: Int
+ NanoUI.Internal.Layout.Arena: getAlignX :: NodeArena -> NodeIdx -> IO AlignX
+ NanoUI.Internal.Layout.Arena: getArenaScope :: NodeArena -> IO Int
+ NanoUI.Internal.Layout.Arena: getClipBounds :: NodeArena -> NodeIdx -> IO (Maybe Rect)
+ NanoUI.Internal.Layout.Arena: getClipRect :: NodeArena -> NodeIdx -> IO (Maybe Rect)
+ NanoUI.Internal.Layout.Arena: getDirection :: NodeArena -> NodeIdx -> IO DirTag
+ NanoUI.Internal.Layout.Arena: getFirstChild :: NodeArena -> NodeIdx -> IO NodeIdx
+ NanoUI.Internal.Layout.Arena: getFlow :: NodeArena -> NodeIdx -> IO Flow
+ NanoUI.Internal.Layout.Arena: getHeightSizing :: NodeArena -> NodeIdx -> IO AxisSizing
+ NanoUI.Internal.Layout.Arena: getIdSuperseded :: NodeArena -> NodeIdx -> IO Bool
+ NanoUI.Internal.Layout.Arena: getImageId :: NodeArena -> NodeIdx -> IO Int
+ NanoUI.Internal.Layout.Arena: getImageNode :: NodeArena -> NodeIdx -> IO (Maybe ImageNode)
+ NanoUI.Internal.Layout.Arena: getNextSibling :: NodeArena -> NodeIdx -> IO NodeIdx
+ NanoUI.Internal.Layout.Arena: getNodeFontColor :: NodeArena -> NodeIdx -> IO (Maybe Color)
+ NanoUI.Internal.Layout.Arena: getNodeFontSize :: NodeArena -> NodeIdx -> IO Float
+ NanoUI.Internal.Layout.Arena: getNodePaintHash :: NodeArena -> NodeIdx -> IO Word64
+ NanoUI.Internal.Layout.Arena: getNodeRect :: NodeArena -> NodeIdx -> IO Rect
+ NanoUI.Internal.Layout.Arena: getNodeScope :: NodeArena -> NodeIdx -> IO Int
+ NanoUI.Internal.Layout.Arena: getNodeType :: NodeArena -> NodeIdx -> IO NodeType
+ NanoUI.Internal.Layout.Arena: getNodeValue :: NodeArena -> NodeIdx -> IO Float
+ NanoUI.Internal.Layout.Arena: getOptions :: NodeArena -> NodeIdx -> IO [Text]
+ NanoUI.Internal.Layout.Arena: getPadding :: NodeArena -> NodeIdx -> IO Padding
+ NanoUI.Internal.Layout.Arena: getPaintSignature :: NodeArena -> IO Word64
+ NanoUI.Internal.Layout.Arena: getParent :: NodeArena -> NodeIdx -> IO NodeIdx
+ NanoUI.Internal.Layout.Arena: getPointerMode :: NodeArena -> NodeIdx -> IO PointerMode
+ NanoUI.Internal.Layout.Arena: getScopeSignature :: NodeArena -> IO Word64
+ NanoUI.Internal.Layout.Arena: getScrollContentW :: NodeArena -> NodeIdx -> IO Float
+ NanoUI.Internal.Layout.Arena: getStyleIdx :: NodeArena -> NodeIdx -> IO Word64
+ NanoUI.Internal.Layout.Arena: getText :: NodeArena -> NodeIdx -> IO Text
+ NanoUI.Internal.Layout.Arena: getWidgetId :: NodeArena -> NodeIdx -> IO WidgetId
+ NanoUI.Internal.Layout.Arena: getWidthSizing :: NodeArena -> NodeIdx -> IO AxisSizing
+ NanoUI.Internal.Layout.Arena: hasBaselineChild :: NodeArenaArrays -> NodeIdx -> IO Bool
+ NanoUI.Internal.Layout.Arena: hasCenteredLabel :: NodeType -> Bool
+ NanoUI.Internal.Layout.Arena: hasPinnedBelow :: NodeArena -> NodeIdx -> IO Bool
+ NanoUI.Internal.Layout.Arena: hasScrollerBelow :: NodeArena -> NodeIdx -> IO Bool
+ NanoUI.Internal.Layout.Arena: isContainerNode :: NodeType -> Bool
+ NanoUI.Internal.Layout.Arena: isFloatingNode :: NodeType -> Bool
+ NanoUI.Internal.Layout.Arena: isScrollNode :: NodeType -> Bool
+ NanoUI.Internal.Layout.Arena: isWidgetNode :: NodeType -> Bool
+ NanoUI.Internal.Layout.Arena: labelFontShift :: Int
+ NanoUI.Internal.Layout.Arena: layeredNodeCount :: NodeArena -> IO Int
+ NanoUI.Internal.Layout.Arena: layoutSigMatches :: NodeArena -> LayoutCache -> IO Bool
+ NanoUI.Internal.Layout.Arena: lookupNodeByKey :: NodeArena -> Int -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: lookupNodeByWidgetId :: NodeArena -> WidgetId -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: memoizeWidth :: NodeArena -> WidthMemo -> NodeIdx -> Float -> IO (Float, Float) -> IO (Float, Float)
+ NanoUI.Internal.Layout.Arena: mixNodePaintHash :: NodeArena -> NodeIdx -> Word64 -> IO ()
+ NanoUI.Internal.Layout.Arena: newLayoutCache :: Int -> IO LayoutCache
+ NanoUI.Internal.Layout.Arena: newNodeArena :: IO NodeArena
+ NanoUI.Internal.Layout.Arena: nodeFontBits :: NodeType -> Word64 -> Word64
+ NanoUI.Internal.Layout.Arena: packsNodeFont :: NodeType -> Bool
+ NanoUI.Internal.Layout.Arena: parentIsRow :: NodeArena -> NodeIdx -> IO Bool
+ NanoUI.Internal.Layout.Arena: readAlignX :: NodeArenaArrays -> NodeIdx -> IO AlignX
+ NanoUI.Internal.Layout.Arena: readAlignY :: NodeArenaArrays -> NodeIdx -> IO AlignY
+ NanoUI.Internal.Layout.Arena: readAxisSizing :: NodeArenaArrays -> NodeIdx -> Bool -> IO AxisSizing
+ NanoUI.Internal.Layout.Arena: readGeom :: NodeArenaArrays -> NodeIdx -> GeomCol -> IO Float
+ NanoUI.Internal.Layout.Arena: readItemsAlign :: NodeArenaArrays -> NodeIdx -> IO ItemsAlign
+ NanoUI.Internal.Layout.Arena: readPadding :: NodeArenaArrays -> NodeIdx -> IO Padding
+ NanoUI.Internal.Layout.Arena: readStyle :: NodeArenaArrays -> NodeIdx -> StyleCol -> IO Float
+ NanoUI.Internal.Layout.Arena: readStyleIdx :: NodeArenaArrays -> NodeIdx -> IO Word64
+ NanoUI.Internal.Layout.Arena: readTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> TagCol -> IO e
+ NanoUI.Internal.Layout.Arena: readTree :: NodeArenaArrays -> NodeIdx -> TreeCol -> IO Int
+ NanoUI.Internal.Layout.Arena: resetNodeArena :: NodeArena -> IO ()
+ NanoUI.Internal.Layout.Arena: restoreLayoutCache :: NodeArena -> LayoutCache -> IO ()
+ NanoUI.Internal.Layout.Arena: restorePlaced :: NodeArena -> NodeIdx -> PlacedFloat -> IO ()
+ NanoUI.Internal.Layout.Arena: restoreScrollExtents :: NodeArenaArrays -> LayoutCache -> NodeIdx -> IO ()
+ NanoUI.Internal.Layout.Arena: rootAttachParent :: NodeArena -> Int -> IO Int
+ NanoUI.Internal.Layout.Arena: scrollableNodeCount :: NodeArena -> IO Int
+ NanoUI.Internal.Layout.Arena: setArenaScope :: NodeArena -> Int -> IO ()
+ NanoUI.Internal.Layout.Arena: setClipRect :: NodeArena -> NodeIdx -> Rect -> IO ()
+ NanoUI.Internal.Layout.Arena: setImageId :: NodeArena -> NodeIdx -> Int -> IO ()
+ NanoUI.Internal.Layout.Arena: setImageNode :: NodeArena -> NodeIdx -> ImageNode -> IO ()
+ NanoUI.Internal.Layout.Arena: setNodeText :: NodeArena -> NodeIdx -> Text -> IO ()
+ NanoUI.Internal.Layout.Arena: setNodeValue :: NodeArena -> NodeIdx -> Float -> IO ()
+ NanoUI.Internal.Layout.Arena: setOptions :: NodeArena -> NodeIdx -> [Text] -> IO ()
+ NanoUI.Internal.Layout.Arena: setRect :: NodeArena -> NodeIdx -> Float -> Float -> Float -> Float -> IO ()
+ NanoUI.Internal.Layout.Arena: setScrollContentW :: NodeArena -> NodeIdx -> Float -> IO ()
+ NanoUI.Internal.Layout.Arena: setSolvedValue :: NodeArena -> NodeIdx -> Float -> IO ()
+ NanoUI.Internal.Layout.Arena: setStyleIdx :: NodeArena -> NodeIdx -> Word64 -> IO ()
+ NanoUI.Internal.Layout.Arena: setWidgetId :: NodeArena -> NodeIdx -> WidgetId -> IO ()
+ NanoUI.Internal.Layout.Arena: snapshotPlaced :: NodeArena -> NodeIdx -> Int -> Rect -> IO PlacedFloat
+ NanoUI.Internal.Layout.Arena: styleStride :: Int
+ NanoUI.Internal.Layout.Arena: subtreeSpan :: NodeArena -> NodeIdx -> IO (Maybe Int)
+ NanoUI.Internal.Layout.Arena: tagStride :: Int
+ NanoUI.Internal.Layout.Arena: textFieldNodeCount :: NodeArena -> IO Int
+ NanoUI.Internal.Layout.Arena: topModalNode :: NodeArena -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Layout.Arena: treeStride :: Int
+ NanoUI.Internal.Layout.Arena: type CustomMeasureRecord = (Word32, Word32, Word32, Word32)
+ NanoUI.Internal.Layout.Arena: type IOArr = MutablePrimArray RealWorld
+ NanoUI.Internal.Layout.Arena: type NodeIdx = Int
+ NanoUI.Internal.Layout.Arena: walkAncestors :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Maybe a)) -> IO (Maybe a)
+ NanoUI.Internal.Layout.Arena: walkFloatingAncestors :: NodeArena -> NodeIdx -> (NodeIdx -> NodeType -> IO (Maybe a)) -> IO (Maybe a)
+ NanoUI.Internal.Layout.Arena: writeClipRectRaw :: NodeArenaArrays -> NodeIdx -> Float -> Float -> Float -> Float -> IO ()
+ NanoUI.Internal.Layout.Arena: writeGeom :: NodeArenaArrays -> NodeIdx -> GeomCol -> Float -> IO ()
+ NanoUI.Internal.Layout.Arena: writeTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> TagCol -> e -> IO ()
+ NanoUI.Internal.Layout.Arena: writeTree :: NodeArenaArrays -> NodeIdx -> TreeCol -> Int -> IO ()
+ NanoUI.Internal.Layout.Solve: Measurers :: FontMetrics -> FontMetrics -> Float -> (Text -> IO (Float, Float)) -> FontResolver -> (WidgetId -> IO (Maybe CustomMeasureFn)) -> TextWrapper -> Measurers
+ NanoUI.Internal.Layout.Solve: [msFm] :: Measurers -> FontMetrics
+ NanoUI.Internal.Layout.Solve: [msFontSize] :: Measurers -> Float
+ NanoUI.Internal.Layout.Solve: [msLookupMeasure] :: Measurers -> WidgetId -> IO (Maybe CustomMeasureFn)
+ NanoUI.Internal.Layout.Solve: [msMeasure] :: Measurers -> Text -> IO (Float, Float)
+ NanoUI.Internal.Layout.Solve: [msMonoFm] :: Measurers -> FontMetrics
+ NanoUI.Internal.Layout.Solve: [msResolveFont] :: Measurers -> FontResolver
+ NanoUI.Internal.Layout.Solve: [msWrap] :: Measurers -> TextWrapper
+ NanoUI.Internal.Layout.Solve: computePopupPosition :: Float -> Float -> Float -> Float -> Float -> PopupAnchor -> PopupPlacement -> Float -> (Float, Float)
+ NanoUI.Internal.Layout.Solve: data Measurers
+ NanoUI.Internal.Layout.Solve: findAncestorMaxW :: NodeArena -> NodeIdx -> IO Float
+ NanoUI.Internal.Layout.Solve: measuredHeightAt :: FontMetrics -> CustomMeasureFn -> Float -> AxisSizing -> Float
+ NanoUI.Internal.Layout.Solve: placeFloatingNodes :: NodeArena -> Measurers -> Float -> Float -> (WidgetId -> IO (Maybe (Float, Float))) -> (WidgetId -> IO (Maybe (Float, Float))) -> (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) -> Maybe (IORef (IntMap PlacedFloat)) -> IO ()
+ NanoUI.Internal.Layout.Solve: placeFloatingNodesWith :: NodeArena -> Measurers -> Float -> Float -> (WidgetId -> IO (Maybe (Float, Float))) -> (WidgetId -> IO (Maybe (Float, Float))) -> (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) -> (WidgetId -> Float -> Float -> IO (Maybe Rect)) -> Maybe (IORef (IntMap PlacedFloat)) -> IO ()
+ NanoUI.Internal.Layout.Solve: runCustomMeasure :: NodeArena -> FontMetrics -> CustomMeasureFn -> NodeIdx -> IO CustomMeasureRecord
+ NanoUI.Internal.Layout.Solve: scrollBarSlotOf :: NodeArena -> NodeIdx -> IO ScrollBarSlot
+ NanoUI.Internal.Layout.Solve: solveLayout :: NodeArena -> Measurers -> Float -> Float -> Maybe LayoutCache -> IO (IntMap CustomMeasureRecord)
+ NanoUI.Internal.Layout.Solve: textWrapCap :: Float -> SizingTag -> Float -> Float
+ NanoUI.Internal.Layout.Solve: windowBodyScroller :: NodeArena -> NodeIdx -> IO (Maybe NodeIdx)
+ NanoUI.Internal.Monad: (<&&>) :: Monad m => m Bool -> m Bool -> m Bool
+ NanoUI.Internal.Monad: NanoUI :: Eff NanoUIEs a -> NanoUI a
+ NanoUI.Internal.Monad: [unNanoUI] :: NanoUI a -> Eff NanoUIEs a
+ NanoUI.Internal.Monad: askBackendSession :: forall (b :: Backend). SBackend b -> NanoUI (Maybe (BackendSession b))
+ NanoUI.Internal.Monad: askContext :: NanoUI Context
+ NanoUI.Internal.Monad: askDefaultLayout :: NanoUI Layout
+ NanoUI.Internal.Monad: askFrameInput :: NanoUI Input
+ NanoUI.Internal.Monad: askHost :: Host a -> NanoUI (Maybe a)
+ NanoUI.Internal.Monad: askInput :: NanoUI Input
+ NanoUI.Internal.Monad: burstNextIds :: Int -> NanoUI ()
+ NanoUI.Internal.Monad: catchView :: Exception e => NanoUI a -> (e -> NanoUI a) -> NanoUI a
+ NanoUI.Internal.Monad: clearFocus :: NanoUI ()
+ NanoUI.Internal.Monad: currentId :: NanoUI WidgetId
+ NanoUI.Internal.Monad: damageFullNow :: NanoUI ()
+ NanoUI.Internal.Monad: damageGroupNow :: [WidgetId] -> DamageBounds -> NanoUI ()
+ NanoUI.Internal.Monad: damageKeyNow :: Int -> DamageBounds -> NanoUI ()
+ NanoUI.Internal.Monad: damageRectNow :: Rect -> NanoUI ()
+ NanoUI.Internal.Monad: damageWidgetNow :: WidgetId -> DamageBounds -> NanoUI ()
+ NanoUI.Internal.Monad: data Ui (a :: Type -> Type) b
+ NanoUI.Internal.Monad: disabledWhen :: Bool -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: embedNanoUI :: forall (es :: [Effect]) a. Ui :> es => NanoUI a -> Eff es a
+ NanoUI.Internal.Monad: explainLayout :: Bool -> NanoUI ()
+ NanoUI.Internal.Monad: explainScope :: NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: explainedNode :: NanoUI (Maybe ExplainedNode)
+ NanoUI.Internal.Monad: explainingLayout :: NanoUI Bool
+ NanoUI.Internal.Monad: focusNext :: NanoUI ()
+ NanoUI.Internal.Monad: focusPrevious :: NanoUI ()
+ NanoUI.Internal.Monad: focusedWidget :: NanoUI WidgetId
+ NanoUI.Internal.Monad: followSystemTheme :: (Maybe Appearance -> Theme) -> NanoUI ()
+ NanoUI.Internal.Monad: freshWidget :: NanoUI (WidgetId, Context)
+ NanoUI.Internal.Monad: getClipboard :: NanoUI (Maybe Text)
+ NanoUI.Internal.Monad: getScrollMetrics :: WidgetId -> NanoUI (Maybe ScrollMetrics)
+ NanoUI.Internal.Monad: getScrollTuning :: NanoUI ScrollTuning
+ NanoUI.Internal.Monad: holdFocus :: WidgetId -> NanoUI ()
+ NanoUI.Internal.Monad: ifM :: Monad m => m Bool -> m a -> m a -> m a
+ NanoUI.Internal.Monad: inArenaRange :: Int -> Int -> Int -> Bool
+ NanoUI.Internal.Monad: inertView :: NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: infixr 3 <&&>
+ NanoUI.Internal.Monad: isFocused :: WidgetId -> NanoUI Bool
+ NanoUI.Internal.Monad: keyedTag :: Word64 -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: lastRect :: WidgetId -> NanoUI (Maybe Rect)
+ NanoUI.Internal.Monad: liftIO :: MonadIO m => IO a -> m a
+ NanoUI.Internal.Monad: lineWidthUi :: FontMetrics -> Text -> NanoUI Float
+ NanoUI.Internal.Monad: localInput :: Input -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: mfilterM :: Monad m => (a -> m Bool) -> Maybe a -> m (Maybe a)
+ NanoUI.Internal.Monad: mouseHeld :: MouseButton -> NanoUI Bool
+ NanoUI.Internal.Monad: mousePressed :: MouseButton -> NanoUI Bool
+ NanoUI.Internal.Monad: mouseReleased :: MouseButton -> NanoUI Bool
+ NanoUI.Internal.Monad: newtype NanoUI a
+ NanoUI.Internal.Monad: nextId :: NanoUI WidgetId
+ NanoUI.Internal.Monad: releaseFocus :: WidgetId -> NanoUI ()
+ NanoUI.Internal.Monad: requestFocus :: WidgetId -> NanoUI ()
+ NanoUI.Internal.Monad: requestFrame :: NanoUI ()
+ NanoUI.Internal.Monad: resolveFontUi :: Float -> FontWeight -> FontStyle -> FontVariant -> NanoUI FontMetrics
+ NanoUI.Internal.Monad: runNanoUI :: Context -> Input -> NanoUI a -> IO a
+ NanoUI.Internal.Monad: runUi :: forall (es :: [Effect]) a. IOE :> es => Context -> Input -> Eff (Ui ': es) a -> Eff es a
+ NanoUI.Internal.Monad: scope :: NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: scrollBy :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: scrollIntoView :: WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: scrollPages :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: scrollRectIntoView :: WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: scrollTo :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: scrollToEnd :: WidgetId -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: scrollToStart :: WidgetId -> ScrollBehavior -> NanoUI ()
+ NanoUI.Internal.Monad: setClipboard :: Text -> NanoUI Bool
+ NanoUI.Internal.Monad: setScrollOffset :: WidgetId -> V2 -> NanoUI ()
+ NanoUI.Internal.Monad: setScrollStep :: WidgetId -> Float -> NanoUI ()
+ NanoUI.Internal.Monad: setScrollTuning :: ScrollTuning -> NanoUI ()
+ NanoUI.Internal.Monad: setTheme :: Theme -> NanoUI ()
+ NanoUI.Internal.Monad: styled :: (Theme -> Theme) -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: systemAppearance :: NanoUI (Maybe Appearance)
+ NanoUI.Internal.Monad: takeEscape :: NanoUI Bool
+ NanoUI.Internal.Monad: themed :: Theme -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: truncateTextUi :: FontMetrics -> Float -> Text -> NanoUI Text
+ NanoUI.Internal.Monad: truncateTextWithUi :: TextEllipsis -> FontMetrics -> Float -> Text -> NanoUI Text
+ NanoUI.Internal.Monad: type NanoUIEs = '[Ui, IOE]
+ NanoUI.Internal.Monad: uiFontMetrics :: NanoUI FontMetrics
+ NanoUI.Internal.Monad: uiFontSize :: NanoUI Float
+ NanoUI.Internal.Monad: uiMousePos :: NanoUI V2
+ NanoUI.Internal.Monad: uiTheme :: NanoUI Theme
+ NanoUI.Internal.Monad: uiTime :: NanoUI Double
+ NanoUI.Internal.Monad: unlessM :: Monad m => m Bool -> m () -> m ()
+ NanoUI.Internal.Monad: whenM :: Monad m => m Bool -> m () -> m ()
+ NanoUI.Internal.Monad: windowHeight :: NanoUI Float
+ NanoUI.Internal.Monad: windowSize :: NanoUI Size
+ NanoUI.Internal.Monad: windowWidth :: NanoUI Float
+ NanoUI.Internal.Monad: withArenaRange :: (Int -> Int -> IO ()) -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: withBuildScope :: IO a -> (a -> IO ()) -> NanoUI b -> NanoUI b
+ NanoUI.Internal.Monad: withContext :: (Context -> IO a) -> NanoUI a
+ NanoUI.Internal.Monad: withDefaultLayout :: (Layout -> Layout) -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: withIdFrame :: (IdContext -> (IdContext, IdContext)) -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: withKey :: Hashable k => k -> NanoUI a -> NanoUI a
+ NanoUI.Internal.Monad: withRunInNanoUI :: forall (es :: [Effect]) a. Ui :> es => ((forall r. () => Eff es r -> NanoUI r) -> NanoUI a) -> Eff es a
+ NanoUI.Internal.Monad: withUiResource :: IO a -> (a -> IO ()) -> NanoUI b -> NanoUI b
+ NanoUI.Internal.Path: BevelJoin :: LineJoin
+ NanoUI.Internal.Path: ButtCap :: LineCap
+ NanoUI.Internal.Path: EvenOdd :: FillRule
+ NanoUI.Internal.Path: Flat :: Color -> Shade
+ NanoUI.Internal.Path: Linear :: V2 -> V2 -> [(Float, Color)] -> Paint
+ NanoUI.Internal.Path: MiterJoin :: LineJoin
+ NanoUI.Internal.Path: NonZero :: FillRule
+ NanoUI.Internal.Path: Path :: [Segment] -> Path
+ NanoUI.Internal.Path: Rings :: PrimArray Float -> PrimArray Int -> PrimArray Int -> Rings
+ NanoUI.Internal.Path: RoundCap :: LineCap
+ NanoUI.Internal.Path: RoundJoin :: LineJoin
+ NanoUI.Internal.Path: SegArc :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Segment
+ NanoUI.Internal.Path: SegArcTo :: Float -> Float -> Float -> Bool -> Bool -> Float -> Float -> Segment
+ NanoUI.Internal.Path: SegClose :: Segment
+ NanoUI.Internal.Path: SegCubic :: Float -> Float -> Float -> Float -> Float -> Float -> Segment
+ NanoUI.Internal.Path: SegLine :: Float -> Float -> Segment
+ NanoUI.Internal.Path: SegMove :: Float -> Float -> Segment
+ NanoUI.Internal.Path: SegQuad :: Float -> Float -> Float -> Float -> Segment
+ NanoUI.Internal.Path: Shaded :: PrimArray Word32 -> Shade
+ NanoUI.Internal.Path: Solid :: Color -> Paint
+ NanoUI.Internal.Path: SquareCap :: LineCap
+ NanoUI.Internal.Path: StrokeStyle :: Float -> LineCap -> LineJoin -> Float -> [Float] -> Float -> Stroke
+ NanoUI.Internal.Path: Transform :: Float -> Float -> Float -> Float -> Float -> Float -> Transform
+ NanoUI.Internal.Path: [strokeCap] :: Stroke -> LineCap
+ NanoUI.Internal.Path: [strokeDashOffset] :: Stroke -> Float
+ NanoUI.Internal.Path: [strokeDash] :: Stroke -> [Float]
+ NanoUI.Internal.Path: [strokeJoin] :: Stroke -> LineJoin
+ NanoUI.Internal.Path: [strokeMiterLimit] :: Stroke -> Float
+ NanoUI.Internal.Path: [strokeWidth] :: Stroke -> Float
+ NanoUI.Internal.Path: affine :: Float -> Float -> Float -> Float -> Float -> Float -> Transform
+ NanoUI.Internal.Path: applyTransform :: Transform -> Float -> Float -> (Float, Float)
+ NanoUI.Internal.Path: arc :: V2 -> Float -> Float -> Float -> Path
+ NanoUI.Internal.Path: arcTo :: V2 -> Float -> Bool -> Bool -> V2 -> Path
+ NanoUI.Internal.Path: averageStretch :: Transform -> Float
+ NanoUI.Internal.Path: buildRings :: (forall s. () => (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()) -> Rings
+ NanoUI.Internal.Path: circle :: V2 -> Float -> Path
+ NanoUI.Internal.Path: cleanRings :: Bool -> Rings -> [(PrimArray Float, Bool)]
+ NanoUI.Internal.Path: close :: Path
+ NanoUI.Internal.Path: cubicTo :: V2 -> V2 -> V2 -> Path
+ NanoUI.Internal.Path: curveTolerance :: Float -> Float
+ NanoUI.Internal.Path: data FillRule
+ NanoUI.Internal.Path: data LineCap
+ NanoUI.Internal.Path: data LineJoin
+ NanoUI.Internal.Path: data Paint
+ NanoUI.Internal.Path: data Rings
+ NanoUI.Internal.Path: data Segment
+ NanoUI.Internal.Path: data Shade
+ NanoUI.Internal.Path: data Stroke
+ NanoUI.Internal.Path: data Transform
+ NanoUI.Internal.Path: ellipse :: V2 -> V2 -> Path
+ NanoUI.Internal.Path: ellipticalArc :: V2 -> V2 -> Float -> Float -> Float -> Path
+ NanoUI.Internal.Path: fillPathOps :: Float -> Transform -> FillRule -> Path -> Paint -> [DrawOp]
+ NanoUI.Internal.Path: fillsWinding :: FillRule -> Int -> Bool
+ NanoUI.Internal.Path: flattenPath :: Float -> (Float -> Float -> Int) -> Transform -> Path -> Rings
+ NanoUI.Internal.Path: idealArcSteps :: Float -> Float -> Float -> Float
+ NanoUI.Internal.Path: instance GHC.Internal.Base.Monoid NanoUI.Internal.Path.Path
+ NanoUI.Internal.Path: instance GHC.Internal.Base.Monoid NanoUI.Internal.Path.Transform
+ NanoUI.Internal.Path: instance GHC.Internal.Base.Semigroup NanoUI.Internal.Path.Path
+ NanoUI.Internal.Path: instance GHC.Internal.Base.Semigroup NanoUI.Internal.Path.Transform
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Eq NanoUI.Internal.Path.FillRule
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Eq NanoUI.Internal.Path.Paint
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Eq NanoUI.Internal.Path.Path
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Eq NanoUI.Internal.Path.Segment
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Eq NanoUI.Internal.Path.Stroke
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Eq NanoUI.Internal.Path.Transform
+ NanoUI.Internal.Path: instance GHC.Internal.Classes.Ord NanoUI.Internal.Path.FillRule
+ NanoUI.Internal.Path: instance GHC.Internal.Enum.Bounded NanoUI.Internal.Path.FillRule
+ NanoUI.Internal.Path: instance GHC.Internal.Enum.Enum NanoUI.Internal.Path.FillRule
+ NanoUI.Internal.Path: instance GHC.Internal.Show.Show NanoUI.Internal.Path.FillRule
+ NanoUI.Internal.Path: instance GHC.Internal.Show.Show NanoUI.Internal.Path.Paint
+ NanoUI.Internal.Path: instance GHC.Internal.Show.Show NanoUI.Internal.Path.Path
+ NanoUI.Internal.Path: instance GHC.Internal.Show.Show NanoUI.Internal.Path.Segment
+ NanoUI.Internal.Path: instance GHC.Internal.Show.Show NanoUI.Internal.Path.Stroke
+ NanoUI.Internal.Path: instance GHC.Internal.Show.Show NanoUI.Internal.Path.Transform
+ NanoUI.Internal.Path: invert :: Transform -> Maybe Transform
+ NanoUI.Internal.Path: lineTo :: V2 -> Path
+ NanoUI.Internal.Path: miterOffset :: Float -> Float -> Float -> Float -> Float -> Maybe (Float, Float)
+ NanoUI.Internal.Path: moveTo :: V2 -> Path
+ NanoUI.Internal.Path: newtype Path
+ NanoUI.Internal.Path: polygon :: [V2] -> Path
+ NanoUI.Internal.Path: polyline :: [V2] -> Path
+ NanoUI.Internal.Path: quadTo :: V2 -> V2 -> Path
+ NanoUI.Internal.Path: rect :: Rect -> Path
+ NanoUI.Internal.Path: ringBox :: PrimArray Float -> (Float, Float, Float, Float)
+ NanoUI.Internal.Path: ringCount :: Rings -> Int
+ NanoUI.Internal.Path: rotate :: Float -> Transform
+ NanoUI.Internal.Path: rotateAround :: V2 -> Float -> Transform
+ NanoUI.Internal.Path: roundedRect :: Rect -> Float -> Path
+ NanoUI.Internal.Path: roundedRectCorners :: Rect -> Float -> Float -> Float -> Float -> Path
+ NanoUI.Internal.Path: scale :: Float -> Float -> Transform
+ NanoUI.Internal.Path: shoelace :: Int -> (Int -> (Float, Float)) -> Float
+ NanoUI.Internal.Path: stroke :: Float -> Stroke
+ NanoUI.Internal.Path: strokePathOps :: Float -> Transform -> Stroke -> Path -> Paint -> [DrawOp]
+ NanoUI.Internal.Path: transformFinite :: Transform -> Bool
+ NanoUI.Internal.Path: transformOp :: Float -> Transform -> DrawOp -> [DrawOp]
+ NanoUI.Internal.Path: transformPoint :: Transform -> V2 -> V2
+ NanoUI.Internal.Path: translate :: Float -> Float -> Transform
+ NanoUI.Internal.RichText.Types: Break :: TokenKind
+ NanoUI.Internal.RichText.Types: Glyph :: TokenKind
+ NanoUI.Internal.RichText.Types: GlyphSpace :: TokenKind
+ NanoUI.Internal.RichText.Types: Inline :: Text -> InlineStyle -> Maybe Text -> Maybe Color -> Maybe Text -> Inline
+ NanoUI.Internal.RichText.Types: InlineBold :: InlineStyle
+ NanoUI.Internal.RichText.Types: InlineCustom :: (Layout -> Layout) -> InlineStyle
+ NanoUI.Internal.RichText.Types: InlineItalic :: InlineStyle
+ NanoUI.Internal.RichText.Types: InlineMono :: InlineStyle
+ NanoUI.Internal.RichText.Types: InlinePlain :: InlineStyle
+ NanoUI.Internal.RichText.Types: Inputs :: [Inline] -> Layout -> Theme -> Int -> Bool -> Inputs
+ NanoUI.Internal.RichText.Types: InteractivePiece :: Int -> Float -> Float -> Float -> Float -> InteractivePiece
+ NanoUI.Internal.RichText.Types: Line :: Int -> Float -> Float -> Float -> Float -> [(Float, Token)] -> Line
+ NanoUI.Internal.RichText.Types: Measured :: Float -> Float -> Float -> Measured
+ NanoUI.Internal.RichText.Types: Paragraph :: Int -> IORef Inputs -> SmallArray Run -> [Token] -> (Float, Float) -> (Float, Float) -> Float -> [Line] -> [InteractivePiece] -> [(Int, Text)] -> Bool -> Bool -> IORef Measured -> Text -> TextBuffer -> Paragraph
+ NanoUI.Internal.RichText.Types: ParagraphCache :: Int -> Int -> IntMap Paragraph -> ParagraphCache
+ NanoUI.Internal.RichText.Types: Paragraphs :: IORef ParagraphCache -> Paragraphs
+ NanoUI.Internal.RichText.Types: RichSelection :: Text -> Cursor -> Cursor -> Bool -> Bool -> Int -> Int -> RichSelection
+ NanoUI.Internal.RichText.Types: Run :: TextFont -> Color -> Float -> Float -> Maybe Text -> Maybe Color -> Maybe Text -> Run
+ NanoUI.Internal.RichText.Types: Space :: TokenKind
+ NanoUI.Internal.RichText.Types: Token :: Text -> Int -> TokenKind -> Float -> Int -> FontMetrics -> Token
+ NanoUI.Internal.RichText.Types: Unmeasured :: Measured
+ NanoUI.Internal.RichText.Types: Word :: TokenKind
+ NanoUI.Internal.RichText.Types: [ipH] :: InteractivePiece -> Float
+ NanoUI.Internal.RichText.Types: [ipRun] :: InteractivePiece -> Int
+ NanoUI.Internal.RichText.Types: [ipW] :: InteractivePiece -> Float
+ NanoUI.Internal.RichText.Types: [ipX] :: InteractivePiece -> Float
+ NanoUI.Internal.RichText.Types: [ipY] :: InteractivePiece -> Float
+ NanoUI.Internal.RichText.Types: [lineAscent] :: Line -> Float
+ NanoUI.Internal.RichText.Types: [lineHeight] :: Line -> Float
+ NanoUI.Internal.RichText.Types: [lineStart] :: Line -> Int
+ NanoUI.Internal.RichText.Types: [lineTokens] :: Line -> [(Float, Token)]
+ NanoUI.Internal.RichText.Types: [lineTop] :: Line -> Float
+ NanoUI.Internal.RichText.Types: [lineWidth] :: Line -> Float
+ NanoUI.Internal.RichText.Types: [paraBuffer] :: Paragraph -> TextBuffer
+ NanoUI.Internal.RichText.Types: [paraEmptyLine] :: Paragraph -> (Float, Float)
+ NanoUI.Internal.RichText.Types: [paraHasGlyphs] :: Paragraph -> Bool
+ NanoUI.Internal.RichText.Types: [paraHasInteractive] :: Paragraph -> Bool
+ NanoUI.Internal.RichText.Types: [paraInputs] :: Paragraph -> IORef Inputs
+ NanoUI.Internal.RichText.Types: [paraInteractive] :: Paragraph -> [InteractivePiece]
+ NanoUI.Internal.RichText.Types: [paraKey] :: Paragraph -> Int
+ NanoUI.Internal.RichText.Types: [paraLines] :: Paragraph -> [Line]
+ NanoUI.Internal.RichText.Types: [paraMeasured] :: Paragraph -> IORef Measured
+ NanoUI.Internal.RichText.Types: [paraNatural] :: Paragraph -> (Float, Float)
+ NanoUI.Internal.RichText.Types: [paraRuns] :: Paragraph -> SmallArray Run
+ NanoUI.Internal.RichText.Types: [paraText] :: Paragraph -> Text
+ NanoUI.Internal.RichText.Types: [paraTokens] :: Paragraph -> [Token]
+ NanoUI.Internal.RichText.Types: [paraTooltipRuns] :: Paragraph -> [(Int, Text)]
+ NanoUI.Internal.RichText.Types: [paraWidth] :: Paragraph -> Float
+ NanoUI.Internal.RichText.Types: [runAscent] :: Run -> Float
+ NanoUI.Internal.RichText.Types: [runBackground] :: Run -> Maybe Color
+ NanoUI.Internal.RichText.Types: [runColor] :: Run -> Color
+ NanoUI.Internal.RichText.Types: [runFont] :: Run -> TextFont
+ NanoUI.Internal.RichText.Types: [runLineHeight] :: Run -> Float
+ NanoUI.Internal.RichText.Types: [runTarget] :: Run -> Maybe Text
+ NanoUI.Internal.RichText.Types: [runTooltip] :: Run -> Maybe Text
+ NanoUI.Internal.RichText.Types: [selectionAnchor] :: RichSelection -> Cursor
+ NanoUI.Internal.RichText.Types: [selectionCursor] :: RichSelection -> Cursor
+ NanoUI.Internal.RichText.Types: [selectionDragging] :: RichSelection -> Bool
+ NanoUI.Internal.RichText.Types: [selectionEnd] :: RichSelection -> Int
+ NanoUI.Internal.RichText.Types: [selectionMoved] :: RichSelection -> Bool
+ NanoUI.Internal.RichText.Types: [selectionStart] :: RichSelection -> Int
+ NanoUI.Internal.RichText.Types: [selectionText] :: RichSelection -> Text
+ NanoUI.Internal.RichText.Types: [tokenKind] :: Token -> TokenKind
+ NanoUI.Internal.RichText.Types: [tokenMetrics] :: Token -> FontMetrics
+ NanoUI.Internal.RichText.Types: [tokenRun] :: Token -> Int
+ NanoUI.Internal.RichText.Types: [tokenStart] :: Token -> Int
+ NanoUI.Internal.RichText.Types: [tokenText] :: Token -> Text
+ NanoUI.Internal.RichText.Types: [tokenWidth] :: Token -> Float
+ NanoUI.Internal.RichText.Types: data Inline
+ NanoUI.Internal.RichText.Types: data InlineStyle
+ NanoUI.Internal.RichText.Types: data Inputs
+ NanoUI.Internal.RichText.Types: data InteractivePiece
+ NanoUI.Internal.RichText.Types: data Line
+ NanoUI.Internal.RichText.Types: data Measured
+ NanoUI.Internal.RichText.Types: data Paragraph
+ NanoUI.Internal.RichText.Types: data ParagraphCache
+ NanoUI.Internal.RichText.Types: data RichSelection
+ NanoUI.Internal.RichText.Types: data Run
+ NanoUI.Internal.RichText.Types: data Token
+ NanoUI.Internal.RichText.Types: data TokenKind
+ NanoUI.Internal.RichText.Types: inlineText :: Text -> Inline
+ NanoUI.Internal.RichText.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.RichText.Types.RichSelection
+ NanoUI.Internal.RichText.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.RichText.Types.TokenKind
+ NanoUI.Internal.RichText.Types: instance GHC.Internal.Data.String.IsString NanoUI.Internal.RichText.Types.Inline
+ NanoUI.Internal.RichText.Types: newtype Paragraphs
+ NanoUI.Internal.SIMD: concentricOffsetsSIMD :: Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> ((Float, Float), (Float, Float), (Float, Float), (Float, Float))
+ NanoUI.Internal.SIMD: pokeQuadCornersSIMD :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Word32 -> IO ()
+ NanoUI.Internal.SIMD: pokeQuadGradientSIMD :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float, Float, Float) -> (Float, Float, Float, Float) -> (Float, Float, Float, Float) -> (Float, Float, Float, Float) -> Word32 -> IO ()
+ NanoUI.Internal.SIMD: pokeQuadIndices :: Ptr Word8 -> Int -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()
+ NanoUI.Internal.SIMD: pokeQuadSIMD :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Word32 -> IO ()
+ NanoUI.Internal.SIMD: pokeVertexSIMD :: Ptr Word8 -> Int -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> IO ()
+ NanoUI.Internal.Shader: ColorEffect :: ShaderKind
+ NanoUI.Internal.Shader: CpuFragCtx :: V2 -> V2 -> V2 -> Float -> Color -> Float -> CpuFragCtx
+ NanoUI.Internal.Shader: DistortionEffect :: ShaderKind
+ NanoUI.Internal.Shader: LayerEffect :: ShaderKind
+ NanoUI.Internal.Shader: PackedShaderPass :: Word64 -> ShaderProgram -> ByteArray -> Word64 -> PackedShaderPass
+ NanoUI.Internal.Shader: Shader :: Word64 -> [ShaderPass u] -> (u -> V2) -> Maybe (u -> CpuShaderEval) -> Maybe (u -> Float) -> Maybe Dynamic -> Shader (k :: ShaderKind) u
+ NanoUI.Internal.Shader: ShaderCapabilities :: Bool -> Bool -> ShaderCapabilities
+ NanoUI.Internal.Shader: ShaderConfig :: LayoutModifier -> Float -> Color -> Color -> ShaderConfig
+ NanoUI.Internal.Shader: ShaderEffectEntry :: [PackedShaderPass] -> V2 -> Maybe Float -> ShaderEffectEntry
+ NanoUI.Internal.Shader: ShaderNodeEntry :: PackedShaderPass -> Float -> Color -> Color -> ShaderNodeEntry
+ NanoUI.Internal.Shader: ShaderPass :: Word64 -> ShaderProgram -> Int -> (u -> MutableByteArray RealWorld -> Int -> IO ()) -> ShaderPass u
+ NanoUI.Internal.Shader: ShaderProgram :: Maybe Text -> Maybe Text -> Maybe ByteString -> Maybe Text -> Bool -> [UniformField] -> Int -> ShaderProgram
+ NanoUI.Internal.Shader: Surface :: ShaderKind
+ NanoUI.Internal.Shader: [capNodeEffects] :: ShaderCapabilities -> Bool
+ NanoUI.Internal.Shader: [capSurfaceShaders] :: ShaderCapabilities -> Bool
+ NanoUI.Internal.Shader: [cfcColor] :: CpuFragCtx -> Color
+ NanoUI.Internal.Shader: [cfcCornerRadius] :: CpuFragCtx -> Float
+ NanoUI.Internal.Shader: [cfcPos] :: CpuFragCtx -> V2
+ NanoUI.Internal.Shader: [cfcScale] :: CpuFragCtx -> Float
+ NanoUI.Internal.Shader: [cfcSize] :: CpuFragCtx -> V2
+ NanoUI.Internal.Shader: [cfcUv] :: CpuFragCtx -> V2
+ NanoUI.Internal.Shader: [pspHash] :: PackedShaderPass -> Word64
+ NanoUI.Internal.Shader: [pspProgram] :: PackedShaderPass -> ShaderProgram
+ NanoUI.Internal.Shader: [pspUniformHash] :: PackedShaderPass -> Word64
+ NanoUI.Internal.Shader: [pspUniforms] :: PackedShaderPass -> ByteArray
+ NanoUI.Internal.Shader: [scCornerRadius] :: ShaderConfig -> Float
+ NanoUI.Internal.Shader: [scFallback] :: ShaderConfig -> Color
+ NanoUI.Internal.Shader: [scLayout] :: ShaderConfig -> LayoutModifier
+ NanoUI.Internal.Shader: [scTint] :: ShaderConfig -> Color
+ NanoUI.Internal.Shader: [seeMargin] :: ShaderEffectEntry -> V2
+ NanoUI.Internal.Shader: [seePasses] :: ShaderEffectEntry -> [PackedShaderPass]
+ NanoUI.Internal.Shader: [seeSvgOpacity] :: ShaderEffectEntry -> Maybe Float
+ NanoUI.Internal.Shader: [shaderCpuEval] :: Shader (k :: ShaderKind) u -> Maybe (u -> CpuShaderEval)
+ NanoUI.Internal.Shader: [shaderFusion] :: Shader (k :: ShaderKind) u -> Maybe Dynamic
+ NanoUI.Internal.Shader: [shaderHash] :: Shader (k :: ShaderKind) u -> Word64
+ NanoUI.Internal.Shader: [shaderMargin] :: Shader (k :: ShaderKind) u -> u -> V2
+ NanoUI.Internal.Shader: [shaderPasses] :: Shader (k :: ShaderKind) u -> [ShaderPass u]
+ NanoUI.Internal.Shader: [shaderSvgOpacity] :: Shader (k :: ShaderKind) u -> Maybe (u -> Float)
+ NanoUI.Internal.Shader: [sneCornerRadius] :: ShaderNodeEntry -> Float
+ NanoUI.Internal.Shader: [sneFallback] :: ShaderNodeEntry -> Color
+ NanoUI.Internal.Shader: [snePass] :: ShaderNodeEntry -> PackedShaderPass
+ NanoUI.Internal.Shader: [sneTint] :: ShaderNodeEntry -> Color
+ NanoUI.Internal.Shader: [spGlsl150] :: ShaderProgram -> Maybe Text
+ NanoUI.Internal.Shader: [spGlslEs300] :: ShaderProgram -> Maybe Text
+ NanoUI.Internal.Shader: [spHash] :: ShaderPass u -> Word64
+ NanoUI.Internal.Shader: [spMsl] :: ShaderProgram -> Maybe Text
+ NanoUI.Internal.Shader: [spNeedsTex] :: ShaderProgram -> Bool
+ NanoUI.Internal.Shader: [spPack] :: ShaderPass u -> u -> MutableByteArray RealWorld -> Int -> IO ()
+ NanoUI.Internal.Shader: [spProgram] :: ShaderPass u -> ShaderProgram
+ NanoUI.Internal.Shader: [spSpirv] :: ShaderProgram -> Maybe ByteString
+ NanoUI.Internal.Shader: [spUniformBytes] :: ShaderProgram -> Int
+ NanoUI.Internal.Shader: [spUniformLayout] :: ShaderProgram -> [UniformField]
+ NanoUI.Internal.Shader: [spUniformSize] :: ShaderPass u -> Int
+ NanoUI.Internal.Shader: class IsNodeEffect (k :: ShaderKind)
+ NanoUI.Internal.Shader: contramapShader :: forall u2 u1 (k :: ShaderKind). (u2 -> u1) -> Shader k u1 -> Shader k u2
+ NanoUI.Internal.Shader: data CpuFragCtx
+ NanoUI.Internal.Shader: data PackedShaderPass
+ NanoUI.Internal.Shader: data Shader (k :: ShaderKind) u
+ NanoUI.Internal.Shader: data ShaderCapabilities
+ NanoUI.Internal.Shader: data ShaderConfig
+ NanoUI.Internal.Shader: data ShaderEffectEntry
+ NanoUI.Internal.Shader: data ShaderKind
+ NanoUI.Internal.Shader: data ShaderNodeEntry
+ NanoUI.Internal.Shader: data ShaderPass u
+ NanoUI.Internal.Shader: data ShaderProgram
+ NanoUI.Internal.Shader: defaultShaderConfig :: ShaderConfig
+ NanoUI.Internal.Shader: emptyShaderProgram :: ShaderProgram
+ NanoUI.Internal.Shader: fixUniform :: forall u (k :: ShaderKind). u -> Shader k u -> Shader k ()
+ NanoUI.Internal.Shader: hashShaderProgram :: ShaderProgram -> Word64
+ NanoUI.Internal.Shader: instance GHC.Internal.Classes.Eq NanoUI.Internal.Shader.CpuFragCtx
+ NanoUI.Internal.Shader: instance GHC.Internal.Classes.Eq NanoUI.Internal.Shader.ShaderCapabilities
+ NanoUI.Internal.Shader: instance GHC.Internal.Classes.Eq NanoUI.Internal.Shader.ShaderKind
+ NanoUI.Internal.Shader: instance GHC.Internal.Classes.Ord NanoUI.Internal.Shader.ShaderKind
+ NanoUI.Internal.Shader: instance GHC.Internal.Enum.Bounded NanoUI.Internal.Shader.ShaderKind
+ NanoUI.Internal.Shader: instance GHC.Internal.Enum.Enum NanoUI.Internal.Shader.ShaderKind
+ NanoUI.Internal.Shader: instance GHC.Internal.Show.Show NanoUI.Internal.Shader.CpuFragCtx
+ NanoUI.Internal.Shader: instance GHC.Internal.Show.Show NanoUI.Internal.Shader.ShaderCapabilities
+ NanoUI.Internal.Shader: instance GHC.Internal.Show.Show NanoUI.Internal.Shader.ShaderKind
+ NanoUI.Internal.Shader: instance NanoUI.Internal.Shader.IsNodeEffect 'NanoUI.Internal.Shader.ColorEffect
+ NanoUI.Internal.Shader: instance NanoUI.Internal.Shader.IsNodeEffect 'NanoUI.Internal.Shader.DistortionEffect
+ NanoUI.Internal.Shader: instance NanoUI.Internal.Shader.IsNodeEffect 'NanoUI.Internal.Shader.LayerEffect
+ NanoUI.Internal.Shader: noShaderCapabilities :: ShaderCapabilities
+ NanoUI.Internal.Shader: nodeEffectKind :: IsNodeEffect k => Proxy k -> ShaderKind
+ NanoUI.Internal.Shader: packShaderPass :: ShaderPass u -> u -> IO PackedShaderPass
+ NanoUI.Internal.Shader: rawLayerShader :: Uniforms u => (u -> V2) -> ShaderProgram -> Shader 'LayerEffect u
+ NanoUI.Internal.Shader: rawShader :: forall (k :: ShaderKind) u. Uniforms u => ShaderProgram -> Shader k u
+ NanoUI.Internal.Shader: type CpuShaderEval = CpuFragCtx -> V2 -> Color -> Color
+ NanoUI.Internal.Store: SlotAnchor :: Slot
+ NanoUI.Internal.Store: SlotColorBase :: Slot
+ NanoUI.Internal.Store: SlotCursor :: Slot
+ NanoUI.Internal.Store: SlotDrag :: Slot
+ NanoUI.Internal.Store: SlotDragW :: Slot
+ NanoUI.Internal.Store: SlotDrop :: Slot
+ NanoUI.Internal.Store: SlotDropPos :: Slot
+ NanoUI.Internal.Store: SlotMenuOpen :: Slot
+ NanoUI.Internal.Store: SlotMenuPos :: Slot
+ NanoUI.Internal.Store: SlotNumericHeld :: Slot
+ NanoUI.Internal.Store: SlotNumericRepeat :: Slot
+ NanoUI.Internal.Store: SlotScrollAxes :: Slot
+ NanoUI.Internal.Store: SlotScrollContent :: Slot
+ NanoUI.Internal.Store: SlotScrollCross :: Slot
+ NanoUI.Internal.Store: SlotScrollLinkX :: Slot
+ NanoUI.Internal.Store: SlotScrollLinkY :: Slot
+ NanoUI.Internal.Store: SlotScrollPending :: Slot
+ NanoUI.Internal.Store: SlotScrollRange :: Slot
+ NanoUI.Internal.Store: SlotScrollStep :: Slot
+ NanoUI.Internal.Store: SlotSearchAge :: Slot
+ NanoUI.Internal.Store: SlotSearchCommitted :: Slot
+ NanoUI.Internal.Store: SlotSeen :: Slot
+ NanoUI.Internal.Store: SlotSpec :: (Int -> Int) -> Field s -> (s -> a) -> (a -> s) -> SlotSpec a
+ NanoUI.Internal.Store: SlotTextAreaAnchorCol :: Slot
+ NanoUI.Internal.Store: SlotTextAreaAnchorRow :: Slot
+ NanoUI.Internal.Store: SlotTextAreaBuffer :: Slot
+ NanoUI.Internal.Store: SlotTextAreaChanged :: Slot
+ NanoUI.Internal.Store: SlotTextAreaLineH :: Slot
+ NanoUI.Internal.Store: SlotTextAreaReveal :: Slot
+ NanoUI.Internal.Store: SlotTextAreaScroll :: Slot
+ NanoUI.Internal.Store: SlotTextAreaText :: Slot
+ NanoUI.Internal.Store: SlotTextAreaViewport :: Slot
+ NanoUI.Internal.Store: SlotTextAreaWidths :: Slot
+ NanoUI.Internal.Store: SlotTextHistory :: Slot
+ NanoUI.Internal.Store: SlotTextInputScroll :: Slot
+ NanoUI.Internal.Store: SlotTextMode :: Slot
+ NanoUI.Internal.Store: SlotTooltipShow :: Slot
+ NanoUI.Internal.Store: SlotWinSize :: Slot
+ NanoUI.Internal.Store: SlotWrites :: (WidgetStore -> Bool) -> (WidgetStore -> WidgetStore) -> SlotWrites
+ NanoUI.Internal.Store: WidgetStore :: Int -> IntMap Int -> IntMap Float -> IntMap Double -> IntMap V2 -> IntMap Text -> IntMap IntSet -> IntMap TextBuffer -> IntMap TextDocument -> IntMap (Text, TextDocument) -> IntMap TextHistory -> IntMap EditorMode -> IntMap LineWidths -> IntMap GridState -> IntMap TableState -> IntMap ComboState -> IntMap RichSelection -> IntMap Int -> WidgetStore
+ NanoUI.Internal.Store: [storeBuffer] :: WidgetStore -> IntMap TextBuffer
+ NanoUI.Internal.Store: [storeCombo] :: WidgetStore -> IntMap ComboState
+ NanoUI.Internal.Store: [storeDocument] :: WidgetStore -> IntMap TextDocument
+ NanoUI.Internal.Store: [storeDouble] :: WidgetStore -> IntMap Double
+ NanoUI.Internal.Store: [storeEditorMode] :: WidgetStore -> IntMap EditorMode
+ NanoUI.Internal.Store: [storeFloat] :: WidgetStore -> IntMap Float
+ NanoUI.Internal.Store: [storeGrid] :: WidgetStore -> IntMap GridState
+ NanoUI.Internal.Store: [storeHistory] :: WidgetStore -> IntMap TextHistory
+ NanoUI.Internal.Store: [storeIntSet] :: WidgetStore -> IntMap IntSet
+ NanoUI.Internal.Store: [storeInt] :: WidgetStore -> IntMap Int
+ NanoUI.Internal.Store: [storeLineWidths] :: WidgetStore -> IntMap LineWidths
+ NanoUI.Internal.Store: [storeOpenSelect] :: WidgetStore -> Int
+ NanoUI.Internal.Store: [storePoint] :: WidgetStore -> IntMap V2
+ NanoUI.Internal.Store: [storeQuiet] :: WidgetStore -> IntMap Int
+ NanoUI.Internal.Store: [storeRichSelection] :: WidgetStore -> IntMap RichSelection
+ NanoUI.Internal.Store: [storeTableState] :: WidgetStore -> IntMap TableState
+ NanoUI.Internal.Store: [storeTextDocument] :: WidgetStore -> IntMap (Text, TextDocument)
+ NanoUI.Internal.Store: [storeText] :: WidgetStore -> IntMap Text
+ NanoUI.Internal.Store: anySelectOpen :: WidgetStore -> Bool
+ NanoUI.Internal.Store: boolInt :: Bool -> Int
+ NanoUI.Internal.Store: closeSelects :: WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: collapseFieldSelection :: Int -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: data Field a
+ NanoUI.Internal.Store: data Slot
+ NanoUI.Internal.Store: data SlotSpec a
+ NanoUI.Internal.Store: data SlotWrites
+ NanoUI.Internal.Store: data WidgetStore
+ NanoUI.Internal.Store: deleteSlot :: Field a -> Int -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: deleteSpec :: SlotSpec a -> Int -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: diffKeys :: Eq a => IntMap a -> IntMap a -> [Int]
+ NanoUI.Internal.Store: emptyWidgetStore :: WidgetStore
+ NanoUI.Internal.Store: encodedSpec :: (s -> a) -> (a -> s) -> SlotSpec s -> SlotSpec a
+ NanoUI.Internal.Store: eqByPtr :: Eq a => a -> a -> Bool
+ NanoUI.Internal.Store: fieldBuffer :: Field TextBuffer
+ NanoUI.Internal.Store: fieldCombo :: Field ComboState
+ NanoUI.Internal.Store: fieldDocument :: Field TextDocument
+ NanoUI.Internal.Store: fieldDouble :: Field Double
+ NanoUI.Internal.Store: fieldEditorMode :: Field EditorMode
+ NanoUI.Internal.Store: fieldFloat :: Field Float
+ NanoUI.Internal.Store: fieldGrid :: Field GridState
+ NanoUI.Internal.Store: fieldHistory :: Field TextHistory
+ NanoUI.Internal.Store: fieldInt :: Field Int
+ NanoUI.Internal.Store: fieldIntSet :: Field IntSet
+ NanoUI.Internal.Store: fieldLineWidths :: Field LineWidths
+ NanoUI.Internal.Store: fieldPoint :: Field V2
+ NanoUI.Internal.Store: fieldQuiet :: Field Int
+ NanoUI.Internal.Store: fieldRichSelection :: Field RichSelection
+ NanoUI.Internal.Store: fieldSelection :: WidgetStore -> Int -> Text -> (Int, Int)
+ NanoUI.Internal.Store: fieldSelectionWrite :: Int -> Text -> Int -> Int -> SlotWrites
+ NanoUI.Internal.Store: fieldTableState :: Field TableState
+ NanoUI.Internal.Store: fieldText :: Field Text
+ NanoUI.Internal.Store: fieldTextDocument :: Field (Text, TextDocument)
+ NanoUI.Internal.Store: findSlot :: Field a -> a -> Int -> WidgetStore -> a
+ NanoUI.Internal.Store: findSpec :: SlotSpec a -> a -> Int -> WidgetStore -> a
+ NanoUI.Internal.Store: flagSlot :: Int -> WidgetStore -> Bool
+ NanoUI.Internal.Store: floatBitsSpec :: SlotSpec Int -> SlotSpec Float
+ NanoUI.Internal.Store: insertSlot :: Field a -> Int -> a -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: insertSpec :: SlotSpec a -> Int -> a -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: instance GHC.Internal.Base.Monoid NanoUI.Internal.Store.SlotWrites
+ NanoUI.Internal.Store: instance GHC.Internal.Base.Semigroup NanoUI.Internal.Store.SlotWrites
+ NanoUI.Internal.Store: instance GHC.Internal.Enum.Enum NanoUI.Internal.Store.Slot
+ NanoUI.Internal.Store: intBool :: Int -> Bool
+ NanoUI.Internal.Store: isSelectOpen :: WidgetStore -> Int -> Bool
+ NanoUI.Internal.Store: lookupSlot :: Field a -> Int -> WidgetStore -> Maybe a
+ NanoUI.Internal.Store: lookupSpec :: SlotSpec a -> Int -> WidgetStore -> Maybe a
+ NanoUI.Internal.Store: memberSpec :: SlotSpec a -> Int -> WidgetStore -> Bool
+ NanoUI.Internal.Store: overField :: Field a -> (IntMap a -> IntMap a) -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: ownSlotSpec :: Field a -> SlotSpec a
+ NanoUI.Internal.Store: ptrEq :: a -> b -> Bool
+ NanoUI.Internal.Store: sameDouble :: Double -> Double -> Bool
+ NanoUI.Internal.Store: sameFloat :: Float -> Float -> Bool
+ NanoUI.Internal.Store: setFieldSelection :: Int -> Int -> Int -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Store: setSelectOpen :: WidgetStore -> Int -> Bool -> WidgetStore
+ NanoUI.Internal.Store: slotChangedKeys :: WidgetStore -> WidgetStore -> [Int]
+ NanoUI.Internal.Store: slotKey :: Slot -> Int -> Int
+ NanoUI.Internal.Store: slotSpec :: Slot -> Field a -> SlotSpec a
+ NanoUI.Internal.Store: slotWrite :: Eq a => Field a -> Int -> a -> SlotWrites
+ NanoUI.Internal.Store: slotWriteOr :: Eq a => Field a -> a -> Int -> a -> SlotWrites
+ NanoUI.Internal.Store: specKey :: SlotSpec a -> Int -> Int
+ NanoUI.Internal.Store: specWrite :: Eq a => SlotSpec a -> Int -> a -> SlotWrites
+ NanoUI.Internal.Store: specWriteOr :: Eq a => SlotSpec a -> a -> Int -> a -> SlotWrites
+ NanoUI.Internal.Store.Types: AreaHistory :: EditHistory -> TextHistory
+ NanoUI.Internal.Store.Types: ComboState :: Int -> Int -> Float -> Float -> Int -> Float -> Float -> Text -> Text -> Bool -> Maybe V2 -> ComboState
+ NanoUI.Internal.Store.Types: Drag :: Word64 -> V2 -> Bool -> Text -> Gesture
+ NanoUI.Internal.Store.Types: FieldHistory :: Text -> EditHistory -> TextHistory
+ NanoUI.Internal.Store.Types: GridState :: Maybe GridNode -> Word64 -> Word64 -> Word64 -> Maybe (Float, Float) -> Gesture -> GridState
+ NanoUI.Internal.Store.Types: LineWidths :: Int -> Int -> Seq Float -> Int -> Float -> Float -> LineWidths
+ NanoUI.Internal.Store.Types: NoGesture :: Gesture
+ NanoUI.Internal.Store.Types: Resize :: Word64 -> Float -> Float -> Gesture
+ NanoUI.Internal.Store.Types: TableState :: [Int] -> [Float] -> IntSet -> Int -> Float -> Float -> TableState
+ NanoUI.Internal.Store.Types: [csCommitted] :: ComboState -> Text
+ NanoUI.Internal.Store.Types: [csContentW] :: ComboState -> Float
+ NanoUI.Internal.Store.Types: [csDragOff] :: ComboState -> Float
+ NanoUI.Internal.Store.Types: [csDrag] :: ComboState -> Int
+ NanoUI.Internal.Store.Types: [csFocused] :: ComboState -> Bool
+ NanoUI.Internal.Store.Types: [csHighlight] :: ComboState -> Int
+ NanoUI.Internal.Store.Types: [csLive] :: ComboState -> Text
+ NanoUI.Internal.Store.Types: [csNavPointer] :: ComboState -> Maybe V2
+ NanoUI.Internal.Store.Types: [csScrollX] :: ComboState -> Float
+ NanoUI.Internal.Store.Types: [csWheelRem] :: ComboState -> Float
+ NanoUI.Internal.Store.Types: [csWindow] :: ComboState -> Int
+ NanoUI.Internal.Store.Types: [gsFocus] :: GridState -> Word64
+ NanoUI.Internal.Store.Types: [gsGesture] :: GridState -> Gesture
+ NanoUI.Internal.Store.Types: [gsMax] :: GridState -> Word64
+ NanoUI.Internal.Store.Types: [gsSeed] :: GridState -> Word64
+ NanoUI.Internal.Store.Types: [gsSpan] :: GridState -> Maybe (Float, Float)
+ NanoUI.Internal.Store.Types: [gsTree] :: GridState -> Maybe GridNode
+ NanoUI.Internal.Store.Types: [tsHidden] :: TableState -> IntSet
+ NanoUI.Internal.Store.Types: [tsOrder] :: TableState -> [Int]
+ NanoUI.Internal.Store.Types: [tsResizeCol] :: TableState -> Int
+ NanoUI.Internal.Store.Types: [tsResizeW] :: TableState -> Float
+ NanoUI.Internal.Store.Types: [tsResizeX] :: TableState -> Float
+ NanoUI.Internal.Store.Types: [tsWidths] :: TableState -> [Float]
+ NanoUI.Internal.Store.Types: data ComboState
+ NanoUI.Internal.Store.Types: data Gesture
+ NanoUI.Internal.Store.Types: data GridState
+ NanoUI.Internal.Store.Types: data LineWidths
+ NanoUI.Internal.Store.Types: data TableState
+ NanoUI.Internal.Store.Types: data TextHistory
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Store.Types.ComboState
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Store.Types.Gesture
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Store.Types.GridState
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Classes.Eq NanoUI.Internal.Store.Types.TableState
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Store.Types.ComboState
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Store.Types.Gesture
+ NanoUI.Internal.Store.Types: instance GHC.Internal.Show.Show NanoUI.Internal.Store.Types.GridState
+ NanoUI.Internal.Store.Types: sameComboVisual :: ComboState -> ComboState -> Bool
+ NanoUI.Internal.Uniforms: ($dmpokeUniformAt) :: (Uniforms u, Generic u, GUniforms (Rep u)) => u -> MutableByteArray RealWorld -> Int -> Int -> IO Int
+ NanoUI.Internal.Uniforms: ($dmuniformFieldsAt) :: (Uniforms u, GUniforms (Rep u)) => Proxy u -> Text -> Int -> (Int, [UniformField])
+ NanoUI.Internal.Uniforms: GBool :: GpuType
+ NanoUI.Internal.Uniforms: GFloat :: GpuType
+ NanoUI.Internal.Uniforms: GInt32 :: GpuType
+ NanoUI.Internal.Uniforms: GUInt32 :: GpuType
+ NanoUI.Internal.Uniforms: GVec2 :: GpuType
+ NanoUI.Internal.Uniforms: GVec3 :: GpuType
+ NanoUI.Internal.Uniforms: GVec4 :: GpuType
+ NanoUI.Internal.Uniforms: UniformField :: Text -> GpuType -> Int -> UniformField
+ NanoUI.Internal.Uniforms: V3 :: Float -> Float -> Float -> V3
+ NanoUI.Internal.Uniforms: V4 :: Float -> Float -> Float -> Float -> V4
+ NanoUI.Internal.Uniforms: [ufName] :: UniformField -> Text
+ NanoUI.Internal.Uniforms: [ufOffset] :: UniformField -> Int
+ NanoUI.Internal.Uniforms: [ufType] :: UniformField -> GpuType
+ NanoUI.Internal.Uniforms: [v3X] :: V3 -> Float
+ NanoUI.Internal.Uniforms: [v3Y] :: V3 -> Float
+ NanoUI.Internal.Uniforms: [v3Z] :: V3 -> Float
+ NanoUI.Internal.Uniforms: [v4W] :: V4 -> Float
+ NanoUI.Internal.Uniforms: [v4X] :: V4 -> Float
+ NanoUI.Internal.Uniforms: [v4Y] :: V4 -> Float
+ NanoUI.Internal.Uniforms: [v4Z] :: V4 -> Float
+ NanoUI.Internal.Uniforms: alignUp :: Int -> Int -> Int
+ NanoUI.Internal.Uniforms: class GUniforms (f :: Type -> Type)
+ NanoUI.Internal.Uniforms: class Eq u => Uniforms u
+ NanoUI.Internal.Uniforms: data GpuType
+ NanoUI.Internal.Uniforms: data UniformField
+ NanoUI.Internal.Uniforms: data V3
+ NanoUI.Internal.Uniforms: data V4
+ NanoUI.Internal.Uniforms: gPokeUniformAt :: GUniforms f => f p -> MutableByteArray RealWorld -> Int -> Int -> IO Int
+ NanoUI.Internal.Uniforms: gUniformFieldsAt :: GUniforms f => Proxy f -> Text -> Int -> (Int, [UniformField])
+ NanoUI.Internal.Uniforms: gpuTypeSize :: GpuType -> Int
+ NanoUI.Internal.Uniforms: hashUniformBytes :: ByteArray -> Word64
+ NanoUI.Internal.Uniforms: instance (GHC.Internal.Generics.Selector s, NanoUI.Internal.Uniforms.GUniforms f) => NanoUI.Internal.Uniforms.GUniforms (GHC.Internal.Generics.S1 s f)
+ NanoUI.Internal.Uniforms: instance (NanoUI.Internal.Uniforms.GUniforms f, NanoUI.Internal.Uniforms.GUniforms g) => NanoUI.Internal.Uniforms.GUniforms (f GHC.Internal.Generics.:*: g)
+ NanoUI.Internal.Uniforms: instance (NanoUI.Internal.Uniforms.Uniforms a, NanoUI.Internal.Uniforms.Uniforms b) => NanoUI.Internal.Uniforms.Uniforms (a, b)
+ NanoUI.Internal.Uniforms: instance (NanoUI.Internal.Uniforms.Uniforms a, NanoUI.Internal.Uniforms.Uniforms b, NanoUI.Internal.Uniforms.Uniforms c) => NanoUI.Internal.Uniforms.Uniforms (a, b, c)
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Classes.Eq NanoUI.Internal.Uniforms.GpuType
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Classes.Eq NanoUI.Internal.Uniforms.UniformField
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Classes.Eq NanoUI.Internal.Uniforms.V3
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Classes.Eq NanoUI.Internal.Uniforms.V4
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Classes.Ord NanoUI.Internal.Uniforms.GpuType
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Enum.Bounded NanoUI.Internal.Uniforms.GpuType
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Enum.Enum NanoUI.Internal.Uniforms.GpuType
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Generics.Generic NanoUI.Internal.Uniforms.V3
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Generics.Generic NanoUI.Internal.Uniforms.V4
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Show.Show NanoUI.Internal.Uniforms.GpuType
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Show.Show NanoUI.Internal.Uniforms.UniformField
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Show.Show NanoUI.Internal.Uniforms.V3
+ NanoUI.Internal.Uniforms: instance GHC.Internal.Show.Show NanoUI.Internal.Uniforms.V4
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.GUniforms GHC.Internal.Generics.U1
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.GUniforms f => NanoUI.Internal.Uniforms.GUniforms (GHC.Internal.Generics.C1 c f)
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.GUniforms f => NanoUI.Internal.Uniforms.GUniforms (GHC.Internal.Generics.D1 d f)
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms ()
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms GHC.Internal.Int.Int32
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms GHC.Internal.Types.Bool
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms GHC.Internal.Types.Float
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms GHC.Internal.Word.Word32
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms NanoUI.Internal.Types.Color
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms NanoUI.Internal.Types.Rect
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms NanoUI.Internal.Types.Size
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms NanoUI.Internal.Types.V2
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms NanoUI.Internal.Uniforms.V3
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms NanoUI.Internal.Uniforms.V4
+ NanoUI.Internal.Uniforms: instance NanoUI.Internal.Uniforms.Uniforms a => NanoUI.Internal.Uniforms.GUniforms (GHC.Internal.Generics.K1 i a)
+ NanoUI.Internal.Uniforms: packUniformBytes :: Uniforms u => u -> IO ByteArray
+ NanoUI.Internal.Uniforms: packZeroedBytes :: Int -> (MutableByteArray RealWorld -> IO a) -> IO ByteArray
+ NanoUI.Internal.Uniforms: pokeSysUniforms :: Rect -> Rect -> Float -> Float -> Float -> Float -> MutableByteArray RealWorld -> Int -> IO ()
+ NanoUI.Internal.Uniforms: pokeUniformAt :: Uniforms u => u -> MutableByteArray RealWorld -> Int -> Int -> IO Int
+ NanoUI.Internal.Uniforms: sysUniformBytes :: Int
+ NanoUI.Internal.Uniforms: uniformFieldsAt :: Uniforms u => Proxy u -> Text -> Int -> (Int, [UniformField])
+ NanoUI.Internal.Uniforms: uniformLayout :: Uniforms u => Proxy u -> [UniformField]
+ NanoUI.Internal.Uniforms: uniformSize :: Uniforms u => Proxy u -> Int
+ NanoUI.Internal.Var: Conservative :: Binding
+ NanoUI.Internal.Var: RenderFinal :: Binding
+ NanoUI.Internal.Var: beginVarPass :: Context -> Int -> IO ()
+ NanoUI.Internal.Var: bindVar :: Eq a => Binding -> Var a -> (a -> NanoUI (r, a)) -> NanoUI r
+ NanoUI.Internal.Var: bindVarBy :: (a -> a -> Bool) -> Binding -> Var a -> (a -> NanoUI (r, a)) -> NanoUI r
+ NanoUI.Internal.Var: bindVarOn :: Eq a => Binding -> (r -> a) -> Var a -> (a -> NanoUI r) -> NanoUI r
+ NanoUI.Internal.Var: data Binding
+ NanoUI.Internal.Var: endVarFrame :: Context -> IO ()
+ NanoUI.Internal.Var: instance GHC.Internal.Classes.Eq NanoUI.Internal.Var.Binding
+ NanoUI.Internal.Var: instance GHC.Internal.Show.Show NanoUI.Internal.Var.Binding
+ NanoUI.Internal.Var: lastFramePasses :: Context -> IO Int
+ NanoUI.Internal.Var: modifyVar :: Eq a => Var a -> (a -> a) -> NanoUI ()
+ NanoUI.Internal.Var: modifyVarIO :: Eq a => Var a -> (a -> a) -> IO ()
+ NanoUI.Internal.Var: newVar :: a -> IO (Var a)
+ NanoUI.Internal.Var: peekVar :: Var a -> NanoUI a
+ NanoUI.Internal.Var: readCell :: Sig -> Cell s -> Lens s a -> NanoUI a
+ NanoUI.Internal.Var: readVar :: Var a -> NanoUI a
+ NanoUI.Internal.Var: readVarIO :: Var a -> IO a
+ NanoUI.Internal.Var: requestRerun :: Context -> IO ()
+ NanoUI.Internal.Var: takeVarRerun :: Context -> IO Bool
+ NanoUI.Internal.Var: useEnumVar :: (Bounded a, Enum a, Typeable a) => a -> NanoUI (Var a)
+ NanoUI.Internal.Var: useVar :: VarSlot a => a -> NanoUI (Var a)
+ NanoUI.Internal.Var: withValue :: a -> (Var a -> NanoUI r) -> NanoUI (r, a)
+ NanoUI.Internal.Var: writeVar :: Eq a => Var a -> a -> NanoUI ()
+ NanoUI.Internal.Var: writeVarIO :: Eq a => Var a -> a -> IO ()
+ NanoUI.Internal.Var.Cell: Cell :: IORef s -> MutablePrimArray RealWorld Word64 -> Cell s
+ NanoUI.Internal.Var.Cell: Sig :: Word64 -> Word64 -> Bool -> Sig
+ NanoUI.Internal.Var.Cell: addToSet :: Cell s -> Int -> Word64 -> Sig -> IO ()
+ NanoUI.Internal.Var.Cell: allBits :: Word64
+ NanoUI.Internal.Var.Cell: countChange :: IO ()
+ NanoUI.Internal.Var.Cell: data Cell s
+ NanoUI.Internal.Var.Cell: data Sig
+ NanoUI.Internal.Var.Cell: flagSlot :: Int
+ NanoUI.Internal.Var.Cell: frameSlots :: Int
+ NanoUI.Internal.Var.Cell: instance GHC.Internal.Classes.Eq NanoUI.Internal.Var.Cell.Sig
+ NanoUI.Internal.Var.Cell: isInert :: Cell s -> Bool
+ NanoUI.Internal.Var.Cell: lastPassesSlot :: Int
+ NanoUI.Internal.Var.Cell: newCell :: s -> IO (Cell s)
+ NanoUI.Internal.Var.Cell: newInertCell :: s -> IO (Cell s)
+ NanoUI.Internal.Var.Cell: newStamps :: Int -> IO (MutablePrimArray RealWorld Word64)
+ NanoUI.Internal.Var.Cell: nextTick :: IO Word64
+ NanoUI.Internal.Var.Cell: obsSet :: Int
+ NanoUI.Internal.Var.Cell: orWord :: MutablePrimArray RealWorld Word64 -> Int -> Word64 -> IO ()
+ NanoUI.Internal.Var.Cell: passNoSlot :: Int
+ NanoUI.Internal.Var.Cell: passSlot :: Int
+ NanoUI.Internal.Var.Cell: seenSet :: Int
+ NanoUI.Internal.Var.Cell: seenWhole :: Cell s -> Word64 -> Sig -> IO Bool
+ NanoUI.Internal.Var.Cell: setHits :: Cell s -> Int -> Word64 -> Sig -> IO Bool
+ NanoUI.Internal.Var.Cell: varChangeCount :: IO Word64
+ NanoUI.Internal.Var.Generic: SL :: Side
+ NanoUI.Internal.Var.Generic: SR :: Side
+ NanoUI.Internal.Var.Generic: class GFocus (p :: [Side]) (f :: Type -> Type) a | p f -> a
+ NanoUI.Internal.Var.Generic: class PathIx (p :: [Side])
+ NanoUI.Internal.Var.Generic: data Side
+ NanoUI.Internal.Var.Generic: gget :: GFocus p f a => f x -> a
+ NanoUI.Internal.Var.Generic: gset :: GFocus p f a => a -> f x -> f x
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.GFocus '[] (GHC.Internal.Generics.M1 GHC.Internal.Generics.S m (GHC.Internal.Generics.K1 i a)) a
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.GFocus p f a => NanoUI.Internal.Var.Generic.GFocus p (GHC.Internal.Generics.M1 GHC.Internal.Generics.D m (GHC.Internal.Generics.M1 GHC.Internal.Generics.C c f)) a
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.GFocus p l a => NanoUI.Internal.Var.Generic.GFocus ('NanoUI.Internal.Var.Generic.SL : p) (l GHC.Internal.Generics.:*: r) a
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.GFocus p r a => NanoUI.Internal.Var.Generic.GFocus ('NanoUI.Internal.Var.Generic.SR : p) (l GHC.Internal.Generics.:*: r) a
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.PathIx '[]
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.PathIx p => NanoUI.Internal.Var.Generic.PathIx ('NanoUI.Internal.Var.Generic.SL : p)
+ NanoUI.Internal.Var.Generic: instance NanoUI.Internal.Var.Generic.PathIx p => NanoUI.Internal.Var.Generic.PathIx ('NanoUI.Internal.Var.Generic.SR : p)
+ NanoUI.Internal.Var.Generic: pathIx :: PathIx p => Int -> Int
+ NanoUI.Internal.Var.Generic: type family FieldPath (x :: Symbol) (s :: t) (rep :: Type -> Type) :: [Side]
+ NanoUI.Internal.Var.Types: SBool :: Var Bool -> SlotVar
+ NanoUI.Internal.Var.Types: SDouble :: Var Double -> SlotVar
+ NanoUI.Internal.Var.Types: SEnum :: TypeRep -> Var Int -> SlotVar
+ NanoUI.Internal.Var.Types: SFloat :: Var Float -> SlotVar
+ NanoUI.Internal.Var.Types: SInt :: Var Int -> SlotVar
+ NanoUI.Internal.Var.Types: SSort :: Var SortCol -> SlotVar
+ NanoUI.Internal.Var.Types: SText :: Var Text -> SlotVar
+ NanoUI.Internal.Var.Types: [ElemCtx] :: forall k s a. Hashable k => Lens s [a] -> (a -> k) -> [a] -> IORef (Maybe ([a], HashMap k a)) -> ElemCtx s k a
+ NanoUI.Internal.Var.Types: [Elem] :: forall s k a. Word64 -> ElemCtx s k a -> k -> a -> Lens s a
+ NanoUI.Internal.Var.Types: [Field] :: forall s b a. Word64 -> Lens s b -> (b -> a) -> (a -> b -> b) -> Lens s a
+ NanoUI.Internal.Var.Types: [Here] :: forall s. Lens s s
+ NanoUI.Internal.Var.Types: [VarConst] :: forall a. a -> Var a
+ NanoUI.Internal.Var.Types: [VarRef] :: forall s a. Cell s -> Lens s a -> Var a
+ NanoUI.Internal.Var.Types: class VarSlot a
+ NanoUI.Internal.Var.Types: constVar :: a -> Var a
+ NanoUI.Internal.Var.Types: data ElemCtx s k a
+ NanoUI.Internal.Var.Types: data Lens s a
+ NanoUI.Internal.Var.Types: data SlotVar
+ NanoUI.Internal.Var.Types: data Var a
+ NanoUI.Internal.Var.Types: fieldLens :: forall (x :: Symbol) s a. (Generic s, GFocus (FieldPath x s (Rep s)) (Rep s) a) => (s -> a, a -> s -> s)
+ NanoUI.Internal.Var.Types: instance (GHC.Internal.Generics.Generic s, NanoUI.Internal.Var.Generic.GFocus (NanoUI.Internal.Var.Generic.FieldPath x s (GHC.Internal.Generics.Rep s)) (GHC.Internal.Generics.Rep s) a, NanoUI.Internal.Var.Generic.PathIx (NanoUI.Internal.Var.Generic.FieldPath x s (GHC.Internal.Generics.Rep s))) => GHC.Internal.Records.HasField x (NanoUI.Internal.Var.Types.Var s) (NanoUI.Internal.Var.Types.Var a)
+ NanoUI.Internal.Var.Types: instance NanoUI.Internal.Var.Types.VarSlot Data.Text.Internal.Text
+ NanoUI.Internal.Var.Types: instance NanoUI.Internal.Var.Types.VarSlot GHC.Internal.Types.Bool
+ NanoUI.Internal.Var.Types: instance NanoUI.Internal.Var.Types.VarSlot GHC.Internal.Types.Double
+ NanoUI.Internal.Var.Types: instance NanoUI.Internal.Var.Types.VarSlot GHC.Internal.Types.Float
+ NanoUI.Internal.Var.Types: instance NanoUI.Internal.Var.Types.VarSlot GHC.Internal.Types.Int
+ NanoUI.Internal.Var.Types: instance NanoUI.Internal.Var.Types.VarSlot NanoUI.Internal.Derived.SortCol
+ NanoUI.Internal.Var.Types: lensSig :: Lens s a -> Sig
+ NanoUI.Internal.Var.Types: newElemCtx :: Hashable k => Lens s [a] -> (a -> k) -> [a] -> IO (ElemCtx s k a)
+ NanoUI.Internal.Var.Types: overLensSig :: Lens s a -> (a -> a) -> s -> (s, Sig)
+ NanoUI.Internal.Var.Types: peekLens :: Lens s a -> s -> IO a
+ NanoUI.Internal.Var.Types: previewLens :: Lens s a -> s -> Maybe a
+ NanoUI.Internal.Var.Types: slotMatch :: VarSlot a => SlotVar -> Maybe (Var a)
+ NanoUI.Internal.Var.Types: slotWrap :: VarSlot a => Var a -> SlotVar
+ NanoUI.Internal.Var.Types: stepBit :: Int -> Word64
+ NanoUI.Internal.Var.Types: structSig :: Lens s [a] -> Sig
+ NanoUI.Internal.Var.Types: viewLens :: Lens s a -> s -> a
+ NanoUI.Internal.Var.Types: zoomVar :: (s -> a) -> (a -> s -> s) -> Var s -> Var a
+ NanoUI.Internal.Var.Types: zoomVarL :: (forall (f :: Type -> Type). Functor f => (a -> f a) -> s -> f s) -> Var s -> Var a
+ NanoUI.Internal.Widgets.Custom: customDrawContext :: Context -> FontMetrics -> WidgetId -> Bool -> Bool -> IO CustomDrawContext
+ NanoUI.Internal.Widgets.Custom: mkCustomDrawContext :: Context -> FontMetrics -> WidgetId -> IO CustomDrawContext
+ NanoUI.Internal.Widgets.SplitPane: AxisH :: GridAxis
+ NanoUI.Internal.Widgets.SplitPane: AxisV :: GridAxis
+ NanoUI.Internal.Widgets.SplitPane: CenterSwap :: CenterDropMode
+ NanoUI.Internal.Widgets.SplitPane: CenterTab :: CenterDropMode
+ NanoUI.Internal.Widgets.SplitPane: DividerInfo :: Word64 -> GridAxis -> Rect -> Rect -> Float -> (Float, Float) -> DividerInfo
+ NanoUI.Internal.Widgets.SplitPane: DropPreview :: GridNode -> Map Word64 Rect -> [DividerInfo] -> Rect -> DropPreview
+ NanoUI.Internal.Widgets.SplitPane: DropSplit :: Word64 -> GridAxis -> Bool -> PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: DropSwap :: Word64 -> PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: DropTab :: Word64 -> Maybe Int -> PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: DropTop :: GridAxis -> Bool -> PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: MinBranch :: Float -> Float -> MinTree -> MinTree -> MinTree
+ NanoUI.Internal.Widgets.SplitPane: MinLeaf :: Float -> Float -> MinTree
+ NanoUI.Internal.Widgets.SplitPane: Pane :: Word64 -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: PaneTabs :: Word64 -> [Word64] -> Word64 -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: Split :: Word64 -> GridAxis -> Float -> GridNode -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: [diAxis] :: DividerInfo -> GridAxis
+ NanoUI.Internal.Widgets.SplitPane: [diBand] :: DividerInfo -> Rect
+ NanoUI.Internal.Widgets.SplitPane: [diMins] :: DividerInfo -> (Float, Float)
+ NanoUI.Internal.Widgets.SplitPane: [diRatio] :: DividerInfo -> Float
+ NanoUI.Internal.Widgets.SplitPane: [diRegion] :: DividerInfo -> Rect
+ NanoUI.Internal.Widgets.SplitPane: [diSplitId] :: DividerInfo -> Word64
+ NanoUI.Internal.Widgets.SplitPane: [dpDividers] :: DropPreview -> [DividerInfo]
+ NanoUI.Internal.Widgets.SplitPane: [dpRect] :: DropPreview -> Rect
+ NanoUI.Internal.Widgets.SplitPane: [dpRegions] :: DropPreview -> Map Word64 Rect
+ NanoUI.Internal.Widgets.SplitPane: [dpTree] :: DropPreview -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: alongAxis :: GridAxis -> Rect -> Rect
+ NanoUI.Internal.Widgets.SplitPane: bestPane :: (Rect -> Maybe Float) -> Map Word64 Rect -> Maybe (Word64, Rect)
+ NanoUI.Internal.Widgets.SplitPane: buildMinTree :: Float -> Float -> GridNode -> MinTree
+ NanoUI.Internal.Widgets.SplitPane: clampRatio :: Float -> DividerInfo -> Float -> Float
+ NanoUI.Internal.Widgets.SplitPane: data CenterDropMode
+ NanoUI.Internal.Widgets.SplitPane: data DividerInfo
+ NanoUI.Internal.Widgets.SplitPane: data DropPreview
+ NanoUI.Internal.Widgets.SplitPane: data GridAxis
+ NanoUI.Internal.Widgets.SplitPane: data GridNode
+ NanoUI.Internal.Widgets.SplitPane: data MinTree
+ NanoUI.Internal.Widgets.SplitPane: data PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: dividerLength :: Float -> DividerInfo -> Float -> Float
+ NanoUI.Internal.Widgets.SplitPane: dropPreviewTreeSized :: Maybe Rect -> Float -> Float -> GridNode -> Word64 -> Word64 -> Rect -> PaneDrop -> Maybe DropPreview
+ NanoUI.Internal.Widgets.SplitPane: dropTargetForPane :: Rect -> V2 -> Word64 -> PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: dropTargetForPaneWith :: CenterDropMode -> Rect -> V2 -> Word64 -> PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Internal.Widgets.SplitPane.DividerInfo
+ NanoUI.Internal.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Internal.Widgets.SplitPane.DropPreview
+ NanoUI.Internal.Widgets.SplitPane: instance GHC.Internal.Classes.Eq NanoUI.Internal.Widgets.SplitPane.PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Internal.Widgets.SplitPane.DividerInfo
+ NanoUI.Internal.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Internal.Widgets.SplitPane.DropPreview
+ NanoUI.Internal.Widgets.SplitPane: instance GHC.Internal.Show.Show NanoUI.Internal.Widgets.SplitPane.PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: layoutNode :: Float -> Float -> GridNode -> Rect -> (Map Word64 Rect, [DividerInfo])
+ NanoUI.Internal.Widgets.SplitPane: mainLen :: GridAxis -> Rect -> Float
+ NanoUI.Internal.Widgets.SplitPane: minTreeDims :: MinTree -> (Float, Float)
+ NanoUI.Internal.Widgets.SplitPane: nearestPane :: Map Word64 Rect -> V2 -> Maybe (Word64, Rect)
+ NanoUI.Internal.Widgets.SplitPane: paneExist :: GridNode -> Word64 -> Bool
+ NanoUI.Internal.Widgets.SplitPane: pinnedSide :: (Word64 -> Bool) -> GridNode -> Bool
+ NanoUI.Internal.Widgets.SplitPane: rectDistSq :: Rect -> V2 -> Float
+ NanoUI.Internal.Widgets.SplitPane: reflowFixed :: (Word64 -> Bool) -> Float -> Float -> Rect -> Rect -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: splitBeside :: Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: splitMinChildren :: Float -> Float -> GridNode -> GridNode -> MinTree -> (MinTree, MinTree)
+ NanoUI.Internal.Widgets.SplitPane: topLevelDropTarget :: Float -> Rect -> V2 -> Maybe PaneDrop
+ NanoUI.Internal.Widgets.SplitPane: treeAddTab :: Word64 -> Word64 -> Maybe Int -> Word64 -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: treeMaxId :: GridNode -> Word64
+ NanoUI.Internal.Widgets.SplitPane: treePanes :: GridNode -> [Word64]
+ NanoUI.Internal.Widgets.SplitPane: treeRemovePane :: Word64 -> GridNode -> Maybe GridNode
+ NanoUI.Internal.Widgets.SplitPane: treeSelectTab :: Word64 -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: treeSetRatio :: Word64 -> Float -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.SplitPane: treeSize :: GridNode -> Int
+ NanoUI.Internal.Widgets.SplitPane: treeSplit :: Word64 -> Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode
+ NanoUI.Internal.Widgets.TextArea: TextAreaState :: TextBuffer -> Cursor -> (Double, Double) -> (Double, Double) -> Double -> EditHistory -> TextAreaState
+ NanoUI.Internal.Widgets.TextArea: [tasBuffer] :: TextAreaState -> TextBuffer
+ NanoUI.Internal.Widgets.TextArea: [tasHistory] :: TextAreaState -> EditHistory
+ NanoUI.Internal.Widgets.TextArea: [tasLineHeight] :: TextAreaState -> Double
+ NanoUI.Internal.Widgets.TextArea: [tasScrollOffset] :: TextAreaState -> (Double, Double)
+ NanoUI.Internal.Widgets.TextArea: [tasSelectionAnchor] :: TextAreaState -> Cursor
+ NanoUI.Internal.Widgets.TextArea: [tasViewportSize] :: TextAreaState -> (Double, Double)
+ NanoUI.Internal.Widgets.TextArea: data TextAreaState
+ NanoUI.Internal.Widgets.TextArea: initTextAreaState :: Text -> TextAreaState
+ NanoUI.Internal.Widgets.TextArea: instance GHC.Internal.Show.Show NanoUI.Internal.Widgets.TextArea.TextAreaState
+ NanoUI.Internal.Widgets.TextArea: loadTextAreaState :: WidgetStore -> Int -> TextAreaState
+ NanoUI.Internal.Widgets.TextArea: runTextAreaCommand :: TextCommand -> TextAreaState -> TextAreaState
+ NanoUI.Internal.Widgets.TextArea: saveTextAreaState :: Int -> TextAreaState -> WidgetStore -> WidgetStore
+ NanoUI.Internal.Widgets.TextArea: setTextAreaSelection :: Cursor -> Cursor -> TextAreaState -> TextAreaState
+ NanoUI.Internal.Widgets.TextArea: setTextAreaViewport :: (Double, Double) -> Double -> TextAreaState -> TextAreaState
+ NanoUI.Internal.Widgets.TextArea: textArea :: Var Text -> NanoUI ()
+ NanoUI.Internal.Widgets.TextArea: textArea' :: Var Text -> NanoUI Response
+ NanoUI.Internal.Widgets.TextArea: textAreaBuffer :: WidgetStore -> Int -> TextBuffer
+ NanoUI.Internal.Widgets.TextArea: textAreaDocument :: Var TextDocument -> NanoUI ()
+ NanoUI.Internal.Widgets.TextArea: textAreaDocument' :: Var TextDocument -> NanoUI Response
+ NanoUI.Internal.Widgets.TextArea: textAreaDocumentWith :: (Layout -> Layout) -> Var TextDocument -> NanoUI ()
+ NanoUI.Internal.Widgets.TextArea: textAreaDocumentWith' :: (Layout -> Layout) -> Var TextDocument -> NanoUI Response
+ NanoUI.Internal.Widgets.TextArea: textAreaFieldEditor :: WidgetStore -> Int -> (Editor, Editor -> WidgetStore -> WidgetStore)
+ NanoUI.Internal.Widgets.TextArea: textAreaLayout :: Layout
+ NanoUI.Internal.Widgets.TextArea: textAreaWith :: (Layout -> Layout) -> Var Text -> NanoUI ()
+ NanoUI.Internal.Widgets.TextArea: textAreaWith' :: (Layout -> Layout) -> Var Text -> NanoUI Response
+ NanoUI.Internal.Widgets.TextDocument: bufferDocument :: TextBuffer -> TextDocument
+ NanoUI.Internal.Widgets.TextDocument: data TextDocument
+ NanoUI.Internal.Widgets.TextDocument: documentBuffer :: TextDocument -> TextBuffer
+ NanoUI.Internal.Widgets.TextDocument: documentLine :: Int -> TextDocument -> Text
+ NanoUI.Internal.Widgets.TextDocument: documentLineCount :: TextDocument -> Int
+ NanoUI.Internal.Widgets.TextDocument: documentLines :: TextDocument -> Seq Text
+ NanoUI.Internal.Widgets.TextDocument: documentRange :: Cursor -> Cursor -> TextDocument -> Text
+ NanoUI.Internal.Widgets.TextDocument: documentText :: TextDocument -> Text
+ NanoUI.Internal.Widgets.TextDocument: editDocument :: TextEdit -> TextDocument -> TextDocument
+ NanoUI.Internal.Widgets.TextDocument: emptyDocument :: TextDocument
+ NanoUI.Internal.Widgets.TextDocument: instance GHC.Internal.Classes.Eq NanoUI.Internal.Widgets.TextDocument.TextDocument
+ NanoUI.Internal.Widgets.TextDocument: instance GHC.Internal.Show.Show NanoUI.Internal.Widgets.TextDocument.TextDocument
+ NanoUI.Internal.Widgets.TextDocument: replaceDocumentRange :: Cursor -> Cursor -> Text -> TextDocument -> TextDocument
+ NanoUI.Internal.Widgets.TextDocument: sameDocument :: TextDocument -> TextDocument -> Bool
+ NanoUI.Internal.Widgets.TextDocument: sameLines :: Seq Text -> Seq Text -> Bool
+ NanoUI.Internal.Widgets.TextDocument: textDocument :: Text -> TextDocument
+ NanoUI.Monad: (<&&>) :: Monad m => m Bool -> m Bool -> m Bool
+ NanoUI.Monad: DamageCustom :: (Rect -> Rect) -> DamageBounds
+ NanoUI.Monad: DamageExact :: Rect -> DamageBounds
+ NanoUI.Monad: DamageInflated :: Float -> DamageBounds
+ NanoUI.Monad: DamageNone :: DamageBounds
+ NanoUI.Monad: DamageSelf :: DamageBounds
+ NanoUI.Monad: DamageUnion :: DamageBounds -> DamageBounds -> DamageBounds
+ NanoUI.Monad: askFrameInput :: NanoUI Input
+ NanoUI.Monad: catchView :: Exception e => NanoUI a -> (e -> NanoUI a) -> NanoUI a
+ NanoUI.Monad: clearFocus :: NanoUI ()
+ NanoUI.Monad: data Context
+ NanoUI.Monad: data DamageBounds
+ NanoUI.Monad: data Host a
+ NanoUI.Monad: data NanoUI a
+ NanoUI.Monad: focusNext :: NanoUI ()
+ NanoUI.Monad: focusPrevious :: NanoUI ()
+ NanoUI.Monad: focusedWidget :: NanoUI WidgetId
+ NanoUI.Monad: followSystemTheme :: (Maybe Appearance -> Theme) -> NanoUI ()
+ NanoUI.Monad: getClipboard :: NanoUI (Maybe Text)
+ NanoUI.Monad: getScrollMetrics :: WidgetId -> NanoUI (Maybe ScrollMetrics)
+ NanoUI.Monad: getScrollTuning :: NanoUI ScrollTuning
+ NanoUI.Monad: holdFocus :: WidgetId -> NanoUI ()
+ NanoUI.Monad: infixr 3 <&&>
+ NanoUI.Monad: isFocused :: WidgetId -> NanoUI Bool
+ NanoUI.Monad: lastRect :: WidgetId -> NanoUI (Maybe Rect)
+ NanoUI.Monad: liftIO :: MonadIO m => IO a -> m a
+ NanoUI.Monad: lineWidthUi :: FontMetrics -> Text -> NanoUI Float
+ NanoUI.Monad: localInput :: Input -> NanoUI a -> NanoUI a
+ NanoUI.Monad: mouseHeld :: MouseButton -> NanoUI Bool
+ NanoUI.Monad: mousePressed :: MouseButton -> NanoUI Bool
+ NanoUI.Monad: mouseReleased :: MouseButton -> NanoUI Bool
+ NanoUI.Monad: newHost :: IO (Host a)
+ NanoUI.Monad: releaseFocus :: WidgetId -> NanoUI ()
+ NanoUI.Monad: requestFocus :: WidgetId -> NanoUI ()
+ NanoUI.Monad: requestFrame :: NanoUI ()
+ NanoUI.Monad: resolveFontUi :: Float -> FontWeight -> FontStyle -> FontVariant -> NanoUI FontMetrics
+ NanoUI.Monad: scrollBy :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: scrollIntoView :: WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: scrollPages :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: scrollRectIntoView :: WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: scrollTo :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: scrollToEnd :: WidgetId -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: scrollToStart :: WidgetId -> ScrollBehavior -> NanoUI ()
+ NanoUI.Monad: setClipboard :: Text -> NanoUI Bool
+ NanoUI.Monad: setHost :: Host a -> a -> IO ()
+ NanoUI.Monad: setScrollOffset :: WidgetId -> V2 -> NanoUI ()
+ NanoUI.Monad: setScrollStep :: WidgetId -> Float -> NanoUI ()
+ NanoUI.Monad: setScrollTuning :: ScrollTuning -> NanoUI ()
+ NanoUI.Monad: setTheme :: Theme -> NanoUI ()
+ NanoUI.Monad: systemAppearance :: NanoUI (Maybe Appearance)
+ NanoUI.Monad: takeEscape :: NanoUI Bool
+ NanoUI.Monad: truncateTextUi :: FontMetrics -> Float -> Text -> NanoUI Text
+ NanoUI.Monad: truncateTextWithUi :: TextEllipsis -> FontMetrics -> Float -> Text -> NanoUI Text
+ NanoUI.Monad: uiFontSize :: NanoUI Float
+ NanoUI.Monad: withUiResource :: IO a -> (a -> IO ()) -> NanoUI b -> NanoUI b
+ NanoUI.Path: BevelJoin :: LineJoin
+ NanoUI.Path: ButtCap :: LineCap
+ NanoUI.Path: EvenOdd :: FillRule
+ NanoUI.Path: Linear :: V2 -> V2 -> [(Float, Color)] -> Paint
+ NanoUI.Path: MiterJoin :: LineJoin
+ NanoUI.Path: NonZero :: FillRule
+ NanoUI.Path: RoundCap :: LineCap
+ NanoUI.Path: RoundJoin :: LineJoin
+ NanoUI.Path: Solid :: Color -> Paint
+ NanoUI.Path: SquareCap :: LineCap
+ NanoUI.Path: affine :: Float -> Float -> Float -> Float -> Float -> Float -> Transform
+ NanoUI.Path: arc :: V2 -> Float -> Float -> Float -> Path
+ NanoUI.Path: arcTo :: V2 -> Float -> Bool -> Bool -> V2 -> Path
+ NanoUI.Path: circle :: V2 -> Float -> Path
+ NanoUI.Path: close :: Path
+ NanoUI.Path: cubicTo :: V2 -> V2 -> V2 -> Path
+ NanoUI.Path: data FillRule
+ NanoUI.Path: data LineCap
+ NanoUI.Path: data LineJoin
+ NanoUI.Path: data Paint
+ NanoUI.Path: data Path
+ NanoUI.Path: data Stroke
+ NanoUI.Path: data Transform
+ NanoUI.Path: ellipse :: V2 -> V2 -> Path
+ NanoUI.Path: ellipticalArc :: V2 -> V2 -> Float -> Float -> Float -> Path
+ NanoUI.Path: invert :: Transform -> Maybe Transform
+ NanoUI.Path: lineTo :: V2 -> Path
+ NanoUI.Path: moveTo :: V2 -> Path
+ NanoUI.Path: polygon :: [V2] -> Path
+ NanoUI.Path: polyline :: [V2] -> Path
+ NanoUI.Path: quadTo :: V2 -> V2 -> Path
+ NanoUI.Path: rect :: Rect -> Path
+ NanoUI.Path: rotate :: Float -> Transform
+ NanoUI.Path: rotateAround :: V2 -> Float -> Transform
+ NanoUI.Path: roundedRect :: Rect -> Float -> Path
+ NanoUI.Path: roundedRectCorners :: Rect -> Float -> Float -> Float -> Float -> Path
+ NanoUI.Path: scale :: Float -> Float -> Transform
+ NanoUI.Path: stroke :: Float -> Stroke
+ NanoUI.Path: transformPoint :: Transform -> V2 -> V2
+ NanoUI.Path: translate :: Float -> Float -> Transform
+ NanoUI.Runner: LoopWindows :: IO Int -> IO Bool -> IO () -> (Context -> IO ()) -> LoopWindows
+ NanoUI.Runner: [lwAfterPass] :: LoopWindows -> Context -> IO ()
+ NanoUI.Runner: [lwDrew] :: LoopWindows -> IO ()
+ NanoUI.Runner: [lwFirstDue] :: LoopWindows -> IO Bool
+ NanoUI.Runner: [lwWait] :: LoopWindows -> IO Int
+ NanoUI.Runner: [sdPacedWait] :: SessionDriver ev -> Maybe (Int -> IO [ev])
+ NanoUI.Runner: [sdVsyncOff] :: SessionDriver ev -> Bool
+ NanoUI.Runner: [sdWindows] :: SessionDriver ev -> Maybe LoopWindows
+ NanoUI.Runner: data LoopWindows
+ NanoUI.Runner: maxFrameDt :: Float
+ NanoUI.Runner: newClickTracker :: IO ClickTracker
+ NanoUI.Runner: newDebugSampler :: IO DebugSamplerRef
+ NanoUI.Runner: pacingMsFor :: Double -> Int
+ NanoUI.Runner: shorterWait :: Int -> Int -> Int
+ NanoUI.Runner: stampClicks :: ClickTracker -> Input -> IO Input
+ NanoUI.Runner: takeDueWake :: Context -> IO Bool
+ NanoUI.Runner: type ClickTracker = IORef (Double, V2, MouseButtons, Int)
+ NanoUI.Runner: type DebugSamplerRef = IORef DebugSampler
+ NanoUI.Runner: waitUntil :: Double -> IO ()
+ NanoUI.Runner: wakeTimeoutMs :: Double -> Double -> Int
+ NanoUI.Runner: windowTimeoutMs :: Bool -> Int -> Context -> IO Int
+ NanoUI.Runner.Windows: WindowOps :: (Context -> WindowSettings -> IO (w, Context)) -> (w -> IO ()) -> (Input -> ev -> Input) -> (ev -> Bool) -> (ev -> Bool) -> (w -> Context -> Input -> IO (Context, Input)) -> (w -> Context -> NanoUI () -> Input -> Bool -> IO Bool) -> (w -> Context -> Input -> IO ()) -> (w -> Int) -> (w -> IO () -> IO (IO ())) -> WindowOps w ev
+ NanoUI.Runner.Windows: [woApplyEvent] :: WindowOps w ev -> Input -> ev -> Input
+ NanoUI.Runner.Windows: [woClose] :: WindowOps w ev -> w -> IO ()
+ NanoUI.Runner.Windows: [woCursor] :: WindowOps w ev -> w -> Context -> Input -> IO ()
+ NanoUI.Runner.Windows: [woDraw] :: WindowOps w ev -> w -> Context -> NanoUI () -> Input -> Bool -> IO Bool
+ NanoUI.Runner.Windows: [woIsButtonEdge] :: WindowOps w ev -> ev -> Bool
+ NanoUI.Runner.Windows: [woIsClose] :: WindowOps w ev -> ev -> Bool
+ NanoUI.Runner.Windows: [woOpen] :: WindowOps w ev -> Context -> WindowSettings -> IO (w, Context)
+ NanoUI.Runner.Windows: [woPacingMs] :: WindowOps w ev -> w -> Int
+ NanoUI.Runner.Windows: [woSync] :: WindowOps w ev -> w -> Context -> Input -> IO (Context, Input)
+ NanoUI.Runner.Windows: [woWatchResize] :: WindowOps w ev -> w -> IO () -> IO (IO ())
+ NanoUI.Runner.Windows: afterMainPass :: Windows w ev -> Context -> IO ()
+ NanoUI.Runner.Windows: closeWindows :: Windows w ev -> IO ()
+ NanoUI.Runner.Windows: data WindowOps w ev
+ NanoUI.Runner.Windows: data Windows w ev
+ NanoUI.Runner.Windows: hasWindows :: Windows w ev -> IO Bool
+ NanoUI.Runner.Windows: loopWindows :: Windows w ev -> LoopWindows
+ NanoUI.Runner.Windows: newWindows :: WindowOps w ev -> IO (Windows w ev)
+ NanoUI.Runner.Windows: openWindows :: Windows w ev -> IO [(w, ev -> IO ())]
+ NanoUI.Shader.Raw: CpuFragCtx :: V2 -> V2 -> V2 -> Float -> Color -> Float -> CpuFragCtx
+ NanoUI.Shader.Raw: GBool :: GpuType
+ NanoUI.Shader.Raw: GFloat :: GpuType
+ NanoUI.Shader.Raw: GInt32 :: GpuType
+ NanoUI.Shader.Raw: GUInt32 :: GpuType
+ NanoUI.Shader.Raw: GVec2 :: GpuType
+ NanoUI.Shader.Raw: GVec3 :: GpuType
+ NanoUI.Shader.Raw: GVec4 :: GpuType
+ NanoUI.Shader.Raw: ShaderProgram :: Maybe Text -> Maybe Text -> Maybe ByteString -> Maybe Text -> Bool -> [UniformField] -> Int -> ShaderProgram
+ NanoUI.Shader.Raw: UniformField :: Text -> GpuType -> Int -> UniformField
+ NanoUI.Shader.Raw: [cfcColor] :: CpuFragCtx -> Color
+ NanoUI.Shader.Raw: [cfcCornerRadius] :: CpuFragCtx -> Float
+ NanoUI.Shader.Raw: [cfcPos] :: CpuFragCtx -> V2
+ NanoUI.Shader.Raw: [cfcScale] :: CpuFragCtx -> Float
+ NanoUI.Shader.Raw: [cfcSize] :: CpuFragCtx -> V2
+ NanoUI.Shader.Raw: [cfcUv] :: CpuFragCtx -> V2
+ NanoUI.Shader.Raw: [spGlsl150] :: ShaderProgram -> Maybe Text
+ NanoUI.Shader.Raw: [spGlslEs300] :: ShaderProgram -> Maybe Text
+ NanoUI.Shader.Raw: [spMsl] :: ShaderProgram -> Maybe Text
+ NanoUI.Shader.Raw: [spNeedsTex] :: ShaderProgram -> Bool
+ NanoUI.Shader.Raw: [spSpirv] :: ShaderProgram -> Maybe ByteString
+ NanoUI.Shader.Raw: [spUniformBytes] :: ShaderProgram -> Int
+ NanoUI.Shader.Raw: [spUniformLayout] :: ShaderProgram -> [UniformField]
+ NanoUI.Shader.Raw: [ufName] :: UniformField -> Text
+ NanoUI.Shader.Raw: [ufOffset] :: UniformField -> Int
+ NanoUI.Shader.Raw: [ufType] :: UniformField -> GpuType
+ NanoUI.Shader.Raw: data CpuFragCtx
+ NanoUI.Shader.Raw: data GpuType
+ NanoUI.Shader.Raw: data ShaderProgram
+ NanoUI.Shader.Raw: data UniformField
+ NanoUI.Shader.Raw: emptyShaderProgram :: ShaderProgram
+ NanoUI.Shader.Raw: rawLayerShader :: Uniforms u => (u -> V2) -> ShaderProgram -> Shader 'LayerEffect u
+ NanoUI.Shader.Raw: rawShader :: forall (k :: ShaderKind) u. Uniforms u => ShaderProgram -> Shader k u
+ NanoUI.Shader.Raw: type CpuShaderEval = CpuFragCtx -> V2 -> Color -> Color
+ NanoUI.Shader.Raw: uniformLayout :: Uniforms u => Proxy u -> [UniformField]
+ NanoUI.Shader.Raw: uniformSize :: Uniforms u => Proxy u -> Int
+ NanoUI.Shortcut: Shortcut :: Maybe Key -> Modifiers -> Shortcut
+ NanoUI.Shortcut: [shortcutKey] :: Shortcut -> Maybe Key
+ NanoUI.Shortcut: [shortcutModifiers] :: Shortcut -> Modifiers
+ NanoUI.Shortcut: alt :: Shortcut
+ NanoUI.Shortcut: class ToKey a
+ NanoUI.Shortcut: cmdOrCtrl :: Shortcut
+ NanoUI.Shortcut: ctrl :: Shortcut
+ NanoUI.Shortcut: data Shortcut
+ NanoUI.Shortcut: key :: ToKey k => k -> Shortcut
+ NanoUI.Shortcut: keyLabel :: Key -> Text
+ NanoUI.Shortcut: parseShortcut :: Text -> Either Text Shortcut
+ NanoUI.Shortcut: shift :: Shortcut
+ NanoUI.Shortcut: shortcutIn :: Shortcut -> Input -> Bool
+ NanoUI.Shortcut: shortcutLabel :: Shortcut -> Text
+ NanoUI.Shortcut: super :: Shortcut
+ NanoUI.Shortcut: toKey :: ToKey a => a -> Key
+ NanoUI.Svg: rasterizeSvgIn :: Int -> Int -> Rect -> Color -> Svg -> ByteString
+ NanoUI.Svg: svgDocument :: Svg -> Document
+ NanoUI.Testing: AtlasRegions :: [(Int, Int, Int, Int)] -> AtlasUpload
+ NanoUI.Testing: AtlasWhole :: AtlasUpload
+ NanoUI.Testing: DirColumn :: DirTag
+ NanoUI.Testing: DirRow :: DirTag
+ NanoUI.Testing: DrawImage :: Rect -> Float -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Testing: DrawTextAligned :: Float -> Float -> Float -> Float -> Float -> TextFont -> Text -> Color -> DrawOp
+ NanoUI.Testing: FillPolygon :: PrimArray Float -> PrimArray Int -> PrimArray Int -> Shade -> DrawOp
+ NanoUI.Testing: Flat :: Color -> Shade
+ NanoUI.Testing: NodeBox :: NodeType
+ NanoUI.Testing: NodeButton :: NodeType
+ NanoUI.Testing: NodeColorPicker :: NodeType
+ NanoUI.Testing: NodeContainer :: NodeType
+ NanoUI.Testing: NodeDrawing :: NodeType
+ NanoUI.Testing: NodeImage :: NodeType
+ NanoUI.Testing: NodeModal :: NodeType
+ NanoUI.Testing: NodePanel :: NodeType
+ NanoUI.Testing: NodePopup :: NodeType
+ NanoUI.Testing: NodeScrollContainer :: NodeType
+ NanoUI.Testing: NodeSelect :: NodeType
+ NanoUI.Testing: NodeSeparator :: NodeType
+ NanoUI.Testing: NodeShader :: NodeType
+ NanoUI.Testing: NodeSlider :: NodeType
+ NanoUI.Testing: NodeSpacer :: NodeType
+ NanoUI.Testing: NodeText :: NodeType
+ NanoUI.Testing: NodeTextArea :: NodeType
+ NanoUI.Testing: NodeTextInput :: NodeType
+ NanoUI.Testing: NodeWindow :: NodeType
+ NanoUI.Testing: PopClip :: DrawOp
+ NanoUI.Testing: PushClip :: Rect -> DrawOp
+ NanoUI.Testing: ScrollBarList :: ScrollBarSlot
+ NanoUI.Testing: ScrollBarPage :: ScrollBarSlot
+ NanoUI.Testing: ScrollBarWindow :: ScrollBarSlot
+ NanoUI.Testing: Shaded :: PrimArray Word32 -> Shade
+ NanoUI.Testing: StrokePolyline :: PrimArray Float -> Float -> Bool -> LineCap -> LineJoin -> Float -> Shade -> DrawOp
+ NanoUI.Testing: TextInputArea :: Rect -> Float -> InputPurpose -> TextInputArea
+ NanoUI.Testing: UiCursorAlias :: UiCursorKind
+ NanoUI.Testing: UiCursorAllScroll :: UiCursorKind
+ NanoUI.Testing: UiCursorCell :: UiCursorKind
+ NanoUI.Testing: UiCursorColResize :: UiCursorKind
+ NanoUI.Testing: UiCursorContextMenu :: UiCursorKind
+ NanoUI.Testing: UiCursorCopy :: UiCursorKind
+ NanoUI.Testing: UiCursorCrosshair :: UiCursorKind
+ NanoUI.Testing: UiCursorEResize :: UiCursorKind
+ NanoUI.Testing: UiCursorHelp :: UiCursorKind
+ NanoUI.Testing: UiCursorHidden :: UiCursorKind
+ NanoUI.Testing: UiCursorMove :: UiCursorKind
+ NanoUI.Testing: UiCursorNResize :: UiCursorKind
+ NanoUI.Testing: UiCursorNeResize :: UiCursorKind
+ NanoUI.Testing: UiCursorNotAllowed :: UiCursorKind
+ NanoUI.Testing: UiCursorNwResize :: UiCursorKind
+ NanoUI.Testing: UiCursorProgress :: UiCursorKind
+ NanoUI.Testing: UiCursorRowResize :: UiCursorKind
+ NanoUI.Testing: UiCursorSResize :: UiCursorKind
+ NanoUI.Testing: UiCursorSeResize :: UiCursorKind
+ NanoUI.Testing: UiCursorSwResize :: UiCursorKind
+ NanoUI.Testing: UiCursorWResize :: UiCursorKind
+ NanoUI.Testing: UiCursorWait :: UiCursorKind
+ NanoUI.Testing: UiCursorZoomIn :: UiCursorKind
+ NanoUI.Testing: UiCursorZoomOut :: UiCursorKind
+ NanoUI.Testing: WrapResult :: [Text] -> Float -> Float -> Float -> WrapResult
+ NanoUI.Testing: [cmdShader] :: DrawCmd -> Int32
+ NanoUI.Testing: [drawClear] :: DrawData -> Color
+ NanoUI.Testing: [drawEffectSpans] :: DrawData -> SmallArray EffectSpan
+ NanoUI.Testing: [drawLayerOffsets] :: DrawData -> PrimArray Int
+ NanoUI.Testing: [drawShaderCalls] :: DrawData -> SmallArray ShaderCall
+ NanoUI.Testing: [drawUniformBytes] :: DrawData -> ByteArray
+ NanoUI.Testing: [textInputAreaCursor] :: TextInputArea -> Float
+ NanoUI.Testing: [textInputAreaPurpose] :: TextInputArea -> InputPurpose
+ NanoUI.Testing: [textInputAreaRect] :: TextInputArea -> Rect
+ NanoUI.Testing: [wrBreakW] :: WrapResult -> Float
+ NanoUI.Testing: [wrFitW] :: WrapResult -> Float
+ NanoUI.Testing: [wrLines] :: WrapResult -> [Text]
+ NanoUI.Testing: [wrWidest] :: WrapResult -> Float
+ NanoUI.Testing: alignedTextPen :: AlignX -> Float -> Float -> Float -> FontMetrics -> Text -> (Float, Float)
+ NanoUI.Testing: atlasChanges :: Context -> Int -> IO (Maybe (Int, Int, ForeignPtr Word8, Int, AtlasUpload))
+ NanoUI.Testing: clipPixelEdges :: Float -> Rect -> (Int, Int, Int, Int)
+ NanoUI.Testing: damagePieces :: [Rect] -> [Rect]
+ NanoUI.Testing: data AtlasUpload
+ NanoUI.Testing: data DirTag
+ NanoUI.Testing: data Host a
+ NanoUI.Testing: data NodeType
+ NanoUI.Testing: data ScrollBarSlot
+ NanoUI.Testing: data Shade
+ NanoUI.Testing: data TextInputArea
+ NanoUI.Testing: data WidgetStore
+ NanoUI.Testing: data WrapResult
+ NanoUI.Testing: floatingWindowOpen :: Context -> IO Bool
+ NanoUI.Testing: followSystemThemeIO :: Context -> (Maybe Appearance -> Theme) -> IO ()
+ NanoUI.Testing: getScrollMetricsIO :: Context -> WidgetId -> IO (Maybe ScrollMetrics)
+ NanoUI.Testing: getScrollOffset2DIO :: Context -> WidgetId -> IO V2
+ NanoUI.Testing: getScrollOffsetIO :: Context -> WidgetId -> IO Float
+ NanoUI.Testing: getScrollStepIO :: Context -> WidgetId -> IO Float
+ NanoUI.Testing: getScrollTuningIO :: Context -> IO ScrollTuning
+ NanoUI.Testing: getThemeIO :: Context -> IO Theme
+ NanoUI.Testing: getWakeAt :: Context -> IO Double
+ NanoUI.Testing: glyphAtlasPages :: Int
+ NanoUI.Testing: glyphPageTextureId :: Int -> Int
+ NanoUI.Testing: lastFramePasses :: Context -> IO Int
+ NanoUI.Testing: liftIO :: MonadIO m => IO a -> m a
+ NanoUI.Testing: newHost :: IO (Host a)
+ NanoUI.Testing: pattern DrawImageRect :: Rect -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Testing: requestWakeAfter :: Context -> Double -> IO ()
+ NanoUI.Testing: requestWakeAt :: Context -> Double -> IO ()
+ NanoUI.Testing: scrollByIO :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Testing: scrollGlidingIO :: Context -> WidgetId -> IO Bool
+ NanoUI.Testing: scrollIntoViewIO :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()
+ NanoUI.Testing: scrollPagesIO :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Testing: scrollRectIntoViewIO :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()
+ NanoUI.Testing: scrollToEndIO :: Context -> WidgetId -> ScrollBehavior -> IO ()
+ NanoUI.Testing: scrollToIO :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI.Testing: scrollToStartIO :: Context -> WidgetId -> ScrollBehavior -> IO ()
+ NanoUI.Testing: setDrawReuse :: Context -> Bool -> IO ()
+ NanoUI.Testing: setScrollOffset2DIO :: Context -> WidgetId -> V2 -> IO ()
+ NanoUI.Testing: setScrollOffsetIO :: Context -> WidgetId -> Float -> IO ()
+ NanoUI.Testing: setScrollStepIO :: Context -> WidgetId -> Float -> IO ()
+ NanoUI.Testing: setScrollTuningIO :: Context -> ScrollTuning -> IO ()
+ NanoUI.Testing: setThemeIO :: Context -> Theme -> IO ()
+ NanoUI.Testing: takeDamagePieces :: Context -> IO [Rect]
+ NanoUI.Testing: textInkEnd :: FontMetrics -> Text -> Float
+ NanoUI.Testing: textInputArea :: Context -> IO (Maybe TextInputArea)
+ NanoUI.Testing: textNodeFontTone :: Word64 -> Maybe Tone
+ NanoUI.Testing: textNodeFontVariant :: Word64 -> FontVariant
+ NanoUI.Testing: textureGlyphPage :: Int -> Int
+ NanoUI.Testing: withFontSize :: Context -> Float -> Context
+ NanoUI.Testing: wrapTextIO :: (Text -> IO Float) -> Text -> Float -> IO WrapResult
+ NanoUI.Testing: wrapTextLinesIO :: (Text -> IO Float) -> Text -> Float -> IO [Text]
+ NanoUI.Testing.Assert: assertJust :: HasCallStack => IORef Int -> Maybe a -> (a -> IO ()) -> IO ()
+ NanoUI.Testing.Assert: assertJustM :: HasCallStack => IORef Int -> IO (Maybe a) -> (a -> IO ()) -> IO ()
+ NanoUI.Testing.Assert: require :: HasCallStack => String -> Bool -> IO ()
+ NanoUI.Testing.Assert: requireEq :: (HasCallStack, Eq a, Show a) => String -> a -> a -> IO ()
+ NanoUI.Testing.Harness: FrameCost :: Int -> Damage -> Int -> FrameCost
+ NanoUI.Testing.Harness: Vertex :: Float -> Float -> (Float, Float, Float) -> Float -> Float -> Float -> Vertex
+ NanoUI.Testing.Harness: [fcDamage] :: FrameCost -> Damage
+ NanoUI.Testing.Harness: [fcFollowUps] :: FrameCost -> Int
+ NanoUI.Testing.Harness: [fcPasses] :: FrameCost -> Int
+ NanoUI.Testing.Harness: [vA] :: Vertex -> Float
+ NanoUI.Testing.Harness: [vRgb] :: Vertex -> (Float, Float, Float)
+ NanoUI.Testing.Harness: [vU] :: Vertex -> Float
+ NanoUI.Testing.Harness: [vV] :: Vertex -> Float
+ NanoUI.Testing.Harness: [vX] :: Vertex -> Float
+ NanoUI.Testing.Harness: [vY] :: Vertex -> Float
+ NanoUI.Testing.Harness: chordInp :: Shortcut -> Input -> Input
+ NanoUI.Testing.Harness: clickPairWith :: MouseButton -> Input -> V2 -> (Input, Input)
+ NanoUI.Testing.Harness: clipCovers :: Damage -> Rect -> Bool
+ NanoUI.Testing.Harness: covers :: Rect -> Rect -> Bool
+ NanoUI.Testing.Harness: cursorOver :: Context -> Input -> NanoUI a -> V2 -> IO UiCursorKind
+ NanoUI.Testing.Harness: damageCovers :: Damage -> Rect -> Bool
+ NanoUI.Testing.Harness: data FrameCost
+ NanoUI.Testing.Harness: data Vertex
+ NanoUI.Testing.Harness: drawTriangles :: DrawData -> IO [(Vertex, Vertex, Vertex)]
+ NanoUI.Testing.Harness: drawnVertices :: DrawData -> IO [Vertex]
+ NanoUI.Testing.Harness: frameCost :: Context -> Input -> Input -> NanoUI a -> IO (a, FrameCost)
+ NanoUI.Testing.Harness: holdAt :: Input -> V2 -> Input
+ NanoUI.Testing.Harness: indexedVertices :: DrawData -> [Int] -> IO [Vertex]
+ NanoUI.Testing.Harness: instance GHC.Internal.Classes.Eq NanoUI.Testing.Harness.FrameCost
+ NanoUI.Testing.Harness: instance GHC.Internal.Classes.Eq NanoUI.Testing.Harness.Vertex
+ NanoUI.Testing.Harness: instance GHC.Internal.Show.Show NanoUI.Testing.Harness.FrameCost
+ NanoUI.Testing.Harness: instance GHC.Internal.Show.Show NanoUI.Testing.Harness.Vertex
+ NanoUI.Testing.Harness: keyRepeatInp :: Key -> Input -> Input
+ NanoUI.Testing.Harness: keyUpInp :: Key -> Input -> Input
+ NanoUI.Testing.Harness: measureRuns :: Int -> Int -> String -> IO () -> IO ()
+ NanoUI.Testing.Harness: newWakeSignal :: Context -> IO (Int -> IO Bool)
+ NanoUI.Testing.Harness: nodesOfType :: NodeType -> Context -> IO [(WidgetId, Rect)]
+ NanoUI.Testing.Harness: pressWith :: MouseButton -> Input -> V2 -> Input
+ NanoUI.Testing.Harness: releaseWith :: MouseButton -> Input -> Input
+ NanoUI.Testing.Harness: runRightClick :: Context -> Input -> NanoUI a -> V2 -> IO a
+ NanoUI.Testing.Harness: setFocus :: Context -> WidgetId -> IO ()
+ NanoUI.Testing.Harness: spanRect :: Text -> [(Rect, Text, a, b, c)] -> Maybe Rect
+ NanoUI.Testing.Harness: spanRectOf :: Text -> [(Rect, Text, a, b, c)] -> Maybe Rect
+ NanoUI.Testing.Harness: textureVertices :: Int -> DrawData -> IO [Vertex]
+ NanoUI.Testing.Harness: trianglePicture :: DrawData -> IO (Map Int (Int, Rect))
+ NanoUI.Testing.Harness: vertexColor :: Vertex -> Color
+ NanoUI.Testing.Harness: warmupFocused :: Context -> Input -> NanoUI a -> IO ()
+ NanoUI.Testing.Runner: check :: IORef Int -> String -> Bool -> IO ()
+ NanoUI.Testing.Runner: runChecks :: [(String, IORef Int -> IO ())] -> IO ()
+ NanoUI.Testing.Sim: At :: V2 -> Target
+ NanoUI.Testing.Sim: Labelled :: Text -> Target
+ NanoUI.Testing.Sim: On :: Response -> Target
+ NanoUI.Testing.Sim: OnWidget :: WidgetId -> Target
+ NanoUI.Testing.Sim: SimOptions :: (Context -> Input -> NanoUI a -> IO (a, Bool)) -> Bool -> SimOptions a
+ NanoUI.Testing.Sim: Within :: Rect -> Target
+ NanoUI.Testing.Sim: [simFailFast] :: SimOptions a -> Bool
+ NanoUI.Testing.Sim: [simFrameRunner] :: SimOptions a -> Context -> Input -> NanoUI a -> IO (a, Bool)
+ NanoUI.Testing.Sim: advance :: Float -> Sim a a
+ NanoUI.Testing.Sim: afterView :: NanoUI b -> Sim a b
+ NanoUI.Testing.Sim: at :: Float -> Float -> Target
+ NanoUI.Testing.Sim: check :: HasCallStack => Bool -> Sim a ()
+ NanoUI.Testing.Sim: checkEq :: (HasCallStack, Eq b, Show b) => b -> b -> Sim a ()
+ NanoUI.Testing.Sim: checkGt :: (HasCallStack, Ord b, Show b) => b -> b -> Sim a ()
+ NanoUI.Testing.Sim: checkJust :: HasCallStack => Maybe b -> (b -> Sim a ()) -> Sim a ()
+ NanoUI.Testing.Sim: checkLt :: (HasCallStack, Ord b, Show b) => b -> b -> Sim a ()
+ NanoUI.Testing.Sim: chord :: Shortcut -> Sim a a
+ NanoUI.Testing.Sim: click :: HasCallStack => Target -> Sim a a
+ NanoUI.Testing.Sim: clickWith :: HasCallStack => MouseButton -> Target -> Sim a a
+ NanoUI.Testing.Sim: cursorAt :: HasCallStack => Target -> Sim a UiCursorKind
+ NanoUI.Testing.Sim: data Sim a r
+ NanoUI.Testing.Sim: data SimOptions a
+ NanoUI.Testing.Sim: data Target
+ NanoUI.Testing.Sim: defaultSimOptions :: SimOptions a
+ NanoUI.Testing.Sim: doubleClick :: HasCallStack => Target -> Sim a a
+ NanoUI.Testing.Sim: drag :: HasCallStack => Target -> Target -> Int -> Sim a a
+ NanoUI.Testing.Sim: expect :: HasCallStack => Text -> Sim a ()
+ NanoUI.Testing.Sim: expectNot :: HasCallStack => Text -> Sim a ()
+ NanoUI.Testing.Sim: findSpan :: Text -> Sim a (Maybe Rect)
+ NanoUI.Testing.Sim: focusOn :: WidgetId -> Sim a ()
+ NanoUI.Testing.Sim: focusRing :: Sim a Bool
+ NanoUI.Testing.Sim: focusedId :: Sim a WidgetId
+ NanoUI.Testing.Sim: frame :: Sim a a
+ NanoUI.Testing.Sim: frameDamage :: Sim a Damage
+ NanoUI.Testing.Sim: frameWith :: (Input -> Input) -> Sim a a
+ NanoUI.Testing.Sim: getInput :: Sim a Input
+ NanoUI.Testing.Sim: hotId :: Sim a WidgetId
+ NanoUI.Testing.Sim: instance GHC.Internal.Base.Applicative (NanoUI.Testing.Sim.Sim a)
+ NanoUI.Testing.Sim: instance GHC.Internal.Base.Functor (NanoUI.Testing.Sim.Sim a)
+ NanoUI.Testing.Sim: instance GHC.Internal.Base.Monad (NanoUI.Testing.Sim.Sim a)
+ NanoUI.Testing.Sim: instance GHC.Internal.Control.Monad.Fail.MonadFail (NanoUI.Testing.Sim.Sim a)
+ NanoUI.Testing.Sim: instance GHC.Internal.Control.Monad.IO.Class.MonadIO (NanoUI.Testing.Sim.Sim a)
+ NanoUI.Testing.Sim: instance GHC.Internal.Data.String.IsString NanoUI.Testing.Sim.Target
+ NanoUI.Testing.Sim: labelShown :: Text -> Sim a Bool
+ NanoUI.Testing.Sim: modifyInput :: (Input -> Input) -> Sim a ()
+ NanoUI.Testing.Sim: moveTo :: HasCallStack => Target -> Sim a a
+ NanoUI.Testing.Sim: onContext :: (Context -> IO b) -> Sim a b
+ NanoUI.Testing.Sim: pointerCursor :: Sim a UiCursorKind
+ NanoUI.Testing.Sim: press :: HasCallStack => Target -> Sim a a
+ NanoUI.Testing.Sim: pressButton :: HasCallStack => MouseButton -> Target -> Sim a a
+ NanoUI.Testing.Sim: pressKey :: Key -> Sim a a
+ NanoUI.Testing.Sim: pressTab :: Int -> Sim a ()
+ NanoUI.Testing.Sim: prevRect :: WidgetId -> Sim a Rect
+ NanoUI.Testing.Sim: readV :: Var v -> Sim a v
+ NanoUI.Testing.Sim: rectOf :: Text -> Sim a Rect
+ NanoUI.Testing.Sim: release :: Sim a a
+ NanoUI.Testing.Sim: releaseButton :: MouseButton -> Sim a a
+ NanoUI.Testing.Sim: resize :: Float -> Float -> Sim a a
+ NanoUI.Testing.Sim: result :: Sim a a
+ NanoUI.Testing.Sim: rightClick :: HasCallStack => Target -> Sim a a
+ NanoUI.Testing.Sim: runSim :: Context -> IORef Int -> Input -> NanoUI a -> Sim a r -> IO r
+ NanoUI.Testing.Sim: runSimWith :: SimOptions a -> Context -> IORef Int -> Input -> NanoUI a -> Sim a r -> IO r
+ NanoUI.Testing.Sim: scrollOffset2DOf :: WidgetId -> Sim a V2
+ NanoUI.Testing.Sim: scrollOffsetOf :: WidgetId -> Sim a Float
+ NanoUI.Testing.Sim: settle :: Sim a a
+ NanoUI.Testing.Sim: simContext :: Sim a Context
+ NanoUI.Testing.Sim: simFailures :: Sim a (IORef Int)
+ NanoUI.Testing.Sim: spans :: Sim a [(Rect, Text, Color, Color, Rect)]
+ NanoUI.Testing.Sim: targetPoint :: HasCallStack => Target -> Sim a V2
+ NanoUI.Testing.Sim: textShown :: Text -> Sim a Bool
+ NanoUI.Testing.Sim: typeText :: Text -> Sim a a
+ NanoUI.Testing.Sim: wakeTime :: Sim a Double
+ NanoUI.Testing.Sim: wantsFrame :: Sim a Bool
+ NanoUI.Testing.Sim: wheel :: HasCallStack => Target -> V2 -> Sim a a
+ NanoUI.Testing.Sim: wouldRedraw :: (Input -> Input) -> Sim a Bool
+ NanoUI.Testing.Sim: writeV :: Eq v => Var v -> v -> Sim a ()
+ NanoUI.Themes: Base16 :: Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Base16
+ NanoUI.Themes: [base00] :: Base16 -> Color
+ NanoUI.Themes: [base01] :: Base16 -> Color
+ NanoUI.Themes: [base02] :: Base16 -> Color
+ NanoUI.Themes: [base03] :: Base16 -> Color
+ NanoUI.Themes: [base04] :: Base16 -> Color
+ NanoUI.Themes: [base05] :: Base16 -> Color
+ NanoUI.Themes: [base06] :: Base16 -> Color
+ NanoUI.Themes: [base07] :: Base16 -> Color
+ NanoUI.Themes: [base08] :: Base16 -> Color
+ NanoUI.Themes: [base09] :: Base16 -> Color
+ NanoUI.Themes: [base0A] :: Base16 -> Color
+ NanoUI.Themes: [base0B] :: Base16 -> Color
+ NanoUI.Themes: [base0C] :: Base16 -> Color
+ NanoUI.Themes: [base0D] :: Base16 -> Color
+ NanoUI.Themes: [base0E] :: Base16 -> Color
+ NanoUI.Themes: [base0F] :: Base16 -> Color
+ NanoUI.Themes: base16TomorrowLight :: Base16
+ NanoUI.Themes: base16TomorrowNight :: Base16
+ NanoUI.Themes: data Base16
+ NanoUI.Themes: themeFromBase16 :: Base16 -> Theme
+ NanoUI.Themes: themeFromBase16Dark :: Base16 -> Theme
+ NanoUI.Themes: themeFromBase16Light :: Base16 -> Theme
+ NanoUI.Themes: tomorrowMidnightMinDarkTheme :: Theme
+ NanoUI.Themes: tomorrowMinLightTheme :: Theme
+ NanoUI.Themes: tomorrowNightMinDarkTheme :: Theme
+ NanoUI.Var: class VarSlot a
+ NanoUI.Var: constVar :: a -> Var a
+ NanoUI.Var: data Var a
+ NanoUI.Var: data VarMap k a
+ NanoUI.Var: dropVar :: Hashable k => VarMap k a -> k -> NanoUI ()
+ NanoUI.Var: forEachVar :: Hashable k => (a -> k) -> Var [a] -> (Var a -> NanoUI ()) -> NanoUI ()
+ NanoUI.Var: modifyVar :: Eq a => Var a -> (a -> a) -> NanoUI ()
+ NanoUI.Var: modifyVarIO :: Eq a => Var a -> (a -> a) -> IO ()
+ NanoUI.Var: newVar :: a -> IO (Var a)
+ NanoUI.Var: newVarMap :: IO (VarMap k a)
+ NanoUI.Var: peekVar :: Var a -> NanoUI a
+ NanoUI.Var: readVar :: Var a -> NanoUI a
+ NanoUI.Var: readVarIO :: Var a -> IO a
+ NanoUI.Var: retainVars :: (k -> Bool) -> VarMap k a -> NanoUI ()
+ NanoUI.Var: useEnumVar :: (Bounded a, Enum a, Typeable a) => a -> NanoUI (Var a)
+ NanoUI.Var: useVar :: VarSlot a => a -> NanoUI (Var a)
+ NanoUI.Var: varAt :: Hashable k => VarMap k a -> k -> a -> NanoUI (Var a)
+ NanoUI.Var: withElemVars :: Hashable k => (a -> k) -> Var [a] -> ([a] -> (a -> Var a) -> NanoUI r) -> NanoUI r
+ NanoUI.Var: withValue :: a -> (Var a -> NanoUI r) -> NanoUI (r, a)
+ NanoUI.Var: writeVar :: Eq a => Var a -> a -> NanoUI ()
+ NanoUI.Var: writeVarIO :: Eq a => Var a -> a -> IO ()
+ NanoUI.Var: zoomVar :: (s -> a) -> (a -> s -> s) -> Var s -> Var a
+ NanoUI.Var: zoomVarL :: (forall (f :: Type -> Type). Functor f => (a -> f a) -> s -> f s) -> Var s -> Var a
+ NanoUI.Widgets.Combo: [ciInput] :: ComboInput -> Input
+ NanoUI.Widgets.Combo: [csNavPointer] :: ComboState -> Maybe V2
+ NanoUI.Widgets.Combo: [csWheelRem] :: ComboState -> Float
+ NanoUI.Widgets.Combo: instance GHC.Internal.Classes.Eq NanoUI.Widgets.Combo.ComboInput
+ NanoUI.Widgets.Combo: instance GHC.Internal.Classes.Eq NanoUI.Widgets.Combo.ComboStep
+ NanoUI.Widgets.Combo: instance GHC.Internal.Show.Show NanoUI.Widgets.Combo.ComboInput
+ NanoUI.Widgets.Combo: instance GHC.Internal.Show.Show NanoUI.Widgets.Combo.ComboStep
+ NanoUI.Widgets.Custom: CanvasConfig :: LayoutModifier -> Int -> Bool -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind) -> Bool -> KeyClaim -> CanvasConfig
+ NanoUI.Widgets.Custom: Conservative :: Binding
+ NanoUI.Widgets.Custom: DrawImage :: Rect -> Float -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: DrawText :: Float -> Float -> Float -> Float -> Text -> Color -> DrawOp
+ NanoUI.Widgets.Custom: DrawTextAligned :: Float -> Float -> Float -> Float -> Float -> TextFont -> Text -> Color -> DrawOp
+ NanoUI.Widgets.Custom: DrawTextStyled :: Float -> Float -> TextFont -> Text -> Color -> DrawOp
+ NanoUI.Widgets.Custom: FillCircle :: Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: FillPolygon :: PrimArray Float -> PrimArray Int -> PrimArray Int -> Shade -> DrawOp
+ NanoUI.Widgets.Custom: FillQuadGradient :: Rect -> Color -> Color -> Color -> Color -> DrawOp
+ NanoUI.Widgets.Custom: FillRect :: Rect -> Color -> DrawOp
+ NanoUI.Widgets.Custom: FillRoundedRect :: Rect -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: FillTriangle :: Float -> Float -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: ImageDraw :: Rect -> ImageId -> Rect -> Float -> Color -> Float -> ImageDraw
+ NanoUI.Widgets.Custom: KeysActivate :: KeyClaim
+ NanoUI.Widgets.Custom: KeysAll :: KeyClaim
+ NanoUI.Widgets.Custom: KeysNavigate :: KeyClaim
+ NanoUI.Widgets.Custom: KeysNone :: KeyClaim
+ NanoUI.Widgets.Custom: KeysOnly :: [Shortcut] -> KeyClaim
+ NanoUI.Widgets.Custom: KeysReadOnly :: KeyClaim
+ NanoUI.Widgets.Custom: KeysType :: KeyClaim
+ NanoUI.Widgets.Custom: PopClip :: DrawOp
+ NanoUI.Widgets.Custom: PushClip :: Rect -> DrawOp
+ NanoUI.Widgets.Custom: RenderFinal :: Binding
+ NanoUI.Widgets.Custom: Stroke :: Float -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: StrokeCircle :: Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: StrokeLineAA :: Float -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: StrokePolyline :: PrimArray Float -> Float -> Bool -> LineCap -> LineJoin -> Float -> Shade -> DrawOp
+ NanoUI.Widgets.Custom: StrokeRoundedRect :: Rect -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: [canvasContent] :: CanvasConfig -> Int
+ NanoUI.Widgets.Custom: [canvasCursor] :: CanvasConfig -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind)
+ NanoUI.Widgets.Custom: [canvasFocusable] :: CanvasConfig -> Bool
+ NanoUI.Widgets.Custom: [canvasKeys] :: CanvasConfig -> KeyClaim
+ NanoUI.Widgets.Custom: [canvasLayout] :: CanvasConfig -> LayoutModifier
+ NanoUI.Widgets.Custom: [canvasTrackPointer] :: CanvasConfig -> Bool
+ NanoUI.Widgets.Custom: [imageAngle] :: ImageDraw -> Float
+ NanoUI.Widgets.Custom: [imageId] :: ImageDraw -> ImageId
+ NanoUI.Widgets.Custom: [imageOpacity] :: ImageDraw -> Float
+ NanoUI.Widgets.Custom: [imageRect] :: ImageDraw -> Rect
+ NanoUI.Widgets.Custom: [imageTint] :: ImageDraw -> Color
+ NanoUI.Widgets.Custom: [imageUV] :: ImageDraw -> Rect
+ NanoUI.Widgets.Custom: [widgetKeys] :: CustomWidgetSpec a -> KeyClaim
+ NanoUI.Widgets.Custom: [widgetTrackPointer] :: CustomWidgetSpec a -> Bool
+ NanoUI.Widgets.Custom: bindVar :: Eq a => Binding -> Var a -> (a -> NanoUI (r, a)) -> NanoUI r
+ NanoUI.Widgets.Custom: bindVarBy :: (a -> a -> Bool) -> Binding -> Var a -> (a -> NanoUI (r, a)) -> NanoUI r
+ NanoUI.Widgets.Custom: canvasConfigured :: CanvasConfig -> (Rect -> CanvasM ()) -> NanoUI Response
+ NanoUI.Widgets.Custom: checkboxBoxSize :: FontMetrics -> Float
+ NanoUI.Widgets.Custom: contentKeyOf :: [KeyPart] -> Int
+ NanoUI.Widgets.Custom: data Binding
+ NanoUI.Widgets.Custom: data CanvasConfig
+ NanoUI.Widgets.Custom: data DrawOp
+ NanoUI.Widgets.Custom: data ImageDraw
+ NanoUI.Widgets.Custom: data KeyClaim
+ NanoUI.Widgets.Custom: data KeyPart
+ NanoUI.Widgets.Custom: defaultCanvasConfig :: CanvasConfig
+ NanoUI.Widgets.Custom: drawCheckbox :: Theme -> Rect -> Bool -> CanvasM ()
+ NanoUI.Widgets.Custom: drawContext :: CanvasM CustomDrawContext
+ NanoUI.Widgets.Custom: drawImageWith :: ImageDraw -> CanvasM ()
+ NanoUI.Widgets.Custom: drawPath :: Path -> Color -> CanvasM ()
+ NanoUI.Widgets.Custom: drawPathWith :: FillRule -> Path -> Paint -> CanvasM ()
+ NanoUI.Widgets.Custom: drawStrokePath :: Path -> Float -> Color -> CanvasM ()
+ NanoUI.Widgets.Custom: drawStrokePathWith :: Stroke -> Path -> Paint -> CanvasM ()
+ NanoUI.Widgets.Custom: drawTextClipped :: Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Widgets.Custom: drawTextClippedWith :: FontMetrics -> TextFont -> TextEllipsis -> Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Widgets.Custom: drawTextWith :: TextFont -> V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()
+ NanoUI.Widgets.Custom: drawing :: (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> NanoUI Response
+ NanoUI.Widgets.Custom: drawingCached :: Double -> Double -> Float -> Int -> (Layout -> Layout) -> IO Layout -> DrawingBuild -> NanoUI Response
+ NanoUI.Widgets.Custom: drawingVersioned :: Int -> (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> NanoUI Response
+ NanoUI.Widgets.Custom: imageDraw :: Rect -> ImageId -> ImageDraw
+ NanoUI.Widgets.Custom: keyPart :: Hashable a => a -> KeyPart
+ NanoUI.Widgets.Custom: pattern DrawImageRect :: Rect -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp
+ NanoUI.Widgets.Custom: runCanvasFor :: CustomDrawContext -> CanvasM a -> SmallArray DrawOp
+ NanoUI.Widgets.Custom: setChanged :: Bool -> Response -> Response
+ NanoUI.Widgets.Custom: setClicked :: Bool -> Response -> Response
+ NanoUI.Widgets.Custom: setSubmitted :: Bool -> Response -> Response
+ NanoUI.Widgets.Custom: shiftDrawOp :: Float -> Float -> DrawOp -> DrawOp
+ NanoUI.Widgets.Custom: type DrawingBuild = Rect -> SmallArray DrawOp
+ NanoUI.Widgets.Custom: useDrag2DOn :: HasResponse r => r -> NanoUI Drag2D
+ NanoUI.Widgets.Custom: useWheelDeltaOn :: HasResponse r => r -> NanoUI (Float, Float)
+ NanoUI.Widgets.Custom: withClip :: Rect -> CanvasM a -> CanvasM a
+ NanoUI.Widgets.Custom: withTransform :: Transform -> CanvasM a -> CanvasM a
+ NanoUI.Widgets.PaneGrid: BesidePane :: Word64 -> PaneEdge -> PaneDropLocation
+ NanoUI.Widgets.PaneGrid: CenterSwap :: CenterDropMode
+ NanoUI.Widgets.PaneGrid: CenterTab :: CenterDropMode
+ NanoUI.Widgets.PaneGrid: ControlledTree :: Var (Maybe GridNode) -> PaneTree
+ NanoUI.Widgets.PaneGrid: InitialTree :: Maybe GridNode -> PaneTree
+ NanoUI.Widgets.PaneGrid: IntoTabs :: Word64 -> PaneDropLocation
+ NanoUI.Widgets.PaneGrid: OutsideGrid :: PaneEdge -> PaneDropLocation
+ NanoUI.Widgets.PaneGrid: Pane :: Word64 -> GridNode
+ NanoUI.Widgets.PaneGrid: PaneAbove :: PaneEdge
+ NanoUI.Widgets.PaneGrid: PaneBelow :: PaneEdge
+ NanoUI.Widgets.PaneGrid: PaneLeft :: PaneEdge
+ NanoUI.Widgets.PaneGrid: PaneRight :: PaneEdge
+ NanoUI.Widgets.PaneGrid: PaneTabs :: Word64 -> [Word64] -> Word64 -> GridNode
+ NanoUI.Widgets.PaneGrid: Split :: Word64 -> GridAxis -> Float -> GridNode -> GridNode -> GridNode
+ NanoUI.Widgets.PaneGrid: [pgCenterDrop] :: PaneGridConfig -> CenterDropMode
+ NanoUI.Widgets.PaneGrid: [pgClosableTabs] :: PaneGridConfig -> Bool
+ NanoUI.Widgets.PaneGrid: [pgDividerColor] :: PaneGridConfig -> Maybe Color
+ NanoUI.Widgets.PaneGrid: [pgFixedPanes] :: PaneGridConfig -> Word64 -> Bool
+ NanoUI.Widgets.PaneGrid: [pgFocusable] :: PaneGridConfig -> Bool
+ NanoUI.Widgets.PaneGrid: [pgPreserveDragSize] :: PaneGridConfig -> Bool
+ NanoUI.Widgets.PaneGrid: [pgTabTitle] :: PaneGridConfig -> Word64 -> Text
+ NanoUI.Widgets.PaneGrid: [pgTree] :: PaneGridConfig -> PaneTree
+ NanoUI.Widgets.PaneGrid: [pgViewTab] :: PaneGridConfig -> Maybe (Word64 -> Bool -> NanoUI ())
+ NanoUI.Widgets.PaneGrid: [pgrCommitted] :: PaneGridResponse -> Bool
+ NanoUI.Widgets.PaneGrid: [pgrDropTarget] :: PaneGridResponse -> Maybe PaneGridDrop
+ NanoUI.Widgets.PaneGrid: [pgrTree] :: PaneGridResponse -> Maybe GridNode
+ NanoUI.Widgets.PaneGrid: commitPaneDrop :: PaneGridDrop -> NanoUI (Maybe (Word64, GridNode))
+ NanoUI.Widgets.PaneGrid: data CenterDropMode
+ NanoUI.Widgets.PaneGrid: data GridNode
+ NanoUI.Widgets.PaneGrid: data PaneDropLocation
+ NanoUI.Widgets.PaneGrid: data PaneEdge
+ NanoUI.Widgets.PaneGrid: data PaneGridDrop
+ NanoUI.Widgets.PaneGrid: data PaneTree
+ NanoUI.Widgets.PaneGrid: instance GHC.Internal.Classes.Eq NanoUI.Widgets.PaneGrid.PaneDropLocation
+ NanoUI.Widgets.PaneGrid: instance GHC.Internal.Classes.Eq NanoUI.Widgets.PaneGrid.PaneEdge
+ NanoUI.Widgets.PaneGrid: instance GHC.Internal.Classes.Eq NanoUI.Widgets.PaneGrid.PaneGridDrop
+ NanoUI.Widgets.PaneGrid: instance GHC.Internal.Show.Show NanoUI.Widgets.PaneGrid.PaneDropLocation
+ NanoUI.Widgets.PaneGrid: instance GHC.Internal.Show.Show NanoUI.Widgets.PaneGrid.PaneEdge
+ NanoUI.Widgets.PaneGrid: instance GHC.Internal.Show.Show NanoUI.Widgets.PaneGrid.PaneGridDrop
+ NanoUI.Widgets.PaneGrid: paneDragHandle :: PaneGridCtx -> (Layout -> Layout) -> NanoUI a -> NanoUI a
+ NanoUI.Widgets.PaneGrid: pgdLocation :: PaneGridDrop -> PaneDropLocation
+ NanoUI.Widgets.PaneGrid: pgdPane :: PaneGridDrop -> Word64
+ NanoUI.Widgets.PaneGrid: pgdRect :: PaneGridDrop -> Rect
+ NanoUI.Widgets.PaneGrid: treeAddTab :: Word64 -> Word64 -> Maybe Int -> Word64 -> GridNode -> GridNode
+ NanoUI.Widgets.PaneGrid: treePanes :: GridNode -> [Word64]
+ NanoUI.Widgets.PaneGrid: treeRemovePane :: Word64 -> GridNode -> Maybe GridNode
+ NanoUI.Widgets.PaneGrid: treeSelectTab :: Word64 -> GridNode -> GridNode
+ NanoUI.Widgets.PaneGrid: treeSplit :: Word64 -> Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode
+ NanoUI.Widgets.PaneGrid: validateGridTree :: GridNode -> Either String ()
+ NanoUI.Widgets.RichText: inlineBackground :: Color -> Inline -> Inline
+ NanoUI.Widgets.RichText: inlineTooltip :: Text -> Inline -> Inline
+ NanoUI.Widgets.RichText: selectableRichText :: [Inline] -> NanoUI (Maybe Text)
+ NanoUI.Widgets.RichText: selectableRichText' :: [Inline] -> NanoUI (Response, Maybe Text)
+ NanoUI.Widgets.RichText: selectableRichTextWith :: (Layout -> Layout) -> [Inline] -> NanoUI (Maybe Text)
+ NanoUI.Widgets.RichText: selectableRichTextWith' :: (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)
+ NanoUI.Widgets.TextArea: [tasBuffer] :: TextAreaState -> TextBuffer
+ NanoUI.Widgets.TextArea: [tasHistory] :: TextAreaState -> EditHistory
+ NanoUI.Widgets.TextArea: [tasLineHeight] :: TextAreaState -> Double
+ NanoUI.Widgets.TextArea: [tasScrollOffset] :: TextAreaState -> (Double, Double)
+ NanoUI.Widgets.TextArea: [tasSelectionAnchor] :: TextAreaState -> Cursor
+ NanoUI.Widgets.TextArea: [tasViewportSize] :: TextAreaState -> (Double, Double)
+ NanoUI.Widgets.TextArea: textAreaDocument :: Var TextDocument -> NanoUI ()
+ NanoUI.Widgets.TextArea: textAreaDocument' :: Var TextDocument -> NanoUI Response
+ NanoUI.Widgets.TextArea: textAreaDocumentWith :: (Layout -> Layout) -> Var TextDocument -> NanoUI ()
+ NanoUI.Widgets.TextArea: textAreaDocumentWith' :: (Layout -> Layout) -> Var TextDocument -> NanoUI Response
+ NanoUI.Widgets.TextBuffer: fromLines :: Seq Text -> TextBuffer
+ NanoUI.Widgets.TextBuffer: joinLines :: Seq Text -> Text
+ NanoUI.Widgets.TextBuffer: snapToCluster :: TextBuffer -> Cursor -> Cursor
+ NanoUI.Widgets.TextBuffer: splitLines :: Text -> Seq Text
+ NanoUI.Widgets.TextCommand: instance GHC.Internal.Classes.Ord NanoUI.Widgets.TextCommand.TextMotion
+ NanoUI.Widgets.TextDocument: bufferDocument :: TextBuffer -> TextDocument
+ NanoUI.Widgets.TextDocument: data TextDocument
+ NanoUI.Widgets.TextDocument: documentBuffer :: TextDocument -> TextBuffer
+ NanoUI.Widgets.TextDocument: documentLine :: Int -> TextDocument -> Text
+ NanoUI.Widgets.TextDocument: documentLineCount :: TextDocument -> Int
+ NanoUI.Widgets.TextDocument: documentLines :: TextDocument -> Seq Text
+ NanoUI.Widgets.TextDocument: documentRange :: Cursor -> Cursor -> TextDocument -> Text
+ NanoUI.Widgets.TextDocument: documentText :: TextDocument -> Text
+ NanoUI.Widgets.TextDocument: editDocument :: TextEdit -> TextDocument -> TextDocument
+ NanoUI.Widgets.TextDocument: emptyDocument :: TextDocument
+ NanoUI.Widgets.TextDocument: replaceDocumentRange :: Cursor -> Cursor -> Text -> TextDocument -> TextDocument
+ NanoUI.Widgets.TextDocument: sameDocument :: TextDocument -> TextDocument -> Bool
+ NanoUI.Widgets.TextDocument: textDocument :: Text -> TextDocument
- NanoUI: Input :: V2 -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> V2 -> SmallArray Key -> Text -> Modifiers -> Size -> Float -> SmallArray DropEvent -> Bool -> Input
+ NanoUI: Input :: V2 -> MouseButtons -> MouseButtons -> MouseButtons -> Int -> V2 -> SmallArray Key -> SmallArray Key -> SmallArray Key -> SmallArray Key -> Text -> Modifiers -> Size -> Float -> SmallArray DropEvent -> Bool -> Maybe Composition -> Input
- NanoUI: Modifiers :: Bool -> Bool -> Bool -> Modifiers
+ NanoUI: Modifiers :: Bool -> Bool -> Bool -> Bool -> Modifiers
- NanoUI: NumericInputConfig :: Double -> Double -> Double -> Int -> Bool -> Layout -> NumericInputConfig
+ NanoUI: NumericInputConfig :: Double -> Double -> Double -> Int -> Bool -> LayoutModifier -> NumericInputConfig
- NanoUI: Response :: WidgetId -> Rect -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Response
+ NanoUI: Response :: WidgetId -> Rect -> Bool -> Bool -> Bool -> Bool -> MouseButtons -> MouseButtons -> Response
- NanoUI: Style :: Color -> Color -> Color -> Float -> Float -> Color -> Color -> Style
+ NanoUI: Style :: Color -> Color -> Color -> Float -> Float -> Color -> Color -> Word8 -> Style
- NanoUI: Tab :: a -> Text -> Bool -> Bool -> Maybe Text -> body -> Tab a body
+ NanoUI: Tab :: a -> Text -> Bool -> Bool -> Maybe Text -> Adornments -> body -> Tab a body
- NanoUI: TabResponse :: Response -> Maybe a -> a -> TabResponse a
+ NanoUI: TabResponse :: Response -> Maybe a -> a -> [(a, Response)] -> Rect -> TabResponse a
- NanoUI: TableConfig :: Int -> Int -> [ColSize] -> IntSet -> TableConfig
+ NanoUI: TableConfig :: Int -> Int -> [ColSize] -> IntSet -> Bool -> Bool -> TableConfig
- NanoUI: TabsConfig :: TabStyle -> TabOrientation -> TabsConfig
+ NanoUI: TabsConfig :: TabStyle -> TabOrientation -> NanoUI () -> TabsConfig
- NanoUI: TextFont :: Float -> FontVariant -> FontWeight -> FontStyle -> TextDecoration -> TextFont
+ NanoUI: TextFont :: Float -> FontVariant -> FontWeight -> FontStyle -> TextDecoration -> Bool -> TextFont
- NanoUI: TextInputConfig :: Text -> Bool -> Layout -> TextInputConfig
+ NanoUI: TextInputConfig :: Text -> Bool -> LayoutModifier -> Adornments -> TextInputConfig
- NanoUI: Theme :: Color -> Style -> Style -> Style -> Style -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Float -> Theme
+ NanoUI: Theme :: Color -> Maybe Color -> Style -> Style -> Style -> Style -> Style -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Color -> Float -> Theme
- NanoUI: [nicLayout] :: NumericInputConfig -> Layout
+ NanoUI: [nicLayout] :: NumericInputConfig -> LayoutModifier
- NanoUI: [ticLayout] :: TextInputConfig -> Layout
+ NanoUI: [ticLayout] :: TextInputConfig -> LayoutModifier
- NanoUI: animate :: forall (es :: [Effect]). Ui :> es => Transition -> Float -> Float -> Eff es Float
+ NanoUI: animate :: Transition -> Float -> Float -> NanoUI Float
- NanoUI: animateTo :: forall (es :: [Effect]). Ui :> es => Transition -> Float -> Eff es Float
+ NanoUI: animateTo :: Transition -> Float -> NanoUI Float
- NanoUI: animateToA :: forall a (es :: [Effect]). (Animatable a, Ui :> es) => Transition -> a -> Eff es a
+ NanoUI: animateToA :: Animatable a => Transition -> a -> NanoUI a
- NanoUI: askDefaultLayout :: forall (es :: [Effect]). Ui :> es => Eff es Layout
+ NanoUI: askDefaultLayout :: NanoUI Layout
- NanoUI: bold :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: bold :: Text -> NanoUI ()
- NanoUI: box :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Color -> Eff es ()
+ NanoUI: box :: (Layout -> Layout) -> Color -> NanoUI ()
- NanoUI: button :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Bool
+ NanoUI: button :: Text -> NanoUI Bool
- NanoUI: button' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Response
+ NanoUI: button' :: Text -> NanoUI Response
- NanoUI: buttonWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es Bool
+ NanoUI: buttonWith :: (Layout -> Layout) -> Text -> NanoUI Bool
- NanoUI: buttonWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es Response
+ NanoUI: buttonWith' :: (Layout -> Layout) -> Text -> NanoUI Response
- NanoUI: callout :: forall (es :: [Effect]) a. Ui :> es => Color -> Eff es a -> Eff es a
+ NanoUI: callout :: Color -> NanoUI a -> NanoUI a
- NanoUI: calloutWith :: forall (es :: [Effect]) a. Ui :> es => Color -> (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: calloutWith :: Color -> (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: canvas :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> (Rect -> CanvasM ()) -> Eff es Response
+ NanoUI: canvas :: LayoutModifier -> (Rect -> CanvasM ()) -> NanoUI Response
- NanoUI: card :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: card :: NanoUI a -> NanoUI a
- NanoUI: center :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: center :: NanoUI a -> NanoUI a
- NanoUI: checkbox :: forall (es :: [Effect]). Ui :> es => Text -> Bool -> Eff es Bool
+ NanoUI: checkbox :: Text -> Var Bool -> NanoUI ()
- NanoUI: checkbox' :: forall (es :: [Effect]). Ui :> es => Text -> Bool -> Eff es (Response, Bool)
+ NanoUI: checkbox' :: Text -> Var Bool -> NanoUI Response
- NanoUI: circularProgress :: forall (es :: [Effect]). Ui :> es => Float -> Eff es ()
+ NanoUI: circularProgress :: Float -> NanoUI ()
- NanoUI: circularProgress' :: forall (es :: [Effect]). Ui :> es => Float -> Eff es Response
+ NanoUI: circularProgress' :: Float -> NanoUI Response
- NanoUI: circularProgressWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es ()
+ NanoUI: circularProgressWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()
- NanoUI: circularProgressWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es Response
+ NanoUI: circularProgressWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response
- NanoUI: colorPicker :: forall (es :: [Effect]). Ui :> es => Color -> Eff es Color
+ NanoUI: colorPicker :: Var Color -> NanoUI ()
- NanoUI: colorPicker' :: forall (es :: [Effect]). Ui :> es => Color -> Eff es (Response, Color)
+ NanoUI: colorPicker' :: Var Color -> NanoUI Response
- NanoUI: colorPickerRGBA :: forall (es :: [Effect]). Ui :> es => Color -> Eff es Color
+ NanoUI: colorPickerRGBA :: Var Color -> NanoUI ()
- NanoUI: colorPickerRGBA' :: forall (es :: [Effect]). Ui :> es => Color -> Eff es (Response, Color)
+ NanoUI: colorPickerRGBA' :: Var Color -> NanoUI Response
- NanoUI: column :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: column :: NanoUI a -> NanoUI a
- NanoUI: columnWith :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: columnWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: comboBox :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => Text -> f Text -> Text -> Eff es Text
+ NanoUI: comboBox :: Foldable f => Text -> f Text -> Var Text -> NanoUI ()
- NanoUI: comboBox' :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => Text -> f Text -> Text -> Eff es (Response, Text)
+ NanoUI: comboBox' :: Foldable f => Text -> f Text -> Var Text -> NanoUI Response
- NanoUI: contextMenu :: forall (es :: [Effect]) r a. (Ui :> es, HasResponse r) => r -> Eff es a -> Eff es (Maybe a)
+ NanoUI: contextMenu :: HasResponse r => r -> NanoUI a -> NanoUI (Maybe a)
- NanoUI: contextMenuArea :: forall (es :: [Effect]) a b. Ui :> es => (Layout -> Layout) -> Eff es a -> (V2 -> Eff es b) -> Eff es (a, Maybe b)
+ NanoUI: contextMenuArea :: (Layout -> Layout) -> NanoUI a -> (V2 -> NanoUI b) -> NanoUI (a, Maybe b)
- NanoUI: currentId :: forall (es :: [Effect]). Ui :> es => Eff es WidgetId
+ NanoUI: currentId :: NanoUI WidgetId
- NanoUI: danger :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: danger :: Text -> NanoUI ()
- NanoUI: disabledWhen :: forall (es :: [Effect]) a. Ui :> es => Bool -> Eff es a -> Eff es a
+ NanoUI: disabledWhen :: Bool -> NanoUI a -> NanoUI a
- NanoUI: dropZone :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es (a, Response, DropTarget)
+ NanoUI: dropZone :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response, DropTarget)
- NanoUI: enumRadio :: forall a (es :: [Effect]). (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es a
+ NanoUI: enumRadio :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()
- NanoUI: enumRadio' :: forall a (es :: [Effect]). (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es (Response, a)
+ NanoUI: enumRadio' :: (Bounded a, Enum a, Show a) => Var a -> NanoUI Response
- NanoUI: enumSelect :: forall a (es :: [Effect]). (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es a
+ NanoUI: enumSelect :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()
- NanoUI: enumSelect' :: forall a (es :: [Effect]). (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es (Response, a)
+ NanoUI: enumSelect' :: (Bounded a, Enum a, Show a) => Var a -> NanoUI Response
- NanoUI: flex :: forall (es :: [Effect]). Ui :> es => Eff es ()
+ NanoUI: flex :: NanoUI ()
- NanoUI: freshImageId :: forall (es :: [Effect]). Ui :> es => Eff es ImageId
+ NanoUI: freshImageId :: NanoUI ImageId
- NanoUI: getScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)
+ NanoUI: getScrollMetrics :: WidgetId -> NanoUI (Maybe ScrollMetrics)
- NanoUI: getScrollTuning :: Context -> IO ScrollTuning
+ NanoUI: getScrollTuning :: NanoUI ScrollTuning
- NanoUI: grid :: forall (es :: [Effect]) a. Ui :> es => Int -> Eff es a -> Eff es a
+ NanoUI: grid :: Int -> NanoUI a -> NanoUI a
- NanoUI: gridWith :: forall (es :: [Effect]) a. Ui :> es => Int -> (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: gridWith :: Int -> (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: heading :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: heading :: Text -> NanoUI ()
- NanoUI: image :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> ImageId -> Eff es ()
+ NanoUI: image :: (Layout -> Layout) -> ImageId -> NanoUI ()
- NanoUI: image' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> ImageId -> Eff es Response
+ NanoUI: image' :: (Layout -> Layout) -> ImageId -> NanoUI Response
- NanoUI: italic :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: italic :: Text -> NanoUI ()
- NanoUI: keepAnimating :: forall r (es :: [Effect]). (HasResponse r, Ui :> es) => r -> Eff es ()
+ NanoUI: keepAnimating :: HasResponse r => r -> NanoUI ()
- NanoUI: knob :: forall (es :: [Effect]). Ui :> es => Float -> Float -> Float -> Eff es Float
+ NanoUI: knob :: Float -> Float -> Var Float -> NanoUI ()
- NanoUI: knob' :: forall (es :: [Effect]). Ui :> es => Float -> Float -> Float -> Eff es (Response, Float)
+ NanoUI: knob' :: Float -> Float -> Var Float -> NanoUI Response
- NanoUI: knobWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Float -> Eff es Float
+ NanoUI: knobWith :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI ()
- NanoUI: knobWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Float -> Eff es (Response, Float)
+ NanoUI: knobWith' :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI Response
- NanoUI: kv :: forall (es :: [Effect]). Ui :> es => Text -> Text -> Eff es ()
+ NanoUI: kv :: Text -> Text -> NanoUI ()
- NanoUI: kvBlock :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f (Text, Text) -> Eff es ()
+ NanoUI: kvBlock :: Foldable f => f (Text, Text) -> NanoUI ()
- NanoUI: kvMono :: forall (es :: [Effect]). Ui :> es => Text -> Text -> Eff es ()
+ NanoUI: kvMono :: Text -> Text -> NanoUI ()
- NanoUI: label :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: label :: Text -> NanoUI ()
- NanoUI: label' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Response
+ NanoUI: label' :: Text -> NanoUI Response
- NanoUI: labelWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es ()
+ NanoUI: labelWith :: (Layout -> Layout) -> Text -> NanoUI ()
- NanoUI: labelWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es Response
+ NanoUI: labelWith' :: (Layout -> Layout) -> Text -> NanoUI Response
- NanoUI: menuButton :: forall (es :: [Effect]). Ui :> es => Text -> Bool -> Eff es Bool
+ NanoUI: menuButton :: Text -> Bool -> NanoUI Bool
- NanoUI: menuButton' :: forall (es :: [Effect]). Ui :> es => Text -> Bool -> Eff es Response
+ NanoUI: menuButton' :: Text -> Bool -> NanoUI Response
- NanoUI: menuHeader :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: menuHeader :: Text -> NanoUI ()
- NanoUI: menuItem :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Bool
+ NanoUI: menuItem :: Text -> NanoUI Bool
- NanoUI: menuItem' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Response
+ NanoUI: menuItem' :: Text -> NanoUI Response
- NanoUI: menuItemDisabled :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: menuItemDisabled :: Text -> NanoUI ()
- NanoUI: menuItemShortcut :: forall (es :: [Effect]). Ui :> es => Text -> Text -> Eff es Bool
+ NanoUI: menuItemShortcut :: Text -> Shortcut -> NanoUI Bool
- NanoUI: menuSeparator :: forall (es :: [Effect]). Ui :> es => Eff es ()
+ NanoUI: menuSeparator :: NanoUI ()
- NanoUI: modal :: forall (es :: [Effect]) a. Ui :> es => Bool -> Text -> Eff es a -> Eff es (Response, Maybe a)
+ NanoUI: modal :: Var Bool -> Text -> NanoUI () -> NanoUI ()
- NanoUI: mono :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: mono :: Text -> NanoUI ()
- NanoUI: muted :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: muted :: Text -> NanoUI ()
- NanoUI: numericInput :: forall (es :: [Effect]). Ui :> es => Double -> Eff es Double
+ NanoUI: numericInput :: Var Double -> NanoUI ()
- NanoUI: numericInput' :: forall (es :: [Effect]). Ui :> es => Double -> Eff es (Response, Double)
+ NanoUI: numericInput' :: Var Double -> NanoUI Response
- NanoUI: numericInputConfigured :: forall (es :: [Effect]). Ui :> es => NumericInputConfig -> Double -> Eff es Double
+ NanoUI: numericInputConfigured :: NumericInputConfig -> Var Double -> NanoUI ()
- NanoUI: numericInputConfigured' :: forall (es :: [Effect]). Ui :> es => NumericInputConfig -> Double -> Eff es (Response, Double)
+ NanoUI: numericInputConfigured' :: NumericInputConfig -> Var Double -> NanoUI Response
- NanoUI: panel :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: panel :: NanoUI a -> NanoUI a
- NanoUI: panelWith :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: panelWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: parseSvg :: Text -> Either String Svg
+ NanoUI: parseSvg :: ByteString -> Either String Svg
- NanoUI: popup :: forall (es :: [Effect]) a. Ui :> es => Bool -> PopupConfig -> Eff es a -> Eff es (Response, Maybe a)
+ NanoUI: popup :: Var Bool -> PopupConfig -> NanoUI () -> NanoUI ()
- NanoUI: popupWith :: forall (es :: [Effect]) a. Ui :> es => Bool -> PopupConfig -> (Layout -> Layout) -> Eff es a -> Eff es (Response, Maybe a)
+ NanoUI: popupWith :: Var Bool -> PopupConfig -> (Layout -> Layout) -> NanoUI () -> NanoUI ()
- NanoUI: progressBar :: forall (es :: [Effect]). Ui :> es => Float -> Eff es ()
+ NanoUI: progressBar :: Float -> NanoUI ()
- NanoUI: progressBar' :: forall (es :: [Effect]). Ui :> es => Float -> Eff es Response
+ NanoUI: progressBar' :: Float -> NanoUI Response
- NanoUI: progressBarWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es ()
+ NanoUI: progressBarWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()
- NanoUI: progressBarWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es Response
+ NanoUI: progressBarWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response
- NanoUI: pulse :: forall (es :: [Effect]). Ui :> es => Float -> Eff es Float
+ NanoUI: pulse :: Float -> NanoUI Float
- NanoUI: radio :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f Text -> Int -> Eff es Int
+ NanoUI: radio :: Foldable f => f Text -> Var Int -> NanoUI ()
- NanoUI: radio' :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f Text -> Int -> Eff es (Response, Int)
+ NanoUI: radio' :: Foldable f => f Text -> Var Int -> NanoUI Response
- NanoUI: registerImageRgba :: forall (es :: [Effect]). Ui :> es => ImageId -> Int -> Int -> ByteString -> Eff es Bool
+ NanoUI: registerImageRgba :: ImageId -> Int -> Int -> ByteString -> NanoUI Bool
- NanoUI: responsive :: forall (es :: [Effect]) a. Ui :> es => Float -> (Eff es a -> Eff es a) -> (Eff es a -> Eff es a) -> Eff es a -> Eff es a
+ NanoUI: responsive :: Float -> (NanoUI a -> NanoUI a) -> (NanoUI a -> NanoUI a) -> NanoUI a -> NanoUI a
- NanoUI: responsiveRowCol :: forall (es :: [Effect]) a. Ui :> es => Float -> (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: responsiveRowCol :: Float -> (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: row :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: row :: NanoUI a -> NanoUI a
- NanoUI: rowWith :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: rowWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: scope :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: scope :: NanoUI a -> NanoUI a
- NanoUI: scroll :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: scroll :: NanoUI a -> NanoUI a
- NanoUI: scroll2D :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: scroll2D :: NanoUI a -> NanoUI a
- NanoUI: scroll2DWith :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: scroll2DWith :: LayoutModifier -> NanoUI a -> NanoUI a
- NanoUI: scrollBy :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI: scrollBy :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollIntoView :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()
+ NanoUI: scrollIntoView :: WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollPages :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI: scrollPages :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollRectIntoView :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()
+ NanoUI: scrollRectIntoView :: WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollTo :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()
+ NanoUI: scrollTo :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollToEnd :: Context -> WidgetId -> ScrollBehavior -> IO ()
+ NanoUI: scrollToEnd :: WidgetId -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollToStart :: Context -> WidgetId -> ScrollBehavior -> IO ()
+ NanoUI: scrollToStart :: WidgetId -> ScrollBehavior -> NanoUI ()
- NanoUI: scrollWith :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: scrollWith :: LayoutModifier -> NanoUI a -> NanoUI a
- NanoUI: select :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f Text -> Int -> Eff es Int
+ NanoUI: select :: Foldable f => f Text -> Var Int -> NanoUI ()
- NanoUI: select' :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => f Text -> Int -> Eff es (Response, Int)
+ NanoUI: select' :: Foldable f => f Text -> Var Int -> NanoUI Response
- NanoUI: selectWith :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => (Layout -> Layout) -> f Text -> Int -> Eff es Int
+ NanoUI: selectWith :: Foldable f => (Layout -> Layout) -> f Text -> Var Int -> NanoUI ()
- NanoUI: selectWith' :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => (Layout -> Layout) -> f Text -> Int -> Eff es (Response, Int)
+ NanoUI: selectWith' :: Foldable f => (Layout -> Layout) -> f Text -> Var Int -> NanoUI Response
- NanoUI: selectableText :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: selectableText :: Text -> NanoUI ()
- NanoUI: selectableText' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Response
+ NanoUI: selectableText' :: Text -> NanoUI Response
- NanoUI: selectableTextWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es ()
+ NanoUI: selectableTextWith :: (Layout -> Layout) -> Text -> NanoUI ()
- NanoUI: selectableTextWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es Response
+ NanoUI: selectableTextWith' :: (Layout -> Layout) -> Text -> NanoUI Response
- NanoUI: separator :: forall (es :: [Effect]). Ui :> es => Eff es ()
+ NanoUI: separator :: NanoUI ()
- NanoUI: setScrollOffset :: Context -> WidgetId -> Float -> IO ()
+ NanoUI: setScrollOffset :: WidgetId -> V2 -> NanoUI ()
- NanoUI: setScrollStep :: Context -> WidgetId -> Float -> IO ()
+ NanoUI: setScrollStep :: WidgetId -> Float -> NanoUI ()
- NanoUI: setScrollTuning :: Context -> ScrollTuning -> IO ()
+ NanoUI: setScrollTuning :: ScrollTuning -> NanoUI ()
- NanoUI: setTheme :: Context -> Theme -> IO ()
+ NanoUI: setTheme :: Theme -> NanoUI ()
- NanoUI: simpleTable :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => [Text] -> f [Text] -> Eff es TableResponse
+ NanoUI: simpleTable :: Foldable f => [Text] -> f [Text] -> NanoUI TableResponse
- NanoUI: slider :: forall (es :: [Effect]). Ui :> es => Float -> Float -> Float -> Eff es Float
+ NanoUI: slider :: Float -> Float -> Var Float -> NanoUI ()
- NanoUI: slider' :: forall (es :: [Effect]). Ui :> es => Float -> Float -> Float -> Eff es (Response, Float)
+ NanoUI: slider' :: Float -> Float -> Var Float -> NanoUI Response
- NanoUI: sliderWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Eff es Float
+ NanoUI: sliderWith :: (Layout -> Layout) -> Float -> Float -> Var Float -> NanoUI ()
- NanoUI: sliderWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Eff es (Response, Float)
+ NanoUI: sliderWith' :: (Layout -> Layout) -> Float -> Float -> Var Float -> NanoUI Response
- NanoUI: sortRows :: Foldable f => Colonnade Headed row Text -> SortCol -> f row -> [row]
+ NanoUI: sortRows :: (Foldable f, ToCell c) => Colonnade Headed row c -> SortCol -> f row -> [row]
- NanoUI: spacer :: forall (es :: [Effect]). Ui :> es => Sizing -> Sizing -> Eff es ()
+ NanoUI: spacer :: Sizing -> Sizing -> NanoUI ()
- NanoUI: sparkline :: forall (es :: [Effect]). Ui :> es => [Float] -> Eff es ()
+ NanoUI: sparkline :: [Float] -> NanoUI ()
- NanoUI: sparkline' :: forall (es :: [Effect]). Ui :> es => [Float] -> Eff es Response
+ NanoUI: sparkline' :: [Float] -> NanoUI Response
- NanoUI: sparklineWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> [Float] -> Eff es ()
+ NanoUI: sparklineWith :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI ()
- NanoUI: sparklineWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> [Float] -> Eff es Response
+ NanoUI: sparklineWith' :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI Response
- NanoUI: spinner :: forall (es :: [Effect]). Ui :> es => Eff es ()
+ NanoUI: spinner :: NanoUI ()
- NanoUI: spinner' :: forall (es :: [Effect]). Ui :> es => Eff es Response
+ NanoUI: spinner' :: NanoUI Response
- NanoUI: spinnerWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Eff es ()
+ NanoUI: spinnerWith :: (Layout -> Layout) -> Float -> NanoUI ()
- NanoUI: spinnerWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Eff es Response
+ NanoUI: spinnerWith' :: (Layout -> Layout) -> Float -> NanoUI Response
- NanoUI: styled :: forall (es :: [Effect]) a. Ui :> es => (Theme -> Theme) -> Eff es a -> Eff es a
+ NanoUI: styled :: (Theme -> Theme) -> NanoUI a -> NanoUI a
- NanoUI: svgIcon :: forall (es :: [Effect]). Ui :> es => Float -> Svg -> Eff es ()
+ NanoUI: svgIcon :: Float -> Svg -> NanoUI ()
- NanoUI: svgIconWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Svg -> Eff es ()
+ NanoUI: svgIconWith :: (Layout -> Layout) -> Svg -> NanoUI ()
- NanoUI: svgIconWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Svg -> Eff es Response
+ NanoUI: svgIconWith' :: (Layout -> Layout) -> Svg -> NanoUI Response
- NanoUI: tabBar :: forall f a (es :: [Effect]) body. (Foldable f, Eq a, Ui :> es) => a -> f (Tab a body) -> Eff es a
+ NanoUI: tabBar :: (Foldable f, Hashable a) => Var a -> f (Tab a body) -> NanoUI ()
- NanoUI: tabBar' :: forall f a (es :: [Effect]) body. (Foldable f, Eq a, Ui :> es) => a -> f (Tab a body) -> Eff es (TabResponse a)
+ NanoUI: tabBar' :: (Foldable f, Hashable a) => Var a -> f (Tab a body) -> NanoUI (TabResponse a)
- NanoUI: tabBarConfigured :: forall f a (es :: [Effect]) body. (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a body) -> Eff es a
+ NanoUI: tabBarConfigured :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a body) -> NanoUI ()
- NanoUI: tabBarConfigured' :: forall f a (es :: [Effect]) body. (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a body) -> Eff es (TabResponse a)
+ NanoUI: tabBarConfigured' :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a body) -> NanoUI (TabResponse a)
- NanoUI: table :: forall f (es :: [Effect]) row. (Foldable f, Ui :> es) => Text -> Colonnade Headed row Text -> f row -> SortCol -> Eff es TableResponse
+ NanoUI: table :: (Foldable f, ToCell c) => Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI ()
- NanoUI: tableConfigured :: forall f (es :: [Effect]) row. (Foldable f, Ui :> es) => TableConfig -> (Layout -> Layout) -> Text -> Colonnade Headed row Text -> f row -> SortCol -> Eff es TableResponse
+ NanoUI: tableConfigured :: (Foldable f, ToCell c) => TableConfig -> (Layout -> Layout) -> Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI ()
- NanoUI: tableWith :: forall f (es :: [Effect]) row. (Foldable f, Ui :> es) => (Layout -> Layout) -> Text -> Colonnade Headed row Text -> f row -> SortCol -> Eff es TableResponse
+ NanoUI: tableWith :: (Foldable f, ToCell c) => (Layout -> Layout) -> Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI ()
- NanoUI: tabs :: forall f a (es :: [Effect]). (Foldable f, Eq a, Ui :> es) => a -> f (Tab a (Eff es ())) -> Eff es a
+ NanoUI: tabs :: (Foldable f, Hashable a) => Var a -> f (Tab a (NanoUI ())) -> NanoUI ()
- NanoUI: tabs' :: forall f a (es :: [Effect]). (Foldable f, Eq a, Ui :> es) => a -> f (Tab a (Eff es ())) -> Eff es (TabResponse a)
+ NanoUI: tabs' :: (Foldable f, Hashable a) => Var a -> f (Tab a (NanoUI ())) -> NanoUI (TabResponse a)
- NanoUI: tabsConfigured :: forall f a (es :: [Effect]). (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a (Eff es ())) -> Eff es a
+ NanoUI: tabsConfigured :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a (NanoUI ())) -> NanoUI ()
- NanoUI: tabsConfigured' :: forall f a (es :: [Effect]). (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a (Eff es ())) -> Eff es (TabResponse a)
+ NanoUI: tabsConfigured' :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a (NanoUI ())) -> NanoUI (TabResponse a)
- NanoUI: textArea :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Text
+ NanoUI: textArea :: Var Text -> NanoUI ()
- NanoUI: textArea' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es (Response, Text)
+ NanoUI: textArea' :: Var Text -> NanoUI Response
- NanoUI: textAreaWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es Text
+ NanoUI: textAreaWith :: (Layout -> Layout) -> Var Text -> NanoUI ()
- NanoUI: textAreaWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es (Response, Text)
+ NanoUI: textAreaWith' :: (Layout -> Layout) -> Var Text -> NanoUI Response
- NanoUI: textInput :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Text
+ NanoUI: textInput :: Var Text -> NanoUI ()
- NanoUI: textInput' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es (Response, Text)
+ NanoUI: textInput' :: Var Text -> NanoUI Response
- NanoUI: textInputConfigured :: forall (es :: [Effect]). Ui :> es => TextInputConfig -> Text -> Eff es Text
+ NanoUI: textInputConfigured :: TextInputConfig -> Var Text -> NanoUI ()
- NanoUI: textInputConfigured' :: forall (es :: [Effect]). Ui :> es => TextInputConfig -> Text -> Eff es (Response, Text)
+ NanoUI: textInputConfigured' :: TextInputConfig -> Var Text -> NanoUI Response
- NanoUI: themed :: forall (es :: [Effect]) a. Ui :> es => Theme -> Eff es a -> Eff es a
+ NanoUI: themed :: Theme -> NanoUI a -> NanoUI a
- NanoUI: toggleSwitch :: forall (es :: [Effect]). Ui :> es => Bool -> Eff es Bool
+ NanoUI: toggleSwitch :: Var Bool -> NanoUI ()
- NanoUI: toggleSwitch' :: forall (es :: [Effect]). Ui :> es => Bool -> Eff es (Response, Bool)
+ NanoUI: toggleSwitch' :: Var Bool -> NanoUI Response
- NanoUI: toggleSwitchWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Bool -> Eff es Bool
+ NanoUI: toggleSwitchWith :: (Layout -> Layout) -> Var Bool -> NanoUI ()
- NanoUI: toggleSwitchWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Bool -> Eff es (Response, Bool)
+ NanoUI: toggleSwitchWith' :: (Layout -> Layout) -> Var Bool -> NanoUI Response
- NanoUI: toolbar :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI: toolbar :: NanoUI a -> NanoUI a
- NanoUI: tooltip :: forall (es :: [Effect]) r. (Ui :> es, HasResponse r) => r -> Text -> Eff es ()
+ NanoUI: tooltip :: HasResponse r => r -> Text -> NanoUI ()
- NanoUI: tooltipAt :: forall (es :: [Effect]) r. (Ui :> es, HasResponse r) => PopupPlacement -> r -> Text -> Eff es ()
+ NanoUI: tooltipAt :: HasResponse r => PopupPlacement -> r -> Text -> NanoUI ()
- NanoUI: tooltipWidget :: forall (es :: [Effect]) r a. (Ui :> es, HasResponse r) => r -> Eff es a -> Eff es (Maybe a)
+ NanoUI: tooltipWidget :: HasResponse r => r -> NanoUI () -> NanoUI ()
- NanoUI: tree :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => Text -> f TreeItem -> Int -> Eff es Int
+ NanoUI: tree :: Foldable f => Text -> f TreeItem -> Var Int -> NanoUI ()
- NanoUI: tree' :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => Text -> f TreeItem -> Int -> Eff es (Response, Int)
+ NanoUI: tree' :: Foldable f => Text -> f TreeItem -> Var Int -> NanoUI Response
- NanoUI: uiFontMetrics :: forall (es :: [Effect]). Ui :> es => Eff es FontMetrics
+ NanoUI: uiFontMetrics :: NanoUI FontMetrics
- NanoUI: uiMousePos :: forall (es :: [Effect]). Ui :> es => Eff es V2
+ NanoUI: uiMousePos :: NanoUI V2
- NanoUI: uiTheme :: forall (es :: [Effect]). Ui :> es => Eff es Theme
+ NanoUI: uiTheme :: NanoUI Theme
- NanoUI: underline :: forall (es :: [Effect]). Ui :> es => Text -> Eff es ()
+ NanoUI: underline :: Text -> NanoUI ()
- NanoUI: useDrop :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es DropTarget
+ NanoUI: useDrop :: Rect -> NanoUI DropTarget
- NanoUI: windowHeight :: forall (es :: [Effect]). Ui :> es => Eff es Float
+ NanoUI: windowHeight :: NanoUI Float
- NanoUI: windowSize :: forall (es :: [Effect]). Ui :> es => Eff es Size
+ NanoUI: windowSize :: NanoUI Size
- NanoUI: windowWidth :: forall (es :: [Effect]). Ui :> es => Eff es Float
+ NanoUI: windowWidth :: NanoUI Float
- NanoUI: withDefaultLayout :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI: withDefaultLayout :: (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI: withKey :: forall k (es :: [Effect]) a. (Hashable k, Ui :> es) => k -> Eff es a -> Eff es a
+ NanoUI: withKey :: Hashable k => k -> NanoUI a -> NanoUI a
- NanoUI: withTooltip :: forall (es :: [Effect]) a b. Ui :> es => Eff es a -> Eff es b -> Eff es (a, Maybe b)
+ NanoUI: withTooltip :: NanoUI a -> NanoUI () -> NanoUI a
- NanoUI.Input: Input :: V2 -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> V2 -> SmallArray Key -> Text -> Modifiers -> Size -> Float -> SmallArray DropEvent -> Bool -> Input
+ NanoUI.Input: Input :: V2 -> MouseButtons -> MouseButtons -> MouseButtons -> Int -> V2 -> SmallArray Key -> SmallArray Key -> SmallArray Key -> SmallArray Key -> Text -> Modifiers -> Size -> Float -> SmallArray DropEvent -> Bool -> Maybe Composition -> Input
- NanoUI.Input: Modifiers :: Bool -> Bool -> Bool -> Modifiers
+ NanoUI.Input: Modifiers :: Bool -> Bool -> Bool -> Bool -> Modifiers
- NanoUI.Monad: askContext :: forall (es :: [Effect]). Ui :> es => Eff es Context
+ NanoUI.Monad: askContext :: NanoUI Context
- NanoUI.Monad: askDefaultLayout :: forall (es :: [Effect]). Ui :> es => Eff es Layout
+ NanoUI.Monad: askDefaultLayout :: NanoUI Layout
- NanoUI.Monad: askHost :: forall a (es :: [Effect]). (Typeable a, Ui :> es) => Eff es (Maybe a)
+ NanoUI.Monad: askHost :: Host a -> NanoUI (Maybe a)
- NanoUI.Monad: askInput :: forall (es :: [Effect]). Ui :> es => Eff es Input
+ NanoUI.Monad: askInput :: NanoUI Input
- NanoUI.Monad: currentId :: forall (es :: [Effect]). Ui :> es => Eff es WidgetId
+ NanoUI.Monad: currentId :: NanoUI WidgetId
- NanoUI.Monad: damageFullNow :: forall (es :: [Effect]). Ui :> es => Eff es ()
+ NanoUI.Monad: damageFullNow :: NanoUI ()
- NanoUI.Monad: damageGroupNow :: forall (es :: [Effect]). Ui :> es => [WidgetId] -> DamageBounds -> Eff es ()
+ NanoUI.Monad: damageGroupNow :: [WidgetId] -> DamageBounds -> NanoUI ()
- NanoUI.Monad: damageKeyNow :: forall (es :: [Effect]). Ui :> es => Int -> DamageBounds -> Eff es ()
+ NanoUI.Monad: damageKeyNow :: Int -> DamageBounds -> NanoUI ()
- NanoUI.Monad: damageRectNow :: forall (es :: [Effect]). Ui :> es => Rect -> Eff es ()
+ NanoUI.Monad: damageRectNow :: Rect -> NanoUI ()
- NanoUI.Monad: damageWidgetNow :: forall (es :: [Effect]). Ui :> es => WidgetId -> DamageBounds -> Eff es ()
+ NanoUI.Monad: damageWidgetNow :: WidgetId -> DamageBounds -> NanoUI ()
- NanoUI.Monad: disabledWhen :: forall (es :: [Effect]) a. Ui :> es => Bool -> Eff es a -> Eff es a
+ NanoUI.Monad: disabledWhen :: Bool -> NanoUI a -> NanoUI a
- NanoUI.Monad: keyedTag :: forall (es :: [Effect]) a. Ui :> es => Word64 -> Eff es a -> Eff es a
+ NanoUI.Monad: keyedTag :: Word64 -> NanoUI a -> NanoUI a
- NanoUI.Monad: nextId :: forall (es :: [Effect]). Ui :> es => Eff es WidgetId
+ NanoUI.Monad: nextId :: NanoUI WidgetId
- NanoUI.Monad: scope :: forall (es :: [Effect]) a. Ui :> es => Eff es a -> Eff es a
+ NanoUI.Monad: scope :: NanoUI a -> NanoUI a
- NanoUI.Monad: styled :: forall (es :: [Effect]) a. Ui :> es => (Theme -> Theme) -> Eff es a -> Eff es a
+ NanoUI.Monad: styled :: (Theme -> Theme) -> NanoUI a -> NanoUI a
- NanoUI.Monad: themed :: forall (es :: [Effect]) a. Ui :> es => Theme -> Eff es a -> Eff es a
+ NanoUI.Monad: themed :: Theme -> NanoUI a -> NanoUI a
- NanoUI.Monad: uiFontMetrics :: forall (es :: [Effect]). Ui :> es => Eff es FontMetrics
+ NanoUI.Monad: uiFontMetrics :: NanoUI FontMetrics
- NanoUI.Monad: uiMousePos :: forall (es :: [Effect]). Ui :> es => Eff es V2
+ NanoUI.Monad: uiMousePos :: NanoUI V2
- NanoUI.Monad: uiTheme :: forall (es :: [Effect]). Ui :> es => Eff es Theme
+ NanoUI.Monad: uiTheme :: NanoUI Theme
- NanoUI.Monad: uiTime :: forall (es :: [Effect]). Ui :> es => Eff es Double
+ NanoUI.Monad: uiTime :: NanoUI Double
- NanoUI.Monad: windowHeight :: forall (es :: [Effect]). Ui :> es => Eff es Float
+ NanoUI.Monad: windowHeight :: NanoUI Float
- NanoUI.Monad: windowSize :: forall (es :: [Effect]). Ui :> es => Eff es Size
+ NanoUI.Monad: windowSize :: NanoUI Size
- NanoUI.Monad: windowWidth :: forall (es :: [Effect]). Ui :> es => Eff es Float
+ NanoUI.Monad: windowWidth :: NanoUI Float
- NanoUI.Monad: withDefaultLayout :: forall (es :: [Effect]) a. Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a
+ NanoUI.Monad: withDefaultLayout :: (Layout -> Layout) -> NanoUI a -> NanoUI a
- NanoUI.Monad: withKey :: forall k (es :: [Effect]) a. (Hashable k, Ui :> es) => k -> Eff es a -> Eff es a
+ NanoUI.Monad: withKey :: Hashable k => k -> NanoUI a -> NanoUI a
- NanoUI.Runner: SessionDriver :: IO [ev] -> (Int -> IO [ev]) -> (Input -> ev -> Input) -> (ev -> Bool) -> (ev -> Bool) -> (ev -> Bool) -> (Context -> Input -> IO (Context, Input)) -> DebugSamplerRef -> Bool -> Int -> IO Bool -> Double -> (Context -> Input -> Input -> Bool -> Bool -> IO Bool) -> (Context -> Input -> Bool -> IO (Bool, Input)) -> (Context -> Input -> IO ()) -> (Input -> Bool) -> SessionDriver ev
+ NanoUI.Runner: SessionDriver :: IO [ev] -> (Int -> IO [ev]) -> Maybe (Int -> IO [ev]) -> (Input -> ev -> Input) -> (ev -> Bool) -> (ev -> Bool) -> (Context -> Input -> IO (Context, Input)) -> DebugSamplerRef -> Bool -> Bool -> Int -> IO Bool -> Double -> (Context -> Input -> Input -> Bool -> Bool -> IO Bool) -> (Context -> Input -> Bool -> IO Bool) -> (Context -> Input -> IO ()) -> (Input -> Bool) -> Maybe LoopWindows -> SessionDriver ev
- NanoUI.Runner: [sdDraw] :: SessionDriver ev -> Context -> Input -> Bool -> IO (Bool, Input)
+ NanoUI.Runner: [sdDraw] :: SessionDriver ev -> Context -> Input -> Bool -> IO Bool
- NanoUI.Svg: parseSvg :: Text -> Either String Svg
+ NanoUI.Svg: parseSvg :: ByteString -> Either String Svg
- NanoUI.Testing: DrawCmd :: Float -> Float -> Float -> Float -> Int -> Word32 -> Word32 -> Layer -> DrawCmd
+ NanoUI.Testing: DrawCmd :: Float -> Float -> Float -> Float -> Int -> Word32 -> Word32 -> Layer -> Int32 -> DrawCmd
- NanoUI.Testing: DrawData :: ForeignPtr Word8 -> Int -> ForeignPtr Word8 -> Int -> PrimArray DrawCmd -> PrimArray LayerSlice -> DrawData
+ NanoUI.Testing: DrawData :: ForeignPtr Word8 -> Int -> ForeignPtr Word8 -> Int -> Vector DrawCmd -> PrimArray Int -> Color -> SmallArray ShaderCall -> ByteArray -> SmallArray EffectSpan -> DrawData
- NanoUI.Testing: [drawCommands] :: DrawData -> PrimArray DrawCmd
+ NanoUI.Testing: [drawCommands] :: DrawData -> Vector DrawCmd
- NanoUI.Testing: askContext :: forall (es :: [Effect]). Ui :> es => Eff es Context
+ NanoUI.Testing: askContext :: NanoUI Context
- NanoUI.Testing: askHost :: forall a (es :: [Effect]). (Typeable a, Ui :> es) => Eff es (Maybe a)
+ NanoUI.Testing: askHost :: Host a -> NanoUI (Maybe a)
- NanoUI.Testing: askInput :: forall (es :: [Effect]). Ui :> es => Eff es Input
+ NanoUI.Testing: askInput :: NanoUI Input
- NanoUI.Testing: runFrame :: Context -> Input -> NanoUI a -> IO (a, [FrameMsg], DrawData, Bool)
+ NanoUI.Testing: runFrame :: Context -> Input -> NanoUI a -> IO (a, DrawData, Bool)
- NanoUI.Testing: setHost :: Typeable a => Context -> a -> IO ()
+ NanoUI.Testing: setHost :: Host a -> a -> IO ()
- NanoUI.Testing: textNodeFontStyle :: Int -> FontStyle
+ NanoUI.Testing: textNodeFontStyle :: Word64 -> FontStyle
- NanoUI.Testing: textNodeFontWeight :: Int -> FontWeight
+ NanoUI.Testing: textNodeFontWeight :: Word64 -> FontWeight
- NanoUI.Testing: textNodeTextDecoration :: Int -> TextDecoration
+ NanoUI.Testing: textNodeTextDecoration :: Word64 -> TextDecoration
- NanoUI.Testing.Assert: run2Frames :: Context -> Input -> NanoUI a -> IO (a, [FrameMsg], DrawData, Bool)
+ NanoUI.Testing.Assert: run2Frames :: Context -> Input -> NanoUI a -> IO (a, DrawData, Bool)
- NanoUI.Testing.Harness: held :: forall (es :: [Effect]) a r. Ui :> es => IORef a -> (a -> Eff es (r, a)) -> Eff es (r, a)
+ NanoUI.Testing.Harness: held :: Var a -> (Var a -> NanoUI r) -> NanoUI (r, a)
- NanoUI.Widgets.Combo: ComboInput :: Bool -> Bool -> Text -> [Text] -> Float -> Rect -> FontMetrics -> V2 -> Bool -> Bool -> V2 -> Bool -> Bool -> Bool -> Bool -> ComboInput
+ NanoUI.Widgets.Combo: ComboInput :: Bool -> Bool -> Text -> [Text] -> Float -> Rect -> Input -> ComboInput
- NanoUI.Widgets.Combo: ComboState :: Int -> Int -> Float -> Float -> Int -> Float -> Text -> Text -> Bool -> ComboState
+ NanoUI.Widgets.Combo: ComboState :: Int -> Int -> Float -> Float -> Int -> Float -> Float -> Text -> Text -> Bool -> Maybe V2 -> ComboState
- NanoUI.Widgets.Combo: comboBox :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => Text -> f Text -> Text -> Eff es Text
+ NanoUI.Widgets.Combo: comboBox :: Foldable f => Text -> f Text -> Var Text -> NanoUI ()
- NanoUI.Widgets.Combo: comboBox' :: forall f (es :: [Effect]). (Foldable f, Ui :> es) => Text -> f Text -> Text -> Eff es (Response, Text)
+ NanoUI.Widgets.Combo: comboBox' :: Foldable f => Text -> f Text -> Var Text -> NanoUI Response
- NanoUI.Widgets.Custom: CustomWidgetSpec :: Layout -> Maybe CustomMeasureFn -> CustomDrawBuild -> Int -> Maybe (CustomDrawContext -> UiCursorKind) -> Bool -> Float -> (Response -> CustomDrawContext -> Input -> (Response, a)) -> CustomWidgetSpec a
+ NanoUI.Widgets.Custom: CustomWidgetSpec :: LayoutModifier -> Maybe CustomMeasureFn -> CustomDrawBuild -> Int -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind) -> Bool -> KeyClaim -> Float -> Bool -> (Response -> CustomDrawContext -> Input -> (Response, a)) -> CustomWidgetSpec a
- NanoUI.Widgets.Custom: [widgetCursor] :: CustomWidgetSpec a -> Maybe (CustomDrawContext -> UiCursorKind)
+ NanoUI.Widgets.Custom: [widgetCursor] :: CustomWidgetSpec a -> Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind)
- NanoUI.Widgets.Custom: [widgetLayout] :: CustomWidgetSpec a -> Layout
+ NanoUI.Widgets.Custom: [widgetLayout] :: CustomWidgetSpec a -> LayoutModifier
- NanoUI.Widgets.Custom: canvas :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> (Rect -> CanvasM ()) -> Eff es Response
+ NanoUI.Widgets.Custom: canvas :: LayoutModifier -> (Rect -> CanvasM ()) -> NanoUI Response
- NanoUI.Widgets.Custom: circularProgress :: forall (es :: [Effect]). Ui :> es => Float -> Eff es ()
+ NanoUI.Widgets.Custom: circularProgress :: Float -> NanoUI ()
- NanoUI.Widgets.Custom: circularProgress' :: forall (es :: [Effect]). Ui :> es => Float -> Eff es Response
+ NanoUI.Widgets.Custom: circularProgress' :: Float -> NanoUI Response
- NanoUI.Widgets.Custom: circularProgressWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es ()
+ NanoUI.Widgets.Custom: circularProgressWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()
- NanoUI.Widgets.Custom: circularProgressWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es Response
+ NanoUI.Widgets.Custom: circularProgressWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response
- NanoUI.Widgets.Custom: customWidget :: forall (es :: [Effect]) a. Ui :> es => CustomWidgetSpec a -> Eff es (Response, a)
+ NanoUI.Widgets.Custom: customWidget :: CustomWidgetSpec a -> NanoUI (Response, a)
- NanoUI.Widgets.Custom: customWidgetWithId :: forall (es :: [Effect]) a. Ui :> es => WidgetId -> CustomWidgetSpec a -> Eff es (Response, a)
+ NanoUI.Widgets.Custom: customWidgetWithId :: WidgetId -> CustomWidgetSpec a -> NanoUI (Response, a)
- NanoUI.Widgets.Custom: knob :: forall (es :: [Effect]). Ui :> es => Float -> Float -> Float -> Eff es Float
+ NanoUI.Widgets.Custom: knob :: Float -> Float -> Var Float -> NanoUI ()
- NanoUI.Widgets.Custom: knob' :: forall (es :: [Effect]). Ui :> es => Float -> Float -> Float -> Eff es (Response, Float)
+ NanoUI.Widgets.Custom: knob' :: Float -> Float -> Var Float -> NanoUI Response
- NanoUI.Widgets.Custom: knobWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Float -> Eff es Float
+ NanoUI.Widgets.Custom: knobWith :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI ()
- NanoUI.Widgets.Custom: knobWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Float -> Eff es (Response, Float)
+ NanoUI.Widgets.Custom: knobWith' :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI Response
- NanoUI.Widgets.Custom: progressBar :: forall (es :: [Effect]). Ui :> es => Float -> Eff es ()
+ NanoUI.Widgets.Custom: progressBar :: Float -> NanoUI ()
- NanoUI.Widgets.Custom: progressBar' :: forall (es :: [Effect]). Ui :> es => Float -> Eff es Response
+ NanoUI.Widgets.Custom: progressBar' :: Float -> NanoUI Response
- NanoUI.Widgets.Custom: progressBarWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es ()
+ NanoUI.Widgets.Custom: progressBarWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()
- NanoUI.Widgets.Custom: progressBarWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es Response
+ NanoUI.Widgets.Custom: progressBarWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response
- NanoUI.Widgets.Custom: sparkline :: forall (es :: [Effect]). Ui :> es => [Float] -> Eff es ()
+ NanoUI.Widgets.Custom: sparkline :: [Float] -> NanoUI ()
- NanoUI.Widgets.Custom: sparkline' :: forall (es :: [Effect]). Ui :> es => [Float] -> Eff es Response
+ NanoUI.Widgets.Custom: sparkline' :: [Float] -> NanoUI Response
- NanoUI.Widgets.Custom: sparklineWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> [Float] -> Eff es ()
+ NanoUI.Widgets.Custom: sparklineWith :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI ()
- NanoUI.Widgets.Custom: sparklineWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Float -> [Float] -> Eff es Response
+ NanoUI.Widgets.Custom: sparklineWith' :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI Response
- NanoUI.Widgets.Custom: spinner :: forall (es :: [Effect]). Ui :> es => Eff es ()
+ NanoUI.Widgets.Custom: spinner :: NanoUI ()
- NanoUI.Widgets.Custom: spinner' :: forall (es :: [Effect]). Ui :> es => Eff es Response
+ NanoUI.Widgets.Custom: spinner' :: NanoUI Response
- NanoUI.Widgets.Custom: spinnerWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Eff es ()
+ NanoUI.Widgets.Custom: spinnerWith :: (Layout -> Layout) -> Float -> NanoUI ()
- NanoUI.Widgets.Custom: spinnerWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Float -> Eff es Response
+ NanoUI.Widgets.Custom: spinnerWith' :: (Layout -> Layout) -> Float -> NanoUI Response
- NanoUI.Widgets.Custom: toggleSwitch :: forall (es :: [Effect]). Ui :> es => Bool -> Eff es Bool
+ NanoUI.Widgets.Custom: toggleSwitch :: Var Bool -> NanoUI ()
- NanoUI.Widgets.Custom: toggleSwitch' :: forall (es :: [Effect]). Ui :> es => Bool -> Eff es (Response, Bool)
+ NanoUI.Widgets.Custom: toggleSwitch' :: Var Bool -> NanoUI Response
- NanoUI.Widgets.Custom: toggleSwitchWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Bool -> Eff es Bool
+ NanoUI.Widgets.Custom: toggleSwitchWith :: (Layout -> Layout) -> Var Bool -> NanoUI ()
- NanoUI.Widgets.Custom: toggleSwitchWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Bool -> Eff es (Response, Bool)
+ NanoUI.Widgets.Custom: toggleSwitchWith' :: (Layout -> Layout) -> Var Bool -> NanoUI Response
- NanoUI.Widgets.PaneGrid: PaneGridConfig :: (Layout -> Layout) -> Float -> Float -> Float -> Float -> (Word64 -> PaneGridCtx es -> Eff es PaneView) -> PaneGridConfig (es :: [Effect])
+ NanoUI.Widgets.PaneGrid: PaneGridConfig :: (Layout -> Layout) -> Float -> Float -> Float -> Float -> Bool -> (Word64 -> Bool) -> PaneTree -> Maybe Color -> Bool -> CenterDropMode -> (Word64 -> Text) -> Maybe (Word64 -> Bool -> NanoUI ()) -> Bool -> (Word64 -> PaneGridCtx -> NanoUI PaneView) -> PaneGridConfig
- NanoUI.Widgets.PaneGrid: PaneGridResponse :: Bool -> Int -> [Word64] -> Word64 -> Word64 -> PaneGridResponse
+ NanoUI.Widgets.PaneGrid: PaneGridResponse :: Bool -> Bool -> Maybe GridNode -> Int -> [Word64] -> Word64 -> Word64 -> Maybe PaneGridDrop -> PaneGridResponse
- NanoUI.Widgets.PaneGrid: PaneView :: Text -> Bool -> Maybe Rect -> PaneView
+ NanoUI.Widgets.PaneGrid: PaneView :: Text -> Bool -> PaneView
- NanoUI.Widgets.PaneGrid: [pgEdgeBand] :: PaneGridConfig (es :: [Effect]) -> Float
+ NanoUI.Widgets.PaneGrid: [pgEdgeBand] :: PaneGridConfig -> Float
- NanoUI.Widgets.PaneGrid: [pgLayout] :: PaneGridConfig (es :: [Effect]) -> Layout -> Layout
+ NanoUI.Widgets.PaneGrid: [pgLayout] :: PaneGridConfig -> Layout -> Layout
- NanoUI.Widgets.PaneGrid: [pgLeeway] :: PaneGridConfig (es :: [Effect]) -> Float
+ NanoUI.Widgets.PaneGrid: [pgLeeway] :: PaneGridConfig -> Float
- NanoUI.Widgets.PaneGrid: [pgMinSize] :: PaneGridConfig (es :: [Effect]) -> Float
+ NanoUI.Widgets.PaneGrid: [pgMinSize] :: PaneGridConfig -> Float
- NanoUI.Widgets.PaneGrid: [pgSpacing] :: PaneGridConfig (es :: [Effect]) -> Float
+ NanoUI.Widgets.PaneGrid: [pgSpacing] :: PaneGridConfig -> Float
- NanoUI.Widgets.PaneGrid: [pgViewPane] :: PaneGridConfig (es :: [Effect]) -> Word64 -> PaneGridCtx es -> Eff es PaneView
+ NanoUI.Widgets.PaneGrid: [pgViewPane] :: PaneGridConfig -> Word64 -> PaneGridCtx -> NanoUI PaneView
- NanoUI.Widgets.PaneGrid: data PaneGridConfig (es :: [Effect])
+ NanoUI.Widgets.PaneGrid: data PaneGridConfig
- NanoUI.Widgets.PaneGrid: data PaneGridCtx (es :: [Effect])
+ NanoUI.Widgets.PaneGrid: data PaneGridCtx
- NanoUI.Widgets.PaneGrid: defaultPaneGridConfig :: forall (es :: [Effect]). PaneGridConfig es
+ NanoUI.Widgets.PaneGrid: defaultPaneGridConfig :: PaneGridConfig
- NanoUI.Widgets.PaneGrid: paneGrid :: forall (es :: [Effect]). Ui :> es => PaneGridConfig es -> Eff es PaneGridResponse
+ NanoUI.Widgets.PaneGrid: paneGrid :: PaneGridConfig -> NanoUI PaneGridResponse
- NanoUI.Widgets.RichText: richText :: forall (es :: [Effect]). Ui :> es => [Inline] -> Eff es (Maybe Text)
+ NanoUI.Widgets.RichText: richText :: [Inline] -> NanoUI (Maybe Text)
- NanoUI.Widgets.RichText: richText' :: forall (es :: [Effect]). Ui :> es => [Inline] -> Eff es (Response, Maybe Text)
+ NanoUI.Widgets.RichText: richText' :: [Inline] -> NanoUI (Response, Maybe Text)
- NanoUI.Widgets.RichText: richTextWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [Inline] -> Eff es (Maybe Text)
+ NanoUI.Widgets.RichText: richTextWith :: (Layout -> Layout) -> [Inline] -> NanoUI (Maybe Text)
- NanoUI.Widgets.RichText: richTextWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> [Inline] -> Eff es (Response, Maybe Text)
+ NanoUI.Widgets.RichText: richTextWith' :: (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)
- NanoUI.Widgets.TextArea: textArea :: forall (es :: [Effect]). Ui :> es => Text -> Eff es Text
+ NanoUI.Widgets.TextArea: textArea :: Var Text -> NanoUI ()
- NanoUI.Widgets.TextArea: textArea' :: forall (es :: [Effect]). Ui :> es => Text -> Eff es (Response, Text)
+ NanoUI.Widgets.TextArea: textArea' :: Var Text -> NanoUI Response
- NanoUI.Widgets.TextArea: textAreaWith :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es Text
+ NanoUI.Widgets.TextArea: textAreaWith :: (Layout -> Layout) -> Var Text -> NanoUI ()
- NanoUI.Widgets.TextArea: textAreaWith' :: forall (es :: [Effect]). Ui :> es => (Layout -> Layout) -> Text -> Eff es (Response, Text)
+ NanoUI.Widgets.TextArea: textAreaWith' :: (Layout -> Layout) -> Var Text -> NanoUI Response
- NanoUI.Widgets.TextField: runTextCommand :: forall (es :: [Effect]). Ui :> es => WidgetId -> TextCommand -> Eff es ()
+ NanoUI.Widgets.TextField: runTextCommand :: WidgetId -> TextCommand -> NanoUI ()
- NanoUI.Widgets.TextField: textCanRedo :: forall (es :: [Effect]). Ui :> es => WidgetId -> Eff es Bool
+ NanoUI.Widgets.TextField: textCanRedo :: WidgetId -> NanoUI Bool
- NanoUI.Widgets.TextField: textCanUndo :: forall (es :: [Effect]). Ui :> es => WidgetId -> Eff es Bool
+ NanoUI.Widgets.TextField: textCanUndo :: WidgetId -> NanoUI Bool

Files

CHANGELOG.md view
@@ -1,5 +1,375 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++See the [0.1 to 0.2 migration guide](https://goolord.github.io/nano-ui/book/getting-started/migrating-0.2.html)+for a complete table of renamed and moved symbols.++### Breaking changes++- **Concrete `NanoUI` monad:** `NanoUI a` (a newtype over `Eff '[Ui, IOE]`)+  replaces `Ui :> es => Eff es a` across every widget, hook, and view helper.+  `liftIO` replaces `uiIO`. Programs that compose views with other `effectful`+  effects use `NanoUI.Effectful` (`NanoUIEs`, `Ui`, `runUi`, `embedNanoUI`,+  `withRunInNanoUI`).+- **`Var`-based state and inputs:** `Var a` (`newVar`, `useVar`,+  `useEnumVar`, `readVar`, `writeVar`, `modifyVar`, `peekVar`, `withValue`,+  `constVar`, `VarMap`, `forEachVar`, `withElemVars`, `zoomVar`, and+  `OverloadedRecordDot` field access) replaces `StateCell`, `useState`,+  `useInt`, `useFloat`, `useFlag`, `useText`, `useEnum`, `useToggle`,+  `useTableSort`, and `useContextMenu`. Controls and overlays (`textInput`,+  `slider`, `checkbox`, `select`, `tabs`, `modal`, `floatingWindow`, `popup`)+  take a `Var` directly and write user edits back to it; primed variants+  (`textInput'`, `modal'`, `floatingWindow'`, `popup'`, `table'`,+  `scrollWith'`, ...) return `Response` (or `(Response, Maybe a)`).+- **Typed emission moved to `nano-ui-emit`:** `NanoUI.Emit`, reducer runners+  (`reduceMessages`, `reduceUpdates`, `runFrameE`), and reducer test helpers+  moved into `nano-ui-emit` on `NanoUIE msg a` without `Typeable`. Core+  `runFrame` and `run2Frames` now return `(result, drawData, dirty)`.+- **Typed hook ownership:** `newTask`, `newStream`, `newImageHandle`,+  `newDrag`, and `newHost` allocate explicit typed owners passed first to+  `useTask`, `useStream`, `useImageRgba`, `useDrag*`, and host accessors.+- **Module boundaries:** Backend and specialized APIs moved out of top-level+  `NanoUI`. Import `NanoUI.Backend` (context, frame runner, font backend,+  damage, `colorToWord32`, `setThemeIO`, `withTheme`, `Layout (..)`),+  `NanoUI.Themes`, `NanoUI.Chrome`, `NanoUI.Widgets.PaneGrid`,+  `NanoUI.Widgets.Custom`, `NanoUI.Widgets.TextDocument`, and+  `NanoUI.Shader.Raw` directly. Internal modules moved under+  `NanoUI.Internal.*`.+- **Opaque `Layout` and `LayoutModifier` configs:** `Layout` constructors and+  fields moved out of `NanoUI`; shape layouts with modifiers (`padTop`,+  `padBottom`, `padLeft`, `padRight`, `padLRTB`, `direction`, `fitW`, `fitH`,+  `growW`, `growH`, `percentH`, `itemsCenter`, `justifyBetween`, ...). Config+  layout fields (`ticLayout`, `sicLayout`, `bcLayout`, `canvasLayout`,+  `widgetLayout`, `scLayout`, `pgLayout`) now take `LayoutModifier` instead of+  a `Layout` value.+- **Widget, layout, and input renames:**+  - `alignMid` -> `alignMiddle`; `window`/`window'` ->+    `floatingWindow`/`floatingWindow'`; `searchField*` (`sfc*`) ->+    `searchInput*` (`sic*`); `bounded*` -> `enum*By` / `enum*ByConfigured`;+    `PopupConfig` `cfg*` -> `popupPlacement`/`popupOffset`/`popupDismissable`;+    `scrollArea*` -> `scrollWith'`/`scroll2DWith'`/`scrollConfigured'`;+    `Cell` `withText` -> `cellWidthText`; view-side scroll and window helpers+    dropped their `Ui` suffix (`getScrollMetrics`, `scrollTo`,+    `setScrollOffset`, `setWindowTitle`, `resizeWindow`, `moveWindow`,+    `maximizeWindow`, `quit`, `setTheme`).+  - `fixedWH w h` sets width min/max bounds like `fixedW w . fixedH h`;+    `muted` and `danger` no longer imply `fillW`; `defaultScrollConfig` is+    vertical-only (use `scroll2DConfig` for 2D); fit containers in grid rows+    keep their own height unless given `fillH`; `tooltip` bodies return+    `NanoUI ()`.+  - Mouse buttons on `Input` and `Response` use `MouseButtons` bitsets+    (`inputButtonsHeld`/`Pressed`/`Released`, read with `heldIn`/`pressedIn`/+    `releasedIn` or `mousePressed`/`mouseReleased`/`mouseHeld`). `Key` is+    `Ord` (not `Enum`), and `KeyClaim` dropped `Enum`/`Bounded` and gained+    `KeysNone`, `KeysReadOnly`, and `KeysOnly`.+  - `Theme` gained `themePage`, `themePopup`, `themeSuccess`, `themeWarning`,+    and `themeDanger`, and `Style` gained `styleBorderSides`. Build custom+    themes by updating `defaultTheme` or `defaultLightTheme`.+  - `parseSvg` takes a UTF-8 `ByteString` (via `nano-svg`) and returns an+    opaque `Svg`; `tabKey` requires `Hashable`; `pgTree` takes `InitialTree`+    or `ControlledTree (Var (Maybe GridNode))`; `useReorder` takes keyed+    `Response`s; `widgetCursor` takes `CustomDrawContext -> Rect -> V2 ->+    UiCursorKind`; `TextAreaState` fields gained the `tas` prefix;+    `Animatable` uses `traverseChannels`; `pvDragPick` was removed in favor of+    `paneDragHandle`.+  - Keyed scopes (`withKey`, `keyedTag`, `forEachVar`, pane grids) no longer+    consume a sibling positional id, so widgets following a keyed list keep+    their state and focus when the list changes.+- **Backend changes:** `markDirty` triggers an incremental diffed repaint+  instead of a full redraw (use `damageFull` for global changes); `DrawData`+  gained `drawClear`, unboxed `drawCommands`, and cumulative+  `drawLayerOffsets`; `WindowHost` gained `hostCapabilities`; `WindowOps`+  gained `woWatchResize`; `SessionDriver` gained `sdVsyncOff` and+  `sdPacedWait` and dropped `sdIsHardQuit`; `BackendSession` associates+  backend state with a `Context`.++### Added++- **Typed fragment shaders:** Core phantom-typed shader IR, `Generic` std140+  `Uniforms` packing, Tier 1 (`shaderBox`, `shaderConfigured`) and Tier 2+  (`withShader`, `withShaderWith`) widgets with margin-expanded damage, and+  shader capability queries, paired with the `nano-ui-shader` package.+- **Vector paths and canvas (`NanoUI.Path`):** Subpath fills (`EvenOdd`,+  `NonZero`), strokes with caps, joins, miter limits, and dash patterns, solid+  and linear-gradient paints, `withTransform`, `withClip`, `drawImageWith`,+  `drawTextWith`, `drawTextClipped`, `canvasConfigured`, `runCanvasFor`, and+  keyboard focus/key claims on canvases.+- **Layout and responsive primitives:** `Flow` (`Line`, `Wrap`, `Layered`),+  `layers`, `wrap`, `lineGap`, `lineAlign`, `pinAt`, `aspect`, `ItemsAlign`+  (`itemsStart`, `itemsCenter`, `itemsEnd`, `itemsBaseline`, `itemsStretch`),+  `Justify` (`justifyStart`, `justifyCenter`, `justifyEnd`, `justifyBetween`),+  `PointerMode` (`PointerAuto`, `PointerBlock`,+  `PointerPass`), `withContainerSize`, `withContainerWidth`,+  `withContainerQuery`, `responsiveIn`, `responsiveRowColIn`, `clipBox`,+  `spacerW`, `spacerH`, `singleLine`, `fontTabular`, `fontProportional`, and+  `TextEllipsis` (`EllipsisEnd`, `EllipsisMiddle`, `EllipsisStart`).+- **Widgets and controls:**+  - `NanoUI.Adornment` for leading/trailing icons, affixes, and interactive+    controls on text inputs (`ticAdornments`), buttons (`buttonConfigured`,+    `buttonContent`, `iconButton`), and tab headers (`tabAdornments`,+    `tabsTrailing`).+  - `collapsing` / `collapsingWith`, `selectableRow`, `buttonGroup`,+    `toggleButton`, `calloutTone`, `mouseArea`, `useReorder`, `useListNav`,+    `useVisibility` / `sensor`, `tableBare`, typed table `SortKey` (`SortText`,+    `SortNum`, `SortInt`), `inlineTooltip`, `inlineBackground`,+    `selectableRichText`, incremental `TextDocument` editing+    (`textAreaDocument`, `replaceDocumentRange`, `editDocument`), and+    `PaneGrid` native tabs (`PaneTabs`, `CenterDropMode`), `pgFixedPanes`,+    `paneDragHandle`, and `pgFocusable`.+  - `enumTabs`, `enumTabBar`, and `enum*By` pickers for bounded enumerations,+    `ScrollConfig` (`ScrollOverlay`, `scrollBare`, `scrollFocusable`),+    `imageConfigured` (`ContentFit`, crop, zoom, rotation),+    `svgIconConfigured`, and `useImageRgba` / `releaseImageRgba`.+- **Shortcuts, input, focus, and IME:** `NanoUI.Shortcut` (`ctrl`, `shift`,+  `alt`, `super`, `cmdOrCtrl`, `key`, `shortcut`, `shortcutOnce`,+  `parseShortcut`, `shortcutLabel`), full `Key` coverage, auto-repeat+  distinction (`keyPressedOnce`), `MouseMiddle`/`MouseBack`/`MouseForward`/+  `MouseOther`, `takeEscape`, `requestFocus`/`focusNext`/`focusPrevious`/+  `clearFocus`, CSS cursor shapes (`UiCursorHidden`, `withCursorShape`), and+  IME composition (`useInputMethod`, `InputPurpose`).+- **Windows, themes, async, and testing:** Unified `WindowSettings`,+  `askWindow`, `askWindowCapabilities`, view-side window commands,+  `requestScreenshot`/`useScreenshot`, custom title-bar chrome+  (`captionButtons`, `dragSpans`, `windowFrame`), system appearance tracking+  (`systemAppearance`, `lightDark`, `defaultLightTheme`), `Tone` colors,+  `pageColor`/`panelPage`, `colorHex`/`colorHexA`, per-side borders+  (`borderTop`/`Right`/`Bottom`/`Left`), `useTask`/`useTaskStatus`/`useStream`,+  `askWake`, `wakeAfter` zero-CPU timers, `catchView`, `explainLayout`,+  `NANO_LOOP_TRACE`, `NANO_DAMAGE_TRACE`, and `NanoUI.Testing.Sim`.++### Changed++- **Zero-cost idle and targeted repaints:** Idle windows use zero CPU and GPU+  (`keepAnimating` is per-frame, `spinner` paces at 60 Hz only while visible,+  and focused text fields no longer poll every 16 ms). Per-node paint hashing,+  `Var` part tracking, and up to four disjoint damage regions limit repaints+  to changed widgets.+- **Performance:** Incremental subtree caching in measure and position passes,+  whole-layout and draw-data reuse on unchanged frames, unboxed `PrimVar`+  counters and growable stacks, `ST`-buffered canvas ops, clipped line drawing+  for large labels and rich text, row-level table caching, faster SVG scanline+  rasterization, and pointer-equality store diffing.+- **Unified pointer routing and overlays:** Pointer ownership resolves once+  per frame against the visible layout so presses, drags, wheels, and drops+  cannot leak through modals, windows, dropdowns, or tooltips. Text-field edit+  menus and select/combo dropdowns render as windowed popups.+- **Typography, Unicode, and styling:** Grapheme-cluster cursor movement and+  wrapping (combining marks, emoji sequences, flags), `\r\n` normalization,+  relative `fontSizeScale`, unified single-line control heights, refreshed+  `TabUnderline`/`TabSegmented`/`TabContained` visuals, and builds on GHC 9.10+  through 9.14 (`base >=4.20 && <4.23`, `effectful >=2.6 && <2.8`).++### Fixed++- Accurate height-for-width layout across wrapping text, wrapped rows, grids,+  scrollers, and custom-measured widgets, including fractional DPI scaling and+  device-pixel snapping on overlays.+- 32-bit `Int` (`wasm32`) widget id truncation and table header style-bit sign+  extension.+- Drag/capture cleanup, overlay hit-testing, scroll-axis bubbling and clamping,+  tab-strip overflow scrolling, pane-grid live drop previews, table column+  resize/reorder edge cases, spring numerical stability, hairline rounded+  borders, and image-atlas space reclamation.+ ## 0.1.0.1 -- 2026-09-18 -* +### Added -../../CHANGELOG.md+- Scoped styling: `styled f` draws the widgets inside it with the theme+  modified by `f`, and `themed t` with another theme. Scopes nest, only+  affect how widgets look, and `uiTheme` reads the theme where it is called.+- Style modifiers (`background`, `foreground`, `borderColor`, `borderWidth`,+  `cornerRadius`, `hoverBackground`, `pressBackground`, `fillColor`) and+  theme modifiers (`buttonStyle`, `inputStyle`, `panelStyle`, `windowStyle`,+  `everyStyle`, `accentColor`, `textColor`, `mutedColor`, `linkColor`,+  `selectionColor`, `windowColor`, `rounded`), composed with `(.)`.+- Button variants as theme modifiers: `primary`, `destructive`, `success`,+  `subtle`, and `tinted` for any theme colour.+- `disabledWhen` disables the widgets inside it: they keep their layout and+  state, take no pointer or keyboard input, leave the focus order, and draw+  with `disabledTheme`.+- Undo and redo in every text field: Ctrl+Z, Ctrl+Shift+Z and Ctrl+Y, and+  Undo and Redo rows in the right-click menu. Typing is undone a word at a+  time and a run of deletes at once. Steps keep the edits, not copies of the+  document.+- `TextCommand` and `TextMotion`: what text fields do, as values. Keys and+  the context menu run them, and `runTextCommand` runs them on a field by its+  id, with `textCanUndo` and `textCanRedo` for enabling menu items.+- SVG icons: `parseSvg` and `loadSvg` read the static subset of SVG icon+  sets use (paths, basic shapes, groups, transforms, strokes with caps and+  joins, fill rules, opacity), and `svgIcon` and `svgIconWith` draw one. A+  one-colour icon is tinted with the text colour or a `fontColor`. Each+  document is rasterized with anti-aliasing once per pixel size and colour,+  at the display's scale, into the image atlas.+- `spinner`, an indeterminate loading indicator that repaints only its own+  rect while it turns.+- Rich text: `richText` draws a paragraph of `Inline` pieces, wrapped at its+  width, and returns the target of a link clicked this frame. Pieces are+  string literals, `strong`, `emphasis`, `inlineCode`, `inlineWith` with any+  font modifiers (size, weight, colour, decoration), and+  `hyperlink target label`, drawn in the theme's link colour, underlined+  while hovered, with the pointer cursor. `restyle` adds modifiers to a+  piece, and `richTextWith` sets the paragraph's default font. Mixed sizes+  share a baseline. A paragraph keeps its measured words between frames+  while its pieces, fonts and colours stay the same.+- `DrawTextStyled` draws text in a `TextFont` (size, variant, weight, style+  and decoration) from custom widgets.+- Mixed-direction lines: `NanoUI.Bidi` splits a line into left-to-right and+  right-to-left runs in visual order (the implicit rules of UAX #9: strong+  types, numbers, neutrals and reordering; no explicit embeddings or+  isolates). Carets, clicks and selections in text fields follow the shaped+  layout, so a selection across Arabic and Latin text covers a span per+  run.+- `ShapedText` and `ShapedGlyphs` let a host backend hand shaped layouts to+  the core through `fmShape` and `drawShaped`.+- Theme slots `themeOnAccent`, `themeSelection`, `themeFocusRing`,+  `themeLink`, `themeShadow` and `themeDisabledFade`, which replace colours+  that were fixed in the painters.+- Scroll tuning: `setScrollTuning` sets how far a wheel notch scrolls+  (`scrollWheelStep`) and how long a scroll takes to settle+  (`scrollSmoothTime`, `0` for no glide). `setScrollStep` gives one scroller+  its own step.+- Scroll commands: `scrollTo`, `scrollBy`, `scrollPages`, `scrollToStart`,+  `scrollToEnd`, `scrollIntoView` and `scrollRectIntoView`, each landing at+  once or gliding (`ScrollInstant` / `ScrollSmooth`).+- `getScrollMetrics` reports a scroller's viewport, offset and reachable+  range, which is what a virtualized list needs to pick the rows it builds.+- `expectText` in `NanoUI.Testing.Harness` fails with a message unless a+  collected span contains the given text.+- `Slot` (in `NanoUI.Store` and `NanoUI.Context`) names each kind of+  per-widget store entry, and `modifyStore` in `NanoUI.Context` updates the+  store in one read and write.++### Changed++- `callout` tints the theme's panel colour instead of a fixed dark grey.+- `uiTheme` returns the theme of the enclosing `styled` scope.+- Undo history keeps its edits' texts as `ShortText` copies, which never+  hold on to the larger text a slice came from. A session of typing,+  deleting and pasting in a 5000-line document keeps a 426 KB history+  instead of 1.74 MB.+- SVG documents are read by hexml instead of a hand-written XML scanner. A+  DOCTYPE, which hexml rejects, is skipped. Attribute values must be quoted,+  as XML requires.+- Rasterizing an SVG allocates far less: a 16px stroked icon with round+  joins allocates 42 KB instead of 1.1 MB, and at 128px 437 KB (mostly its+  pixel buffers) instead of 7.2 MB, taking 0.37 ms instead of 4 ms. Contours+  and stroke outlines are flat arrays, and coverage sweeps edges sorted by+  row instead of filtering every edge on every sample row. Output is+  unchanged. `nano-ui-profile svg` measures it.+- Draw ops are a `SmallArray DrawOp` from `primitive` instead of a boxed+  `Vector`: `DrawingBuild`, `CustomDrawBuild`, `runCanvas`, `drawing`,+  `drawingVersioned` and `emitDrawOps`. Build them with+  `smallArrayFromList`; the arrays are `Foldable`, `Eq` and a `Semigroup`.+- `inputKeys` and `inputDrops` are `SmallArray`s. `appendDropEvent` adds a+  drop the way `appendInputKey` adds a key.+- Tree rows, table column metrics and sizes, the SVG rasterizer's buffers,+  and polygon triangulation and stroking use `primitive` arrays. Stroking a+  10,000-point line allocates 2.0 MB instead of 4.7 MB and takes about+  0.34 ms instead of 0.59 ms; a 50-row tree frame allocates 213 KB instead of+  275 KB.+- A custom widget with a measure hook and a fit height is measured again at+  the width layout gives it, as wrapped labels are, so its height can follow+  its width.+- Custom widgets with a content key rebuild their ops when a theme scope+  changes, instead of keeping the old theme's colours.+- `RunQuad`, `fmRun` and `drawRun` are replaced by `fmShape` and+  `drawShaped`. A backend without shaping sets `fmShape = const Nothing` and+  keeps per-character advances and kerning.+- `takeTextEditLastAction` reports the `TextCommand` a text field's menu+  ran.+- Text areas keep their document as a finger tree of lines and repaint only+  the lines in view, so a keystroke in a 100,000-line document costs about+  1.4 ms on the headless profiler instead of about 26 ms.+- A wheel notch scrolls three text lines instead of one, matching what+  desktops send a notch as. `setScrollTuning` puts it back.+- `adoptStoreInt`, `adoptStoreFloat` and `adoptStoreText` return the value+  they adopted.+- `runClick` in `NanoUI.Testing.Harness` returns the release frame's result.+- `NanoUI.Layout.Solve.positionWindowNode` is now `placeWindowNode`.+- `SessionDriver` takes the session's debug sampler (`sdDebug`), whether to+  redraw continuously (`sdContinuous`), a pacing wait (`sdPacingMs`) and+  whether presents wait for the display (`sdPresentPaces`). The event loop+  decides the wait itself, counts clicks with fixed thresholds, samples+  debug timing, and syncs the cursor after every pass, so `sdWaitTimeout`,+  `sdSkip`, `sdNoteLoop`, `sdClickDistance` and `sdClickTime` are gone.+  `sdShouldDraw` also takes whether the debug readout is due.+- `NanoUI.Debug` refreshes snapshots through `refreshDebugSnapshot` and+  `debugRefreshDue` instead of `makeCoreDebugSnapshot`, `presentRate` and+  `takeDebugLive`.+- Lines are drawn as one anti-aliased strip with round caps instead of a+  capsule per segment.+- Tables encode each row once and sort row indices with a merge sort, combo+  boxes filter their options only while focused, pane grid dividers and+  overlays are keyed drawings, and unchanged animations are not rewritten+  to the store, cutting per-frame work for those widgets.+- Damage is gathered into one running union instead of rect lists, paint+  keeps the opaque floating panels it culls against in a flat array built+  only when a frame has floating panels, and the node arena tracks the+  topmost modal as nodes are added instead of hit tests scanning for it.+  On the headless profiler, 3000 frames of a button grid with a pointer+  moving over it and a floating window allocate 1.46 GB instead of 1.64 GB,+  or 1.38 GB instead of 1.48 GB with a modal.++### Fixed++- Circles sharing a centre are concentric whatever their radii. A circle's+  centre snaps to the pixel grid, not its bounding box's corner, which+  rounded differently per radius and put a small disc drawn over a larger+  one up to a pixel off-centre.+- Disabled context-menu rows (`menuItemDisabled`) take the same height,+  minimum width and label inset as enabled rows, instead of a bare label+  flush against the panel edge.+- Where two widgets overlap, a press goes to the one hover highlights (the+  earlier sibling, which paints on top).+- Opening a modal or floating window no longer shifts the ids, and so the+  state, of the widgets declared after it.+- Ctrl+Alt (AltGr) characters type text in text areas, as they already did+  in single-line fields.+- `runTextCommand` focuses the field it runs on, so a command from an app+  menu (Select All, say) shows its selection and the next keystroke goes to+  the field.+- `useDrag2D` does not start a drag during a menu's pointer gesture.+- `drawingVersioned 0` is treated as unversioned, as `drawing` is.+- A grow container with a `minW` counts as that minimum, not as its content,+  in the width of the scroller around it. A long label in such a cell no+  longer makes a 2D scroller scroll sideways while the row would fit.+- Modals, windows and popups lay out their contents with the fonts and+  custom measurements the solve used. A label in a font size other than the+  base no longer wraps onto a line the modal did not make room for, which+  made the modal scroll and clip its last row.++### Removed++- `panelStyled` and `panelStyledWith`; use+  `styled (panelStyle (background bg . borderColor border))` around a panel.+- `MenuAction`; text field menus run `TextCommand`s.+- `labelContentInset`, `panelPaintPad`, `resolveLayoutGap`,+  `resolveLayoutPadding` and `tableCellInset` from `NanoUI`.+- The `slot*` tag constants in `NanoUI.Store` and `NanoUI.Context`; use+  `slotKey` with a `Slot` constructor.+- `stopAnimation`, and store and state accessors from `NanoUI.Context` that+  only internal code used, among them `deleteWidgetStore`, `setStoreBool`,+  `writeStoreText`, `getPrevRects`, `setPrevRectsAndClips`,+  `setOpenSelectDrop`, `setWindowDrag` and `setTextFieldClickCell`.+- `withLayout` from `NanoUI.Monad` (`withIdFrame` is exported instead).+- `stopAnimation` and `textDisplayWidth` from `NanoUI.Testing`.+- `runClickPair` and `runClickRelease` from `NanoUI.Testing.Harness`; use+  `runClick`.+- The text area's `TextAreaEvent`, `handleTextAreaEvent`,+  `computeTextAreaLayout`, `processTextArea`, `textAreaInputCommands`,+  `TextAreaLayout`, `VisualLine` and `Modifiers` exports, and the+  `NanoUI.Widgets.TextBuffer` edit functions (`insertChar`, `insertText`,+  `deleteRange`, `replaceRange` and others). Drive text areas with+  `TextCommand`s. `NanoUI.Widgets.TextEditor` exports `inputTextCommands`+  in place of `ctrlCharCommand` and `isShortcutChar`.+- Internal layout arena column constants and setters from+  `NanoUI.Layout.Arena`, `TextAreaGeom`, `textAreaGeom` and+  `textAreaBarLanes` from `NanoUI.Frame.TextEdit` (which exports+  `textAreaBarLane` and `textAreaLineHeight`), and `resizeFromEdge` and `windowResizeEdgeAt`+  from `NanoUI.Frame.Window`.++## 0.1.0.0++First release.
+ GUIDE.md view
@@ -0,0 +1,739 @@+# Using nano-ui++## Build a windowed application++Use GHC 9.10 through 9.14 (9.14 is used for development) and Cabal. Save the+counter example from the README as `Main.hs` and create `counter.cabal` next to+it:++```cabal+cabal-version: 3.4+name: counter+version: 0.1.0.0+build-type: Simple++executable counter+  main-is: Main.hs+  default-language: GHC2024+  ghc-options: -threaded+  build-depends:+    base >=4.20 && <4.23,+    text ^>=2.1,+    nano-ui ^>=0.2,+    nano-ui-sdl ^>=0.2+```++Install SDL3 and SDL3_ttf 3.2 or later with `pkg-config` metadata available+(`pkg-config --modversion sdl3 sdl3-ttf` should locate both), then run the+application with `cabal run counter`.++For a bitmap-font application without SDL dependencies, use `nano-ui-rgfw` and+`runRgfwApp` instead (see+[its README](https://github.com/goolord/nano-ui/blob/main/packages/nano-ui-rgfw/README.md)+for its native windowing libraries).++## What runs each frame++A `NanoUI` action describes the current interface for a frame. Each widget call+appends layout nodes, reads the current frame's input, and returns an+interaction result. Once the action finishes, layout is solved, pointer and+keyboard interactions are resolved against the computed geometry, and damaged+regions are painted. Writing to a `Var` that was already read earlier in the+same frame triggers a second pass within the same frame, with one-shot input+events cleared so clicks and key presses are not repeated.++Because the UI action can run more than once per frame, load files and allocate+long-lived resources in `IO` before entering the backend runner, and guard+side-effecting actions behind event checks such as+`whenM (button "Save") saveDocument`.++For Elm-style model/update applications, `NanoUI.Emit` (from `nano-ui-emit`)+emits typed messages from `NanoUIE msg a` views, which are ordinary `NanoUI`+actions with the view's message sink in scope, so standard widgets run in them+unchanged. The reducer runner (`runSdlAppReduce`, `runRgfwAppReduce`) applies+all emitted messages in order after the frame's UI pass completes. If the+model changes, a follow-up frame is scheduled automatically.++Use `Emit.emitWhen (button "Save") Save` for click activations,+`Emit.emitChanged (slider 0 100) volume SetVolume` for value changes, and+`Emit.emitEdited textArea' notes SetNotes` when you only want a message on user+edits. The same adapters work with configured and custom widgets.++## Values and interaction state++Mutable state is held in a `Var`. Input widgets take the `Var` to display and+update directly, while internal interaction state (caret position, text+selection, drag anchor, open dropdown state) is kept in the internal widget+store.++```haskell+nameField :: NanoUI ()+nameField = do+  name <- useVar ""+  textInput name+  greeting <- readVar name+  label ("Hello, " <> greeting)+```++A `Var` can be created in three ways:++- `useVar initial` allocates a positional `Var` inside `NanoUI` without prior+  setup. It supports `Int`, `Double`, `Float`, `Bool`, `Text`, and `SortCol`+  (`useEnumVar` supports `Enum` types). The `initial` value is used only when+  the slot is first initialized; to reset the value later, call `writeVar`.+- `newVar initial` allocates a `Var` of any type in `IO`. Create it once during+  setup, store it in an application record, and pass it into your UI action.+  Each call to `newVar` creates an independent `Var`; passing the same `Var` to+  multiple places shares the state.+- `VarMap` stores one `Var` per key for dynamic lists: `varAt` looks up or+  allocates the `Var` for a row key, and `dropVar` removes it.++```haskell+data Editor = Editor {document :: Var TextDocument}++newEditor :: IO Editor+newEditor = Editor <$> newVar emptyDocument++editorView :: Editor -> NanoUI ()+editorView editor = textAreaDocument (document editor)+```++Use `readVar` to read the current value, `writeVar` to replace it, and+`modifyVar` to apply a pure function to the latest value (so multiple updates+in the same frame compose without overwriting each other). Writes that do not change the value (`==`)+do nothing. `readVar` can also be used inside event handlers: reading a `Var`+and then writing to it costs at most one extra pass on that frame. To check+whether an input widget modified its `Var` on the current frame, inspect+`respChanged` on the widget's primed variant (e.g. `textInput'`).++To read a `Var` without recording a read dependency (for example, when comparing+the previous frame's value against the current one), use `peekVar` from+`NanoUI.Var`. From `IO` or background threads, use `readVarIO`, `writeVarIO`,+and `modifyVarIO`, then invoke the callback returned by `askWake` to wake the+event loop. Never call `liftIO (newVar initial)` inside a UI action, as that+allocates a fresh `Var` on every pass.++When a `Var` holds a record with a `Generic` instance, `OverloadedRecordDot`+projects a `Var` for individual fields: `settings.volume` is a `Var Float` that+reads and writes only that field (e.g. `slider 0 100 settings.volume`). Custom+projections can be defined with `zoomVar` (getter and setter) or `zoomVarL`+(van Laarhoven lens). For lists stored in a `Var [a]`, `forEachVar key list body`+renders each item inside `withKey` with an element `Var` that tracks its key+across reorders; `withElemVars` provides the same per-element `Var`s when you+filter or sort the list yourself before rendering.++`constVar x` creates a read-only `Var` where writes do nothing, which is useful+for displaying a derived value in an input widget and handling edits through+the primed widget's `Response`. To run a `Var`-based widget against a plain+value and receive the updated value back, use `withValue value widget`.++### What a write costs++Each frame runs the UI action, solves layout, and paints. If a `Var` is written+after already being read earlier in the same pass (via `readVar` or a bound+widget), the UI action is re-run once before layout so earlier widgets reflect+the updated value (with one-shot inputs cleared so clicks and key presses do not+fire twice). If a `Var` is written before anything reads it, no extra pass is+needed: placing `readVar` below the input widget that edits it keeps typing to a+single pass. Either way, paint-hash damage tracking compares each node's text,+value, style, and bounds against the previous frame and repaints only the+regions that changed.++Read/write tracking is granular up to two levels of nesting (a record field or+list element, plus a nested field within it). With a record in a single `Var`,+`m.title` and `m.volume` are tracked separately, so reading `m.title` above a+slider bound to `m.volume` does not trigger a second pass when the slider moves.+Reading the entire record `m` or projecting through `zoomVar` marks all fields+as read. `forEachVar` only reads the list's keys and order, so editing a single row's `Var` does not invalidate earlier rows; `withElemVars` returns the elements directly and therefore marks the whole list as read. Rows are distinguished using 63 hash bits of their keys, so past ~63 rows (or for keys that collide on the same bit, such as `Int` keys 64 apart), editing a row may trigger a second pass if sibling rows call `readVar` on that field; damage tracking still repaints only the rows whose output changed.++Primed widget variants (`button'`, `textInput'`, `slider'`) return a `Response`:+`respChanged` is `True` when the value was edited, `respSubmitted` when+committed (such as pressing Enter in a text input), and `respClicked` when+activated. `respPressed` is `True` while the mouse button is held down on the+widget, rather than on a single-frame click.++`searchInput'` updates its `Var` on every keystroke but debounces+`respChanged`, so you can trigger expensive searches on `respChanged`.++## Stable identity++Widgets and positional `useVar` calls each use their own sequential counter+within a container scope. Keep call order consistent across frames, and wrap+conditional widgets or `useVar` calls in `scope`:++```haskell+details :: Bool -> NanoUI ()+details showDetails = column $ do+  scope $ when showDetails $ label "Additional details"+  nameField+```++`scope` reserves a single slot in the parent sequence regardless of whether its+body runs, so `nameField` keeps the same ID below it. Because `useVar` uses a+counter separate from widget IDs, conditional widgets alone do not shift+`useVar` slots, but conditional `useVar` calls still require `scope`.++For dynamic or reorderable lists, wrap each item in `withKey` using a unique,+stable key (not the list index):++```haskell+names :: [(Int, Text)] -> NanoUI ()+names entries = column $+  forM_ entries $ \(itemId, name) -> withKey itemId $ do+    checked <- useVar False+    checkbox name checked+```++Keyed state stored by `useVar` or by widgets like text fields remains alive for the lifetime of the context, even while its key is hidden, so temporarily hidden content preserves its state. For unbounded collections whose keys keep growing (such as a chat log), store per-row state in a `VarMap` rather than `useVar`, and prune removed keys with `retainVars`.++## Layout and coordinates++All layout dimensions use logical pixels, with `(0, 0)` at the top-left corner,+`x` increasing to the right, and `y` increasing downward. Backends scale logical+pixels to physical display pixels automatically; custom widgets should work in+logical coordinates.++Layout modifiers are `Layout -> Layout` functions composed with `(.)`:++```haskell+columnWith (gap 8 . padAll 12 . fillW) $ do+  label "Settings"+  buttonWith (fixedW 120) "Apply"+```++When two modifiers set the same property, the leftmost modifier takes+precedence. `fillW` and `fillH` distribute available space across growing+siblings; `minW` and `maxW` clamp width; `percent 50` requests 50% of the+parent's available width; `tight` zeroes padding while preserving `gap`.++Container flow along a `Row` or `Column` defaults to a single `Line`, and can+be changed to `Wrap` or `Layered`:++- `layers` stacks its children in a shared box sized to the largest child; each+  child is placed according to its alignment, and later children are drawn on+  top. The `layered` modifier applies the same behavior to a panel or card,+  e.g. `panelWith (layered . fixedWH 240 160)`.+- `wrap` wraps a row or column onto additional lines when children exceed the+  available main-axis size, e.g.+  `rowWith (wrap . gap 6 . lineGap 4) (mapM_ chip tags)`. `lineAlign LinesCenter`+  or `lineAlign LinesEnd` aligns wrapped lines along the cross axis. Inside a+  shrink-to-fit parent, give a wrapping row an explicit `maxW` or `fixedW`.+- `pinAt x y` takes a child out of normal flow and positions it over its+  siblings at offset `(x, y)` relative to its alignment anchor in the parent's+  content box (top-left by default, or bottom-right with+  `pinAt (-16) (-16) . alignEnd . alignBottom` for a floating action button).+  `pinAt 0 0 . grow` covers the parent's content box without affecting the+  parent's size, which is useful for scrims or drop-target highlights.+- `aspect r` constrains height from width at ratio `r` (e.g.+  `box (fillW . aspect (16 / 9)) c`).++When layers or pinned nodes overlap, pointer input goes to the topmost+interactive control (buttons, inputs, sliders, custom drawings) at the cursor,+while panels, labels, images, and layout containers do not intercept pointer+events. Override this behavior with `pointer PointerBlock` (so a panel or+overlay scrim blocks pointer events over its full rectangle) or+`pointer PointerPass` (so a decorative drawing does not intercept pointer+events):++```haskell+layers $ do+  list+  panelWith (pointer PointerBlock . alignEnd . fixedW 240) details+```++Scroll containers require a bounded viewport size, such as+`scrollWith (fixedH 240 . fillW) body`. `scrollWith'` (or `scrollConfigured'`)+also returns the scroller's `Response` (including its `WidgetId`) for+programmatic scroll commands like `scrollTo`, `scrollToEnd`, and+`scrollRectIntoView`. For large virtualized lists, use `getScrollMetrics` to+query the current scroll offset and viewport size so you only build the visible+rows.++To defer work until a widget enters the viewport, wrap it in `sensor` (or pass+its ID to `useVisibility`). The returned visibility record contains the widget's+previous-frame bounds (`visBounds`), its visible intersection on screen+(`visRect`), and `becameVisible` (`True` on the frame the widget enters view).+In `sensorConfigured`, `sensorAnticipate` expands the check by a given number of+pixels outside the viewport, and `sensorDelay` requires the widget to stay in+view for a given duration before `becameVisible` turns `True` (so scrolling+quickly past a list does not trigger loads for intermediate items):++```haskell+lazyImage :: Var (Maybe ImageId) -> NanoUI ImageId -> NanoUI ()+lazyImage pictureVar load = do+  picture <- readVar pictureVar+  let config = defaultSensorConfig {sensorAnticipate = 200, sensorLayout = fixedWH 96 96}+  (vis, _) <- sensorConfigured config $+    maybe (label "Loading") (image (fixedWH 96 96)) picture+  when (becameVisible vis && isNothing picture) $+    writeVar pictureVar . Just =<< load+```++Because layout is solved after the UI action completes, `respRect` returns the+widget's rectangle from the previous frame and is empty on the first frame a+widget appears. Keep this in mind when positioning custom popups or writing+headless pointer tests.++## Themes, overlays, and input++Use `styled` to modify the active theme for a subtree, or `themed` to replace+it completely. Theme scopes affect colors and painting only, not layout+metrics (font sizes are set via layout modifiers). `disabledWhen condition`+disables interaction and applies disabled styling across a subtree while+preserving layout geometry and widget state.++Semantic status colors are applied with tones: `fontTone Warning` sets a+label's text color (combining with font faces like `fontMono . fontTone Danger`),+`tone Danger` styles buttons, `calloutTone Warning` tints callout panels, and+`toneColor` retrieves the `Color` value for custom drawing. Helpers such as+`fontMuted`, `fontDanger`, `primary`, `destructive`, `success`, and `warning`+are shorthands for the corresponding tones.++To follow the operating system's light or dark mode, pass a theme selector such+as `lightDark defaultLightTheme defaultTheme` (which falls back to the dark+theme on platforms that do not report system appearance, such as RGFW). You can+apply it inside your UI action:++```haskell+setTheme . lightDark defaultLightTheme defaultTheme =<< systemAppearance+```++Or configure it via `followSystemTheme` inside the view, or at startup via+`sdlAppThemeFor` or `optThemeFor`. Calling `setTheme` switches to a fixed theme,+and `themeAppearance` returns whether a `Theme` is light or dark. Extra preset+themes and Base16 palettes live in `NanoUI.Themes`.++Modals, floating windows, and popups take a `Var Bool` controlling whether they+are open. While the `Var` is `True`, the overlay is shown; pressing Escape,+clicking outside, or clicking the close button writes `False` to the `Var`. A+`floatingWindow` closes only by its close button.+Call the overlay unconditionally every frame so sibling widget IDs remain+stable:++```haskell+confirm <- useVar False+whenM (button "Delete...") (writeVar confirm True)+modal confirm "Delete the file?" $+  whenM (button "Delete") (deleteFile >> writeVar confirm False)+```++If the open state is derived or the dialog must not close until explicitly+confirmed, pass a `constVar` and handle dismissal via `respClicked` on the+primed variant (`modal'`, `floatingWindow'`, `popup'`).++Tooltips require no state variable: passing a widget's response to `tooltip`+(or wrapping the widget with `withTooltip`, for a tooltip built from widgets)+displays the tooltip after the pointer rests on the target for `tooltipDelay`+(0.5s by default) and hides it when the pointer leaves or a mouse button is+pressed.+Tooltips also trigger on disabled widgets. `tooltipConfigured` customizes the+delay, placement, and offset; `PlacementAtCursor` positions the tooltip at the+cursor (or at the click position for popups and context menus).++Standard widgets read layer-routed input via `askInput`, where covered layers+receive no pointer events. `askFrameInput` returns raw window-wide input (used+for outside-click dismissal) and should not be used by ordinary controls.++To control keyboard focus programmatically, pass a widget's ID to+`requestFocus` (e.g. `when findPressed (requestFocus (respId resp))`, or+`requestFocus =<< currentId` immediately before the widget call). `focusNext`+and `focusPrevious` cycle focus like Tab and Shift+Tab, `clearFocus` removes+focus, and `isFocused wid` checks whether that widget is focused. Focus+requests take effect at the end of the frame (clearing any active selection or+open menu on the previously focused field and skipping disabled or+modal-blocked widgets), whereas `releaseFocus` drops focus from a specific+widget immediately during the current pass. Clicking focuses text fields,+selects, and focusable custom widgets (such as a knob, or a canvas with+`canvasFocusable`).++`withCursorShape` sets the default cursor shape for a subtree (such as+`UiCursorCrosshair` over a canvas, `UiCursorNotAllowed` over disabled controls,+or `UiCursorHidden` over a video player). Custom widgets can set their own+cursor via `widgetCursor` based on their bounds and pointer position (returning+`UiCursorDefault` to defer to the enclosing `withCursorShape` scope), and that+cursor is retained throughout an active drag even if the pointer leaves the+widget's bounds.++Keyboard state is exposed in `inputKeys` (pressed this frame, including key+repeats), `inputKeysNew` (initial presses only, excluding repeats),+`inputKeysReleased`, `inputKeysHeld`, and `inputChars` (committed text).+Printable keys are represented as `KeyChar` with the unmodified character (so+Ctrl+S produces `KeyChar 's'` with `modCtrl` set and no entry in `inputChars`).+Because a single frame's `Input` does not record the relative ordering of text+and command keys, the event runner flushes a frame whenever a command key or+chord is followed by text, another key, or a modifier change, so any text typed+before a shortcut is processed on the preceding frame. Helper predicates+`pressedIn`, `pressedOnceIn`, `releasedIn`, and `heldIn` query keys or mouse+buttons directly on an `Input` record (e.g.+`sdlAppShouldQuit = pressedOnceIn KeyEscape`).++Keyboard shortcuts are built with modifiers (`ctrl`, `shift`, `alt`, `super`,+and `cmdOrCtrl`, which maps to Command on macOS and Ctrl elsewhere) combined+with `key` via `<>` from `NanoUI.Shortcut`:++```haskell+import NanoUI.Shortcut++whenM (shortcut (ctrl <> key 's')) save+whenM (shortcut (cmdOrCtrl <> shift <> key 'p')) (setPaletteOpen True)+whenM (shortcut (key (KeyF 5))) refresh+```++Modifier-only chords without a key never fire. `parseShortcut` parses chords+from configuration strings such as `"C-s"`, `"M-S-p"`, `"A-<Enter>"`, or+`"<F5>"`.++`shortcut` triggers on press (including key repeats) for the first matching+`shortcut` call in the frame; `shortcutOnce` and `keyPressedOnce` ignore+auto-repeats. Shortcuts and view-level key queries (`keyPressed`,+`keyReleased`, `keyHeld`) are suppressed when blocked by a modal, inside+`disabledWhen`, or when handled by the focused widget (for example, typing or+Ctrl+A in a text input, Enter/Space on a focused button, or arrow keys on a+focused slider or list; modified chords like Ctrl+Enter or Alt+Left still pass+through to shortcuts). An Escape press that dismisses an open dropdown, a focused combo box list, or a text field's context menu is consumed before reaching either shortcuts or key queries, along with its key repeats and release (`keyHeld`, `keyReleased`). Custom widgets specify+which keys they handle via `widgetKeys` (for example, a terminal widget sets+`KeysAll`); one that claims Tab this way keeps focus when Tab is pressed.+`menuItemShortcut` only matches while its menu is open; to make the shortcut+active while the menu is closed, declare a matching top-level `shortcut` after+the menu so the open menu handles the chord first.++Built-in text inputs and text areas handle IME composition automatically: the+focused field renders the active pre-edit string (`inputComposition`) at the+caret and updates its `Var` only when the composition is committed. While a+composition is active, key events are suppressed so shortcuts do not trigger.+Custom text-entry widgets (such as a terminal) can opt into IME composition by+calling `useInputMethod` on every frame they hold focus, passing the caret+rectangle and input purpose (`InputNormal`, `InputSecure`, or `InputNumeric`),+and rendering the returned composition string. Backends like SDL only enable OS+text input on frames where `useInputMethod` is called, so any UI that reads+`inputChars` outside a built-in text field must call `useInputMethod` as well.++Mouse buttons are represented by `MouseButton` (`MouseLeft`, `MouseRight`,+`MouseMiddle`, `MouseBack`, `MouseForward`, and `MouseOther n`). On a widget's+`Response`, `respHeldWith` lists the buttons pressed on that widget and still+held down, and `respClickedWith` lists the buttons pressed and released on it+(`respClicked` is `True` on standard activation via left click or Enter).+Pressing a button outside a widget and dragging across it does not count as+pressing or clicking that widget. For scope-wide mouse queries (suppressed+behind modals and inside `disabledWhen`), use `mousePressed`, `mouseReleased`,+and `mouseHeld`:++```haskell+whenM (mousePressed MouseBack) goBack+tab <- button' "Report"+when (respClickedWith MouseMiddle tab) closeReport+```++`mouseArea` wraps a layout subtree and returns a `Response` for the combined+region. It registers hover and mouse button clicks over the region unless an+interactive child widget inside it handled the click:++```haskell+(_, item) <- mouseArea (fillW . gap 6) $ do+  label name+  muted path+when (respClickedWith MouseMiddle item) (openInNewTab path)+when (respClickedWith MouseRight item) (showMenuFor path)+```++Closable tabs also close on middle-click.++## Animation and background work++Backends block waiting for events when no frame is scheduled. Call+`keepAnimating` from any on-screen widget that needs continuous animation+frames. For periodic or delayed updates (clocks, debounces, timers), call+`wakeAfter` on each frame that still requires a future wake-up. Do not force+redraws by marking the context dirty every frame, as that creates an unpaced+busy loop.++Long-running or blocking operations (such as file or network I/O) should run on+a background thread via a `Task` handle allocated during setup (`task <- newTask`):++```haskell+status <- useTaskStatus task path (T.readFile path)+case status of+  TaskRunning _ -> label "Loading..."+  TaskDone contents -> label contents+  TaskFailed e _ -> danger (T.pack (displayException e))+```++`useTaskStatus` returns whether the task is running, completed with a result,+or failed with a synchronous exception (`TaskFailed`); `useTask` returns+`Maybe a` (`Nothing` until the first result is produced). A task runs once per+key and wakes the event loop when it finishes. When the key changes, the+previous thread is canceled with an asynchronous exception and a new thread is+spawned; while the new key is still running, both `useTaskStatus` and `useTask`+continue to provide the previous key's result (`TaskRunning (Just old)`) so UI+lists do not flash empty while re-querying. To add a retry trigger, include an+attempt counter in the key, e.g. `useTaskStatus task (path, attempt)`. Because+canceled tasks receive an asynchronous exception and may briefly overlap with+the new task, use `bracket` inside tasks that open files or hold external+resources. Task results are evaluated to WHNF on the worker thread. Compile+applications with `-threaded`.++Skipping a `useTask` or `useTaskStatus` call for a full frame cancels the+running task, so place task calls outside conditional branches or tabs if the+work should continue while hidden. Task calls do not consume widget IDs, so+calling them conditionally does not affect sibling widget identity:++```haskell+when previewOpen (void (useTask task path (renderPreview path)))+```++For streaming data (sensor readings, download progress, token-by-token+responses), allocate `stream <- newStream` during setup and pass a producer to+`useStream`. The producer is passed an atomic `update` function that modifies+the stream's state and wakes the event loop; multiple updates between frames+coalesce into a single frame. The state resets to the initial value whenever+the key changes, and the producer thread runs for as long as `useStream`+continues to be called each frame:++```haskell+sensorView stream = do+  reading <- useStream stream () Nothing $ \update -> forever $ do+    r <- readSensor+    update (const (Just r))+  label (maybe "--" (T.pack . show) reading)+```++To accumulate all emitted items into a list, fold each item into the state+(`update (r :)`).++The `Context` and its arenas must only be accessed from the UI thread. If an+external thread managed outside `useTask`/`useStream` updates shared state, it+should write the update and then invoke the wake callback obtained from+`askWake`; multiple wakes before the next frame coalesce into a single frame+whose damage diff repaints only the nodes whose text, value, style, or bounds+changed.++Note that low-level damage requests only mark screen regions for repainting and+do not wake a blocked event loop on their own; external updates must trigger a+wake as well.++## Custom drawing and large text++`drawing` and `customWidget` construct `DrawOp` lists from solved logical+bounds. When caching a custom drawing with a content key, include all dynamic+inputs (including animation state) in the key so visual changes are not skipped;+unkeyed custom widgets rebuild and diff their `DrawOp` list on every frame.++Vector paths are constructed using `NanoUI.Path` (typically imported qualified+as `P`): build paths with `P.moveTo`, `P.lineTo`, `P.cubicTo`, `P.arc`, etc.,+and render them with `drawPath` / `drawPathWith` (for fills) or+`drawStrokePath` / `drawStrokePathWith` (for strokes). `drawPathWith` takes a+fill rule (`P.NonZero` or `P.EvenOdd`, where inner subpaths can cut holes such+as rings) and a paint (`P.Solid` or `P.Linear` gradient). `drawStrokePathWith`+takes a `P.Stroke` specifying stroke width, line caps, joins, miter limit, and+dash pattern. Use `withTransform` to translate, rotate, or scale canvas+operations, and `withClip` to clip them. Within a custom widget, run canvas+blocks via `runCanvasFor` (or use the `canvas` / `canvasConfigured` widget+helpers) so curve tessellation adapts to the display scale; `drawContext`+returns the current `Theme` along with the widget's hover and press state:++```haskell+import NanoUI.Path qualified as P++gauge :: Float -> NanoUI Response+gauge level =+  canvasConfigured defaultCanvasConfig {canvasLayout = fixedWH 80 80, canvasContent = contentKey [level]} $+    \(Rect x y w h) -> do+      cdc <- drawContext+      let c = V2 (x + w / 2) (y + h / 2)+          theme = cdcTheme cdc+      drawPathWith P.EvenOdd (P.circle c 36 <> P.circle c 26) (P.Solid (themeSeparator theme))+      drawStrokePathWith (P.stroke 10) {P.strokeCap = P.RoundCap}+        (P.arc c 31 (-pi / 2) (2 * pi * level))+        (P.Solid (if cdcHovered cdc then themeAccent theme else themeMuted theme))+```++Path fills do not compute self-intersections: intersecting subpaths are filled+independently, and self-intersecting contours may not fill as expected. Path+strokes are centered on the path geometry, whereas `drawStrokeRoundedRect` and+`drawStrokeCircle` inset their border inside the shape bounds (matching panel+borders).++For multi-line text editing, `textArea` operates on a `Var Text` and rejoins+lines on each edit. For large documents, use `textAreaDocument` with a+`Var TextDocument`, which shares unchanged lines across edits; convert back to+a single `Text` with `documentText` only when saving or exporting.++Backends receive borrowed `DrawData` vertex/index buffers that are reused on+the next frame, so backends must consume or copy them during presentation.+Native font and renderer handles must not outlive their backend session.++## Images++For scoped image lifetimes, allocate `owner <- newImageHandle` during setup and+call `useImageRgba owner key w h pixels` in your UI action. The RGBA buffer is+uploaded on the first frame for a given key, and the texture slot in the image+atlas is freed automatically if a frame completes without calling `useImageRgba`+for that handle, or when the key changes. For static images kept for the entire+session, allocate an ID with `freshImageId` and upload once with+`registerImageRgba`; `releaseImageRgba` frees one you no longer need.++`image` stretches an image to fill its layout bounds. `imageConfigured` takes+an `ImageConfig` supporting CSS-style `ContentFit` (`FitFill`, `FitContain`,+`FitCover`, `FitScaleDown`, `FitNone`), alignment, pixel sub-rectangle cropping+(`icCrop`), zoom (`icScale`), opacity, and rotation (`RotateSolid` fits the+rotated bounding box into layout bounds; `RotateFloating` rotates in place and+clips). Unconstrained layout axes default to the image's intrinsic dimensions,+and setting one axis with `FitContain`/`FitCover` preserves aspect ratio on the+other (so `icLayout = fillW` scales height proportionally). `svgIconConfigured`+applies the same fitting rules to SVG icons (`svgIcon` defaults to+`FitContain`), and `fitRect` computes the fitted rectangle directly. On a+canvas, draw images with `drawImage`, `drawImageUV`, or `drawImageWith` (which+takes an `ImageDraw` specifying destination bounds, UV crop, rotation, tint,+and opacity).++```haskell+thumbnail :: ImageHandle FilePath -> FilePath -> Int -> Int -> ByteString -> NanoUI ()+thumbnail owner path w h pixels = do+  photo <- useImageRgba owner path w h pixels+  for_ photo $+    imageConfigured defaultImageConfig {icLayout = fixedWH 120 90, icFit = FitCover}+```++## Inspecting layout++Calling `explainLayout True` draws depth-colored outlines around every layout+node and highlights the node under the cursor. `explainedNode` returns metadata+for the hovered node: its `WidgetId`, solved rectangle, padding, width/height+`Sizing` constraints, gap, layout direction, `Flow`, pin offset, and+`PointerMode`. To limit the debug overlay to a specific subtree, wrap that+subtree in `explainScope`. You can also enable the overlay at startup via+`sdlExplainLayout`, `optExplainLayout`, or `--explain` in the SDL demo, or+toggle it from a checkbox in a debug panel:++```haskell+on <- explainingLayout+(_, on') <- withValue on (checkbox "Outline layout nodes")+explainLayout on'+```++## Window management++Initial window parameters are configured with `WindowSettings` across all+backends (`sdlWindowSettings` in `SdlOptions`, `optWindow` in `RgfwOptions`).+Dimensions in `WindowSettings` are specified in logical layout units and scaled+by the backend when the window opens:++```haskell+main :: IO ()+main =+  runSdlApp+    defaultSdlOptions+      { sdlWindowSettings =+          defaultWindowSettings {wsTitle = "Notes", wsSize = Size 900 600, wsMinSize = Just (Size 480 320)}+      }+    notesView+```++`askWindow` returns the window's state at the start of the frame (logical size,+display scale, screen position, keyboard focus, and minimized/maximized/fullscreen+mode). UI actions that call `askWindow` automatically receive a new frame when+window state changes. Declarative setters (`setWindowTitle`,+`setWindowIcon`, `setWindowMinSize`, `setWindowMaxSize`,+`setWindowOpacity`, `setWindowMode`) are no-ops when the requested value+matches the current state, so they can be called unconditionally each frame.+Imperative window actions (`moveWindow`, `centerWindow`, `resizeWindow`,+`minimizeWindow`, `maximizeWindow`, `restoreWindow`, `toggleMaximized`)+apply on every call and should only be triggered from events. Transparent+windows (`wsTransparent = True` combined with a translucent theme+`windowColor`) are supported on the SDL backend when a desktop compositor is+present; RGFW windows are always opaque and ignore `wsOpacity` and+`setWindowOpacity`.++By default, clicking the window's close button exits the session immediately.+With `wsExitOnCloseRequest = False`, close requests are not handled+automatically: `winCloseRequested` on `askWindow` becomes `True` on the next+frame, and the window stays open until `quit` is called:++```haskell+asking <- useVar False+whenM (winCloseRequested <$> askWindow) $+  if unsaved then writeVar asking True else quit+modal asking "Discard your changes?" $ do+  whenM (button "Discard") quit+  whenM (button "Keep editing") (writeVar asking False)+```++`requestScreenshot` registers a callback that receives a `Screenshot`+(containing the frame's `RgbaPixels` and pixel-per-logical-unit scale, or+`Nothing` when running headlessly) once the current frame finishes presenting.+Call `requestScreenshot` from an event handler and keep the callback fast (or+offload encoding to a worker thread), as it runs before the next frame starts.+To capture and save a screenshot inside a background task, obtain a trigger+with `askScreenshot`:++```haskell+shoot <- askScreenshot+saved <- useTaskStatus task shots (shoot >>= traverse_ (savePng "shot.png"))+```++`useScreenshot task key` captures a screenshot per key for displaying directly+in the UI. To construct `RgbaPixels` for window icons, use `rgbaPixels` (which+checks that the width and height are positive and the buffer is exactly+`w * h * 4` bytes, and returns `Nothing` otherwise).++## Writing a backend++`NanoUI` exports the user-facing GUI API, while `NanoUI.Backend` exports the+types and functions used to implement a windowing and rendering backend:+`emptyInput` and event-folding helpers, `FontBackend` callbacks for text+measurement and shaping, `Damage` regions for partial presentation, and default+widget metrics. Because held mouse buttons, modifier state, cursor position,+and window size carry over between frames, pass the previous frame's `Input`+through `clearEphemeral` (which clears one-shot presses and text while+preserving held state) and fold new platform events into the result rather than+starting from `emptyInput` each frame. `newContext` / `newPixelContext` (from+`NanoUI.Backend`) allocate the persistent session context, and `NanoUI.Runner`+provides the shared event-loop state machine. See `NanoUI.Backend.Sdl` and+`NanoUI.Backend.Rgfw` for complete implementations.++Fold keyboard events into `Input` with `applyKey` (recording printable keys as+their unmodified `KeyChar`, appending committed text to `inputChars`, and+treating key repeats as presses) and IME pre-edit updates with+`applyComposition`. After each frame, inspect `textInputArea` to determine+whether a widget is requesting text input, its `InputPurpose`, and the caret+rectangle for positioning the IME candidate window; enable or disable OS text+input accordingly.++Initialize the native window from `WindowSettings` (title, logical size, window+mode, resizability, transparency). Before the first frame, install a+`WindowHost` callback record with `installWindowHost` constructed via record+update on `defaultWindowHost` (so fields added in future versions have sensible+defaults). Register a thread-safe wake callback with `setWakeLoop`, report OS+light/dark appearance changes with `setSystemAppearance`, update window metrics+before each frame with `reportWindowState`, and fulfill pending screenshot+requests after presentation with `answerScreenshots`. `runSessionLoop` manages+close requests and `quit` automatically; custom event loops can drive them+with `requestWindowClose`, `clearWindowClose`, and `quitRequested`.++## Headless tests++`NanoUI.Testing` exports `newContext` and `runFrame` for running frames without+a window or GPU. `runFrame` returns the UI action's result, the frame's+`DrawData`, and whether a follow-up frame was requested; for `NanoUIE` views,+`runFrameE` from `nano-ui-emit` also returns the emitted messages.+Provide an explicit window size and `dt` in the test `Input`. When targeting a+widget by its `respRect`, run an initial warm-up frame so layout geometry is+populated before sending press and release frames.++`NanoUI.Testing.Harness` provides test helpers including `warmup2`,+`clickPair`, `clickPairWith` (e.g. `clickPairWith MouseMiddle base pos`),+`runClick`, and text-span lookup functions. `held var widget` runs a widget+bound to a `Var` and returns both the widget result and the updated `Var`+value. `lastFramePasses` returns how many passes the previous frame executed+(note that when a backward write triggers a second pass in the same frame,+one-shot click and change flags from the first pass are cleared on the second+pass's return value).++Because tooltip hover delays use the wall clock, set `tooltipDelay = 0` in+tests. Use `newWakeSignal` to wait for background task wake-ups deterministically,+and call `cancelTasks` (from `NanoUI.Backend`) during test teardown to stop any+background threads still running.++Headless tests verify layout, state, and input logic; when modifying rendering,+font handling, native dialogs, or DPI scaling, run the native backend test+suites and demos as well.
README.md view
@@ -1,1 +1,70 @@-../../README.md+# nano-ui++Core immediate-mode GUI toolkit for Haskell. A window is a single monadic action that runs every frame using ordinary functions, `do` blocks, and standard control flow (`if`, `case`, `for_`). Widgets return results directly (such as `Bool` from `button`), and mutable state lives in typed `Var` references inside `NanoUI`.++```haskell+{-# LANGUAGE OverloadedStrings #-}++import Data.Text qualified as T+import NanoUI+import NanoUI.Backend.Sdl (defaultSdlOptions, runSdlApp)++main :: IO ()+main = runSdlApp defaultSdlOptions counter++counter :: NanoUI ()+counter = row $ do+  n <- useVar (0 :: Int)+  whenM (button "-") (modifyVar n (subtract 1))+  label . T.pack . show =<< readVar n+  whenM (button "+") (modifyVar n (+ 1))+```++## Backends and companion packages++`nano-ui` provides the widgets, layout solver, input handling, theming, and draw lists. Pair it with a backend package to open windows and render frames:++| Package | Description |+| --- | --- |+| [nano-ui-sdl](https://hackage.haskell.org/package/nano-ui-sdl) | Desktop SDL3 backend with HarfBuzz TrueType fonts, system font lookup, and native file dialogs |+| [nano-ui-rgfw](https://hackage.haskell.org/package/nano-ui-rgfw) | RGFW + OpenGL 3.2 backend with a bundled bitmap font and no extra library dependencies |+| [nano-ui-sdl-web](https://hackage.haskell.org/package/nano-ui-sdl-web) | Browser backend for GHC's WebAssembly target using SDL_ttf and WebGL2 |++Optional companion packages add [typed GPU fragment shaders](https://hackage.haskell.org/package/nano-ui-shader) (`nano-ui-shader`), [charts and diagrams](https://hackage.haskell.org/package/nano-ui-diagrams) (`nano-ui-diagrams`), [validated forms](https://hackage.haskell.org/package/nano-ui-form) (`nano-ui-form`), [streamable Markdown](https://hackage.haskell.org/package/nano-ui-markdown) (`nano-ui-markdown`), [SVG export](https://hackage.haskell.org/package/nano-ui-svg) (`nano-ui-svg`), and [Elm-style message reducers](https://hackage.haskell.org/package/nano-ui-emit) (`nano-ui-emit`).++Regular application code only needs `import NanoUI`. `NanoUI.Testing` runs frames headlessly against scripted input, and `NanoUI.Backend` exports the hooks for custom backends.++## State and `Var`s++Allocate view-local state with `useVar`, pass it straight to input widgets, and read the updated value with `readVar`:++```haskell+greeter :: NanoUI ()+greeter = columnWith (gap 8 . padAll 16) $ do+  name <- useVar "world"+  size <- useVar 16+  shout <- useVar False++  heading "Greeter"+  textInput name+  slider 10 48 size+  checkbox "Shout" shout++  greeting <- ("Hello, " <>) . (<> "!") <$> readVar name+  loud <- readVar shout+  px <- readVar size+  labelWith (fontSize px) (if loud then T.toUpper greeting else greeting)+```++`useVar` handles view-local primitives without setup, `newVar` allocates state of any type in `IO`, and `v.field` projects a `Var` for a single field of a `Generic` record. A frame only runs a second pass if a `Var` is written *after* it was already read earlier in the same pass, so placing `readVar` below the widget that edits it keeps updates to a single pass. If you prefer an Elm-style reducer loop, add `nano-ui-emit` for `NanoUIE msg a`.++## What is included++Built-in controls cover text inputs, multi-line editors with undo/redo, numeric fields, sliders, knobs, selects, combo boxes, sortable tables, trees, tabs, menus, modals, floating windows, pane grids, color pickers, sparklines, rich text, SVG icons, drag and drop, and a 2D vector canvas (`customWidget`). Layout modifiers compose as `Layout -> Layout` functions (rows, columns, grids, wrapping, layers, pinned overlays, scrolling, aspect ratios). Keyboard focus, shortcuts, IME composition, keyed async tasks (`useTask`), streams (`useStream`), themes, and spring/tween animations are built in. The event loop blocks while idle and per-frame damage tracking repaints only changed regions.++## Documentation++- [The nano-ui Book](https://goolord.github.io/nano-ui/book/): Tutorials, widget gallery, interactive styling lab, and architecture guide.+- [User guide](https://github.com/goolord/nano-ui/blob/main/packages/nano-ui/GUIDE.md) (also bundled as `GUIDE.md` in the Hackage tarball): Reference for setup, state, widget identity, layout, async tasks, custom drawing, and headless testing.+- `NanoUI` Haddocks: API reference for widgets, state, and layout modifiers.+- [GitHub repository](https://github.com/goolord/nano-ui): Example apps and development setup.
benchmark/IdBench.hs view
@@ -1,9 +1,11 @@ module Main (main) where  import Control.Monad (forM_, replicateM_, void, when)-import GHC.Stats (RTSStats (..), getRTSStats)+import GHC.Conc (getAllocationCounter) import NanoUI-import NanoUI.Testing (newContext, runFrame)+import NanoUI.Backend (burstNextIds, emptyInput)+import NanoUI.Monad (nextId)+import NanoUI.Testing (Context, newContext, runFrame) import System.Exit (exitFailure) import System.Mem (performGC) import Test.Tasty.Bench@@ -16,36 +18,51 @@ idBurst = column (burstNextIds 4096)  scopedWidgets :: NanoUI ()-scopedWidgets =+scopedWidgets = rows (void nextId)++-- | 32 rows of 32 @cell@s.+rows :: NanoUI () -> NanoUI ()+rows cell =   columnWith (gap 2)     $ replicateM_ 32     $ rowWith (gap 2)-    $ replicateM_ 32 (void nextId)+    $ replicateM_ 32 cell -measureFrameAlloc :: NanoUI a -> IO Integer-measureFrameAlloc ui = do+-- | A context that has run @ui@, so its next frame is warm.+warmContext :: NanoUI a -> IO Context+warmContext ui = do   ctx <- newContext-  _ <- runFrame ctx benchInput (column (void nextId))+  replicateM_ 2 (runFrame ctx benchInput ui)+  pure ctx++-- | Bytes a warm frame of @ui@ allocates.+frameAlloc :: NanoUI a -> IO Integer+frameAlloc ui = do+  ctx <- warmContext ui   performGC-  before <- getRTSStats+  -- The thread's allocation counter is current even if the frame never+  -- fills the nursery; RTSStats.allocated_bytes only catches up at a GC.+  before <- getAllocationCounter   _ <- runFrame ctx benchInput ui-  after <- getRTSStats-  pure (fromIntegral (allocated_bytes after - allocated_bytes before) :: Integer)+  after <- getAllocationCounter+  pure (fromIntegral (before - after))  main :: IO () main = do-  let scenes = [("burst4096", idBurst), ("scopedWidgets", scopedWidgets)]-  forM_ scenes $ \(name, ui) -> do-    alloc <- measureFrameAlloc ui-    when (alloc > 0) $ do-      putStrLn ("FAIL: " ++ name ++ " allocated " ++ show alloc ++ " bytes during runFrame")+  -- Each scene against the same nodes without the ids: issuing ids+  -- allocates nothing, so a boxed id cursor (16 bytes or more an id) trips+  -- this.+  let scenes = [("burst4096", idBurst, column (pure ())), ("scopedWidgets", scopedWidgets, rows (pure ()))]+  forM_ scenes $ \(name, ui, base) -> do+    extra <- (-) <$> frameAlloc ui <*> frameAlloc base+    when (extra > 1024) $ do+      putStrLn ("FAIL: " ++ name ++ " allocated " ++ show extra ++ " bytes more than the same nodes without ids")       exitFailure+  ctxs <- mapM (\(_, ui, _) -> warmContext ui) scenes   defaultMain     [ bgroup         "id/nextId"-        [ bench name $ whnfIO $ do-            ctx <- newContext-            void (runFrame ctx benchInput ui)-        | (name, ui) <- scenes+        [ bench name $ whnfIO (void (runFrame ctx benchInput ui))+        | ((name, ui, _), ctx) <- zip scenes ctxs         ]     ]
examples/Profile.hs view
@@ -1,14 +1,21 @@ module Main (main) where  import Control.Exception (evaluate)-import Control.Monad (forM_, replicateM_, void)+import Control.Monad (forM, forM_, replicateM_, void, when)+import Data.ByteString (ByteString) import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef) import Data.Text (Text) import Data.Text qualified as T+import Data.Foldable (toList) import Data.Primitive.SmallArray (SmallArray) import NanoUI+import NanoUI.Backend (applyMouseButton, buttonsFromList, emptyInput, inputKeysFromList, monospaceMetrics)+import NanoUI.Path qualified as P import NanoUI.Svg (rasterizeSvg)-import NanoUI.Testing (newContext, runFrame)+import NanoUI.Testing (newContext, runFrame, setDrawReuse, uiCursorKind)+import NanoUI.Widgets.Custom (CustomWidgetSpec (..), DrawOp, customWidget, defaultCustomWidgetSpec, runCanvasFor)+import NanoUI.Widgets.TextDocument (TextDocument, textDocument)+import GHC.Clock (getMonotonicTime) import System.Environment (getArgs) import System.IO.Unsafe (unsafePerformIO) @@ -16,6 +23,48 @@ iterations :: Int iterations = 3000 +-- | A floating window above @n@ rows of a scroll area.+windowScene :: Int -> NanoUI ()+windowScene n = columnWith (fillW . fillH) $ do+  void $ scroll2DWith (fillW . fillH) $ columnWith (tight . fillW) $+    forM_ [1 .. n] $ \i -> rowWith (tight . fillW) $ do+      label (T.pack ("row " <> show i))+      void (button (T.pack ("b" <> show i)))+  floatingWindow (constVar True) "Tools" $ columnWith (tight . gap 4 . minW 200) $ do+    label "a floating window"+    void (button "ok")++-- | @n@ rows of a label, a checkbox and a button in a scroll area, with a+-- text field on top: a large arena for the pointer to move over.+pointerScene :: Int -> NanoUI ()+pointerScene n = columnWith (fillW . fillH) $ do+  textInput (constVar "")+  void $ scrollWith (fillW . fillH) $ columnWith (tight . fillW) $+    forM_ [1 .. n] $ \i -> rowWith (tight . fillW) $ do+      label (T.pack ("row " <> show i))+      checkbox "c" (constVar False)+      void (button (T.pack ("b" <> show i)))++-- | 60 rows of 5 to 154 grow columns, with content widths up to 40 pixels+-- and grow weights of 0.5 to 3 from a fixed pseudo-random sequence, under a+-- label that changes every frame so the layout is solved again. Sharing a+-- row's space locks the columns whose content outgrows their share, and in+-- about one row in four that takes more than two passes.+growScene :: Int -> NanoUI ()+growScene frame = columnWith (tight . gap 0 . fillW . fillH) $ do+  label (T.pack (show frame))+  forM_ (take 60 (iterate (lcg . lcg . lcg) 7)) $ \seed ->+    rowWith (tight . gap 0 . fillW) $ forM_ (growRow seed) $ \(c, g) ->+      columnWith (tight . growW g) (spacer (Fixed c) (Fixed 1))+ where+  lcg x = (x * 1103515245 + 12345) `mod` 2147483648 :: Int+  growRow seed =+    let k = 5 + seed `mod` 150+        xs = take (2 * k) (drop 1 (iterate lcg seed))+     in [(fromIntegral (a `mod` 4000) / 100, [1, 2, 3, 0.5] !! (b `mod` 4)) | (a, b) <- pairs xs]+  pairs (a : b : r) = (a, b) : pairs r+  pairs _ = []+ -- | A grid of buttons and labels: the ordinary widget path. widgetScene :: NanoUI () widgetScene =@@ -28,10 +77,29 @@         label "nano-ui profile loop"     ) +-- | 200 short paragraphs in a scroll area, full-width and capped at a width+-- they stay under in turn: the rich text path, whose paragraphs are laid out+-- again only when their width or pieces change.+richTextScene :: NanoUI ()+richTextScene = void $ scrollWith (fillW . fillH) $ columnWith (tight . fillW) $+  forM_ [1 .. 200 :: Int] $ \i ->+    richTextWith+      (if even i then fillW else maxW 290)+      [ inlineText ("Paragraph " <> T.pack (show i) <> " mixes ")+      , strong "bold"+      , " and "+      , emphasis "italic"+      , " text with "+      , inlineCode "code"+      , " and a "+      , hyperlink "x" "link"+      , " in one wrapped line of prose that is long enough to wrap onto a few lines at most widths."+      ]+ -- | A thousand rects: enough ops that building them costs more than replaying -- them, which is the case a content key is for. canvasOps :: CustomDrawContext -> Rect -> SmallArray DrawOp-canvasOps cdc (Rect x y w h) = runCanvas $ do+canvasOps cdc (Rect x y w h) = runCanvasFor cdc $ do   let side = 32 :: Int       cw = w / fromIntegral side       ch = h / fromIntegral side@@ -64,24 +132,84 @@   void $     customWidget       defaultCustomWidgetSpec-        { widgetLayout = fixedWH 512 512 defaultLayout+        { widgetLayout = fixedWH 512 512         , widgetContent = key         , widgetDraw = countedCanvasOps         } +-- | Path counterpart of 'canvasOps': 64 filled circles and 64 stroked+-- rounded rects, then, rotated by @turn@, a star (ear-clip triangulated) and+-- a 400-point polyline.+pathOps :: Float -> CustomDrawContext -> Rect -> SmallArray DrawOp+pathOps turn cdc (Rect x y w h) = runCanvasFor cdc $ do+  let accent = themeAccent (cdcTheme cdc)+      ink = styleFg (themePanel (cdcTheme cdc))+      c = V2 (x + w / 2) (y + h / 2)+      star = [V2 (x + w / 2 + r * cos a) (y + h / 2 + r * sin a) | k <- [0 .. 19 :: Int], let a = pi * fromIntegral k / 10; r = if even k then 200 else 90]+      wave = [V2 (x + fromIntegral k * w / 400) (y + h / 2 + 60 * sin (fromIntegral k / 12)) | k <- [0 .. 399 :: Int]]+  forM_ [0 .. 7 :: Int] $ \i -> forM_ [0 .. 7 :: Int] $ \j -> do+    let cx = x + 32 + fromIntegral i * 60+        cy = y + 32 + fromIntegral j * 60+    drawPath (P.circle (V2 cx cy) 20) accent+    drawStrokePath (P.roundedRect (Rect (cx - 25) (cy - 25) 50 50) 8) 2 ink+  withTransform (P.rotateAround c turn) $ do+    drawPath (P.polygon star) accent+    drawStrokePath (P.polyline wave) 3 ink++-- | A custom widget that builds 'pathOps' every frame, rotated a little more+-- each time so every frame also repaints.+pathScene :: NanoUI ()+pathScene =+  void $+    customWidget+      defaultCustomWidgetSpec+        { widgetLayout = fixedWH 512 512+        , widgetDraw = countedPathOps+        }++{-# NOINLINE countedPathOps #-}+countedPathOps :: CustomDrawContext -> Rect -> SmallArray DrawOp+countedPathOps cdc rect = unsafePerformIO $ do+  modifyIORef' buildCount (+ 1)+  n <- readIORef buildCount+  pure (pathOps (fromIntegral n * 0.01) cdc rect)+ -- | A focused text area over a long document, typing into its middle: the -- editor path, whose per-frame cost must not grow with the document.-textAreaScene :: IORef Text -> NanoUI ()-textAreaScene ref = column $ do-  txt <- textAreaWith grow =<< uiIO (readIORef ref)-  uiIO (writeIORef ref txt)+textAreaScene :: Var TextDocument -> NanoUI ()+textAreaScene doc = column (textAreaDocumentWith grow doc) -clockIcon :: Text+-- | 'textAreaScene' over 'Text', which joins the document on every frame+-- that edits it.+textAreaTextScene :: Var Text -> NanoUI ()+textAreaTextScene txt = column (textAreaWith grow txt)++-- | 200 keyed rows of a label, a text field, a slider and a checkbox, each+-- holding its own state. Returns row 1's slider and checkbox, and counts view+-- passes in @passes@.+formScene :: IORef Int -> NanoUI (Response, Response)+formScene passes = do+  liftIO (modifyIORef' passes (+ 1))+  rows <- scrollWith (fillW . fillH) $ columnWith (tight . fillW) $+    forM [1 .. 200 :: Int] $ \i -> withKey i $ rowWith (tight . fillW) $ do+      t <- useVar ("" :: Text)+      v <- useVar (50 :: Float)+      c <- useVar False+      label (T.pack ("row " <> show i))+      textInput t+      sr <- sliderWith' (fixedW 160) 0 100 v+      cr <- checkbox' "on" c+      pure (sr, cr)+  case rows of+    r : _ -> pure r+    [] -> pure (mempty, mempty)++clockIcon :: ByteString clockIcon =   "<svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'>\   \<circle cx='12' cy='12' r='10'/><path d='M12 6v6l4 2'/></svg>" -starIcon :: Text+starIcon :: ByteString starIcon =   "<svg viewBox='0 0 24 24'><path fill='#e0a030' d='M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z'/></svg>" @@ -92,6 +220,18 @@ main = do   args <- getArgs   ctx <- newContext+  -- Frames here repeat one scene: time their paint instead of reusing it.+  setDrawReuse ctx False+  let+    -- Focus the text area, move 5,000 lines down and type 1,000 characters.+    typeIntoMiddle scene = do+      let inp = emptyInput {inputWindowSize = Size 800 600}+          frame i = void (runFrame ctx i scene)+      frame inp+      frame inp {inputKeys = inputKeysFromList [KeyTab]}+      replicateM_ 50 (frame inp {inputKeys = inputKeysFromList (replicate 100 KeyDown)})+      forM_ (take 1000 (cycle "typing into the middle ")) $ \c ->+        frame inp {inputChars = T.singleton c}   case args of     ("svg" : _) -> do       -- A stroked icon with round caps and joins and a filled one, at a small@@ -106,26 +246,159 @@               void (evaluate (rasterizeSvg (16 + i `mod` 2) 16 white doc))               void (evaluate (rasterizeSvg (128 + i `mod` 2) 128 white doc))       putStrLn "profiled 1000 rasterizations of two icons at 16 and 128 px"+    ("canvas-paths-build" : _) -> do+      -- Build 'pathOps' with no frame around it, timing the ops alone.+      let cdc = CustomDrawContext False False False False False defaultTheme (monospaceMetrics 16)+      forM_ [1 .. iterations] $ \i ->+        mapM_ evaluate (toList (pathOps (fromIntegral i * 0.01) cdc (Rect 0 0 512 512)))+      putStrLn ("built " ++ show iterations ++ " path scenes")+    ("window" : rest) -> do+      -- A floating window over 3000 rows of a scroll area, held still or,+      -- with "drag", dragged back and forth by its title bar.+      let inp = emptyInput {inputWindowSize = Size 1280 800, inputMousePos = V2 5 790, inputDeltaTime = 0.016}+          drag = rest == ["drag"]+          ui = windowScene 3000+          grab = V2 1014 22+      replicateM_ 5 (void (runFrame ctx inp ui))+      when drag $+        void (runFrame ctx (applyMouseButton MouseLeft True inp {inputMousePos = grab}) ui)+      forM_ [1 .. 300 :: Int] $ \i -> do+        let V2 gx gy = grab+            step = inp {inputMousePos = V2 (gx - 100 + fromIntegral (i `mod` 2) * 6) (gy + 50), inputButtonsHeld = buttonsFromList [MouseLeft]}+        void (runFrame ctx (if drag then step else inp) ui)+      putStrLn ("profiled 300 window frames" ++ if drag then ", dragging" else "")+    ("pointer" : _) -> do+      -- The pointer sweeping down over 3000 rows, pressing and releasing+      -- every tenth frame, with the cursor queried each frame as a backend+      -- does: hover, press and cursor hit tests over a large arena.+      let inp = emptyInput {inputWindowSize = Size 1280 800, inputDeltaTime = 0.016}+          ui = pointerScene 3000+          at i = inp {inputMousePos = V2 (fromIntegral (40 + (i * 7) `mod` 200)) (fromIntegral (40 + (i * 13) `mod` 740))}+          frames = 2000 :: Int+      replicateM_ 5 (void (runFrame ctx inp ui))+      cursorTime <- newIORef 0+      t0 <- getMonotonicTime+      forM_ [1 .. frames] $ \i -> do+        let base = at i+            fi = case i `mod` 10 of+              0 -> applyMouseButton MouseLeft True base+              1 -> applyMouseButton MouseLeft False base+              _ -> base+        void (runFrame ctx fi ui)+        c0 <- getMonotonicTime+        void (evaluate =<< uiCursorKind ctx fi)+        c1 <- getMonotonicTime+        modifyIORef' cursorTime (+ (c1 - c0))+      t1 <- getMonotonicTime+      ct <- readIORef cursorTime+      let perFrame t = show (t * 1000 / fromIntegral frames) ++ " ms"+      putStrLn ("profiled " ++ show frames ++ " pointer frames: " ++ perFrame (t1 - t0) ++ "/frame, cursor query " ++ perFrame ct)+    ("grow" : _) -> do+      let inp = emptyInput {inputWindowSize = Size 1280 800, inputDeltaTime = 0.016}+          frames = 2000 :: Int+      replicateM_ 5 (void (runFrame ctx inp (growScene 0)))+      t0 <- getMonotonicTime+      forM_ [1 .. frames] $ \i -> void (runFrame ctx inp (growScene i))+      t1 <- getMonotonicTime+      putStrLn ("profiled " ++ show frames ++ " grow frames: " ++ show ((t1 - t0) * 1000 / fromIntegral frames) ++ " ms/frame")+    ("richtext" : rest) -> do+      -- 'richTextScene' with the pointer on a paragraph every other frame and+      -- off the window in between, so a paragraph is drawn again every frame+      -- at an unchanged width; with "resize" the window's width changes every+      -- frame as well.+      let resize = rest == ["resize"]+          frames = 1000 :: Int+          inp i =+            emptyInput+              { inputWindowSize = Size (if resize then 600 + fromIntegral (i `mod` 50) * 4 else 800) 800+              , inputDeltaTime = 0.016+              , inputMousePos = if even i then V2 40 (fromIntegral (20 + (i * 7) `mod` 760)) else V2 (-10) (-10)+              }+      replicateM_ 5 (void (runFrame ctx (inp 0) richTextScene))+      t0 <- getMonotonicTime+      forM_ [1 .. frames] $ \i -> void (runFrame ctx (inp i) richTextScene)+      t1 <- getMonotonicTime+      putStrLn ("profiled " ++ show frames ++ " richtext frames" ++ (if resize then ", resizing" else "") ++ ": " ++ show ((t1 - t0) * 1000 / fromIntegral frames) ++ " ms/frame")+    ("dropdowns" : _) -> do+      -- An open select of 200 options, then a focused combo box of the same+      -- options, each with the pointer moving down its rows for 1000 frames.+      sel <- newVar (0 :: Int)+      txt <- newVar ""+      let inp = emptyInput {inputWindowSize = Size 1280 800, inputDeltaTime = 0.016}+          opts = [T.pack ("option " <> show i) | i <- [1 .. 200 :: Int]]+          ui = columnWith (gap 8) ((,) <$> selectWith' (fixedW 200) opts sel <*> comboBox' "pick" opts txt)+          centre r = let Rect x y w h = respRect r in V2 (x + w / 2) (y + h / 2)+          click p = do+            _ <- runFrame ctx (applyMouseButton MouseLeft True inp {inputMousePos = p}) ui+            void (runFrame ctx (applyMouseButton MouseLeft False inp {inputMousePos = p}) ui)+          sweep (V2 x y) = forM_ [1 .. 1000 :: Int] $ \i ->+            runFrame ctx inp {inputMousePos = V2 x (y + 30 + fromIntegral (i `mod` 300))} ui+      replicateM_ 3 (void (runFrame ctx inp ui))+      ((selR, comboR), _, _) <- runFrame ctx inp ui+      click (centre selR)+      sweep (centre selR)+      _ <- runFrame ctx (inp {inputKeys = inputKeysFromList [KeyEscape], inputKeysNew = inputKeysFromList [KeyEscape]}) ui+      click (centre comboR)+      sweep (centre comboR)+      putStrLn "profiled 2000 open-dropdown frames"+    ("form" : _) -> do+      -- Tab into row 1's field and type 500 characters, drag row 1's slider+      -- for 500 frames, then click its checkbox 100 times. After each input,+      -- frames run until the view settles, as a session loop would.+      passes <- newIORef (0 :: Int)+      frames <- newIORef (0 :: Int)+      let inp = emptyInput {inputWindowSize = Size 1280 800, inputDeltaTime = 0.016}+          ui = formScene passes+          frame i = do+            modifyIORef' frames (+ 1)+            (r, _, dirty) <- runFrame ctx i ui+            pure (r, dirty)+          settle i = do+            (r, dirty) <- frame i+            let idle = i {inputChars = "", inputKeys = mempty, inputKeysNew = mempty, inputButtonsPressed = mempty, inputButtonsReleased = mempty}+                go 0 = pure ()+                go k = do (_, d) <- frame idle; when d (go (k - 1 :: Int))+            when dirty (go 8)+            pure r+      -- The first frame has laid nothing out yet, so its rects are empty.+      (slider0, check0) <- settle inp >> settle inp+      _ <- settle inp {inputKeys = inputKeysFromList [KeyTab], inputKeysNew = inputKeysFromList [KeyTab]}+      writeIORef passes 0 >> writeIORef frames 0+      forM_ (take 500 (cycle "typing ")) $ \c -> settle inp {inputChars = T.singleton c}+      let at (V2 x y) dx = inp {inputMousePos = V2 (x + dx) y}+          centre r = let Rect x y w h = respRect r in V2 (x + w / 2) (y + h / 2)+      _ <- settle (applyMouseButton MouseLeft True (at (centre slider0) 0))+      forM_ [1 .. 500 :: Int] $ \i -> settle (at (centre slider0) (if even i then 30 else -30)) {inputButtonsHeld = buttonsFromList [MouseLeft]}+      _ <- settle (applyMouseButton MouseLeft False (at (centre slider0) 0))+      forM_ [1 .. 100 :: Int] $ \_ -> do+        _ <- settle (applyMouseButton MouseLeft True (at (centre check0) 0))+        settle (applyMouseButton MouseLeft False (at (centre check0) 0))+      n <- readIORef passes+      f <- readIORef frames+      putStrLn ("profiled form: " ++ show f ++ " frames, " ++ show n ++ " view passes")     ("textarea" : _) -> do-      ref <- newIORef longDocument-      let inp = emptyInput {inputWindowSize = Size 800 600}-          frame i = void (runFrame ctx i (textAreaScene ref))-      frame inp-      frame inp {inputKeys = inputKeysFromList [KeyTab]}-      replicateM_ 50 (frame inp {inputKeys = inputKeysFromList (replicate 100 KeyDown)})-      forM_ (take 1000 (cycle "typing into the middle ")) $ \c ->-        frame inp {inputChars = T.singleton c}+      doc <- newVar (textDocument longDocument)+      typeIntoMiddle (textAreaScene doc)       putStrLn "profiled 1000 textarea keystroke frames"+    ("textarea-text" : _) -> do+      txt <- newVar longDocument+      typeIntoMiddle (textAreaTextScene txt)+      putStrLn "profiled 1000 textarea-text keystroke frames"     _ -> do       let inp =             emptyInput               { inputWindowSize = Size 800 600               , inputMousePos = V2 400 300-              , inputMouseDown = True+              , inputButtonsHeld = buttonsFromList [MouseLeft]               }           (name, ui) = case args of             ("canvas" : _) -> ("canvas", canvasScene 0)             ("canvas-keyed" : _) -> ("canvas-keyed", canvasScene 1)+            ("canvas-paths" : _) -> ("canvas-paths", pathScene)+            -- A still frame of 1000 custom widgets, against 1000 buttons:+            -- what a custom widget costs per frame beyond a built-in one.+            ("knobs" : _) -> ("knobs", gridWith 40 (gap 2) (replicateM_ 1000 (void (withValue 50 (knob' 0 100)))))+            ("buttons" : _) -> ("buttons", gridWith 40 (gap 2) (replicateM_ 1000 (void (button' "OK"))))             _ -> ("widgets", widgetScene)       replicateM_ iterations (void (runFrame ctx inp ui))       builds <- readIORef buildCount
lib/NanoUI.hs view
@@ -5,1195 +5,1274 @@ -- License     : MIT -- Maintainer  : zacharyachurchill@gmail.com ----- A view is a function that runs every frame. Widgets are ordinary calls:--- each one lays itself out, reads this frame's input, and returns what the--- user did. There are no widget objects to keep and no callbacks to register.------ @--- counter :: NanoUI ()--- counter = do---   (n, setN) <- useInt 0---   row $ do---     whenM (button "-") (setN (n - 1))---     label (T.pack (show n))---     whenM (button "+") (setN (n + 1))--- @------ Run a view with a backend: @runSdlApp@ from @nano-ui-sdl@ or @runRgfwApp@--- from @nano-ui-rgfw@.------ = Conventions------ * Widgets return what you usually need: 'Bool' for buttons and menu items,---   the new value for inputs, and @()@ for text and decoration.--- * A primed name also returns the widget's 'Response', for hover state,---   geometry, tooltips, and change or submit flags: @button'@, @slider'@.--- * Inputs are controlled. Pass the current value and keep the result; a---   change you do not store is undone on the next frame. Editing state such---   as the caret, a drag in progress, or an open dropdown stays inside the---   widget.--- * Layout arguments are modifiers, as in @buttonWith (fixedW 120)@ or---   @columnWith (gap 8 . padAll 12)@. Widgets with more options take a---   configuration record: 'textInputConfigured', 'tabsConfigured'.------ = State------ Keep state in local hooks ('useInt', 'useText', 'useState'), in a model you--- pass down through the view, or in a reducer: "NanoUI.Emit" has widgets that--- emit messages, and the backends' reducer runners fold them into the model.-module NanoUI-  ( -- * Views-    NanoUI-  , Ui-  , runUi-  , runNanoUI-  , uiIO-  , whenM-  , unlessM-  , ifM-  , windowSize-  , windowWidth-  , windowHeight-  , uiMousePos--    -- * Widget identity--    -- | Every widget and hook takes the next 'WidgetId' in its container:-    -- ids count up in call order among siblings, and a container starts a-    -- new count for its children. Widget state is stored under that id, so-    -- the same widgets and hooks must run in the same order every frame.-    ---    -- A widget that runs on some frames and not others moves the ids of the-    -- siblings after it. Put the conditional part inside 'scope', which takes-    -- one id whether or not its body adds anything. For a list whose items-    -- are added, removed or reordered, run each item under 'withKey' (or-    -- 'keyed') with a key unique among its siblings, so the item's state-    -- follows its key instead of its position.-  , scope-  , keyed-  , keyedTag-  , withKey-  , nextId-  , currentId-  , burstNextIds-  , WidgetId (..)-  , IdContext-  , initialIdContext-  , widgetId-  , hashWidgetId-  , mix64-  , mixFnv--    -- * Responses-  , Response (..)-  , HasResponse (..)-  , respId-  , respRect-  , respHovered-  , respPressed-  , respClicked-  , respChanged-  , respSubmitted-  , respRightPressed-  , respRightClicked-  , setChanged-  , setClicked-  , setSubmitted--    -- * Containers-  , row-  , rowWith-  , column-  , columnWith-  , hstack-  , vstack-  , grid-  , gridWith-  , panel-  , panelWith-  , card-  , callout-  , calloutWith-  , toolbar-  , center-  , responsive-  , responsiveRowCol-  , scroll-  , scrollWith-  , scroll2D-  , scroll2DWith-  , scrollArea-  , scrollArea2D-  , separator-  , spacer-  , flex--    -- * Text-  , label-  , label'-  , labelWith-  , labelWith'-  , heading-  , muted-  , mono-  , danger-  , bold-  , italic-  , underline-  , kv-  , kvMono-  , kvBlock-  , selectableText-  , selectableText'-  , selectableTextWith-  , selectableTextWith'--    -- * Buttons and menus-  , button-  , button'-  , buttonWith-  , buttonWith'-  , menuButton-  , menuButton'-  , menuItem-  , menuItem'-  , menuItemShortcut-  , menuItemDisabled-  , menuSeparator-  , menuHeader-  , contextMenu-  , contextMenuArea-  , useContextMenu--    -- * Inputs-  , checkbox-  , checkbox'-  , toggleSwitch-  , toggleSwitch'-  , toggleSwitchWith-  , toggleSwitchWith'-  , radio-  , radio'-  , boundedRadio-  , boundedRadio'-  , enumRadio-  , enumRadio'-  , select-  , select'-  , selectWith-  , selectWith'-  , boundedSelect-  , boundedSelect'-  , enumSelect-  , enumSelect'-  , slider-  , slider'-  , sliderWith-  , sliderWith'-  , knob-  , knob'-  , knobWith-  , knobWith'-  , TextInputConfig (..)-  , defaultTextInputConfig-  , textInput-  , textInput'-  , textInputConfigured-  , textInputConfigured'-  , NumericInputConfig (..)-  , defaultNumericInputConfig-  , numericInput-  , numericInput'-  , numericInputConfigured-  , numericInputConfigured'-  , SearchFieldConfig (..)-  , defaultSearchFieldConfig-  , searchField-  , searchField'-  , searchFieldConfigured-  , searchFieldConfigured'-  , comboBox-  , comboBox'-  , textArea-  , textArea'-  , textAreaWith-  , textAreaWith'-  , colorPicker-  , colorPicker'-  , colorPickerRGBA-  , colorPickerRGBA'-  , colorToHex-  , colorToHexA-  , colorFromHex--    -- * Text editing-    -- | Text fields change their text only through 'TextCommand's. Keys run-    -- them (Backspace is @'Delete' 'CharLeft'@, Ctrl+Z is 'Undo'), the-    -- right-click menu runs them, and an app can run them on a field by its-    -- id:-    ---    -- @-    -- (resp, body') <- 'textArea'' body-    -- canUndo <- 'textCanUndo' ('respId' resp)-    -- 'whenM' ('menuItem' \"Undo\") ('runTextCommand' ('respId' resp) 'Undo')-    -- 'whenM' ('menuItem' \"Insert date\") ('runTextCommand' ('respId' resp) ('InsertText' today))-    -- @-    ---    -- Every command that changes text is recorded for undo. Typing joins one-    -- undo step per word and deleting one per run; the steps keep the edits-    -- themselves, not copies of the document, so a long history of a large-    -- document stays small. Replacing the value a field is passed clears its-    -- history.-  , TextCommand (..)-  , TextMotion (..)-  , Cursor (..)-  , runTextCommand-  , textCanUndo-  , textCanRedo--    -- * Tabs, trees, and tables-  , Tab (..)-  , TabStyle (..)-  , TabOrientation (..)-  , TabResponse (..)-  , TabsConfig (..)-  , defaultTabsConfig-  , tab-  , closableTab-  , tabs-  , tabs'-  , tabsConfigured-  , tabsConfigured'-  , tabBar-  , tabBar'-  , tabBarConfigured-  , tabBarConfigured'-  , TreeItem (..)-  , tree-  , tree'-  , SortDir (..)-  , SortCol (..)-  , ColSize (..)-  , TableConfig (..)-  , TableResponse (..)-  , defaultTableConfig-  , table-  , tableWith-  , tableConfigured-  , simpleTable-  , useTableSort-  , tableHiddenIndices-  , sortRows-  , Colonnade-  , Headed (..)-  , headed-  , headless--    -- * Overlays-  , modal-  , window-  , PopupAnchor (..)-  , PopupPlacement (..)-  , PopupConfig (..)-  , defaultPopupConfig-  , popup-  , popupWith-  , tooltip-  , tooltipAt-  , tooltipWidget-  , withTooltip--    -- * Pane grids-  , PaneGridConfig (..)-  , defaultPaneGridConfig-  , PaneGridCtx (..)-  , PaneView (..)-  , PaneGridResponse (..)-  , GridAxis (..)-  , paneGrid--    -- * Progress and sparklines-  , progressBar-  , progressBar'-  , progressBarWith-  , progressBarWith'-  , circularProgress-  , circularProgress'-  , circularProgressWith-  , circularProgressWith'-  , spinner-  , spinner'-  , spinnerWith-  , spinnerWith'-  , Inline-  , inlineText-  , inlineWith-  , restyle-  , strong-  , emphasis-  , inlineCode-  , hyperlink-  , richText-  , richText'-  , richTextWith-  , richTextWith'-  , sparkline-  , sparkline'-  , sparklineWith-  , sparklineWith'--    -- * Images and drawing-  , ImageId (..)-  , image-  , image'-  , freshImageId-  , registerImageRgba-  , Svg-  , parseSvg-  , loadSvg-  , svgIcon-  , svgIconWith-  , svgIconWith'-  , svgSize-  , box-  , drawing-  , drawingVersioned-  , drawingCached-  , DrawOp (..)-  , TextFont (..)-  , defaultTextFont-  , DrawingBuild-  , drawTextBox-  , shiftDrawOp--    -- * Custom widgets-  , CustomWidgetSpec (..)-  , defaultCustomWidgetSpec-  , customWidget-  , customWidgetWithId-  , contentKey-  , CustomDrawContext (..)-  , CustomMeasureFn-  , CustomDrawBuild-  , CanvasM-  , runCanvas-  , canvas-  , drawRect-  , drawRoundedRect-  , drawCircle-  , drawStroke-  , drawStrokeRoundedRect-  , drawStrokeCircle-  , drawStrokeAA-  , drawQuadGradient-  , drawLinearGradientH-  , drawLinearGradientV-  , drawImage-  , drawImageUV-  , drawText-  , useDrag2D-  , Drag2D (..)-  , useWheelDelta--    -- * Drag and drop-  , DropType (..)-  , DropEvent (..)-  , emptyDropEvents-  , DropTarget (..)-  , useDrop-  , dropZone--    -- * Local state-  , useState-  , useFlag-  , useToggle-  , useInt-  , useFloat-  , useEnum-  , useText--    -- * Scrolling--    -- | A scroll container ('scroll', 'scroll2D') handles the wheel and its-    -- own scrollbars. These move one from the outside, keyed by the-    -- 'WidgetId' that 'scrollArea' and 'scrollArea2D' hand back.-    ---    -- How far the wheel goes, and whether a scroll glides onto its target-    -- instead of jumping, is one setting for the whole app:-    ---    -- @-    -- 'setScrollTuning' ctx 'defaultScrollTuning'-    --   { 'scrollWheelStep' = 3 * rowHeight  -- three rows a notch-    --   , 'scrollSmoothTime' = 0.12          -- glide onto it-    --   }-    -- @-    ---    -- 'setScrollStep' gives one list a step of its own. With a glide time-    -- set, every wheel notch and every 'ScrollSmooth' command eases onto its-    -- target over that many seconds, and the frame loop keeps drawing until-    -- it lands.-    ---    -- 'scrollIntoView' brings a widget inside the scroller into view: the row-    -- a keyboard selection just moved to, say. A list that only builds the-    -- rows it shows has no widget to point at for the rest, so scroll to-    -- where the row would be with 'scrollRectIntoView', whose rectangle is in-    -- content coordinates. 'getScrollMetrics' reports the viewport, range and-    -- offset such a list needs to pick its visible rows in the first place.-  , ScrollTuning (..)-  , defaultScrollTuning-  , getScrollTuning-  , setScrollTuning-  , getScrollStep-  , setScrollStep-  , ScrollMetrics (..)-  , ScrollAxes (..)-  , getScrollMetrics-  , ScrollBehavior (..)-  , ScrollAlign (..)-  , scrollTo-  , scrollBy-  , scrollPages-  , scrollToStart-  , scrollToEnd-  , scrollIntoView-  , scrollRectIntoView-  , scrollGliding-  , getScrollOffset-  , setScrollOffset-  , getScrollOffset2D-  , setScrollOffset2D--    -- * Animation-  , Transition (..)-  , animate-  , animateTo-  , animateToA-  , pulse-  , keepAnimating-  , Animatable (..)-  , Ease (..)-  , applyEase-  , SpringParams (..)-  , presetBouncy-  , presetSmooth-  , presetStiff--    -- * Layout-  , Layout (..)-  , LayoutModifier-  , Sizing (..)-  , Direction (..)-  , AlignX (..)-  , AlignY (..)-  , Padding (..)-  , defaultLayout-  , askDefaultLayout-  , withDefaultLayout-  , padAll-  , padXY-  , gap-  , fillW-  , fillH-  , grow-  , minW-  , maxW-  , fixedW-  , minH-  , maxH-  , fixedH-  , fixedWH-  , alignMid-  , alignEnd-  , alignStart-  , alignCenter-  , alignTop-  , alignBottom-  , alignBaseline-  , tight-  , percent-  , gridMinColW-  , gridCols-  , fixedAspectW-  , fixedAspectH--    -- * Text style-  , FontVariant (..)-  , FontWeight (..)-  , FontStyle (..)-  , TextDecoration (..)-  , fontRegular-  , fontHeading-  , fontMuted-  , fontMono-  , fontDanger-  , fontSize-  , fontSizeScale-  , fontColor-  , fontWeight-  , fontBold-  , fontLight-  , fontMedium-  , fontSemiBold-  , fontExtraBold-  , fontBlack-  , fontStyle-  , fontItalic-  , fontOblique-  , textDecoration-  , fontUnderline-  , fontStrike--    -- * Styling-    -- | A 'Theme' says how every kind of widget looks: a 'Style' for each-    -- surface (buttons, inputs, panels, floating windows) and colours for-    -- accents, text selection, links and so on. The context holds one theme-    -- for the whole app ('setTheme'); 'styled' changes it for part of the-    -- view. Style and theme modifiers compose with @(.)@ like layout-    -- modifiers do:-    ---    -- @-    -- toolbar = 'styled' ('subtle' . 'buttonStyle' ('cornerRadius' 6)) $ 'row' $ do-    --   'whenM' ('button' \"Open\") openFile-    --   'styled' 'primary' ('whenM' ('button' \"Save\") save)-    -- @-    ---    -- Scopes nest, and each one modifies the theme around it, so a modifier-    -- written once ('primary', 'destructive', or one of your own) works in any-    -- theme. 'uiTheme' reads the theme where it is called.-    ---    -- 'disabledWhen' switches the widgets inside it off: they keep their-    -- layout and state, take no input, and fade toward the window colour.-  , styled-  , themed-  , disabledWhen-  , uiTheme-    -- ** Style modifiers-  , background-  , foreground-  , borderColor-  , borderWidth-  , cornerRadius-  , hoverBackground-  , pressBackground-  , fillColor-    -- ** Theme modifiers-  , buttonStyle-  , inputStyle-  , panelStyle-  , windowStyle-  , everyStyle-  , accentColor-  , textColor-  , mutedColor-  , linkColor-  , selectionColor-  , windowColor-  , rounded-  , primary-  , destructive-  , success-  , subtle-  , tinted-  , readableOn-  , disabledTheme--    -- * Themes-  , Theme (..)-  , Style (..)-  , defaultTheme-  , tomorrowNightMinDarkTheme-  , tomorrowMinLightTheme-  , tomorrowMidnightMinDarkTheme-  , Base16 (..)-  , themeFromBase16-  , themeFromBase16Dark-  , themeFromBase16Light-  , base16TomorrowNight-  , base16TomorrowLight-  , withTheme-  , setTheme-  , getTheme-  , setUiTheme-  , themeSeries-  , scrollBarTrackColor-  , scrollBarThumbColor--    -- * Geometry and colour-  , V2 (..)-  , Rect (..)-  , Size (..)-  , Color (..)-  , colorRGBA-  , colorToWord32-  , colorLuminance-  , colorR-  , colorG-  , colorB-  , colorA-  , lerpColor-  , contrastRatio-  , rectContains-  , rectInflate-  , rectIntersect-  , rectUnion-  , v2Add-  , v2Sub-  , onGrid-  , roundHalfUp--    -- * Input-  , Input (..)-  , Key (..)-  , Modifiers (..)-  , emptyInput-  , inputInteracted-  , inputPointerHeld-  , appendInputKey-  , appendDropEvent-  , emptyInputKeys-  , inputKeysElem-  , inputKeysFromList-  , inputKeysNull-  , foldInputKeys--    -- * Damage-  , Damage (..)-  , DamageBounds (..)-  , defaultDamageSlop-  , sliderDamageSlop-  , haloDamageSlop-  , resolveDamageRect-  , damageWidgetNow-  , damageKeyNow-  , damageRectNow-  , damageGroupNow-  , damageFullNow--    -- * Backend support-  , FontMetrics (..)-  , FontBackend (..)-  , prepareFontMetrics-  , prepareFontMetricsMany-  , measureTextIO-  , lineWidthIO-  , lineWidth-  , drawShaped-  , drawGlyph-  , GlyphQuad (..)-  , ShapedText (..)-  , ShapedGlyphs (..)-  , scaleFontMetrics-  , monospaceMetrics-  , uiFontMetrics-  , widgetContentInset-  , widgetPadding-  , treeItemPadding-  , ScrollBarSlot (..)-  , scrollBarGutter-  , scrollBarWidth-  , windowPad-  , windowMargin-  , Compact-  , compactHost-  , askCompact-  )-where--import NanoUI.Animatable (Animatable (..))-import NanoUI.Animation-  ( SpringParams (..)-  , presetBouncy-  , presetSmooth-  , presetStiff-  )-import NanoUI.Compact (Compact, askCompact, compactHost)-import NanoUI.Context-  ( Ease (..)-  , ScrollAlign (..)-  , ScrollAxes (..)-  , ScrollBehavior (..)-  , ScrollMetrics (..)-  , ScrollTuning (..)-  , applyEase-  , defaultScrollTuning-  , getScrollMetrics-  , getScrollOffset-  , getScrollOffset2D-  , getScrollStep-  , getScrollTuning-  , getTheme-  , scrollBy-  , scrollGliding-  , scrollIntoView-  , scrollPages-  , scrollRectIntoView-  , scrollTo-  , scrollToEnd-  , scrollToStart-  , setScrollOffset-  , setScrollOffset2D-  , setScrollStep-  , setScrollTuning-  , setTheme-  , withTheme-  )-import NanoUI.Draw (TextFont (..), defaultTextFont, drawTextBox, shiftDrawOp)-import NanoUI.Font-  ( FontBackend (..)-  , FontMetrics (..)-  , GlyphQuad (..)-  , ShapedText (..)-  , ShapedGlyphs (..)-  , ScrollBarSlot (..)-  , drawGlyph-  , drawShaped-  , lineWidth-  , lineWidthIO-  , measureTextIO-  , monospaceMetrics-  , prepareFontMetrics-  , prepareFontMetricsMany-  , scaleFontMetrics-  , scrollBarGutter-  , scrollBarWidth-  , treeItemPadding-  , widgetContentInset-  , widgetPadding-  )-import NanoUI.Hooks (useEnum, useFlag, useFloat, useInt, useState, useText, useToggle)-import NanoUI.Id-  ( IdContext-  , WidgetId (..)-  , hashWidgetId-  , initialIdContext-  , mix64-  , mixFnv-  , widgetId-  )-import NanoUI.Input-  ( DropEvent (..)-  , DropType (..)-  , Input (..)-  , Key (..)-  , Modifiers (..)-  , appendInputKey-  , appendDropEvent-  , emptyDropEvents-  , emptyInput-  , emptyInputKeys-  , foldInputKeys-  , inputInteracted-  , inputKeysElem-  , inputKeysFromList-  , inputKeysNull-  , inputPointerHeld-  )-import NanoUI.Monad-  ( NanoUI-  , Ui-  , askDefaultLayout-  , burstNextIds-  , currentId-  , damageFullNow-  , disabledWhen-  , styled-  , themed-  , damageGroupNow-  , damageKeyNow-  , damageRectNow-  , damageWidgetNow-  , ifM-  , keyed-  , keyedTag-  , nextId-  , runNanoUI-  , runUi-  , scope-  , setUiTheme-  , uiFontMetrics-  , uiIO-  , uiMousePos-  , uiTheme-  , unlessM-  , whenM-  , windowHeight-  , windowSize-  , windowWidth-  , withDefaultLayout-  , withKey-  )-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Base16 (..)-  , Direction (..)-  , FontStyle (..)-  , FontVariant (..)-  , FontWeight (..)-  , Layout (..)-  , LayoutModifier-  , Padding (..)-  , Sizing (..)-  , Style (..)-  , TextDecoration (..)-  , Theme (..)-  , accentColor-  , background-  , borderColor-  , borderWidth-  , buttonStyle-  , cornerRadius-  , destructive-  , disabledTheme-  , everyStyle-  , fillColor-  , foreground-  , hoverBackground-  , inputStyle-  , linkColor-  , mutedColor-  , panelStyle-  , pressBackground-  , primary-  , readableOn-  , rounded-  , selectionColor-  , subtle-  , success-  , textColor-  , tinted-  , windowColor-  , windowStyle-  , alignBaseline-  , alignBottom-  , alignCenter-  , alignEnd-  , alignMid-  , alignStart-  , alignTop-  , base16TomorrowLight-  , base16TomorrowNight-  , defaultLayout-  , defaultTheme-  , fillH-  , fillW-  , fixedAspectH-  , fixedAspectW-  , fixedH-  , fixedW-  , fixedWH-  , fontBlack-  , fontBold-  , fontColor-  , fontDanger-  , fontExtraBold-  , fontHeading-  , fontItalic-  , fontLight-  , fontMedium-  , fontMono-  , fontMuted-  , fontOblique-  , fontRegular-  , fontSemiBold-  , fontSize-  , fontSizeScale-  , fontStrike-  , fontStyle-  , fontUnderline-  , fontWeight-  , gap-  , gridCols-  , gridMinColW-  , grow-  , maxH-  , maxW-  , minH-  , minW-  , padAll-  , padXY-  , percent-  , scrollBarThumbColor-  , scrollBarTrackColor-  , textDecoration-  , themeFromBase16-  , themeFromBase16Dark-  , themeFromBase16Light-  , themeSeries-  , tight-  , tomorrowMidnightMinDarkTheme-  , tomorrowMinLightTheme-  , tomorrowNightMinDarkTheme-  , windowMargin-  , windowPad-  )-import NanoUI.Svg (Svg, parseSvg, svgSize)-import NanoUI.Types-  ( Color (..)-  , Damage (..)-  , DamageBounds (..)-  , ImageId (..)-  , Rect (..)-  , Size (..)-  , V2 (..)-  , colorA-  , colorB-  , colorG-  , colorLuminance-  , colorR-  , colorRGBA-  , colorToWord32-  , contrastRatio-  , defaultDamageSlop-  , haloDamageSlop-  , lerpColor-  , onGrid-  , rectContains-  , rectInflate-  , rectIntersect-  , rectUnion-  , resolveDamageRect-  , roundHalfUp-  , sliderDamageSlop-  , v2Add-  , v2Sub-  )-import NanoUI.WidgetText (colorFromHex, colorToHex, colorToHexA)-import NanoUI.Widgets.Animate (Transition (..), animate, animateTo, animateToA, keepAnimating, pulse)-import NanoUI.Widgets.Button (button, button', buttonWith, buttonWith')-import NanoUI.Widgets.Checkbox (checkbox, checkbox')-import NanoUI.Widgets.ColorPicker (colorPicker, colorPicker', colorPickerRGBA, colorPickerRGBA')-import NanoUI.Widgets.Combo (comboBox, comboBox')-import NanoUI.Widgets.Custom-  ( CanvasM-  , CustomDrawBuild-  , CustomDrawContext (..)-  , CustomMeasureFn-  , CustomWidgetSpec (..)-  , Drag2D (..)-  , canvas-  , circularProgress-  , circularProgress'-  , circularProgressWith-  , circularProgressWith'-  , spinner-  , spinner'-  , spinnerWith-  , spinnerWith'-  , customWidget-  , customWidgetWithId-  , contentKey-  , defaultCustomWidgetSpec-  , drawCircle-  , drawImage-  , drawImageUV-  , drawLinearGradientH-  , drawLinearGradientV-  , drawQuadGradient-  , drawRect-  , drawRoundedRect-  , drawStroke-  , drawStrokeAA-  , drawStrokeCircle-  , drawStrokeRoundedRect-  , drawText-  , knob-  , knob'-  , knobWith-  , knobWith'-  , progressBar-  , progressBar'-  , progressBarWith-  , progressBarWith'-  , runCanvas-  , sparkline-  , sparkline'-  , sparklineWith-  , sparklineWith'-  , toggleSwitch-  , toggleSwitch'-  , toggleSwitchWith-  , toggleSwitchWith'-  , useDrag2D-  , useWheelDelta-  )-import NanoUI.Widgets.Display-  ( bold-  , box-  , card-  , danger-  , freshImageId-  , heading-  , image-  , image'-  , italic-  , kv-  , kvBlock-  , kvMono-  , mono-  , muted-  , registerImageRgba-  , loadSvg-  , svgIcon-  , svgIconWith-  , svgIconWith'-  , toolbar-  , underline-  )-import NanoUI.Widgets.Drawing (DrawOp (..), DrawingBuild, drawing, drawingCached, drawingVersioned)-import NanoUI.Widgets.Drop (DropTarget (..), dropZone, useDrop)-import NanoUI.Widgets.Layout-  ( callout-  , calloutWith-  , center-  , column-  , columnWith-  , flex-  , grid-  , gridWith-  , hstack-  , label-  , label'-  , vstack-  , labelWith-  , labelWith'-  , panel-  , panelWith-  , responsive-  , responsiveRowCol-  , row-  , rowWith-  , scroll-  , scroll2D-  , scroll2DWith-  , scrollArea-  , scrollArea2D-  , scrollWith-  , separator-  , spacer-  )-import NanoUI.Widgets.Menu-  ( contextMenu-  , contextMenuArea-  , menuButton-  , menuButton'-  , menuHeader-  , menuItem-  , menuItem'-  , menuItemDisabled-  , menuItemShortcut-  , menuSeparator-  , useContextMenu-  )-import NanoUI.Widgets.Node-  ( HasResponse (..)-  , Response (..)-  , respChanged-  , respClicked-  , respHovered-  , respId-  , respPressed-  , respRect-  , respRightClicked-  , respRightPressed-  , respSubmitted-  , setChanged-  , setClicked-  , setSubmitted-  )-import NanoUI.Widgets.NumericInput (NumericInputConfig (..), defaultNumericInputConfig, numericInput, numericInput', numericInputConfigured, numericInputConfigured')-import NanoUI.Widgets.Overlay (modal, window)-import NanoUI.Widgets.PaneGrid-  ( GridAxis (..)-  , PaneGridConfig (..)-  , PaneGridCtx (..)-  , PaneGridResponse (..)-  , PaneView (..)-  , defaultPaneGridConfig-  , paneGrid-  )-import NanoUI.Widgets.Popup-  ( PopupAnchor (..)-  , PopupConfig (..)-  , PopupPlacement (..)-  , defaultPopupConfig-  , popup-  , popupWith-  , tooltip-  , tooltipAt-  , tooltipWidget-  , withTooltip-  )-import NanoUI.Widgets.Radio (boundedRadio, boundedRadio', enumRadio, enumRadio', radio, radio')-import NanoUI.Widgets.RichText (Inline, emphasis, hyperlink, inlineCode, inlineText, inlineWith, restyle, richText, richText', richTextWith, richTextWith', strong)-import NanoUI.Widgets.Select-  ( boundedSelect-  , boundedSelect'-  , enumSelect-  , enumSelect'-  , select-  , select'-  , selectWith-  , selectWith'-  )-import NanoUI.Widgets.Slider (slider, slider', sliderWith, sliderWith')-import NanoUI.Widgets.Table-  ( ColSize (..)-  , Colonnade-  , Headed (..)-  , SortCol (..)-  , SortDir (..)-  , TableConfig (..)-  , TableResponse (..)-  , defaultTableConfig-  , headed-  , headless-  , simpleTable-  , sortRows-  , table-  , tableConfigured-  , tableHiddenIndices-  , tableWith-  , useTableSort-  )-import NanoUI.Widgets.Tabs-  ( Tab (..)-  , TabOrientation (..)-  , TabResponse (..)-  , TabStyle (..)-  , TabsConfig (..)-  , closableTab-  , defaultTabsConfig-  , tab-  , tabBar-  , tabBar'-  , tabBarConfigured-  , tabBarConfigured'-  , tabs-  , tabs'-  , tabsConfigured-  , tabsConfigured'-  )-import NanoUI.Widgets.TextArea (textArea, textArea', textAreaWith, textAreaWith')-import NanoUI.Widgets.TextBuffer (Cursor (..))-import NanoUI.Widgets.TextCommand (TextCommand (..), TextMotion (..))-import NanoUI.Widgets.TextField (runTextCommand, textCanRedo, textCanUndo)-import NanoUI.Widgets.TextInput-  ( SearchFieldConfig (..)-  , TextInputConfig (..)-  , defaultSearchFieldConfig-  , defaultTextInputConfig-  , searchField-  , searchField'-  , searchFieldConfigured-  , searchFieldConfigured'-  , selectableText-  , selectableText'-  , selectableTextWith-  , selectableTextWith'-  , textInput-  , textInput'-  , textInputConfigured-  , textInputConfigured'-  )-import NanoUI.Widgets.Tree (TreeItem (..), tree, tree')+-- Views are written in the 'NanoUI' monad, and the backend re-runs the view+-- function when events arrive. Each widget call emits a layout node, reads the+-- current frame's input, and returns the user interaction directly.+--+-- > counter :: NanoUI ()+-- > counter = row $ do+-- >   n <- useVar (0 :: Int)+-- >   whenM (button "-") (modifyVar n (subtract 1))+-- >   label . T.pack . show =<< readVar n+-- >   whenM (button "+") (modifyVar n (+ 1))+--+-- Run a view with a backend: @runSdlApp@ from @nano-ui-sdl@ or @runRgfwApp@+-- from @nano-ui-rgfw@.+--+-- This module re-exports the core view API. Companion modules inside+-- @nano-ui@ cover specialized subsystems:+--+-- * "NanoUI.Widgets.PaneGrid" for split-pane workspaces.+-- * "NanoUI.Widgets.TextDocument" for multi-line text document queries and edits.+-- * "NanoUI.Widgets.Custom" for authoring custom widgets ('CustomWidgetSpec', 'DrawOp', 'bindVar').+-- * "NanoUI.Themes" for extra theme presets and Base16 palettes.+-- * "NanoUI.Chrome" for frameless window title-bar chrome.+-- * "NanoUI.Shader.Raw" for hand-written GPU shader programs and std140 metadata.+-- * "NanoUI.Backend" for custom backends and frame harnesses.+--+-- = Conventions+--+-- * Simple widgets return 'Bool' (buttons, menu items, selectable rows) or @()@+--   (inputs, text, decoration).+-- * A primed name returns the widget's 'Response' as well or instead, for+--   hover state, geometry, tooltips, and change or submit flags:+--   @button'@, @slider'@, @scrollWith'@.+-- * Input widgets take a mutable 'Var' holding their state: @textInput draft@+--   reads and mutates @draft@ in place. Pass @'constVar' x@ for a read-only+--   value. Transient UI state such as caret position, an active drag, or an+--   open dropdown is stored internally per widget.+-- * Layout arguments are modifiers, as in @buttonWith (fixedW 120)@ or+--   @columnWith (gap 8 . padAll 12)@. Widgets with more options take a+--   configuration record: 'textInputConfigured', 'tabsConfigured'.+--+-- = State+--+-- Keep mutable state in 'Var's: 'useVar' allocates one tied to its call site+-- in the view, and 'newVar' allocates one in 'IO'. Read a 'Var' with 'readVar'.+-- Or use a pure model and reducer with @nano-ui-emit@. See "NanoUI.Var".+module NanoUI+  ( -- * Views+    NanoUI+  , liftIO+  , whenM+  , unlessM+  , ifM+  , windowSize+  , windowWidth+  , windowHeight+  , uiMousePos+  , askInput+  , uiTime+  , requestFrame+  , lastRect++    -- * Widget identity++    -- | Every widget receives the next 'WidgetId' in its container: IDs count+    -- up in call order among siblings, and each container starts a new counter+    -- for its children. Internal widget state is keyed by 'WidgetId', so+    -- widgets should be called in a consistent order across frames. Positional+    -- 'useVar' calls use a separate counter so widget and 'useVar' IDs do not+    -- affect each other.+    --+    -- A widget (or 'useVar') that runs conditionally shifts the IDs of+    -- subsequent siblings in the same container. Wrap conditional subtrees in+    -- 'scope', which consumes a single ID regardless of whether its body adds+    -- widgets. For dynamic lists where items are added, removed, or reordered,+    -- wrap each item in 'withKey' with a sibling-unique key so state follows+    -- the key rather than the index.+  , scope+  , withKey+  , currentId+  , WidgetId (..)++    -- * Responses+  , Response (..)+  , HasResponse (..)+  , respId+  , respRect+  , respHovered+  , respPressed+  , respClicked+  , respChanged+  , respSubmitted+  , respHeldWith+  , respClickedWith+  , respRightPressed+  , respRightClicked++    -- * Containers+  , row+  , rowWith+  , rowWith'+  , column+  , columnWith+  , columnWith'+  , grid+  , gridWith+  , gridWith'+  , clipBox+  , panel+  , panelWith+  , panelWith'+  , card+  , callout+  , calloutWith+  , calloutWith'+  , calloutTone+  , calloutToneWith+  , calloutToneWith'+  , toolbar+  , center+  , selectableRow+  , selectableRow'+  , selectableRowWith+  , selectableRowWith'+  , collapsing+  , collapsingWith+  , responsive+  , responsiveRowCol+  , withContainerQuery+  , withContainerSize+  , withContainerWidth+  , responsiveIn+  , responsiveRowColIn+  , separator+  , spacer+  , spacerW+  , spacerH+  , flex+  , layers+  , layersWith+  , layersWith'+  , mouseArea++    -- * Scrolling++    -- | Scroll containers ('scroll', 'scroll2D') handle mouse wheel input and+    -- scrollbars automatically. The control functions below adjust scroll+    -- position and tuning from inside a view using the 'WidgetId' from+    -- 'scrollWith'', 'scroll2DWith'', or 'scrollConfigured'' (or 'currentId'+    -- immediately before declaring the scroll container):+    --+    -- > sid <- currentId+    -- > when moved (scrollRectIntoView sid (Rect 0 (row * rowH) 1 rowH) ScrollNearest ScrollInstant)+    -- > metrics <- getScrollMetrics sid+    -- > (picked, _) <- scrollWith' (fillW . fillH) (visibleRows metrics)+    --+    -- 'setScrollTuning' configures wheel step distance and smooth-scroll+    -- duration globally; 'setScrollStep' overrides the wheel step for one+    -- scroll container. Tab and 'requestFocus' scroll focused widgets into+    -- view automatically.+  , ScrollPolicy (..)+  , ScrollConfig (..)+  , defaultScrollConfig+  , scroll2DConfig+  , scroll+  , scrollWith+  , scrollWith'+  , scroll2D+  , scroll2DWith+  , scroll2DWith'+  , scrollConfigured+  , scrollConfigured'+  , ScrollTuning (..)+  , defaultScrollTuning+  , getScrollTuning+  , setScrollTuning+  , ScrollMetrics (..)+  , ScrollAxes (..)+  , ScrollBehavior (..)+  , ScrollAlign (..)+  , getScrollMetrics+  , setScrollOffset+  , scrollTo+  , scrollBy+  , scrollPages+  , scrollToStart+  , scrollToEnd+  , scrollIntoView+  , scrollRectIntoView+  , setScrollStep++    -- * Visibility++    -- | A visibility sensor reports whether a widget's bounds intersect the+    -- window and all enclosing clip rects (scroll containers, panels, and+    -- floating windows). 'sensor' wraps a subtree in a monitored container;+    -- 'useVisibility' monitors an existing widget by 'WidgetId'.+    --+    -- Because layout runs after the view pass, visibility reflects the+    -- previous frame's layout (like 'respRect'). When layout changes a+    -- sensor's visibility, the frame loop schedules a follow-up pass and+    -- reports the transition in 'visEvent' on the first pass of that frame.+    -- If a sensor call is omitted on a frame (e.g. inside an inactive tab or+    -- skipped 'scope'), its state is cleared and it will report+    -- 'BecameVisible' again when re-entered.+    --+    -- 'sensorAnticipate' expands the intersection margin outward (in pixels)+    -- for prefetching ahead of scroll. 'sensorDelay' requires the target to+    -- remain in view for a minimum duration before firing, avoiding work for+    -- rows scrolled past quickly. 'visRect' is the visible intersection and+    -- 'visBounds' is the full widget rect:+    --+    -- Make @pictureVar <- newVar Nothing@ once during component setup.+    --+    -- > thumbnail :: Var (Maybe ImageId) -> FilePath -> NanoUI ()+    -- > thumbnail pictureVar path = do+    -- >   picture <- readVar pictureVar+    -- >   let cfg = defaultSensorConfig {sensorAnticipate = 200, sensorLayout = fixedWH 96 96}+    -- >   (vis, _) <- sensorConfigured cfg $+    -- >     maybe (label "Loading") (image (fixedWH 96 96)) picture+    -- >   when (becameVisible vis && isNothing picture) $ do+    -- >     (w, h, rgba) <- liftIO (decodeRgba path)+    -- >     iid <- freshImageId+    -- >     whenM (registerImageRgba iid w h rgba) (writeVar pictureVar (Just iid))+    -- >   when (becameHidden vis) $ do+    -- >     mapM_ releaseImageRgba picture+    -- >     writeVar pictureVar Nothing+  , Visibility (..)+  , VisibilityEvent (..)+  , becameVisible+  , becameHidden+  , sensor+  , sensorWith+  , SensorConfig (..)+  , defaultSensorConfig+  , sensorConfigured+  , useVisibility++    -- * Text+  , label+  , label'+  , labelWith+  , labelWith'+  , heading+  , muted+  , mono+  , danger+  , bold+  , italic+  , underline+  , kv+  , kvMono+  , kvBlock+  , selectableText+  , selectableText'+  , selectableTextWith+  , selectableTextWith'++    -- ** Rich text+  , module NanoUI.Widgets.RichText++    -- * Buttons and menus+  , button+  , button'+  , buttonWith+  , buttonWith'+  , iconButton+  , iconButton'+  , buttonContent+  , buttonContent'+  , buttonContentWith+  , buttonContentWith'+  , buttonGroup+  , buttonGroupWith+  , ButtonConfig (..)+  , defaultButtonConfig+  , buttonConfigured+  , buttonConfigured'+  , menuButton+  , menuButton'+  , menuButtonWith+  , menuButtonWith'+  , menuItem+  , menuItem'+  , menuItemShortcut+  , menuItemDisabled+  , menuSeparator+  , menuHeader+  , contextMenu+  , contextMenuArea++    -- * Inputs+  , checkbox+  , checkbox'+  , checkboxWith+  , checkboxWith'+  , toggleButton+  , toggleButton'+  , toggleButtonWith+  , toggleButtonWith'+  , radio+  , radio'+  , enumRadioBy+  , enumRadioBy'+  , enumRadio+  , enumRadio'+  , select+  , select'+  , selectWith+  , selectWith'+  , enumSelectBy+  , enumSelectBy'+  , enumSelect+  , enumSelect'+  , slider+  , slider'+  , sliderWith+  , sliderWith'+  , TextInputConfig (..)+  , defaultTextInputConfig+  , textInput+  , textInput'+  , textInputConfigured+  , textInputConfigured'+  , NumericInputConfig (..)+  , defaultNumericInputConfig+  , numericInput+  , numericInput'+  , numericInputConfigured+  , numericInputConfigured'+  , SearchInputConfig (..)+  , defaultSearchInputConfig+  , searchInput+  , searchInput'+  , searchInputConfigured+  , searchInputConfigured'+  , comboBox+  , comboBox'+  , textArea+  , textArea'+  , textAreaWith+  , textAreaWith'+  , textAreaDocument+  , textAreaDocument'+  , textAreaDocumentWith+  , textAreaDocumentWith'+  , colorPicker+  , colorPicker'+  , colorPickerRGBA+  , colorPickerRGBA'+  , colorToHex+  , colorToHexA+  , colorFromHex++    -- ** Text editing++    -- | Text fields apply edits through 'TextCommand's. Keyboard input+    -- (Backspace is @'Delete' 'CharLeft'@, Ctrl+Z is 'Undo'), the right-click+    -- context menu, and programmatic calls via 'runTextCommand' all dispatch+    -- through the same command set:+    --+    -- > resp <- textArea' body+    -- > canUndo <- textCanUndo (respId resp)+    -- > whenM (menuItem "Undo") (runTextCommand (respId resp) Undo)+    -- > whenM (menuItem "Insert date") (runTextCommand (respId resp) (InsertText today))+    --+    -- Every command that mutates text is recorded for undo. Consecutive typing+    -- is grouped by word and deletions by run; undo entries store only the+    -- diffs rather than full document snapshots. Modifying the 'Var' from+    -- outside the widget clears its undo history.+  , TextCommand (..)+  , TextMotion (..)+  , Cursor (..)+  , module NanoUI.Widgets.TextField++    -- * Tabs, trees, and tables++    -- ** Tabs+  , Tab (..)+  , TabStyle (..)+  , TabOrientation (..)+  , TabResponse (..)+  , TabsConfig (..)+  , defaultTabsConfig+  , tab+  , closableTab+  , tabs+  , tabs'+  , tabsConfigured+  , tabsConfigured'+  , tabBar+  , tabBar'+  , tabBarConfigured+  , tabBarConfigured'+  , enumTabsBy+  , enumTabsByConfigured+  , enumTabs+  , enumTabBarBy+  , enumTabBarByConfigured+  , enumTabBar++    -- ** Trees+  , TreeItem (..)+  , tree+  , tree'++    -- ** Tables+  , SortDir (..)+  , SortCol (..)+  , SortKey (..)+  , ColSize (..)+  , TableConfig (..)+  , TableResponse (..)+  , defaultTableConfig+  , table+  , tableWith+  , tableConfigured+  , table'+  , tableWith'+  , tableConfigured'+  , simpleTable+  , tableHiddenIndices+  , sortRows+  , Colonnade+  , Headed (..)+  , headed+  , headless+  , ToCell (..)+  , Cell (..)+  , textCell+  , cellWidget+  , cellSort+  , cellSortKey+  , cellSortNum+  , cellSortInt+  , cellWidthText++    -- * Overlays++    -- ** Modals and floating windows+  , modal+  , modal'+  , modalWith+  , modalWith'+  , modalPanel+  , modalPanel'+  , modalPanelWith+  , modalPanelWith'+  , floatingWindow+  , floatingWindow'+  , floatingWindowWith+  , floatingWindowWith'++    -- ** Popups+  , PopupAnchor (..)+  , PopupPlacement (..)+  , PopupConfig (..)+  , defaultPopupConfig+  , popup+  , popup'+  , popupWith+  , popupWith'++    -- ** Tooltips++    -- | A tooltip opens after the pointer rests on its target for+    -- 'tooltipDelay', or immediately if another tooltip was recently open. It+    -- closes when the pointer leaves or a mouse button is pressed; scrolling+    -- restarts the delay timer via a timed wake without spinning the frame+    -- loop. 'PlacementAtCursor' positions the tooltip 'tooltipGap' below the+    -- cursor. Tooltips also appear on disabled widgets.+  , tooltip+  , tooltipAt+  , tooltipWidget+  , withTooltip+  , TooltipConfig (..)+  , defaultTooltipConfig+  , tooltipConfigured+  , tooltipWidgetConfigured++    -- * Images and SVG+  , ImageId (..)+  , image+  , image'+  , freshImageId+  , registerImageRgba+  , releaseImageRgba+  , useImageRgba+  , ImageHandle+  , newImageHandle+  , Svg+  , parseSvg+  , loadSvg+  , svgIcon+  , svgIconWith+  , svgIconWith'+  , svgIconConfigured+  , svgIconConfigured'+  , svgSize+  , box++    -- ** Image fit, opacity, and rotation++    -- | 'imageConfigured' fits an image into its layout rect (similar to CSS+    -- @object-fit@ via 'ContentFit'), with alignment, cropping, zoom, opacity,+    -- and 'Rotation'. Unlike 'image', an axis left at fit sizing uses the+    -- image's natural dimension, and a fit height preserves aspect ratio:+    --+    -- > imageConfigured defaultImageConfig {icFit = FitContain, icLayout = fixedWH 200 120} photo+    -- > imageConfigured defaultImageConfig {icRotation = RotateSolid (pi / 2), icOpacity = 0.5} photo+    -- > imageConfigured defaultImageConfig {icLayout = fillW, icCrop = Just (Rect 0 0 64 64)} sheet+    --+    -- 'svgIconConfigured' applies the same rules to SVG icons. 'fitRect'+    -- computes the destination rectangle for canvases drawing images with+    -- 'drawImageWith'.+  , ContentFit (..)+  , Rotation (..)+  , rotationAngle+  , ImageConfig (..)+  , defaultImageConfig+  , imageConfigured+  , imageConfigured'+  , fitRect++    -- * Shaders++    -- | Pure, phantom-typed fragment shaders for leaf surfaces ('shaderBox',+    -- 'shaderConfigured') and subtree effects ('withShader', 'withShader'').+    -- Uniform records derive 'Uniforms' via "GHC.Generics" for std140 packing+    -- and automatic paint-hash damage tracking. Use @nano-ui-shader@ to author+    -- multi-backend fragment shaders in typed Haskell, or "NanoUI.Shader.Raw"+    -- for hand-written backend sources.+  , V3 (..)+  , V4 (..)+  , Uniforms (..)+  , ShaderKind (..)+  , IsNodeEffect+  , ShaderCapabilities (..)+  , askShaderCapabilities+  , Shader+  , contramapShader+  , fixUniform+  , ShaderConfig (..)+  , defaultShaderConfig+  , shaderBox+  , shaderBox'+  , shaderConfigured+  , shaderConfigured'+  , withShader+  , withShader'+  , withShaderWith+  , withShaderWith'++    -- * Canvas and built-in custom widgets++    -- | 'canvas' draws 2D shapes, text, images, and "NanoUI.Path" vector paths+    -- into a laid-out rectangle. Authoring full custom widgets with+    -- 'NanoUI.Widgets.Custom.CustomWidgetSpec', 'NanoUI.Widgets.Custom.DrawOp',+    -- and 'NanoUI.Widgets.Custom.bindVar' lives in "NanoUI.Widgets.Custom".+  , CanvasM+  , canvas+  , CanvasConfig (..)+  , defaultCanvasConfig+  , canvasConfigured+  , CustomDrawContext (..)+  , drawContext+  , drawRect+  , drawRoundedRect+  , drawCircle+  , drawStroke+  , drawStrokeRoundedRect+  , drawStrokeCircle+  , drawStrokeAA+  , drawQuadGradient+  , drawLinearGradientH+  , drawLinearGradientV+  , drawImage+  , drawImageUV+  , ImageDraw (..)+  , imageDraw+  , drawImageWith+  , TextFont (..)+  , defaultTextFont+  , drawText+  , drawTextWith+  , drawTextClipped+  , drawTextClippedWith+  , drawPath+  , drawPathWith+  , drawStrokePath+  , drawStrokePathWith+  , withTransform+  , withClip++    -- ** Caching and gestures+  , contentKey+  , contentKeyOf+  , KeyPart+  , keyPart+  , useDrag2DOn+  , Drag2D (..)+  , useWheelDeltaOn++    -- ** Built-in custom widgets+  , knob+  , knob'+  , knobWith+  , knobWith'+  , toggleSwitch+  , toggleSwitch'+  , toggleSwitchWith+  , toggleSwitchWith'+  , circularProgress+  , circularProgress'+  , circularProgressWith+  , circularProgressWith'+  , spinner+  , spinner'+  , spinnerWith+  , spinnerWith'+  , progressBar+  , progressBar'+  , progressBarWith+  , progressBarWith'+  , sparkline+  , sparkline'+  , sparklineWith+  , sparklineWith'++    -- ** Text measurement+  , FontMetrics (fmLineHeight, fmAscent)+  , lineWidth+  , lineWidthUi+  , truncateTextUi+  , truncateTextWithUi+  , uiFontMetrics+  , uiFontSize+  , resolveFontUi++    -- * Drag and drop+  , DropType (..)+  , DropEvent (..)+  , DropTarget (..)+  , useDrop+  , dropZone+  , Reorder (..)+  , useReorder+  , Drag (..)+  , DragPhase (..)+  , DragAxis (..)+  , useDrag+  , DragHandle+  , newDrag+  , insertionIndex++    -- * State++    -- | Mutable state references passed to input widgets; see "NanoUI.Var".+  , Var+  , constVar+  , newVar+  , useVar+  , useEnumVar+  , VarSlot+  , readVar+  , writeVar+  , modifyVar+  , readVarIO+  , writeVarIO+  , modifyVarIO+  , zoomVar+  , zoomVarL+  , forEachVar+  , withElemVars+  , VarMap+  , newVarMap+  , varAt+  , dropVar+  , retainVars+  , withValue++    -- ** Background work++    -- | Run IO work on a background thread and wake the frame loop on+    -- completion. 'useTaskStatus' reports whether the task is running, done,+    -- or failed; 'useTask' returns the latest completed result. A task starts+    -- on the first frame it is called with a key, restarts when the key+    -- changes, and is canceled if the call is omitted on a later frame.+    -- Allocate @searchTask <- newTask@ during setup:+    --+    -- > query <- useVar ""+    -- > textInput query+    -- > q <- readVar query+    -- > hits <- useTask searchTask q (searchIndex index q)+    -- > mapM_ (label . hitTitle) (fromMaybe [] hits)+    --+    -- While a new key's task is running, 'useTask' continues returning the+    -- previous result so the UI does not flash empty between queries.+    -- 'useStream' runs a background producer that pushes values into state,+    -- and 'askWake' returns an IO callback that schedules a frame from any+    -- thread.+  , TaskStatus (..)+  , useTaskStatus+  , Task+  , newTask+  , Stream+  , newStream+  , useTask+  , useStream+  , askWake++    -- * Animation+  , Transition (..)+  , animate+  , animateTo+  , animateToA+  , pulse+  , keepAnimating+  , wakeAfter+  , Animatable (..)+  , Ease (..)+  , applyEase+  , SpringParams (..)+  , presetBouncy+  , presetSmooth+  , presetStiff++    -- * Layout++    -- | Containers arrange children along a 'Row' or 'Column', either on a+    -- single 'Line' or wrapping across lines with 'Wrap' ('wrap', 'lineGap',+    -- 'lineAlign'). A 'Layered' container ('layers', or 'layered' on a panel+    -- or card) stacks children in z-order with later children on top. 'pinAt'+    -- removes a child from flow layout and offsets it from the corner selected+    -- by its alignment; @pinAt 0 0 . grow@ overlays the parent's bounds+    -- without affecting its measured size. 'aspect' constrains a fit height to+    -- a fixed width-to-height ratio.+    --+    -- When nodes overlap, interactive widgets capture pointer events while+    -- non-interactive nodes pass them through to elements beneath. 'pointer'+    -- overrides this: 'PointerBlock' captures pointer events across a+    -- container's full rect, and 'PointerPass' makes a subtree transparent to+    -- pointer hit-testing.+  , Layout+  , LayoutModifier+  , Sizing (..)+  , Direction (..)+  , Flow (..)+  , AlignX (..)+  , AlignY (..)+  , ItemsAlign (..)+  , Justify (..)+  , Padding (..)+  , defaultLayout+  , askDefaultLayout+  , withDefaultLayout+  , direction+  , padAll+  , padXY+  , padLeft+  , padRight+  , padTop+  , padBottom+  , padLRTB+  , gap+  , fillW+  , fillH+  , fitW+  , fitH+  , grow+  , growW+  , growH+  , minW+  , maxW+  , fixedW+  , minH+  , maxH+  , fixedH+  , fixedWH+  , alignMiddle+  , alignEnd+  , alignStart+  , alignCenter+  , alignTop+  , alignBottom+  , alignBaseline+  , itemsAlign+  , itemsStart+  , itemsCenter+  , itemsEnd+  , itemsBaseline+  , itemsStretch+  , justify+  , justifyStart+  , justifyCenter+  , justifyEnd+  , justifyBetween+  , tight+  , percent+  , percentH+  , gridMinColW+  , gridCols+  , fixedAspectW+  , fixedAspectH+  , aspect+  , wrap+  , layered+  , lineGap+  , lineAlign+  , LineAlign (..)+  , pinAt+  , PointerMode (..)+  , pointer++    -- * Styling and themes++    -- | A 'Theme' defines surface styles ('Style' for buttons, inputs, panels,+    -- floating windows, popups) and semantic colors (accents, text selection,+    -- links). 'setTheme' sets the active base theme, and 'styled' applies a+    -- 'Theme' -> 'Theme' modifier to a subtree. Style and theme modifiers+    -- compose with @(.)@:+    --+    -- > toolbar = styled (subtle . buttonStyle (cornerRadius 6)) $ row $ do+    -- >   whenM (button "Open") openFile+    -- >   styled primary (whenM (button "Save") save)+    --+    -- The page behind the view is the window background by default+    -- ('pageBackground'; 'themeWindow'), laid under the content. 'panelPage'+    -- gives a view that draws no panel the panel surface instead.+    --+    -- Nested 'styled' calls modify the enclosing theme, so semantic modifiers+    -- ('primary', 'destructive', etc.) adapt to whichever base theme is+    -- active. 'uiTheme' reads the current theme in the view.+    --+    -- 'disabledWhen' disables all widgets in a subtree: they keep their layout+    -- and state, ignore input, and render with dimmed colors.+  , styled+  , themed+  , disabledWhen+  , uiTheme++    -- ** Text style+  , FontVariant (..)+  , FontWeight (..)+  , FontStyle (..)+  , TextDecoration (..)+  , fontRegular+  , fontProportional+  , fontHeading+  , fontMuted+  , fontMono+  , fontDanger+  , fontSize+  , fontSizeScale+  , fontColor+  , fontWeight+  , fontBold+  , fontLight+  , fontMedium+  , fontSemiBold+  , fontExtraBold+  , fontBlack+  , fontStyle+  , fontItalic+  , fontOblique+  , textDecoration+  , fontUnderline+  , fontStrike+  , fontTabular+  , singleLine+  , TextBreak (..)+  , textBreak+  , breakAnywhere+  , TextEllipsis (..)+  , textEllipsis+  , ellipsisEnd+  , ellipsisMiddle+  , ellipsisStart+  , Tone (..)+  , fontTone++    -- ** Style modifiers+  , background+  , foreground+  , borderColor+  , borderWidth+  , borderSides+  , borderLeft+  , borderRight+  , borderTop+  , borderBottom+  , Side (..)+  , cornerRadius+  , hoverBackground+  , pressBackground+  , fillColor++    -- ** Theme modifiers+  , buttonStyle+  , inputStyle+  , panelStyle+  , windowStyle+  , popupStyle+  , everyStyle+  , accentColor+  , textColor+  , mutedColor+  , linkColor+  , selectionColor+  , windowColor+  , pageBackground+  , pageColor+  , panelPage+  , rounded+  , tone+  , toneColor+  , primary+  , destructive+  , success+  , warning+  , subtle+  , tinted+  , readableOn+  , disabledTheme++    -- ** Themes+  , Theme (..)+  , Style (..)+  , defaultTheme+  , setTheme+  , themeSeries++    -- ** Following the system++    -- | 'systemAppearance' queries the OS light/dark preference (supported by+    -- SDL; RGFW returns 'Nothing'). 'lightDark' selects a theme for an+    -- 'Appearance', defaulting to dark when 'Nothing':+    --+    -- > setTheme . lightDark defaultLightTheme defaultTheme =<< systemAppearance+    --+    -- Alternatively, 'followSystemTheme' (or the backends' @sdlAppThemeFor@+    -- and @optThemeFor@ options) updates the theme automatically when the OS+    -- appearance changes. 'setTheme' switches back to a fixed theme.+  , defaultLightTheme+  , Appearance (..)+  , lightDark+  , defaultThemeFor+  , themeAppearance+  , systemAppearance+  , followSystemTheme++    -- * Geometry and color+  , V2 (..)+  , Rect (..)+  , Size (..)+  , Color (..)+  , colorRGBA+  , colorRGB+  , colorHex+  , colorHexA+  , withAlpha+  , colorWhite+  , colorBlack+  , colorTransparent+  , colorLuminance+  , colorR+  , colorG+  , colorB+  , colorA+  , lerpColor+  , contrastRatio+  , rectContains+  , rectInflate+  , rectIntersect+  , rectUnion+  , v2Add+  , v2Sub++    -- * Input, focus, and shortcuts++    -- ** Focus++    -- | Tab moves focus between focusable widgets. Clicking a text field, a+    -- select, or a focusable custom widget (a knob, or a canvas with+    -- 'canvasFocusable') focuses it; clicking anywhere else unfocuses the+    -- current field.+    -- A view that handles keyboard input directly can call 'holdFocus' each+    -- frame to claim focus and receive Tab events.+    --+    -- 'requestFocus' focuses a widget, identified by its response's 'respId' or+    -- by 'currentId' just before declaring it. 'focusNext' and+    -- 'focusPrevious' act like Tab and Shift+Tab, and 'clearFocus' unfocuses.+    -- Focus changes apply at the end of the frame and behave like Tab: the+    -- target widget shows the focus ring, a text field preserves its caret,+    -- the previously focused field drops its selection and commits, and the+    -- next Tab continues from the newly focused widget. Disabled widgets and+    -- widgets behind an open modal cannot be focused. Check focus state with+    -- 'isFocused' on the next frame:+    --+    -- > resp <- searchInput' "Find" query+    -- > findPressed <- shortcut (ctrl <> key 'f')+    -- > when findPressed (requestFocus (respId resp))+    --+    -- 'NanoUI.Monad.releaseFocus' clears focus immediately mid-frame.+  , holdFocus+  , requestFocus+  , focusNext+  , focusPrevious+  , clearFocus+  , isFocused++    -- ** Keyboard and shortcuts++    -- | 'keyPressed', 'keyReleased', and 'keyHeld' check key state, and+    -- 'shortcut' matches a key chord built with "NanoUI.Shortcut":+    --+    -- > whenM (shortcut (ctrl <> key 's')) save+    -- > whenM (shortcut (cmdOrCtrl <> shift <> key 'p')) (setPaletteOpen True)+    --+    -- A shortcut matches when its exact modifiers are held, and only the first+    -- matching 'shortcut' call in a frame fires. Shortcuts and key listeners+    -- are suppressed behind an open modal or when the focused widget claims the+    -- key combination (for example, Ctrl+A in a focused text field). Focused+    -- controls only claim unmodified or Shift-modified keys, leaving chords+    -- like Alt+Left available for shortcuts. Custom widgets declare claimed+    -- keys via 'NanoUI.Widgets.Custom.widgetKeys'. 'menuItemShortcut' binds its+    -- chord while its menu is open.+    --+    -- Key auto-repeat counts as a press (so holding Ctrl+Z repeats undo). Use+    -- 'keyPressedOnce' and 'shortcutOnce' to ignore auto-repeat.+  , keyPressed+  , keyPressedOnce+  , keyReleased+  , keyHeld++    -- | Focused custom widgets read their claimed keys using+    -- 'focusedKeyPressed', 'useKeyNav' (arrow keys, Enter, Space), or+    -- 'keyActivated' (Enter/Space activation).+  , focusedKeyPressed+  , focusedKeyPressedOnce+  , useKeyNav+  , KeyNav (..)+  , navStep+  , ListNav (..)+  , ListNavScroll (..)+  , useListNav+  , useListNavWith+  , keyActivated+  , shortcut+  , shortcutOnce+  , noModifiers+  , modPrimary+  , primaryModifiers+  , modJump+  , modMacCommand++    -- ** Mouse buttons++    -- | 'respHeldWith' and 'respClickedWith' report which mouse buttons are+    -- held on or clicked a widget. 'mousePressed', 'mouseReleased', and+    -- 'mouseHeld' check mouse button state in the current view scope:+    --+    -- > whenM (mousePressed MouseBack) goBack+  , MouseButton (..)+  , mousePressed+  , mouseReleased+  , mouseHeld++    -- ** Cursors and clipboard++    -- | Built-in widgets set an appropriate cursor when hovered (pointer hand+    -- on buttons, I-beam on text fields, or 'widgetCursor' on custom widgets).+    -- 'withCursorShape' sets a fallback cursor for a subtree when no inner+    -- widget overrides it:+    --+    -- > withCursorShape UiCursorMove (canvas (fixedWH 320 200) board)+    --+    -- 'UiCursorDefault' indicates no widget override (or resets to the default+    -- arrow inside 'withCursorShape'). 'UiCursorHidden' hides the cursor.+    -- Disabled widgets fall back to the default arrow unless wrapped in+    -- @withCursorShape UiCursorNotAllowed@.+  , UiCursorKind (..)+  , withCursorShape+  , getClipboard+  , setClipboard++    -- ** Raw input and IME++    -- | Per-frame input state populated by the backend (see "NanoUI.Backend").+    --+    -- During IME text composition ('inputComposition'), the focused text field+    -- renders the active 'Composition' at the caret, and key events in+    -- 'inputKeys', 'inputKeysReleased', and 'inputKeysHeld' are suppressed+    -- until composition finishes so shortcuts do not trigger mid-composition.+    -- Custom text widgets opt into IME via 'useInputMethod'.+    -- 'pressedIn', 'releasedIn', and 'heldIn' test a key or mouse button in an+    -- 'Input'; 'pressedOnceIn' ignores key auto-repeat:+    --+    -- > runSdlApp defaultSdlOptions {sdlAppShouldQuit = pressedOnceIn KeyEscape} view+  , Input (..)+  , Pressable (..)+  , Key (..)+  , Modifiers (..)+  , takeEscape+  , Composition (..)+  , InputPurpose (..)+  , useInputMethod++    -- * The native window++    -- | Initial window configuration is passed via 'WindowSettings'+    -- (@sdlWindowSettings@ in @SdlOptions@, @optWindow@ in @RgfwOptions@).+    -- Inside a view, 'askWindow' reads the current 'WindowState', the setters+    -- and commands below update the window, and 'quit' requests exit. In+    -- headless test contexts, window operations are no-ops and+    -- 'requestScreenshot' answers its callback with 'Nothing' (as+    -- 'askScreenshot' does).+    --+    -- Setters ('setWindowTitle', 'setWindowMode', ...) only issue a+    -- backend call when the value changes, so they can be called every frame.+    -- Action commands ('moveWindow', 'resizeWindow', 'maximizeWindow',+    -- ...) run on every call and should be triggered by events. To confirm+    -- before closing, set 'wsExitOnCloseRequest' to 'False', check+    -- 'winCloseRequested', and call 'quit' when confirmed:+    --+    -- > editor :: NanoUI ()+    -- > editor = do+    -- >   asking <- useVar False+    -- >   closing <- winCloseRequested <$> askWindow+    -- >   when closing (writeVar asking True)+    -- >   modal asking "Discard your changes?" $ do+    -- >     whenM (button "Discard") quit+    -- >     whenM (button "Keep editing") (writeVar asking False)+  , WindowSettings (..)+  , defaultWindowSettings+  , WindowPosition (..)+  , WindowMode (..)+  , WindowState (..)+  , askWindow+  , WindowCapabilities (..)+  , askWindowCapabilities+  , setWindowTitle+  , setWindowIcon+  , setWindowMinSize+  , setWindowMaxSize+  , setWindowOpacity+  , setWindowMode+  , moveWindow+  , centerWindow+  , resizeWindow+  , minimizeWindow+  , maximizeWindow+  , restoreWindow+  , toggleMaximized+  , quit++    -- ** More windows++    -- | 'nativeWindow' opens another native window beside the first, with+    -- its own view, while a 'Var' holds 'True'. An app with one window+    -- never calls it and pays nothing for it.+  , nativeWindow++    -- ** Pixels and screenshots+  , RgbaPixels+  , rgbaPixels+  , rgbaWidth+  , rgbaHeight+  , rgbaBytes+  , Screenshot (..)+  , requestScreenshot+  , askScreenshot+  , useScreenshot++    -- * Debugging++    -- | 'explainLayout' draws depth-colored outlines around layout nodes and+    -- highlights the node under the pointer. 'explainedNode' returns that+    -- node's 'ExplainedNode' record (widget ID, rect, padding, sizing, gap,+    -- flow, pin, and pointer mode). 'explainScope' restricts the overlay to a+    -- subtree.+  , explainLayout+  , explainingLayout+  , explainedNode+  , explainScope+  , ExplainedNode (..)+  )+where++import NanoUI.Internal.Animatable+import NanoUI.Internal.Animation+import NanoUI.Internal.ChildWindow (nativeWindow)+import NanoUI.Internal.Context+  ( ExplainedNode (..)+  , ScrollAlign (..)+  , ScrollAxes (..)+  , ScrollBehavior (..)+  , ScrollMetrics (..)+  , ScrollTuning (..)+  , defaultScrollTuning+  )+import NanoUI.Internal.Draw (TextFont (..), defaultTextFont)+import NanoUI.Internal.Font (FontMetrics (..), lineWidth)+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Input+import NanoUI.Internal.Monad+import NanoUI.Internal.NativeWindow+import NanoUI.Internal.Shader+  ( IsNodeEffect+  , Shader+  , ShaderCapabilities (..)+  , ShaderConfig (..)+  , ShaderKind (..)+  , contramapShader+  , defaultShaderConfig+  , fixUniform+  )+import NanoUI.Internal.Style+import NanoUI.Internal.Tasks+import NanoUI.Internal.Types+import NanoUI.Internal.Uniforms (Uniforms (..), V3 (..), V4 (..))+import NanoUI.Internal.WidgetText (colorFromHex, colorToHex, colorToHexA)+import NanoUI.Internal.Widgets.Animate+import NanoUI.Internal.Widgets.Behavior+  ( DragAxis (..)+  , KeyNav (..)+  , ListNav (..)+  , ListNavScroll (..)+  , Reorder (..)+  , focusedKeyPressed+  , focusedKeyPressedOnce+  , keyActivated+  , navStep+  , useInputMethod+  , useKeyNav+  , useListNav+  , useListNavWith+  , useReorder+  )+import NanoUI.Internal.Widgets.Button+import NanoUI.Internal.Widgets.Checkbox+import NanoUI.Internal.Widgets.ColorPicker+import NanoUI.Internal.Widgets.Cursor+import NanoUI.Internal.Widgets.Disclosure+import NanoUI.Internal.Widgets.Display+import NanoUI.Internal.Widgets.Drop+import NanoUI.Internal.Widgets.Image+import NanoUI.Internal.Widgets.Layout+import NanoUI.Internal.Widgets.Menu+import NanoUI.Internal.Widgets.Node+import NanoUI.Internal.Widgets.NumericInput+import NanoUI.Internal.Widgets.Overlay+import NanoUI.Internal.Widgets.Popup+import NanoUI.Internal.Widgets.Radio+import NanoUI.Internal.Widgets.Select+import NanoUI.Internal.Widgets.Sensor+import NanoUI.Internal.Widgets.Shader+import NanoUI.Internal.Widgets.Shortcut+import NanoUI.Internal.Widgets.Slider+import NanoUI.Internal.Widgets.Table+import NanoUI.Internal.Widgets.Tabs+import NanoUI.Internal.Widgets.TextInput+import NanoUI.Internal.Widgets.Tree+import NanoUI.Svg+import NanoUI.Var+import NanoUI.Widgets.Combo+import NanoUI.Widgets.Custom+import NanoUI.Widgets.RichText+import NanoUI.Widgets.TextArea+import NanoUI.Widgets.TextBuffer+import NanoUI.Widgets.TextCommand+import NanoUI.Widgets.TextField
+ lib/NanoUI/Adornment.hs view
@@ -0,0 +1,34 @@+-- | Adornments: icons, short texts and views a text field draws before or+-- after its value, and a button beside its label. They are values, combined+-- side by side with '<>', and set in the widget's configuration. The names+-- are short, so import the module qualified:+--+-- > import NanoUI.Adornment qualified as A+-- >+-- > textInputConfigured defaultTextInputConfig+-- >   { ticAdornments = A.leading (A.icon mailIcon) <> A.trailing (A.affix "@example.com") } email+-- > hidden <- not <$> readVar shown+-- > textInputConfigured defaultTextInputConfig+-- >   { ticPassword = hidden+-- >   , ticAdornments = A.trailing (A.control (whenM (buttonWith tight "Show") (modifyVar shown not)))+-- >   } password+--+-- The widget lays each side out as a row inside its own box, the layout's gap+-- from its text and between adornments, and draws them in its text colour,+-- muted in a field. A press on an icon, a text or a 'view' is a press on the+-- widget. A 'control' takes its own presses: the widget around it does not+-- report them, and a text field keeps its focus and caret.+module NanoUI.Adornment+  ( Adornment+  , Adornments (..)+  , leading+  , trailing+  , icon+  , iconSized+  , affix+  , view+  , control+  )+where++import NanoUI.Internal.Widgets.Adornment (Adornment, Adornments (..), affix, control, icon, iconSized, leading, trailing, view)
− lib/NanoUI/Animatable.hs
@@ -1,41 +0,0 @@-module NanoUI.Animatable-  ( Animatable (..)-  ) where--import Data.Word (Word8)-import NanoUI.Types (Color, V2 (..), clamp01, colorA, colorB, colorG, colorR, colorRGBA)---- Float components for multi-component tweens. Extra components are dropped.--- Short Color lists pad RGB with 0 and alpha with 1. Other types pad with 0.-class Animatable a where-  toComponents :: a -> [Float]-  fromComponents :: [Float] -> a--instance Animatable Float where-  toComponents v = [v]-  fromComponents (v : _) = v-  fromComponents [] = 0--instance Animatable Double where-  toComponents v = [realToFrac v]-  fromComponents (v : _) = realToFrac v-  fromComponents [] = 0--instance Animatable V2 where-  toComponents (V2 x y) = [x, y]-  fromComponents (x : y : _) = V2 x y-  fromComponents [x] = V2 x 0-  fromComponents [] = V2 0 0--instance Animatable Color where-  toComponents c =-    [chan (colorR c), chan (colorG c), chan (colorB c), chan (colorA c)]-  fromComponents (r : g : b : a : _) =-    colorRGBA (byte r) (byte g) (byte b) (byte a)-  fromComponents xs = fromComponents (take 3 (xs ++ repeat 0) ++ [1])--chan :: Word8 -> Float-chan w = fromIntegral w / 255--byte :: Float -> Word8-byte x = fromIntegral (round (clamp01 x * 255) :: Int)
− lib/NanoUI/Animation.hs
@@ -1,236 +0,0 @@-module NanoUI.Animation-  ( Ease (..)-  , Animation (..)-  , SpringParams (..)-  , presetBouncy-  , presetSmooth-  , presetStiff-  , springEps-  , applyEase-  , approxEq-  , animInProgress-  , animationValue-  , easeSameSpec-  , stepAnim-  , writeRest-  ) where--import Data.IntMap.Strict (IntMap)-import qualified Data.IntMap.Strict as IM-import NanoUI.Types (clamp01)---- Cubic Bezier easing. X control points are clamped to [0, 1] (CSS-style).--- t=0 and t=1 return the endpoints so Newton cannot pop the first/last frame.-evaluateBezier :: Float -> Float -> Float -> Float -> Float -> Float-evaluateBezier x1 y1 x2 y2 t0-  | t0 <= 0 = 0-  | t0 >= 1 = 1-  | otherwise =-      let p1 = clamp01 x1-          p2 = clamp01 x2-          tau = solveBezierX p1 p2 t0 0.5 0-       in sampleBezier y1 y2 tau--sampleBezier :: Float -> Float -> Float -> Float-sampleBezier p1 p2 u =-  let one = 1 - u-   in 3 * one * one * u * p1 + 3 * one * u * u * p2 + u * u * u--bezierDeriv :: Float -> Float -> Float -> Float-bezierDeriv p1 p2 u =-  let one = 1 - u-   in 3 * one * one * p1 + 6 * one * u * (p2 - p1) + 3 * u * u * (1 - p2)--solveBezierX :: Float -> Float -> Float -> Float -> Int -> Float-solveBezierX p1 p2 targetT estimate iter-  | iter >= 8 = estimate-  | otherwise =-      let currentX = sampleBezier p1 p2 estimate-          errorVal = currentX - targetT-       in if abs errorVal < 1e-4-            then estimate-            else-              let deriv = bezierDeriv p1 p2 estimate-                  safeDeriv =-                    if abs deriv < 1e-6-                      then if deriv >= 0 then 1e-6 else -1e-6-                      else deriv-                  nextEst = clamp01 (estimate - errorVal / safeDeriv)-               in solveBezierX p1 p2 targetT nextEst (iter + 1)--data SpringParams = SpringParams-  { springStiffness :: {-# UNPACK #-} !Float-  , springDamping :: {-# UNPACK #-} !Float-  , springMass :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)--presetBouncy :: SpringParams-presetBouncy = SpringParams {springStiffness = 180, springDamping = 12, springMass = 1}--presetSmooth :: SpringParams-presetSmooth = SpringParams {springStiffness = 120, springDamping = 20, springMass = 1}--presetStiff :: SpringParams-presetStiff = SpringParams {springStiffness = 300, springDamping = 30, springMass = 1}--springEps :: Float-springEps = 1e-3--maxSubstep :: Float-maxSubstep = 1 / 30--maxSubsteps :: Int-maxSubsteps = 32--stepSpring :: SpringParams -> Float -> Float -> Float -> Float -> (Float, Float)-stepSpring params x v target dt-  | dt <= 0 = (x, v)-  | otherwise = go x v dt 0-  where-    go !pos !vel remain n-      | remain <= 1e-8 || n >= maxSubsteps = (pos, vel)-      | otherwise =-          let h = min maxSubstep remain-              (pos', vel') = rk4 params pos vel target h-           in go pos' vel' (remain - h) (n + 1)--rk4 :: SpringParams -> Float -> Float -> Float -> Float -> (Float, Float)-rk4 params x v xTarget dt =-  let k1v = accel x v-      k1x = v-      k2v = accel (x + 0.5 * dt * k1x) (v + 0.5 * dt * k1v)-      k2x = v + 0.5 * dt * k1v-      k3v = accel (x + 0.5 * dt * k2x) (v + 0.5 * dt * k2v)-      k3x = v + 0.5 * dt * k2v-      k4v = accel (x + dt * k3x) (v + dt * k3v)-      k4x = v + dt * k3v-      xNext = x + (dt / 6) * (k1x + 2 * k2x + 2 * k3x + k4x)-      vNext = v + (dt / 6) * (k1v + 2 * k2v + 2 * k3v + k4v)-   in (xNext, vNext)-  where-    k = max 0 (springStiffness params)-    c = max 0 (springDamping params)-    m = max 1e-6 (springMass params)-    accel pos vel = (-k * (pos - xTarget) - c * vel) / m--data Ease-  = EaseLinear-  | EaseInQuad-  | EaseOutQuad-  | EaseInOutQuad-  | EaseInCubic-  | EaseOutCubic-  | EaseInOutCubic-  | EaseOutBack-  | EaseCubicBezier-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-  deriving (Eq, Show)---- EaseAnim start end duration elapsed ease delay delayReq--- SpringAnim pos vel target params-data Animation-  = EaseAnim-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Ease-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-  | SpringAnim-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !SpringParams-  deriving (Eq, Show)---- True when this ease slot matches the call-site spec and target.-easeSameSpec :: Animation -> Ease -> Float -> Float -> Float -> Bool-easeSameSpec (EaseAnim _ end dur _ ease _ delayReq) wantEase wantDur delay target =-  ease == wantEase-    && approxEq dur wantDur-    && approxEq delay delayReq-    && approxEq end target-easeSameSpec _ _ _ _ _ = False---- Map unit progress through an easing curve. Input is clamped to [0, 1].--- EaseOutBack may return a value outside that range (overshoot).-applyEase :: Ease -> Float -> Float-applyEase ease t0 =-  let t = clamp01 t0-   in case ease of-        EaseLinear -> t-        EaseInQuad -> t * t-        EaseOutQuad -> t * (2 - t)-        EaseInOutQuad-          | t < 0.5 -> 2 * t * t-          | otherwise -> -1 + (4 - 2 * t) * t-        EaseInCubic -> t * t * t-        EaseOutCubic ->-          let u = 1 - t-           in 1 - u * u * u-        EaseInOutCubic-          | t < 0.5 -> 4 * t * t * t-          | otherwise ->-              let u = -2 * t + 2-               in 1 - (u * u * u) / 2-        EaseOutBack ->-          let c1 = 1.70158-              c3 = c1 + 1-              u = t - 1-           in 1 + c3 * u * u * u + c1 * u * u-        EaseCubicBezier x1 y1 x2 y2 -> evaluateBezier x1 y1 x2 y2 t--approxEq :: Float -> Float -> Bool-approxEq a b = abs (a - b) <= 1e-4--{-# INLINE animInProgress #-}-animInProgress :: Animation -> Bool-animInProgress (EaseAnim start end dur elapsed _ delay _) =-  not (approxEq start end)-    && dur > 0-    && (delay > 0 || elapsed < dur)-animInProgress (SpringAnim pos vel target _) =-  abs (pos - target) > springEps || abs vel > springEps--{-# INLINE animationValue #-}-animationValue :: Animation -> Float-animationValue a@(EaseAnim start end dur elapsed ease delay _)-  | not (animInProgress a) = end-  | delay > 0 = start-  | otherwise =-      let t = min 1 (elapsed / max 0.001 dur)-       in start + (end - start) * applyEase ease t-animationValue (SpringAnim pos _ _ _) = pos--stepAnim :: Float -> Animation -> Animation-stepAnim dt a@(EaseAnim start end dur elapsed ease delay delayReq)-  | not (animInProgress a) = a-  | delay > 0 =-      let remain = delay - dt-       in if remain > 0-            then EaseAnim start end dur elapsed ease remain delayReq-            else stepAnim (negate remain) (EaseAnim start end dur elapsed ease 0 delayReq)-  | otherwise =-      let next = elapsed + dt-       in if next >= dur-            then EaseAnim end end 0 0 ease 0 0-            else EaseAnim start end dur next ease 0 delayReq-stepAnim dt (SpringAnim pos vel target params) =-  let (pos', vel') = stepSpring params pos vel target dt-   in if abs (pos' - target) <= springEps && abs vel' <= springEps-        then SpringAnim target 0 target params-        else SpringAnim pos' vel' target params--writeRest :: IntMap Float -> Int -> Animation -> IntMap Float-writeRest rest key a =-  let end = case a of-        EaseAnim _ e _ _ _ _ _ -> e-        SpringAnim _ _ t _ -> t-   in if approxEq end 0-        then IM.delete key rest-        else IM.insert key end rest
− lib/NanoUI/Atlas.hs
@@ -1,216 +0,0 @@-module NanoUI.Atlas-  ( ImageAtlas-  , newImageAtlas-  , atlasTextureId-  , registerImage-  , freshImageId-  , lookupImageUv-  , atlasSnapshot-  )-where--import Control.Applicative ((<|>))-import Data.ByteString (ByteString)-import Data.ByteString qualified as BS-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Word (Word8)-import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtrBytes, withForeignPtr)-import Foreign.Marshal.Utils (copyBytes, fillBytes)-import Foreign.Ptr (plusPtr)-import NanoUI.Types (ImageId (..))---- | GPU texture id shared by every packed image so draw cmds batch.-atlasTextureId :: Int-atlasTextureId = 1--atlasPad :: Int-atlasPad = 1--atlasStart :: Int-atlasStart = 256--atlasMax :: Int-atlasMax = 4096--data AtlasSlot = AtlasSlot-  { slotX :: {-# UNPACK #-} !Int-  , slotY :: {-# UNPACK #-} !Int-  , slotW :: {-# UNPACK #-} !Int-  , slotH :: {-# UNPACK #-} !Int-  }--data AtlasState = AtlasState-  { asW :: {-# UNPACK #-} !Int-  , asH :: {-# UNPACK #-} !Int-  , asPtr :: ForeignPtr Word8-  , asSlots :: IM.IntMap AtlasSlot-  , asX :: {-# UNPACK #-} !Int-  , asY :: {-# UNPACK #-} !Int-  , asRowH :: {-# UNPACK #-} !Int-  , asGen :: {-# UNPACK #-} !Int-  , asLastFresh :: {-# UNPACK #-} !Int-  -- ^ The last id 'freshImageId' returned.-  }--newtype ImageAtlas = ImageAtlas (IORef AtlasState)--newImageAtlas :: IO ImageAtlas-newImageAtlas = do-  fp <- allocPixels atlasStart atlasStart-  ImageAtlas-    <$> newIORef-      AtlasState-        { asW = atlasStart-        , asH = atlasStart-        , asPtr = fp-        , asSlots = IM.empty-        , asX = atlasPad-        , asY = atlasPad-        , asRowH = 0-        , asGen = 0-        , asLastFresh = 0-        }--registerImage :: ImageAtlas -> ImageId -> Int -> Int -> ByteString -> IO Bool-registerImage (ImageAtlas ref) (ImageId tid) w h pixels-  | tid <= 0 || w <= 0 || h <= 0 = pure False-  | w > atlasMax - 2 * atlasPad || h > atlasMax - 2 * atlasPad = pure False-  | BS.length pixels < w * h * 4 = pure False-  | otherwise = do-      st0 <- readIORef ref-      case IM.lookup tid (asSlots st0) of-        Just slot-          | slotW slot == w && slotH slot == h -> do-              blitPixels (asPtr st0) (asW st0) (slotX slot) (slotY slot) w h pixels-              writeIORef ref st0 {asGen = asGen st0 + 1}-              pure True-          | otherwise -> pure False-        Nothing -> do-          mSt <- fitImage st0 tid w h pixels-          case mSt of-            Nothing -> pure False-            Just st1 -> do-              writeIORef ref st1-              pure True---- | An id above every registered image's and every id this returned before.--- An id the app picks itself can still collide with one returned and not yet--- registered, so register those first.-freshImageId :: ImageAtlas -> IO ImageId-freshImageId (ImageAtlas ref) = do-  st <- readIORef ref-  let tid = 1 + maybe (asLastFresh st) (max (asLastFresh st) . fst) (IM.lookupMax (asSlots st))-  writeIORef ref st {asLastFresh = tid}-  pure (ImageId tid)--lookupImageUv ::-  ImageAtlas -> ImageId -> IO (Maybe (Float, Float, Float, Float))-lookupImageUv (ImageAtlas ref) (ImageId tid) = do-  st <- readIORef ref-  pure $-    case IM.lookup tid (asSlots st) of-      Nothing -> Nothing-      Just (AtlasSlot x y w h) ->-        let-          fw = fromIntegral (asW st)-          fh = fromIntegral (asH st)-         in-          Just-            ( fromIntegral x / fw-            , fromIntegral y / fh-            , fromIntegral (x + w) / fw-            , fromIntegral (y + h) / fh-            )---- Pinned pixel buffer. SDL uploads this pointer; do not copy to ByteString first.-atlasSnapshot :: ImageAtlas -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))-atlasSnapshot (ImageAtlas ref) = do-  st <- readIORef ref-  if asGen st == 0-    then pure Nothing-    else pure (Just (asW st, asH st, asPtr st, asGen st))--fitImage ::-  AtlasState -> Int -> Int -> Int -> ByteString -> IO (Maybe AtlasState)-fitImage st0 tid w h pixels =-  -- Plan the shelf position before allocating or copying the atlas. A full-  -- atlas must reject an image without repeatedly allocating doomed growth.-  case cursorFor st0 w h <|> cursorFor grown w h of-    Nothing -> pure Nothing-    Just (x, y, placed) -> do-      fp <--        if asW placed == asW st0 && asH placed == asH st0-          then pure (asPtr st0)-          else do-            resized <- allocPixels (asW placed) (asH placed)-            copyAtlas (asPtr st0) (asW st0) (asH st0) resized (asW placed)-            pure resized-      blitPixels fp (asW placed) x y w h pixels-      pure $-        Just-          placed-            { asPtr = fp-            , asSlots = IM.insert tid (AtlasSlot x y w h) (asSlots placed)-            , asX = x + w + atlasPad-            , asY = y-            , asRowH = max (asRowH placed) h-            , asGen = asGen placed + 1-            }- where-  grown =-    st0-      { asW = growDim (asW st0) (w + 2 * atlasPad)-      , asH = growDim (asH st0) (asY st0 + asRowH st0 + h + 2 * atlasPad)-      }--cursorFor :: AtlasState -> Int -> Int -> Maybe (Int, Int, AtlasState)-cursorFor st w h-  | asX st + w + atlasPad <= asW st && asY st + h + atlasPad <= asH st =-      Just (asX st, asY st, st)-  | asY st + asRowH st + atlasPad + h + atlasPad <= asH st-      && w + 2 * atlasPad <= asW st =-      let-        y = asY st + asRowH st + atlasPad-       in-        Just (atlasPad, y, st {asX = atlasPad, asY = y, asRowH = 0})-  | otherwise = Nothing--growDim :: Int -> Int -> Int-growDim cur need-  | need <= cur = cur-  | otherwise = min atlasMax (max need (cur * 2))--allocPixels :: Int -> Int -> IO (ForeignPtr Word8)-allocPixels w h = do-  let-    n = w * h * 4-  fp <- mallocForeignPtrBytes n-  withForeignPtr fp $ \p -> fillBytes p 0 n-  pure fp--copyAtlas :: ForeignPtr Word8 -> Int -> Int -> ForeignPtr Word8 -> Int -> IO ()-copyAtlas src oldW oldH dst newW =-  withForeignPtr src $ \sp ->-    withForeignPtr dst $ \dp ->-      mapM_ (copyRow sp dp) [0 .. oldH - 1]- where-  rowBytes = oldW * 4-  copyRow sp dp row =-    copyBytes-      (dp `plusPtr` (row * newW * 4))-      (sp `plusPtr` (row * oldW * 4))-      rowBytes--blitPixels ::-  ForeignPtr Word8 -> Int -> Int -> Int -> Int -> Int -> ByteString -> IO ()-blitPixels dest destW destX destY w h pixels =-  withForeignPtr dest $ \dp ->-    BS.useAsCStringLen pixels $ \(sp, _) ->-      mapM_ (copyRow dp sp) [0 .. h - 1]- where-  copyRow dp sp row =-    copyBytes-      (dp `plusPtr` (((destY + row) * destW + destX) * 4))-      (sp `plusPtr` (row * w * 4))-      (w * 4)
+ lib/NanoUI/Backend.hs view
@@ -0,0 +1,523 @@+-- |+-- Module      : NanoUI.Backend+-- Description : What a window backend is built from+-- Copyright   : (c) 2026 Zachary Churchill+-- License     : MIT+-- Maintainer  : zacharyachurchill@gmail.com+--+-- The parts of nano-ui a backend needs and a view does not: filling in a+-- frame's 'Input', measuring and shaping text for the widgets, reading back+-- the rectangles a frame changed, and running a view against a context.+-- @NanoUI.Backend.Sdl@ and @NanoUI.Backend.Rgfw@ are written against this+-- module; so is anything else that drives frames itself, such as a recorder,+-- a benchmark, or a test harness.+--+-- Writing a GUI needs none of it: "NanoUI" has the widgets, layout, styling+-- and state, and a backend's own runner (@runSdlApp@, @runRgfwApp@) starts+-- the loop. Nothing here shadows a name in "NanoUI": the names the two+-- share (the input types, 'FontMetrics', 'lineWidth', 'Appearance' and+-- 'WindowState') are the same entities in both, so importing both is safe.+--+-- A backend's frame is: collect events into an 'Input', run the view with+-- 'runFrame', take the 'Damage' and present the rectangles it names. 'Context'+-- holds state that outlives a frame. "NanoUI.Runner" supplies a reusable loop;+-- "NanoUI.Testing" adds assertions and inspection helpers for tests.+module NanoUI.Backend+  ( -- * Running a view++    -- | Run the view only. 'runFrame' additionally solves layout and paints.+    runNanoUI+  , runFrame++    -- ** Context setup+  , Context+  , newContext+  , newPixelContext+  , withFontMetrics+  , withMonoFontMetrics+  , withMeasureText+  , withFontResolver+  , withFontSize+  , withClipboard+  , withTheme+  , setThemeIO+  , getThemeIO+  , followSystemThemeIO++    -- ** Loop pacing and dirty state+  , markDirty+  , clearDirty+  , isDirty+  , requestWakeAt+  , requestWakeAfter+  , getWakeAt++    -- ** Layout and color helpers+  , Layout (..)+  , onGrid+  , roundHalfUp+  , colorToWord32+  , scrollBarTrackColor+  , scrollBarThumbColor+  , scrollBarThumbHoverColor++    -- * Rendering a frame++    -- ** Draw buffers and commands+  , DrawData (..)+  , DrawCmd (..)+  , Layer (..)+  , drawCmdNull+  , drawCmdElems+  , forDrawCmdsInLayer_+  , drawCmdCount+  , cmdEffectiveClip+  , vertexSize+  , indexSize+  , collectRasterSpans++    -- ** Shaders and effects+  , ShaderCall (..)+  , EffectSpan (..)+  , EffectPassDraw (..)+  , EffectDriver (..)+  , spanEffectiveClip+  , shiftClip+  , execEffectSpans+  , withEffectUniforms+  , emptyShaderCalls+  , emptyEffectSpans+  , emptyUniformBytes+  , ShaderProgram (..)+  , ShaderCapabilities (..)+  , noShaderCapabilities+  , setShaderCapabilities+  , getShaderCapabilities+  , setDrawPixelScale+  , sysUniformBytes++    -- ** Frame caches+  , IntGenCache+  , newIntGenCache+  , intGenCacheStartFrame+  , intGenCacheLookup+  , intGenCacheTouch+  , intGenCacheInsert+  , intGenCacheSize++    -- ** Images and texture atlases+  , registerImage+  , registerImages+  , releaseImage+  , atlasTextureId+  , atlasSnapshot+  , atlasChanges+  , AtlasUpload (..)+  , backdropDimTextureId+  , glyphAtlasTextureId+  , glyphAtlasPages+  , glyphPageTextureId+  , textureGlyphPage++    -- * Input++    -- | Start from 'emptyInput' once. Each later frame carries the last+    -- frame's input forward through 'clearEphemeral', which drops the+    -- one-shot events (keys, typed text, clicks, scroll, drops) and keeps+    -- what is held (buttons, pointer, modifiers, window size), then folds the+    -- window's new events into it. Starting from 'emptyInput' every frame+    -- instead loses held buttons and pointer position between events.+    --+    -- Keys go through 'applyKey', which tracks presses, releases and held+    -- keys; mouse buttons through 'applyMouseButton' (numbered with+    -- 'mouseButtonNumber'); dropped files through 'appendDropEvent'. When the+    -- pointer leaves the window, 'applyPointerLeave' moves it off every+    -- widget, unless a button is held. While one is, the backend keeps+    -- delivering motion and the release from outside the window (capturing+    -- the mouse where the platform allows), so a drag follows the pointer out+    -- and back. When the window loses keyboard focus, 'releaseAllKeys'+    -- releases the held keys, whose release events go elsewhere.+    --+    -- Every key goes in as a 'Key' whatever the modifiers; a key that types a+    -- character is the 'KeyChar' it types with no modifier held. The typed+    -- text also goes in 'inputChars'; a chord such as Ctrl+C types none.+    -- Auto-repeats go in as presses, which 'applyKey' keeps out of+    -- 'inputKeysNew'. 'keypadKey' maps keypad keys.+    --+    -- A frame does not keep the order of its text, keys and modifiers, so+    -- 'NanoUI.Runner.runSessionLoop' ends a frame after a command key when+    -- text, another key or a modifier change follows. A frame's text thus+    -- comes before its one command key ('inputKeys'). A backend's own loop+    -- should batch events the same way.+  , Input (..)+  , Key (..)+  , Modifiers (..)+  , MouseButton (..)+  , mouseButtonNumber+  , MouseButtons+  , DropEvent (..)+  , DropType (..)+  , emptyInput+  , applyMouseButton+  , applyPointerLeave+  , noButtons+  , buttonsMember+  , buttonsNull+  , buttonsInsert+  , buttonsDelete+  , buttonsToList+  , buttonsFromList+  , clearEphemeral+  , appendInputKey+  , appendDropEvent+  , inputInteracted+  , inputPointerHeld+  , inputKeysFromList+  , inputKeysNull+  , foldInputKeys+  , applyKey+  , releaseAllKeys+  , keypadKey+  , noModifiers+  , modifiersFromBits++    -- * Input methods++    -- | An input method (IME) composes text before committing it, such as+    -- Japanese kana before conversion to kanji. Fold each composition update+    -- into the input with 'applyComposition'. The composition is held, like+    -- a button, until the next update ends or replaces it, and the focused+    -- text field draws it at its caret. Committed text arrives as typed text+    -- in 'inputChars'.+    --+    -- After a frame, 'textInputArea' reports whether a text widget is active,+    -- the candidate window placement, and the 'InputPurpose'. Enable platform+    -- text input only while it returns 'Just', so the IME and on-screen+    -- keyboard are active only during text entry. 'getFocusId' returns the+    -- focused widget; drop any composition in progress when focus changes.+  , Composition (..)+  , applyComposition+  , InputPurpose (..)+  , TextInputArea (..)+  , textInputArea+  , getFocusId++    -- * Cursors+  , uiCursorKind+  , UiCursorKind (..)+  , cursorFallback+  , syncCursorKind++    -- * Fonts++    -- | A backend configures the context with 'FontMetrics' containing a+    -- 'FontBackend' for text measurement and shaping. 'prepareFontMetrics'+    -- returns a snapshot with shaped metrics for a specific 'Data.Text.Text' (or the+    -- original metrics when 'fmBackend' is 'Nothing'). 'drawShaped' shapes a+    -- run into 'ShapedGlyphs', and 'drawGlyph' looks up a single glyph's+    -- 'GlyphQuad' from the snapshot. A backend that loads other fonts or+    -- rasterizes at a new scale calls 'clearMeasureCache', so text is+    -- measured again with the new metrics.+  , FontMetrics (..)+  , FontBackend (..)+  , prepareFontMetrics+  , prepareFontMetricsMany+  , scaleFontMetrics+  , monospaceMetrics+  , uiFontMetrics+  , measureTextIO+  , lineWidthIO+  , lineWidth+  , drawShaped+  , drawGlyph+  , drawTextBox+  , GlyphQuad (..)+  , ShapedText (..)+  , ShapedGlyphs (..)+  , clearMeasureCache+  , wrapMeasureCache+  , textNodeFontVariant+  , textNodeFontTone+  , textNodeFontWeight+  , textNodeFontStyle+  , textNodeTextDecoration++    -- * Damage++    -- | What changed since the last frame, so a backend can present part of+    -- the window instead of all of it. 'takeDamage'+    -- reads the frame's damage; the @Now@ functions mark a rectangle from+    -- inside a view, which a custom widget that paints outside its own node+    -- needs. 'damageFull' queues a whole-window repaint from outside a view,+    -- as after a font change, when glyphs change under rects that did not.+  , Damage (..)+  , DamageBounds (..)+  , takeDamage+  , takeDamagePieces+  , damagePieces+  , damageIsEmpty+  , pixelEdges+  , clipPixelEdges+  , snapDamage+  , defaultDamageSlop+  , sliderDamageSlop+  , haloDamageSlop+  , resolveDamageRect+  , damageWidgetNow+  , damageKeyNow+  , damageRectNow+  , damageGroupNow+  , damageFullNow+  , damageFull++    -- * Frame metrics++    -- | Standard widget padding and scrollbar dimensions, exposed for backends+    -- that draw window chrome and for layout tests.+  , widgetContentInset+  , widgetPadding+  , treeItemPadding+  , ScrollBarSlot (..)+  , scrollBarGutter+  , scrollBarWidth+  , windowPad+  , windowMargin++    -- * Widget ids++    -- | How a @WidgetId@ is derived. A view uses @scope@, @withKey@ and+    -- @nextId@ from "NanoUI" instead; this is for code that hashes ids the+    -- same way nano-ui does. The operations on an 'IdContext' (the next+    -- sibling's id, entering a scope or a key) are in "NanoUI.Internal.Id",+    -- which can change without notice.+  , IdContext+  , initialIdContext+  , widgetId+  , hashWidgetId+  , mix64+  , mixFnv+  , burstNextIds++    -- * Compact allocation++    -- | The compact region long-lived host state is kept in, so the+    -- collector does not walk it every frame.+  , Compact+  , compactHost+  , askCompact++    -- * Debugging++    -- | Control the @explainLayout@ overlay from outside the view, for a+    -- backend option or a test harness.+  , setExplainLayout+  , getExplainLayout+  , getExplainedNode++    -- * System appearance++    -- | A backend that can read the desktop's light or dark setting reports+    -- it with 'setSystemAppearance' before the first frame and whenever it+    -- changes. Views read it with @systemAppearance@; a context set up with+    -- @followSystemTheme@ switches theme to match.+  , Appearance (..)+  , setSystemAppearance+  , getSystemAppearance++    -- * The native window++    -- | A backend opens its window from a 'NanoUI.WindowSettings' with its+    -- title, size, mode, resizability and transparency, then calls+    -- 'installWindowHost', which applies the remaining settings through the+    -- 'WindowHost'. The host carries out view requests such as+    -- 'NanoUI.setWindowTitle' and 'NanoUI.moveWindow'. Build it by+    -- updating 'defaultWindowHost', so fields added later are no-ops, and+    -- set 'hostCapabilities' to the operations it carries out, which views+    -- read with 'NanoUI.askWindowCapabilities'.+    --+    -- Each frame, before the view runs, report the window's scale, position,+    -- focus and mode with 'reportWindowState' (views read it with+    -- 'NanoUI.askWindow'). Once the frame is on screen, call+    -- 'answerScreenshots' with a capture of it.+    -- For a direct backbuffer use 'answerScreenshotsAfter' to capture before+    -- presentation but deliver callbacks afterwards. Bracket the whole session+    -- (including its opening frames) with 'closeWindowHost' and 'cancelTasks'+    -- before releasing native resources. Both cleanups are idempotent.+    --+    -- @runSessionLoop@ in "NanoUI.Runner" handles closing: a close request+    -- either ends the session or, per the settings, is passed to the view,+    -- and 'NanoUI.quit' ends it. A backend's own loop does the same with+    -- 'requestWindowClose' and 'quitRequested'; the next frame to run the+    -- view clears the request ('clearWindowClose').+  , WindowHost (..)+  , defaultWindowHost+  , WindowCapabilities (..)+  , noWindowCapabilities+  , allWindowCapabilities+  , installWindowHost+  , closeWindowHost+  , sizeLimitAt+  , WindowState (..)+  , defaultWindowState+  , reportWindowState+  , answerScreenshots+  , answerScreenshotsAfter+  , requestWindowClose+  , clearWindowClose+  , quitRequested++    -- ** More windows++    -- | A view declares further windows with 'NanoUI.nativeWindow'. After a+    -- frame, 'childWindows' lists those the view declared open; a backend+    -- opens a window for each new key, runs 'childView' as its view on a+    -- context of its own, and closes windows whose key stopped appearing.+    -- Each window's loop also runs its view when 'varChangeCount' has moved+    -- since that view last began, so a 'NanoUI.Var' written in one window+    -- shows in the others.+  , ChildWindow (..)+  , childWindows+  , childView+  , varChangeCount++    -- * The backend's session++    -- | Each backend names itself in the 'Backend' kind, gives a+    -- 'BackendSession' type family instance, and installs its session state+    -- with 'withBackendSession'. SDL has its own constructor; every other+    -- backend, RGFW included, uses @'Custom "name"@. Backend-specific view+    -- operations retrieve the session with 'askBackendSession' and the+    -- 'SBackend' singleton (returning 'Nothing' under other backends).+    --+    -- > type instance BackendSession 'Sdl = SdlEnv+    -- > askSdlEnv = askBackendSession SSdl+    -- >+    -- > type instance BackendSession ('Custom "mine") = MyEnv+    -- > askMyEnv = askBackendSession (SCustom (SSymbol @"mine"))+  , Backend (..)+  , SBackend (..)+  , BackendSession+  , withBackendSession+  , setBackendSession+  , backendSession+  , askBackendSession++    -- * Background work++    -- | Background jobs (@useTaskStatus@, @useTask@, @useStream@) and+    -- threads calling the action from @askWake@ wake the loop through the+    -- action installed with 'setWakeLoop' before the first frame. It must be+    -- callable from any thread and end the loop's wait for events, or make+    -- the next wait return at once, for example by pushing a custom event+    -- onto the platform queue. The core runs it once for a run of wakes until+    -- the loop takes them, and not for dirty marks made on the thread running+    -- @runSessionLoop@, so it needs no filtering of its own. Without it, a+    -- blocking loop shows a job's result only when other input arrives.+    --+    -- 'markDirty' belongs to the thread that runs frames, or to a callback+    -- that thread is blocked on, such as a resize watch. Any other thread+    -- publishes its change and then calls the action from @askWake@, which+    -- is safe from every thread.+    --+    -- Jobs run until their hooks stop being called. @runSessionLoop@ in+    -- "NanoUI.Runner" cancels the rest when it returns; a host that runs+    -- frames itself calls 'cancelTasks' when it closes the session.+  , setWakeLoop+  , setWakeLoopChecked+  , cancelTasks++    -- * Threads+  , inBoundThread+  )+where++import Control.Concurrent (rtsSupportsBoundThreads, runInBoundThread)++import NanoUI.Internal.Compact (Compact, askCompact, compactHost)+import NanoUI.Internal.BackendSession (Backend (..), BackendSession, SBackend (..))+import NanoUI.Internal.Context+  ( Context, newContext, newPixelContext, withFontMetrics, withMonoFontMetrics+  , withMeasureText, withFontResolver, withFontSize, withClipboard, withTheme+  , clearMeasureCache, wrapMeasureCache, damageFull+  , markDirty, clearDirty, isDirty, requestWakeAt, requestWakeAfter, getWakeAt+  , takeDamage, takeDamagePieces, registerImage, registerImages, releaseImage+  , atlasTextureId, atlasSnapshot, atlasChanges, AtlasUpload (..)+  , getExplainLayout, getExplainedNode, getFocusId, getSystemAppearance+  , setExplainLayout, setSystemAppearance, setWakeLoop, setWakeLoopChecked+  , withBackendSession, setBackendSession, backendSession+  , setShaderCapabilities, getShaderCapabilities, setDrawPixelScale+  )+import NanoUI.Internal.Context qualified as Ctx+import NanoUI.Internal.Shader (ShaderCapabilities (..), ShaderProgram (..), noShaderCapabilities)+import NanoUI.Internal.Uniforms (sysUniformBytes)+import NanoUI.Internal.Frame (runFrame)+import NanoUI.Internal.ChildWindow (ChildWindow (..), childView, childWindows)+import NanoUI.Internal.Var.Cell (varChangeCount)+import NanoUI.Internal.Frame.Spans (collectRasterSpans)+import NanoUI.Internal.Frame.Cursor (uiCursorKind)+import NanoUI.Internal.Damage (clipPixelEdges, damagePieces, pixelEdges, snapDamage)+import NanoUI.Internal.Frame.TextArea (TextInputArea (..), textInputArea)+import NanoUI.Internal.Draw hiding (setDrawPixelScale)+import NanoUI.Internal.EffectDriver+  ( EffectDriver (..)+  , EffectPassDraw (..)+  , execEffectSpans+  , withEffectUniforms+  )+import NanoUI.Internal.Font+import NanoUI.Internal.GenCache+  ( IntGenCache+  , intGenCacheInsert+  , intGenCacheLookup+  , intGenCacheSize+  , intGenCacheStartFrame+  , intGenCacheTouch+  , newIntGenCache+  )+import NanoUI.Internal.Id+import NanoUI.Internal.Input+import NanoUI.Internal.Monad+import NanoUI.Internal.NativeWindow+  ( WindowHost (..)+  , WindowCapabilities (..)+  , WindowState (..)+  , allWindowCapabilities+  , noWindowCapabilities+  , answerScreenshots+  , answerScreenshotsAfter+  , closeWindowHost+  , clearWindowClose+  , defaultWindowHost+  , defaultWindowState+  , installWindowHost+  , quitRequested+  , reportWindowState+  , requestWindowClose+  , sizeLimitAt+  )+import NanoUI.Internal.Style (Appearance (..), Layout (..), Theme, scrollBarThumbColor, scrollBarThumbHoverColor, scrollBarTrackColor, windowMargin, windowPad)+import NanoUI.Internal.Tasks (cancelTasks)+import NanoUI.Internal.Types+import NanoUI.Internal.WidgetText (textNodeFontStyle, textNodeFontTone, textNodeFontVariant, textNodeFontWeight, textNodeTextDecoration)++-- | Set a fixed theme on a context from outside a view.+setThemeIO :: Context -> Theme -> IO ()+setThemeIO = Ctx.setTheme++-- | Read the context's current base theme from outside a view.+getThemeIO :: Context -> IO Theme+getThemeIO = Ctx.getTheme++-- | Configure a context to follow OS light/dark changes from outside a view.+followSystemThemeIO :: Context -> (Maybe Appearance -> Theme) -> IO ()+followSystemThemeIO = Ctx.followSystemTheme++-- | Run an action on a bound thread, one OS thread for the whole run, or+-- as it is under the non-threaded runtime, which runs Haskell on one OS+-- thread anyway. A backend runs its session in it when native state belongs+-- to the OS thread that made it: an OpenGL context is current only on the+-- thread that made it current, and on Windows the thread that creates a+-- window pumps its messages. An unbound Haskell thread can move to another+-- OS thread across a safe foreign call.+inBoundThread :: IO a -> IO a+inBoundThread act = if rtsSupportsBoundThreads then runInBoundThread act else act
lib/NanoUI/Bidi.hs view
@@ -4,7 +4,8 @@ -- This is the implicit part of the Unicode bidirectional algorithm (UAX #9) -- for a single line: the paragraph direction from the first strong -- character, European and Arabic numbers, neutrals between runs, and--- reordering by level. Explicit embeddings, overrides, isolates and bracket+-- the separators and terminators that keep a number whole, and reordering+-- by level. Explicit embeddings, overrides, isolates and bracket -- pairs are not handled; text using them lays out as if they were absent. module NanoUI.Bidi   ( BidiRun (..)@@ -13,7 +14,7 @@   ) where  import Control.Applicative ((<|>))-import Data.Char (ord)+import Data.Char (GeneralCategory (..), generalCategory, ord) import Data.List.NonEmpty qualified as NE import Data.Text (Text) import Data.Text qualified as T@@ -26,7 +27,7 @@   }   deriving (Eq, Show) -data Class = L | R | AL | EN | AN | NSM | WS | ON+data Class = L | R | AL | EN | AN | ES | ET | CS | NSM | WS | ON   deriving (Eq, Show)  -- | Whether a line has characters that can flow right to left. A line@@ -61,6 +62,12 @@ classify c   | n < 0x0590 = latin   | n <= 0x05FF = if n >= 0x0591 && n <= 0x05C7 && n /= 0x05BE && n /= 0x05C0 && n /= 0x05C3 && n /= 0x05C6 then NSM else R+  -- Arabic number signs, comma, percent sign and decimal and thousands+  -- separators.+  | n >= 0x0600 && n <= 0x0605 = AN+  | n == 0x060C = CS+  | n == 0x066A = ET+  | n == 0x066B || n == 0x066C = AN   | n >= 0x0660 && n <= 0x0669 = AN   | n >= 0x06F0 && n <= 0x06F9 = EN   | n >= 0x064B && n <= 0x065F || n == 0x0670 || n >= 0x06D6 && n <= 0x06ED = NSM@@ -71,40 +78,84 @@   | n >= 0x200E && n <= 0x200F = if n == 0x200E then L else R   | n >= 0xFB1D && n <= 0xFB4F = R   | n >= 0xFB50 && n <= 0xFDFF = AL+  -- A byte order mark directs nothing.+  | n == 0xFEFF = ON   | n >= 0xFE70 && n <= 0xFEFF = AL   | n >= 0x2000 && n <= 0x206F = if n <= 0x200A || n == 0x2028 || n == 0x2029 then WS else ON   | n >= 0x10800 && n <= 0x10FFF = R   | n >= 0x1E800 && n <= 0x1EFFF = AL-  | otherwise = L+  | otherwise = case generalCategory c of+      NonSpacingMark -> NSM+      EnclosingMark -> NSM+      CurrencySymbol -> ET+      Space -> WS+      MathSymbol -> ON+      ModifierSymbol -> ON+      OtherSymbol -> ON+      ConnectorPunctuation -> ON+      DashPunctuation -> ON+      OpenPunctuation -> ON+      ClosePunctuation -> ON+      InitialQuote -> ON+      FinalQuote -> ON+      OtherPunctuation -> ON+      _ -> L   where     n = ord c     latin       | c >= '0' && c <= '9' = EN       | c == ' ' || c == '\t' = WS+      | c == '+' || c == '-' = ES+      | c == '#' || c == '$' || c == '%' = ET+      | c == ',' || c == '.' || c == '/' || c == ':' = CS       | n < 0x80 && not (isAsciiLetter c) = ON+      | n == 0xA0 = CS+      | n >= 0xA2 && n <= 0xA5 || n == 0xB0 || n == 0xB1 = ET       | n >= 0x80 && n <= 0xBF = ON       | n == 0xD7 || n == 0xF7 = ON       | n >= 0x0300 && n <= 0x036F = NSM       | otherwise = L     isAsciiLetter ch = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') --- | Weak types: a mark takes the class before it, a European number after--- Arabic letters reads as an Arabic number and one after Latin letters (or--- at the start of a left-to-right line) as Latin.+-- | Weak types (UAX #9 W1-W7): a mark takes the class before it; a European+-- number after Arabic letters reads as an Arabic number; a separator between+-- two numbers of one kind and terminators next to a European number join the+-- number, so 1.5, 1,000 and 50% stay whole; other separators are neutral; and+-- a European number after Latin letters (or at the start of a left-to-right+-- line) reads as Latin. resolveWeak :: Bool -> [Class] -> [Class]-resolveWeak paragraphRtl = go ON (if paragraphRtl then R else L)+resolveWeak paragraphRtl ks0 = w7 sos (map w6 w5)   where+    sos = if paragraphRtl then R else L+    -- W1-W3.+    w13 = go sos sos ks0     go _ _ [] = []     go prev lastStrong (k : ks) =       let k1 = if k == NSM then prev else k-          k2-            | k1 == EN && lastStrong == AL = AN-            | k1 == EN && lastStrong == L = L-            | otherwise = k1+          k2 = if k1 == EN && lastStrong == AL then AN else k1           k3 = if k2 == AL then R else k2           lastStrong' = if k1 == L || k1 == R || k1 == AL then k1 else lastStrong        in k3 : go k1 lastStrong' ks+    -- W4: one separator between two numbers of one kind.+    w4 = zipWith3 separator (Nothing : map Just w13) w13 (map Just (drop 1 w13) ++ [Nothing])+    separator (Just EN) ES (Just EN) = EN+    separator (Just EN) CS (Just EN) = EN+    separator (Just AN) CS (Just AN) = AN+    separator _ k _ = k+    -- W5: terminators next to a European number.+    groups = NE.groupBy (\a b -> (a == ET) == (b == ET)) w4+    w5 = concat (zipWith3 terminators (Nothing : map (Just . NE.last) groups) groups (map (Just . NE.head) (drop 1 groups) ++ [Nothing]))+    terminators before g after+      | NE.head g == ET && (before == Just EN || after == Just EN) = map (const EN) (NE.toList g)+      | otherwise = NE.toList g+    -- W6.+    w6 k = if k == ES || k == ET || k == CS then ON else k+    -- W7.+    w7 _ [] = []+    w7 lastStrong (k : ks) =+      (if k == EN && lastStrong == L then L else k) : w7 (if k == L || k == R then k else lastStrong) ks + -- | Neutrals between two characters of the same direction take it (numbers -- count as right to left here); other neutrals take the paragraph's. resolveNeutrals :: Bool -> [Class] -> [Class]@@ -128,7 +179,6 @@ implicitLevel base k   | even base = case k of       R -> base + 1-      AL -> base + 1       AN -> base + 2       EN -> base + 2       _ -> base
+ lib/NanoUI/Chrome.hs view
@@ -0,0 +1,23 @@+-- | Client-side window chrome for frameless windows: caption buttons,+-- window borders, and title-bar drag regions.+module NanoUI.Chrome+  ( -- * Caption buttons+    CaptionGlyph (..)+  , CaptionAction (..)+  , CaptionConfig (..)+  , defaultCaptionConfig+  , captionButton+  , captionButtons+  , captionButtonsConfigured++    -- * Window border+  , WindowFrame (..)+  , defaultWindowFrame+  , windowFrame++    -- * Geometry+  , captionBarHeight+  , dragSpans+  ) where++import NanoUI.Internal.Widgets.Caption
− lib/NanoUI/Compact.hs
@@ -1,25 +0,0 @@-{-# LANGUAGE TypeApplications #-}--module NanoUI.Compact-  ( Compact-  , compactHost-  , askCompact-  ) where--import Data.Typeable (Typeable)-import Effectful (Eff, type (:>))-import GHC.Compact (Compact, compact, getCompact)-import NanoUI.Context (Context, setHost)-import NanoUI.Monad (Ui, askHost)---- Pin read-heavy app state so GC treats it as one block.-compactHost :: Typeable a => Context -> a -> IO (Compact a)-compactHost ctx a = do-  region <- compact a-  setHost ctx region-  pure region--askCompact :: forall a es. (Typeable a, Ui :> es) => Eff es (Maybe a)-askCompact = do-  region <- askHost @(Compact a)-  pure (fmap getCompact region)
− lib/NanoUI/Context.hs
@@ -1,700 +0,0 @@--- | The 'Context' a view runs against, and the operations on its state:--- focus, dirty flags and damage, the widget store, drawing and measure--- caches, overlays, and host hooks. Backends and advanced widgets use this--- module; views normally only need "NanoUI".-module NanoUI.Context-  ( Context (..)-  , MeasureCacheKey-  , TextInputMenu (..)-  , TextInputDrag (..)-  , TextFieldClickCell (..)-  , WindowResizeEdge (..)-  , WindowResizeDrag (..)-  , DamageState (..)-  , OverlayState (..)-  , AnimationState (..)-  , DrawingCacheState (..)-  , DrawingEntry (..)-  , DrawFitCache (..)-  , SpanCacheEntry (..)-  , WidgetTextCacheEntry (..)-  , WidgetTextPlacement (..)-  , InteractionState (..)-  , initialInteractionState-  , initialDamageState-  , initialOverlayState-  , initialAnimationState-  , initialScrollState-  , initialDrawingCacheState-  , getsInteraction-  , modifyInteraction-  , getsOverlay-  , modifyOverlay-  , getsDamage-  , modifyDamage-  , getScrollDrag-  , setTextInputDrag-  , getTextInputMenu-  , setTextInputMenu-  , takeTextEditLastAction-  , getMenuPointerGesture-  , setMenuPointerGesture-  , getWindowDrag-  , getWindowResize-  , intKey-  , markDirty-  , clearDirty-  , isDirty-  , setWakeLoop-  , takeDamage-  , DamageRequest (..)-  , requestDamage-  , damageWidget-  , damageKey-  , damageRect-  , damagePeers-  , damageFull-  , registerPopupConfig-  , lookupPopupConfig-  , registerDrawing-  , lookupDrawing-  , cachedDrawingOps-  , cachedWidgetLayout-  , lookupDrawFitEnvelope-  , pruneDrawOpCache-  , CustomMeasureFn-  , CustomDrawContext (..)-  , CustomDrawBuild-  , registerCustomDrawing-  , lookupCustomDrawing-  , cachedCustomDrawingOps-  , refreshCustomDrawingOps-  , drawingOpsStale-  , CustomDrawingEntry (..)-  , registerCustomMeasure-  , lookupCustomMeasure-  , registerCustomCursor-  , lookupCustomCursor-  , registerCustomDamageSlop-  , lookupCustomDamageSlop-  , resetDrawingScopeCache-  , getStore-  , setStore-  , modifyStore-  , getStoreBool-  , writeStoreInt-  , writeStoreFloat-  , writeStoreBool-  , adoptStoreInt-  , adoptStoreFloat-  , adoptStoreText-  , recordStoreInt-  , recordStoreFloat-  , recordStoreText-  , isDisabled-  , newThemeScopes-  , beginThemeScopes-  , pushThemeScope-  , themeScopesChanged-  , scopeTheme-  , scopeRawTheme-  , currentTheme-  , nodeTheme-  , widgetTheme-  , getScrollOffset-  , setScrollOffset-  , getScrollOffset2D-  , setScrollOffset2D-  , setScrollConfig-  , defaultScrollConfig-  , linkScrollAxes-  , ScrollTuning (..)-  , defaultScrollTuning-  , getScrollTuning-  , setScrollTuning-  , getScrollStep-  , setScrollStep-  , resolveScrollStep-  , ScrollAxes (..)-  , ScrollMetrics (..)-  , getScrollMetrics-  , cacheScrollMetrics-  , beginScrollMetrics-  , getScrollOffsetIn-  , setScrollOffsetIn-  , ScrollBehavior (..)-  , ScrollAlign (..)-  , scrollTo-  , scrollBy-  , scrollPages-  , scrollToStart-  , scrollToEnd-  , scrollIntoView-  , scrollRectIntoView-  , applyScrollTarget-  , scrollTargetOffset-  , scrollGliding-  , clampScrollOffset-  , cancelScrollGlide-  , stepScrollGlides-  , getPrevRect-  , getPrevClipRect-  , atlasTextureId-  , registerImage-  , registerImages-  , lookupImageUv-  , atlasSnapshot-  , withFontMetrics-  , withMonoFontMetrics-  , withMeasureText-  , withFontResolver-  , wrapMeasureCache-  , clearMeasureCache-  , ensureMetricCaches-  , hasCustomLayoutInputs-  , withExternalText-  , withTheme-  , setTheme-  , getTheme-  , withClipboard-  , enableMeasureCache-  , setHost-  , setDrawSnapScale-  , setDrawSquareGeometry-  , setDrawExternalText-  , askHostIO-  , pushMessage-  , drainMessages-  -- Constructors-  , newContext-  , newPixelHostContext-  -- Focus-  , getFocusId-  , getFocusVisible-  , getHotId-  , registerFocusable-  , getFocusables-  -- Modal & Overlay-  , textInputEditActive-  , modalActive-  , overlayConsumesQuit-  , markEscapeConsumed-  , pointerBlockedByModal-  , pointerBlockedByOverlay-  , armMenuPointerCapture-  , seedFloatingPanel-  , beginModal-  , endModal-  , beginFrameModal-  , modalDamageFlip-  -- Animation-  , anyAnimating-  , getLiveAnimations-  , takeAnimSettled-  , lookupAnimation-  , getAnimRectless-  , setAnimRectless-  , startAnimation-  , startAnimationEase-  , startAnimationEaseDelay-  , startSpring-  , setAnimationValue-  , tickAnimations-  , getAnimationValue-  , getAnimRest-  , pruneAnimRest-  , FrameMsg (..)-  , decodeMessages-  , reduceMessages-  , reduceUpdates-  , WidgetStore (..)-  , bumpMirror-  , slotKey-  , Slot (..)-  , boolInt-  , intBool-  , anySelectOpen-  , isSelectOpen-  , setSelectOpen-  , closeSelects-  , Ease (..)-  , Animation (..)-  , SpringParams (..)-  , presetBouncy-  , presetSmooth-  , presetStiff-  , applyEase-  , easeSameSpec-  , approxEq-  , animInProgress-  ) where--import Control.Monad (foldM, forM, when)-import Data.Bits ((.&.))-import Data.ByteString (ByteString)-import Data.Dynamic (fromDynamic, toDyn)-import Data.HashMap.Strict (HashMap)-import Data.HashMap.Strict qualified as HashMap-import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Map.Strict qualified as Map-import Data.Primitive.PrimArray-  ( newPrimArray-  , readPrimArray-  , writePrimArray-  , getSizeofMutablePrimArray-  , resizeMutablePrimArray-  )-import Data.Proxy (Proxy (..))-import Data.Text (Text)-import Data.Typeable (Typeable, typeOf, typeRep)-import Data.Word (Word8)-import Foreign.ForeignPtr (ForeignPtr)--import NanoUI.Animation-  ( Animation (..)-  , Ease (..)-  , SpringParams (..)-  , animInProgress-  , applyEase-  , approxEq-  , easeSameSpec-  , presetBouncy-  , presetSmooth-  , presetStiff-  )-import NanoUI.Atlas (atlasTextureId)-import NanoUI.Atlas qualified as Atlas-import NanoUI.Context.Animation-import NanoUI.Context.Core-import NanoUI.Context.Drawing-import NanoUI.Context.Overlay-import NanoUI.Context.Scroll-import NanoUI.Context.Types-  ( AnimationState (..)-  , Context (..)-  , CustomDrawBuild-  , CustomDrawContext (..)-  , CustomDrawingEntry (..)-  , CustomMeasureFn-  , DamageRequest (..)-  , DamageState (..)-  , DrawFitCache (..)-  , DrawingCacheState (..)-  , DrawingEntry (..)-  , FrameMsg (..)-  , InteractionState (..)-  , MeasureCacheKey-  , MetricSource (..)-  , OverlayState (..)-  , SpanCacheEntry (..)-  , TextFieldClickCell (..)-  , TextInputDrag (..)-  , TextInputMenu (..)-  , WidgetTextCacheEntry (..)-  , WidgetTextPlacement (..)-  , WindowResizeDrag (..)-  , WindowResizeEdge (..)-  , decodeMessages-  , initialAnimationState-  , initialScrollState-  , initialDamageState-  , initialDrawingCacheState-  , initialInteractionState-  , initialOverlayState-  , intKey-  , reduceMessages-  , reduceUpdates-  )-import NanoUI.Draw (newDrawArena)-import NanoUI.Draw qualified as Draw-import NanoUI.Font (FontMetrics, fmLineHeight, measureTextIO, monospaceMetrics, scaleFontMetrics)-import NanoUI.Frame.SpanArena (newSpanArena)-import NanoUI.Frame.Scroll.Geometry (defaultScrollConfig)-import NanoUI.Id (WidgetId (..), initialIdContext)-import NanoUI.Layout.Arena (getArenaScope, newNodeArena)-import NanoUI.Store-  ( WidgetStore (..)-  , anySelectOpen-  , boolInt-  , bumpMirror-  , closeSelects-  , emptyWidgetStore-  , intBool-  , isSelectOpen-  , ptrEq-  , setSelectOpen-  , Slot (..)-  , slotKey-  )-import NanoUI.Style (FontStyle, FontVariant (..), FontWeight, Theme, defaultLayout, defaultTheme)-import NanoUI.Types (ImageId)--{-# INLINE registerImage #-}-registerImage :: Context -> ImageId -> Int -> Int -> ByteString -> IO Bool-registerImage ctx iid w h px = do-  ok <- Atlas.registerImage (ctxImageAtlas ctx) iid w h px-  when ok (markDirty ctx)-  pure ok--registerImages :: Foldable f => Context -> f (ImageId, Int, Int, ByteString) -> IO Bool-registerImages ctx = foldM register True-  where-    register ok (iid, w, h, px) = do-      result <- registerImage ctx iid w h px-      pure (ok && result)--{-# INLINE lookupImageUv #-}-lookupImageUv :: Context -> ImageId -> IO (Maybe (Float, Float, Float, Float))-lookupImageUv ctx = Atlas.lookupImageUv (ctxImageAtlas ctx)--{-# INLINE atlasSnapshot #-}-atlasSnapshot :: Context -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))-atlasSnapshot ctx = Atlas.atlasSnapshot (ctxImageAtlas ctx)---- | Metrics for a font variant scaled to line height @sz@, and the scale--- factor applied (1 when @sz@ or the base line height is not positive).-{-# INLINE resolveScale #-}-resolveScale :: Context -> Float -> FontVariant -> (FontMetrics, Float)-resolveScale ctx sz var =-  let baseFm = if var == FontMono then ctxMonoFontMetrics ctx else ctxFontMetrics ctx-      scale =-        if sz > 0 && fmLineHeight baseFm > 0-          then sz / fmLineHeight baseFm-          else 1.0-   in (if scale /= 1.0 then scaleFontMetrics scale baseFm else baseFm, scale)--defaultResolveFont :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)-defaultResolveFont ctx sz _w _st var = pure (fst (resolveScale ctx sz var), False)--defaultResolveMeasure :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)-defaultResolveMeasure ctx sz _w _st var txt-  | var == FontMono = measureTextIO textFm txt-  | scale /= 1.0 = (\(w, h) -> (w * scale, h * scale)) <$> ctxMeasureText ctx txt-  | otherwise = ctxMeasureText ctx txt-  where-    (textFm, scale) = resolveScale ctx sz var--{-# INLINE withFontResolver #-}-withFontResolver ::-  Context ->-  (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) ->-  (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) ->-  Context-withFontResolver ctx rf rm = trackMetricSource ctx {ctxResolveFont = rf, ctxResolveMeasure = rm}--withFontMetrics :: Context -> FontMetrics -> Context-withFontMetrics ctx fm =-  let ctx' =-        ctx-          { ctxFontMetrics = fm-          , ctxMeasureText = measureTextIO fm-          }-   in trackMetricSource ctx'-        { ctxResolveFont = defaultResolveFont ctx'-        , ctxResolveMeasure = defaultResolveMeasure ctx'-        }--withMonoFontMetrics :: Context -> FontMetrics -> Context-withMonoFontMetrics ctx mono =-  let ctx' = ctx {ctxMonoFontMetrics = mono}-   in trackMetricSource ctx'-        { ctxResolveFont = defaultResolveFont ctx'-        , ctxResolveMeasure = defaultResolveMeasure ctx'-        }--withMeasureText :: Context -> (Text -> IO (Float, Float)) -> Context-withMeasureText ctx fn =-  let ctx' = ctx {ctxMeasureText = fn}-   in trackMetricSource ctx'-        { ctxResolveMeasure = defaultResolveMeasure ctx'-        }---- Keep the identity boxed. No structural callback comparison or unsafe pure--- mutation is needed, and repeated frames with the same Context do no work.-trackMetricSource :: Context -> Context-trackMetricSource ctx =-  ctx {ctxMetricSource = MetricSource-    (ctxFontMetrics ctx) (ctxMonoFontMetrics ctx) (ctxMeasureText ctx)-    (ctxResolveFont ctx) (ctxResolveMeasure ctx)}---- | Called once before building a frame. Context configuration remains pure;--- cache invalidation happens at the IO boundary, including when alternating--- between differently configured Contexts that share their backing stores.-ensureMetricCaches :: Context -> IO ()-ensureMetricCaches ctx = do-  -- Compare evaluated identities: passed unevaluated, the selector application-  -- is a fresh thunk without optimisation, so the check would miss every-  -- frame and force full damage with cleared caches.-  let !current = ctxMetricSource ctx-  previous <- readIORef (ctxLastMetricSource ctx)-  case previous of-    Just source | ptrEq source current -> pure ()-    _ -> do-      clearMeasureCache ctx-      damageFull ctx-      markDirty ctx--cacheMeasureText ::-  IORef (HashMap MeasureCacheKey (Float, Float)) ->-  Float ->-  (Text -> IO (Float, Float)) ->-  Text ->-  IO (Float, Float)-cacheMeasureText ref scale base txt = do-  let key = (txt, scale)-  m <- readIORef ref-  case HashMap.lookup key m of-    Just sz -> pure sz-    Nothing -> do-      sz <- base txt-      modifyIORef' ref (HashMap.insert key sz)-      pure sz--wrapMeasureCache :: Float -> Context -> (Text -> IO (Float, Float)) -> Context-wrapMeasureCache scale ctx measure =-  case ctxMeasureCache ctx of-    Nothing -> trackMetricSource ctx {ctxMeasureText = measure}-    Just ref -> trackMetricSource ctx {ctxMeasureText = cacheMeasureText ref scale measure}---- | Drop text span, widget text and whole-layout caches and bump the metric--- generation, for changes that alter how text lays out.-invalidateTextCaches :: Context -> IO ()-invalidateTextCaches ctx = do-  writeIORef (ctxSpanCache ctx) IM.empty-  writeIORef (ctxWidgetTextCache ctx) IM.empty-  writeIORef (ctxLayoutCache ctx) Nothing-  modifyIORef' (ctxMetricGen ctx) (+ 1)--clearMeasureCache :: Context -> IO ()-clearMeasureCache ctx = do-  -- Store the evaluated source so 'ensureMetricCaches' can match its identity.-  let !source = ctxMetricSource ctx-  writeIORef (ctxLastMetricSource ctx) (Just source)-  invalidateTextCaches ctx-  case ctxMeasureCache ctx of-    Just ref -> writeIORef ref HashMap.empty-    Nothing -> pure ()--withExternalText :: Context -> Bool -> Context-withExternalText ctx ext = ctx {ctxExternalText = ext}---- | Configure a context's theme. Goes through 'setTheme' so a theme swapped--- between frames invalidates the caches keyed on it, drawing-op caches--- included, instead of leaving widgets painting the previous theme.-withTheme :: Context -> Theme -> IO Context-withTheme ctx theme = do-  setTheme ctx theme-  pure ctx--setTheme :: Context -> Theme -> IO ()-setTheme ctx th = do-  cur <- readIORef (ctxTheme ctx)-  when (cur /= th) $ do-    writeIORef (ctxTheme ctx) th-    invalidateTextCaches ctx-    damageFull ctx-    markDirty ctx--getTheme :: Context -> IO Theme-getTheme ctx = readIORef (ctxTheme ctx)--withClipboard :: Context -> IO (Maybe Text) -> (Text -> IO Bool) -> Context-withClipboard ctx getter setter = ctx {ctxClipboardGet = getter, ctxClipboardSet = setter}--enableMeasureCache :: Context -> IO Context-enableMeasureCache ctx =-  case ctxMeasureCache ctx of-    Just _ -> pure ctx-    Nothing -> do-      ref <- newIORef HashMap.empty-      pure ctx {ctxMeasureCache = Just ref, ctxMeasureText = cacheMeasureText ref 0 (ctxMeasureText ctx)}--{-# INLINE setHost #-}-setHost :: forall a. (Typeable a) => Context -> a -> IO ()-setHost ctx val = do-  m <- readIORef (ctxHost ctx)-  let k = typeOf val-  writeIORef (ctxHost ctx) (Map.insert k (toDyn val) m)---- | Set the device pixel scale used to snap geometry origins/endpoints to--- whole pixels. The SDL backend calls this when the window pixel density is synced.-{-# INLINE setDrawSnapScale #-}-setDrawSnapScale :: Context -> Float -> IO ()-setDrawSnapScale ctx s = Draw.setDrawSnapScale (ctxDrawArena ctx) s---- | Emit rounded shapes and AA strokes as flat, axis-aligned fills. Software--- framebuffer hosts enable this so every primitive is a solid quad.-{-# INLINE setDrawSquareGeometry #-}-setDrawSquareGeometry :: Context -> Bool -> IO ()-setDrawSquareGeometry ctx = Draw.setDrawSquareGeometry (ctxDrawArena ctx)---- | Skip text quads in the draw buffer. Hosts that rasterize text from the--- collected text spans enable this.-{-# INLINE setDrawExternalText #-}-setDrawExternalText :: Context -> Bool -> IO ()-setDrawExternalText ctx = Draw.setDrawExternalText (ctxDrawArena ctx)--{-# INLINE askHostIO #-}-askHostIO :: forall a. (Typeable a) => Context -> IO (Maybe a)-askHostIO ctx = do-  m <- readIORef (ctxHost ctx)-  let k = typeRep (Proxy :: Proxy a)-  pure (Map.lookup k m >>= fromDynamic)--{-# INLINE pushMessage #-}-pushMessage :: Context -> FrameMsg -> IO ()-pushMessage ctx msg = modifyIORef' (ctxMessages ctx) (msg :)--{-# INLINE drainMessages #-}-drainMessages :: Context -> IO [FrameMsg]-drainMessages ctx = do-  msgs <- readIORef (ctxMessages ctx)-  writeIORef (ctxMessages ctx) []-  pure (reverse msgs)---- =============================================================================--- Constructors--- =============================================================================--newContext :: IO Context-newContext = do-  nodeArena <- newNodeArena-  drawArena <- newDrawArena-  ctxHotId <- newIORef (WidgetId 0)-  ctxLastHotId <- newIORef (WidgetId 0)-  ctxActiveId <- newIORef (WidgetId 0)-  ctxClickedId <- newIORef (WidgetId 0)-  ctxReleaseClickedId <- newIORef (WidgetId 0)-  ctxPressPos <- newIORef Nothing-  ctxRightPressPos <- newIORef Nothing-  ctxFocusId <- newIORef (WidgetId 0)-  ctxFocusVisible <- newIORef False-  ctxStore <- newIORef emptyWidgetStore-  ctxDamageState <- newIORef initialDamageState-  ctxOverlayState <- newIORef initialOverlayState-  ctxAnimationState <- newIORef initialAnimationState-  ctxScrollState <- newIORef initialScrollState-  ctxDrawingCache <- newIORef initialDrawingCacheState-  ctxIdContext <- newIORef initialIdContext-  ctxContainerStack <- newIORef []-  ctxMessages <- newIORef []-  let initCap = 64-  ctxFocusables <- newIORef =<< newPrimArray initCap-  ctxFocusablesCount <- newIORef 0-  ctxSpanBase <- newSpanArena 64-  ctxSpanOverlay <- newSpanArena 64-  ctxInteractionState <- newIORef initialInteractionState-  ctxImageAtlas <- Atlas.newImageAtlas-  ctxWakeLoop <- newIORef Nothing-  ctxHost <- newIORef Map.empty-  ctxDefaultLayout <- newIORef defaultLayout-  ctxTheme <- newIORef defaultTheme-  ctxThemeScopes <- newIORef =<< newThemeScopes-  ctxSpanCache <- newIORef IM.empty-  ctxWidgetTextCache <- newIORef IM.empty-  ctxLayoutCache <- newIORef Nothing-  ctxMetricGen <- newIORef 0-  ctxLastMetricSource <- newIORef Nothing-  ctxPaintFull <- newIORef True-  let fm0 = monospaceMetrics 12-      ctx = Context-        { ctxNodeArena = nodeArena-        , ctxDrawArena = drawArena-        , ctxHotId-        , ctxLastHotId-        , ctxActiveId-        , ctxClickedId-        , ctxReleaseClickedId-        , ctxPressPos-        , ctxRightPressPos-        , ctxFocusId-        , ctxFocusVisible-        , ctxStore-        , ctxDamageState-        , ctxOverlayState-        , ctxAnimationState-        , ctxScrollState-        , ctxDrawingCache-        , ctxIdContext-        , ctxFontMetrics = fm0-        , ctxMonoFontMetrics = fm0-        , ctxMeasureText = measureTextIO fm0-        , ctxResolveFont = defaultResolveFont ctx-        , ctxResolveMeasure = defaultResolveMeasure ctx-        , ctxMeasureCache = Nothing-        , ctxSpanCache-        , ctxWidgetTextCache-        , ctxLayoutCache-        , ctxMetricGen-        , ctxMetricSource = InitialMetricSource-        , ctxLastMetricSource-        , ctxPaintFull-        , ctxExternalText = False-        , ctxTheme-        , ctxThemeScopes-        , ctxContainerStack-        , ctxMessages-        , ctxFocusables-        , ctxFocusablesCount-        , ctxSpanBase-        , ctxSpanOverlay-        , ctxInteractionState-        , ctxClipboardGet = pure Nothing-        , ctxClipboardSet = \_ -> pure False-        , ctxImageAtlas-        , ctxWakeLoop-        , ctxHost-        , ctxDefaultLayout-        }-  pure ctx--newPixelHostContext :: IO Context-newPixelHostContext = do-  ctx0 <- newContext-  ctx <- enableMeasureCache ctx0-  withTheme (withExternalText (withFontMetrics ctx (monospaceMetrics 16)) True) defaultTheme---- =============================================================================--- Focus--- =============================================================================--{-# INLINE getFocusId #-}-getFocusId :: Context -> IO WidgetId-getFocusId ctx = readIORef (ctxFocusId ctx)---- | Whether the focused widget shows its focus ring: focus moved by keyboard--- since the last pointer press.-{-# INLINE getFocusVisible #-}-getFocusVisible :: Context -> IO Bool-getFocusVisible ctx = readIORef (ctxFocusVisible ctx)--{-# INLINE getHotId #-}-getHotId :: Context -> IO WidgetId-getHotId ctx = readIORef (ctxHotId ctx)---- | Add @wid@ to this frame's keyboard focus order, unless it is declared in a--- disabled scope.-registerFocusable :: Context -> WidgetId -> IO ()-registerFocusable ctx wid = do-  scope <- getArenaScope (ctxNodeArena ctx)-  when (scope .&. 1 == 0) $ do-    idx <- readIORef (ctxFocusablesCount ctx)-    arr <- readIORef (ctxFocusables ctx)-    cap <- getSizeofMutablePrimArray arr-    arr' <--      if idx >= cap-        then do-          grown <- resizeMutablePrimArray arr (max 16 (cap * 2))-          writeIORef (ctxFocusables ctx) grown-          pure grown-        else pure arr-    writePrimArray arr' idx wid-    writeIORef (ctxFocusablesCount ctx) (idx + 1)--{-# INLINE getFocusables #-}-getFocusables :: Context -> IO [WidgetId]-getFocusables ctx = do-  count <- readIORef (ctxFocusablesCount ctx)-  arr <- readIORef (ctxFocusables ctx)-  forM [0 .. count - 1] (readPrimArray arr)
− lib/NanoUI/Context/Animation.hs
@@ -1,217 +0,0 @@--- | Per-widget animations: starting, ticking, settling and reading values.-module NanoUI.Context.Animation-  ( anyAnimating-  , getLiveAnimations-  , isAnimatingKey-  , takeAnimSettled-  , lookupAnimation-  , getAnimRectless-  , setAnimRectless-  , startAnimation-  , startAnimationEase-  , startAnimationEaseDelay-  , startSpring-  , setAnimationValue-  , tickAnimations-  , getAnimationValue-  , getAnimRest-  , pruneAnimRest-  ) where--import Control.Monad (unless, when)-import Data.IORef (modifyIORef', readIORef, writeIORef)-import Data.IntMap.Strict (IntMap)-import Data.IntMap.Strict qualified as IM--import NanoUI.Animation-  ( Animation (..)-  , Ease (..)-  , SpringParams-  , animInProgress-  , animationValue-  , approxEq-  , easeSameSpec-  , springEps-  , stepAnim-  , writeRest-  )-import NanoUI.Context.Core (damageKey, getsDamage, markDirty)-import NanoUI.Context.Types (AnimationState (..), Context (..), DamageState (..), ScrollState (..), intKey)-import NanoUI.Id (WidgetId)-import NanoUI.Layout.Arena (getRect, lookupNodeByKey)-import NanoUI.Types (DamageBounds (..), defaultDamageSlop)---- | Whether the frame loop has to keep drawing: an animation is running, or a--- scroller is still gliding onto its target.-{-# INLINE anyAnimating #-}-anyAnimating :: Context -> IO Bool-anyAnimating ctx = do-  anim <- asAnyAnimating <$> readIORef (ctxAnimationState ctx)-  if anim-    then pure True-    else not . IM.null . ssGlides <$> readIORef (ctxScrollState ctx)--{-# INLINE getLiveAnimations #-}-getLiveAnimations :: Context -> IO (IntMap Animation)-getLiveAnimations ctx = IM.filter animInProgress . asAnimations <$> readIORef (ctxAnimationState ctx)---- | Whether the widget key has an animation in progress. Unlike--- 'getLiveAnimations' this does not rebuild the animation map.-{-# INLINE isAnimatingKey #-}-isAnimatingKey :: Context -> Int -> IO Bool-isAnimatingKey ctx key =-  maybe False animInProgress . IM.lookup key . asAnimations <$> readIORef (ctxAnimationState ctx)---- Consecutive frames each live animation has had no nonzero widget rect in the--- arena. Maintained by 'NanoUI.Damage.updatePrevRects'; used by 'writeDamage'--- to bound the DamageFull escalation for rect-less animations so a perpetual--- animation whose widget left the arena (e.g. `keepAnimating` on a widget--- hidden by a tab switch) stops repainting the whole window after a frame or--- two, instead of forever.-{-# INLINE getAnimRectless #-}-getAnimRectless :: Context -> IO (IntMap Int)-getAnimRectless ctx = asRectless <$> readIORef (ctxAnimationState ctx)--{-# INLINE setAnimRectless #-}-setAnimRectless :: Context -> IntMap Int -> IO ()-setAnimRectless ctx m =-  modifyIORef' (ctxAnimationState ctx) $ \as -> as {asRectless = m}--takeAnimSettled :: Context -> IO Bool-takeAnimSettled ctx = do-  as <- readIORef (ctxAnimationState ctx)-  if asAnimSettled as-    then do-      writeIORef (ctxAnimationState ctx) $! as {asAnimSettled = False}-      pure True-    else pure False--{-# INLINE lookupAnimation #-}-lookupAnimation :: Context -> WidgetId -> IO (Maybe Animation)-lookupAnimation ctx wid = IM.lookup (intKey wid) . asAnimations <$> readIORef (ctxAnimationState ctx)--{-# INLINE startAnimation #-}-startAnimation :: Context -> WidgetId -> Float -> Float -> Float -> IO ()-startAnimation ctx wid start end dur = startAnimationEase ctx wid start end dur EaseLinear--{-# INLINE startAnimationEase #-}-startAnimationEase :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> IO ()-startAnimationEase ctx wid start end dur ease = startAnimationEaseDelay ctx wid start end dur ease 0--startAnimationEaseDelay :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> Float -> IO ()-startAnimationEaseDelay ctx wid start end dur ease delay-  | dur <= 0 || approxEq start end = settleKey ctx key end-  | otherwise = do-      as <- readIORef (ctxAnimationState ctx)-      let req = max 0 delay-      case IM.lookup key (asAnimations as) of-        Just a@(EaseAnim aStart _ _ _ _ _ _) | approxEq aStart start && easeSameSpec a ease dur req end -> pure ()-        _ ->-          writeIORef (ctxAnimationState ctx) $!-            as-              { asAnimRest = IM.delete key (asAnimRest as)-              , asAnimations = IM.insert key (EaseAnim start end dur 0 ease req req) (asAnimations as)-              , asAnyAnimating = True-              }-      markDirtyIfOrphan ctx key-  where-    key = intKey wid--startSpring :: Context -> WidgetId -> SpringParams -> Float -> IO ()-startSpring ctx wid params target = do-  let key = intKey wid-  as <- readIORef (ctxAnimationState ctx)-  case IM.lookup key (asAnimations as) of-    Just (SpringAnim _ _ t p) | t == target && p == params -> markDirtyIfOrphan ctx key-    running -> do-      let (pos, vel) = case running of-            Just (SpringAnim p v _ _) -> (p, v)-            Just a -> (animationValue a, 0)-            Nothing -> (IM.findWithDefault 0 key (asAnimRest as), 0)-      if abs (pos - target) <= springEps && abs vel <= springEps-        then settleKey ctx key target-        else do-          writeIORef (ctxAnimationState ctx) $!-            as-              { asAnimRest = IM.delete key (asAnimRest as)-              , asAnimations = IM.insert key (SpringAnim pos vel target params) (asAnimations as)-              , asAnyAnimating = True-              }-          markDirtyIfOrphan ctx key--{-# INLINE setAnimationValue #-}-setAnimationValue :: Context -> WidgetId -> Float -> IO ()-setAnimationValue ctx wid val = settleKey ctx (intKey wid) val--tickAnimations :: Context -> Float -> IO ()-tickAnimations ctx dt =-  modifyIORef' (ctxAnimationState ctx) $ \as ->-    if IM.null (asAnimations as)-      then as {asAnyAnimating = False, asAnimSettled = False}-      else-        let stepped = IM.map (stepAnim dt) (asAnimations as)-            (live, done) = IM.partition animInProgress stepped-            rest' = IM.foldlWithKey' writeRest (asAnimRest as) done-         in as-              { asAnimations = live-              , asAnimRest = rest'-              , asAnyAnimating = not (IM.null live)-              , asAnimSettled = not (IM.null done)-              }--markDirtyIfOrphan :: Context -> Int -> IO ()-markDirtyIfOrphan ctx key = do-  hadRect <- IM.member key <$> getsDamage ctx dsPrevRects-  hasNow <- nodeHasKey ctx key-  unless (hadRect || hasNow) (markDirty ctx)--nodeHasKey :: Context -> Int -> IO Bool-nodeHasKey ctx key = do-  mIdx <- lookupNodeByKey (ctxNodeArena ctx) key-  case mIdx of-    Nothing -> pure False-    Just idx -> do-      (_, _, w, h) <- getRect (ctxNodeArena ctx) idx-      pure (w > 0 && h > 0)--settleKey :: Context -> Int -> Float -> IO ()-settleKey ctx key val = do-  as <- readIORef (ctxAnimationState ctx)-  let rest = asAnimRest as-      prevRest = IM.findWithDefault 0 key rest-      prevLive = IM.lookup key (asAnimations as)-      restChanged-        | approxEq val 0 = IM.member key rest-        | otherwise = prevRest /= val-      rest'-        | not restChanged = rest-        | approxEq val 0 = IM.delete key rest-        | otherwise = IM.insert key val rest-  -- A spring at rest settles every frame; write only what changes.-  case prevLive of-    Just _ -> do-      let anims' = IM.delete key (asAnimations as)-      writeIORef (ctxAnimationState ctx) $!-        as {asAnimations = anims', asAnimRest = rest', asAnyAnimating = not (IM.null anims')}-    Nothing -> when restChanged $ writeIORef (ctxAnimationState ctx) $! as {asAnimRest = rest'}-  when (maybe (not (approxEq prevRest val)) (not . approxEq val . animationValue) prevLive) $ do-    damageKey ctx key (DamageInflated defaultDamageSlop)-    markDirty ctx--getAnimationValue :: Context -> WidgetId -> IO Float-getAnimationValue ctx wid = do-  let key = intKey wid-  as <- readIORef (ctxAnimationState ctx)-  case IM.lookup key (asAnimations as) of-    Just a -> pure $! animationValue a-    Nothing -> pure $! IM.findWithDefault 0 key (asAnimRest as)--{-# INLINE getAnimRest #-}-getAnimRest :: Context -> IO (IntMap Float)-getAnimRest ctx = asAnimRest <$> readIORef (ctxAnimationState ctx)--{-# INLINE pruneAnimRest #-}-pruneAnimRest :: Context -> (Int -> Bool) -> IO ()-pruneAnimRest ctx shouldKeep =-  modifyIORef' (ctxAnimationState ctx) $ \as ->-    as {asAnimRest = IM.filterWithKey (\k _ -> shouldKeep k) (asAnimRest as)}
− lib/NanoUI/Context/Core.hs
@@ -1,528 +0,0 @@--- | Accessors the other Context modules build on: interaction, overlay and--- damage state, damage requests, the dirty flag, and widget store writes.-module NanoUI.Context.Core-  ( getsInteraction-  , modifyInteraction-  , getsOverlay-  , modifyOverlay-  , getsDamage-  , modifyDamage-  -- Interaction-  , getScrollDrag-  , setTextInputDrag-  , getTextInputMenu-  , setTextInputMenu-  , takeTextEditLastAction-  , getMenuPointerGesture-  , setMenuPointerGesture-  , getWindowDrag-  , getWindowResize-  -- Damage-  , markDirty-  , clearDirty-  , isDirty-  , setWakeLoop-  , takeDamage-  , requestDamage-  , damageWidget-  , damageKey-  , damageRect-  , damagePeers-  , damageFull-  , getPrevRect-  , getPrevClipRect-  -- Store-  , getStore-  , setStore-  , modifyStore-  , getStoreBool-  , writeStoreInt-  , writeStoreFloat-  , writeStoreBool-  , adoptStoreInt-  , adoptStoreFloat-  , adoptStoreText-  , recordStoreInt-  , recordStoreFloat-  , recordStoreText-  , isDisabled-  -- Theme scopes-  , newThemeScopes-  , beginThemeScopes-  , pushThemeScope-  , themeScopesChanged-  , scopeTheme-  , scopeRawTheme-  , currentTheme-  , nodeTheme-  , widgetTheme-  ) where--import Control.Monad (forM_, when)-import Data.Bits (shiftR, (.&.))-import Data.IORef (modifyIORef', readIORef, writeIORef)-import Data.Primitive.SmallArray (copySmallMutableArray, newSmallArray, readSmallArray, getSizeofSmallMutableArray, writeSmallArray)-import Data.IntMap.Strict (IntMap)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)--import NanoUI.Context.Types-  ( Context (..)-  , DamageRequest (..)-  , DamageState (..)-  , InteractionState (..)-  , OverlayState-  , TextInputDrag-  , TextInputMenu-  , ThemeScopes (..)-  , WindowResizeDrag-  , intKey-  )-import NanoUI.Id (WidgetId, hashWidgetId)-import NanoUI.Layout.Arena (DirTag, NodeIdx, getArenaScope, getNodeScope, getScopeSignature, lookupNodeByWidgetId)-import NanoUI.Store-  ( WidgetStore (..)-  , boolInt-  , intBool-  , ptrEq-  , slotKey-  , Slot (..)-  )-import NanoUI.Style (Theme)-import NanoUI.Types (Damage, DamageBounds (..), Rect, defaultDamageSlop, rectH, rectW)-import NanoUI.Widgets.TextCommand (TextCommand)---- =============================================================================--- State records--- =============================================================================--{-# INLINE getsInteraction #-}-getsInteraction :: Context -> (InteractionState -> a) -> IO a-getsInteraction ctx f = f <$> readIORef (ctxInteractionState ctx)--{-# INLINE modifyInteraction #-}-modifyInteraction :: Context -> (InteractionState -> InteractionState) -> IO ()-modifyInteraction ctx = modifyIORef' (ctxInteractionState ctx)--{-# INLINE getsOverlay #-}-getsOverlay :: Context -> (OverlayState -> a) -> IO a-getsOverlay ctx f = f <$> readIORef (ctxOverlayState ctx)--{-# INLINE modifyOverlay #-}-modifyOverlay :: Context -> (OverlayState -> OverlayState) -> IO ()-modifyOverlay ctx = modifyIORef' (ctxOverlayState ctx)--{-# INLINE getsDamage #-}-getsDamage :: Context -> (DamageState -> a) -> IO a-getsDamage ctx f = f <$> readIORef (ctxDamageState ctx)--{-# INLINE modifyDamage #-}-modifyDamage :: Context -> (DamageState -> DamageState) -> IO ()-modifyDamage ctx = modifyIORef' (ctxDamageState ctx)---- =============================================================================--- Interaction--- =============================================================================--{-# INLINE getScrollDrag #-}-getScrollDrag :: Context -> IO (Maybe (WidgetId, DirTag, Float))-getScrollDrag ctx = getsInteraction ctx isScrollDrag--{-# INLINE setTextInputDrag #-}-setTextInputDrag :: Context -> Maybe TextInputDrag -> IO ()-setTextInputDrag ctx v = modifyInteraction ctx (\s -> s {isTextInputDrag = v})--{-# INLINE getTextInputMenu #-}-getTextInputMenu :: Context -> IO (Maybe TextInputMenu)-getTextInputMenu ctx = getsInteraction ctx isTextInputMenu--{-# INLINE setTextInputMenu #-}-setTextInputMenu :: Context -> Maybe TextInputMenu -> IO ()-setTextInputMenu ctx v = modifyInteraction ctx (\s -> s {isTextInputMenu = v})--takeTextEditLastAction :: Context -> IO (Maybe (WidgetId, TextCommand))-takeTextEditLastAction ctx = do-  act <- getsInteraction ctx isTextEditLastAction-  modifyInteraction ctx (\s -> s {isTextEditLastAction = Nothing})-  pure act--{-# INLINE getMenuPointerGesture #-}-getMenuPointerGesture :: Context -> IO Bool-getMenuPointerGesture ctx = getsInteraction ctx isMenuPointerGesture--{-# INLINE setMenuPointerGesture #-}-setMenuPointerGesture :: Context -> Bool -> IO ()-setMenuPointerGesture ctx v = modifyInteraction ctx (\s -> s {isMenuPointerGesture = v})--{-# INLINE getWindowDrag #-}-getWindowDrag :: Context -> IO (Maybe (WidgetId, Float, Float))-getWindowDrag ctx = getsInteraction ctx isWindowDrag--{-# INLINE getWindowResize #-}-getWindowResize :: Context -> IO (Maybe WindowResizeDrag)-getWindowResize ctx = getsInteraction ctx isWindowResize---- =============================================================================--- Damage--- =============================================================================--{-# INLINE requestDamage #-}-requestDamage :: Context -> DamageRequest -> IO ()-requestDamage ctx req = modifyDamage ctx (\ds -> ds {dsRequests = req : dsRequests ds})--{-# INLINE damageWidget #-}-damageWidget :: Context -> WidgetId -> DamageBounds -> IO ()-damageWidget ctx wid bounds-  | hashWidgetId wid == 0 = pure ()-  | otherwise = requestDamage ctx (ReqWidget wid bounds)--{-# INLINE damageKey #-}-damageKey :: Context -> Int -> DamageBounds -> IO ()-damageKey ctx k bounds-  | k == 0 = pure ()-  | otherwise = requestDamage ctx (ReqKey k bounds)--{-# INLINE damageRect #-}-damageRect :: Context -> Rect -> IO ()-damageRect ctx r-  | rectW r <= 0 || rectH r <= 0 = pure ()-  | otherwise = requestDamage ctx (ReqRect r)--{-# INLINE damagePeers #-}-damagePeers :: Context -> [WidgetId] -> DamageBounds -> IO ()-damagePeers ctx wids bounds =-  case filter (\w -> hashWidgetId w /= 0) wids of-    [] -> pure ()-    valid -> requestDamage ctx (ReqPeers valid bounds)--{-# INLINE damageFull #-}-damageFull :: Context -> IO ()-damageFull ctx = requestDamage ctx ReqFull--{-# INLINE markDirty #-}-markDirty :: Context -> IO ()-markDirty ctx = do-  modifyDamage ctx (\ds -> ds {dsDirty = True})-  readIORef (ctxWakeLoop ctx) >>= sequence_--{-# INLINE clearDirty #-}-clearDirty :: Context -> IO ()-clearDirty ctx = modifyDamage ctx (\ds -> ds {dsDirty = False})--{-# INLINE isDirty #-}-isDirty :: Context -> IO Bool-isDirty ctx = getsDamage ctx dsDirty--{-# INLINE setWakeLoop #-}-setWakeLoop :: Context -> IO () -> IO ()-setWakeLoop ctx wake = writeIORef (ctxWakeLoop ctx) (Just wake)--{-# INLINE takeDamage #-}-takeDamage :: Context -> IO Damage-takeDamage ctx = getsDamage ctx dsDamage--{-# INLINE getPrevRect #-}-getPrevRect :: Context -> WidgetId -> IO (Maybe Rect)-getPrevRect ctx wid = getsDamage ctx (IM.lookup (intKey wid) . dsPrevRects)--{-# INLINE getPrevClipRect #-}-getPrevClipRect :: Context -> WidgetId -> IO (Maybe Rect)-getPrevClipRect ctx wid = getsDamage ctx (IM.lookup (intKey wid) . dsPrevClips)---- =============================================================================--- Store--- =============================================================================--{-# INLINE getStore #-}-getStore :: Context -> IO WidgetStore-getStore ctx = readIORef (ctxStore ctx)--setStore :: Context -> WidgetStore -> IO ()-setStore ctx store = modifyStore ctx (const store)---- | Replace the store with @f@ of it, damaging the keys whose values changed--- and waking the loop when anything did.-modifyStore :: Context -> (WidgetStore -> WidgetStore) -> IO ()-modifyStore ctx f = do-  prev <- readIORef (ctxStore ctx)-  -- WHNF-force the new record: record-update arguments are unevaluated-  -- thunks, and writeIORef would otherwise park one in the long-lived store-  -- every frame.-  let !store = f prev-  writeIORef (ctxStore ctx) store-  let changedKeys =-        diffKeys (storeInt prev) (storeInt store)-          ++ diffKeys (storeFloat prev) (storeFloat store)-          ++ diffKeys (storeDouble prev) (storeDouble store)-          ++ diffKeys (storePoint prev) (storePoint store)-          ++ diffKeys (storeText prev) (storeText store)-          ++ diffKeys (storeFloatList prev) (storeFloatList store)-          ++ diffKeys (storeIntList prev) (storeIntList store)-          ++ diffKeys (storeIntSet prev) (storeIntSet store)-          ++ diffKeysBy ptrEq (storeDyn prev) (storeDyn store)-  -- The key diff doubles as the store comparison: checking 'prev /= store'-  -- first would walk every changed map twice. Its lazy concatenation stops at-  -- the first changed key and allocates less than a list per map.-  when-    ( storeMirrorGen prev /= storeMirrorGen store-        || storeOpenSelect prev /= storeOpenSelect store-        || not (null changedKeys)-    )-    $ do-      forM_ changedKeys $ \k -> damageKey ctx k (DamageInflated defaultDamageSlop)-      markDirty ctx--diffKeysBy :: (a -> a -> Bool) -> IntMap a -> IntMap a -> [Int]-diffKeysBy eq old new-  -- Unchanged maps keep their identity through a record update; skip the-  -- whole merge when the caller only rebuilt a different field.-  | ptrEq old new = []-  | otherwise =-      IM.keys-        ( IM.mergeWithKey-            (\_ a b -> if eq a b then Nothing else Just ())-            (IM.map (const ()))-            (IM.map (const ()))-            old-            new-        )--diffKeys :: Eq a => IntMap a -> IntMap a -> [Int]-diffKeys = diffKeysBy (==)---- | Targeted single-slot write: compares only the target slot, updates one map--- field, damages the owning widget and wakes the loop. Unlike 'setStore' it--- never diffs the whole store, and an equal write is a no-op.-{-# INLINE writeSlot #-}-writeSlot ::-  Eq a =>-  (WidgetStore -> IntMap a) ->-  (IntMap a -> WidgetStore -> WidgetStore) ->-  Context ->-  WidgetId ->-  Int ->-  a ->-  IO ()-writeSlot field setField ctx owner k v = do-  st <- readIORef (ctxStore ctx)-  case IM.lookup k (field st) of-    Just old | old == v -> pure ()-    _ -> do-      writeIORef (ctxStore ctx) $! setField (IM.insert k v (field st)) st-      damageWidget ctx owner DamageSelf-      markDirty ctx--writeStoreInt :: Context -> WidgetId -> Int -> Int -> IO ()-writeStoreInt = writeSlot storeInt (\m st -> st {storeInt = m})--writeStoreFloat :: Context -> WidgetId -> Int -> Float -> IO ()-writeStoreFloat = writeSlot storeFloat (\m st -> st {storeFloat = m})--{-# INLINE writeStoreBool #-}-writeStoreBool :: Context -> WidgetId -> Bool -> IO ()-writeStoreBool ctx owner v = writeStoreInt ctx owner (intKey owner) (boolInt v)---- | Controlled widgets take their value from the caller every frame. The--- caller's value replaces the stored one only when it differs from the value--- the widget last returned ('recordSlot'). An edit applied between frames,--- such as a menu cut, then survives a caller that passes the previous result--- back, while a value changed by the application still wins. Returns the--- slot's value after adopting.-{-# INLINE adoptSlot #-}-adoptSlot ::-  Eq a =>-  (WidgetStore -> IntMap a) ->-  (IntMap a -> WidgetStore -> WidgetStore) ->-  Context ->-  WidgetId ->-  Int ->-  a ->-  IO a-adoptSlot field setField ctx owner k v = do-  st <- readIORef (ctxStore ctx)-  let-    m = field st-    seenK = slotKey SlotSeen k-  if IM.lookup seenK m == Just v-    then pure $! IM.findWithDefault v k m-    else do-      writeIORef (ctxStore ctx) $! setField (IM.insert seenK v (IM.insert k v m)) st-      when (IM.lookup k m /= Just v) $ do-        damageWidget ctx owner DamageSelf-        markDirty ctx-      pure v---- | Remember the value a controlled widget returned this frame.-{-# INLINE recordSlot #-}-recordSlot ::-  Eq a =>-  (WidgetStore -> IntMap a) ->-  (IntMap a -> WidgetStore -> WidgetStore) ->-  Context ->-  Int ->-  a ->-  IO ()-recordSlot field setField ctx k v = do-  st <- readIORef (ctxStore ctx)-  let seenK = slotKey SlotSeen k-  when (IM.lookup seenK (field st) /= Just v) $-    writeIORef (ctxStore ctx) $! setField (IM.insert seenK v (field st)) st--adoptStoreInt :: Context -> WidgetId -> Int -> Int -> IO Int-adoptStoreInt = adoptSlot storeInt (\m st -> st {storeInt = m})--adoptStoreFloat :: Context -> WidgetId -> Int -> Float -> IO Float-adoptStoreFloat = adoptSlot storeFloat (\m st -> st {storeFloat = m})--adoptStoreText :: Context -> WidgetId -> Int -> Text -> IO Text-adoptStoreText = adoptSlot storeText (\m st -> st {storeText = m})--recordStoreInt :: Context -> Int -> Int -> IO ()-recordStoreInt = recordSlot storeInt (\m st -> st {storeInt = m})--recordStoreFloat :: Context -> Int -> Float -> IO ()-recordStoreFloat = recordSlot storeFloat (\m st -> st {storeFloat = m})--recordStoreText :: Context -> Int -> Text -> IO ()-recordStoreText = recordSlot storeText (\m st -> st {storeText = m})--{-# INLINE getStoreBool #-}-getStoreBool :: Context -> WidgetId -> Bool -> IO Bool-getStoreBool ctx wid def =-  intBool . IM.findWithDefault (boolInt def) (intKey wid) . storeInt <$> getStore ctx---- | Whether @wid@ was declared inside a disabled scope. A widget asks before--- its node exists, while the scope it is declared in is still the arena's.-{-# INLINE isDisabled #-}-isDisabled :: Context -> WidgetId -> IO Bool-isDisabled ctx wid = do-  ts <- readIORef (ctxThemeScopes ctx)-  if tsDisabled ts then scopeDisabled ctx wid else pure False--{-# NOINLINE scopeDisabled #-}-scopeDisabled :: Context -> WidgetId -> IO Bool-scopeDisabled ctx wid = do-  let na = ctxNodeArena ctx-  mIdx <- lookupNodeByWidgetId na wid-  scope <- maybe (getArenaScope na) (getNodeScope na) mIdx-  pure (scope .&. 1 /= 0)---- =============================================================================--- Theme scopes--- =============================================================================--newThemeScopes :: IO ThemeScopes-newThemeScopes = do-  let unset = error "theme scope: unset"-  cur <- newSmallArray 8 unset-  raw <- newSmallArray 8 unset-  prev <- newSmallArray 8 unset-  prevRaw <- newSmallArray 8 unset-  pure-    ThemeScopes-      { tsCount = 0-      , tsThemes = cur-      , tsRaw = raw-      , tsPrevCount = 0-      , tsPrev = prev-      , tsPrevRaw = prevRaw-      , tsDisabled = False-      , tsChanged = False-      , tsPrevSig = 0-      }---- | Start a view pass with no pushed themes. The first pass of a frame keeps--- last frame's themes to compare against; a rebuild pass keeps comparing--- against the same ones.-beginThemeScopes :: Context -> Bool -> IO ()-beginThemeScopes ctx newFrame = do-  ts <- readIORef (ctxThemeScopes ctx)-  if newFrame-    then do-      sig <- getScopeSignature (ctxNodeArena ctx)-      writeIORef (ctxThemeScopes ctx) $!-        ts-          { tsCount = 0-          , tsThemes = tsPrev ts-          , tsRaw = tsPrevRaw ts-          , tsPrevCount = tsCount ts-          , tsPrev = tsThemes ts-          , tsPrevRaw = tsRaw ts-          , tsDisabled = False-          , tsChanged = False-          , tsPrevSig = sig-          }-    else writeIORef (ctxThemeScopes ctx) $! ts {tsCount = 0, tsDisabled = False, tsChanged = False}---- | Add a scope drawn with @theme@, whose nested scopes modify @raw@ and which--- is disabled or not, and--- return its theme index. A theme equal to last frame's at the same index--- keeps last frame's value.-pushThemeScope :: Context -> Bool -> Theme -> Theme -> IO Int-pushThemeScope ctx disabled raw theme = do-  ts <- readIORef (ctxThemeScopes ctx)-  let !i = tsCount ts-  cap <- getSizeofSmallMutableArray (tsThemes ts)-  (themes, raws) <--    if i < cap-      then pure (tsThemes ts, tsRaw ts)-      else do-        grown <- newSmallArray (cap * 2) theme-        copySmallMutableArray grown 0 (tsThemes ts) 0 i-        grownRaw <- newSmallArray (cap * 2) raw-        copySmallMutableArray grownRaw 0 (tsRaw ts) 0 i-        pure (grown, grownRaw)-  same <--    if i < tsPrevCount ts-      then (== theme) <$> readSmallArray (tsPrev ts) i-      else pure False-  writeSmallArray themes i theme-  writeSmallArray raws i raw-  writeIORef (ctxThemeScopes ctx) $!-    ts {tsCount = i + 1, tsThemes = themes, tsRaw = raws, tsDisabled = tsDisabled ts || disabled, tsChanged = tsChanged ts || not same}-  pure (i + 1)---- | Whether this frame's scopes look different from last frame's: a theme--- changed, scopes were added or dropped, or nodes moved between scopes.-themeScopesChanged :: Context -> IO Bool-themeScopesChanged ctx = do-  ts <- readIORef (ctxThemeScopes ctx)-  sig <- getScopeSignature (ctxNodeArena ctx)-  pure (tsChanged ts || tsCount ts /= tsPrevCount ts || sig /= tsPrevSig ts)--{-# INLINE scopeTheme #-}-scopeTheme :: Context -> Int -> IO Theme-scopeTheme ctx scope-  | ti == 0 = readIORef (ctxTheme ctx)-  | otherwise = do-      ts <- readIORef (ctxThemeScopes ctx)-      readSmallArray (tsThemes ts) (ti - 1)-  where-    !ti = scope `shiftR` 1---- | A scope's theme before any disabled scope faded it.-scopeRawTheme :: Context -> Int -> IO Theme-scopeRawTheme ctx scope-  | ti == 0 = readIORef (ctxTheme ctx)-  | otherwise = do-      ts <- readIORef (ctxThemeScopes ctx)-      readSmallArray (tsRaw ts) (ti - 1)-  where-    !ti = scope `shiftR` 1---- | The theme of the scope the view is declaring in.-{-# INLINE currentTheme #-}-currentTheme :: Context -> IO Theme-currentTheme ctx = getArenaScope (ctxNodeArena ctx) >>= scopeTheme ctx--{-# INLINE nodeTheme #-}-nodeTheme :: Context -> NodeIdx -> IO Theme-nodeTheme ctx idx = getNodeScope (ctxNodeArena ctx) idx >>= scopeTheme ctx---- | The theme of @wid@'s node, or of the current scope before it has one.-widgetTheme :: Context -> WidgetId -> IO Theme-widgetTheme ctx wid = do-  ts <- readIORef (ctxThemeScopes ctx)-  if tsCount ts == 0-    then readIORef (ctxTheme ctx)-    else lookupNodeByWidgetId (ctxNodeArena ctx) wid >>= maybe (currentTheme ctx) (nodeTheme ctx)
− lib/NanoUI/Context/Drawing.hs
@@ -1,340 +0,0 @@--- | Per-widget drawing registrations and the caches derived from them.-module NanoUI.Context.Drawing-  ( registerPopupConfig-  , lookupPopupConfig-  , registerDrawing-  , lookupDrawing-  , cachedDrawingOps-  , cachedWidgetLayout-  , lookupDrawFitEnvelope-  , pruneDrawOpCache-  , registerCustomDrawing-  , lookupCustomDrawing-  , cachedCustomDrawingOps-  , refreshCustomDrawingOps-  , drawingOpsStale-  , registerCustomMeasure-  , lookupCustomMeasure-  , registerCustomCursor-  , lookupCustomCursor-  , registerCustomDamageSlop-  , lookupCustomDamageSlop-  , resetDrawingScopeCache-  , hasCustomLayoutInputs-  ) where--import Data.IORef (modifyIORef', readIORef)-import Data.IntMap.Strict (IntMap)-import Data.IntMap.Strict qualified as IM-import Data.Primitive.SmallArray (SmallArray, mapSmallArray')--import NanoUI.Context.Animation (isAnimatingKey)-import NanoUI.Context.Types-  ( Context (..)-  , CustomDrawBuild-  , CustomDrawContext (..)-  , CustomDrawOpCacheEntry (..)-  , CustomDrawingEntry (..)-  , CustomMeasureFn-  , DrawFitCache (..)-  , DrawOpCacheEntry (..)-  , DrawingCacheState (..)-  , DrawingEntry (..)-  , PopupConfig (..)-  , intKey-  )-import NanoUI.Draw (DrawOp, DrawingBuild, shiftDrawOp)-import NanoUI.Id (WidgetId)-import NanoUI.Input (UiCursorKind)-import NanoUI.Style (Layout)-import NanoUI.Types (PopupAnchor, PopupPlacement, Rect (..), rectH, rectW)--{-# INLINE lookupIn #-}-lookupIn :: (DrawingCacheState -> IntMap a) -> Context -> WidgetId -> IO (Maybe a)-lookupIn field ctx wid = IM.lookup (intKey wid) . field <$> readIORef (ctxDrawingCache ctx)--{-# INLINE registerIn #-}-registerIn ::-  (DrawingCacheState -> IntMap a) ->-  (IntMap a -> DrawingCacheState -> DrawingCacheState) ->-  Context ->-  WidgetId ->-  a ->-  IO ()-registerIn field setField ctx wid v =-  modifyIORef' (ctxDrawingCache ctx) $ \dc ->-    setField (IM.insert (intKey wid) v (field dc)) dc--{-# INLINE registerPopupConfig #-}-registerPopupConfig :: Context -> WidgetId -> PopupAnchor -> PopupPlacement -> Float -> IO ()-registerPopupConfig ctx wid anchor placement offset =-  registerIn dcsPopupConfigs (\m dc -> dc {dcsPopupConfigs = m}) ctx wid (PopupConfig anchor placement offset)--{-# INLINE lookupPopupConfig #-}-lookupPopupConfig :: Context -> WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))-lookupPopupConfig ctx wid =-  fmap (\(PopupConfig anchor placement offset) -> (anchor, placement, offset))-    <$> lookupIn dcsPopupConfigs ctx wid--{-# INLINE registerDrawing #-}-registerDrawing :: Context -> WidgetId -> Int -> DrawingBuild -> IO ()-registerDrawing ctx wid content build =-  registerIn dcsDrawings (\m dc -> dc {dcsDrawings = m}) ctx wid (DrawingEntry content build)--{-# INLINE lookupDrawing #-}-lookupDrawing :: Context -> WidgetId -> IO (Maybe DrawingEntry)-lookupDrawing = lookupIn dcsDrawings---- | One draw-op cache step. @hit@ holds the bounds and ops of an entry whose--- key still matches. A same-size hit is reused, translated if the widget--- moved; a miss or a resize uses @rebuilt@. Ops that differ from the entry are--- written back with @store@.-serveOps ::-  Maybe (Rect, SmallArray DrawOp) ->-  Rect ->-  SmallArray DrawOp ->-  (SmallArray DrawOp -> IO ()) ->-  IO (SmallArray DrawOp)-serveOps hit rect rebuilt store =-  case hit of-    Just (r, ops)-      | rectW r == rectW rect && rectH r == rectH rect ->-          if rectX r == rectX rect && rectY r == rectY rect-            then pure ops-            else keep (mapSmallArray' (shiftDrawOp (rectX rect - rectX r) (rectY rect - rectY r)) ops)-    _ -> keep rebuilt-  where-    keep ops = store ops >> pure ops---- | Rebuild draw ops when the content version or width/height change. A move--- only translates. An unversioned drawing (content 0) additionally drops its--- cache while the widget is animating, since it has no other invalidation--- signal; versioned drawings are invalidated by their content key alone.-cachedDrawingOps :: Context -> WidgetId -> Int -> Rect -> DrawingBuild -> IO (SmallArray DrawOp)-cachedDrawingOps ctx wid content rect build = do-  let k = intKey wid-  animated <--    if content == 0-      then isAnimatingKey ctx k-      else pure False-  cached <- IM.lookup k . dcsDrawOpCache <$> readIORef (ctxDrawingCache ctx)-  let hit = case cached of-        Just DrawOpCacheEntry {doeContent = c, doeBounds = r, doeOps = ops}-          | c == content && not animated -> Just (r, ops)-        _ -> Nothing-  serveOps hit rect (build rect) $ \ops ->-    modifyIORef' (ctxDrawingCache ctx) $ \s ->-      s {dcsDrawOpCache = IM.insert k (DrawOpCacheEntry content rect ops) (dcsDrawOpCache s)}---- | Reuse a derived layout while envelope, font, content key, and caller layout match.-cachedWidgetLayout ::-  Context ->-  WidgetId ->-  Double ->-  Double ->-  Float ->-  Int ->-  Layout ->-  IO Layout ->-  IO Layout-cachedWidgetLayout ctx wid dw dh lh content incoming compute = do-  let k = intKey wid-  dc <- readIORef (ctxDrawingCache ctx)-  case IM.lookup k (dcsDrawFitCache dc) of-    Just e-      | dfcDw e == dw-          && dfcDh e == dh-          && dfcLh e == lh-          && dfcContent e == content-          && dfcIn e == incoming ->-          pure (dfcOut e)-    _ -> do-      out <- compute-      modifyIORef' (ctxDrawingCache ctx) $ \s ->-        s { dcsDrawFitCache = IM.insert k (DrawFitCache dw dh lh content incoming out) (dcsDrawFitCache s)-          , dcsDrawOpCache = IM.delete k (dcsDrawOpCache s)-          }-      pure out--lookupDrawFitEnvelope ::-  Context ->-  WidgetId ->-  Float ->-  Int ->-  Layout ->-  IO (Maybe (Double, Double))-lookupDrawFitEnvelope ctx wid lh content incoming = do-  cached <- lookupIn dcsDrawFitCache ctx wid-  pure $ case cached of-    Just e-      | dfcLh e == lh-          && dfcContent e == content-          && dfcIn e == incoming ->-          Just (dfcDw e, dfcDh e)-    _ -> Nothing---- | Drop cached ops for drawings that did not rebuild this frame.-pruneDrawOpCache :: Context -> IO ()-pruneDrawOpCache ctx =-  modifyIORef' (ctxDrawingCache ctx) $ \dc ->-    let live = dcsDrawings dc-        customLive = dcsCustomDrawings dc-     in dc-          { dcsDrawOpCache = dcsDrawOpCache dc `IM.intersection` live-          , dcsCustomDrawOpCache = dcsCustomDrawOpCache dc `IM.intersection` customLive-          , dcsDrawFitCache = dcsDrawFitCache dc `IM.intersection` live-          }--{-# INLINE registerCustomDrawing #-}-registerCustomDrawing :: Context -> WidgetId -> Int -> CustomDrawBuild -> IO ()-registerCustomDrawing ctx wid content build =-  registerIn dcsCustomDrawings (\m dc -> dc {dcsCustomDrawings = m}) ctx wid (CustomDrawingEntry content build)--{-# INLINE lookupCustomDrawing #-}-lookupCustomDrawing :: Context -> WidgetId -> IO (Maybe CustomDrawingEntry)-lookupCustomDrawing = lookupIn dcsCustomDrawings---- | Whether a cache entry was built from these inputs, leaving aside where the--- widget sits: ops built at another origin translate rather than rebuild.-{-# INLINE customEntryMatches #-}-customEntryMatches :: CustomDrawOpCacheEntry -> Int -> Rect -> CustomDrawContext -> Int -> Bool-customEntryMatches e content rect cdc gen =-  cdeContent e == content-    && rectW (cdeBounds e) == rectW rect-    && rectH (cdeBounds e) == rectH rect-    && cdeHovered e == cdcHovered cdc-    && cdePressed e == cdcPressed cdc-    && cdeFocused e == cdcFocused cdc-    && cdeDisabled e == cdcDisabled cdc-    && cdeGen e == gen---- | Draw ops for a custom widget's paint: the ops 'refreshCustomDrawingOps'--- settled on this frame while every input still matches, translated if the--- widget only moved, else a fresh build.-cachedCustomDrawingOps ::-  Context ->-  WidgetId ->-  Int ->-  Rect ->-  CustomDrawContext ->-  CustomDrawBuild ->-  IO (SmallArray DrawOp)-cachedCustomDrawingOps ctx wid content rect cdc build = do-  let k = intKey wid-  gen <- readIORef (ctxMetricGen ctx)-  cached <- IM.lookup k . dcsCustomDrawOpCache <$> readIORef (ctxDrawingCache ctx)-  let hit = case cached of-        Just e | customEntryMatches e content rect cdc gen -> Just (cdeBounds e, cdeOps e)-        _ -> Nothing-  serveOps hit rect (build cdc rect) (storeCustomDrawingOps ctx k content rect cdc gen)---- | Settle a custom widget's ops for this frame and cache them for paint,--- returning whether what it draws changed at an unchanged rect.------ A widget that declares a content key is taken at its word, as a versioned--- drawing is: an unchanged key with unchanged size, interaction state and--- metrics neither rebuilds the ops nor repaints them, animating or not, so a--- drawing that reads an animated value has to fold it into its key. One that--- only moved keeps its ops too; paint translates them. Without a key (0) the--- build can read anything (a sort flag, a fraction), and nothing but building--- it shows that its output changed, so it is rebuilt and compared.------ Whatever forced a rebuild, the ops it produced decide the damage, so a key--- bumped without a visible change repaints nothing and a rebuild the key never--- mentioned still repaints. A new, moved or resized widget reports no change:--- rect damage covers it.-refreshCustomDrawingOps ::-  Context ->-  WidgetId ->-  Int ->-  Rect ->-  CustomDrawContext ->-  CustomDrawBuild ->-  IO Bool-refreshCustomDrawingOps ctx wid content rect cdc build = do-  let k = intKey wid-  gen <- readIORef (ctxMetricGen ctx)-  cached <- IM.lookup k . dcsCustomDrawOpCache <$> readIORef (ctxDrawingCache ctx)-  let keyed = content /= 0-  case cached of-    -- A keyed widget that only moved keeps its ops: paint translates them, and-    -- the move is damaged by the rect delta.-    Just e | keyed && customEntryMatches e content rect cdc gen -> pure False-    _ -> do-      let ops = build cdc rect-          -- Whatever made this frame rebuild - the key, the interaction state,-          -- a theme or font change - the ops are built now, so ask them-          -- directly rather than trusting the key for damage as well.-          changed = case cached of-            Just e | cdeBounds e == rect -> cdeOps e /= ops-            _ -> False-      storeCustomDrawingOps ctx k content rect cdc gen ops-      pure changed--storeCustomDrawingOps :: Context -> Int -> Int -> Rect -> CustomDrawContext -> Int -> SmallArray DrawOp -> IO ()-storeCustomDrawingOps ctx k content rect cdc gen ops =-  modifyIORef' (ctxDrawingCache ctx) $ \s ->-    let entry =-          CustomDrawOpCacheEntry-            content-            rect-            (cdcHovered cdc)-            (cdcPressed cdc)-            (cdcFocused cdc)-            (cdcDisabled cdc)-            gen-            ops-     in s {dcsCustomDrawOpCache = IM.insert k entry (dcsCustomDrawOpCache s)}---- | Whether a versioned drawing's cached ops are for another version at the--- same rect. Paint rebuilds them; the pixels they covered must repaint too,--- and checking the version costs nothing next to building the ops here.-drawingOpsStale :: Context -> WidgetId -> Int -> Rect -> IO Bool-drawingOpsStale ctx wid content rect = do-  cached <- IM.lookup (intKey wid) . dcsDrawOpCache <$> readIORef (ctxDrawingCache ctx)-  pure $ case cached of-    Just DrawOpCacheEntry {doeContent = c, doeBounds = r} -> c /= content && r == rect-    Nothing -> False--{-# INLINE registerCustomMeasure #-}-registerCustomMeasure :: Context -> WidgetId -> CustomMeasureFn -> IO ()-registerCustomMeasure = registerIn dcsCustomMeasures (\m dc -> dc {dcsCustomMeasures = m})--{-# INLINE lookupCustomMeasure #-}-lookupCustomMeasure :: Context -> WidgetId -> IO (Maybe CustomMeasureFn)-lookupCustomMeasure = lookupIn dcsCustomMeasures--{-# INLINE registerCustomCursor #-}-registerCustomCursor :: Context -> WidgetId -> (CustomDrawContext -> UiCursorKind) -> IO ()-registerCustomCursor = registerIn dcsCustomCursors (\m dc -> dc {dcsCustomCursors = m})--{-# INLINE lookupCustomCursor #-}-lookupCustomCursor :: Context -> WidgetId -> IO (Maybe (CustomDrawContext -> UiCursorKind))-lookupCustomCursor = lookupIn dcsCustomCursors--{-# INLINE registerCustomDamageSlop #-}-registerCustomDamageSlop :: Context -> WidgetId -> Float -> IO ()-registerCustomDamageSlop = registerIn dcsCustomDamageSlop (\m dc -> dc {dcsCustomDamageSlop = m})--{-# INLINE lookupCustomDamageSlop #-}-lookupCustomDamageSlop :: Context -> WidgetId -> IO (Maybe Float)-lookupCustomDamageSlop = lookupIn dcsCustomDamageSlop--resetDrawingScopeCache :: Context -> IO ()-resetDrawingScopeCache ctx =-  modifyIORef' (ctxDrawingCache ctx) $ \dc ->-    dc-      { dcsDrawings = IM.empty-      , dcsPopupConfigs = IM.empty-      , dcsCustomMeasures = IM.empty-      , dcsCustomCursors = IM.empty-      , dcsCustomDrawings = IM.empty-      , dcsCustomDamageSlop = IM.empty-      }---- | True when any node has a custom measure function, whose output is not--- captured by the arena descriptor comparison, so whole-layout reuse must be--- disabled for the frame.-hasCustomLayoutInputs :: Context -> IO Bool-hasCustomLayoutInputs ctx =-  not . IM.null . dcsCustomMeasures <$> readIORef (ctxDrawingCache ctx)
− lib/NanoUI/Context/Overlay.hs
@@ -1,157 +0,0 @@--- | Modal, floating-panel and menu pointer-capture state.-module NanoUI.Context.Overlay-  ( textInputEditActive-  , modalActive-  , overlayConsumesQuit-  , markEscapeConsumed-  , pointerBlockedByModal-  , pointerBlockedByOverlay-  , armMenuPointerCapture-  , seedFloatingPanel-  , beginModal-  , endModal-  , beginFrameModal-  , modalDamageFlip-  ) where--import Control.Monad (when)-import Data.IORef (readIORef)-import Data.IntMap.Strict qualified as IM--import NanoUI.Context.Core-  ( getMenuPointerGesture-  , getTextInputMenu-  , getsOverlay-  , modifyOverlay-  , setMenuPointerGesture-  , getsInteraction-  )-import NanoUI.Context.Types (Context (..), OverlayState (..), TextInputMenu (..), intKey, InteractionState (..))-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (Input, Key (KeyEscape), inputKeys, inputKeysElem, inputMousePos, inputMousePressed)-import NanoUI.Types (Rect, V2, rectContains, rectHit, rectNonEmpty)--textInputEditActive :: Context -> IO Bool-textInputEditActive ctx = do-  focus <- readIORef (ctxFocusId ctx)-  menu <- getTextInputMenu ctx-  pure (hashWidgetId focus /= 0 || menu /= Nothing)--modalActive :: Context -> IO Bool-modalActive ctx = getsOverlay ctx (\os -> osModalWasActive os || osModalActive os)--overlayConsumesQuit :: Context -> Input -> IO Bool-overlayConsumesQuit ctx inp = do-  consumed <- getsOverlay ctx osEscapeConsumed-  pure (inputKeysElem KeyEscape (inputKeys inp) && consumed)--markEscapeConsumed :: Context -> IO ()-markEscapeConsumed ctx = modifyOverlay ctx (\os -> os {osEscapeConsumed = True})--pointerBlockedByModal :: Context -> IO Bool-pointerBlockedByModal ctx =-  getsOverlay ctx (\os -> osModalDepth os <= 0 && (osModalWasActive os || osModalActive os))--pointerBlockedByOverlay :: Context -> V2 -> IO Bool-pointerBlockedByOverlay ctx mouse = do-  gesture <- getMenuPointerGesture ctx-  blocked <--    if gesture-      then pure True-      else do-        menuBlocked <- overlayMenuBlocksPointer ctx mouse-        if menuBlocked-          then pure True-          else do-            modalBlocked <- pointerBlockedByModal ctx-            if modalBlocked-              then pure True-              else do-                mTop <- cachedTopmost ctx mouse-                case mTop of-                  Nothing -> pure False-                  Just top -> do-                    mCur <- getsOverlay ctx osCurrentFloatingId-                    pure (mCur /= Just top)-  modifyOverlay ctx (\os -> os {osLastPointerBlocked = blocked})-  pure blocked--armMenuPointerCapture :: Context -> Input -> IO ()-armMenuPointerCapture ctx inp =-  when (inputMousePressed inp) $ do-    blocked <- overlayMenuBlocksPointer ctx (inputMousePos inp)-    setMenuPointerGesture ctx blocked--overlayMenuBlocksPointer :: Context -> V2 -> IO Bool-overlayMenuBlocksPointer ctx mouse = do-  mMenu <- getTextInputMenu ctx-  let textMenu =-        case mMenu of-          Just m | rectContains (textInputMenuRect m) mouse -> True-          _ -> False-  if textMenu-    then pure True-    else do-      mDrop <- getsInteraction ctx isOpenSelectDrop-      pure-        ( case mDrop of-            Just (_, r) -> rectContains r mouse-            Nothing -> False-        )--cachedTopmost :: Context -> V2 -> IO (Maybe WidgetId)-cachedTopmost ctx mouse = do-  cache <- getsOverlay ctx osTopmostCache-  case cache of-    Just (p, t) | p == mouse -> pure t-    _ -> do-      t <- topmostFloatingAtMouse ctx mouse-      modifyOverlay ctx (\os -> os {osTopmostCache = Just (mouse, t)})-      pure t--topmostFloatingAtMouse :: Context -> V2 -> IO (Maybe WidgetId)-topmostFloatingAtMouse ctx mouse = do-  os <- readIORef (ctxOverlayState ctx)-  let rects = osPrevFloatingRects os-      order = osPrevFloatingOrder os-      hit k = maybe False (`rectHit` mouse) (IM.lookup k rects)-      picked = foldl' (\acc k -> if hit k then Just k else acc) Nothing order-  pure (WidgetId . fromIntegral <$> picked)--seedFloatingPanel :: Context -> WidgetId -> Rect -> IO ()-seedFloatingPanel ctx wid rect-  | not (rectNonEmpty rect) = pure ()-  | otherwise = do-      let k = intKey wid-      modifyOverlay ctx $ \os ->-        let rects = IM.insert k rect (osPrevFloatingRects os)-            order = filter (/= k) (osPrevFloatingOrder os) ++ [k]-         in os-              { osPrevFloatingRects = rects-              , osPrevFloatingOrder = order-              , osTopmostCache = Nothing-              }--beginModal :: Context -> IO ()-beginModal ctx =-  modifyOverlay ctx (\os -> os {osModalActive = True, osModalDepth = osModalDepth os + 1})--endModal :: Context -> IO ()-endModal ctx =-  modifyOverlay ctx (\os -> os {osModalDepth = max 0 (osModalDepth os - 1)})--beginFrameModal :: Context -> IO ()-beginFrameModal ctx =-  modifyOverlay ctx $ \os ->-    os-      { osModalWasActive = osModalActive os-      , osModalActive = False-      , osModalDepth = 0-      , osTopmostCache = Nothing-      , osCurrentFloatingId = Nothing-      , osLastPointerBlocked = False-      , osEscapeConsumed = False-      }--modalDamageFlip :: Context -> IO Bool-modalDamageFlip ctx = getsOverlay ctx (\os -> osModalWasActive os /= osModalActive os)
− lib/NanoUI/Context/Scroll.hs
@@ -1,623 +0,0 @@--- | Scroll offsets, links and configuration kept in the widget store, the--- wheel and glide tuning kept in the context, and the commands that move a--- scroller: to an offset, by a delta or page, or onto a widget.-module NanoUI.Context.Scroll-  ( getScrollOffset-  , setScrollOffset-  , getScrollOffset2D-  , setScrollOffset2D-  , setScrollConfig-  , linkScrollAxes-    -- * Tuning-  , ScrollTuning (..)-  , defaultScrollTuning-  , getScrollTuning-  , setScrollTuning-  , getScrollStep-  , setScrollStep-  , resolveScrollStep-    -- * Geometry-  , ScrollAxes (..)-  , ScrollMetrics (..)-  , getScrollMetrics-  , cacheScrollMetrics-  , beginScrollMetrics-  , getScrollOffsetIn-  , setScrollOffsetIn-    -- * Commands-  , ScrollBehavior (..)-  , ScrollAlign (..)-  , scrollTo-  , scrollBy-  , scrollPages-  , scrollToStart-  , scrollToEnd-  , scrollIntoView-  , scrollRectIntoView-    -- * Glide-  , applyScrollTarget-  , scrollTargetOffset-  , scrollGliding-  , clampScrollOffset-  , cancelScrollGlide-  , stepScrollGlides-  ) where--import Control.Monad (unless, when)-import Data.IORef (modifyIORef', readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.IntSet qualified as IS--import NanoUI.Context.Core (damageWidget, getPrevRect, getStore, setStore)-import NanoUI.Context.Types-  ( Context (..)-  , ScrollAxes (..)-  , ScrollGlide (..)-  , ScrollState (..)-  , ScrollTuning (..)-  , defaultScrollTuning-  , intKey-  )-import NanoUI.Draw qualified as Draw-import NanoUI.Frame.Scroll.Geometry-  ( ScrollConfig-  , decodeScrollConfig-  , defaultScrollConfig-  , encodeScrollConfig-  , scrollConfigNative2D-  )-import NanoUI.Id (WidgetId)-import NanoUI.Store-  ( WidgetStore (..)-  , slotKey-  , Slot (..)-  )-import NanoUI.Types (DamageBounds (..), Rect (..), V2 (..), clamp, onGrid, v2X, v2Y)--{-# INLINE snapScrollOffset #-}-snapScrollOffset :: Context -> Float -> IO Float-snapScrollOffset ctx v = do-  s <- Draw.getDrawSnapScale (ctxDrawArena ctx)-  pure (onGrid s v)--getScrollOffset :: Context -> WidgetId -> IO Float-getScrollOffset ctx wid = do-  s <- getStore ctx-  let key = intKey wid-      points = storePoint s-      cfgBits = IM.findWithDefault (encodeScrollConfig defaultScrollConfig) (slotKey SlotScrollCfg key) (storeInt s)-      -- Text areas keep both axes in their own slot; native 2D scrollers keep-      -- them in the offset slot, falling back to the main-axis float as-      -- 'getScrollOffset2D' does.-      off = case IM.lookup (slotKey SlotTextAreaScroll key) points of-        Just (_, sy) -> sy-        Nothing-          | scrollConfigNative2D (decodeScrollConfig cfgBits)-          , Just (_, y) <- IM.lookup (slotKey SlotScrollOff key) points ->-              y-          | otherwise -> IM.findWithDefault 0 key (storeFloat s)-  snapScrollOffset ctx off---- | Move a scroller to an offset along its main axis. Cancels a glide in--- flight: whoever sets an offset outright owns it.-setScrollOffset :: Context -> WidgetId -> Float -> IO ()-setScrollOffset ctx wid off = do-  cancelScrollGlide ctx wid-  writeScrollOffset ctx wid off--writeScrollOffset :: Context -> WidgetId -> Float -> IO ()-writeScrollOffset ctx wid off = do-  store <- getStore ctx-  let key = intKey wid-      sKey = slotKey SlotTextAreaScroll key-  case IM.lookup sKey (storePoint store) of-    Just (sx, sy) ->-      when (sy /= off) $ do-        setStore ctx (store {storePoint = IM.insert sKey (sx, off) (storePoint store)})-        damageWidget ctx wid DamageSelf-    Nothing -> do-      cfg <- getScrollConfig ctx wid-      if scrollConfigNative2D cfg-        then do-          cur <- getScrollOffset2D ctx wid-          writeScrollOffset2D ctx wid (V2 (v2X cur) off)-        else do-          let prev = IM.findWithDefault 0 key (storeFloat store)-          when (prev /= off) $ do-            let floats0 = IM.insert key off (storeFloat store)-                yKey = IM.findWithDefault 0 (slotKey SlotScrollLinkY key) (storeInt store)-            if yKey == 0-              then setStore ctx (store {storeFloat = floats0})-              else do-                let offKey = slotKey SlotScrollOff yKey-                    crossKey = slotKey SlotScrollCross yKey-                    prevY = IM.findWithDefault 0 yKey floats0-                    floats1 = IM.insert yKey prevY $ IM.insert crossKey off floats0-                    points = IM.insert offKey (off, prevY) (storePoint store)-                setStore ctx (store {storeFloat = floats1, storePoint = points})--getScrollOffset2D :: Context -> WidgetId -> IO V2-getScrollOffset2D ctx wid = do-  s <- getStore ctx-  let widKey = intKey wid-      sKey = slotKey SlotTextAreaScroll widKey-  v <--    case IM.lookup sKey (storePoint s) of-      Just (sx, sy) -> pure (V2 sx sy)-      Nothing -> do-        let offKey = slotKey SlotScrollOff widKey-            crossKey = slotKey SlotScrollCross widKey-        case IM.lookup offKey (storePoint s) of-          Just (x, y) -> pure (V2 x y)-          Nothing ->-            pure-              ( V2-                  (IM.findWithDefault 0 crossKey (storeFloat s))-                  (IM.findWithDefault 0 widKey (storeFloat s))-              )-  sx <- snapScrollOffset ctx (v2X v)-  sy <- snapScrollOffset ctx (v2Y v)-  pure (V2 sx sy)---- | Move a scroller to an offset on both axes. Cancels a glide in flight.-setScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()-setScrollOffset2D ctx wid off = do-  cancelScrollGlide ctx wid-  writeScrollOffset2D ctx wid off--writeScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()-writeScrollOffset2D ctx wid off = do-  store <- getStore ctx-  let widKey = intKey wid-      sKey = slotKey SlotTextAreaScroll widKey-  -- Text areas only reach the first branch because `textAreaWith` seeds this-  -- slot at init; without the seed a freshly mounted editor falls through to-  -- the container slots below and its offsets are never rendered.-  case IM.lookup sKey (storePoint store) of-    Just (sx, sy) -> do-      let sx' = v2X off-          sy' = v2Y off-      when (sx /= sx' || sy /= sy') $ do-        setStore ctx (store {storePoint = IM.insert sKey (sx', sy') (storePoint store)})-        damageWidget ctx wid DamageSelf-    Nothing -> do-      let offKey = slotKey SlotScrollOff widKey-          crossKey = slotKey SlotScrollCross widKey-          prev = IM.lookup offKey (storePoint store)-          next = (v2X off, v2Y off)-          prevY = IM.findWithDefault 0 widKey (storeFloat store)-          prevX = IM.findWithDefault 0 crossKey (storeFloat store)-          xLink = IM.findWithDefault 0 (slotKey SlotScrollLinkX widKey) (storeInt store)-      when (prev /= Just next || prevY /= v2Y off || prevX /= v2X off) $ do-        let floats0 =-              IM.insert widKey (v2Y off) $-                IM.insert crossKey (v2X off) (storeFloat store)-            floats1 =-              if xLink == 0 then floats0 else IM.insert xLink (v2X off) floats0-        setStore ctx-          ( store-              { storePoint = IM.insert offKey next (storePoint store)-              , storeFloat = floats1-              }-          )--linkScrollAxes :: Context -> WidgetId -> WidgetId -> IO ()-linkScrollAxes ctx yWid xWid = do-  store <- getStore ctx-  let yKey = intKey yWid-      xKey = intKey xWid-      ints =-        IM.insert (slotKey SlotScrollLinkX yKey) xKey $-          IM.insert (slotKey SlotScrollLinkY xKey) yKey (storeInt store)-  setStore ctx (store {storeInt = ints})-  V2 x2 y <- getScrollOffset2D ctx yWid-  x1 <- do-    s <- getStore ctx-    pure (IM.findWithDefault 0 xKey (storeFloat s))-  let x = if x2 == 0 && x1 /= 0 then x1 else x2-  when (x /= x2 || x /= x1) $-    setScrollOffset2D ctx yWid (V2 x y)--getScrollConfig :: Context -> WidgetId -> IO ScrollConfig-getScrollConfig ctx wid = do-  s <- getStore ctx-  let cfgKey = slotKey SlotScrollCfg (intKey wid)-      bits = IM.findWithDefault (encodeScrollConfig defaultScrollConfig) cfgKey (storeInt s)-  pure (decodeScrollConfig bits)--setScrollConfig :: Context -> WidgetId -> ScrollConfig -> IO ()-setScrollConfig ctx wid cfg = do-  store <- getStore ctx-  let cfgKey = slotKey SlotScrollCfg (intKey wid)-      bits = encodeScrollConfig cfg-      prev = IM.findWithDefault (encodeScrollConfig defaultScrollConfig) cfgKey (storeInt store)-  when (prev /= bits) $-    setStore ctx (store {storeInt = IM.insert cfgKey bits (storeInt store)})---- =============================================================================--- Tuning--- =============================================================================---- | Wheel step and glide time for every scroller in this context.-getScrollTuning :: Context -> IO ScrollTuning-getScrollTuning ctx = ssTuning <$> readIORef (ctxScrollState ctx)---- | Set the wheel step and glide time. Raising 'scrollWheelStep' makes the--- wheel cover more ground per notch; a nonzero 'scrollSmoothTime' turns every--- wheel notch and every 'ScrollSmooth' command into a glide.-setScrollTuning :: Context -> ScrollTuning -> IO ()-setScrollTuning ctx tuning =-  modifyIORef' (ctxScrollState ctx) $ \st -> st {ssTuning = tuning}---- | This scroller's own wheel step, or @0@ when it follows the context's.-getScrollStep :: Context -> WidgetId -> IO Float-getScrollStep ctx wid = do-  s <- getStore ctx-  pure (IM.findWithDefault 0 (slotKey SlotScrollStep (intKey wid)) (storeFloat s))---- | Give one scroller its own wheel step, in pixels per notch. @0@ puts it--- back on the context's step. A list whose rows are a fixed height reads best--- at a whole number of rows per notch.-setScrollStep :: Context -> WidgetId -> Float -> IO ()-setScrollStep ctx wid px = do-  store <- getStore ctx-  let key = slotKey SlotScrollStep (intKey wid)-      prev = IM.findWithDefault 0 key (storeFloat store)-  when (prev /= px) $-    setStore ctx (store {storeFloat = IM.insert key px (storeFloat store)})---- | Pixels one wheel notch scrolls this scroller.-resolveScrollStep :: Context -> WidgetId -> IO Float-resolveScrollStep ctx wid = do-  own <- getScrollStep ctx wid-  if own > 0-    then pure own-    else max 1 . scrollWheelStep <$> getScrollTuning ctx---- =============================================================================--- Geometry--- =============================================================================---- | What a scroller looked like on the frame it was last laid out on.--- Offsets and ranges are in window axes: @x@ rightwards, @y@ downwards,--- whichever way the scroller itself is built.-data ScrollMetrics = ScrollMetrics-  { scrollViewport :: !Rect-  -- ^ The visible content, in window coordinates, inside padding and clear of-  -- the scrollbars.-  , scrollRange :: !V2-  -- ^ Largest offset each axis reaches. @0@ on an axis that does not scroll.-  , scrollOffset :: !V2-  -- ^ Where the scroller is now.-  , scrollAxes :: !ScrollAxes-  }-  deriving (Eq, Show)---- | Geometry of the scroller @wid@, or 'Nothing' before it has been laid out.--- Reads the last frame's layout, so it is safe to call while building the--- next one.-getScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)-getScrollMetrics ctx wid = do-  s <- getStore ctx-  let key = intKey wid-      point slot = IM.lookup (slotKey slot key) (storePoint s)-  case (point SlotScrollViewPos, point SlotScrollViewSize, point SlotScrollRange) of-    (Just (vx, vy), Just (vw, vh), Just (mx, my)) -> do-      let axes = decodeScrollAxes (IM.findWithDefault 0 (slotKey SlotScrollAxes key) (storeInt s))-      off <- getScrollOffsetIn ctx wid axes-      pure $-        Just-          ScrollMetrics-            { scrollViewport = Rect vx vy vw vh-            , scrollRange = V2 mx my-            , scrollOffset = off-            , scrollAxes = axes-            }-    _ -> pure Nothing---- | Start a frame's geometry pass: the first scroll node to publish under a--- widget id wins for that frame.-beginScrollMetrics :: Context -> IO ()-beginScrollMetrics ctx =-  modifyIORef' (ctxScrollState ctx) $ \st ->-    if IS.null (ssCached st) then st else st {ssCached = IS.empty}---- | Record what the scroll pass measured, so the commands and the app can--- read it between frames. Writes nothing when nothing moved, and nothing at--- all for a second node sharing this one's widget id. A table's frozen pane--- and its body share theirs, and letting both publish would rewrite the store--- every frame and hand the commands a viewport that alternates between panes.-cacheScrollMetrics :: Context -> WidgetId -> ScrollAxes -> Rect -> V2 -> IO ()-cacheScrollMetrics ctx wid axes viewport range = do-  taken <- claimScrollMetrics ctx (intKey wid)-  unless taken (writeScrollMetrics ctx wid axes viewport range)---- | Whether this widget id has already published geometry this frame; marks--- it published if not.-claimScrollMetrics :: Context -> Int -> IO Bool-claimScrollMetrics ctx key = do-  st <- readIORef (ctxScrollState ctx)-  if IS.member key (ssCached st)-    then pure True-    else do-      writeIORef (ctxScrollState ctx) $! st {ssCached = IS.insert key (ssCached st)}-      pure False--writeScrollMetrics :: Context -> WidgetId -> ScrollAxes -> Rect -> V2 -> IO ()-writeScrollMetrics ctx wid axes (Rect vx vy vw vh) range@(V2 mx my) = do-  -- A range that just shrank (a filtered list, a narrower window) would leave-  -- a glide heading past the new end.-  clampScrollGlide ctx wid range-  store <- getStore ctx-  let key = intKey wid-      axesKey = slotKey SlotScrollAxes key-      posKey = slotKey SlotScrollViewPos key-      sizeKey = slotKey SlotScrollViewSize key-      rangeKey = slotKey SlotScrollRange key-      code = encodeScrollAxes axes-      points = storePoint store-      ints = storeInt store-      samePoint k v = IM.lookup k points == Just v-  unless-    ( samePoint posKey (vx, vy)-        && samePoint sizeKey (vw, vh)-        && samePoint rangeKey (mx, my)-        && IM.lookup axesKey ints == Just code-    )-    $ setStore ctx-      ( store-          { storePoint =-              IM.insert posKey (vx, vy) $-                IM.insert sizeKey (vw, vh) $-                  IM.insert rangeKey (mx, my) points-          , storeInt = IM.insert axesKey code ints-          }-      )--encodeScrollAxes :: ScrollAxes -> Int-encodeScrollAxes = \case-  ScrollAxisY -> 0-  ScrollAxisX -> 1-  ScrollAxisXY -> 2--decodeScrollAxes :: Int -> ScrollAxes-decodeScrollAxes = \case-  1 -> ScrollAxisX-  2 -> ScrollAxisXY-  _ -> ScrollAxisY---- | A 1D row scroller keeps its offset in the main-axis slot, so window and--- stored axes are swapped for it and identical for everything else. The swap--- is its own inverse.-{-# INLINE swapAxes #-}-swapAxes :: ScrollAxes -> V2 -> V2-swapAxes ScrollAxisX (V2 x y) = V2 y x-swapAxes _ v = v---- | This scroller's offset in window axes.-getScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> IO V2-getScrollOffsetIn ctx wid axes = swapAxes axes <$> getScrollOffset2D ctx wid---- | Move a scroller to an offset in window axes, cancelling any glide. A 1D--- scroller ignores the axis it does not scroll on.-setScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> V2 -> IO ()-setScrollOffsetIn ctx wid axes off = do-  cancelScrollGlide ctx wid-  writeScrollOffsetIn ctx wid axes off--writeScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> V2 -> IO ()-writeScrollOffsetIn ctx wid axes off =-  case axes of-    ScrollAxisXY -> writeScrollOffset2D ctx wid off-    ScrollAxisY -> writeScrollOffset ctx wid (v2Y off)-    ScrollAxisX -> writeScrollOffset ctx wid (v2X off)---- =============================================================================--- Commands--- =============================================================================---- | Whether a scroll lands on its target at once or glides onto it.--- 'ScrollSmooth' still lands at once when the context's 'scrollSmoothTime' is--- @0@, so one setting turns smooth scrolling on for the whole app.-data ScrollBehavior = ScrollInstant | ScrollSmooth-  deriving (Eq, Show)---- | Where a widget ends up in the viewport once it is scrolled into view.-data ScrollAlign-  = -- | Move as little as possible: nothing at all when it is already whole.-    ScrollNearest-  | -- | Against the leading edge, at the top or left.-    ScrollStart-  | ScrollCenter-  | -- | Against the trailing edge, at the bottom or right.-    ScrollEnd-  deriving (Eq, Show)---- | Scroll to an absolute offset, clamped to the scroller's range.-scrollTo :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()-scrollTo ctx wid off behavior =-  withScrollMetrics ctx wid $ \m ->-    applyScrollTarget ctx wid (scrollAxes m) (clampScrollOffset (scrollRange m) off) behavior---- | Scroll by a delta in pixels. Deltas accumulate onto a glide already in--- flight, so repeated calls keep up rather than fighting each other.-scrollBy :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()-scrollBy ctx wid delta behavior =-  withScrollMetrics ctx wid $ \m -> scrollMetricsBy ctx wid m delta behavior---- | Scroll by whole viewports: @V2 0 1@ is one page down, @V2 0 (-0.5)@ half--- a page up.-scrollPages :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()-scrollPages ctx wid (V2 px py) behavior =-  withScrollMetrics ctx wid $ \m -> do-    let Rect _ _ vw vh = scrollViewport m-    scrollMetricsBy ctx wid m (V2 (px * vw) (py * vh)) behavior--scrollMetricsBy :: Context -> WidgetId -> ScrollMetrics -> V2 -> ScrollBehavior -> IO ()-scrollMetricsBy ctx wid m (V2 dx dy) behavior = do-  V2 bx by <- scrollTargetOffset ctx wid (scrollOffset m)-  applyScrollTarget ctx wid (scrollAxes m) (clampScrollOffset (scrollRange m) (V2 (bx + dx) (by + dy))) behavior---- | Scroll back to the top (and left).-scrollToStart :: Context -> WidgetId -> ScrollBehavior -> IO ()-scrollToStart ctx wid = scrollTo ctx wid (V2 0 0)---- | Scroll to the end of the content.-scrollToEnd :: Context -> WidgetId -> ScrollBehavior -> IO ()-scrollToEnd ctx wid behavior =-  withScrollMetrics ctx wid $ \m ->-    applyScrollTarget ctx wid (scrollAxes m) (scrollRange m) behavior---- | Scroll @target@ into the viewport of the scroller @wid@ it is built--- inside. Both widgets are read from the last frame's layout, so a widget--- that was not built then, such as a row a virtualized list left out, cannot--- be found; scroll to its content rectangle with 'scrollRectIntoView' instead.-scrollIntoView :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()-scrollIntoView ctx wid target align behavior = do-  mMetrics <- getScrollMetrics ctx wid-  mRect <- getPrevRect ctx target-  case (mMetrics, mRect) of-    (Just m, Just (Rect rx ry rw rh)) -> do-      let Rect vx vy _ _ = scrollViewport m-          V2 ox oy = scrollOffset m-      scrollRectIntoView ctx wid (Rect (rx - vx + ox) (ry - vy + oy) rw rh) align behavior-    _ -> pure ()---- | Scroll a rectangle of the content into view. The rectangle is in content--- coordinates: the origin is where the content starts, which is where the--- viewport shows it at offset @0@.-scrollRectIntoView :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()-scrollRectIntoView ctx wid (Rect rx ry rw rh) align behavior =-  withScrollMetrics ctx wid $ \m -> do-    let Rect _ _ vw vh = scrollViewport m-        V2 ox oy = scrollOffset m-        V2 mx my = scrollRange m-        target =-          V2-            (clamp 0 mx (alignAxis align vw rx rw ox))-            (clamp 0 my (alignAxis align vh ry rh oy))-    applyScrollTarget ctx wid (scrollAxes m) target behavior---- | Offset that puts a span of the content where @align@ asks for it.-alignAxis :: ScrollAlign -> Float -> Float -> Float -> Float -> Float-alignAxis align viewSize start size cur =-  case align of-    ScrollStart -> start-    ScrollEnd -> start + size - viewSize-    ScrollCenter -> start + (size - viewSize) / 2-    ScrollNearest-      | start < cur -> start-      | start + size > cur + viewSize -> min start (start + size - viewSize)-      | otherwise -> cur---- | Hold an offset inside @0@ and the scroller's range on each axis.-{-# INLINE clampScrollOffset #-}-clampScrollOffset :: V2 -> V2 -> V2-clampScrollOffset (V2 mx my) (V2 x y) = V2 (clamp 0 mx x) (clamp 0 my y)---- | Drop the axis a 1D scroller does not move on. A table's paired panes link--- their cross offsets, so a vertical scroller can carry a horizontal offset it--- does not own; a glide that watched it would never settle.-{-# INLINE projectAxes #-}-projectAxes :: ScrollAxes -> V2 -> V2-projectAxes axes (V2 x y) =-  case axes of-    ScrollAxisY -> V2 0 y-    ScrollAxisX -> V2 x 0-    ScrollAxisXY -> V2 x y--withScrollMetrics :: Context -> WidgetId -> (ScrollMetrics -> IO ()) -> IO ()-withScrollMetrics ctx wid act = getScrollMetrics ctx wid >>= mapM_ act---- =============================================================================--- Glide--- =============================================================================---- | Send a scroller to an offset in window axes, gliding if the caller asked--- for it and the context is tuned for it. The target must already be clamped--- to the scroller's range.-applyScrollTarget :: Context -> WidgetId -> ScrollAxes -> V2 -> ScrollBehavior -> IO ()-applyScrollTarget ctx wid axes target0 behavior = do-  st <- readIORef (ctxScrollState ctx)-  let smooth = scrollSmoothTime (ssTuning st)-      target = projectAxes axes target0-  if behavior == ScrollInstant || smooth <= 0-    then setScrollOffsetIn ctx wid axes target-    else do-      cur <- getScrollOffsetIn ctx wid axes-      if nearOffset (projectAxes axes cur) target-        then setScrollOffsetIn ctx wid axes target-        else-          writeIORef (ctxScrollState ctx) $!-            st {ssGlides = IM.insert (intKey wid) (ScrollGlide wid target axes) (ssGlides st)}---- | Where the scroller is headed: the glide's target if one is in flight, and--- @fallback@ (normally the current offset) if not. Deltas add onto this so--- that notches arriving mid-glide are not swallowed.-scrollTargetOffset :: Context -> WidgetId -> V2 -> IO V2-scrollTargetOffset ctx wid fallback = do-  st <- readIORef (ctxScrollState ctx)-  pure (maybe fallback sgTarget (IM.lookup (intKey wid) (ssGlides st)))--scrollGliding :: Context -> WidgetId -> IO Bool-scrollGliding ctx wid =-  IM.member (intKey wid) . ssGlides <$> readIORef (ctxScrollState ctx)---- | Hold a glide in flight inside a range that has just been measured again.--- Without this a list filtered down mid-glide coasts past its new end and--- stops there, showing nothing, until something else scrolls it.-clampScrollGlide :: Context -> WidgetId -> V2 -> IO ()-clampScrollGlide ctx wid range =-  modifyIORef' (ctxScrollState ctx) $ \st ->-    if IM.null (ssGlides st)-      then st-      else st {ssGlides = IM.adjust clampGlide (intKey wid) (ssGlides st)}-  where-    clampGlide g = g {sgTarget = projectAxes (sgAxes g) (clampScrollOffset range (sgTarget g))}--cancelScrollGlide :: Context -> WidgetId -> IO ()-cancelScrollGlide ctx wid =-  modifyIORef' (ctxScrollState ctx) $ \st ->-    if IM.null (ssGlides st)-      then st-      else st {ssGlides = IM.delete (intKey wid) (ssGlides st)}---- | Advance every glide by @dt@ seconds. Each one covers the same fraction of--- what is left every second, so a long throw starts fast and eases in, and at--- least a pixel a frame so a glide cannot stall on the pixel grid the offsets--- snap to.-stepScrollGlides :: Context -> Float -> IO ()-stepScrollGlides ctx dt = do-  st <- readIORef (ctxScrollState ctx)-  unless (IM.null (ssGlides st)) $ do-    let alpha = glideAlpha (scrollSmoothTime (ssTuning st)) dt-    done <- mapM (stepGlide ctx alpha) (IM.toList (ssGlides st))-    let settled = [k | (k, True) <- done]-    unless (null settled) $-      modifyIORef' (ctxScrollState ctx) $ \s ->-        s {ssGlides = foldr IM.delete (ssGlides s) settled}---- | Fraction of the remaining distance a glide covers in @dt@ seconds.--- 'scrollSmoothTime' is the time to cover all but a twentieth of it.-glideAlpha :: Float -> Float -> Float-glideAlpha smooth dt-  | smooth <= 0 || dt <= 0 = 1-  | otherwise = clamp 0 1 (1 - exp (negate (3 * dt / smooth)))--stepGlide :: Context -> Float -> (Int, ScrollGlide) -> IO (Int, Bool)-stepGlide ctx alpha (key, ScrollGlide wid target axes) = do-  cur <- projectAxes axes <$> getScrollOffsetIn ctx wid axes-  let next = V2 (stepAxis (v2X cur) (v2X target)) (stepAxis (v2Y cur) (v2Y target))-  writeScrollOffsetIn ctx wid axes next-  pure (key, nearOffset next target)-  where-    stepAxis c t-      | abs (t - c) <= 1 = t-      | otherwise =-          let moved = c + (t - c) * alpha-           in if abs (moved - c) < 1-                then c + signum (t - c)-                else moved--nearOffset :: V2 -> V2 -> Bool-nearOffset (V2 ax ay) (V2 bx by) = abs (ax - bx) <= 0.01 && abs (ay - by) <= 0.01
− lib/NanoUI/Context/Types.hs
@@ -1,538 +0,0 @@-{-# LANGUAGE StrictData #-}---- | Record types behind 'Context': interaction, damage, overlay, animation,--- scroll and drawing-cache state, theme scopes, and frame messages.-module NanoUI.Context.Types-  ( Context (..)-  , MeasureCacheKey-  , MetricSource (..)-  , TextInputMenu (..)-  , TextInputDrag (..)-  , TextFieldClickCell (..)-  , WindowResizeEdge (..)-  , WindowResizeDrag (..)-  , DamageRequest (..)-  , DamageState (..)-  , initialDamageState-  , OverlayState (..)-  , initialOverlayState-  , AnimationState (..)-  , initialAnimationState-  , ScrollTuning (..)-  , defaultScrollTuning-  , ScrollAxes (..)-  , ScrollGlide (..)-  , ScrollState (..)-  , initialScrollState-  , DrawFitCache (..)-  , DrawingEntry (..)-  , DrawingCacheState (..)-  , PopupConfig (..)-  , DrawOpCacheEntry (..)-  , CustomDrawingEntry (..)-  , CustomDrawOpCacheEntry (..)-  , SpanCacheEntry (..)-  , WidgetTextCacheEntry (..)-  , WidgetTextPlacement (..)-  , initialDrawingCacheState-  , InteractionState (..)-  , initialInteractionState-  , CustomMeasureFn-  , CustomDrawContext (..)-  , CustomDrawBuild-  , ThemeScopes (..)-  , FrameMsg (..)-  , decodeMessages-  , reduceMessages-  , reduceUpdates-  , intKey-  ) where--import Data.Dynamic (Dynamic)-import Data.HashMap.Strict (HashMap)-import Data.IORef (IORef)-import Data.IntMap.Strict (IntMap)-import Data.IntMap.Strict qualified as IM-import Data.IntSet (IntSet)-import Data.IntSet qualified as IS-import Data.Map.Strict (Map)-import Data.Primitive.PrimArray (MutablePrimArray)-import Data.Primitive.SmallArray (SmallArray, SmallMutableArray)-import Data.Word (Word64)-import Data.Text (Text)-import Data.Typeable (TypeRep, Typeable, cast)-import GHC.Exts (RealWorld)--import NanoUI.Animation (Animation)-import NanoUI.Atlas (ImageAtlas)-import NanoUI.Draw.Types (DrawArena, DrawOp, DrawingBuild)-import NanoUI.Font (CustomMeasureFn, FontMetrics)-import NanoUI.Frame.SpanArena (SpanArena)-import NanoUI.Id (IdContext, WidgetId, hashWidgetId)-import NanoUI.Input (UiCursorKind)-import NanoUI.Layout.Arena (DirTag, LayoutCache, NodeArena)-import NanoUI.Store (WidgetStore)-import NanoUI.Style (FontStyle, FontVariant, FontWeight, Layout, Theme)-import NanoUI.Widgets.TextCommand (TextCommand)-import NanoUI.Types-  ( Color-  , Damage (..)-  , DamageBounds-  , PopupAnchor-  , PopupPlacement-  , Rect-  , Size (..)-  , V2-  )---- | Themes the view's @styled@ scopes pushed this frame, and last frame's, to--- tell whether a frame changed only how its scopes look. A node's scope holds--- an index into 'tsThemes' plus one; index 0 is the context theme.-data ThemeScopes = ThemeScopes-  { tsCount :: {-# UNPACK #-} !Int-  , tsThemes :: !(SmallMutableArray RealWorld Theme)-  -- ^ What each scope is drawn with.-  , tsRaw :: !(SmallMutableArray RealWorld Theme)-  -- ^ Each scope's theme before a disabled scope faded it, which nested-  -- @styled@ scopes modify.-  , tsPrevCount :: {-# UNPACK #-} !Int-  , tsPrev :: !(SmallMutableArray RealWorld Theme)-  , tsPrevRaw :: !(SmallMutableArray RealWorld Theme)-  , tsDisabled :: !Bool-  -- ^ A disabled scope was entered this pass, so some widget may be disabled.-  , tsChanged :: !Bool-  -- ^ A pushed theme differs from the one at its index last frame.-  , tsPrevSig :: {-# UNPACK #-} !Word64-  -- ^ Last frame's scope signature ('NanoUI.Layout.Arena.getScopeSignature').-  }--data FrameMsg where-  FrameMsg :: Typeable a => a -> FrameMsg--decodeMessages :: (Foldable f, Typeable a) => f FrameMsg -> [a]-decodeMessages = foldr (\(FrameMsg x) rest -> maybe rest (: rest) (cast x)) []--reduceMessages :: (Foldable f, Typeable msg) => (msg -> model -> model) -> model -> f FrameMsg -> model-reduceMessages update = foldl' (\model (FrameMsg x) -> maybe model (`update` model) (cast x))--reduceUpdates :: (Foldable f, Typeable model) => model -> f FrameMsg -> model-reduceUpdates = reduceMessages ($)--type MeasureCacheKey = (Text, Float)---- | Identity of a font/measurement configuration. Pure Context modifiers--- replace this value; the next frame invalidates shared caches if its identity--- differs. Holding the current inputs (not a revision counter/history) also--- distinguishes two differently configured Contexts derived from one parent.-data MetricSource-  = InitialMetricSource-  | MetricSource-      !FontMetrics-      !FontMetrics-      !(Text -> IO (Float, Float))-      !(Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool))-      !(Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float))---- | Explicit damage invalidation request queued during frame evaluation.-data DamageRequest-  = ReqWidget !WidgetId !DamageBounds      -- ^ Invalidate widget layout bounds (old & new)-  | ReqKey !Int !DamageBounds              -- ^ Invalidate widget bounds by integer key-  | ReqRect !Rect                          -- ^ Invalidate an explicit window-space rectangle-  | ReqPeers ![WidgetId] !DamageBounds     -- ^ Invalidate a collection of widgets-  | ReqFull                                -- ^ Force full window invalidation-  deriving (Eq, Show)--data TextInputMenu = TextInputMenu-  { textInputMenuWidget :: WidgetId-  , textInputMenuRect :: Rect-  }-  deriving (Eq, Show)--data TextInputDrag = TextInputDrag-  { textInputDragWidget :: WidgetId-  , textInputDragAnchor :: {-# UNPACK #-} !Int-  , textInputDragAnchorRow :: {-# UNPACK #-} !Int-  , textInputDragAnchorCol :: {-# UNPACK #-} !Int-  , textInputDragMultiline :: {-# UNPACK #-} !Bool-  , textInputDragClicks :: {-# UNPACK #-} !Int-  }-  deriving (Eq, Show)--data TextFieldClickCell = TextFieldClickCell-  { textFieldClickWidget :: WidgetId-  , textFieldClickFlat :: {-# UNPACK #-} !Int-  , textFieldClickRow :: {-# UNPACK #-} !Int-  , textFieldClickCol :: {-# UNPACK #-} !Int-  , textFieldClickMultiline :: {-# UNPACK #-} !Bool-  }-  deriving (Eq, Show)--data WindowResizeEdge-  = ResizeN-  | ResizeS-  | ResizeE-  | ResizeW-  | ResizeNE-  | ResizeNW-  | ResizeSE-  | ResizeSW-  deriving (Eq, Show)--data WindowResizeDrag = WindowResizeDrag-  { wrdWidget :: WidgetId-  , wrdEdge :: WindowResizeEdge-  , wrdGrabX :: {-# UNPACK #-} !Float-  , wrdGrabY :: {-# UNPACK #-} !Float-  , wrdStartX :: {-# UNPACK #-} !Float-  , wrdStartY :: {-# UNPACK #-} !Float-  , wrdStartW :: {-# UNPACK #-} !Float-  , wrdStartH :: {-# UNPACK #-} !Float-  , wrdMinW :: {-# UNPACK #-} !Float-  , wrdMinH :: {-# UNPACK #-} !Float-  , wrdMaxW :: {-# UNPACK #-} !Float-  , wrdMaxH :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)--data DamageState = DamageState-  { dsDirty :: !Bool-  , dsDamage :: !Damage-  , dsRequests :: ![DamageRequest]-  , dsLastWindowSize :: !Size-  , dsPrevRects :: !(IntMap Rect)-  , dsPrevClips :: !(IntMap Rect)-  , dsPrevNodeTexts :: !(IntMap Text)-  }--initialDamageState :: DamageState-initialDamageState = DamageState-  { dsDirty = True-  , dsDamage = DamageFull-  , dsRequests = []-  , dsLastWindowSize = Size 0 0-  , dsPrevRects = IM.empty-  , dsPrevClips = IM.empty-  , dsPrevNodeTexts = IM.empty-  }--data OverlayState = OverlayState-  { osModalWasActive :: {-# UNPACK #-} !Bool-  , osModalActive :: {-# UNPACK #-} !Bool-  , osModalDepth :: {-# UNPACK #-} !Int-  , osEscapeConsumed :: {-# UNPACK #-} !Bool-  , osPrevFloatingRects :: !(IntMap Rect)-  , osPrevFloatingOrder :: ![Int]-  , osTopmostCache :: !(Maybe (V2, Maybe WidgetId))-  , osCurrentFloatingId :: !(Maybe WidgetId)-  , osLastPointerBlocked :: {-# UNPACK #-} !Bool-  }--initialOverlayState :: OverlayState-initialOverlayState = OverlayState-  { osModalWasActive = False-  , osModalActive = False-  , osModalDepth = 0-  , osEscapeConsumed = False-  , osPrevFloatingRects = IM.empty-  , osPrevFloatingOrder = []-  , osTopmostCache = Nothing-  , osCurrentFloatingId = Nothing-  , osLastPointerBlocked = False-  }--data AnimationState = AnimationState-  { asAnimations :: !(IntMap Animation)-  , asAnimRest :: !(IntMap Float)-  , asAnyAnimating :: {-# UNPACK #-} !Bool-  , asAnimSettled :: {-# UNPACK #-} !Bool-  , asRectless :: !(IntMap Int)-  }--initialAnimationState :: AnimationState-initialAnimationState = AnimationState-  { asAnimations = IM.empty-  , asAnimRest = IM.empty-  , asAnyAnimating = False-  , asAnimSettled = False-  , asRectless = IM.empty-  }---- | How far one wheel notch scrolls, and how long a scroll takes to settle.--- One setting for the whole context; a single scroller can take its own step--- (see @setScrollStep@).-data ScrollTuning = ScrollTuning-  { scrollWheelStep :: Float-  -- ^ Pixels one wheel notch scrolls. The default is three text lines, which-  -- is what Windows and most desktops send a notch as.-  , scrollSmoothTime :: Float-  -- ^ Seconds a scroll takes to cover most of the distance to its target.-  -- @0@ (the default) lands on it in the same frame.-  }-  deriving (Eq, Show)--defaultScrollTuning :: ScrollTuning-defaultScrollTuning =-  ScrollTuning-    { scrollWheelStep = 60-    , scrollSmoothTime = 0-    }---- | Which axes a scroller moves on, and how an offset in window axes (x--- rightwards, y downwards) maps onto its stored offset. A 1D row scroller--- keeps its offset in the main-axis slot, so its horizontal offset is the one--- that needs swapping.-data ScrollAxes-  = ScrollAxisY-  | ScrollAxisX-  | ScrollAxisXY-  deriving (Eq, Show)---- | A scroller on its way to an offset it has not reached yet. The target is--- in window axes and already clamped to the scroller's range.-data ScrollGlide = ScrollGlide-  { sgWidget :: WidgetId-  , sgTarget :: V2-  , sgAxes :: ScrollAxes-  }-  deriving (Eq, Show)--data ScrollState = ScrollState-  { ssTuning :: !ScrollTuning-  , ssGlides :: !(IntMap ScrollGlide)-  , ssCached :: !IntSet-  -- ^ Scrollers whose geometry has been published this frame. Two scroll-  -- nodes can share a widget id (a table's frozen pane and its body), and-  -- without this the second would overwrite the first every frame, churning-  -- the store and flipping the geometry the commands read.-  }--initialScrollState :: ScrollState-initialScrollState =-  ScrollState-    { ssTuning = defaultScrollTuning-    , ssGlides = IM.empty-    , ssCached = IS.empty-    }--data DrawFitCache = DrawFitCache-  { dfcDw :: {-# UNPACK #-} !Double-  , dfcDh :: {-# UNPACK #-} !Double-  , dfcLh :: {-# UNPACK #-} !Float-  , dfcContent :: {-# UNPACK #-} !Int-  , dfcIn :: !Layout-  , dfcOut :: !Layout-  }---- | Cached text-span layout for one arena node. Key fields are every input--- that changes the produced spans; 'sceSpans' is the shared result. The whole--- cache is dropped on theme or font-scale changes.-data SpanCacheEntry = SpanCacheEntry-  { sceText :: !Text-  , sceFg :: {-# UNPACK #-} !Color-  , sceBg :: {-# UNPACK #-} !Color-  , sceStyle :: {-# UNPACK #-} !Int-  , sceFontSize :: {-# UNPACK #-} !Float-  , sceAlign :: {-# UNPACK #-} !Int-  , sceWidthTag :: {-# UNPACK #-} !Int-  , sceRect :: !Rect-  , sceEffMaxW :: {-# UNPACK #-} !Float-  , sceRowChild :: {-# UNPACK #-} !Bool-  , sceSpans :: ![(Rect, Text, Color, Color)]-  }---- | A cacheable widget label is a single line (or absent for close buttons).--- Coordinates are relative to the node origin; paint translates them without--- rebuilding a list or invalidating the cache when a widget scrolls.-data WidgetTextPlacement = WidgetTextPlacement-  !Text-  {-# UNPACK #-} !Float-  {-# UNPACK #-} !Float-  {-# UNPACK #-} !Float-  {-# UNPACK #-} !Float--data WidgetTextCacheEntry = WidgetTextCacheEntry-  { wtcNodeType :: {-# UNPACK #-} !Int-  , wtcStyle :: {-# UNPACK #-} !Int-  , wtcFontSize :: {-# UNPACK #-} !Float-  , wtcText :: !Text-  , wtcWidth :: {-# UNPACK #-} !Float-  , wtcHeight :: {-# UNPACK #-} !Float-  , wtcAlign :: {-# UNPACK #-} !Int-  , wtcPlacement :: {-# NOUNPACK #-} !(Maybe WidgetTextPlacement)-  }--data CustomDrawContext = CustomDrawContext-  { cdcHovered  :: {-# UNPACK #-} !Bool-  , cdcPressed  :: {-# UNPACK #-} !Bool-  , cdcFocused  :: {-# UNPACK #-} !Bool-  , cdcActive   :: {-# UNPACK #-} !Bool-  , cdcDisabled :: {-# UNPACK #-} !Bool-  , cdcTheme    :: !Theme-  , cdcFont     :: !FontMetrics-  }--type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp---- | A registered custom drawing: its content key plus the op builder. A--- non-zero key is the author's promise that the ops follow it, so a frame--- whose key is unchanged neither rebuilds nor repaints them. Key 0 means the--- drawing carries no key and is rebuilt every frame and compared.-data CustomDrawingEntry = CustomDrawingEntry-  { cdrContent :: {-# UNPACK #-} !Int-  , cdrBuild :: !CustomDrawBuild-  }---- | A registered drawing: content version plus the op builder. The version--- participates in the draw-op cache key, so a builder whose output changes--- without its size changing must bump the version to invalidate.-data DrawingEntry = DrawingEntry-  { deContent :: {-# UNPACK #-} !Int-  , deBuild :: !DrawingBuild-  }--data DrawingCacheState = DrawingCacheState-  { dcsPopupConfigs :: !(IntMap PopupConfig)-  , dcsDrawings :: !(IntMap DrawingEntry)-  , dcsCustomDrawings :: !(IntMap CustomDrawingEntry)-  , dcsCustomMeasures :: !(IntMap CustomMeasureFn)-  , dcsCustomCursors :: !(IntMap (CustomDrawContext -> UiCursorKind))-  , dcsCustomDamageSlop :: !(IntMap Float)-  , dcsDrawOpCache :: !(IntMap DrawOpCacheEntry)-  , dcsCustomDrawOpCache :: !(IntMap CustomDrawOpCacheEntry)-  , dcsDrawFitCache :: !(IntMap DrawFitCache)-  }---- | Strict cache entry for a popup's anchor configuration.-data PopupConfig = PopupConfig-  { pcAnchor :: !PopupAnchor-  , pcPlacement :: !PopupPlacement-  , pcOffset :: {-# UNPACK #-} !Float-  }---- | Strict cache entry for a drawing's compiled draw ops.-data DrawOpCacheEntry = DrawOpCacheEntry-  { doeContent :: {-# UNPACK #-} !Int-  , doeBounds :: !Rect-  , doeOps :: !(SmallArray DrawOp)-  }---- | Strict cache entry for a custom drawing's compiled draw ops. Every input--- the ops can depend on is part of the key: the content key, the rect, the--- interaction state the draw context exposes, and the metric generation, which--- a theme or font change bumps.-data CustomDrawOpCacheEntry = CustomDrawOpCacheEntry-  { cdeContent :: {-# UNPACK #-} !Int-  , cdeBounds :: !Rect-  , cdeHovered :: {-# UNPACK #-} !Bool-  , cdePressed :: {-# UNPACK #-} !Bool-  , cdeFocused :: {-# UNPACK #-} !Bool-  , cdeDisabled :: {-# UNPACK #-} !Bool-  , cdeGen :: {-# UNPACK #-} !Int-  , cdeOps :: !(SmallArray DrawOp)-  }--initialDrawingCacheState :: DrawingCacheState-initialDrawingCacheState = DrawingCacheState-  { dcsPopupConfigs = IM.empty-  , dcsDrawings = IM.empty-  , dcsCustomDrawings = IM.empty-  , dcsCustomMeasures = IM.empty-  , dcsCustomCursors = IM.empty-  , dcsCustomDamageSlop = IM.empty-  , dcsDrawOpCache = IM.empty-  , dcsCustomDrawOpCache = IM.empty-  , dcsDrawFitCache = IM.empty-  }--data InteractionState = InteractionState-  { isScrollDrag :: !(Maybe (WidgetId, DirTag, Float))-  , isTextInputDrag :: !(Maybe TextInputDrag)-  , isTextFieldClickCell :: !(Maybe TextFieldClickCell)-  , isTextInputMenu :: !(Maybe TextInputMenu)-  , isTextEditLastAction :: !(Maybe (WidgetId, TextCommand))-  , isSelectDropPress :: {-# UNPACK #-} !Bool-  , isOpenSelectDrop :: !(Maybe (WidgetId, Rect))-  , isMenuPointerGesture :: {-# UNPACK #-} !Bool-  , isWindowDrag :: !(Maybe (WidgetId, Float, Float))-  , isWindowResize :: !(Maybe WindowResizeDrag)-  }-  deriving (Eq, Show)--initialInteractionState :: InteractionState-initialInteractionState = InteractionState-  { isScrollDrag = Nothing-  , isTextInputDrag = Nothing-  , isTextFieldClickCell = Nothing-  , isTextInputMenu = Nothing-  , isTextEditLastAction = Nothing-  , isSelectDropPress = False-  , isOpenSelectDrop = Nothing-  , isMenuPointerGesture = False-  , isWindowDrag = Nothing-  , isWindowResize = Nothing-  }--data Context = Context-  { ctxNodeArena :: NodeArena-  , ctxDrawArena :: DrawArena-  , ctxHotId :: IORef WidgetId-  , ctxLastHotId :: IORef WidgetId-  , ctxActiveId :: IORef WidgetId-  , ctxClickedId :: IORef WidgetId-  , ctxReleaseClickedId :: IORef WidgetId-  -- | Where the held left and right buttons went down, cleared when they come-  -- up. A click belongs to the widget the press landed on, so a widget-  -- hit-tests this point as well as the release point. 'Nothing' (a release-  -- with no press behind it) lets the release stand on its own.-  , ctxPressPos :: IORef (Maybe V2)-  , ctxRightPressPos :: IORef (Maybe V2)-  , ctxFocusId :: IORef WidgetId-  -- | Focus last moved by keyboard, so the focused widget shows its ring. A-  -- pointer press hides it again.-  , ctxFocusVisible :: IORef Bool-  , ctxStore :: IORef WidgetStore-  , ctxDamageState :: IORef DamageState-  , ctxOverlayState :: IORef OverlayState-  , ctxAnimationState :: IORef AnimationState-  , ctxScrollState :: !(IORef ScrollState)-  , ctxDrawingCache :: IORef DrawingCacheState-  , ctxIdContext :: IORef IdContext-  , ctxFontMetrics :: FontMetrics-  , ctxMonoFontMetrics :: FontMetrics-  , ctxMeasureText :: Text -> IO (Float, Float)-  , ctxResolveFont :: !(Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool))-  , ctxResolveMeasure :: !(Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float))-  , ctxMeasureCache :: Maybe (IORef (HashMap MeasureCacheKey (Float, Float)))-  , ctxSpanCache :: !(IORef (IntMap SpanCacheEntry))-  , ctxWidgetTextCache :: !(IORef (IntMap WidgetTextCacheEntry))-  -- Whole-layout reuse cache (Phase 5A): cached signature + solved rects,-  -- with the window size and font/theme generation it was captured under.-  , ctxLayoutCache :: !(IORef (Maybe (LayoutCache, Size, Int)))-  , ctxMetricGen :: !(IORef Int)-  , ctxMetricSource :: {-# NOUNPACK #-} !MetricSource-  , ctxLastMetricSource :: !(IORef (Maybe MetricSource))-  -- True when the next present must repaint the whole window (fresh retain-  -- texture, forced full, continuous present, or window expose). When False,-  -- a DamageClip frame culls the paint pass to the damaged region.-  , ctxPaintFull :: !(IORef Bool)-  , ctxExternalText :: Bool-  , ctxTheme :: !(IORef Theme)-  , ctxThemeScopes :: !(IORef ThemeScopes)-  , ctxContainerStack :: IORef [Int]-  , ctxMessages :: IORef [FrameMsg]-  , ctxFocusables :: IORef (MutablePrimArray RealWorld WidgetId)-  , ctxFocusablesCount :: IORef Int-  , ctxSpanBase :: SpanArena-  , ctxSpanOverlay :: SpanArena-  , ctxInteractionState :: !(IORef InteractionState)-  , ctxClipboardGet :: IO (Maybe Text)-  , ctxClipboardSet :: Text -> IO Bool-  , ctxImageAtlas :: ImageAtlas-  , ctxWakeLoop :: IORef (Maybe (IO ()))-  , ctxHost :: IORef (Map TypeRep Dynamic)-  , ctxDefaultLayout :: IORef Layout-  }--{-# INLINE intKey #-}-intKey :: WidgetId -> Int-intKey = fromIntegral . hashWidgetId
− lib/NanoUI/Damage.hs
@@ -1,704 +0,0 @@-module NanoUI.Damage-  ( updatePrevRects-  , floatingPanelRects-  , FrameSnapshot (..)-  , writeDamage-  ) where--import Control.Monad (forM_, join, unless, when)-import Data.IORef (readIORef)-import Data.IntMap.Strict qualified as IM-import Data.IntSet qualified as IS-import Data.Maybe (fromMaybe, isJust)-import Data.Primitive.PrimArray (MutablePrimArray, newPrimArray, readPrimArray, writePrimArray)-import Data.Text (Text)-import GHC.Exts (RealWorld)-import NanoUI.Context-  ( Animation-  , Context (..)-  , DamageRequest (..)-  , WidgetStore (..)-  , getHotId-  , getLiveAnimations-  , getAnimRest-  , pruneAnimRest-  , getAnimRectless-  , getPrevRect-  , getStore-  , getWindowDrag-  , getWindowResize-  , intKey-  , markDirty-  , modalDamageFlip-  , setAnimRectless-  , takeAnimSettled-  , lookupCustomDamageSlop-  , lookupCustomDrawing-  , lookupDrawing-  , refreshCustomDrawingOps-  , drawingOpsStale-  , CustomDrawingEntry (..)-  , DrawingEntry (..)-  , DamageState (..)-  , OverlayState (..)-  , getsDamage-  , modifyDamage-  , modifyOverlay-  )-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input-  ( Input (..)-  , inputWindowSize-  )-import NanoUI.Frame.Hit (findNodeByKey)-import NanoUI.Store (eqByPtr, mirrorStoresChanged, ptrEq, slotKey, Slot (..))-import NanoUI.Layout.Arena-  ( NodeArena-  , NodeType (..)-  , SizingTag (..)-  , arenaCount-  , foldNodeRevM-  , getClipRect-  , getHeightSizing-  , getNodeType-  , getParent-  , getRect-  , getStyleIdx-  , getText-  , getWidgetId-  , getWidthSizing-  , isFloatingNode-  , isScrollNode-  )-import NanoUI.Frame.Scroll.Geometry (decodeScrollConfig, scrollBare)-import NanoUI.Widgets.Custom (mkCustomDrawContext)-import NanoUI.Types-  ( Damage (..)-  , Rect (..)-  , Size (..)-  , defaultDamageSlop-  , rectArea-  , rectFullyInside-  , rectInflate-  , rectIntersect-  , rectNonEmpty-  , rectUnion-  , resolveDamageRect-  )--layoutSettleMinArea :: Float-layoutSettleMinArea = 0.25---- | Bound on how many consecutive rect-less frames a live animation may force a--- full-window repaint. An animation whose widget is about to be laid out for the--- first time gets a couple of frames of DamageFull cover; a perpetual animation--- whose widget has left the arena (e.g. `keepAnimating` behind a tab switch)--- must stop repainting the whole window once it is clearly gone.-orphanEscalateFrames :: Int-orphanEscalateFrames = 2---- Partial retain clears with themeWindow. Expand interaction clips to the painted--- panel/window backdrop so slop pixels get the correct fill, not window color.-backdropRectFromNode :: Context -> Int -> IO (Maybe Rect)-backdropRectFromNode ctx idx = walkAncestors step (ctxNodeArena ctx) idx-  where-    step i = do-      let na = ctxNodeArena ctx-      nt <- getNodeType na i-      if nt == NodePanel || isFloatingNode nt-        then getNonzeroRect na i-        else case nt of-          NodeScrollContainer -> do-            (wTag, _) <- getWidthSizing na i-            (hTag, _) <- getHeightSizing na i-            si <- getStyleIdx na i-            if (wTag == SizingGrow && hTag == SizingGrow) || scrollBare (decodeScrollConfig si)-              then pure Nothing-              else getNonzeroRect na i-          _ -> pure Nothing--{-# INLINE walkAncestors #-}-walkAncestors :: (Int -> IO (Maybe a)) -> NodeArena -> Int -> IO (Maybe a)-walkAncestors step arena idx = loop idx-  where-    loop i-      | i < 0 = pure Nothing-      | otherwise = do-          mr <- step i-          case mr of-            Just x -> pure (Just x)-            Nothing -> getParent arena i >>= loop--{-# INLINE getNonzeroRect #-}-getNonzeroRect :: NodeArena -> Int -> IO (Maybe Rect)-getNonzeroRect arena i = do-  (x, y, w, h) <- getRect arena i-  let r = Rect x y w h-  pure (if rectNonEmpty r then Just r else Nothing)--updatePrevRects :: Context -> IO ()-updatePrevRects ctx = do-  live <- getLiveAnimations ctx-  prevRectless <- getAnimRectless ctx-  oldRects <- getsDamage ctx dsPrevRects-  oldClips <- getsDamage ctx dsPrevClips-  oldTexts <- getsDamage ctx dsPrevNodeTexts-  let na = ctxNodeArena ctx-      bump rects = do-        rest <- getAnimRest ctx-        let rectless' =-              IM.fromSet-                (\k -> if IM.member k rects then 0 else IM.findWithDefault 0 k prevRectless + 1)-                (IM.keysSet live <> IM.keysSet rest)-            deadRest = IM.filterWithKey (\k _ -> IM.findWithDefault 0 k rectless' > 300) rest-        unless (IM.null deadRest) $-          pruneAnimRest ctx (\k -> IM.notMember k deadRest)-        -- Every key is live or resting, so this drops exactly the dead resting-        -- keys that are not live again.-        setAnimRectless ctx (rectless' `IM.difference` (deadRest `IM.difference` live))-  count <- arenaCount na-  if count <= 0-    then do-      modifyDamage ctx (\ds -> ds {dsPrevRects = IM.empty, dsPrevClips = IM.empty, dsPrevNodeTexts = IM.empty})-      bump IM.empty-    else do-      -- Walk the arena from base maps, touching only entries whose value-      -- changed. Seeded with last frame's maps, frames with stable rects-      -- (hover, text churn, animations) allocate nothing. The walk cannot-      -- delete keys that vanished from the arena, so when the key set changed-      -- it reruns from empty maps, where no key counts as old.-      let go olds !i !m !cm !tm !foundOld !dropped-            | i >= count =-                if dropped || foundOld /= IM.size olds-                  then go IM.empty 0 IM.empty IM.empty IM.empty 0 False-                  else do-                    modifyDamage ctx (\ds -> ds {dsPrevRects = m, dsPrevClips = cm, dsPrevNodeTexts = tm})-                    bump m-            | otherwise = do-                wid <- getWidgetId na i-                if hashWidgetId wid == 0-                  then go olds (i + 1) m cm tm foundOld dropped-                  else do-                    let !k = intKey wid-                        isOld = IM.member k olds-                    mRect <- getNonzeroRect na i-                    case mRect of-                      Nothing ->-                        let dropped' = dropped || isOld-                            m' = if isOld then IM.delete k m else m-                            cm' = if IM.member k cm then IM.delete k cm else cm-                            tm' = if IM.member k tm then IM.delete k tm else tm-                         in go olds (i + 1) m' cm' tm' foundOld dropped'-                      Just r -> do-                        mClip <- getClipRect na i-                        nt <- getNodeType na i-                        let !m' = if IM.lookup k m == Just r then m else IM.insert k r m-                            !cm' = case mClip of-                              Just c -> if IM.lookup k cm == Just c then cm else IM.insert k c cm-                              Nothing -> if IM.member k cm then IM.delete k cm else cm-                        -- Text nodes, and images, whose text is their image-                        -- id: switching an image repaints it like new text.-                        tm' <--                          if nt == NodeText || nt == NodeImage-                            then do-                              txt <- getText na i-                              pure $! if IM.lookup k tm == Just txt then tm else IM.insert k txt tm-                            else pure $! if IM.member k tm then IM.delete k tm else tm-                        go olds (i + 1) m' cm' tm' (foundOld + if isOld then 1 else 0) dropped-      go oldRects 0 oldRects oldClips oldTexts 0 False--floatingPanelsInOrder :: Context -> IO [(Int, Rect)]-floatingPanelsInOrder ctx = foldNodeRevM na step []-  where-    na = ctxNodeArena ctx-    step acc idx = do-      nt <- getNodeType na idx-      if not (isFloatingNode nt)-        then pure acc-        else do-          wid <- getWidgetId na idx-          if hashWidgetId wid == 0-            then pure acc-            else do-              (x, y, w, h) <- getRect na idx-              pure ((intKey wid, Rect x y w h) : acc)--floatingPanelRects :: Context -> IO (IM.IntMap Rect)-floatingPanelRects ctx = IM.fromList <$> floatingPanelsInOrder ctx---- | State 'NanoUI.Frame' captures before the UI pass; 'writeDamage' compares--- it against the finished frame.-data FrameSnapshot = FrameSnapshot-  { fsWasDirty :: !Bool-  , fsSize :: !Size-  , fsStore :: !WidgetStore-  , fsHot :: !WidgetId-  , fsActive :: !WidgetId-  , fsFocus :: !WidgetId-  , fsHotRect :: !(Maybe Rect)-  , fsActiveRect :: !(Maybe Rect)-  , fsFocusRect :: !(Maybe Rect)-  , fsFloatingRects :: !(IM.IntMap Rect)-  , fsRects :: !(IM.IntMap Rect)-  , fsTexts :: !(IM.IntMap Text)-  , fsAnimKeys :: !IS.IntSet-  }---- | What the finished frame looks like and what changed since the snapshot.--- Derived fields stay lazy: a frame that is already 'DamageFull' for a cheap--- reason never pays for them.-data FrameDelta = FrameDelta-  { fdWinSize :: !Size-  , fdOverlayOpen :: !Bool-  , fdStore :: !WidgetStore-  , fdRects :: !(IM.IntMap Rect)-  , fdTexts :: !(IM.IntMap Text)-  , fdFloatingRects :: !(IM.IntMap Rect)-  , fdModalFlip :: !Bool-  , fdLiveAnims :: !(IM.IntMap Animation)-  , fdRectless :: !(IM.IntMap Int)-  , fdWindowLive :: !Bool-  , fdRequests :: ![DamageRequest]-  , fdAnimLive :: Bool-  , fdFloatingChanged :: Bool-  , fdScrollChanged :: Bool-  , fdPointsChanged :: Bool-  , fdScrollOnly :: Bool-  -- ^ Only 'storeFloat' changed in the store, e.g. a floating pane scrolled.-  , fdSettledMoved :: !RectGroup-  -- ^ Changed key rects, clipped to their scroll viewports, that cover some-  -- area.-  , fdChurn :: !RectGroup-  -- ^ Rects of keys that left or joined the arena.-  , fdRedrawn :: ![Int]-  -- ^ Keys of drawings whose ops changed at an unchanged rect.-  }--writeDamage :: Context -> Input -> Bool -> FrameSnapshot -> IO ()-writeDamage ctx inp overlayOpen snap = do-  newStore <- getStore ctx-  panels <- floatingPanelsInOrder ctx-  newRects <- getsDamage ctx dsPrevRects-  newTexts <- getsDamage ctx dsPrevNodeTexts-  modalFlip <- modalDamageFlip ctx-  liveAnims <- getLiveAnimations ctx-  settled <- takeAnimSettled ctx-  rectless <- getAnimRectless ctx-  winDragActive <- isJust <$> getWindowDrag ctx-  winResizeActive <- isJust <$> getWindowResize ctx-  requests <- getsDamage ctx dsRequests-  redrawn <- refreshCustomDrawings ctx-  let oldRects = fsRects snap-      oldStore = fsStore snap-      newFloatingRects = IM.fromList panels-  (settledMoved, churn) <- rectDeltas ctx (map snd panels) oldRects newRects-  let scrollChanged = not (eqByPtr (storeFloat oldStore) (storeFloat newStore))-      delta =-        FrameDelta-          { fdWinSize = inputWindowSize inp-          , fdOverlayOpen = overlayOpen-          , fdStore = newStore-          , fdRects = newRects-          , fdTexts = newTexts-          , fdFloatingRects = newFloatingRects-          , fdModalFlip = modalFlip-          , fdLiveAnims = liveAnims-          , fdRectless = rectless-          , fdWindowLive = winDragActive || winResizeActive-          , fdRequests = requests-          , fdAnimLive = not (IM.null liveAnims) || settled-          , fdFloatingChanged = fsFloatingRects snap /= newFloatingRects-          , fdScrollChanged = scrollChanged-          , fdPointsChanged = not (eqByPtr (storePoint oldStore) (storePoint newStore))-          , fdScrollOnly =-              scrollChanged && oldStore == newStore {storeFloat = storeFloat oldStore}-          , fdSettledMoved = settledMoved-          , fdChurn = churn-          , fdRedrawn = redrawn-          }-  dmg <--    if needsFullDamage snap delta-      then pure DamageFull-      else clipDamage ctx snap delta-  modifyDamage ctx (\ds -> ds {dsDamage = dmg, dsLastWindowSize = inputWindowSize inp, dsRequests = []})-  modifyOverlay ctx (\os -> os {osPrevFloatingRects = newFloatingRects, osPrevFloatingOrder = map fst panels})-  when modalFlip (markDirty ctx)-  when (fdFloatingChanged delta && not (IM.null (fsFloatingRects snap) && not (IM.null newFloatingRects))) $-    markDirty ctx---- | Settle every drawing's ops for this frame and return the keys of those--- that now draw something else at an unchanged rect. A drawing follows state--- the arena does not hold, so nothing else damages it, and paint must not--- replay the previous frame's ops for it. What this costs per widget is the--- widget's own choice: see 'refreshCustomDrawingOps'.-refreshCustomDrawings :: Context -> IO [Int]-refreshCustomDrawings ctx = arenaCount na >>= \count -> go count 0 []-  where-    na = ctxNodeArena ctx-    go count !i acc-      | i >= count = pure acc-      | otherwise = do-          nt <- getNodeType na i-          if nt /= NodeDrawing-            then go count (i + 1) acc-            else do-              wid <- getWidgetId na i-              (x, y, w, h) <- getRect na i-              let rect = Rect x y w h-              mCustom <- lookupCustomDrawing ctx wid-              changed <- case mCustom of-                Just (CustomDrawingEntry content build) -> do-                  cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) wid-                  refreshCustomDrawingOps ctx wid content rect cdc build-                Nothing -> do-                  -- A versioned drawing rebuilds in paint once its version-                  -- changes, but the pixels it covered still need damage. An-                  -- unversioned one is cached by contract, so it stays put.-                  mDrawing <- lookupDrawing ctx wid-                  case mDrawing of-                    Just (DrawingEntry content _) | content /= 0 -> drawingOpsStale ctx wid content rect-                    _ -> pure False-              go count (i + 1) (if changed then intKey wid : acc else acc)---- | Whether the frame repaints the whole window rather than a clip.-needsFullDamage :: FrameSnapshot -> FrameDelta -> Bool-needsFullDamage snap d =-  ReqFull `elem` fdRequests d-    || not (fdScrollOnly d)-      && ( fsWasDirty snap-             || mirrorStoresChanged (fsStore snap) (fdStore d)-             || sizeChanged-             || fdOverlayOpen d-             || fdModalFlip d-             || fdFloatingChanged d-             || fdWindowLive d-             || (orphanAnim && fdAnimLive d)-             || keysChanged-             || layoutSettle-         )-    || (missingAnim && fdAnimLive d)-  where-    oldRects = fsRects snap-    newRects = fdRects d-    oldSize = fsSize snap-    sizeChanged = oldSize /= Size 0 0 && oldSize /= fdWinSize d-    recentlyRectless k = IM.findWithDefault 0 k (fdRectless d) < orphanEscalateFrames-    orphanAnim =-      any (\k -> IM.notMember k newRects && recentlyRectless k) (IM.keys (fdLiveAnims d))-    -- A live animation whose key has no rect this frame or last is not-    -- clipped: the retain texture may never have shown it.-    missingAnim =-      any-        (\k -> k /= 0 && IM.notMember k oldRects && IM.notMember k newRects && recentlyRectless k)-        (IS.toList (fsAnimKeys snap <> IM.keysSet (fdLiveAnims d)))-    keysChanged =-      not (IM.null oldRects)-        && rgAny (fdChurn d)-        && not (rgInPanels (fdChurn d))-    layoutSettle =-      not (IM.null oldRects)-        && rgAny (fdSettledMoved d)-        && not (fdAnimLive d)-        && not (fdScrollChanged d)-        && not (rgInPanels (fdSettledMoved d))---- | The clip covering everything that changed, or 'DamageFull' once that clip--- exceeds half the window.-clipDamage :: Context -> FrameSnapshot -> FrameDelta -> IO Damage-clipDamage ctx snap d = do-  let oldRects = fsRects snap-      newRects = fdRects d-      Size winW winH = fdWinSize d-      oldOf wid-        | wid == fsHot snap = fsHotRect snap-        | wid == fsActive snap = fsActiveRect snap-        | wid == fsFocus snap = fsFocusRect snap-        | otherwise = Nothing-  acc <- newRectUnion-  resolveDamageRequests ctx acc oldRects newRects (fdRequests d)-  -- Backdrop expansion covers interaction slop (hover/press halos) and-  -- explicit damage requests. Animation keys must not expand to their panel-  -- backdrop: an animated widget inside a large panel would damage the whole-  -- panel every frame, and once that union crosses half the window the frame-  -- degrades to DamageFull. The scissored replay redraws the backdrop fill-  -- inside the anim's own rect+slop, so no stale pixels remain.-  let addBackdrop k =-        unless (k == 0) $-          findNodeByKey ctx k-            >>= maybe (pure Nothing) (backdropRectFromNode ctx)-            >>= mapM_ (addRect acc . clipRectToWindow winW winH)-      addInteraction wid = do-        when (hashWidgetId wid /= 0) $ do-          newR <- getPrevRect ctx wid-          slop <- fromMaybe defaultDamageSlop <$> lookupCustomDamageSlop ctx wid-          let addSide = mapM_ (\r -> clipKeyRect ctx (intKey wid) (rectInflate slop r) >>= mapM_ (addRect acc))-          addSide (oldOf wid)-          addSide newR-        addBackdrop (intKey wid)-      -- A parked pointer must not re-damage its hot widget every frame: only-      -- an id change (hover in/out, press, focus move) or a rect move-      -- repaints. Unchanged interaction rects kept the steady state at-      -- DamageFull whenever the hot widget sat inside a panel whose backdrop-      -- covered over half the window.-      role oldW oldR newW = do-        newR <- getPrevRect ctx newW-        when (oldR /= newR) $ addInteraction oldW >> addInteraction newW-  role (fsHot snap) (fsHotRect snap) =<< getHotId ctx-  role (fsActive snap) (fsActiveRect snap) =<< readIORef (ctxActiveId ctx)-  role (fsFocus snap) (fsFocusRect snap) =<< readIORef (ctxFocusId ctx)-  forM_ (fdRequests d) $ \case-    ReqKey k _ -> addBackdrop k-    _ -> pure ()-  when (fdScrollChanged d || fdPointsChanged d) $-    scrollOffsetDamage ctx acc (fsStore snap) (fdStore d)-  let addAnim k =-        unless (k == 0) $-          forM_ [IM.lookup k oldRects, IM.lookup k newRects] $-            mapM_ (\r -> clipKeyRect ctx k (rectInflate defaultDamageSlop r) >>= mapM_ (addRect acc))-  IS.foldr (\k rest -> addAnim k >> rest) (pure ()) (fsAnimKeys snap)-  IM.foldrWithKey-    (\k _ rest -> unless (IS.member k (fsAnimKeys snap)) (addAnim k) >> rest)-    (pure ())-    (fdLiveAnims d)-  -- Same-key text changes that keep the rect (monospace counters, refreshed-  -- readouts) still repaint: rect-delta damage alone would leave them stale.-  -- New text keys inside floating panels also land here; outside panels the-  -- keysChanged predicate already forces full damage. updatePrevRects keeps-  -- last frame's map when no text changed.-  let addText k =-        forM_ (IM.lookup k newRects) $ \r -> do-          -- An image that switched to another image keeps its size, so only-          -- its own rect repaints. A text change can reflow the enclosing-          -- scroller's content and reactivate/resize its chrome (thumb, caps)-          -- outside the text rect; damage the scroll node's full rect so the-          -- lane repaints.-          addRect acc r-          mIdx <- findNodeByKey ctx k-          isImage <- maybe (pure False) (fmap (== NodeImage) . getNodeType (ctxNodeArena ctx)) mIdx-          unless isImage $ scrollAncestorRect ctx k >>= mapM_ (addRect acc)-  unless (ptrEq (fdTexts d) (fsTexts snap)) $-    IM.foldrWithKey (\k _ rest -> addText k >> rest) (pure ()) $-      IM.mergeWithKey-        (\_ new old -> if new /= old then Just () else Nothing)-        (IM.map (const ()))-        (const IM.empty)-        (fdTexts d)-        (fsTexts snap)-  -- Drawings redrawn in place repaint their own rects, like a text change-  -- that keeps its rect.-  forM_ (fdRedrawn d) $ \k ->-    forM_ (IM.lookup k newRects) $ \r -> clipKeyRect ctx k r >>= mapM_ (addRect acc)-  unless (fdScrollOnly d) $ addGroup acc (fdSettledMoved d)-  -- Keys that left repaint as the current backdrop over their old rects. Keys-  -- that arrived must repaint inside their new rects too: the retain texture-  -- has never shown that content, and nothing else covers it (mirror writes-  -- escalate these frames to DamageFull, but layout-driven churn inside-  -- floating panels does not).-  addGroup acc (fdChurn d)-  -- Floating panels that moved, opened or closed repaint where they were and-  -- where they are.-  let addFloating other k r rest = unless (IM.lookup k other == Just r) (addRect acc r) >> rest-  IM.foldrWithKey (addFloating (fdFloatingRects d)) (pure ()) (fsFloatingRects snap)-  IM.foldrWithKey (addFloating (fsFloatingRects snap)) (pure ()) (fdFloatingRects d)-  base <- readRectUnion acc-  let clip = clipRectToWindow winW winH base-      winArea = winW * winH-  -- A live animation with an empty clip is not DamageFull: its-  -- key was either scroll-clipped out of view (nothing visible-  -- changes; scrolling back in damages via the scroll delta) or-  -- rect-less, which missingAnim already promoted to full.-  pure $-    if winArea > 0 && rectArea clip > winArea * 0.5-      then DamageFull-      else DamageClip clip--resolveDamageRequests ::-  Context ->-  RectUnion ->-  IM.IntMap Rect ->-  IM.IntMap Rect ->-  [DamageRequest] ->-  IO ()-resolveDamageRequests ctx acc oldRects newRects reqs =-  forM_ reqs $ \case-    ReqFull -> pure ()-    ReqRect r -> addRect acc r-    ReqWidget wid bounds -> resolveKey (intKey wid) bounds-    ReqKey k bounds -> resolveKey k bounds-    ReqPeers wids bounds -> forM_ wids $ \wid -> resolveKey (intKey wid) bounds-  where-    resolveKey k bounds =-      forM_ [IM.lookup k oldRects, IM.lookup k newRects] $-        mapM_ $ \r -> do-          clipped <- clipDeltaToScrollViewport ctx k (resolveDamageRect bounds r)-          when (rectNonEmpty clipped) $ addRect acc clipped---- | A running union of rects, as @x0, y0, x1, y1@ followed by how many of--- them lie outside every floating panel. The bounds start inverted, so the--- first rect sets them and an empty union reads back as the zero rect.-newtype RectUnion = RectUnion (MutablePrimArray RealWorld Float)--newRectUnion :: IO RectUnion-newRectUnion = do-  a <- newPrimArray 5-  writePrimArray a 0 infinity-  writePrimArray a 1 infinity-  writePrimArray a 2 (-infinity)-  writePrimArray a 3 (-infinity)-  writePrimArray a 4 0-  pure (RectUnion a)-  where-    infinity = 1 / 0--{-# INLINE addRect #-}-addRect :: RectUnion -> Rect -> IO ()-addRect (RectUnion a) (Rect x y w h) = do-  x0 <- readPrimArray a 0-  y0 <- readPrimArray a 1-  x1 <- readPrimArray a 2-  y1 <- readPrimArray a 3-  writePrimArray a 0 (min x0 x)-  writePrimArray a 1 (min y0 y)-  writePrimArray a 2 (max x1 (x + w))-  writePrimArray a 3 (max y1 (y + h))--readRectUnion :: RectUnion -> IO Rect-readRectUnion (RectUnion a) = do-  x0 <- readPrimArray a 0-  y0 <- readPrimArray a 1-  x1 <- readPrimArray a 2-  y1 <- readPrimArray a 3-  pure $! if x0 > x1 then Rect 0 0 0 0 else Rect x0 y0 (x1 - x0) (y1 - y0)---- | A set of rects reduced to what damage needs from it.-data RectGroup = RectGroup-  { rgAny :: !Bool-  , rgInPanels :: !Bool-  -- ^ Some floating panel fully contains each rect; False for an empty group.-  , rgBounds :: !Rect-  }--addGroup :: RectUnion -> RectGroup -> IO ()-addGroup acc g = when (rgAny g) $ addRect acc (rgBounds g)---- | One pass over the keys whose rect changed, reduced to the settled moves--- (clipped to scroll viewports, above 'layoutSettleMinArea') and the keys--- that left or joined the arena.-rectDeltas :: Context -> [Rect] -> IM.IntMap Rect -> IM.IntMap Rect -> IO (RectGroup, RectGroup)-rectDeltas ctx panelRects old new-  | ptrEq old new = pure (emptyGroup, emptyGroup)-  | otherwise = do-      settled <- newRectUnion-      churn <- newRectUnion-      let note acc@(RectUnion a) r = do-            addRect acc r-            unless (any (rectFullyInside r) panelRects) $-              readPrimArray a 4 >>= writePrimArray a 4 . (+ 1)-      IM.foldrWithKey-        ( \k r rest -> do-            when (rectNonEmpty r) $ do-              when (IM.notMember k new || IM.notMember k old) $ note churn r-              clipped <- clipDeltaToScrollViewport ctx k r-              when (rectArea clipped >= layoutSettleMinArea) $ note settled clipped-            rest-        )-        (pure ())-        (IM.mergeWithKey (\_ a b -> if a /= b then Just (rectUnion a b) else Nothing) id id old new)-      (,) <$> freeze settled <*> freeze churn-  where-    emptyGroup = RectGroup False False (Rect 0 0 0 0)-    freeze acc@(RectUnion a) = do-      bounds <- readRectUnion acc-      x0 <- readPrimArray a 0-      x1 <- readPrimArray a 2-      outside <- readPrimArray a 4-      let !present = x0 <= x1-      pure (RectGroup present (present && not (null panelRects) && outside == 0) bounds)--clipDeltaToScrollViewport :: Context -> Int -> Rect -> IO Rect-clipDeltaToScrollViewport ctx k r = do-  findNodeByKey ctx k >>= \case-    Nothing -> pure r-    Just idx -> do-      mClip <- getClipRect (ctxNodeArena ctx) idx-      pure $-        case mClip of-          Nothing -> r-          Just clip -> fromMaybe (Rect 0 0 0 0) (rectIntersect r clip)--clipRectToWindow :: Float -> Float -> Rect -> Rect-clipRectToWindow winW winH r =-  fromMaybe (Rect 0 0 0 0) (rectIntersect r (Rect 0 0 winW winH))--clipKeyRect :: Context -> Int -> Rect -> IO (Maybe Rect)-clipKeyRect ctx k r-  | k == 0 = pure (Just r)-  | otherwise = do-      clipped <- clipDeltaToScrollViewport ctx k r-      pure (if rectNonEmpty clipped then Just clipped else Nothing)---- | Rect of the nearest scroll-container ancestor of a keyed node, covering--- the content viewport and the scrollbar lane its chrome paints in. The walk--- stops at the first scroll node even when its rect is empty.-scrollAncestorRect :: Context -> Int -> IO (Maybe Rect)-scrollAncestorRect ctx k =-  findNodeByKey ctx k >>= maybe (pure Nothing) (fmap join . walkAncestors step na)-  where-    na = ctxNodeArena ctx-    step i = do-      nt <- getNodeType na i-      if isScrollNode nt-        then Just <$> getNonzeroRect na i-        else pure Nothing--scrollOffsetDamage :: Context -> RectUnion -> WidgetStore -> WidgetStore -> IO ()-scrollOffsetDamage ctx acc oldStore newStore =-  unless (IM.null changedKeys) $ do-    -- Every store key that holds a scroll node's offset, mapped to the first-    -- such node. Built once, only on frames where an offset changed.-    owners <- foldNodeRevM na addOwner IM.empty-    IM.foldrWithKey-      ( \k _ rest -> do-          forM_ (IM.lookup k owners) $ \idx -> do-            -- The scroll node's rect covers the content viewport AND the-            -- scrollbar lane: offset changes move the thumb, which paints-            -- outside the content clip.-            getNonzeroRect na idx >>= mapM_ (addRect acc)-            floatingAncestorRect ctx idx >>= mapM_ (addRect acc)-          rest-      )-      (pure ())-      changedKeys-  where-    na = ctxNodeArena ctx-    -- Floating-pane offsets live in storeFloat; wheel/keyboard offsets-    -- live under the SlotTextAreaScroll slot in storePoint. Both move the-    -- scroller's content and its chrome. New or removed float offsets only-    -- count when nonzero.-    changedKeys =-      changedKeysWith (fmap (const ()) . IM.filter (/= 0)) (storeFloat oldStore) (storeFloat newStore)-        `IM.union` changedKeysWith (fmap (const ())) (storePoint oldStore) (storePoint newStore)-    changedKeysWith :: Eq a => (IM.IntMap a -> IM.IntMap ()) -> IM.IntMap a -> IM.IntMap a -> IM.IntMap ()-    changedKeysWith oneSided old new =-      IM.mergeWithKey (\_ a b -> if a /= b then Just () else Nothing) oneSided oneSided old new-    addOwner m idx = do-      nt <- getNodeType na idx-      if not (isScrollNode nt)-        then pure m-        else do-          wid <- getWidgetId na idx-          let widKey = intKey wid-          pure $-            IM.insert widKey idx $-              IM.insert (slotKey SlotScrollCross widKey) idx $-                IM.insert (slotKey SlotTextAreaScroll widKey) idx m--floatingAncestorRect :: Context -> Int -> IO (Maybe Rect)-floatingAncestorRect ctx idx =-  walkAncestors check (ctxNodeArena ctx) idx-  where-    check i = do-      nt <- getNodeType (ctxNodeArena ctx) i-      if isFloatingNode nt-        then getNonzeroRect (ctxNodeArena ctx) i-        else pure Nothing
− lib/NanoUI/Debug.hs
@@ -1,338 +0,0 @@--- | Debug readout sampling shared by the backends: frame timing and skip--- counts, RTS statistics, draw counts, and the rows the debug windows show.-module NanoUI.Debug-  ( debugRefreshSec-  , blend-  , RtsStatsSnapshot (..)-  , readRtsSnapshot-  , CoreDebugSnapshot (..)-  , emptyCoreDebugSnapshot-  , DebugSampler (..)-  , DebugSamplerRef-  , newDebugSampler-  , noteDebugLoop-  , noteDebugSkip-  , isDebugActive-  , debugRefreshDue-  , noteDebugPresent-  , refreshDebugSnapshot-  , formatFpsRows-  , formatDrawRows-  , formatCoreRtsRows-  ) where--import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)-import Data.Text (Text)-import qualified Data.Text as T-import Data.Word (Word32, Word64)-import GHC.Clock (getMonotonicTime)-import GHC.Conc (getNumCapabilities, getNumProcessors)-import GHC.Stats (GCDetails (..), RTSStats (..), getRTSStats, getRTSStatsEnabled)-import Text.Printf (printf)--debugRefreshSec :: Double-debugRefreshSec = 0.25--blend :: Double -> Double -> Double-blend prev sample-  | prev <= 0 = sample-  | otherwise = prev * 0.85 + sample * 0.15--data RtsStatsSnapshot = RtsStatsSnapshot-  { rtsEnabled :: !Bool-  , rtsGcs :: !Word32-  , rtsMajorGcs :: !Word32-  , rtsAllocMb :: !Double-  , rtsLiveMb :: !Double-  , rtsMaxMemMb :: !Double-  , rtsCopiedMb :: !Double-  , rtsGcPct :: !Double-  , rtsLastGcGen :: !Word32-  , rtsLastGcMs :: !Double-  , rtsCaps :: !Int-  , rtsCpus :: !Int-  }-  deriving (Eq, Show)--emptyRtsSnapshot :: RtsStatsSnapshot-emptyRtsSnapshot =-  RtsStatsSnapshot-    { rtsEnabled = False-    , rtsGcs = 0-    , rtsMajorGcs = 0-    , rtsAllocMb = 0-    , rtsLiveMb = 0-    , rtsMaxMemMb = 0-    , rtsCopiedMb = 0-    , rtsGcPct = 0-    , rtsLastGcGen = 0-    , rtsLastGcMs = 0-    , rtsCaps = 0-    , rtsCpus = 0-    }--readRtsSnapshot :: IO RtsStatsSnapshot-readRtsSnapshot = do-  caps <- getNumCapabilities-  cpus <- getNumProcessors-  rtsOn <- getRTSStatsEnabled-  if not rtsOn-    then pure emptyRtsSnapshot {rtsCaps = caps, rtsCpus = cpus}-    else do-      st <- getRTSStats-      let tot = elapsed_ns st-          lastGc = gc st-          bytesMb n = fromIntegral n / (1024 * 1024)-      pure-        RtsStatsSnapshot-          { rtsEnabled = True-          , rtsGcs = gcs st-          , rtsMajorGcs = major_gcs st-          , rtsAllocMb = bytesMb (allocated_bytes st)-          , rtsLiveMb = bytesMb (gcdetails_live_bytes lastGc)-          , rtsMaxMemMb = bytesMb (max_mem_in_use_bytes st)-          , rtsCopiedMb = bytesMb (copied_bytes st)-          , rtsGcPct =-              if tot > 0 then 100 * fromIntegral (gc_elapsed_ns st) / fromIntegral tot else 0-          , rtsLastGcGen = gcdetails_gen lastGc-          , rtsLastGcMs = fromIntegral (gcdetails_elapsed_ns lastGc) / 1.0e6-          , rtsCaps = caps-          , rtsCpus = cpus-          }--data CoreDebugSnapshot = CoreDebugSnapshot-  { dbgPresentFps :: !Double-  , dbgLoopFps    :: !Double-  , dbgFrameMs    :: !Double-  , dbgUiMs       :: !Double-  , dbgRenderMs   :: !Double-  , dbgPresentMs  :: !Double-  , dbgPresents   :: !Word64-  , dbgSkips      :: !Word64-  , dbgVerts      :: !Int-  , dbgIndices    :: !Int-  , dbgCmds       :: !Int-  , dbgWinW       :: !Float-  , dbgWinH       :: !Float-  , dbgMouseX     :: !Float-  , dbgMouseY     :: !Float-  , dbgRts        :: !RtsStatsSnapshot-  }-  deriving (Eq, Show)--emptyCoreDebugSnapshot :: CoreDebugSnapshot-emptyCoreDebugSnapshot =-  CoreDebugSnapshot-    { dbgPresentFps = 0-    , dbgLoopFps = 0-    , dbgFrameMs = 0-    , dbgUiMs = 0-    , dbgRenderMs = 0-    , dbgPresentMs = 0-    , dbgPresents = 0-    , dbgSkips = 0-    , dbgVerts = 0-    , dbgIndices = 0-    , dbgCmds = 0-    , dbgWinW = 0-    , dbgWinH = 0-    , dbgMouseX = 0-    , dbgMouseY = 0-    , dbgRts = emptyRtsSnapshot-    }--data DebugSampler = DebugSampler-  { smPresentEma   :: {-# UNPACK #-} !Double-  , smLoopEma      :: {-# UNPACK #-} !Double-  , smLastPresentT :: {-# UNPACK #-} !Double-  , smLastDebugT   :: {-# UNPACK #-} !Double-  , smLastQueryT   :: {-# UNPACK #-} !Double-  , smPresents     :: {-# UNPACK #-} !Word64-  , smSkips        :: {-# UNPACK #-} !Word64-  , smUiMs         :: {-# UNPACK #-} !Double-  , smRenderMs     :: {-# UNPACK #-} !Double-  , smPresentMs    :: {-# UNPACK #-} !Double-  , smFrameMs      :: {-# UNPACK #-} !Double-  , smVerts        :: {-# UNPACK #-} !Int-  , smIndices      :: {-# UNPACK #-} !Int-  , smCmds         :: {-# UNPACK #-} !Int-  , smRatePresents :: {-# UNPACK #-} !Word64-  , smRateT        :: {-# UNPACK #-} !Double-  }--type DebugSamplerRef = IORef DebugSampler--newDebugSampler :: IO DebugSamplerRef-newDebugSampler = do-  now <- getMonotonicTime-  newIORef-    DebugSampler-      { smPresentEma = 0-      , smLoopEma = 0-      , smLastPresentT = now-      , smLastDebugT = 0-      , smLastQueryT = 0-      , smPresents = 0-      , smSkips = 0-      , smUiMs = 0-      , smRenderMs = 0-      , smPresentMs = 0-      , smFrameMs = 0-      , smVerts = 0-      , smIndices = 0-      , smCmds = 0-      , smRatePresents = 0-      , smRateT = now-      }--noteDebugLoop :: DebugSamplerRef -> Float -> IO ()-noteDebugLoop ref dt =-  atomicModifyIORef' ref $ \s ->-    let dtD = realToFrac dt :: Double-        fps = if dtD > 1e-4 && dtD < 0.25 then 1 / dtD else 0-        ema' =-          if fps > 0-            then blend (smLoopEma s) fps-            else smLoopEma s-     in (s {smLoopEma = ema'}, ())--noteDebugSkip :: DebugSamplerRef -> IO ()-noteDebugSkip ref =-  atomicModifyIORef' ref $ \s -> (s {smSkips = smSkips s + 1}, ())---- | Debug HUD cadence is driven by actual snapshot consumption: a snapshot--- query ('refreshDebugSnapshot') refreshes 'smLastQueryT', so the 4 Hz refresh--- loop only runs while a stats window is being built. An open window alone--- does not count as activity, or the event loop would wake every refresh--- period while any floating window is open.-isDebugActive :: DebugSamplerRef -> IO Bool-isDebugActive ref = do-  now <- getMonotonicTime-  s <- readIORef ref-  pure (now - smLastQueryT s < 1.0)---- | Whether the published snapshot is older than 'debugRefreshSec'.-debugRefreshDue :: DebugSamplerRef -> IO Bool-debugRefreshDue ref = do-  now <- getMonotonicTime-  s <- readIORef ref-  pure (snapshotDue now s)--snapshotDue :: Double -> DebugSampler -> Bool-snapshotDue now s = smLastDebugT s <= 0 || now - smLastDebugT s >= debugRefreshSec--noteDebugPresent :: DebugSamplerRef -> Double -> Double -> Double -> Double -> Int -> Int -> Int -> IO ()-noteDebugPresent ref uiMs renderMs presentMs frameMs verts indices cmds = do-  now <- getMonotonicTime-  atomicModifyIORef' ref $ \s ->-    let dt = now - smLastPresentT s-        instantFps =-          if dt > 1e-4 && dt < 0.25-            then 1 / dt-            else 0-        ema' =-          if instantFps > 0-            then blend (smPresentEma s) instantFps-            else smPresentEma s-     in ( s-             { smPresentEma = ema'-             , smLastPresentT = now-             , smPresents = smPresents s + 1-             , smUiMs = uiMs-             , smRenderMs = renderMs-             , smPresentMs = presentMs-             , smFrameMs = frameMs-             , smVerts = verts-             , smIndices = indices-             , smCmds = cmds-             }-        , ()-        )---- | The published snapshot, rebuilt at most every 'debugRefreshSec' and cached--- in between. A due query samples the core stats and hands them to @build@,--- which adds the backend's fields: window size and mouse position are left 0--- for it to fill. Every query marks the readout active ('isDebugActive').-refreshDebugSnapshot :: DebugSamplerRef -> IORef s -> (CoreDebugSnapshot -> IO s) -> IO s-refreshDebugSnapshot ref cache build = do-  now <- getMonotonicTime-  due <- atomicModifyIORef' ref $ \cur -> (cur {smLastQueryT = now}, snapshotDue now cur)-  if not due-    then readIORef cache-    else do-      rts <- readRtsSnapshot-      core <- atomicModifyIORef' ref $ \cur ->-        -- Actual presents per second since the previous refresh. Unlike the-        -- per-present EMA this stays truthful when presents are sparse (idle-        -- app: ~4/s with the HUD open, not the theoretical fps of one fast-        -- frame).-        let elapsed = now - smRateT cur-            rate-              | elapsed > 1e-3 = fromIntegral (smPresents cur - smRatePresents cur) / elapsed-              | otherwise = 0-            cur' = cur {smLastDebugT = now, smRatePresents = smPresents cur, smRateT = now}-         in (cur', (coreDebugSnapshot cur' rts) {dbgPresentFps = rate})-      snap <- build core-      writeIORef cache snap-      pure snap--coreDebugSnapshot :: DebugSampler -> RtsStatsSnapshot -> CoreDebugSnapshot-coreDebugSnapshot s rts =-  CoreDebugSnapshot-    { dbgPresentFps = smPresentEma s-    , dbgLoopFps = smLoopEma s-    , dbgFrameMs = smFrameMs s-    , dbgUiMs = smUiMs s-    , dbgRenderMs = smRenderMs s-    , dbgPresentMs = smPresentMs s-    , dbgPresents = smPresents s-    , dbgSkips = smSkips s-    , dbgVerts = smVerts s-    , dbgIndices = smIndices s-    , dbgCmds = smCmds s-    , dbgWinW = 0-    , dbgWinH = 0-    , dbgMouseX = 0-    , dbgMouseY = 0-    , dbgRts = rts-    }--formatFpsRows :: CoreDebugSnapshot -> [(Text, Text)]-formatFpsRows s =-  [ ("fps present", T.pack (printf "%6.1f" (dbgPresentFps s)))-  , ("fps loop", T.pack (printf "%6.1f" (dbgLoopFps s)))-  , ("frame ms", T.pack (printf "%6.2f" (dbgFrameMs s)))-  , ("ui ms", T.pack (printf "%6.2f" (dbgUiMs s)))-  , ("render ms", T.pack (printf "%6.2f" (dbgRenderMs s)))-  , ("present ms", T.pack (printf "%6.2f" (dbgPresentMs s)))-  , ("presents", T.pack (printf "%10d" (dbgPresents s)))-  , ("skips", T.pack (printf "%10d" (dbgSkips s)))-  ]--formatDrawRows :: CoreDebugSnapshot -> [(Text, Text)]-formatDrawRows s =-  [ ("vertices", T.pack (printf "%10d" (dbgVerts s)))-  , ("indices", T.pack (printf "%10d" (dbgIndices s)))-  , ("commands", T.pack (printf "%10d" (dbgCmds s)))-  ]--formatCoreRtsRows :: CoreDebugSnapshot -> [(Text, Text)]-formatCoreRtsRows core-  | not (rtsEnabled s) =-      [ ("rts", "stats off (need +RTS -T)")-      , ("haskell", T.pack (printf "%2d cap / %2d cpu" (rtsCaps s) (rtsCpus s)))-      ]-  | otherwise =-      [ ("haskell", T.pack (printf "%2d cap / %2d cpu" (rtsCaps s) (rtsCpus s)))-      , ("gc total", T.pack (printf "%10d" (rtsGcs s)))-      , ("gc major", T.pack (printf "%10d" (rtsMajorGcs s)))-      , ("last gen", T.pack (printf "%10d" (rtsLastGcGen s)))-      , ("last gc", T.pack (printf "%7.2f ms" (rtsLastGcMs s)))-      , ("heap live", T.pack (printf "%6.1f MiB" (rtsLiveMb s)))-      , ("heap alloc", T.pack (printf "%6.1f MiB" (rtsAllocMb s)))-      , ("copied", T.pack (printf "%6.1f MiB" (rtsCopiedMb s)))-      , ("rss max", T.pack (printf "%6.1f MiB" (rtsMaxMemMb s)))-      , ("gc time", T.pack (printf "%9.1f%%" (rtsGcPct s)))-      ]-  where-    s = dbgRts core
− lib/NanoUI/Draw.hs
@@ -1,55 +0,0 @@--- | Draw layer facade: data types, arena, geometry and text emitters.-module NanoUI.Draw-  ( Layer (..)-  , DrawCmd (..)-  , LayerSlice (..)-  , DrawData (..)-  , DrawArena (..)-  , DrawOp (..)-  , TextFont (..)-  , defaultTextFont-  , DrawingBuild-  , shiftDrawOp-  , newDrawArena-  , resetDrawArena-  , setDrawSnapScale-  , getDrawSnapScale-  , setDrawSquareGeometry-  , setDrawExternalText-  , beginLayer-  , currentLayer-  , currentClip-  , setClip-  , withClip-  , finishDraw-  , drawCmdCount-  , drawCmdNull-  , forDrawCmdsInLayer_-  , drawCmdElems-  , vertexSize-  , indexSize-  , backdropDimTextureId-  , glyphAtlasTextureId-  , pushRect-  , pushQuadGradient-  , pushImage-  , pushRoundedRect-  , pushRoundedRectRaw-  , pushRoundedStroke-  , pushRoundedStrokeRaw-  , pushCircle-  , pushCircleStroke-  , pushLine-  , pushStrokeAA-  , pushStroke-  , pushFilledTriangle-  , drawTextBox-  , pushText-  , pushTextStyled-  , emitDrawOps-  ) where--import NanoUI.Draw.Arena-import NanoUI.Draw.Shapes-import NanoUI.Draw.Text-import NanoUI.Draw.Types
− lib/NanoUI/Draw/Arena.hs
@@ -1,440 +0,0 @@-{-# LANGUAGE RecordWildCards #-}-{-# LANGUAGE StrictData #-}---- | Draw arena lifecycle, command batching and vertex reservation. The shape--- and text emitters reserve room here and poke vertices straight into the--- pinned buffers.-module NanoUI.Draw.Arena-  ( newDrawArena-  , resetDrawArena-  , setDrawSnapScale-  , getDrawSnapScale-  , setDrawSquareGeometry-  , setDrawExternalText-  , beginLayer-  , currentLayer-  , currentClip-  , setClip-  , withClip-  , setTexture-  , finishDraw-  , withVerts-  , withVertsRaw-  , withVertsReserve-  , pushQuad-  , snapRectOrigin-  , unpackColorF-  , pokeQuadIndices-  , loopIO-  , whitePixelU-  , whitePixelV-  ) where--import Control.Monad (unless, when)-import Data.Bits (shiftR, (.&.))-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Maybe (fromMaybe)-import Data.Primitive.PrimArray-  ( MutablePrimArray-  , PrimArray-  , newPrimArray-  , readPrimArray-  , setPrimArray-  , unsafeFreezePrimArray-  , writePrimArray-  , resizeMutablePrimArray-  )-import Data.Word (Word32, Word8)-import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtrBytes, withForeignPtr)-import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)-import Foreign.Marshal.Array (copyArray)-import Foreign.Ptr (Ptr)-import Foreign.Storable (pokeByteOff)-import GHC.Exts (RealWorld)-import NanoUI.Draw.Types-import NanoUI.SIMD (pokeQuadSIMD)-import NanoUI.Types (Color (..), Rect (..), onGrid, rectIntersect)--vertexCapacity :: Int-vertexCapacity = 4096--indexCapacity :: Int-indexCapacity = 8192--bufferPoolLimit :: Int-bufferPoolLimit = 4--cmdInitialCapacity :: Int-cmdInitialCapacity = 64--newDrawArena :: IO DrawArena-newDrawArena = do-  vFPtr <- mallocForeignPtrBytes (vertexCapacity * vertexSize)-  iFPtr <- mallocForeignPtrBytes (indexCapacity * indexSize)-  daVertexFPtr <- newIORef vFPtr-  daVertexPtr <- newIORef (unsafeForeignPtrToPtr vFPtr)-  daVertexCap <- newIORef vertexCapacity-  daVertexCount <- newIORef 0-  daVertexPool <- newIORef []-  daIndexFPtr <- newIORef iFPtr-  daIndexPtr <- newIORef (unsafeForeignPtrToPtr iFPtr)-  daIndexCap <- newIORef indexCapacity-  daIndexCount <- newIORef 0-  daIndexPool <- newIORef []-  daCmdStore <- newIORef =<< newPrimArray cmdInitialCapacity-  daCmdCount <- newIORef 0-  daCmdCapacity <- newIORef cmdInitialCapacity-  daCurrentLayer <- newIORef LayerContent-  daCurrentClip <- newPrimArray 4-  daCurrentTexture <- newIORef glyphAtlasTextureId-  daCmdStartIndex <- newIORef 0-  daSnapScale <- newIORef 0.0-  daSquareGeometry <- newIORef False-  daExternalText <- newIORef False-  let da = DrawArena {..}-  resetDrawArena da-  pure da--resetDrawArena :: DrawArena -> IO ()-resetDrawArena da = do-  writeIORef (daVertexCount da) 0-  writeIORef (daIndexCount da) 0-  writeIORef (daCmdCount da) 0-  writeIORef (daCurrentLayer da) LayerContent-  setClip da (Rect 0 0 1e9 1e9)-  writeIORef (daCurrentTexture da) glyphAtlasTextureId-  writeIORef (daCmdStartIndex da) 0---- | Device pixel scale used to snap primitive origins/endpoints to whole--- device pixels. A non-positive value disables snapping. The SDL backend keeps--- this in sync with the window pixel density. Headless contexts and the RGFW backend--- leave it disabled.-{-# INLINE setDrawSnapScale #-}-setDrawSnapScale :: DrawArena -> Float -> IO ()-setDrawSnapScale da s = writeIORef (daSnapScale da) (if s > 0 then s else 0)--{-# INLINE getDrawSnapScale #-}-getDrawSnapScale :: DrawArena -> IO Float-getDrawSnapScale da = readIORef (daSnapScale da)---- | Square geometry for hosts that draw flat, axis-aligned fills, such as the--- RGFW backend. Rounded rects, circles and their strokes lower to--- plain rects, and coverage-AA strips lower to solid quads with no--- transparent fringe vertices. Persists across 'resetDrawArena'.-{-# INLINE setDrawSquareGeometry #-}-setDrawSquareGeometry :: DrawArena -> Bool -> IO ()-setDrawSquareGeometry da = writeIORef (daSquareGeometry da)---- | External text for hosts that rasterize text themselves from the collected--- text spans. Text emitters push no quads, so fonts without a glyph atlas do--- not leave per-character advance boxes in the buffer. Persists across--- 'resetDrawArena'.-{-# INLINE setDrawExternalText #-}-setDrawExternalText :: DrawArena -> Bool -> IO ()-setDrawExternalText da = writeIORef (daExternalText da)--{-# NOINLINE poolTake #-}-poolTake :: BufferPool -> Int -> Int -> IO (ForeignPtr Word8)-poolTake pool bytes minCap = do-  entries <- readIORef pool-  case break (\(_, cap) -> cap >= minCap) entries of-    (before, (ptr, _) : after) -> do-      writeIORef pool (before ++ after)-      pure ptr-    _ -> mallocForeignPtrBytes bytes--{-# NOINLINE poolGive #-}-poolGive :: BufferPool -> ForeignPtr Word8 -> Int -> IO ()-poolGive pool ptr cap = do-  entries <- readIORef pool-  writeIORef pool (take bufferPoolLimit ((ptr, cap) : entries))--{-# NOINLINE growBuffer #-}-growBuffer ::-  Int ->-  IORef (ForeignPtr Word8) ->-  IORef (Ptr Word8) ->-  IORef Int ->-  BufferPool ->-  Int ->-  Int ->-  IO ()-growBuffer count fptrRef ptrRef capRef pool elemBytes needElems = do-  cap <- readIORef capRef-  let required = count + needElems-  when (required > cap) $ do-    oldFPtr <- readIORef fptrRef-    let newCap = max (cap * 2) required-    newFPtr <- poolTake pool (newCap * elemBytes) newCap-    withForeignPtr newFPtr $ \newP ->-      withForeignPtr oldFPtr $ \oldP ->-        copyArray newP oldP (count * elemBytes)-    poolGive pool oldFPtr cap-    writeIORef fptrRef newFPtr-    writeIORef ptrRef (unsafeForeignPtrToPtr newFPtr)-    writeIORef capRef newCap--ensureCapacity :: DrawArena -> Int -> Int -> IO ()-ensureCapacity da needVerts needIndices = do-  vCount <- readIORef (daVertexCount da)-  growBuffer vCount (daVertexFPtr da) (daVertexPtr da) (daVertexCap da) (daVertexPool da) vertexSize needVerts-  iCount <- readIORef (daIndexCount da)-  growBuffer iCount (daIndexFPtr da) (daIndexPtr da) (daIndexCap da) (daIndexPool da) indexSize needIndices--{-# INLINE ensureAndAlloc #-}-ensureAndAlloc :: DrawArena -> Int -> Int -> IO (Ptr Word8, Ptr Word8, Int, Int)-ensureAndAlloc da needV needI = do-  vCount <- readIORef (daVertexCount da)-  iCount <- readIORef (daIndexCount da)-  vCap <- readIORef (daVertexCap da)-  iCap <- readIORef (daIndexCap da)-  unless (vCount + needV <= vCap && iCount + needI <= iCap) $-    ensureCapacity da needV needI-  vp <- readIORef (daVertexPtr da)-  ip <- readIORef (daIndexPtr da)-  pure (vp, ip, vCount, iCount)--{-# NOINLINE growCmdStore #-}-growCmdStore :: DrawArena -> Int -> IO ()-growCmdStore da oldCap = do-  let newCap = oldCap * 2-  arr <- readIORef (daCmdStore da)-  newArr <- resizeMutablePrimArray arr newCap-  writeIORef (daCmdStore da) newArr-  writeIORef (daCmdCapacity da) newCap---- | Close the pending index run as a command. A run that continues the last--- command's state and index range extends that command instead. Only reached--- when the layer, clip or texture changes and from 'finishDraw', so it stays--- out of the emitters.-{-# NOINLINE flushCmd #-}-flushCmd :: DrawArena -> IO ()-flushCmd da = do-  start <- readIORef (daCmdStartIndex da)-  end <- readIORef (daIndexCount da)-  when (end > start) $ do-    Rect cx cy cw ch <- currentClip da-    tex <- readIORef (daCurrentTexture da)-    layer <- readIORef (daCurrentLayer da)-    n <- readIORef (daCmdCount da)-    arr <- readIORef (daCmdStore da)-    let off = fromIntegral start :: Word32-        cnt = fromIntegral (end - start) :: Word32-    extended <--      if n <= 0-        then pure False-        else do-          prev <- readPrimArray arr (n - 1)-          let same =-                cmdClipX prev == cx-                  && cmdClipY prev == cy-                  && cmdClipW prev == cw-                  && cmdClipH prev == ch-                  && cmdTextureId prev == tex-                  && cmdLayer prev == layer-                  && cmdIndexOffset prev + cmdIndexCount prev == off-          when same $-            writePrimArray arr (n - 1) prev {cmdIndexCount = cmdIndexCount prev + cnt}-          pure same-    unless extended $ do-      cap <- readIORef (daCmdCapacity da)-      when (n >= cap) $ growCmdStore da cap-      arr' <- readIORef (daCmdStore da)-      writePrimArray arr' n (DrawCmd cx cy cw ch tex off cnt layer)-      writeIORef (daCmdCount da) (n + 1)-    writeIORef (daCmdStartIndex da) end--{-# INLINE currentLayer #-}-currentLayer :: DrawArena -> IO Layer-currentLayer = readIORef . daCurrentLayer--beginLayer :: DrawArena -> Layer -> IO ()-beginLayer da layer = do-  cur <- readIORef (daCurrentLayer da)-  when (cur /= layer) $ do-    flushCmd da-    writeIORef (daCurrentLayer da) layer-    readIORef (daIndexCount da) >>= writeIORef (daCmdStartIndex da)--setClip :: DrawArena -> Rect -> IO ()-setClip da (Rect x y w h) = do-  flushCmd da-  let clip = daCurrentClip da-  writePrimArray clip 0 x-  writePrimArray clip 1 y-  writePrimArray clip 2 w-  writePrimArray clip 3 h--{-# INLINE currentClip #-}-currentClip :: DrawArena -> IO Rect-currentClip da = do-  let clip = daCurrentClip da-  x <- readPrimArray clip 0-  y <- readPrimArray clip 1-  w <- readPrimArray clip 2-  h <- readPrimArray clip 3-  pure $! Rect x y w h----- | Run @act@ clipped to the intersection with the current clip. Not--- exception-safe: the frame resets the clip before the next paint anyway.-{-# INLINE withClip #-}-withClip :: DrawArena -> Rect -> IO a -> IO a-withClip da rect act = do-  prev <- currentClip da-  setClip da (fromMaybe (Rect 0 0 0 0) (rectIntersect prev rect))-  act <* setClip da prev---- | Bind a texture. The unchanged case is the common one and stays inline; a--- real switch closes the pending command out of line.-{-# INLINE setTexture #-}-setTexture :: DrawArena -> Int -> IO ()-setTexture da tex = do-  cur <- readIORef (daCurrentTexture da)-  when (cur /= tex) $ switchTexture da tex--{-# NOINLINE switchTexture #-}-switchTexture :: DrawArena -> Int -> IO ()-switchTexture da tex = do-  flushCmd da-  writeIORef (daCurrentTexture da) tex--finishDraw :: DrawArena -> IO DrawData-finishDraw da = do-  flushCmd da-  vFPtr <- readIORef (daVertexFPtr da)-  iFPtr <- readIORef (daIndexFPtr da)-  vCount <- readIORef (daVertexCount da)-  iCount <- readIORef (daIndexCount da)-  count <- readIORef (daCmdCount da)-  arr <- readIORef (daCmdStore da)-  (cmds, slices) <- groupCmdsByLayer arr count-  pure-    DrawData-      { drawVertices = vFPtr-      , drawVertexCount = vCount-      , drawIndices = iFPtr-      , drawIndexCount = iCount-      , drawCommands = cmds-      , drawLayerSlices = slices-      }---- | Stable counting sort of the recorded commands by layer, plus one slice per--- layer into the sorted array.-groupCmdsByLayer :: MutablePrimArray RealWorld DrawCmd -> Int -> IO (PrimArray DrawCmd, PrimArray LayerSlice)-groupCmdsByLayer src n = do-  let layers = fromEnum (maxBound :: Layer) + 1-      layerAt i = fromEnum . cmdLayer <$> readPrimArray src i-  counts <- newPrimArray layers-  setPrimArray counts 0 layers (0 :: Int)-  loopIO 0 (n - 1) $ \i -> do-    l <- layerAt i-    readPrimArray counts l >>= writePrimArray counts l . (+ 1)-  cursors <- newPrimArray layers-  slices <- newPrimArray layers-  let offsets !l !off =-        when (l < layers) $ do-          c <- readPrimArray counts l-          writePrimArray cursors l off-          writePrimArray slices l (LayerSlice off c)-          offsets (l + 1) (off + c)-  offsets 0 0-  dest <- newPrimArray n-  loopIO 0 (n - 1) $ \i -> do-    cmd <- readPrimArray src i-    let l = fromEnum (cmdLayer cmd)-    j <- readPrimArray cursors l-    writePrimArray dest j cmd-    writePrimArray cursors l (j + 1)-  (,) <$> unsafeFreezePrimArray dest <*> unsafeFreezePrimArray slices--{-# INLINE unpackColorF #-}-unpackColorF :: Color -> (Float, Float, Float, Float)-unpackColorF (Color w) =-  let !inv255 = 1.0 / 255.0-      !r = fromIntegral ((w `shiftR` 24) .&. 0xFF) * inv255-      !g = fromIntegral ((w `shiftR` 16) .&. 0xFF) * inv255-      !b = fromIntegral ((w `shiftR` 8) .&. 0xFF) * inv255-      !a = fromIntegral (w .&. 0xFF) * inv255-   in (r, g, b, a)---- Allocate room for a primitive, hand the derived offsets to the body, and--- commit the vertex/index counts afterwards. INLINE: erased at -O.-{-# INLINE withVerts #-}-withVerts :: DrawArena -> Int -> Int -> (Ptr Word8 -> Ptr Word8 -> Int -> Int -> Word32 -> IO ()) -> IO ()-withVerts da needV needI f = do-  (vp, ip, base, baseIdx) <- ensureAndAlloc da needV needI-  let !vOff = base * vertexSize-      !iOff = baseIdx * indexSize-      !baseIdxWord = fromIntegral base :: Word32-  f vp ip vOff iOff baseIdxWord-  writeIORef (daVertexCount da) (base + needV)-  writeIORef (daIndexCount da) (baseIdx + needI)---- Like 'withVerts' but for primitives that index vertices relative to 'base'--- themselves instead of using one contiguous offset.-{-# INLINE withVertsRaw #-}-withVertsRaw :: DrawArena -> Int -> Int -> (Ptr Word8 -> Ptr Word8 -> Int -> Int -> IO ()) -> IO ()-withVertsRaw da needV needI f = do-  (vp, ip, base, baseIdx) <- ensureAndAlloc da needV needI-  f vp ip base baseIdx-  writeIORef (daVertexCount da) (base + needV)-  writeIORef (daIndexCount da) (baseIdx + needI)---- | Reserve room for up to @maxV@ vertices / @maxI@ indices, hand the body a--- commit action, then record only the counts the body reports. Batches many--- small quads (text glyphs) into one arena reservation instead of one--- @withVerts@ closure + capacity check per quad.-{-# INLINE withVertsReserve #-}-withVertsReserve ::-  DrawArena ->-  Int ->-  Int ->-  (Ptr Word8 -> Ptr Word8 -> Int -> Int -> (Int -> Int -> IO ()) -> IO ()) ->-  IO ()-withVertsReserve da maxV maxI f = do-  (vp, ip, base, baseIdx) <- ensureAndAlloc da maxV maxI-  f vp ip base baseIdx $ \nv ni -> do-    writeIORef (daVertexCount da) (base + nv)-    writeIORef (daIndexCount da) (baseIdx + ni)---- | Strict numeric loop. Replaces @forM_ [lo .. hi]@ on the rounded-geometry--- hot path, where the intermediate range list was a measurable allocation and--- prevented the body from fusing into a straight-line loop.-{-# INLINE loopIO #-}-loopIO :: Int -> Int -> (Int -> IO ()) -> IO ()-loopIO !lo !hi f = go lo-  where-    go !i-      | i > hi = pure ()-      | otherwise = f i >> go (i + 1)--{-# INLINE pushQuad #-}-pushQuad :: DrawArena -> Rect -> Float -> Float -> Float -> Float -> Color -> IO ()-pushQuad da (Rect x y w h) u0 v0 u1 v1 col = do-  let !(r, g, b, a) = unpackColorF col-  withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->-    pokeQuadSIMD vp vOff ip iOff x y w h u0 v0 u1 v1 r g b a baseIdxWord--{-# INLINE snapRectOrigin #-}-snapRectOrigin :: DrawArena -> Rect -> IO Rect-snapRectOrigin da (Rect x y w h) = do-  s <- readIORef (daSnapScale da)-  pure (Rect (onGrid s x) (onGrid s y) w h)--{-# INLINE pokeQuadIndices #-}-pokeQuadIndices :: Ptr Word8 -> Int -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()-pokeQuadIndices ip off a b c d = do-  pokeByteOff ip off a-  pokeByteOff ip (off + 4) b-  pokeByteOff ip (off + 8) c-  pokeByteOff ip (off + 12) a-  pokeByteOff ip (off + 16) c-  pokeByteOff ip (off + 20) d---- | Center of the 4x4 white pixel patch in the 1024x1024 font atlas.-whitePixelU :: Float-whitePixelU = 1.5 / 1024.0--whitePixelV :: Float-whitePixelV = 1.5 / 1024.0
− lib/NanoUI/Draw/Shapes.hs
@@ -1,474 +0,0 @@-{-# LANGUAGE StrictData #-}---- | Solid geometry emitters: rects, gradients, images, rounded fills and--- borders, coverage-AA strokes, lines and triangles.-module NanoUI.Draw.Shapes-  ( pushRect-  , pushQuadGradient-  , pushImage-  , pushRoundedRect-  , pushRoundedRectRaw-  , pushRoundedStroke-  , pushRoundedStrokeRaw-  , pushCircle-  , pushCircleStroke-  , pushLine-  , pushStrokeAA-  , pushStroke-  , pushFilledTriangle-  ) where--import Control.Monad (when)-import Data.IORef (readIORef)-import Data.Word (Word32, Word8)-import Foreign.Ptr (Ptr)-import Foreign.Storable (pokeByteOff)-import NanoUI.Draw.Arena-import NanoUI.Draw.Types (DrawArena (..), glyphAtlasTextureId, indexSize, vertexSize)-import NanoUI.SIMD-  ( concentricOffsetsSIMD-  , pokeQuadGradientSIMD-  , pokeQuadSIMD-  , pokeVertexSIMD-  )-import NanoUI.Types (Color (..), Rect (..), onGrid)--{-# INLINE pushRect #-}-pushRect :: DrawArena -> Rect -> Color -> IO ()-pushRect da rect col = do-  r <- snapRectOrigin da rect-  setTexture da glyphAtlasTextureId-  pushQuad da r whitePixelU whitePixelV whitePixelU whitePixelV col---- Quad with a color per corner. GPU interpolates across the two triangles.--- Corners: top-left, top-right, bottom-right, bottom-left.-pushQuadGradient :: DrawArena -> Rect -> Color -> Color -> Color -> Color -> IO ()-pushQuadGradient da (Rect x y w h) tl tr br bl-  | w <= 0 || h <= 0 = pure ()-  | otherwise = do-      s <- readIORef (daSnapScale da)-      setTexture da glyphAtlasTextureId-      let !px = onGrid s x-          !py = onGrid s y-          !c0 = unpackColorF tl-          !c1 = unpackColorF tr-          !c2 = unpackColorF br-          !c3 = unpackColorF bl-      withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->-        pokeQuadGradientSIMD vp vOff ip iOff px py w h whitePixelU whitePixelV c0 c1 c2 c3 baseIdxWord--{-# INLINE pushImage #-}-pushImage :: DrawArena -> Rect -> Int -> Float -> Float -> Float -> Float -> Color -> IO ()-pushImage da rect tex u0 v0 u1 v1 col-  | tex <= 0 = pushRect da rect col-  | otherwise = do-      r <- snapRectOrigin da rect-      setTexture da tex-      pushQuad da r u0 v0 u1 v1 col---- 4 segments per 90° arc. Lookup table in cornerCosSin has 5 points per quadrant.-cornerSegments :: Int-cornerSegments = 4---- Precomputed unit-circle cos/sin for rounded-rect corners (4 segments per 90° arc).-{-# INLINE cornerCosSin #-}-cornerCosSin :: Int -> Int -> (Float, Float)-cornerCosSin q seg =-  case q * 5 + seg of-    0 -> (-1.0, 0.0)-    1 -> (-0.9238795325, -0.3826834324)-    2 -> (-0.7071067812, -0.7071067812)-    3 -> (-0.3826834324, -0.9238795325)-    4 -> (0.0, -1.0)-    5 -> (0.0, -1.0)-    6 -> (0.3826834324, -0.9238795325)-    7 -> (0.7071067812, -0.7071067812)-    8 -> (0.9238795325, -0.3826834324)-    9 -> (1.0, 0.0)-    10 -> (1.0, 0.0)-    11 -> (0.9238795325, 0.3826834324)-    12 -> (0.7071067812, 0.7071067812)-    13 -> (0.3826834324, 0.9238795325)-    14 -> (0.0, 1.0)-    15 -> (0.0, 1.0)-    16 -> (-0.3826834324, 0.9238795325)-    17 -> (-0.7071067812, 0.7071067812)-    18 -> (-0.9238795325, 0.3826834324)-    19 -> (-1.0, 0.0)-    _ -> (0.0, 0.0)---- | Poke one coverage-AA strip into a reservation at vertex offset @vi@ and--- index offset @ii@ (both relative to @base@/@baseIdx@). Callers guarantee--- @(x0,y0) /= (x1,y1)@. Shared by straight strokes and the fused--- rounded-stroke paths, so a whole border shares one arena reservation.-{-# INLINE pokeStripAt #-}-pokeStripAt ::-  Ptr Word8 ->-  Ptr Word8 ->-  Int ->-  Int ->-  Int ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-pokeStripAt vp ip base baseIdx vi ii x0 y0 x1 y1 bw r g b a = do-  let !dx = x1 - x0-      !dy = y1 - y0-      !len = sqrt (dx * dx + dy * dy)-      !nx = (-dy) / len-      !ny = dx / len-      !half = bw * 0.5-      !core = max 0 (half - 0.5)-      !outer = half + 0.5-      pokeEnd !ev !ex !ey = do-        let ((p0x, p0y), (p1x, p1y), (p2x, p2y), (p3x, p3y)) =-              concentricOffsetsSIMD ex ey nx ny (-outer) (-core) core outer-            !vBase = (base + vi + ev) * vertexSize-        pokeVertexSIMD vp vBase p0x p0y r g b 0 whitePixelU whitePixelV-        pokeVertexSIMD vp (vBase + 32) p1x p1y r g b a whitePixelU whitePixelV-        pokeVertexSIMD vp (vBase + 64) p2x p2y r g b a whitePixelU whitePixelV-        pokeVertexSIMD vp (vBase + 96) p3x p3y r g b 0 whitePixelU whitePixelV-  pokeEnd 0 x0 y0-  pokeEnd 4 x1 y1-  let !va = fromIntegral (base + vi) :: Word32-      !vb = va + 4-  pokeQuadIndices ip ((baseIdx + ii) * indexSize) va (va + 1) (vb + 1) vb-  pokeQuadIndices ip ((baseIdx + ii + 6) * indexSize) (va + 1) (va + 2) (vb + 2) (vb + 1)-  pokeQuadIndices ip ((baseIdx + ii + 12) * indexSize) (va + 2) (va + 3) (vb + 3) (vb + 2)--{-# INLINE pushRoundedRect #-}-pushRoundedRect :: DrawArena -> Rect -> Float -> Color -> IO ()-pushRoundedRect da (Rect x y w h) radius col = do-  s <- readIORef (daSnapScale da)-  pushRoundedRectRaw da (Rect (onGrid s x) (onGrid s y) w h) radius col---- | Unsnapped variant used when the rect is already anchored to the snapped--- device pixel grid, e.g. a mark that must stay concentric with a border that--- has already snapped its own origin. Re-snapping here would round the--- off-origin inset (delta = (box - mark)/2) away, and since absolute snapping--- rides on the fractional part of the widget position the mark would drift--- off-center by up to a pixel as the widget scrolls.--- Keep the fused emitter out of its many paint callers: inlining it duplicates--- the corner loops and increases instruction-cache pressure substantially.-{-# NOINLINE pushRoundedRectRaw #-}-pushRoundedRectRaw :: DrawArena -> Rect -> Float -> Color -> IO ()-pushRoundedRectRaw da (Rect x y w h) radius col-  | w <= 0 || h <= 0 = pure ()-  | radius <= 0.5 = pushRect da (Rect x y w h) col-  | otherwise = do-      square <- readIORef (daSquareGeometry da)-      let !rad = min radius (min (w * 0.5) (h * 0.5))-      if square || rad <= 0.5-        then pushRect da (Rect x y w h) col-        else do-          setTexture da glyphAtlasTextureId-          let !segs = cornerSegments-              !ring = segs + 1-              !midW = max 0 (w - 2 * rad)-              !midH = max 0 (h - 2 * rad)-              !hasCenter = midW > 0 && midH > 0-              !hasTB = midW > 0-              !hasLR = midH > 0-              !quadCount =-                (if hasCenter then 1 else 0)-                  + (if hasTB then 2 else 0)-                  + (if hasLR then 2 else 0)-              !cornerV = 1 + 2 * ring-              !cornerI = segs * 9-              !needV = quadCount * 4 + 4 * cornerV-              !needI = quadCount * 6 + 4 * cornerI-          withVertsRaw da needV needI $ \vp ip base baseIdx -> do-            let !(cr, cg, cb, ca) = unpackColorF col-                !u = whitePixelU-                !v = whitePixelV-                pokeQuadAt !vi !ii !qx !qy !qw !qh =-                  pokeQuadSIMD-                    vp-                    ((base + vi) * vertexSize)-                    ip-                    ((baseIdx + ii) * indexSize)-                    qx-                    qy-                    qw-                    qh-                    u-                    v-                    u-                    v-                    cr-                    cg-                    cb-                    ca-                    (fromIntegral (base + vi))-                pokeCorner !vi !ii !ccx !ccy !q = do-                  let !vBase = (base + vi) * vertexSize-                      !centerIdx = fromIntegral (base + vi) :: Word32-                      !inRad = max 0 (rad - 1.0)-                  pokeVertexSIMD vp vBase ccx ccy cr cg cb ca u v-                  loopIO 0 segs $ \i -> do-                    let !(ct, st) = cornerCosSin q i-                        !rimI = base + vi + 1 + i-                        !outI = base + vi + 1 + ring + i-                    pokeVertexSIMD vp (rimI * vertexSize) (ccx + inRad * ct) (ccy + inRad * st) cr cg cb ca u v-                    pokeVertexSIMD vp (outI * vertexSize) (ccx + rad * ct) (ccy + rad * st) cr cg cb 0 u v-                    when (i > 0) $ do-                      let !k = i - 1-                          !rim0 = fromIntegral (base + vi + i) :: Word32-                          !rim1 = fromIntegral (base + vi + 1 + i) :: Word32-                          !out0 = fromIntegral (base + vi + 1 + ring + k) :: Word32-                          !out1 = fromIntegral (base + vi + 1 + ring + i) :: Word32-                          !fillOff = (baseIdx + ii + k * 3) * indexSize-                          !fringeOff = (baseIdx + ii + segs * 3 + k * 6) * indexSize-                      pokeByteOff ip fillOff centerIdx-                      pokeByteOff ip (fillOff + 4) rim0-                      pokeByteOff ip (fillOff + 8) rim1-                      pokeQuadIndices ip fringeOff rim0 out0 out1 rim1-                !vi1 = if hasCenter then 4 else 0-                !ii1 = if hasCenter then 6 else 0-                !vi2 = vi1 + (if hasTB then 8 else 0)-                !ii2 = ii1 + (if hasTB then 12 else 0)-                !vi3 = vi2 + (if hasLR then 8 else 0)-                !ii3 = ii2 + (if hasLR then 12 else 0)-            when hasCenter $ pokeQuadAt 0 0 (x + rad) (y + rad) midW midH-            when hasTB $ do-              pokeQuadAt vi1 ii1 (x + rad) y midW rad-              pokeQuadAt (vi1 + 4) (ii1 + 6) (x + rad) (y + h - rad) midW rad-            when hasLR $ do-              pokeQuadAt vi2 ii2 x (y + rad) rad midH-              pokeQuadAt (vi2 + 4) (ii2 + 6) (x + w - rad) (y + rad) rad midH-            pokeCorner vi3 ii3 (x + rad) (y + rad) 0-            pokeCorner (vi3 + cornerV) (ii3 + cornerI) (x + w - rad) (y + rad) 1-            pokeCorner (vi3 + 2 * cornerV) (ii3 + 2 * cornerI) (x + w - rad) (y + h - rad) 2-            pokeCorner (vi3 + 3 * cornerV) (ii3 + 3 * cornerI) (x + rad) (y + h - rad) 3---- | A filled circle. The centre snaps to the device pixel grid, not the--- bounding box's origin: snapping the origin rounds @cx - radius@, so two--- circles sharing a centre but not a radius would land up to a pixel apart.-{-# INLINE pushCircle #-}-pushCircle :: DrawArena -> Float -> Float -> Float -> Color -> IO ()-pushCircle da cx cy radius col = do-  s <- readIORef (daSnapScale da)-  pushRoundedRectRaw da (circleBox (onGrid s cx) (onGrid s cy) radius) radius col---- | A circle's outline, its centre snapped as 'pushCircle' snaps it.-{-# INLINE pushCircleStroke #-}-pushCircleStroke :: DrawArena -> Float -> Float -> Float -> Float -> Color -> IO ()-pushCircleStroke da cx cy radius bw col = do-  s <- readIORef (daSnapScale da)-  pushRoundedStrokeRaw da (circleBox (onGrid s cx) (onGrid s cy) radius) radius bw col--circleBox :: Float -> Float -> Float -> Rect-circleBox cx cy radius = Rect (cx - radius) (cy - radius) (2 * radius) (2 * radius)--{-# INLINE pushRoundedStroke #-}-pushRoundedStroke :: DrawArena -> Rect -> Float -> Float -> Color -> IO ()-pushRoundedStroke da (Rect x y w h) radius bw col = do-  s <- readIORef (daSnapScale da)-  pushRoundedStrokeRaw da (Rect (onGrid s x) (onGrid s y) w h) radius bw col---- | 'pushRoundedStroke' without snapping the origin, for a rect already--- anchored to the grid; see 'pushRoundedRectRaw'.-{-# NOINLINE pushRoundedStrokeRaw #-}-pushRoundedStrokeRaw :: DrawArena -> Rect -> Float -> Float -> Color -> IO ()-pushRoundedStrokeRaw da (Rect px py w h) radius bw col-  | w <= 0 || h <= 0 || bw <= 0 = pure ()-  | otherwise = do-      setTexture da glyphAtlasTextureId-      square <- readIORef (daSquareGeometry da)-      let !rad = min (max 0 radius) (min (w * 0.5) (h * 0.5))-          !ibw = min bw (min (w * 0.5) (h * 0.5))-      if square-        then pushSquareStroke da px py w h ibw col-        else if rad <= 0.5-        then do-          let !t = ibw-              !ox = px + t / 2-              !oy = py + t / 2-              !ow = max 0 (w - t)-              !oh = max 0 (h - t)-              !doTB = ow >= 0.001-              !doLR = oh >= 0.001-              !stripCount = (if doTB then 2 else 0) + (if doLR then 2 else 0)-          withVertsRaw da (stripCount * 8) (stripCount * 18) $ \vp ip base baseIdx -> do-            let !(r, g, b, a) = unpackColorF col-                !viLR = if doTB then 16 else 0-                !iiLR = if doTB then 36 else 0-            when doTB $ do-              pokeStripAt vp ip base baseIdx 0 0 ox oy (ox + ow) oy t r g b a-              pokeStripAt vp ip base baseIdx 8 18 ox (oy + oh) (ox + ow) (oy + oh) t r g b a-            when doLR $ do-              pokeStripAt vp ip base baseIdx viLR iiLR ox oy ox (oy + oh) t r g b a-              pokeStripAt vp ip base baseIdx (viLR + 8) (iiLR + 18) (ox + ow) oy (ox + ow) (oy + oh) t r g b a-        else do-          let !n = cornerSegments-          let !midW = max 0 (w - 2 * rad)-              !midH = max 0 (h - 2 * rad)-              !topY = py + ibw / 2-              !botY = py + h - ibw / 2-              !leftX = px + ibw / 2-              !rightX = px + w - ibw / 2-              !cr = max 0.25 (rad - ibw / 2)-              !doTB = midW >= 0.001-              !doLR = midH >= 0.001-              !stripCount = (if doTB then 2 else 0) + (if doLR then 2 else 0)-              -- Hairlines have coincident inner/outer core rings. Share that-              -- ring and omit its zero-area triangles instead of submitting-              -- a fourth vertex and a third quad for every arc segment.-              !core = max 0 (ibw * 0.5 - 0.5)-              !hasCore = core > 0-              !arcStride = if hasCore then 4 else 3-              !arcIndices = if hasCore then 18 else 12-              !arcV = (n + 1) * arcStride-              !arcI = n * arcIndices-              !needV = stripCount * 8 + 4 * arcV-              !needI = stripCount * 18 + 4 * arcI-          withVertsRaw da needV needI $ \vp ip base baseIdx -> do-            let !(r, g, b, a) = unpackColorF col-                pokeArc !vi !ii !ccx !ccy !q = do-                  let !inner = max 0 (cr - core)-                      !outerR = cr + core-                      !innerAA = max 0 (inner - 1.0)-                      !outerAA = outerR + 1.0-                  loopIO 0 n $ \i -> do-                    let !(ct, st) = cornerCosSin q i-                        !v0 = base + vi + i * arcStride-                        !vBase = v0 * vertexSize-                        ((p0x, p0y), (p1x, p1y), (p2x, p2y), (p3x, p3y)) =-                          concentricOffsetsSIMD ccx ccy ct st innerAA inner outerR outerAA-                    pokeVertexSIMD vp vBase p0x p0y r g b 0 whitePixelU whitePixelV-                    pokeVertexSIMD vp (vBase + 32) p1x p1y r g b a whitePixelU whitePixelV-                    when hasCore $-                      pokeVertexSIMD vp (vBase + 64) p2x p2y r g b a whitePixelU whitePixelV-                    pokeVertexSIMD vp (vBase + (arcStride - 1) * vertexSize) p3x p3y r g b 0 whitePixelU whitePixelV-                  loopIO 0 (n - 1) $ \i -> do-                    let !va = fromIntegral (base + vi + i * arcStride) :: Word32-                        !vb = va + fromIntegral arcStride-                        !iOff = (baseIdx + ii + i * arcIndices) * indexSize-                    pokeQuadIndices ip iOff va (va + 1) (vb + 1) vb-                    pokeQuadIndices ip (iOff + 24) (va + 1) (va + 2) (vb + 2) (vb + 1)-                    when hasCore $-                      pokeQuadIndices ip (iOff + 48) (va + 2) (va + 3) (vb + 3) (vb + 2)-                !viLR = if doTB then 16 else 0-                !iiLR = if doTB then 36 else 0-                !viC = stripCount * 8-                !iiC = stripCount * 18-            when doTB $ do-              pokeStripAt vp ip base baseIdx 0 0 (px + rad) topY (px + rad + midW) topY ibw r g b a-              pokeStripAt vp ip base baseIdx 8 18 (px + rad) botY (px + rad + midW) botY ibw r g b a-            when doLR $ do-              pokeStripAt vp ip base baseIdx viLR iiLR leftX (py + rad) leftX (py + rad + midH) ibw r g b a-              pokeStripAt vp ip base baseIdx (viLR + 8) (iiLR + 18) rightX (py + rad) rightX (py + rad + midH) ibw r g b a-            pokeArc viC iiC (px + rad) (py + rad) 0-            pokeArc (viC + arcV) (iiC + arcI) (px + w - rad) (py + rad) 1-            pokeArc (viC + 2 * arcV) (iiC + 2 * arcI) (px + w - rad) (py + h - rad) 2-            pokeArc (viC + 3 * arcV) (iiC + 3 * arcI) (px + rad) (py + h - rad) 3---- | Border of four flat rects inside @(x, y, w, h)@, @t@ thick. The origin is--- already snapped by the caller; the texture is already selected.-pushSquareStroke :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()-pushSquareStroke da x y w h t col = do-  let edge qx qy qw qh =-        when (qw > 0 && qh > 0) $-          pushQuad da (Rect qx qy qw qh) whitePixelU whitePixelV whitePixelU whitePixelV col-      !innerH = h - 2 * t-  edge x y w t-  edge x (y + h - t) w t-  edge x (y + t) t innerH-  edge (x + w - t) (y + t) t innerH---- | A line @thickness@ wide with round caps: a coverage-AA strip with a--- round cap on each end. An axis-aligned line is a plain rect spanning its--- caps.-{-# INLINE pushLine #-}-pushLine :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()-pushLine da x1 y1 x2 y2 thickness col = do-  square <- readIORef (daSquareGeometry da)-  let !r = thickness / 2-      cap cx cy = pushCircle da cx cy r col-  if square-    then pushStroke da x1 y1 x2 y2 thickness col-    else-      if x1 == x2 || y1 == y2-        then pushRect da (Rect (min x1 x2 - r) (min y1 y2 - r) (abs (x2 - x1) + thickness) (abs (y2 - y1) + thickness)) col-        else when (thickness > 0) $ do-          pushStrokeAA da x1 y1 x2 y2 thickness col-          cap x1 y1-          cap x2 y2---- Coverage-AA strip for a straight segment. Same weight as pushCornerArcStroke,--- without round caps that blob at rounded-rect corners.-{-# INLINE pushStrokeAA #-}-pushStrokeAA :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()-pushStrokeAA da x0 y0 x1 y1 bw col-  | bw <= 0 = pure ()-  | otherwise = do-      s <- readIORef (daSnapScale da)-      pushStrokeAARaw da (onGrid s x0) (onGrid s y0) (onGrid s x1) (onGrid s y1) bw col---- | Unsnapped variant: the caller already snapped the endpoints.-pushStrokeAARaw :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()-pushStrokeAARaw da x0 y0 x1 y1 bw col = do-  square <- readIORef (daSquareGeometry da)-  if square-    then pushStroke da x0 y0 x1 y1 bw col-    else case strokeAxes x0 y0 x1 y1 of-      Nothing -> pure ()-      Just _ -> do-        setTexture da glyphAtlasTextureId-        let !(r, g, b, a) = unpackColorF col-        withVertsRaw da 8 18 $ \vp ip base baseIdx ->-          pokeStripAt vp ip base baseIdx 0 0 x0 y0 x1 y1 bw r g b a--strokeAxes :: Float -> Float -> Float -> Float -> Maybe (Float, Float, Float)-strokeAxes x0 y0 x1 y1 =-  let dx = x1 - x0-      dy = y1 - y0-      len = sqrt (dx * dx + dy * dy)-   in if len < 0.001 then Nothing else Just (dx, dy, len)---- One quad per segment. Plots and diagrams use this; pushLine adds round caps.-pushStroke :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()-pushStroke da x1 y1 x2 y2 thickness col-  | thickness <= 0 = pure ()-  | otherwise = do-      s <- readIORef (daSnapScale da)-      let !px1 = onGrid s x1-          !py1 = onGrid s y1-          !px2 = onGrid s x2-          !py2 = onGrid s y2-      case strokeAxes px1 py1 px2 py2 of-        Nothing -> pure ()-        Just (dx, dy, len) -> do-          setTexture da glyphAtlasTextureId-          let !invLen = (thickness * 0.5) / len-              !hx = (-dy) * invLen-              !hy = dx * invLen-          withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord -> do-            let !(r, g, b, a) = unpackColorF col-                poke off px py = pokeVertexSIMD vp off px py r g b a whitePixelU whitePixelV-            poke vOff (px1 + hx) (py1 + hy)-            poke (vOff + 32) (px2 + hx) (py2 + hy)-            poke (vOff + 64) (px2 - hx) (py2 - hy)-            poke (vOff + 96) (px1 - hx) (py1 - hy)-            pokeQuadIndices ip iOff baseIdxWord (baseIdxWord + 1) (baseIdxWord + 2) (baseIdxWord + 3)--pushFilledTriangle :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()-pushFilledTriangle da x0 y0 x1 y1 x2 y2 col = do-  s <- readIORef (daSnapScale da)-  setTexture da glyphAtlasTextureId-  let !(r, g, b, a) = unpackColorF col-  withVerts da 3 3 $ \vp ip vOff iOff baseIdxWord -> do-    pokeVertexSIMD vp vOff (onGrid s x0) (onGrid s y0) r g b a whitePixelU whitePixelV-    pokeVertexSIMD vp (vOff + 32) (onGrid s x1) (onGrid s y1) r g b a whitePixelU whitePixelV-    pokeVertexSIMD vp (vOff + 64) (onGrid s x2) (onGrid s y2) r g b a whitePixelU whitePixelV-    pokeByteOff ip iOff baseIdxWord-    pokeByteOff ip (iOff + 4) (baseIdxWord + 1)-    pokeByteOff ip (iOff + 8) (baseIdxWord + 2)
− lib/NanoUI/Draw/Text.hs
@@ -1,258 +0,0 @@-{-# LANGUAGE StrictData #-}---- | Text emitters (plain and synthetic-styled) and the 'DrawOp' interpreter.-module NanoUI.Draw.Text-  ( drawTextBox-  , pushText-  , pushTextStyled-  , emitDrawOps-  ) where--import Control.Monad (forM_, unless, when)-import Data.IORef (readIORef)-import qualified Data.Text as T-import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray)-import Data.Primitive.PrimArray (indexPrimArray, sizeofPrimArray)-import Data.Word (Word32, Word8)-import Foreign.Ptr (Ptr)-import NanoUI.Draw.Arena-import NanoUI.Draw.Shapes-import NanoUI.Draw.Types (DrawArena (..), DrawOp (..), TextFont (..), glyphAtlasTextureId, indexSize, vertexSize)-import NanoUI.Font-  ( FontMetrics (..)-  , GlyphQuad (..)-  , ShapedGlyphs (..)-  , drawGlyph-  , drawShaped-  , kernedAdvance-  , lineWidth-  , prepareFontMetrics-  )-import NanoUI.SIMD (pokeQuadSIMD, pokeVertexSIMD)-import NanoUI.Style (FontStyle (..), FontWeight (..), TextDecoration (..))-import NanoUI.Types (Color (..), Rect (..), onGrid)---- | Pixel box for a 'DrawText' using host advances. diagrams text has no--- envelope, so plot sizing uses this instead of `fontSizeL`.-drawTextBox :: FontMetrics -> Float -> Float -> Float -> Float -> T.Text -> Rect-drawTextBox fm x y ax ay t =-  let tw = lineWidth fm t-      th = fmLineHeight fm-      px = x - tw * max 0 ax-      py =-        if ay < 0-          then y - fmAscent fm-          else y - th * (1 - ay)-   in Rect px py tw th--{-# INLINE pushText #-}-pushText :: DrawArena -> FontMetrics -> Float -> Float -> T.Text -> Color -> IO ()-pushText _da _fm _x _y txt _col | T.null txt = pure ()-pushText da fm x y txt col = do-  prepared <- prepareFontMetrics fm txt-  external <- readIORef (daExternalText da)-  unless external $ pushPreparedTextQuads da prepared x y txt col--{-# INLINE pushTextStyled #-}-pushTextStyled ::-  DrawArena ->-  FontMetrics ->-  FontWeight ->-  FontStyle ->-  TextDecoration ->-  Float ->-  Float ->-  T.Text ->-  Color ->-  IO ()-pushTextStyled da fm weight fstyle deco x y txt col = do-  prepared <- prepareFontMetrics fm txt-  external <- readIORef (daExternalText da)-  unless external $ pushPreparedTextStyledQuads da prepared weight fstyle deco x y txt col---- Snapping the pen to the device pixel grid keeps every glyph quad on a whole--- pixel. Advances, bearings, and ink sizes are all integer pixel counts divided--- by the snap scale, so snapping the origin alone aligns the whole line:--- otherwise fractional layout positions leave glyphs straddling pixel--- boundaries, which makes nearest-sampled atlas text blurry and jitter as--- scroll position changes.-pushPreparedTextQuads :: DrawArena -> FontMetrics -> Float -> Float -> T.Text -> Color -> IO ()-pushPreparedTextQuads da fm x y txt col = do-  let !px = onGrid (fmSnapScale fm) x-      !py = onGrid (fmSnapScale fm) y-  -- The host's shaped glyphs when it shapes, otherwise glyphs by character.-  drawShaped fm txt >>= \case-    Just glyphs -> pushShapedQuads da fm 0 px py glyphs col-    Nothing -> pushGlyphQuads da fm 0 px py txt col---- | A shaped line's glyph quads from pen @(px, py)@, sheared by @slant@--- around the baseline like 'pushGlyphQuads'.-pushShapedQuads :: DrawArena -> FontMetrics -> Float -> Float -> Float -> ShapedGlyphs -> Color -> IO ()-pushShapedQuads da fm slant px py (ShapedGlyphs quads) col = do-  let !count = sizeofPrimArray quads `div` 8-  when (count > 0) $ do-    setTexture da glyphAtlasTextureId-    withVertsReserve da (count * 4) (count * 6) $ \vp ip base baseIdx commit -> do-      let !(r, g, b, a) = unpackColorF col-          !baselineY = py + fmAscent fm-          at k = indexPrimArray quads k-          go !q-            | q >= count = pure ()-            | otherwise = do-                let !o = q * 8-                    !gx = px + at o-                    !gy = py + at (o + 1)-                    !gw = at (o + 2)-                    !gh = at (o + 3)-                    !u0 = at (o + 4)-                    !v0 = at (o + 5)-                    !u1 = at (o + 6)-                    !v1 = at (o + 7)-                pokeGlyphQuad vp ip base baseIdx slant baselineY r g b a q gx gy gw gh u0 v0 u1 v1-                go (q + 1)-      go 0-      commit (count * 4) (count * 6)---- | Glyph quad @q@ of a text reservation whose vertices start at @base@ and--- indices at @baseIdx@. A non-zero @slant@ shears the quad around--- @baselineY@. INLINE: it runs per glyph and takes more arguments than GHC--- unboxes for a call.-{-# INLINE pokeGlyphQuad #-}-pokeGlyphQuad ::-  Ptr Word8 ->-  Ptr Word8 ->-  Int ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-pokeGlyphQuad vp ip base baseIdx slant baselineY r g b a q gx gy gw gh u0 v0 u1 v1 = do-  let !vb = (base + q * 4) * vertexSize-      !ib = (baseIdx + q * 6) * indexSize-      !i0 = fromIntegral (base + q * 4) :: Word32-  if slant == 0-    then pokeQuadSIMD vp vb ip ib gx gy gw gh u0 v0 u1 v1 r g b a i0-    else do-      let !gy1 = gy + gh-          !topDx = slant * (baselineY - gy)-          !botDx = slant * (baselineY - gy1)-      pokeVertexSIMD vp vb (gx + topDx) gy r g b a u0 v0-      pokeVertexSIMD vp (vb + 32) (gx + gw + topDx) gy r g b a u1 v0-      pokeVertexSIMD vp (vb + 64) (gx + gw + botDx) gy1 r g b a u1 v1-      pokeVertexSIMD vp (vb + 96) (gx + botDx) gy1 r g b a u0 v1-      pokeQuadIndices ip ib i0 (i0 + 1) (i0 + 2) (i0 + 3)---- | Glyph quads for one line from pen @(px, py)@, used as given: synthetic bold--- relies on its sub-pixel pass offsets. Every quad shares one arena--- reservation. A non-zero @slant@ shears glyphs around the shared baseline for--- synthetic oblique, so stems stay parallel and descenders lean left. A glyph--- the font lacks draws an upright advance box on the device grid.-pushGlyphQuads :: DrawArena -> FontMetrics -> Float -> Float -> Float -> T.Text -> Color -> IO ()-pushGlyphQuads da fm slant px py txt col = do-  let !cap = T.length txt-  when (cap > 0) $ do-    scale <- readIORef (daSnapScale da)-    setTexture da glyphAtlasTextureId-    withVertsReserve da (cap * 4) (cap * 6) $ \vp ip base baseIdx commit -> do-      let !(r, g, b, a) = unpackColorF col-          !baselineY = py + fmAscent fm-          walk !q !ox !prev !t =-            case T.uncons t of-              Nothing -> pure q-              Just (c, rest) -> do-                let !adv = kernedAdvance fm prev c-                    next !q' = walk q' (ox + adv) (Just c) rest-                drawGlyph fm c >>= \case-                  Nothing-                    | adv > 0 && c /= ' ' -> do-                        pokeGlyphQuad vp ip base baseIdx 0 baselineY r g b a q (onGrid scale ox) (onGrid scale py) adv (fmLineHeight fm) whitePixelU whitePixelV whitePixelU whitePixelV-                        next (q + 1)-                    | otherwise -> next q-                  Just gq -> do-                    pokeGlyphQuad vp ip base baseIdx slant baselineY r g b a q (ox + gqX gq) (py + gqY gq) (gqW gq) (gqH gq) (gqU0 gq) (gqV0 gq) (gqU1 gq) (gqV1 gq)-                    next (q + 1)-      !k <- walk 0 px Nothing txt-      commit (k * 4) (k * 6)---- | Synthetic weight, slant and decoration over the plain text path. Upright--- normal weight keeps the run path; every other pass walks glyphs.-pushPreparedTextStyledQuads :: DrawArena -> FontMetrics -> FontWeight -> FontStyle -> TextDecoration -> Float -> Float -> T.Text -> Color -> IO ()-pushPreparedTextStyledQuads da fm weight fstyle deco x y txt col-  | weight == WeightNormal && fstyle == FontStyleNormal && deco == DecorationNone =-      pushPreparedTextQuads da fm x y txt col-  | otherwise = do-      let !px = onGrid (fmSnapScale fm) x-          !py = onGrid (fmSnapScale fm) y-          !lh = fmLineHeight fm-          !bOff = max 1.0 (0.05 * lh)-          !slant = if fstyle == FontStyleNormal then 0 else 0.18-          -- Pen offsets, in bold steps, of the passes that synthesize a weight.-          passes = case weight of-            WeightNormal -> [0]-            WeightLight -> [0]-            WeightMedium -> [0, 0.5]-            WeightSemiBold -> [0, 0.75]-            WeightBold -> [0, 1]-            WeightExtraBold -> [0, 1, 1.5]-            WeightBlack -> [0, 1, 1.5, 2]-      if slant == 0 && weight == WeightNormal-        then pushPreparedTextQuads da fm px py txt col-        else do-          shaped <- drawShaped fm txt-          forM_ passes $ \k -> case shaped of-            Just glyphs -> pushShapedQuads da fm slant (px + k * bOff) py glyphs col-            Nothing -> pushGlyphQuads da fm slant (px + k * bOff) py txt col-      when (deco /= DecorationNone) $ do-        let !textW = lineWidth fm txt-            !thick = max 1.0 (0.06 * lh)-            underline = pushRect da (Rect px (py + fmAscent fm + max 1.0 (0.1 * lh)) textW thick) col-            strike = pushRect da (Rect px (py + fmAscent fm * 0.65) textW thick) col-        case deco of-          DecorationUnderline -> underline-          DecorationStrikethrough -> strike-          DecorationUnderlineStrike -> underline >> strike-          DecorationNone -> pure ()---- | Emit ops with @fm@ as the default font and @resolve@ giving the font of--- styled text, and whether it draws its weight and slant natively.-emitDrawOps :: DrawArena -> FontMetrics -> (TextFont -> IO (FontMetrics, Bool)) -> SmallArray DrawOp -> IO ()-emitDrawOps da fm resolve ops = go 0-  where-    go !i-      | i >= sizeofSmallArray ops = pure ()-      | otherwise = emitOne (indexSmallArray ops i) >> go (i + 1)-    emitOne (FillRect r c) = pushRect da r c-    emitOne (FillRoundedRect r radius c) = pushRoundedRect da r radius c-    emitOne (FillTriangle x0 y0 x1 y1 x2 y2 c) = pushFilledTriangle da x0 y0 x1 y1 x2 y2 c-    emitOne (FillCircle cx cy radius c) = pushCircle da cx cy radius c-    emitOne (Stroke x0 y0 x1 y1 t c) = pushStroke da x0 y0 x1 y1 t c-    emitOne (StrokeRoundedRect r radius bw c) = pushRoundedStroke da r radius bw c-    emitOne (StrokeCircle cx cy radius bw c) = pushCircleStroke da cx cy radius bw c-    emitOne (StrokeLineAA x0 y0 x1 y1 bw c) = pushStrokeAA da x0 y0 x1 y1 bw c-    emitOne (FillQuadGradient r c0 c1 c2 c3) = pushQuadGradient da r c0 c1 c2 c3-    emitOne (DrawImageRect r tex u0 v0 u1 v1 c) = pushImage da r tex u0 v0 u1 v1 c-    emitOne (DrawText x y ax ay t c) = do-      prepared <- prepareFontMetrics fm t-      let Rect px py _ _ = drawTextBox prepared x y ax ay t-      -- Drawing text has no collected text span, so it keeps its quads even-      -- when the host rasterizes widget text externally.-      pushPreparedTextQuads da prepared px py t c-    emitOne (DrawTextStyled x y font t c) = do-      (styledFm, native) <- resolve font-      let weight = if native then WeightNormal else textFontWeight font-          fstyle = if native then FontStyleNormal else textFontStyle font-      prepared <- prepareFontMetrics styledFm t-      pushPreparedTextStyledQuads da prepared weight fstyle (textFontDecoration font) x y t c
− lib/NanoUI/Draw/Types.hs
@@ -1,423 +0,0 @@-{-# LANGUAGE StrictData #-}---- | Draw-layer data: immediate vector ops, batched draw commands, the finished--- per-frame draw data and the arena record. Free of font and emitter code so--- the context types can name these without depending on the emitters.-module NanoUI.Draw.Types-  ( Layer (..)-  , DrawOp (..)-  , TextFont (..)-  , defaultTextFont-  , DrawingBuild-  , shiftDrawOp-  , DrawCmd (..)-  , LayerSlice (..)-  , DrawData (..)-  , drawCmdCount-  , drawCmdNull-  , forDrawCmdsInLayer_-  , drawCmdElems-  , DrawArena (..)-  , BufferPool-  , vertexSize-  , indexSize-  , backdropDimTextureId-  , glyphAtlasTextureId-  ) where--import Data.IORef (IORef)-import Data.Primitive.PrimArray (MutablePrimArray, PrimArray, indexPrimArray, sizeofPrimArray)-import Data.Primitive.Types (Prim (..), defaultSetByteArray#, defaultSetOffAddr#)-import qualified Data.Text as T-import Data.Primitive.SmallArray (SmallArray)-import Data.Word (Word32, Word8)-import Foreign.ForeignPtr (ForeignPtr)-import Foreign.Ptr (Ptr)-import GHC.Exts-  ( Float (F#)-  , Int (I#)-  , RealWorld-  , (*#)-  , (+#)-  , indexFloatOffAddr#-  , indexIntOffAddr#-  , indexWord8Array#-  , indexWord8ArrayAsFloat#-  , indexWord8ArrayAsInt#-  , indexWord8ArrayAsWord32#-  , indexWord8OffAddr#-  , indexWord32OffAddr#-  , plusAddr#-  , readFloatOffAddr#-  , readIntOffAddr#-  , readWord8Array#-  , readWord8ArrayAsFloat#-  , readWord8ArrayAsInt#-  , readWord8ArrayAsWord32#-  , readWord8OffAddr#-  , readWord32OffAddr#-  , writeFloatOffAddr#-  , writeIntOffAddr#-  , writeWord8Array#-  , writeWord8ArrayAsFloat#-  , writeWord8ArrayAsInt#-  , writeWord8ArrayAsWord32#-  , writeWord8OffAddr#-  , writeWord32OffAddr#-  )-import GHC.Word (Word8 (W8#), Word32 (W32#))-import NanoUI.Style (FontStyle (..), FontVariant (..), FontWeight (..), TextDecoration (..))-import NanoUI.Types (Color (..), Rect (..))--data Layer = LayerBackground | LayerContent | LayerOverlay | LayerChrome-  deriving (Eq, Show, Enum, Bounded)---- Immediate vector ops, in widget pixel space. diagrams (and other plotters)--- flatten into this list; paint emits them after layout.-data DrawOp-  = FillRect !Rect !Color-  | FillRoundedRect !Rect {-# UNPACK #-} !Float !Color-  | FillTriangle-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Color-  | FillCircle-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Color-  | Stroke-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Color-  | StrokeRoundedRect !Rect {-# UNPACK #-} !Float {-# UNPACK #-} !Float !Color-  | StrokeCircle-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Color-  | StrokeLineAA-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Color-  | FillQuadGradient !Rect !Color !Color !Color !Color-  | DrawImageRect-      !Rect-      {-# UNPACK #-} !Int-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !Color-  | DrawText-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !T.Text-      !Color-  -- ^ Pen at (x, y) is the alignment point. ax 0..1 is left..right. ay 0..1 is-  -- bottom..top. ay < 0 means baseline (x is left, y is the baseline). Glyph size-  -- is the host font (`drawTextBox`).-  | DrawTextStyled-      {-# UNPACK #-} !Float-      {-# UNPACK #-} !Float-      !TextFont-      !T.Text-      !Color-  -- ^ Text in a font of its own, its line box's top left corner at (x, y).-  deriving (Eq)---- | The font a 'DrawTextStyled' draws with: the same choices a label's--- layout makes.-data TextFont = TextFont-  { textFontSize :: {-# UNPACK #-} !Float-  -- ^ Point size, @0@ for the theme's.-  , textFontVariant :: !FontVariant-  , textFontWeight :: !FontWeight-  , textFontStyle :: !FontStyle-  , textFontDecoration :: !TextDecoration-  }-  deriving (Eq, Show)---- | The theme's regular font.-defaultTextFont :: TextFont-defaultTextFont = TextFont 0 FontRegular WeightNormal FontStyleNormal DecorationNone---- | Translate every vertex in a 'DrawOp'. Paint reuses ops when only (x, y) moved.-shiftDrawOp :: Float -> Float -> DrawOp -> DrawOp-shiftDrawOp dx dy op =-  case op of-    FillRect (Rect x y w h) c -> FillRect (Rect (x + dx) (y + dy) w h) c-    FillRoundedRect (Rect x y w h) r c -> FillRoundedRect (Rect (x + dx) (y + dy) w h) r c-    FillTriangle x0 y0 x1 y1 x2 y2 c ->-      FillTriangle (x0 + dx) (y0 + dy) (x1 + dx) (y1 + dy) (x2 + dx) (y2 + dy) c-    FillCircle cx cy r c -> FillCircle (cx + dx) (cy + dy) r c-    Stroke x0 y0 x1 y1 t c -> Stroke (x0 + dx) (y0 + dy) (x1 + dx) (y1 + dy) t c-    StrokeRoundedRect (Rect x y w h) r bw c -> StrokeRoundedRect (Rect (x + dx) (y + dy) w h) r bw c-    StrokeCircle cx cy r bw c -> StrokeCircle (cx + dx) (cy + dy) r bw c-    StrokeLineAA x0 y0 x1 y1 bw c -> StrokeLineAA (x0 + dx) (y0 + dy) (x1 + dx) (y1 + dy) bw c-    FillQuadGradient (Rect x y w h) c0 c1 c2 c3 -> FillQuadGradient (Rect (x + dx) (y + dy) w h) c0 c1 c2 c3-    DrawImageRect (Rect x y w h) tex u0 v0 u1 v1 c -> DrawImageRect (Rect (x + dx) (y + dy) w h) tex u0 v0 u1 v1 c-    DrawText x y ax ay t c -> DrawText (x + dx) (y + dy) ax ay t c-    DrawTextStyled x y font t c -> DrawTextStyled (x + dx) (y + dy) font t c--type DrawingBuild = Rect -> SmallArray DrawOp--data DrawCmd = DrawCmd-  { cmdClipX :: {-# UNPACK #-} !Float-  , cmdClipY :: {-# UNPACK #-} !Float-  , cmdClipW :: {-# UNPACK #-} !Float-  , cmdClipH :: {-# UNPACK #-} !Float-  , cmdTextureId :: {-# UNPACK #-} !Int-  , cmdIndexOffset :: {-# UNPACK #-} !Word32-  , cmdIndexCount :: {-# UNPACK #-} !Word32-  , cmdLayer :: !Layer-  }-  deriving (Eq, Show)--data LayerSlice = LayerSlice-  { sliceOffset :: {-# UNPACK #-} !Int-  , sliceCount :: {-# UNPACK #-} !Int-  }-  deriving (Eq, Show)---- Two packed Ints, 16 bytes, 8-byte aligned.-instance Prim LayerSlice where-  sizeOfType# _ = 16#-  alignmentOfType# _ = 8#-  indexByteArray# arr# i# =-    let o# = i# *# 16#-     in LayerSlice-          (I# (indexWord8ArrayAsInt# arr# o#))-          (I# (indexWord8ArrayAsInt# arr# (o# +# 8#)))-  readByteArray# arr# i# s0 =-    let o# = i# *# 16#-     in case readWord8ArrayAsInt# arr# o# s0 of-          (# s1, off# #) ->-            case readWord8ArrayAsInt# arr# (o# +# 8#) s1 of-              (# s2, cnt# #) -> (# s2, LayerSlice (I# off#) (I# cnt#) #)-  writeByteArray# arr# i# (LayerSlice (I# off#) (I# cnt#)) s0 =-    let o# = i# *# 16#-     in writeWord8ArrayAsInt# arr# (o# +# 8#) cnt# (writeWord8ArrayAsInt# arr# o# off# s0)-  setByteArray# = defaultSetByteArray#-  indexOffAddr# addr# i# =-    let a# = addr# `plusAddr#` (i# *# 16#)-     in LayerSlice (I# (indexIntOffAddr# a# 0#)) (I# (indexIntOffAddr# (a# `plusAddr#` 8#) 0#))-  readOffAddr# addr# i# s0 =-    let a# = addr# `plusAddr#` (i# *# 16#)-     in case readIntOffAddr# a# 0# s0 of-          (# s1, off# #) ->-            case readIntOffAddr# (a# `plusAddr#` 8#) 0# s1 of-              (# s2, cnt# #) -> (# s2, LayerSlice (I# off#) (I# cnt#) #)-  writeOffAddr# addr# i# (LayerSlice (I# off#) (I# cnt#)) s0 =-    let a# = addr# `plusAddr#` (i# *# 16#)-     in writeIntOffAddr# (a# `plusAddr#` 8#) 0# cnt# (writeIntOffAddr# a# 0# off# s0)-  setOffAddr# = defaultSetOffAddr#--{-# INLINE layerToWord8 #-}-layerToWord8 :: Layer -> Word8-layerToWord8 ly = fromIntegral (fromEnum ly)--{-# INLINE layerFromWord8 #-}-layerFromWord8 :: Word8 -> Layer-layerFromWord8 w = toEnum (fromIntegral w)---- Clip floats (16) + Int tex (8) + two Word32 (8) + Layer Word8 + pad = 40.-instance Prim DrawCmd where-  sizeOfType# _ = 40#-  alignmentOfType# _ = 8#-  indexByteArray# arr# i# =-    let o# = i# *# 40#-     in DrawCmd-          (F# (indexWord8ArrayAsFloat# arr# o#))-          (F# (indexWord8ArrayAsFloat# arr# (o# +# 4#)))-          (F# (indexWord8ArrayAsFloat# arr# (o# +# 8#)))-          (F# (indexWord8ArrayAsFloat# arr# (o# +# 12#)))-          (I# (indexWord8ArrayAsInt# arr# (o# +# 16#)))-          (W32# (indexWord8ArrayAsWord32# arr# (o# +# 24#)))-          (W32# (indexWord8ArrayAsWord32# arr# (o# +# 28#)))-          (layerFromWord8 (W8# (indexWord8Array# arr# (o# +# 32#))))-  readByteArray# arr# i# s0 =-    let o# = i# *# 40#-     in case readWord8ArrayAsFloat# arr# o# s0 of-          (# s1, x# #) ->-            case readWord8ArrayAsFloat# arr# (o# +# 4#) s1 of-              (# s2, y# #) ->-                case readWord8ArrayAsFloat# arr# (o# +# 8#) s2 of-                  (# s3, w# #) ->-                    case readWord8ArrayAsFloat# arr# (o# +# 12#) s3 of-                      (# s4, h# #) ->-                        case readWord8ArrayAsInt# arr# (o# +# 16#) s4 of-                          (# s5, tex# #) ->-                            case readWord8ArrayAsWord32# arr# (o# +# 24#) s5 of-                              (# s6, off# #) ->-                                case readWord8ArrayAsWord32# arr# (o# +# 28#) s6 of-                                  (# s7, cnt# #) ->-                                    case readWord8Array# arr# (o# +# 32#) s7 of-                                      (# s8, ly# #) ->-                                        (# s8-                                         , DrawCmd-                                            (F# x#)-                                            (F# y#)-                                            (F# w#)-                                            (F# h#)-                                            (I# tex#)-                                            (W32# off#)-                                            (W32# cnt#)-                                            (layerFromWord8 (W8# ly#))-                                         #)-  writeByteArray# arr# i# cmd s0 =-    case cmd of-      DrawCmd (F# x#) (F# y#) (F# w#) (F# h#) (I# tex#) (W32# off#) (W32# cnt#) ly ->-        let o# = i# *# 40#-            !(W8# ly#) = layerToWord8 ly-         in writeWord8Array# arr# (o# +# 32#) ly# $-              writeWord8ArrayAsWord32# arr# (o# +# 28#) cnt# $-                writeWord8ArrayAsWord32# arr# (o# +# 24#) off# $-                  writeWord8ArrayAsInt# arr# (o# +# 16#) tex# $-                    writeWord8ArrayAsFloat# arr# (o# +# 12#) h# $-                      writeWord8ArrayAsFloat# arr# (o# +# 8#) w# $-                        writeWord8ArrayAsFloat# arr# (o# +# 4#) y# $-                          writeWord8ArrayAsFloat# arr# o# x# s0-  setByteArray# = defaultSetByteArray#-  indexOffAddr# addr# i# =-    let a# = addr# `plusAddr#` (i# *# 40#)-     in DrawCmd-          (F# (indexFloatOffAddr# a# 0#))-          (F# (indexFloatOffAddr# (a# `plusAddr#` 4#) 0#))-          (F# (indexFloatOffAddr# (a# `plusAddr#` 8#) 0#))-          (F# (indexFloatOffAddr# (a# `plusAddr#` 12#) 0#))-          (I# (indexIntOffAddr# (a# `plusAddr#` 16#) 0#))-          (W32# (indexWord32OffAddr# (a# `plusAddr#` 24#) 0#))-          (W32# (indexWord32OffAddr# (a# `plusAddr#` 28#) 0#))-          (layerFromWord8 (W8# (indexWord8OffAddr# (a# `plusAddr#` 32#) 0#)))-  readOffAddr# addr# i# s0 =-    let a# = addr# `plusAddr#` (i# *# 40#)-     in case readFloatOffAddr# a# 0# s0 of-          (# s1, x# #) ->-            case readFloatOffAddr# (a# `plusAddr#` 4#) 0# s1 of-              (# s2, y# #) ->-                case readFloatOffAddr# (a# `plusAddr#` 8#) 0# s2 of-                  (# s3, w# #) ->-                    case readFloatOffAddr# (a# `plusAddr#` 12#) 0# s3 of-                      (# s4, h# #) ->-                        case readIntOffAddr# (a# `plusAddr#` 16#) 0# s4 of-                          (# s5, tex# #) ->-                            case readWord32OffAddr# (a# `plusAddr#` 24#) 0# s5 of-                              (# s6, off# #) ->-                                case readWord32OffAddr# (a# `plusAddr#` 28#) 0# s6 of-                                  (# s7, cnt# #) ->-                                    case readWord8OffAddr# (a# `plusAddr#` 32#) 0# s7 of-                                      (# s8, ly# #) ->-                                        (# s8-                                         , DrawCmd-                                            (F# x#)-                                            (F# y#)-                                            (F# w#)-                                            (F# h#)-                                            (I# tex#)-                                            (W32# off#)-                                            (W32# cnt#)-                                            (layerFromWord8 (W8# ly#))-                                         #)-  writeOffAddr# addr# i# cmd s0 =-    case cmd of-      DrawCmd (F# x#) (F# y#) (F# w#) (F# h#) (I# tex#) (W32# off#) (W32# cnt#) ly ->-        let a# = addr# `plusAddr#` (i# *# 40#)-            !(W8# ly#) = layerToWord8 ly-         in writeWord8OffAddr# (a# `plusAddr#` 32#) 0# ly# $-              writeWord32OffAddr# (a# `plusAddr#` 28#) 0# cnt# $-                writeWord32OffAddr# (a# `plusAddr#` 24#) 0# off# $-                  writeIntOffAddr# (a# `plusAddr#` 16#) 0# tex# $-                    writeFloatOffAddr# (a# `plusAddr#` 12#) 0# h# $-                      writeFloatOffAddr# (a# `plusAddr#` 8#) 0# w# $-                        writeFloatOffAddr# (a# `plusAddr#` 4#) 0# y# $-                          writeFloatOffAddr# a# 0# x# s0-  setOffAddr# = defaultSetOffAddr#--data DrawData = DrawData-  { drawVertices :: ForeignPtr Word8-  , drawVertexCount :: {-# UNPACK #-} !Int-  , drawIndices :: ForeignPtr Word8-  , drawIndexCount :: {-# UNPACK #-} !Int-  , drawCommands :: !(PrimArray DrawCmd)-  , drawLayerSlices :: !(PrimArray LayerSlice)-  }--{-# INLINE drawCmdCount #-}-drawCmdCount :: DrawData -> Int-drawCmdCount dd = sizeofPrimArray (drawCommands dd)--{-# INLINE drawCmdNull #-}-drawCmdNull :: DrawData -> Bool-drawCmdNull dd = drawCmdCount dd == 0--{-# INLINE forDrawCmdsInLayer_ #-}-forDrawCmdsInLayer_ :: Layer -> DrawData -> (DrawCmd -> IO ()) -> IO ()-forDrawCmdsInLayer_ ly dd f =-  let LayerSlice off cnt = indexPrimArray (drawLayerSlices dd) (fromEnum ly)-      cmds = drawCommands dd-      go !i-        | i >= cnt = pure ()-        | otherwise = f (indexPrimArray cmds (off + i)) >> go (i + 1)-   in go 0--drawCmdElems :: DrawData -> [DrawCmd]-drawCmdElems dd =-  let cmds = drawCommands dd-   in [indexPrimArray cmds i | i <- [0 .. sizeofPrimArray cmds - 1]]--type BufferPool = IORef [(ForeignPtr Word8, Int)]--data DrawArena = DrawArena-  { daVertexFPtr :: !(IORef (ForeignPtr Word8))-  , daVertexPtr :: !(IORef (Ptr Word8))-  , daVertexCap :: !(IORef Int)-  , daVertexCount :: !(IORef Int)-  , daVertexPool :: !BufferPool-  , daIndexFPtr :: !(IORef (ForeignPtr Word8))-  , daIndexPtr :: !(IORef (Ptr Word8))-  , daIndexCap :: !(IORef Int)-  , daIndexCount :: !(IORef Int)-  , daIndexPool :: !BufferPool-  , daCmdStore :: !(IORef (MutablePrimArray RealWorld DrawCmd))-  , daCmdCount :: !(IORef Int)-  , daCmdCapacity :: !(IORef Int)-  , daCurrentLayer :: !(IORef Layer)-  , daCurrentClip :: !(MutablePrimArray RealWorld Float)-  -- ^ The current clip rect: x, y, width and height.-  , daCurrentTexture :: !(IORef Int)-  , daCmdStartIndex :: !(IORef Int)-  , daSnapScale :: !(IORef Float)-  , daSquareGeometry :: !(IORef Bool)-  , daExternalText :: !(IORef Bool)-  }--vertexSize :: Int-vertexSize = 32--indexSize :: Int-indexSize = 4---- Reserved texture id. These quads act as a backdrop dim, not a solid fill.--- Mix comes from the vertex color alpha.-backdropDimTextureId :: Int-backdropDimTextureId = 0x7ffffffe---- Reserved texture id for the per-glyph SDL_ttf atlas. The renderer binds--- the glyph atlas SDL_Texture when it sees this id. Glyphs are cached as--- white-on-alpha so vertex color tints them at draw time.-glyphAtlasTextureId :: Int-glyphAtlasTextureId = 0x7ffffffd
+ lib/NanoUI/Effectful.hs view
@@ -0,0 +1,32 @@+-- | A 'NanoUI' view is an @effectful@ computation in the row 'NanoUIEs'.+-- Nothing else in nano-ui needs this module; it is for applications that+-- already use @effectful@ and want their views to share effects with the+-- rest of the program.+--+-- A view written in a larger row declares widgets with 'embedNanoUI', and+-- hands a container widget a body that uses its other effects with+-- 'withRunInNanoUI':+--+-- > sidebar :: (Ui :> es, Reader Config :> es) => Eff es ()+-- > sidebar = withRunInNanoUI $ \run -> column $ do+-- >   title <- run (asks configTitle)+-- >   heading title+--+-- 'runFrameEff' runs a frame of such a view, given a runner for the effects+-- other than 'Ui'.+module NanoUI.Effectful+  ( -- * The view type+    NanoUI (..)+  , NanoUIEs+  , Ui++    -- * Views in other effect rows+  , embedNanoUI+  , withRunInNanoUI+  , runUi+  , runFrameEff+  )+where++import NanoUI.Internal.Frame (runFrameEff)+import NanoUI.Internal.Monad (NanoUI (..), NanoUIEs, Ui, embedNanoUI, runUi, withRunInNanoUI)
− lib/NanoUI/Emit.hs
@@ -1,91 +0,0 @@--- | Widgets for reducer-style applications.------ Each function draws a widget from the model and, when the user changes it,--- emits a message instead of returning the new value. The backend's reducer--- runner (@runSdlAppReduce@, @runRgfwAppReduce@) folds the frame's messages--- into the model with your update function.------ The names match "NanoUI", so import this module qualified:------ @--- import NanoUI.Emit qualified as Emit------ data Msg = Increment | Decrement------ view :: Int -> NanoUI ()--- view n = row $ do---   Emit.button "-" Decrement---   label (T.pack (show n))---   Emit.button "+" Increment--- @-module NanoUI.Emit-  ( emit-  , button-  , checkbox-  , slider-  , select-  , radio-  , textInput-  , textArea-  , tabs-  )-where--import Control.Monad (when)-import Data.Text (Text)-import Data.Typeable (Typeable)-import Effectful (Eff, type (:>))-import NanoUI.Monad (Ui, emit)-import NanoUI.Widgets.Button qualified as W-import NanoUI.Widgets.Checkbox qualified as W-import NanoUI.Widgets.Node (respChanged)-import NanoUI.Widgets.Radio qualified as W-import NanoUI.Widgets.TextArea qualified as W-import NanoUI.Widgets.Select qualified as W-import NanoUI.Widgets.Slider qualified as W-import NanoUI.Widgets.Tabs (Tab)-import NanoUI.Widgets.Tabs qualified as W-import NanoUI.Widgets.TextInput qualified as W---- | Emit @msg@ when the button is clicked.-button :: (Typeable msg, Ui :> es) => Text -> msg -> Eff es ()-button txt msg = do-  clicked <- W.button txt-  when clicked (emit msg)--checkbox :: (Typeable msg, Ui :> es) => Text -> Bool -> (Bool -> msg) -> Eff es ()-checkbox txt checked toMsg = do-  new <- W.checkbox txt checked-  when (new /= checked) (emit (toMsg new))--slider :: (Typeable msg, Ui :> es) => Float -> Float -> Float -> (Float -> msg) -> Eff es ()-slider minV maxV value toMsg = do-  new <- W.slider minV maxV value-  when (new /= value) (emit (toMsg new))--select :: (Foldable f, Typeable msg, Ui :> es) => f Text -> Int -> (Int -> msg) -> Eff es ()-select options index toMsg = do-  new <- W.select options index-  when (new /= index) (emit (toMsg new))--radio :: (Foldable f, Typeable msg, Ui :> es) => f Text -> Int -> (Int -> msg) -> Eff es ()-radio options index toMsg = do-  new <- W.radio options index-  when (new /= index) (emit (toMsg new))--textInput :: (Typeable msg, Ui :> es) => Text -> (Text -> msg) -> Eff es ()-textInput value toMsg = do-  new <- W.textInput value-  when (new /= value) (emit (toMsg new))---- | Emit the new text after an edit. Caret and scroll changes emit nothing.-textArea :: (Typeable msg, Ui :> es) => Text -> (Text -> msg) -> Eff es ()-textArea value toMsg = do-  (resp, new) <- W.textArea' value-  when (respChanged resp && new /= value) (emit (toMsg new))---- | Emit the newly active key when the user switches tabs.-tabs :: (Foldable f, Eq a, Typeable msg, Ui :> es) => a -> f (Tab a (Eff es ())) -> (a -> msg) -> Eff es ()-tabs active ts toMsg = do-  new <- W.tabs active ts-  when (new /= active) (emit (toMsg new))
− lib/NanoUI/Font.hs
@@ -1,640 +0,0 @@-{-# LANGUAGE StrictData #-}--module NanoUI.Font-  ( GlyphQuad (..)-  , ShapedText (..)-  , ShapedGlyphs (..)-  , FontMetrics (..)-  , FontBackend (..)-  , CustomMeasureFn-  , prepareFontMetrics-  , prepareFontMetricsMany-  , measureTextIO-  , lineWidthIO-  , drawShaped-  , drawGlyph-  , caretX-  , caretXIO-  , selectionSpans-  , monospaceMetrics-  , scaleFontMetrics-  , measureTextWrappedIO-  , wrapTextLinesIO-  , truncateTextIO-  , lineWidth-  , kernedAdvance-  , textIndexAtX-  , tableCellInset-  , widgetContentInset-  , widgetPadding-  , buttonPadding-  , selectPadding-  , menuOuterPad-  , menuItemPadX-  , menuItemRowH-  , menuSepH-  , menuMinW-  , menuAccentW-  , menuAccentInset-  , centeredTextY-  , alignedTextPen-  , textInkEnd-  , isDefaultNodeFont-  , checkboxBoxSize-  , checkboxLeading-  , treeItemPadding-  , treeRowLeading-  , treeChevronRect-  , scrollBarWidth-  , scrollBarSideGap-  , scrollBarGeomFor-  , scrollBarGap-  , scrollBarGutter-  , ScrollBarSlot (..)-  , classifyScrollBar-  , scrollLayoutGutter-  , sliderTrackBounds-  , sliderTrackHeight-  , sliderHandleDiameter-  , sliderHandleSlack-  ) where--import qualified Data.Map.Strict as Map-import Data.Primitive.PrimArray (PrimArray, imapPrimArray, indexPrimArray, mapPrimArray, sizeofPrimArray)-import Data.Text (Text)-import qualified Data.Text as T-import NanoUI.Types (Rect (..), onGrid)-import NanoUI.Style (AlignX (..), FontStyle (..), FontVariant (..), FontWeight (..))--data GlyphQuad = GlyphQuad-  { gqX :: {-# UNPACK #-} !Float-  , gqY :: {-# UNPACK #-} !Float-  , gqW :: {-# UNPACK #-} !Float-  , gqH :: {-# UNPACK #-} !Float-  , gqU0 :: {-# UNPACK #-} !Float-  , gqV0 :: {-# UNPACK #-} !Float-  , gqU1 :: {-# UNPACK #-} !Float-  , gqV1 :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)---- | A line of text as the host's shaper laid it out: glyphs chosen and placed--- with the font's kerning, ligatures and contextual forms, in fallback fonts--- where the font lacks a character, and right-to-left runs reordered.-data ShapedText = ShapedText-  { stAdvance :: {-# UNPACK #-} !Float-  , stInkEnd :: {-# UNPACK #-} !Float-  -- ^ The right edge of the rightmost glyph's ink.-  , stCarets :: !(PrimArray Float)-  -- ^ Where the caret sits before each character, and after the last: one-  -- more entry than the text has characters. A right-to-left run's carets-  -- decrease, and the characters of a cluster share its width.-  }-  deriving (Eq, Show)---- | The glyph quads that draw a shaped line: eight numbers a glyph (x, y,--- width and height from the pen, then the atlas UVs u0 v0 u1 v1), in logical--- pixels. Valid until the host's glyph atlas next resets.-newtype ShapedGlyphs = ShapedGlyphs (PrimArray Float)-  deriving (Eq, Show)--data FontMetrics = FontMetrics-  { fmLineHeight :: {-# UNPACK #-} !Float-  , fmAscent :: {-# UNPACK #-} !Float-  -- | Device pixels per logical unit used to snap glyph quads to the pixel-  -- grid. The SDL backend sets this to the window pixel density so text lands on-  -- whole device pixels.-  , fmSnapScale :: {-# UNPACK #-} !Float-  , fmAdvance :: Char -> Float-  , fmKerning :: Char -> Char -> Float-  , fmShape :: Text -> Maybe ShapedText-  -- ^ The shaped layout of a text the snapshot was prepared for, when the-  -- host shapes. Other texts fall back to 'fmAdvance' and 'fmKerning'.-  , fmGlyph :: Char -> Maybe GlyphQuad-  -- | Optional effectful backend. Pure callbacks above are immutable metric-  -- snapshots; they must never perform font loading or atlas mutation.-  , fmBackend :: Maybe FontBackend-  }---- | Text preparation performs font queries in IO and returns an immutable--- snapshot for pure layout. Rasterisation is separate and occurs during draw.-data FontBackend = FontBackend-  { fbPrepare :: Text -> IO FontMetrics-  , fbDrawShaped :: Text -> IO (Maybe ShapedGlyphs)-  , fbDrawGlyph :: Char -> IO (Maybe GlyphQuad)-  }---- | Custom node measurement: font metrics and available (width, height) to--- the node's desired (width, height).-type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)--{-# INLINE prepareFontMetrics #-}-prepareFontMetrics :: FontMetrics -> Text -> IO FontMetrics-prepareFontMetrics fm txt = case fmBackend fm of-  Nothing -> pure fm-  Just backend -> fbPrepare backend txt---- | Prepare a finite text workspace for pure multi-label layout algorithms.-prepareFontMetricsMany :: FontMetrics -> [Text] -> IO FontMetrics-prepareFontMetricsMany fm texts = case fmBackend fm of-  Nothing -> pure fm-  Just _ -> do-    combined <- prepareFontMetrics fm (T.intercalate "\n" texts)-    shapes <- mapM (\t -> do-      prepared <- prepareFontMetrics fm t-      pure (t, fmShape prepared t)) texts-    let !byText = Map.fromList shapes-    pure combined {fmShape = \t -> Map.findWithDefault Nothing t byText}--{-# INLINE lineWidthIO #-}-lineWidthIO :: FontMetrics -> Text -> IO Float-lineWidthIO fm txt = do-  prepared <- prepareFontMetrics fm txt-  pure $! lineWidth prepared txt--{-# INLINE measureTextIO #-}-measureTextIO :: FontMetrics -> Text -> IO (Float, Float)-measureTextIO fm txt = do-  prepared <- prepareFontMetrics fm txt-  pure $! measureText prepared txt---- | The glyph quads of a shaped line, placing glyphs in the host's atlas as--- needed; 'Nothing' when the host does not shape.-{-# INLINE drawShaped #-}-drawShaped :: FontMetrics -> Text -> IO (Maybe ShapedGlyphs)-drawShaped fm txt = case fmBackend fm of-  Nothing -> pure Nothing-  Just backend -> fbDrawShaped backend txt--{-# INLINE drawGlyph #-}-drawGlyph :: FontMetrics -> Char -> IO (Maybe GlyphQuad)-drawGlyph fm c = case fmBackend fm of-  Nothing -> pure (fmGlyph fm c)-  Just backend -> fbDrawGlyph backend c--monospaceMetrics :: Float -> FontMetrics-monospaceMetrics cell =-  FontMetrics-    { fmLineHeight = cell-    , fmAscent = cell * 0.8-    , fmSnapScale = 1.0-    , fmAdvance = \_ -> cell-    , fmKerning = \_ _ -> 0-    , fmShape = \_ -> Nothing-    , fmGlyph = \_ -> Nothing-    , fmBackend = Nothing-    }--scaleFontMetrics :: Float -> FontMetrics -> FontMetrics-scaleFontMetrics s fm-  | s == 1.0 = fm-  | otherwise =-      FontMetrics-        { fmLineHeight = fmLineHeight fm * s-        , fmAscent = fmAscent fm * s-        -- Snap scale is a display property, not a font-size property.-        , fmSnapScale = fmSnapScale fm-        , fmAdvance = \c -> fmAdvance fm c * s-        , fmKerning = \a b -> fmKerning fm a b * s-        , fmShape = \t -> fmap scaleShape (fmShape fm t)-        , fmGlyph = fmap scaleGlyph . fmGlyph fm-        , fmBackend = fmap scaleBackend (fmBackend fm)-        }-  where-    scaleBackend backend = FontBackend-      { fbPrepare = \t -> scaleFontMetrics s <$> fbPrepare backend t-      , fbDrawShaped = \t -> fmap (fmap scaleGlyphs) (fbDrawShaped backend t)-      , fbDrawGlyph = \c -> fmap (fmap scaleGlyph) (fbDrawGlyph backend c)-      }-    scaleGlyph gq = gq-      { gqX = gqX gq * s, gqY = gqY gq * s-      , gqW = gqW gq * s, gqH = gqH gq * s-      }-    scaleShape st =-      st-        { stAdvance = stAdvance st * s-        , stInkEnd = stInkEnd st * s-        , stCarets = mapPrimArray (* s) (stCarets st)-        }-    -- UVs stay in normalised atlas space; only positions and sizes scale.-    scaleGlyphs (ShapedGlyphs quads) =-      ShapedGlyphs (imapPrimArray (\i v -> if i `mod` 8 < 4 then v * s else v) quads)---- | Horizontal text inset of a table cell. Zebra and header fills use the full cell rect.-tableCellInset :: Float-tableCellInset = 6--{-# INLINE widgetContentInset #-}-widgetContentInset :: FontMetrics -> (Float, Float)-widgetContentInset fm =-  let pad = fmAdvance fm ' ' * 1.25-   in (pad, pad)--{-# INLINE buttonPadding #-}-buttonPadding :: FontMetrics -> (Float, Float)-buttonPadding fm =-  let adv = fmAdvance fm ' '-      lh = fmLineHeight fm-   in (adv * 2.0, lh * 0.30)--{-# INLINE selectPadding #-}-selectPadding :: FontMetrics -> (Float, Float)-selectPadding fm =-  let adv = fmAdvance fm ' '-      lh = fmLineHeight fm-   in (adv * 2.0, lh * 0.50)---- Menu metrics shared by the text-field context menu painter, the generic--- context-menu widgets, and the layout/paint passes, so both menus render--- identically by construction.---- | Blank border between the menu panel edge and its rows.-menuOuterPad :: Float-menuOuterPad = 6---- | Extra horizontal inset of a menu row's label past 'menuOuterPad'.-menuItemPadX :: Float-menuItemPadX = 10---- | Fixed height of one menu row.-menuItemRowH :: Float-menuItemRowH = 28---- | Height of a separator band inside a menu.-menuSepH :: Float-menuSepH = 9---- | Floor for the menu panel width.-menuMinW :: Float-menuMinW = 148---- | Width of the hover accent marker painted at a menu row's left edge.-menuAccentW :: Float-menuAccentW = 2---- | Gap between the hover accent marker and the row's top and bottom edges.-menuAccentInset :: Float-menuAccentInset = 3--{-# INLINE centeredTextY #-}-centeredTextY :: FontMetrics -> Float -> Float -> Float -> Float-centeredTextY fm y h th =-  case fmGlyph fm 'H' of-    Nothing -> y + (h - th) / 2-    Just gq -> y + onGrid (fmSnapScale fm) (h / 2 - (gqY gq + gqH gq / 2))-  where-    -- Snap the (constant) baseline offset to the device grid rather than the-    -- whole pen: pen = snap(y + offset) rounds a fractional offset with ties-    -- to even, so adjacent rows (and the same row across a sub-pixel scroll)-    -- land on alternating device pixels while the geometry beside them stays-    -- rigid. Snapping only the constant offset keeps every row fixed on the-    -- grid no matter where y falls.---- Origin and used width inside the node box, inset on all AlignX sides.-{-# INLINE alignedTextBox #-}-alignedTextBox :: AlignX -> Float -> Float -> Float -> Float -> (Float, Float)-alignedTextBox ax x w ix tw =-  let contentW = max 0 (w - 2 * ix)-      used = min tw contentW-      tx = case ax of-        AlignEnd -> x + w - ix - used-        AlignCenter -> x + ix + (contentW - used) / 2-        AlignStart -> x + ix-   in (tx, used)---- Last glyph ink right in the same space as 'pushText' (pen + gqX + gqW).--- Falls back to advance when 'fmGlyph' is Nothing (tests).-textInkEnd :: FontMetrics -> Text -> Float-textInkEnd fm txt =-  case T.unsnoc txt of-    Nothing -> 0-    Just (prefix, c) ->-      case fmShape fm txt of-        Just st -> stInkEnd st-        Nothing ->-          let pen = lineWidth fm prefix-           in case fmGlyph fm c of-                Just gq -> pen + gqX gq + gqW gq-                Nothing -> pen + fmAdvance fm c---- Align using per-glyph advances (same as 'pushText'), not TTF_GetStringSize.--- When the line fits, AlignEnd/Center shift by ink so the visual right edge--- stays put as the last character's right bearing changes.-alignedTextPen :: AlignX -> Float -> Float -> Float -> FontMetrics -> Text -> (Float, Float)-alignedTextPen ax x w ix fm txt =-  let tw = lineWidth fm txt-      ink = textInkEnd fm txt-      contentW = max 0 (w - 2 * ix)-      used = min tw contentW-      shift =-        if tw > contentW-          then used-          else case ax of-            AlignStart -> used-            _ -> ink-      (tx, _) = alignedTextBox ax x w ix shift-   in (tx, used)--{-# INLINE widgetPadding #-}-widgetPadding :: FontMetrics -> (Float, Float)-widgetPadding fm =-  let (cx, cy) = widgetContentInset fm-   in (2 * cx, 2 * cy)--{-# INLINE checkboxBoxSize #-}-checkboxBoxSize :: FontMetrics -> Float-checkboxBoxSize fm = min 22 (max 18 (fmLineHeight fm * 1.15))--{-# INLINE checkboxLeading #-}-checkboxLeading :: FontMetrics -> Float-checkboxLeading fm = checkboxBoxSize fm + 8--{-# INLINE treeItemPadding #-}-treeItemPadding :: FontMetrics -> (Float, Float)-treeItemPadding fm =-  let lh = fmLineHeight fm-   in (0, max 8 (fromIntegral (round (lh * 0.40) :: Int)))--{-# INLINE treeIndentStep #-}-treeIndentStep :: FontMetrics -> Float-treeIndentStep fm = max 12 (fmLineHeight fm * 0.85)--{-# INLINE treeChevronLeading #-}-treeChevronLeading :: FontMetrics -> Float-treeChevronLeading fm = checkboxBoxSize fm + 6--{-# INLINE treeRowLeading #-}-treeRowLeading :: FontMetrics -> Int -> Float-treeRowLeading fm depth =-  treeIndentStep fm * fromIntegral (max 0 depth) + treeChevronLeading fm--{-# INLINE treeChevronRect #-}-treeChevronRect :: FontMetrics -> Float -> Float -> Float -> Float -> Int -> Rect-treeChevronRect fm x y _w h depth =-  let indent = treeIndentStep fm * fromIntegral (max 0 depth)-      lead = max 1 (treeChevronLeading fm)-   in Rect (x + indent) y lead h--sliderTrackHeight :: Float-sliderTrackHeight = 10--sliderHandleDiameter :: Float-sliderHandleDiameter = 18--sliderHandleSlack :: Float-sliderHandleSlack = (sliderHandleDiameter - sliderTrackHeight) / 2--{-# INLINE sliderTrackBounds #-}-sliderTrackBounds :: Float -> Float -> Float -> Float -> Rect-sliderTrackBounds x y w h =-  let trackY = y + max 0 ((h - sliderTrackHeight) / 2)-   in Rect x trackY (max 0 w) sliderTrackHeight---- | Thickness of a list or page scrollbar.-scrollBarWidth :: Float-scrollBarWidth = 8---- Window bodies take a slimmer bar.-scrollBarSlimWidth :: Float-scrollBarSlimWidth = 4--scrollBarMargin :: Float-scrollBarMargin = 3---- | The sliver between a page or window bar and the outer edge, and the--- smallest gap on either side of a list bar.-scrollBarSideGap :: Float-scrollBarSideGap = 3---- | Bar width and end margin for a slot.-scrollBarGeomFor :: ScrollBarSlot -> (Float, Float)-scrollBarGeomFor slot =-  case slot of-    ScrollBarList -> (scrollBarWidth, scrollBarMargin)-    ScrollBarPage -> (scrollBarWidth, scrollBarMargin)-    -- Window bar: side gaps only. No end inset.-    ScrollBarWindow -> (scrollBarSlimWidth, 0)---- | The layout arena stores a scroller's slot as its 'Enum' value, and every--- other node reads a zero there, so 'ScrollBarList' comes first.-data ScrollBarSlot = ScrollBarList | ScrollBarPage | ScrollBarWindow-  deriving (Eq, Show, Enum)--classifyScrollBar :: Bool -> Bool -> ScrollBarSlot-classifyScrollBar isWindowBody isPageGrow-  | isWindowBody = ScrollBarWindow-  | isPageGrow = ScrollBarPage-  | otherwise = ScrollBarList---- | Gap between the content and a bar, given the padding @trailPad@ on the--- bar's side: the padding itself, never under 'scrollBarSideGap'.-scrollBarGap :: Float -> Float-scrollBarGap trailPad = max scrollBarSideGap trailPad---- | Space an overflowing scroller takes from its content, beside the padding--- @trailPad@ on the bar's side, so the content stops one gap before the bar.--- A list bar keeps a gap to its well's edge as well. A page bar sits a side--- gap inside the page's edge. A window body's bar sits out in the window's--- padding, a side gap inside the window's edge, so that padding is the gap--- and only the bar and the side gap come out of the content.-scrollBarGutter :: ScrollBarSlot -> Float -> Float-scrollBarGutter slot trailPad =-  let (barW, _) = scrollBarGeomFor slot-      gap = scrollBarGap trailPad-   in case slot of-        ScrollBarList -> barW + 2 * gap - trailPad-        ScrollBarPage -> barW + scrollBarSideGap + gap - trailPad-        ScrollBarWindow -> barW + scrollBarSideGap--scrollLayoutGutter :: ScrollBarSlot -> Float -> Float -> Float -> Float-scrollLayoutGutter slot trailPad contentSize innerMain-  | contentSize <= innerMain = 0-  | otherwise = scrollBarGutter slot trailPad--measureText :: FontMetrics -> Text -> (Float, Float)-measureText fm txt =-  let h = fmLineHeight fm-      w = lineWidth fm txt-   in (w, h)---- | The one policy for "does this node use the ambient base font, or does it--- need the host resolver?". A zero size with a plain weight/style and the--- regular or mono variant resolves to the pre-read base metrics; everything--- else (heading/muted/danger, bold, italic, explicit size) defers to the host.--- Layout, paint, span placement and hit testing all share this so they cannot--- pick different faces for the same node.-{-# INLINE isDefaultNodeFont #-}-isDefaultNodeFont :: Float -> FontWeight -> FontStyle -> FontVariant -> Bool-isDefaultNodeFont size weight style variant =-  size <= 0-    && weight == WeightNormal-    && style == FontStyleNormal-    && (variant == FontRegular || variant == FontMono)---- | Advance of @c@ plus its kerning against the previous character: the one--- pen step shared by measuring, hit testing and glyph emission.-{-# INLINE kernedAdvance #-}-kernedAdvance :: FontMetrics -> Maybe Char -> Char -> Float-kernedAdvance fm prev c = case prev of-  Nothing -> fmAdvance fm c-  Just p -> fmAdvance fm c + fmKerning fm p c---- | The character index whose caret is nearest @x@: from the shaped carets--- when the text was prepared by a shaping host, which handles clusters and--- right-to-left runs, and otherwise from the same advances and kerning as--- 'NanoUI.Draw.pushText', so the caret lands where the glyph to its left was--- drawn.-textIndexAtX :: FontMetrics -> Text -> Float -> Int-textIndexAtX fm txt x-  | T.null txt = 0-  | Just st <- fmShape fm txt =-      let carets = stCarets st-          n = sizeofPrimArray carets-          nearest !best !bestD !i-            | i >= n = best-            | otherwise =-                let d = abs (indexPrimArray carets i - x)-                 in if d < bestD then nearest i d (i + 1) else nearest best bestD (i + 1)-       in nearest 0 (1 / 0) 0-  | x <= 0 = 0-  | otherwise = go 0 0.0 Nothing txt-  where-    go !i !acc prev t =-      case T.uncons t of-        Nothing -> i-        Just (c, rest) ->-          let adv = kernedAdvance fm prev c-              mid = acc + adv * 0.5-           in if x < mid then i else go (i + 1) (acc + adv) (Just c) rest---- | Where the caret before character @i@ of @txt@ sits: a shaped caret when--- the snapshot was prepared for @txt@, else the width of the characters--- before it.-caretX :: FontMetrics -> Text -> Int -> Float-caretX fm txt i = case fmShape fm txt of-  Just st ->-    let carets = stCarets st-     in if sizeofPrimArray carets == 0 then 0 else indexPrimArray carets (max 0 (min (sizeofPrimArray carets - 1) i))-  Nothing -> lineWidth fm (T.take i txt)--caretXIO :: FontMetrics -> Text -> Int -> IO Float-caretXIO fm txt i = do-  prepared <- prepareFontMetrics fm txt-  pure $! caretX prepared txt i---- | The horizontal extents covering characters @lo@ to @hi@: one span for--- left-to-right text, and a span per direction run where a selection crosses--- right-to-left text.-selectionSpans :: FontMetrics -> Text -> Int -> Int -> [(Float, Float)]-selectionSpans fm txt lo hi-  | hi <= lo = []-  | Just st <- fmShape fm txt =-      let carets = stCarets st-          n = sizeofPrimArray carets - 1-          charSpan i =-            let a = indexPrimArray carets i-                b = indexPrimArray carets (i + 1)-             in (min a b, max a b)-          merge [] = []-          merge [one] = [one]-          merge ((a0, a1) : (b0, b1) : rest)-            | b0 <= a1 + 0.5 && b1 >= a0 - 0.5 = merge ((min a0 b0, max a1 b1) : rest)-            | otherwise = (a0, a1) : merge ((b0, b1) : rest)-       in merge [charSpan i | i <- [max 0 lo .. min n hi - 1]]-  | otherwise = [(caretX fm txt lo, caretX fm txt hi)]--lineWidth :: FontMetrics -> Text -> Float-lineWidth fm line-  | T.null line = 0-  | otherwise =-      case fmShape fm line of-        Just st -> stAdvance st-        Nothing ->-          let !spaceAdv = fmAdvance fm ' '-              !xAdv = fmAdvance fm 'x'-              !mAdv = fmAdvance fm 'M'-           in if spaceAdv == xAdv && xAdv == mAdv && fmKerning fm 'x' 'M' == 0-                then fromIntegral (T.length line) * spaceAdv-                else case T.uncons line of-                  Just (c0, rest) ->-                    fst (T.foldl' step (fmAdvance fm c0, c0) rest)-                  Nothing -> 0-  where-    step (!w, !prev) c = (w + kernedAdvance fm (Just prev) c, c)--measureTextWrappedIO :: (Text -> IO Float) -> FontMetrics -> Text -> Float -> IO (Float, Float)-measureTextWrappedIO lineW fm txt maxW = do-  textLines <- wrapTextLinesIO lineW txt maxW-  ws <- mapM lineW textLines-  let lineH = fmLineHeight fm-  pure $ case textLines of-    [] -> (0, lineH)-    _ -> (min maxW (maximum ws), lineH * fromIntegral (length textLines))---- | Wrap each paragraph to @maxW@ using the host line measure: whole words--- first, characters for words (or paragraphs) that cannot fit.-wrapTextLinesIO :: (Text -> IO Float) -> Text -> Float -> IO [Text]-wrapTextLinesIO lineW txt maxW = concat <$> mapM wrapParagraph (T.lines txt)-  where-    wrapParagraph para-      | maxW <= 0 = pure []-      | T.null para = pure [""]-      | otherwise = do-          w <- lineW para-          if w <= maxW-            then pure [para]-            else if T.any (== ' ') para-              then wrapWords (T.words para) []-              else reverse <$> charLines para []-    wrapWords [] acc = pure (reverse acc)-    wrapWords (word : wordsLeft) acc = case acc of-      [] -> startLine word wordsLeft acc-      line : rest -> do-        let candidate = line <> " " <> word-        width <- lineW candidate-        if width <= maxW-          then wrapWords wordsLeft (candidate : rest)-          else startLine word wordsLeft acc-    startLine word wordsLeft acc = do-      width <- lineW word-      if width <= maxW-        then wrapWords wordsLeft (word : acc)-        else do-          broken <- charLines word []-          wrapWords wordsLeft (broken ++ acc)-    charLines chunk acc-      | T.null chunk = pure acc-      | otherwise = do-          (line, rest) <- takeWidth lineW maxW chunk-          if T.null line-            then pure acc-            else charLines rest (line : acc)---- Always consume at least one character from non-empty text, even when a--- single glyph exceeds the available width, so wrapping makes progress.-takeWidth :: (Text -> IO Float) -> Float -> Text -> IO (Text, Text)-takeWidth lineW maxW txt-  | T.null txt = pure (txt, T.empty)-  | otherwise = (`T.splitAt` txt) <$> maxFit 1 (T.length txt)-  where-    maxFit lo hi-      | lo >= hi = pure lo-      | otherwise = do-          let mid = (lo + hi + 1) `div` 2-          ok <- (<= maxW) <$> lineW (T.take mid txt)-          if ok then maxFit mid hi else maxFit lo (mid - 1)--truncateTextIO :: (Text -> IO Float) -> Float -> Text -> IO Text-truncateTextIO lineW maxW txt-  | maxW <= 0 = pure ""-  | otherwise = do-      w <- lineW txt-      if w <= maxW-        then pure txt-        else do-          ellW <- lineW "..."-          if maxW <= ellW-            then fst <$> takeWidth lineW maxW txt-            else do-              (fit, _) <- takeWidth lineW (maxW - ellW) txt-              pure (T.dropWhileEnd (== '.') fit <> "...")
− lib/NanoUI/Frame.hs
@@ -1,413 +0,0 @@-{-# LANGUAGE DataKinds #-}--module NanoUI.Frame-  ( runFrame-  , runFrameEff-  , runFrameReduce-  , runFrameReduceEff-  , needsRedraw-  , pointerDragActive-  , textFieldActive-  , floatingPanelActive-  , debugPanelOpen-  , collectTextSpans-  , collectOverlayTextSpans-  , collectRasterSpans-  , widgetNodeCount-  , pointerCursorWanted-  , cursorKindIs-  , uiCursorKind-  , UiCursorKind (..)-  )-where--import Control.Monad (unless, when)-import Data.IORef (modifyIORef', readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Typeable (Typeable)-import Effectful (Eff, IOE, runEff, type (:>))-import NanoUI.Context-  ( Context (..)-  , armMenuPointerCapture-  , beginThemeScopes-  , damageFull-  , themeScopesChanged-  , FrameMsg (..)-  , clearDirty-  , decodeMessages-  , drainMessages-  , getLiveAnimations-  , getPrevRect-  , getStore-  , isDirty-  , lookupPopupConfig-  , markDirty-  , pruneDrawOpCache-  , resetDrawingScopeCache-  , setMenuPointerGesture-  , stepScrollGlides-  , takeDamage-  , tickAnimations-  , hasCustomLayoutInputs-  , ensureMetricCaches-  , InteractionState (..)-  , getsOverlay-  , OverlayState (..)-  , getsDamage-  , DamageState (..)-  , modifyInteraction-  )-import NanoUI.Context (beginFrameModal)-import NanoUI.Damage (FrameSnapshot (..), updatePrevRects, writeDamage)-import NanoUI.Draw-  ( DrawData-  , Layer (..)-  , beginLayer-  , finishDraw-  , pushRect-  , resetDrawArena-  , setClip-  )-import NanoUI.Frame.Cursor-  ( UiCursorKind (..)-  , cursorKindIs-  , pointerCursorWanted-  , uiCursorKind-  )-import NanoUI.Frame.Input-  ( armPointerPress-  , disarmPointerPress-  , finalizePointerPress-  , finalizePointerRelease-  , finalizeSelectFocus-  , finalizeTabFocus-  , finalizeTextInputFocus-  , refreshHover-  )-import NanoUI.Frame.Focus (constrainFocusToModal, syncWidgetLabels)-import NanoUI.Frame.Paint (lowerShapes)-import NanoUI.Frame.Redraw-  ( debugPanelOpen-  , floatingPanelActive-  , needsRedraw-  , overlayMenuOpen-  , pointerDragActive-  , textFieldActive-  )-import NanoUI.Frame.Scroll-  ( applyScrollOffsets-  , updateScrollDrag-  , updateScrollWheel-  )-import NanoUI.Frame.Select-  ( cacheOpenSelectDrop-  , closeSelectOnOutsideClick-  , drawSelectOverlays-  , finalizeSelectKeyboard-  , finalizeSelectPick-  , markSelectDropPress-  )-import NanoUI.Frame.Spans-  ( collectOverlayTextSpans-  , collectRasterSpans-  , collectTextSpans-  , widgetNodeCount-  )-import NanoUI.Frame.Overlay (drawModalOverlays, drawPopupOverlays, drawWindowOverlays)-import NanoUI.Frame.TextEdit (finalizeTextFieldMouse)-import NanoUI.Frame.TextEdit.Menu-  ( closeTextEditMenuOnEscape-  , closeTextEditMenuOnOutsideClick-  , drawTextEditMenuOverlays-  , finalizeTextEditMenuPick-  , openTextEditMenu-  )-import NanoUI.Frame.Window-  ( contextMeasurers-  , lookupWindowPos-  , lookupWindowSize-  , persistWindowPositions-  , updateWindowDrag-  , updateWindowResize-  )-import NanoUI.Id (WidgetId (..), initialIdContext)-import NanoUI.Input (Input (..), inputMouseDown, stripInteractionInput)-import NanoUI.Layout.Arena-  ( captureLayoutCache-  , layoutCacheEligible-  , layoutInputsMatch-  , newLayoutCache-  , resetNodeArena-  , restoreLayoutCache-  )-import NanoUI.Layout.Solve (placeModals, placePopups, placeWindows, solveLayout)-import NanoUI.Monad (NanoUI, Ui, runUi, whenM)-import NanoUI.Store (mirrorStoresChanged)-import NanoUI.Style (Theme (..))-import NanoUI.Types (Damage (..), Size (..), rectInflate, rectNonEmpty)--runFrame :: Context -> Input -> NanoUI a -> IO (a, [FrameMsg], DrawData, Bool)-runFrame = runFrameEff runEff---- View this model, then apply decoded messages at frame end.--- DrawData is from the pre-reduce model (one-frame lag). The idle--- loop redraws when the reduced model differs.-runFrameReduce ::-  (Typeable msg, Eq model) =>-  (msg -> model -> model)-  -> Context-  -> Input-  -> model-  -> (model -> NanoUI a)-  -> IO (a, model, [msg], DrawData, Bool)-runFrameReduce = runFrameReduceEff runEff--runFrameReduceEff ::-  (IOE :> es, Typeable msg, Eq model) =>-  (forall x. Eff es x -> IO x)-  -> (msg -> model -> model)-  -> Context-  -> Input-  -> model-  -> (model -> Eff (Ui : es) a)-  -> IO (a, model, [msg], DrawData, Bool)-runFrameReduceEff unlift update ctx inp model view = do-  (a, msgs, draw, dirty) <- runFrameEff unlift ctx inp (view model)-  let-    typed = decodeMessages msgs-    model' = foldl' (flip update) model typed-  when (model' /= model) (markDirty ctx)-  dirty' <- isDirty ctx-  pure (a, model', typed, draw, dirty || dirty')--runFrameEff ::-  IOE :> es =>-  (forall x. Eff es x -> IO x)-  -> Context-  -> Input-  -> Eff (Ui : es) a-  -> IO (a, [FrameMsg], DrawData, Bool)-runFrameEff unlift ctx inp ui = do-  ensureMetricCaches ctx-  oldHot <- readIORef (ctxLastHotId ctx)-  oldActive <- readIORef (ctxActiveId ctx)-  oldFocus <- readIORef (ctxFocusId ctx)-  oldHotRect <- getPrevRect ctx oldHot-  oldActiveRect <- getPrevRect ctx oldActive-  oldFocusRect <- getPrevRect ctx oldFocus-  oldFloatingRects <- getsOverlay ctx osPrevFloatingRects-  oldRects <- getsDamage ctx dsPrevRects-  oldTexts <- getsDamage ctx dsPrevNodeTexts-  oldSize <- getsDamage ctx dsLastWindowSize-  oldStore <- getStore ctx-  wasDirty <- isDirty ctx-  clearDirty ctx-  animKeys <- IM.keysSet <$> getLiveAnimations ctx-  -- Wheel and thumb-drag input targets the previous frame's layout, so apply-  -- it while that arena is still intact, before it is reset for the new-  -- build. Settling offsets before the UI pass keeps build-time-  -- virtualization (table body rows) materialized for the range that will-  -- actually be visible, without a second build pass.-  updateScrollWheel ctx inp-  -- A glide advances with the wheel, before the build, for the same reason:-  -- the offset this frame renders at is the one virtualization must see.-  stepScrollGlides ctx (inputDeltaTime inp)-  updateScrollDrag ctx inp-  beginThemeScopes ctx True-  resetNodeArena (ctxNodeArena ctx)-  resetDrawArena (ctxDrawArena ctx)-  resetUiBuildScopes ctx-  unless (inputMouseDown inp) $-    modifyInteraction ctx (\s -> s {isSelectDropPress = False})-  when (not (inputMouseDown inp) && not (inputMouseReleased inp)) $-    setMenuPointerGesture ctx False-  beginFrameModal ctx-  writeIORef (ctxReleaseClickedId ctx) (WidgetId 0)-  armMenuPointerCapture ctx inp-  armPointerPress ctx inp-  result0 <- unlift (runUi ctx inp ui)-  -- Pending click is one-shot. Clear before a mirror rebuild so toggles do not fire twice.-  writeIORef (ctxClickedId ctx) (WidgetId 0)-  storeMid <- getStore ctx-  result <--    if mirrorStoresChanged oldStore storeMid-      then do-        resetUiBuild ctx-        unlift (runUi ctx (stripInteractionInput inp) ui)-      else pure result0-  -- Scopes only change how nodes look, which the rect and text diffs below-  -- cannot see, and custom widgets' cached ops hold the old theme's colours.-  whenM (themeScopesChanged ctx) $ do-    damageFull ctx-    modifyIORef' (ctxMetricGen ctx) (+ 1)-  -- Sync widget node values (checkbox/radio/tree) from the store before measure-  -- so labels and layout reflect the current state.-  syncWidgetLabels ctx-  let-    Size w h = inputWindowSize inp-  reused <- tryReuseLayout ctx (Size w h)-  unless reused $ do-    solvePlaceWindows ctx w h-    captureLayout ctx (Size w h)-  movedResize <- updateWindowResize ctx inp w h-  movedWindow <- updateWindowDrag ctx inp-  when (movedResize || movedWindow) $-    placeWindows-      (ctxNodeArena ctx)-      (contextMeasurers ctx)-      w-      h-      (lookupWindowPos ctx)-      (lookupWindowSize ctx)-  persistWindowPositions ctx-  applyScrollOffsets ctx-  finalizePointerPress ctx inp-  finalizePointerRelease ctx inp-  disarmPointerPress ctx inp-  finalizeTextInputFocus ctx inp-  finalizeSelectFocus ctx inp-  finalizeTextFieldMouse ctx inp-  closeTextEditMenuOnOutsideClick ctx inp-  openTextEditMenu ctx inp-  finalizeTextEditMenuPick ctx inp-  closeTextEditMenuOnEscape ctx inp-  constrainFocusToModal ctx-  finalizeTabFocus ctx inp-  finalizeSelectKeyboard ctx inp-  markSelectDropPress ctx inp-  finalizeSelectPick ctx inp-  closeSelectOnOutsideClick ctx inp-  storeAfter <- getStore ctx-  let storeChanged = mirrorStoresChanged storeMid storeAfter-  when storeChanged $ syncWidgetLabels ctx-  let layoutDirty = storeChanged || movedResize || movedWindow-  when layoutDirty $ do-    solvePlaceWindows ctx w h-    captureLayout ctx (Size w h)-    applyScrollOffsets ctx-  cacheOpenSelectDrop ctx-  updatePrevRects ctx-  refreshHover ctx inp-  tickAnimations ctx (inputDeltaTime inp)-  pruneDrawOpCache ctx-  overlayOpen <- overlayMenuOpen ctx-  writeDamage ctx inp overlayOpen-    FrameSnapshot-      { fsWasDirty = wasDirty-      , fsSize = oldSize-      , fsStore = oldStore-      , fsHot = oldHot-      , fsActive = oldActive-      , fsFocus = oldFocus-      , fsHotRect = oldHotRect-      , fsActiveRect = oldActiveRect-      , fsFocusRect = oldFocusRect-      , fsFloatingRects = oldFloatingRects-      , fsRects = oldRects-      , fsTexts = oldTexts-      , fsAnimKeys = animKeys-      }-  -- Clip frames only repaint the damaged region: the retain texture already-  -- holds every other pixel, and the runner scissors the present to the same-  -- damage. The region repaints from the window backdrop, inflated by one-  -- logical pixel to cover the runner's outward pixel snap. Full-present-  -- frames (fresh retain, forced full, continuous) paint everything.-  paintFull <- readIORef (ctxPaintFull ctx)-  beginLayer (ctxDrawArena ctx) LayerBackground-  unless paintFull $-    paintDamageClip ctx =<< takeDamage ctx-  lowerShapes ctx-  beginLayer (ctxDrawArena ctx) LayerOverlay-  drawWindowOverlays ctx-  drawModalOverlays ctx (inputWindowSize inp)-  drawPopupOverlays ctx-  drawSelectOverlays ctx inp-  drawTextEditMenuOverlays ctx inp-  drawData <- finishDraw (ctxDrawArena ctx)-  msgs <- drainMessages ctx-  dirtyAfterUi <- isDirty ctx-  pure (result, msgs, drawData, dirtyAfterUi)---- Second UI pass after mirror store write. Keeps ctxStore, animations, and--- prev rects; only rebuilds node arena and id scopes.-resetUiBuild :: Context -> IO ()-resetUiBuild ctx = do-  beginThemeScopes ctx False-  resetNodeArena (ctxNodeArena ctx)-  resetUiBuildScopes ctx---- | Start a clip frame from the window backdrop, as a full frame starts from a--- window-coloured clear. Widgets with a transparent fill, such as an idle--- menu-bar title, draw nothing over the pixels they covered, so without the--- backdrop a hover that just ended would stay in the retain texture.-paintDamageClip :: Context -> Damage -> IO ()-paintDamageClip _ DamageFull = pure ()-paintDamageClip ctx (DamageClip r) = do-  let da = ctxDrawArena ctx-      clip = rectInflate 1 r-  setClip da clip-  when (rectNonEmpty r) $ do-    theme <- readIORef (ctxTheme ctx)-    pushRect da clip (themeWindow theme)--resetUiBuildScopes :: Context -> IO ()-resetUiBuildScopes ctx = do-  writeIORef (ctxContainerStack ctx) []-  writeIORef (ctxIdContext ctx) initialIdContext-  writeIORef (ctxFocusablesCount ctx) 0-  writeIORef (ctxHotId ctx) (WidgetId 0)-  resetDrawingScopeCache ctx--solvePlaceWindows :: Context -> Float -> Float -> IO ()-solvePlaceWindows ctx w h = do-  let ms = contextMeasurers ctx-  solveLayout (ctxNodeArena ctx) ms w h-  placeModals (ctxNodeArena ctx) ms w h-  placeWindows-    (ctxNodeArena ctx)-    ms-    w-    h-    (lookupWindowPos ctx)-    (lookupWindowSize ctx)-  placePopups-    (ctxNodeArena ctx)-    ms-    w-    h-    (lookupPopupConfig ctx)---- | Reuse solved geometry for unchanged layout inputs. Floating placement and--- custom measurement have dependencies outside the arena and must be solved.-tryReuseLayout :: Context -> Size -> IO Bool-tryReuseLayout ctx size = do-  custom <- hasCustomLayoutInputs ctx-  if custom-    then pure False-    else do-      gen <- readIORef (ctxMetricGen ctx)-      mc <- readIORef (ctxLayoutCache ctx)-      case mc of-        Just (c, cachedSize, cachedGen)-          | cachedSize == size && cachedGen == gen -> do-              ok <- layoutInputsMatch (ctxNodeArena ctx) c-              if ok-                then restoreLayoutCache (ctxNodeArena ctx) c >> pure True-                else pure False-        _ -> pure False---- | Snapshot the solved layout so the next frame can reuse it.-captureLayout :: Context -> Size -> IO ()-captureLayout ctx size = do-  custom <- hasCustomLayoutInputs ctx-  eligible <- if custom then pure False else layoutCacheEligible (ctxNodeArena ctx)-  if not eligible-    then writeIORef (ctxLayoutCache ctx) Nothing-    else do-      gen <- readIORef (ctxMetricGen ctx)-      mc <- readIORef (ctxLayoutCache ctx)-      c0 <- case mc of-        Just (c, _, _) -> pure c-        Nothing -> newLayoutCache 64-      c <- captureLayoutCache (ctxNodeArena ctx) c0-      writeIORef (ctxLayoutCache ctx) (Just (c, size, gen))
− lib/NanoUI/Frame/Chrome.hs
@@ -1,399 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Widget paint helpers: labels, styles, rects, menu panels and display text.-module NanoUI.Frame.Chrome-  ( floatingAncestor-  , displayText-  , widgetVisualStyle-  , textInputValue-  , textInputFocused-  , fillStyledRect-  , strokeStyledRect-  , paintStyledRect-  , overlayWindowStyle-  , overlayModalStyle-  , overlayMenuStyle-  , paintMenuPanel-  , paintMenuAccent-  , paintScrollBarLayout-  , imageIdFromText-  , paintTabHeader-  , paintTableHeader-  ) where--import Control.Monad (when)-import Data.IORef (readIORef)-import qualified Data.IntMap.Strict as IM-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Read as TR-import NanoUI.Context-  ( Context (..)-  , WidgetStore (..)-  , getAnimationValue-  , getStore-  , intKey-  , nodeTheme-  )-import NanoUI.Draw (DrawArena, pushRect, pushRoundedRect, pushRoundedStroke)-import NanoUI.Font (menuAccentInset, menuAccentW)-import NanoUI.Frame.Scroll.Geometry (ScrollBarLayout (..))-import NanoUI.Id (hashWidgetId)-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , getNodeType-  , getNodeValue-  , getOptions-  , getParent-  , getStyleIdx-  , getText-  , getWidgetId-  , isFloatingNode-  )-import NanoUI.Style-  ( Style (..)-  , Theme (..)-  , themeAccent-  , themeButton-  , themeFloatingWindow-  , themeInput-  , themeMuted-  , themePanel-  , themeWindow-  , themeOnAccent-  , themeShadow-  )-import NanoUI.Types (Color (..), Rect (..), colorA, colorRGBA, lerpColor)-import NanoUI.WidgetText-  ( buttonFlagsFromStyle-  , buttonVisualStyle-  , isMenuBarStyle-  , isMenuItemStyle-  , isTableHeaderStyle-  , selectDisplayText-  , stripeColor-  , tableHeaderDisplayText-  , textInputFieldText-  , textInputPasswordMode-  , treeDecodeStripe-  )--floatingAncestor :: Context -> NodeIdx -> IO (Maybe NodeType)-floatingAncestor ctx idx = go idx-  where-    go i-      | i < 0 = pure Nothing-      | otherwise = do-          nt <- getNodeType (ctxNodeArena ctx) i-          if isFloatingNode nt-            then pure (Just nt)-            else getParent (ctxNodeArena ctx) i >>= go--displayText :: Context -> NodeType -> NodeIdx -> IO Text-displayText ctx nt idx = do-  txt <- getText (ctxNodeArena ctx) idx-  case nt of-    NodeButton -> do-      si <- getStyleIdx (ctxNodeArena ctx) idx-      pure $! if isTableHeaderStyle si then tableHeaderDisplayText txt else txt-    NodeTextInput -> textInputFieldText txt <$> textInputValue ctx idx <*> textInputFocused ctx idx-    NodeTextArea -> textInputValue ctx idx-    NodeSelect -> selectDisplayText txt <$> selectCurrentOption ctx idx-    _ -> pure txt--selectCurrentOption :: Context -> NodeIdx -> IO Text-selectCurrentOption ctx idx = do-  store <- getStore ctx-  opts <- getOptions (ctxNodeArena ctx) idx-  wid <- getWidgetId (ctxNodeArena ctx) idx-  let picked = IM.findWithDefault 0 (intKey wid) (storeInt store)-  pure $ case drop picked opts of-    (o : _) -> o-    _ -> ""---- | The text a field displays: its stored value, masked one character per--- character for password inputs so caret and selection offsets still line up.-textInputValue :: Context -> NodeIdx -> IO Text-textInputValue ctx idx = do-  let na = ctxNodeArena ctx-  wid <- getWidgetId na idx-  nt <- getNodeType na idx-  si <- getStyleIdx na idx-  store <- getStore ctx-  let value = IM.findWithDefault "" (intKey wid) (storeText store)-  pure $-    if nt == NodeTextInput && textInputPasswordMode si-      then T.replicate (T.length value) "*"-      else value--textInputFocused :: Context -> NodeIdx -> IO Bool-textInputFocused ctx idx = do-  wid <- getWidgetId (ctxNodeArena ctx) idx-  focus <- readIORef (ctxFocusId ctx)-  pure (focus == wid)---- | Transparent fills and no border.-clearStyle :: Style -> Style-clearStyle s = s {styleBg = clear, styleHoverBg = clear, styleActiveBg = clear, styleBorderWidth = 0}-  where-    clear = colorRGBA 0 0 0 0--closeButtonStyle :: Theme -> Bool -> Float -> Style-closeButtonStyle theme isHot animT =-  let btn = themeButton theme-      muted = lerpColor (styleFg btn) (styleBg (themePanel theme)) 0.42-      t = if isHot && not (animT > 0) then 1 else animT-   in (clearStyle btn) {styleFg = lerpColor muted (styleFg btn) t}--tabHeaderVisualStyle :: Theme -> Int -> Bool -> Style-tabHeaderVisualStyle theme styleIdx isActive =-  let panel = themePanel theme-      btn = themeButton theme-      muted = themeMuted theme-      accent = themeAccent theme-      clear = colorRGBA 0 0 0 0-      hoverLift = lerpColor (themeWindow theme) (styleHoverBg btn) 0.55-      (cr, activeBg, activeFg, activeBw, inactFg) = case styleIdx of-        1 -> (6, accent, themeOnAccent theme, 0, muted)-        2 -> (8, styleBg panel, styleFg panel, 1, muted)-        _ -> (6, styleBg panel, styleFg panel, 1, lerpColor muted (styleFg panel) 0.78)-   in if isActive-        then panel-          { styleBg = activeBg-          , styleHoverBg = activeBg-          , styleFg = activeFg-          , styleBorder = activeBg-          , styleBorderWidth = activeBw-          , styleCornerRadius = cr-          }-        else panel-          { styleBg = clear-          , styleHoverBg = hoverLift-          , styleFg = inactFg-          , styleBorder = clear-          , styleBorderWidth = 0-          , styleCornerRadius = cr-          }---- | Flat menu row / menu-bar entry. Transparent at rest, a hover highlight--- (matching the text-field context menu), and an accent-tinted fill while it--- owns an open drop-down (@val > 0.5@, menu-bar titles only).-menuItemVisualStyle :: Theme -> Float -> Style-menuItemVisualStyle theme val =-  let menu = overlayMenuStyle theme-      accent = themeAccent theme-      clear = colorRGBA 0 0 0 0-      openBg = lerpColor (styleBg menu) accent 0.3-      isOpen = val > 0.5-   in menu-        { styleBg = if isOpen then openBg else clear-        , styleHoverBg = if isOpen then openBg else styleHoverBg menu-        , styleActiveBg = lerpColor (styleBg menu) accent 0.4-        , styleBorder = clear-        , styleBorderWidth = 0-        -- The text-field context menu fills hovered rows with a square-        -- pushRect; keep the generic menu identical.-        , styleCornerRadius = 0-        }--tableHeaderVisualStyle :: Theme -> Bool -> Style-tableHeaderVisualStyle theme isSorted =-  let btn = themeButton theme-      accent = themeAccent theme-      headerBg = lerpColor (styleBg (themePanel theme)) (styleBg btn) 0.55-   in btn-        { styleBg = headerBg-        , styleHoverBg = lerpColor headerBg accent 0.18-        , styleActiveBg = lerpColor headerBg accent 0.28-        , styleFg = if isSorted then styleFg btn else themeMuted theme-        , styleBorderWidth = 0-        , styleCornerRadius = 0-        }--paintTabHeader :: DrawArena -> Theme -> Int -> Bool -> Style -> Float -> Float -> Float -> Float -> IO ()-paintTabHeader da theme styleIdx isActive style x y w h = do-  let rect = Rect x y w h-      r = max 0 (styleCornerRadius style)-      bg = styleBg style-  if isActive-    then case styleIdx `mod` 4 of-      1 -> pushRoundedRect da rect r bg-      2 -> do-        pushRoundedRect da rect r bg-        strokeStyledRect da style rect-      _ -> do-        pushRoundedRect da rect r bg-        pushRoundedStroke da (Rect x y w (h + 1)) (min r (min (w / 2) (h / 2))) 1 (styleBorder (themePanel theme))-        pushRect da (Rect x (y + h - 2) w 2) (themeAccent theme)-    else when (bg /= colorRGBA 0 0 0 0) $ pushRoundedRect da rect r bg--paintTableHeader :: DrawArena -> Theme -> Bool -> Style -> Float -> Float -> Float -> Float -> IO ()-paintTableHeader da theme isSorted style x y w h = do-  pushRect da (Rect x y w h) (styleBg style)-  when isSorted $-    pushRect da (Rect x (y + h - 2) w 2) (themeAccent theme)--widgetVisualStyle :: Context -> NodeType -> NodeIdx -> IO Style-widgetVisualStyle ctx nt idx = do-  wid <- getWidgetId (ctxNodeArena ctx) idx-  val <- getNodeValue (ctxNodeArena ctx) idx-  hot <- readIORef (ctxHotId ctx)-  active <- readIORef (ctxActiveId ctx)-  focus <- readIORef (ctxFocusId ctx)-  animT <- getAnimationValue ctx wid-  -- Only these node types consult the floating ancestor; skip the parent-  -- walk for the common panel/text/button path.-  let modalAware = nt == NodeCheckbox || nt == NodeRadio || nt == NodeTree || nt == NodeSlider-  mFloat <- if modalAware then floatingAncestor ctx idx else pure Nothing-  styleIdx <--    if nt == NodeButton || nt == NodeTree-      then getStyleIdx (ctxNodeArena ctx) idx-      else pure 0-  let (isClose, isTab, isTable) =-        if nt == NodeButton-          then buttonFlagsFromStyle styleIdx-          else (False, False, False)-      isMenu = nt == NodeButton && (isMenuItemStyle styleIdx || isMenuBarStyle styleIdx)-  theme <- nodeTheme ctx idx-  let isFocus = focus == wid-      isHot = wid == hot-      focusBorder s = if isFocus then s {styleBorder = themeAccent theme} else s-      base =-        case nt of-          NodeTextInput -> focusBorder (themeInput theme)-          NodeTextArea -> focusBorder (themeInput theme)-          NodeSelect -> focusBorder (themeButton theme)-          NodeColorPicker -> focusBorder (themeInput theme)-          NodeSlider -> clearStyle (themeInput theme)-          NodeCheckbox -> clearStyle (themeButton theme)-          NodeRadio -> clearStyle (themeButton theme)-          NodeTree ->-            let btn = themeButton theme-                accent = themeAccent theme-                unselectedBg =-                  case stripeColor theme (treeDecodeStripe styleIdx) of-                    Just c -> c-                    Nothing -> styleBg (themePanel theme)-             in if val > 0.5-                  then-                    btn-                      { styleBg = lerpColor unselectedBg accent 0.25-                      , styleHoverBg = lerpColor unselectedBg accent 0.35-                      , styleActiveBg = lerpColor unselectedBg accent 0.45-                      , styleBorderWidth = 0-                      , styleCornerRadius = 0-                      }-                  else-                    btn-                      { styleBg = unselectedBg-                      , styleHoverBg = lerpColor unselectedBg accent 0.12-                      , styleActiveBg = lerpColor unselectedBg accent 0.22-                      , styleBorderWidth = 0-                      , styleCornerRadius = 0-                      }-          NodeButton-            | isMenu -> menuItemVisualStyle theme val-            | isClose -> closeButtonStyle theme isHot animT-            | isTab -> tabHeaderVisualStyle theme (buttonVisualStyle styleIdx `mod` 4) (val > 0.5)-            | isTable -> tableHeaderVisualStyle theme (val > 0.5)-            | val > 0.5 ->-                (themeButton theme)-                  { styleBg = themeAccent theme-                  , styleHoverBg = themeAccent theme-                  , styleFg = themeOnAccent theme-                  , styleBorder = themeAccent theme-                  }-          _ -> themeButton theme-      widgetBase =-        case mFloat of-          Just NodeModal | modalAware -> overlayModalStyle theme-          _ -> base-      bg-        | nt == NodeTextInput, isFocus = styleActiveBg widgetBase-        | nt == NodeTextArea, isFocus = styleActiveBg widgetBase-        | hashWidgetId wid == hashWidgetId active = styleActiveBg widgetBase-        | nt == NodeCheckbox || nt == NodeRadio || nt == NodeSlider || isClose = styleBg widgetBase-        | isMenu = if isHot then styleHoverBg widgetBase else styleBg widgetBase-        | otherwise = hoverBackground widgetBase animT isHot-  -- Idle widgets (no hover/active tint change) reuse the base style record-  -- rather than allocating a fresh Style through a record update.-  pure $! if bg == styleBg widgetBase then widgetBase else widgetBase {styleBg = bg}--hoverBackground :: Style -> Float -> Bool -> Color-hoverBackground base val isHot-  | styleBg base == styleHoverBg base = styleBg base-  | isHot = lerpColor (styleBg base) (styleHoverBg base) (if val > 0 then val else 1)-  | otherwise = lerpColor (styleBg base) (styleHoverBg base) val--{-# INLINE fillStyledRect #-}-fillStyledRect :: DrawArena -> Style -> Rect -> IO ()-fillStyledRect da style rect =-  if styleCornerRadius style <= 0-    then pushRect da rect (styleBg style)-    else pushRoundedRect da rect (styleCornerRadius style) (styleBg style)--{-# INLINE strokeStyledRect #-}-strokeStyledRect :: DrawArena -> Style -> Rect -> IO ()-strokeStyledRect da style rect@(Rect _ _ w h) =-  when (styleBorderWidth style > 0) $ do-    let rr = max 0 (min (styleCornerRadius style) (min (w / 2) (h / 2)))-    pushRoundedStroke da rect rr (max 1 (styleBorderWidth style)) (styleBorder style)---- | A style's fill, then its border.-{-# INLINE paintStyledRect #-}-paintStyledRect :: DrawArena -> Style -> Rect -> IO ()-paintStyledRect da style rect = do-  fillStyledRect da style rect-  strokeStyledRect da style rect--overlayMenuStyle :: Theme -> Style-overlayMenuStyle theme =-  let panel = themePanel theme-      hover =-        if styleHoverBg panel == styleBg panel-          then styleHoverBg (themeButton theme)-          else styleHoverBg panel-   in panel-        { styleCornerRadius = 2-        , styleBorderWidth = 1-        , styleHoverBg = hover-        , styleActiveBg = lerpColor (styleBg panel) (themeAccent theme) 0.22-        }--overlayWindowStyle :: Theme -> Style-overlayWindowStyle theme = (themeFloatingWindow theme) {styleCornerRadius = 2, styleBorderWidth = 1}--overlayModalStyle :: Theme -> Style-overlayModalStyle theme = (overlayMenuStyle theme) {styleCornerRadius = 2, styleBorderWidth = 1}---- | Panel behind menus, dropdowns and floating windows: the theme's offset--- shadow, then the styled fill and border.-paintMenuPanel :: DrawArena -> Theme -> Style -> Rect -> IO ()-paintMenuPanel da theme style rect@(Rect x y w h) = do-  when (colorA (themeShadow theme) > 0) $-    pushRoundedRect da (Rect (x + 3) (y + 3) w h) (styleCornerRadius style) (themeShadow theme)-  paintStyledRect da style rect---- | Accent marker at a menu row's left edge, inset from its top and bottom.-paintMenuAccent :: DrawArena -> Theme -> Rect -> IO ()-paintMenuAccent da theme (Rect x y _ h) =-  pushRoundedRect-    da-    (Rect x (y + menuAccentInset) menuAccentW (max 0 (h - 2 * menuAccentInset)))-    1-    (themeAccent theme)---- | Scrollbar track and thumb, each rounded to at most 4px.-paintScrollBarLayout :: DrawArena -> Color -> Color -> ScrollBarLayout -> IO ()-paintScrollBarLayout da trackCol thumbCol layout = do-  pill (sbTrack layout) trackCol-  pill (sbThumb layout) thumbCol-  where-    pill r@(Rect _ _ rw rh) = pushRoundedRect da r (min 4 (min rw rh / 2))--imageIdFromText :: Text -> Int-imageIdFromText txt =-  case TR.decimal txt of-    Right (n, rest) | T.null rest, n > 0 -> n-    _ -> 0
− lib/NanoUI/Frame/Cursor.hs
@@ -1,363 +0,0 @@-{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Cursor-  ( UiCursorKind (..)-  , uiCursorKind-  , pointerCursorWanted-  , cursorKindIs-  ) where--import Data.IORef (readIORef)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (fromMaybe, isJust)-import NanoUI.Context-  ( Context (..)-  , CustomDrawContext (..)-  , WidgetStore (..)-  , getFocusId-  , getHotId-  , getScrollDrag-  , getStore-  , intKey-  , isDisabled-  , isSelectOpen-  , lookupCustomCursor-  , widgetTheme-  , getsInteraction-  , InteractionState (..)-  )-import NanoUI.Font (FontMetrics, sliderHandleSlack, sliderTrackBounds)-import NanoUI.Frame.Hit (findNodeByWidgetId, nodePointVisible, scrollHitRect)-import NanoUI.Frame.Scroll (ScrollBarLayout (..), scrollBarsFor)-import NanoUI.Frame.Select (overlayMenuOwnerAt, selectDropRect)-import NanoUI.Frame.TextArea.Content (isMouseOnTextAreaScrollBarAt)-import NanoUI.Frame.TextEdit.Menu (textEditMenuCursorKind, textFieldWidgetAtMouse)-import NanoUI.Frame.TextInput (nodeTextFieldGeom, searchClearHit)-import NanoUI.Frame.Window (windowResizeCursorKind)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input-  ( Input (..)-  , UiCursorKind (..)-  , grabDragKind-  , grabHoverKind-  , inputMouseDown-  , inputMousePos-  )-import NanoUI.Layout.Arena-  ( DirTag (..)-  , NodeIdx-  , NodeType (..)-  , findChildM-  , findNodeM-  , getDirection-  , getNodeType-  , getOptions-  , getParent-  , getRect-  , getStyleIdx-  , getWidgetId-  , isScrollNode-  )-import NanoUI.Types (Rect (..), V2 (..), rectContains)-import NanoUI.WidgetText (numericStepperRects, textInputNumericMode)-import NanoUI.WidgetText (isTableHeaderStyle)--uiCursorKind :: Context -> Input -> IO UiCursorKind-uiCursorKind ctx inp = do-  -- The first query with an opinion wins; later ones do not run.-  mKind <--    foldr-      (\query rest -> query >>= maybe rest (pure . Just))-      (pure Nothing)-      [ textEditMenuCursorKind ctx inp-      , selectDropdownCursorKind ctx inp-      , windowResizeCursorKind ctx inp-      , tableColResizeCursorKind ctx inp-      , scrollThumbCursorKind ctx inp-      , textFieldHoverCursorKind ctx inp-      ]-  case mKind of-    Just k -> pure k-    Nothing -> do-      let mouse = inputMousePos inp-      active <- readIORef (ctxActiveId ctx)-      activeKind <- cursorKindAt ctx active mouse inp-      if activeKind /= UiCursorDefault-        then pure activeKind-        else do-          hot <- getHotId ctx-          cursorKindAt ctx hot mouse inp--selectDropdownCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)-selectDropdownCursorKind ctx inp = do-  let mouse = inputMousePos inp-      na = ctxNodeArena ctx-  dropPress <- getsInteraction ctx isSelectDropPress-  store <- getStore ctx-  mSel <--    findNodeM na $ \idx -> do-      nt <- getNodeType na idx-      if nt /= NodeSelect-        then pure False-        else do-          wid <- getWidgetId na idx-          opts <- getOptions na idx-          (x, y, w, h) <- getRect na idx-          let dropRect = selectDropRect x y w h (length opts)-          pure ((isSelectOpen store (intKey wid) || dropPress) && rectContains dropRect mouse)-  if isJust mSel-    then pure (Just UiCursorPointer)-    else-      -- A focused combo's dropdown (visible while its field holds focus) is-      -- not a select: pointer over its menu like the select's. The text-input-      -- menu case inside overlayMenuOwnerAt is unreachable here, since-      -- textEditMenuCursorKind runs first in uiCursorKind.-      (UiCursorPointer <$) <$> overlayMenuOwnerAt ctx mouse--scrollThumbCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)-scrollThumbCursorKind ctx inp = do-  mDrag <- getScrollDrag ctx-  if inputMouseDown inp && isJust mDrag-    then pure (Just UiCursorGrabbing)-    else do-      onThumb <- scrollThumbHit ctx (inputMousePos inp)-      pure (if onThumb then Just (grabHoverKind True inp) else Nothing)---- Field well, not the label. Independent of focus and hot. A search field's--- clear button raises the pointer cursor; everywhere else over a field is text.-textFieldHoverCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)-textFieldHoverCursorKind ctx inp = do-  let mouse = inputMousePos inp-  mWid <- textFieldWidgetAtMouse ctx mouse-  case mWid of-    Nothing -> pure Nothing-    Just wid -> do-      onClear <- searchClearHit ctx wid mouse-      onStepper <- numericStepperHit ctx wid mouse-      pure (Just (if onClear || onStepper then UiCursorPointer else UiCursorText))---- | Whether the pointer is over a numeric field's stepper, which takes the--- pointer cursor rather than the text cursor.-numericStepperHit :: Context -> WidgetId -> V2 -> IO Bool-numericStepperHit ctx wid mouse =-  findNodeByWidgetId ctx wid >>= \case-    Nothing -> pure False-    Just idx -> do-      si <- getStyleIdx (ctxNodeArena ctx) idx-      if not (textInputNumericMode si)-        then pure False-        else do-          (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-          let (up, down) = numericStepperRects x y w h-          pure (rectContains up mouse || rectContains down mouse)--scrollThumbHit :: Context -> V2 -> IO Bool-scrollThumbHit ctx mouse =-  fmap isJust . findNodeM na $ \idx -> do-    nt <- getNodeType na idx-    if nt /= NodeTextArea && not (isScrollNode nt)-      then pure False-      else do-        wid <- getWidgetId na idx-        any (\(_, layout, _) -> rectContains (sbThumb layout) mouse) <$> scrollBarsFor ctx idx wid-  where-    na = ctxNodeArena ctx--cursorKindAt :: Context -> WidgetId -> V2 -> Input -> IO UiCursorKind-cursorKindAt ctx wid mouse inp-  | hashWidgetId wid == 0 = pure UiCursorDefault-  | otherwise = do-      disabled <- isDisabled ctx wid-      if disabled-        then pure UiCursorDefault-        else do-          mCursorFn <- lookupCustomCursor ctx wid-          case mCursorFn of-            Just cursorFn -> do-              visible <- widgetVisibleAt ctx wid mouse-              if not visible-                then pure UiCursorDefault-                else do-                  active <- readIORef (ctxActiveId ctx)-                  hot <- getHotId ctx-                  focused <- (== wid) <$> getFocusId ctx-                  theme <- widgetTheme ctx wid-                  let cdc =-                        CustomDrawContext-                          { cdcHovered = hot == wid-                          , cdcPressed = active == wid-                          , cdcFocused = focused-                          , cdcActive = active == wid-                          , cdcDisabled = disabled-                          , cdcTheme = theme-                          , cdcFont = ctxFontMetrics ctx-                          }-                  pure (cursorFn cdc)-            Nothing -> do-              -- Resolve the node through the arena's id index rather than-              -- building a type table of every widget for two lookups.-              mNodeType <- findNodeByWidgetId ctx wid >>= traverse (getNodeType (ctxNodeArena ctx))-              case mNodeType of-                Just NodeButton -> widgetPointerCursor ctx wid mouse-                Just NodeCheckbox -> widgetPointerCursor ctx wid mouse-                Just NodeRadio -> widgetPointerCursor ctx wid mouse-                Just NodeTree -> widgetPointerCursor ctx wid mouse-                Just NodeSelect -> selectCursorKind ctx wid mouse-                Just NodeColorPicker -> pure UiCursorPointer-                Just NodeTextInput -> textInputCursorKind ctx wid mouse-                Just NodeTextArea -> textAreaCursorKind ctx wid mouse-                Just NodeSlider -> sliderCursorKind ctx wid mouse inp-                _ -> pure UiCursorDefault--selectCursorKind :: Context -> WidgetId -> V2 -> IO UiCursorKind-selectCursorKind ctx wid mouse = do-  visible <- widgetVisibleAt ctx wid mouse-  if not visible-    then pure UiCursorDefault-    else do-      mrect <- scrollHitRect ctx wid-      pure (if maybe False (`rectContains` mouse) mrect then UiCursorPointer else UiCursorDefault)--widgetVisibleAt :: Context -> WidgetId -> V2 -> IO Bool-widgetVisibleAt ctx wid mouse = do-  mIdx <- findNodeByWidgetId ctx wid-  case mIdx of-    Nothing -> pure False-    Just idx -> nodePointVisible ctx idx mouse--widgetPointerCursor :: Context -> WidgetId -> V2 -> IO UiCursorKind-widgetPointerCursor ctx wid mouse = do-  visible <- widgetVisibleAt ctx wid mouse-  pure (if visible then UiCursorPointer else UiCursorDefault)--sliderCursorKind :: Context -> WidgetId -> V2 -> Input -> IO UiCursorKind-sliderCursorKind ctx wid mouse inp = do-  active <- readIORef (ctxActiveId ctx)-  if active == wid && inputMouseDown inp-    then pure UiCursorGrabbing-    else do-      visible <- widgetVisibleAt ctx wid mouse-      if not visible-        then pure UiCursorDefault-        else do-          mrect <- scrollHitRect ctx wid-          pure $-            case mrect of-              Nothing -> UiCursorDefault-              Just (Rect x y w h) ->-                let Rect tx ty tw th = sliderTrackBounds x y w h-                    hitRect = Rect tx (ty - sliderHandleSlack) tw (th + 2 * sliderHandleSlack)-                 in grabDragKind (rectContains hitRect mouse) False inp--textInputCursorKind :: Context -> WidgetId -> V2 -> IO UiCursorKind-textInputCursorKind ctx wid mouse = do-  visible <- widgetVisibleAt ctx wid mouse-  if not visible-    then pure UiCursorDefault-    else do-      mIdx <- findNodeByWidgetId ctx wid-      mrect <- scrollHitRect ctx wid-      case (mIdx, mrect) of-        (Just idx, Just (Rect x y w h)) -> do-          (field, _) <- nodeTextFieldGeom ctx idx x y w h-          onStepper <- numericStepperHit ctx wid mouse-          pure $-            if onStepper-              then UiCursorPointer-              else if rectContains field mouse then UiCursorText else UiCursorDefault-        _ -> pure UiCursorDefault--textAreaCursorKind :: Context -> WidgetId -> V2 -> IO UiCursorKind-textAreaCursorKind ctx wid mouse = do-  mIdx <- findNodeByWidgetId ctx wid-  case mIdx of-    Nothing -> pure UiCursorDefault-    Just idx -> do-      onScroll <- isMouseOnTextAreaScrollBarAt ctx idx mouse-      if onScroll-        then pure UiCursorDefault-        else-          textFieldCursorKind ctx wid mouse $ \_ x y w h ->-            Rect x y w h--textFieldCursorKind ::-  Context ->-  WidgetId ->-  V2 ->-  (FontMetrics -> Float -> Float -> Float -> Float -> Rect) ->-  IO UiCursorKind-textFieldCursorKind ctx wid mouse fieldAt = do-  visible <- widgetVisibleAt ctx wid mouse-  if not visible-    then pure UiCursorDefault-    else do-      mrect <- scrollHitRect ctx wid-      pure $-        case mrect of-          Just (Rect x y w h)-            | rectContains (fieldAt (ctxFontMetrics ctx) x y w h) mouse -> UiCursorText-          _ -> UiCursorDefault--tableColResizeCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)-tableColResizeCursorKind ctx inp = do-  store <- getStore ctx-  let dragging = any (\n -> n <= -1000 && n > -2000) (IM.elems (storeInt store))-      na = ctxNodeArena ctx-      V2 mx my = inputMousePos inp-  if inputMouseDown inp && dragging-    then pure (Just UiCursorEwResize)-    else do-      mEdge <--        findNodeM na $ \idx -> do-          nt <- getNodeType na idx-          if nt /= NodeButton-            then pure False-            else do-              si <- getStyleIdx na idx-              if not (isTableHeaderStyle si)-                then pure False-                else do-                  (x, y, w, h) <- getRect na idx-                  -- The resize cursor spans the whole column height-                  -- (header plus body cells down to the body-                  -- scroller's bottom edge), matching the drag grab-                  -- zone: tableBodyScrollerBottom locates the same-                  -- body scroller whose rect the grab zone anchors-                  -- on (its prev-frame value, readable at build-                  -- time), so the two zones cannot disagree.-                  yBot <- fromMaybe (y + h) <$> tableBodyScrollerBottom ctx idx-                  pure (my >= y && my <= yBot && abs (mx - (x + w)) <= 4 && w > 0 && h > 0)-      pure (UiCursorEwResize <$ mEdge)---- | Bottom edge of a table's body scroller, located structurally from one--- of its header buttons: walk up to the first ancestor that has a direct--- Column-direction scroll-container child (the pane column built by--- tableSplitPanes) and take that child's rect bottom. Runs post-solve, so--- the rect is current-frame. Nothing when no such scroller exists (the--- caller falls back to the header button's own bottom).-tableBodyScrollerBottom :: Context -> NodeIdx -> IO (Maybe Float)-tableBodyScrollerBottom ctx = goUp-  where-    na = ctxNodeArena ctx-    goUp i = do-      p <- getParent na i-      if p < 0-        then pure Nothing-        else do-          mScroller <--            findChildM na p $ \c -> do-              nt <- getNodeType na c-              if isScrollNode nt-                then (== DirColumn) <$> getDirection na c-                else pure False-          case mScroller of-            Just sc -> do-              (_, sy, _, sh) <- getRect na sc-              pure (Just (sy + sh))-            Nothing -> goUp p--pointerCursorWanted :: Context -> Input -> IO Bool-pointerCursorWanted ctx inp = cursorKindIs ctx inp UiCursorPointer--cursorKindIs :: Context -> Input -> UiCursorKind -> IO Bool-cursorKindIs ctx inp want = (== want) <$> uiCursorKind ctx inp
− lib/NanoUI/Frame/Focus.hs
@@ -1,125 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Focus traversal and modal focus constraints.-module NanoUI.Frame.Focus-  ( filterModalFocusables-  , constrainFocusToModal-  , syncWidgetLabels-  , tabNext-  , tabNextFocusables-  ) where--import Control.Monad (filterM, unless, when)-import Data.IORef (readIORef, writeIORef)-import Data.Primitive.PrimArray (readPrimArray)-import qualified Data.IntMap.Strict as IM-import NanoUI.Context (Context (..), WidgetStore (..), getStore, intBool, intKey)-import NanoUI.Frame.Hit (widgetIdInSubtree)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Layout.Arena-  ( NodeType (NodeCheckbox, NodeRadio, NodeTree)-  , forNodes_-  , getNodeType-  , getParent-  , getStyleIdx-  , getWidgetId-  , setNodeValue-  , topModalNode-  )-import NanoUI.WidgetText (treeDecodeStyle)--tabNext :: WidgetId -> [WidgetId] -> Bool -> WidgetId-tabNext cur ids shift =-  case ids of-    [] -> WidgetId 0-    first : rest ->-      let lastId !prev [] = prev-          lastId _ (x : xs) = lastId x xs-          search _ [] = first-          search prev (x : xs)-            | x == cur = if shift then prev else case xs of-                next : _ -> next-                [] -> first-            | otherwise = search x xs-       in if cur == first && shift-            then lastId first rest-            else search first ids---- | Scan the live focus buffer. Skip zero ids. No freeze or list copy.-tabNextFocusables :: Context -> WidgetId -> Bool -> IO WidgetId-tabNextFocusables ctx cur shift = do-  n <- readIORef (ctxFocusablesCount ctx)-  arr <- readIORef (ctxFocusables ctx)-  let at i = readPrimArray arr i-      findCur !i-        | i >= n = pure Nothing-        | otherwise = do-            w <- at i-            if w == cur && hashWidgetId w /= 0 then pure (Just i) else findCur (i + 1)-      firstLive !i-        | i >= n = pure (WidgetId 0)-        | otherwise = do-            w <- at i-            if hashWidgetId w /= 0 then pure w else firstLive (i + 1)-      step !i !left-        | left <= 0 = firstLive 0-        | otherwise = do-            let j = if shift then (i - 1 + n) `mod` n else (i + 1) `mod` n-            w <- at j-            if hashWidgetId w /= 0 then pure w else step j (left - 1)-  if n <= 0-    then pure (WidgetId 0)-    else do-      found <- findCur 0-      case found of-        Nothing -> firstLive 0-        Just i -> step i n--filterModalFocusables :: Context -> [WidgetId] -> IO [WidgetId]-filterModalFocusables ctx ids = do-  -- Searching the arena once per focusable makes a large modal's Tab traversal-  -- quadratic. Resolve its root once, then test ancestry for each widget.-  top <- topModalNode (ctxNodeArena ctx)-  case top of-    Nothing -> pure ids-    Just modal -> filterM (widgetIdInSubtree ctx modal) ids--constrainFocusToModal :: Context -> IO ()-constrainFocusToModal ctx = do-  top <- topModalNode (ctxNodeArena ctx)-  case top of-    Nothing -> pure ()-    Just modal -> do-      focus <- readIORef (ctxFocusId ctx)-      when (hashWidgetId focus /= 0) $ do-        ok <- widgetIdInSubtree ctx modal focus-        unless ok $ writeIORef (ctxFocusId ctx) (WidgetId 0)--syncWidgetLabels :: Context -> IO ()-syncWidgetLabels ctx = do-  store <- getStore ctx-  let na = ctxNodeArena ctx-  forNodes_ na $ \idx -> do-    nt <- getNodeType na idx-    wid <- getWidgetId na idx-    let key = intKey wid-    case nt of-      NodeCheckbox ->-        -- Only sync when the widget owns stored state; otherwise keep the-        -- value set from the initial argument during the UI pass.-        case IM.lookup key (storeInt store) of-          Just v -> setNodeValue na idx (if intBool v then 1 else 0)-          Nothing -> pure ()-      _-        -- A radio's option index is its style; a tree row packs its node-        -- index there. Either is selected when its group's stored value names it.-        | nt == NodeRadio || nt == NodeTree -> do-            parent <- getParent na idx-            si <- getStyleIdx na idx-            groupWid <- getWidgetId na parent-            let own-                  | nt == NodeTree, (nodeIdx, _, _, _) <- treeDecodeStyle si = nodeIdx-                  | otherwise = si-                selected = IM.findWithDefault own (intKey groupWid) (storeInt store)-            setNodeValue na idx (if selected == own then 1 else 0)-      _ -> pure ()
− lib/NanoUI/Frame/Hit.hs
@@ -1,161 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Layout hit testing for modals, windows, and overlay stacking.-module NanoUI.Frame.Hit-  ( findNodeByWidgetId-  , findNodeByKey-  , modalTreeOpen-  , nodeInSubtree-  , widgetIdInSubtree-  , overlayHitAllowed-  , topmostOverlayAtMouse-  , topmostModalAtMouse-  , widgetOverlayAllowed-  , scrollHitRect-  , nodePointVisible-  , nodeClippedHit-  , nodeInteractionHit-  ) where--import Data.Maybe (isJust)-import NanoUI.Context (Context (..), getPrevRect, getPrevClipRect)-import NanoUI.Id (WidgetId)-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (NodeModal, NodePopup, NodeScrollContainer, NodeWindow)-  , findNodeRevM-  , getClipRect-  , getNodeType-  , getParent-  , getRect-  , getWidgetId-  , lookupNodeByKey-  , lookupNodeByWidgetId-  , topModalNode-  )-import NanoUI.Types (Rect (..), V2 (..), rectContains, rectH, rectW)--findNodeByWidgetId :: Context -> WidgetId -> IO (Maybe NodeIdx)-findNodeByWidgetId ctx wid = lookupNodeByWidgetId (ctxNodeArena ctx) wid--findNodeByKey :: Context -> Int -> IO (Maybe NodeIdx)-findNodeByKey ctx k = lookupNodeByKey (ctxNodeArena ctx) k--modalTreeOpen :: Context -> IO Bool-modalTreeOpen ctx = do-  top <- topModalNode (ctxNodeArena ctx)-  pure (isJust top)--nodeInSubtree :: Context -> NodeIdx -> NodeIdx -> IO Bool-nodeInSubtree ctx idx top = go idx-  where-    go i-      | i < 0 = pure False-      | i == top = pure True-      | otherwise = do-          parent <- getParent (ctxNodeArena ctx) i-          go parent---- | Membership predicate for an already-resolved subtree root. Callers--- filtering many widgets can resolve the root once for the whole operation.-widgetIdInSubtree :: Context -> NodeIdx -> WidgetId -> IO Bool-widgetIdInSubtree ctx root wid = do-  node <- findNodeByWidgetId ctx wid-  maybe (pure False) (\idx -> nodeInSubtree ctx idx root) node--overlayHitAllowed :: Context -> NodeIdx -> V2 -> IO Bool-overlayHitAllowed ctx idx mouse = do-  mModal <- topModalNode (ctxNodeArena ctx)-  case mModal of-    Just top -> nodeInSubtree ctx idx top-    Nothing -> do-      mTop <- topmostOverlayAtMouse ctx mouse-      case mTop of-        Nothing -> pure True-        Just tidx -> nodeInSubtree ctx idx tidx--topmostOverlayAtMouse :: Context -> V2 -> IO (Maybe NodeIdx)-topmostOverlayAtMouse ctx mouse =-  topmostFloatingAtMouse ctx mouse (\nt -> nt == NodeWindow || nt == NodePopup)--topmostModalAtMouse :: Context -> V2 -> IO (Maybe NodeIdx)-topmostModalAtMouse ctx mouse =-  topmostFloatingAtMouse ctx mouse (== NodeModal)--topmostFloatingAtMouse :: Context -> V2 -> (NodeType -> Bool) -> IO (Maybe NodeIdx)-topmostFloatingAtMouse ctx mouse wanted =-  findNodeRevM (ctxNodeArena ctx) $ \idx -> do-    nt <- getNodeType (ctxNodeArena ctx) idx-    if not (wanted nt)-      then pure False-      else do-        (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-        pure (w > 0 && h > 0 && rectContains (Rect x y w h) mouse)--widgetOverlayAllowed :: Context -> WidgetId -> IO Bool-widgetOverlayAllowed ctx wid = do-  top <- topModalNode (ctxNodeArena ctx)-  case top of-    Nothing -> pure True-    Just modal -> widgetIdInSubtree ctx modal wid---- Prev rects are visual space (snapshot after applyScrollOffsets).-scrollHitRect :: Context -> WidgetId -> IO (Maybe Rect)-scrollHitRect = getPrevRect--{-# INLINE nodePointVisible #-}-nodePointVisible :: Context -> NodeIdx -> V2 -> IO Bool-nodePointVisible ctx idx mouse = do-  (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-  let vis = Rect x y w h-  if not (w > 0 && h > 0 && rectContains vis mouse)-    then pure False-    else do-      mClip <- getClipRect (ctxNodeArena ctx) idx-      pure (maybe True (`rectContains` mouse) mClip)--{-# INLINE nodeClippedHit #-}-nodeClippedHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool-nodeClippedHit ctx idx rect mouse = do-  if not (rectW rect > 0 && rectH rect > 0 && rectContains rect mouse)-    then pure False-    else do-      na <- pure (ctxNodeArena ctx)-      mLive <- getClipRect na idx-      mClip <--        case mLive of-          Just r -> pure (Just r)-          Nothing -> do-            wid <- getWidgetId na idx-            getPrevClipRect ctx wid-      pure (maybe True (`rectContains` mouse) mClip)---- | Hit test during UI build (before applyScrollOffsets). Uses prev rects and--- scroll viewport clips only, not per-node live clips.-{-# INLINE nodeInteractionHit #-}-nodeInteractionHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool-nodeInteractionHit ctx idx rect mouse = do-  if not (rectW rect > 0 && rectH rect > 0 && rectContains rect mouse)-    then pure False-    else scrollViewportHit ctx idx mouse--scrollViewportHit :: Context -> NodeIdx -> V2 -> IO Bool-scrollViewportHit ctx idx mouse = go idx-  where-    go i-      | i <= 0 = pure True-      | otherwise = do-          p <- getParent (ctxNodeArena ctx) i-          if p < 0-            then pure True-            else do-              nt <- getNodeType (ctxNodeArena ctx) p-              if nt == NodeScrollContainer-                then do-                  wid <- getWidgetId (ctxNodeArena ctx) p-                  mClip <- getPrevClipRect ctx wid-                  case mClip of-                    Nothing -> go p-                    Just clip ->-                      if rectContains clip mouse then go p else pure False-                else go p
− lib/NanoUI/Frame/Input.hs
@@ -1,337 +0,0 @@-{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Input-  ( finalizeTabFocus-  , refreshHover-  , armPointerPress-  , disarmPointerPress-  , finalizePointerPress-  , finalizePointerRelease-  , finalizeTextInputFocus-  , finalizeSelectFocus-  , findTopWidgetUnderMouse-  , isInteractiveNode-  ) where--import Control.Applicative ((<|>))-import Control.Monad (unless, when)-import Data.IORef (readIORef, writeIORef)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (isJust, isNothing)-import NanoUI.Context-  ( Context (..)-  , TextInputMenu (..)-  , WidgetStore (..)-  , damageWidget-  , getFocusables-  , getMenuPointerGesture-  , getStore-  , getTextInputMenu-  , intKey-  , isDisabled-  , markDirty-  , pointerBlockedByOverlay-  , setAnimationValue-  , setMenuPointerGesture-  , setStore-  , setTextInputMenu-  , startAnimation-  )-import NanoUI.Frame.Focus (filterModalFocusables, tabNext, tabNextFocusables)-import NanoUI.Frame.Hit-  ( findNodeByWidgetId-  , modalTreeOpen-  , nodeClippedHit-  , nodeInteractionHit-  , overlayHitAllowed-  , scrollHitRect-  )-import NanoUI.Frame.Redraw (probeHotId)-import NanoUI.Frame.Select (findSelectUnderMouse, overlayMenuOwnerAt)-import NanoUI.Frame.Spans (widgetHitRect)-import NanoUI.Frame.TextEdit (collapseTextFieldSelection)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input-  ( Input (..)-  , Key (..)-  , inputKeysElem-  , inputModifiers-  , inputMousePos-  , inputMousePressed-  , inputMouseReleased-  , inputMouseRightPressed-  , inputMouseRightReleased-  , modShift-  )-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , findNodeM-  , foldNodesM-  , getNodeType-  , getParent-  , getRect-  , getStyleIdx-  , getWidgetId-  )-import NanoUI.Monad (whenM)-import NanoUI.Types (DamageBounds (..), Rect (..), V2 (..), defaultDamageSlop, rectContains, rectH, rectW)-import NanoUI.WidgetText (buttonVisualStyle, isMenuBarStyle, isMenuItemStyle, isTabButtonStyle)--finalizeTabFocus :: Context -> Input -> IO ()-finalizeTabFocus ctx inp =-  when (inputKeysElem KeyTab (inputKeys inp)) $ do-    open <- modalTreeOpen ctx-    let shift = modShift (inputModifiers inp)-    cur <- readIORef (ctxFocusId ctx)-    next <--      if not open-        then tabNextFocusables ctx cur shift-        else do-          focusables <- getFocusables ctx-          ids <- filterModalFocusables ctx (filter (/= WidgetId 0) focusables)-          pure (tabNext cur ids shift)-    when (hashWidgetId next /= 0) $ do-      -- Keyboard focus shows its ring until the next pointer press. Focus that-      -- stays put (a lone focusable) changes no focus rect, so damage it here.-      wasVisible <- readIORef (ctxFocusVisible ctx)-      when (next == cur && not wasVisible) $-        damageWidget ctx next (DamageInflated defaultDamageSlop)-      writeIORef (ctxFocusId ctx) next-      writeIORef (ctxFocusVisible ctx) True-      markDirty ctx---- Flat menu buttons never animate: their hover highlight snaps on and off.-isMenuButtonWidget :: Context -> WidgetId -> IO Bool-isMenuButtonWidget ctx wid-  | hashWidgetId wid == 0 = pure False-  | otherwise =-      findNodeByWidgetId ctx wid >>= \case-        Nothing -> pure False-        Just idx -> do-          nt <- getNodeType (ctxNodeArena ctx) idx-          if nt /= NodeButton-            then pure False-            else do-              si <- getStyleIdx (ctxNodeArena ctx) idx-              pure (isMenuItemStyle si || isMenuBarStyle si)--refreshHover :: Context -> Input -> IO ()-refreshHover ctx inp = do-  prevHot <- readIORef (ctxLastHotId ctx)-  newHot <- probeHotId ctx (inputMousePos inp)-  writeIORef (ctxHotId ctx) newHot-  writeIORef (ctxLastHotId ctx) newHot-  when (prevHot /= newHot) $ do-    prevMenu <- isMenuButtonWidget ctx prevHot-    newMenu <- isMenuButtonWidget ctx newHot-    when (hashWidgetId prevHot /= 0 && not prevMenu) $ startAnimation ctx prevHot 1 0 0.12-    when (hashWidgetId newHot /= 0 && not newMenu) $ startAnimation ctx newHot 0 1 0.12---- | Remember where a press landed, before the UI builds: widgets resolve their--- click against this point, so a release that drifted onto a neighbour fires--- nowhere. Runs every frame; 'disarmPointerPress' clears it once the button--- comes up and the frame has consumed the release.-armPointerPress :: Context -> Input -> IO ()-armPointerPress ctx inp = do-  let here = Just (inputMousePos inp)-  when (inputMousePressed inp) $ writeIORef (ctxPressPos ctx) here-  when (inputMouseRightPressed inp) $ writeIORef (ctxRightPressPos ctx) here--disarmPointerPress :: Context -> Input -> IO ()-disarmPointerPress ctx inp = do-  when (inputMouseReleased inp) $ writeIORef (ctxPressPos ctx) Nothing-  when (inputMouseRightReleased inp) $ writeIORef (ctxRightPressPos ctx) Nothing---- Same walk as refreshHover: later nodes paint first, earlier widget hits win.-finalizePointerPress :: Context -> Input -> IO ()-finalizePointerPress ctx inp =-  when (inputMousePressed inp) $ do-    -- A pointer press hides the keyboard focus ring.-    writeIORef (ctxFocusVisible ctx) False-    gesture <- getMenuPointerGesture ctx-    if gesture-      then writeIORef (ctxActiveId ctx) (WidgetId 0)-      else do-        let mouse = inputMousePos inp-        mMenu <- overlayMenuOwnerAt ctx mouse-        case mMenu of-          Just _ -> do-            setMenuPointerGesture ctx True-            writeIORef (ctxActiveId ctx) (WidgetId 0)-          Nothing -> do-            mWid <- findTopWidgetUnderMouse ctx mouse isInteractiveNode-            case mWid of-              Nothing -> pure ()-              Just wid ->-                whenM (not <$> isDisabled ctx wid) $-                  writeIORef (ctxActiveId ctx) wid---- | The widget of a wanted type under @mouse@ that hover would pick: the--- first in arena order, since earlier siblings paint over later ones.-findTopWidgetUnderMouse :: Context -> V2 -> (NodeType -> Bool) -> IO (Maybe WidgetId)-findTopWidgetUnderMouse ctx mouse wanted = do-  let na = ctxNodeArena ctx-  mIdx <--    findNodeM na $ \idx -> do-      nt <- getNodeType na idx-      if not (wanted nt)-        then pure False-        else do-          (x, y, w, h) <- getRect na idx-          rect <- widgetHitRect ctx nt idx x y w h-          if rectW rect > 0 && rectH rect > 0-            then do-              hit <- nodeClippedHit ctx idx rect mouse-              if hit then overlayHitAllowed ctx idx mouse else pure False-            else pure False-  traverse (getWidgetId na) mIdx--isInteractiveNode :: NodeType -> Bool-isInteractiveNode nt =-  nt == NodeButton-    || nt == NodeCheckbox-    || nt == NodeRadio-    || nt == NodeTree-    || nt == NodeSlider-    || nt == NodeSelect-    || nt == NodeColorPicker-    || nt == NodeTextInput-    || nt == NodeTextArea-    || nt == NodeDrawing---- Clicks are finalized against solved layout rects; widgets only track press state.--- Radio/tab selection is written here. Clickable widgets use the same solved--- hit; if in-UI prev-rect tests missed, ctxClickedId fires next frame.-finalizePointerRelease :: Context -> Input -> IO ()-finalizePointerRelease ctx inp =-  when (inputMouseReleased inp) $ do-    let mouse = inputMousePos inp-        na = ctxNodeArena ctx-    gesture <- getMenuPointerGesture ctx-    mMenu <- overlayMenuOwnerAt ctx mouse-    if gesture || isJust mMenu-      then do-        writeIORef (ctxActiveId ctx) (WidgetId 0)-        setMenuPointerGesture ctx False-      else do-        active <- readIORef (ctxActiveId ctx)-        when (hashWidgetId active /= 0) $ do-          releasedClicked <- readIORef (ctxReleaseClickedId ctx)-          -- Every node carrying the active id takes the release; the first-          -- one decides whether the pointer came up over the widget.-          let release over idx = do-                wid <- getWidgetId na idx-                if wid /= active-                  then pure over-                  else do-                    nt <- getNodeType na idx-                    (x, y, w, h) <- getRect na idx-                    visible <- nodeClippedHit ctx idx (Rect x y w h) mouse-                    when visible $ do-                      case nt of-                        NodeRadio -> getStyleIdx na idx >>= setParentSelection ctx idx-                        NodeButton -> do-                          packed <- getStyleIdx na idx-                          when (isTabButtonStyle packed) $-                            setParentSelection ctx idx (buttonVisualStyle packed `div` 4)-                        _ -> pure ()-                      when (postsLayoutClick nt && releasedClicked /= active) $ do-                        uiHit <- inUiClickHit ctx active mouse-                        unless uiHit $ writeIORef (ctxClickedId ctx) active-                    pure (over <|> Just visible)-          releasedOver <- foldNodesM na release Nothing-          writeIORef (ctxActiveId ctx) (WidgetId 0)-          when (releasedOver == Just True) $-            setAnimationValue ctx active 1---- Radio options and tab buttons keep their selection on the parent group.-setParentSelection :: Context -> NodeIdx -> Int -> IO ()-setParentSelection ctx idx selected = do-  parent <- getParent (ctxNodeArena ctx) idx-  when (parent >= 0) $ do-    store <- getStore ctx-    groupWid <- getWidgetId (ctxNodeArena ctx) parent-    setStore ctx store {storeInt = IM.insert (intKey groupWid) selected (storeInt store)}--postsLayoutClick :: NodeType -> Bool-postsLayoutClick nt =-  nt == NodeButton || nt == NodeTree || nt == NodeSelect || nt == NodeCheckbox--inUiClickHit :: Context -> WidgetId -> V2 -> IO Bool-inUiClickHit ctx wid mouse = do-  disabled <- isDisabled ctx wid-  blocked <- pointerBlockedByOverlay ctx mouse-  if disabled || blocked-    then pure False-    else do-      mrect <- scrollHitRect ctx wid-      case mrect of-        Nothing -> pure False-        Just r ->-          findNodeByWidgetId ctx wid >>= \case-            Nothing -> pure (rectContains r mouse)-            Just idx -> nodeInteractionHit ctx idx r mouse---- Focus text inputs using solved layout rects so the caret appears on first press.--- A press on an open dropdown overlay (select menu or a focused combo's--- suggestions) must not clear focus first: the combo's dropdown is visible--- exactly while its field holds focus, and the select finalizers below need--- the owner still resolvable to route the pick.-finalizeTextInputFocus :: Context -> Input -> IO ()-finalizeTextInputFocus ctx inp =-  when (inputMousePressed inp) $ do-    mMenu <- getTextInputMenu ctx-    let mouse = inputMousePos inp-    mDrop <- overlayMenuOwnerAt ctx mouse-    let onMenu = maybe False (\menu -> rectContains (textInputMenuRect menu) mouse) mMenu-    when (not onMenu && isNothing mDrop) $ do-      prevFocus <- readIORef (ctxFocusId ctx)-      mFocused <- findTextInputUnderMouse ctx mouse-      case mFocused of-        Nothing -> do-          when (prevFocus /= WidgetId 0) $ markDirty ctx-          collapseTextFieldSelection ctx prevFocus-          writeIORef (ctxFocusId ctx) (WidgetId 0)-          setTextInputMenu ctx Nothing-        Just wid -> do-          writeIORef (ctxFocusId ctx) wid-          when (prevFocus /= wid) $ markDirty ctx--finalizeSelectFocus :: Context -> Input -> IO ()-finalizeSelectFocus ctx inp =-  when (inputMousePressed inp) $ do-    let mouse = inputMousePos inp-    mOpen <- findSelectUnderMouse ctx mouse-    -- A press on a select's own field that just closed its dropdown leaves no-    -- open dropdown under the pointer, but the select keeps focus all the same.-    mWid <- maybe (findTopWidgetUnderMouse ctx mouse (== NodeSelect)) (pure . Just) mOpen-    case mWid of-      Nothing -> pure ()-      Just wid ->-        whenM (not <$> isDisabled ctx wid) $ do-          prev <- readIORef (ctxFocusId ctx)-          writeIORef (ctxFocusId ctx) wid-          when (prev /= wid) $ markDirty ctx--findTextInputUnderMouse :: Context -> V2 -> IO (Maybe WidgetId)-findTextInputUnderMouse ctx mouse = do-  let na = ctxNodeArena ctx-  mIdx <--    findNodeM na $ \idx -> do-      nt <- getNodeType na idx-      if nt /= NodeTextInput && nt /= NodeTextArea-        then pure False-        else do-          (x, y, w, h) <- getRect na idx-          rect <- widgetHitRect ctx nt idx x y w h-          hit <- nodeClippedHit ctx idx rect mouse-          if hit then overlayHitAllowed ctx idx mouse else pure False-  mWid <- traverse (getWidgetId na) mIdx-  -- A press on a disabled field lands on nothing: it takes focus from-  -- whichever field had it and gives it to none.-  case mWid of-    Just wid -> do-      disabled <- isDisabled ctx wid-      pure (if disabled then Nothing else Just wid)-    Nothing -> pure Nothing
− lib/NanoUI/Frame/Node.hs
@@ -1,118 +0,0 @@--- | Per-node queries shared by the paint, span, scroll and hit passes: the--- font a node renders and measures in, and a scroll node's fields and content--- viewport.-module NanoUI.Frame.Node-  ( resolveFontFor-  , resolveTextFont-  , nodeFontMetrics-  , ScrollNode (..)-  , readScrollNode-  , scrollNodeViewport-  ) where--import Data.Text (Text)-import NanoUI.Context (Context (..))-import NanoUI.Draw.Types (TextFont (..))-import NanoUI.Font (FontMetrics, ScrollBarSlot, isDefaultNodeFont, measureTextIO)-import NanoUI.Frame.Scroll.Geometry-  ( ScrollConfig-  , decodeScrollConfig-  , scrollConfigNative2D-  , scrollContentClip-  , scrollViewportClip2D-  )-import NanoUI.Layout.Arena-  ( DirTag-  , NodeArena-  , NodeIdx-  , NodeType (..)-  , getDirection-  , getNodeFontSize-  , getNodeType-  , getNodeValue-  , getPadding-  , getScrollContentW-  , getStyleIdx-  )-import NanoUI.Layout.Solve (scrollBarSlotOf)-import NanoUI.Style (FontVariant (..), Padding)-import NanoUI.Types (Rect)-import NanoUI.WidgetText (textNodeFontStyle, textNodeFontVariant, textNodeFontWeight)---- | Font for a node of type @nt@ with an explicit size and packed style: the--- metrics, whether the host returned a native styled face (paint then skips--- synthetic weight and slant), and the matching measure. Base sans and mono--- resolve to the pre-read metrics; everything else defers to the host--- resolver. INLINE: it runs for every text-bearing node painted, and inlining--- lets the result triple fold away at each call site (measured: 30 MB less--- allocation over the 3000-frame profile).------ Only text and text-input nodes pack a font into their style. Other widgets--- keep their own data in those bits (a radio's option index, a colour picker--- part, a tab's look), so their style must not be read as a font.-{-# INLINE resolveFontFor #-}-resolveFontFor :: Context -> NodeType -> Float -> Int -> IO (FontMetrics, Bool, Text -> IO (Float, Float))-resolveFontFor ctx nt size packed-  | isDefaultNodeFont size weight style variant =-      pure $-        if variant == FontMono-          then (ctxMonoFontMetrics ctx, False, measureTextIO (ctxMonoFontMetrics ctx))-          else (ctxFontMetrics ctx, False, ctxMeasureText ctx)-  | otherwise = do-      (fm, native) <- ctxResolveFont ctx size weight style variant-      pure (fm, native, ctxResolveMeasure ctx size weight style variant)-  where-    si = if nt == NodeText || nt == NodeTextInput then packed else 0-    variant = textNodeFontVariant si-    weight = textNodeFontWeight si-    style = textNodeFontStyle si---- | The font a 'DrawTextStyled' op names, and whether the host draws its--- weight and slant natively.-resolveTextFont :: Context -> TextFont -> IO (FontMetrics, Bool)-resolveTextFont ctx (TextFont size variant weight style _)-  | isDefaultNodeFont size weight style variant =-      pure (if variant == FontMono then ctxMonoFontMetrics ctx else ctxFontMetrics ctx, False)-  | otherwise = ctxResolveFont ctx size weight style variant---- | Metrics of the font node @idx@ is styled with.-nodeFontMetrics :: Context -> NodeIdx -> IO FontMetrics-nodeFontMetrics ctx idx = do-  nt <- getNodeType (ctxNodeArena ctx) idx-  si <- getStyleIdx (ctxNodeArena ctx) idx-  size <- getNodeFontSize (ctxNodeArena ctx) idx-  (fm, _, _) <- resolveFontFor ctx nt size si-  pure fm---- | What the scroll passes read off a scroll container: its bar slot, scroll--- config, whether it scrolls natively in 2D, direction, padding, the content--- extent along its main axis (the content height for 2D) and, for 2D, the--- content width.-data ScrollNode = ScrollNode-  { snSlot :: !ScrollBarSlot-  , snConfig :: !ScrollConfig-  , sn2D :: !Bool-  , snDir :: !DirTag-  , snPad :: {-# UNPACK #-} !Padding-  , snContentMain :: {-# UNPACK #-} !Float-  , snContentW :: {-# UNPACK #-} !Float-  }--{-# INLINE readScrollNode #-}-readScrollNode :: NodeArena -> NodeIdx -> IO ScrollNode-readScrollNode na idx = do-  si <- getStyleIdx na idx-  slot <- scrollBarSlotOf na idx-  dir <- getDirection na idx-  pad <- getPadding na idx-  contentMain <- getNodeValue na idx-  contentW <- getScrollContentW na idx-  let cfg = decodeScrollConfig si-  pure $! ScrollNode slot cfg (si /= 0 && scrollConfigNative2D cfg) dir pad contentMain contentW---- | Content viewport of a scroll node placed at @x y w h@: its padding box--- minus the live scrollbar gutters.-scrollNodeViewport :: ScrollNode -> Float -> Float -> Float -> Float -> Rect-scrollNodeViewport (ScrollNode slot cfg native2D dir pad contentMain contentW) x y w h-  | native2D = scrollViewportClip2D slot cfg x y w h pad contentW contentMain-  | otherwise = scrollContentClip slot cfg dir x y w h pad contentMain
− lib/NanoUI/Frame/Overlay.hs
@@ -1,60 +0,0 @@--- | Floating panel overlays: windows, popups and modals (with the modal--- backdrop), each a menu-style panel with its subtree painted inside.-module NanoUI.Frame.Overlay-  ( drawWindowOverlays-  , drawModalOverlays-  , drawPopupOverlays-  ) where--import Control.Monad (when)-import Data.IORef (readIORef)-import NanoUI.Context (Context (..), nodeTheme)-import NanoUI.Draw (pushRect, withClip)-import NanoUI.Frame.Chrome (overlayMenuStyle, overlayModalStyle, overlayWindowStyle, paintMenuPanel)-import NanoUI.Frame.Hit (modalTreeOpen)-import NanoUI.Frame.Paint (walkChildren)-import NanoUI.Layout.Arena (NodeIdx, NodeType (..), forNodes_, getNodeType, getPadding, getRect)-import NanoUI.Style (Padding (..), Style, Theme, themeOverlayDim, themeSeparator)-import NanoUI.Types (Rect (..), Size (..))-import NanoUI.Widgets.Chrome (titleBarChromeHFor, windowChromeSepH)--drawWindowOverlays :: Context -> IO ()-drawWindowOverlays ctx =-  forFloatingNode ctx NodeWindow $ \idx rect@(Rect x y w _) -> do-    theme <- nodeTheme ctx idx-    drawFloatingPanel ctx theme idx (overlayWindowStyle theme) rect-    pad <- getPadding (ctxNodeArena ctx) idx-    let sepY = y + padT pad + titleBarChromeHFor - windowChromeSepH-    pushRect-      (ctxDrawArena ctx)-      (Rect (x + padL pad) sepY (max 0 (w - padL pad - padR pad)) windowChromeSepH)-      (themeSeparator theme)--drawPopupOverlays :: Context -> IO ()-drawPopupOverlays ctx =-  forFloatingNode ctx NodePopup $ \idx rect -> do-    theme <- nodeTheme ctx idx-    drawFloatingPanel ctx theme idx (overlayMenuStyle theme) rect--drawModalOverlays :: Context -> Size -> IO ()-drawModalOverlays ctx (Size ww wh) = do-  found <- modalTreeOpen ctx-  when found $ do-    theme <- readIORef (ctxTheme ctx)-    pushRect (ctxDrawArena ctx) (Rect 0 0 ww wh) (themeOverlayDim theme)-    forFloatingNode ctx NodeModal $ \idx rect -> do-      modalTheme <- nodeTheme ctx idx-      drawFloatingPanel ctx modalTheme idx (overlayModalStyle modalTheme) rect--forFloatingNode :: Context -> NodeType -> (NodeIdx -> Rect -> IO ()) -> IO ()-forFloatingNode ctx nodeType draw =-  forNodes_ (ctxNodeArena ctx) $ \idx -> do-    nt <- getNodeType (ctxNodeArena ctx) idx-    when (nt == nodeType) $ do-      (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-      draw idx (Rect x y w h)--drawFloatingPanel :: Context -> Theme -> NodeIdx -> Style -> Rect -> IO ()-drawFloatingPanel ctx theme idx style rect = do-  paintMenuPanel (ctxDrawArena ctx) theme style rect-  withClip (ctxDrawArena ctx) rect (walkChildren ctx idx)
− lib/NanoUI/Frame/Paint.hs
@@ -1,438 +0,0 @@--- Paint traversal for NanoUI. This module owns the node walk and the--- structural painters; widget chrome painting lives in sibling--- NanoUI.Frame.Paint.Widgets.------ The module is shaped for GHC's optimizer: the recursive walker------   paintNodeWithEnv -> lowerNodeVisible (explicit dispatch)---         -> per-node painters (containers recurse via walkChildrenWithOccluders)------ sits on top of {-# NOINLINE #-} seams, and the heavyweight painters (widget--- chrome, text, scroll containers, drawings) stay out of line, so no single--- binding carries the whole painting body inside the recursive loop. That--- stops the simplifier / SpecConstr from seeing one monolithic binding in the--- loop, which is what blew up compilation under -fspecialise-aggressively +--- LLVM; hence the guard flags below.-{-# OPTIONS_GHC -fasm -fno-specialise-aggressively #-}--{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Paint-  ( lowerShapes-  , walkChildren-  ) where--import Control.Monad (forM_, unless, when)-import Data.Bits ((.&.))-import Data.Maybe (catMaybes, fromMaybe)-import Data.Primitive.PrimArray-  ( PrimArray-  , emptyPrimArray-  , indexPrimArray-  , newPrimArray-  , shrinkMutablePrimArray-  , sizeofPrimArray-  , unsafeFreezePrimArray-  , writePrimArray-  )-import qualified Data.Text as T-import Data.Word (Word32)-import NanoUI.Context-  ( Context (..)-  , CustomDrawingEntry (..)-  , DrawingEntry (..)-  , atlasTextureId-  , cachedCustomDrawingOps-  , cachedDrawingOps-  , getScrollOffset-  , getScrollOffset2D-  , lookupCustomDrawing-  , lookupDrawing-  , lookupImageUv-  , nodeTheme-  , scopeTheme-  )-import NanoUI.Draw-  ( Layer (..)-  , beginLayer-  , currentClip-  , currentLayer-  , emitDrawOps-  , pushImage-  , pushRect-  , pushRoundedStroke-  , pushTextStyled-  , withClip-  )-import NanoUI.Font (ScrollBarSlot (..))-import NanoUI.Frame.Chrome-  ( floatingAncestor-  , imageIdFromText-  , overlayMenuStyle-  , overlayModalStyle-  , overlayWindowStyle-  , paintScrollBarLayout-  , paintStyledRect-  )-import NanoUI.Frame.Node (ScrollNode (..), readScrollNode, resolveFontFor, resolveTextFont, scrollNodeViewport)-import NanoUI.Frame.Paint.Types (PaintEnv (..), buildPaintEnv)-import NanoUI.Frame.Paint.Widgets (paintTextAreaNode, paintTextInputNode, paintWidget)-import NanoUI.Frame.Scroll.Geometry-  ( borderContentClip-  , padContentClip-  , scrollBare-  , scrollBarLayout-  , scrollBarLayouts2D-  , scrollChromeActive-  )-import NanoUI.Frame.Spans (collectNodeTextSpans)-import NanoUI.Id (hashWidgetId)-import NanoUI.Layout.Arena-  ( DirTag (..)-  , NodeIdx-  , NodeType (..)-  , SizingTag (..)-  , arenaCount-  , floatingNodeCount-  , foldNodesM-  , forChildNodes_-  , getHeightSizing-  , getNodeFontColor-  , getNodeFontSize-  , getNodeScope-  , getNodeType-  , getRect-  , getStyleIdx-  , getText-  , getWidgetId-  , getWidthSizing-  , isFloatingNode-  )-import NanoUI.Style-  ( FontStyle (..)-  , FontWeight (..)-  , Style (..)-  , Theme (..)-  , scrollBarThumbColor-  , scrollBarTrackColor-  , themeAccent-  , themeFloatingWindow-  , themeInput-  , themePanel-  , themeSeparator-  , themeWindow-  , fadeAlpha-  , themeDisabledFade-  , themeFocusRing-  )-import NanoUI.Types (Color (..), ImageId (..), Rect (..), V2 (..), colorA, colorRGBA, rectInflate)-import NanoUI.Widgets.ColorPicker (colorPickerPartRect)-import NanoUI.Widgets.Custom (mkCustomDrawContext)-import NanoUI.WidgetText-  ( tableStripeColor-  , textNodeFontStyle-  , textNodeFontWeight-  , textNodeTextDecoration-  )--lowerShapes :: Context -> IO ()-lowerShapes ctx = do-  count <- arenaCount (ctxNodeArena ctx)-  when (count > 0) $ do-    occluders <- collectFloatingOccluders ctx-    buildPaintEnv ctx occluders >>= (`paintNodeWithEnv` 0)---- | Rects of opaque floating panels, inset past their rounded border, that--- hide whatever lies fully behind them, as @x0, y0, x1, y1@ runs. Frames--- without floating nodes skip the arena walk.-collectFloatingOccluders :: Context -> IO (PrimArray Float)-collectFloatingOccluders ctx = do-  let na = ctxNodeArena ctx-  floating <- floatingNodeCount na-  if floating <= 0-    then pure emptyPrimArray-    else do-      buf <- newPrimArray (floating * 4)-      n <- foldNodesM na (addOccluder na buf) 0-      shrinkMutablePrimArray buf (n * 4)-      unsafeFreezePrimArray buf-  where-    isOpaque s = colorA (styleBg s) == 255-    occludes theme = \case-      NodeWindow -> isOpaque (overlayWindowStyle theme)-      NodeModal -> isOpaque (overlayModalStyle theme)-      NodePopup -> isOpaque (overlayMenuStyle theme)-      _ -> False-    addOccluder na buf !n idx = do-      nt <- getNodeType na idx-      opaque <- if isFloatingNode nt then (`occludes` nt) <$> nodeTheme ctx idx else pure False-      if not opaque-        then pure n-        else do-          (x, y, w, h) <- getRect na idx-          if not (w > 6 && h > 6)-            then pure n-            else do-              let !o = n * 4-                  Rect ox oy ow oh = rectInflate (-3) (Rect x y w h)-              writePrimArray buf o ox-              writePrimArray buf (o + 1) oy-              writePrimArray buf (o + 2) (ox + ow)-              writePrimArray buf (o + 3) (oy + oh)-              pure (n + 1)---- | Clip + occluder short-circuit, then lower the node. NOINLINE so the--- recursive container walk never exposes the dispatch below to the simplifier.------ The clip test widens the node by 'paintOverhang': a clip frame starts from a--- blank backdrop, so a node whose focus ring reaches into the clip must repaint--- even when its own rect stays outside.-{-# NOINLINE paintNodeWithEnv #-}-paintNodeWithEnv :: PaintEnv -> NodeIdx -> IO ()-paintNodeWithEnv env idx = do-  (x, y, w, h) <- getRect (peNodeArena env) idx-  Rect cx cy cw ch <- currentClip (peDrawArena env)-  let !l = max (x - paintOverhang) cx-      !t = max (y - paintOverhang) cy-      !r = min (x + w + paintOverhang) (cx + cw)-      !b = min (y + h + paintOverhang) (cy + ch)-  unless (w <= 0 || h <= 0 || r <= l || b <= t) $-    unless (occluded (peOccluders env) l t r b) $ do-      nt <- getNodeType (peNodeArena env) idx-      scope <- getNodeScope (peNodeArena env) idx-      if scope == peScope env-        then lowerNodeVisible env idx nt (Rect x y w h)-        else do-          theme <- scopeTheme (peContext env) scope-          lowerNodeVisible env {peTheme = theme, peScope = scope} idx nt (Rect x y w h)---- | Whether an opaque floating panel fully covers the clipped node rect--- @l, t, r, b@, which the caller has already checked is non-empty.-{-# INLINE occluded #-}-occluded :: PrimArray Float -> Float -> Float -> Float -> Float -> Bool-occluded occ !l !t !r !b = go 0-  where-    !end = sizeofPrimArray occ-    go !o-      | o >= end = False-      | l >= indexPrimArray occ o-          && t >= indexPrimArray occ (o + 1)-          && r <= indexPrimArray occ (o + 2)-          && b <= indexPrimArray occ (o + 3) =-          True-      | otherwise = go (o + 4)---- | How far a node may paint outside its rect: the focus ring sits 2px out--- with a 1.5px stroke.-paintOverhang :: Float-paintOverhang = 4---- | Explicit per-node-type dispatch. Kept NOINLINE and thin so the recursive--- loop never sees the branch bodies.-{-# NOINLINE lowerNodeVisible #-}-lowerNodeVisible :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()-lowerNodeVisible env idx nt rect = do-  case nt of-    NodeContainer -> paintContainerNode env idx rect-    NodePanel -> paintPanelNode env idx rect-    NodeScrollContainer -> paintScrollContainerNode env idx rect-    NodeText -> paintTextNode env idx rect-    NodeSeparator -> paintSeparatorNode env rect-    NodeTextInput -> paintTextInputNode env idx rect-    NodeTextArea -> paintTextAreaNode env idx rect-    NodeSpacer -> pure ()-    NodeModal -> pure ()-    NodeWindow -> pure ()-    NodePopup -> pure ()-    NodeBox -> paintBoxNode env idx rect-    NodeImage -> paintImageNode env idx rect-    NodeDrawing -> paintDrawingNode env idx rect-    NodeWidget -> pure ()-    _ -> paintWidget env idx nt rect-  unless (hashWidgetId (peFocusRing env) == 0) $-    paintFocusRing env idx nt rect---- | Accent ring around the widget holding keyboard focus. Text fields and--- selects already swap in an accent border while focused, so they get none.--- Tree rows fill their scroller edge to edge, so their ring sits just inside--- the row; colour picker parts ring the square or bar they draw.-{-# NOINLINE paintFocusRing #-}-paintFocusRing :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()-paintFocusRing env idx nt rect = do-  wid <- getWidgetId (peNodeArena env) idx-  when (wid == peFocusRing env && nt /= NodeTextInput && nt /= NodeTextArea && nt /= NodeSelect) $ do-    target <--      if nt == NodeColorPicker-        then colorPickerPartRect (peNodeArena env) idx rect-        else pure rect-    let (ring, radius)-          | nt == NodeTree = (rectInflate (-1) target, 0)-          | otherwise = (rectInflate 2 target, 4)-    pushRoundedStroke (peDrawArena env) ring radius 1.5 (themeFocusRing (peTheme env))--paintContainerNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintContainerNode env idx rect = do-  walkChildrenWithOccluders env idx-  let ctx = peContext env-  wid <- getWidgetId (peNodeArena env) idx-  mBuild <- lookupCustomDrawing ctx wid-  forM_ mBuild $ \(CustomDrawingEntry _ build) -> do-    let fm = peFontMetrics env-        da = peDrawArena env-    cdc <- mkCustomDrawContext ctx fm wid-    withClip da rect (emitDrawOps da fm (resolveTextFont ctx) (build cdc rect))--paintPanelNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintPanelNode env idx rect = do-  let da = peDrawArena env-      style = themePanel (peTheme env)-  paintStyledRect da style rect-  withClip da (borderContentClip style rect) $ walkChildrenWithOccluders env idx--{-# NOINLINE paintScrollContainerNode #-}-paintScrollContainerNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintScrollContainerNode env idx rect@(Rect x y w h) = do-  let ctx = peContext env-      arena = peNodeArena env-      da = peDrawArena env-      tm = peTheme env-  sn <- readScrollNode arena idx-  -- A bare scroller paints nothing at all: it only lends its clip and-  -- offset, so whatever sits behind it (window, panel) keeps showing-  -- through. Grow×grow scrollers (page-level) keep no well so they blend-  -- into the window backdrop. That backdrop only exists while the runner-  -- clears it on DamageFull frames; on clip frames (scrolling, resize)-  -- the strip vacated by scrolled content has no covering command and-  -- the retained texture would show stale pixels, a ghost of a previous-  -- scroll position. Paint the full rect with the window color instead:-  -- invisible on a cleared backdrop, and clip replay then always-  -- repaints the whole viewport.-  unless (scrollBare (snConfig sn)) $ do-    inFloating <- maybe False isFloatingNode <$> floatingAncestor ctx idx-    (wTag, _) <- getWidthSizing arena idx-    (hTag, _) <- getHeightSizing arena idx-    if wTag == SizingGrow && hTag == SizingGrow-      then pushRect da rect (if inFloating then styleBg (themeFloatingWindow tm) else themeWindow tm)-      else do-        let well = (if inFloating then themeFloatingWindow tm else themeInput tm) {styleCornerRadius = 0}-        paintStyledRect da well rect-  withClip da (scrollNodeViewport sn x y w h) $ walkChildrenWithOccluders env idx-  paintScrollChrome env idx sn rect---- | Scrollbars of a scroll container whose chrome is active, drawn one layer--- above the content so they stay on top of it.-paintScrollChrome :: PaintEnv -> NodeIdx -> ScrollNode -> Rect -> IO ()-paintScrollChrome env idx (ScrollNode slot cfg native2D dir pad contentMain contentW) (Rect x y w h) = do-  let ctx = peContext env-      da = peDrawArena env-      theme = peTheme env-      Rect _ _ innerW innerH = padContentClip x y w h pad-  wid <- getWidgetId (peNodeArena env) idx-  bars <--    if native2D-      then-        if scrollChromeActive cfg DirColumn contentMain innerH || scrollChromeActive cfg DirRow contentW innerW-          then do-            V2 offX offY <- getScrollOffset2D ctx wid-            let (mV, mH) = scrollBarLayouts2D slot cfg x y w h pad contentW contentMain offX offY-            pure (catMaybes [mV, mH])-          else pure []-      else do-        let innerMain = case dir of-              DirColumn -> innerH-              DirRow -> innerW-        if scrollChromeActive cfg dir contentMain innerMain-          then do-            off <- getScrollOffset ctx wid-            pure (catMaybes [scrollBarLayout slot dir x y w h pad contentMain off])-          else pure []-  unless (null bars) $ do-    layer <- currentLayer da-    beginLayer da (if layer == LayerOverlay then LayerChrome else LayerContent)-    let base = case slot of-          ScrollBarWindow -> themeFloatingWindow theme-          _ -> themeInput theme-    mapM_ (paintScrollBarLayout da (scrollBarTrackColor base theme) (scrollBarThumbColor base theme)) bars-    beginLayer da layer--{-# NOINLINE paintTextNode #-}-paintTextNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintTextNode env idx rect = do-  let arena = peNodeArena env-      da = peDrawArena env-  si <- getStyleIdx arena idx-  forM_ (tableStripeColor (peTheme env) si) (pushRect da rect)-  raw <- getText arena idx-  unless (T.null raw) $ do-    spans <- collectNodeTextSpans (peContext env) idx-    fontSize <- getNodeFontSize arena idx-    (fm, isNative, _) <- resolveFontFor (peContext env) NodeText fontSize si-    let deco = textNodeTextDecoration si-        weight = if isNative then WeightNormal else textNodeFontWeight si-        style = if isNative then FontStyleNormal else textNodeFontStyle si-    forM_ spans $ \(Rect tx ty _ _, line, spanFg, _) ->-      unless (T.null line) $-        pushTextStyled da fm weight style deco tx ty line spanFg--paintSeparatorNode :: PaintEnv -> Rect -> IO ()-paintSeparatorNode env (Rect x y w h) =-  pushRect (peDrawArena env) line (themeSeparator (peTheme env))-  where-    line-      | w >= h = Rect x (y + (h - 1) / 2) w 1-      | otherwise = Rect (x + (w - 1) / 2) y 1 h--paintBoxNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintBoxNode env idx rect = do-  si <- getStyleIdx (peNodeArena env) idx-  -- styleIdx holds RGBA Word32 bits; see `box` in NanoUI.Widgets.-  pushRect (peDrawArena env) rect (Color (fromIntegral si :: Word32))--paintImageNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintImageNode env idx rect = do-  let da = peDrawArena env-  tex <- imageIdFromText <$> getText (peNodeArena env) idx-  mUv <- lookupImageUv (peContext env) (ImageId tex)-  case mUv of-    Just (u0, v0, u1, v1) -> do-      -- An image may carry a tint in its font colour (an SVG icon). A-      -- disabled image fades the way disabled widget colours do.-      base <- fromMaybe (colorRGBA 255 255 255 255) <$> getNodeFontColor (peNodeArena env) idx-      let tint-            | peScope env .&. 1 /= 0 = fadeAlpha base (round (fromIntegral (colorA base) * (1 - themeDisabledFade (peTheme env))))-            | otherwise = base-      pushImage da rect atlasTextureId u0 v0 u1 v1 tint-    _ -> pushRect da rect (themeAccent (peTheme env))--{-# NOINLINE paintDrawingNode #-}-paintDrawingNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintDrawingNode env idx rect = do-  let ctx = peContext env-      fm = peFontMetrics env-      da = peDrawArena env-  wid <- getWidgetId (peNodeArena env) idx-  mCustomBuild <- lookupCustomDrawing ctx wid-  case mCustomBuild of-    Just (CustomDrawingEntry content customBuild) -> do-      cdc <- mkCustomDrawContext ctx fm wid-      ops <- cachedCustomDrawingOps ctx wid content rect cdc customBuild-      withClip da rect (emitDrawOps da fm (resolveTextFont ctx) ops)-    Nothing -> do-      mBuild <- lookupDrawing ctx wid-      forM_ mBuild $ \(DrawingEntry content build) -> do-        ops <- cachedDrawingOps ctx wid content rect build-        withClip da rect (emitDrawOps da fm (resolveTextFont ctx) ops)---- | Lower the children of @idx@ with the current paint env. NOINLINE keeps--- this recursive call out of the simplifier's loop analysis, so the whole--- walker stays a call to opaque seams rather than one inlined monster.-{-# NOINLINE walkChildrenWithOccluders #-}-walkChildrenWithOccluders :: PaintEnv -> NodeIdx -> IO ()-walkChildrenWithOccluders env idx =-  forChildNodes_ (peNodeArena env) idx (paintNodeWithEnv env)---- | Children walk for callers painting a subtree inside their own clip--- (floating overlays); builds a fresh env without occluders.-{-# NOINLINE walkChildren #-}-walkChildren :: Context -> NodeIdx -> IO ()-walkChildren ctx idx = buildPaintEnv ctx emptyPrimArray >>= (`walkChildrenWithOccluders` idx)
− lib/NanoUI/Frame/Paint/Types.hs
@@ -1,86 +0,0 @@--- Shared leaf module for NanoUI.Frame.Paint and its widget painter sibling:--- both the walker (NanoUI.Frame.Paint) and the chrome painters--- (NanoUI.Frame.Paint.Widgets) consume the paint env, so the record and its--- small helpers live here to keep the module graph acyclic (Paint imports--- Widgets, Widgets imports Types, Paint imports Types).-module NanoUI.Frame.Paint.Types-  ( PaintEnv (..)-  , buildPaintEnv-  , popupPanelRect-  ) where--import Data.IORef (readIORef)-import Data.Primitive.PrimArray (PrimArray)-import NanoUI.Context (Context (..))-import NanoUI.Draw (DrawArena)-import NanoUI.Font (FontMetrics)-import NanoUI.Id (WidgetId (..))-import NanoUI.Layout.Arena-  ( NodeArena-  , NodeIdx-  , NodeType (..)-  , getNodeType-  , getParent-  , getRect-  )-import NanoUI.Style (Theme)-import NanoUI.Types (Rect (..))---- | Everything a paint pass needs, bundled so the walker does not re-read the--- theme IORef (or rebuild arena handles) for every node. Baked once per--- frame by 'buildPaintEnv'. Fields are lazy: under--- -funbox-strict-fields a strict paint env would unbox every reachable--- field of Context/Theme/Style recursively, turning each record selector into--- a ~100-way case that dominates Core size; lazy fields stay single pointers--- (all bindings here are already-evaluated values, so no thunks are paid).-data PaintEnv = PaintEnv-  { peContext :: Context-  , peNodeArena :: NodeArena-  , peDrawArena :: DrawArena-  , peTheme :: Theme-  , peScope :: Int-    -- ^ The node scope 'peTheme' belongs to. A node in another scope repaints-    -- its subtree with that scope's theme.-  , peFontMetrics :: FontMetrics-  , peOccluders :: PrimArray Float-    -- ^ Opaque floating panel rects as @x0, y0, x1, y1@ runs; empty when the-    -- frame has none.-  , peFocusRing :: WidgetId-    -- ^ The focused widget while its keyboard focus ring shows, else 0.-  }---- | Locality helper for callers inside the paint frame loop; a fresh env--- re-reads the theme once.-{-# NOINLINE buildPaintEnv #-}-buildPaintEnv :: Context -> PrimArray Float -> IO PaintEnv-buildPaintEnv ctx occluders = do-  theme <- readIORef (ctxTheme ctx)-  focus <- readIORef (ctxFocusId ctx)-  focusVisible <- readIORef (ctxFocusVisible ctx)-  pure PaintEnv-    { peContext = ctx-    , peNodeArena = ctxNodeArena ctx-    , peDrawArena = ctxDrawArena ctx-    , peTheme = theme-    , peScope = 0-    , peFontMetrics = ctxFontMetrics ctx-    , peOccluders = occluders-    , peFocusRing = if focusVisible then focus else WidgetId 0-    }---- | Rect of the nearest popup-panel ancestor of @idx@, if any. Menu rows use--- it to paint hover fills edge-to-edge across the panel.-popupPanelRect :: Context -> NodeIdx -> IO (Maybe Rect)-popupPanelRect ctx = go-  where-    go i = do-      p <- getParent (ctxNodeArena ctx) i-      if p < 0-        then pure Nothing-        else do-          nt <- getNodeType (ctxNodeArena ctx) p-          if nt == NodePopup-            then do-              (px, py, pw, ph) <- getRect (ctxNodeArena ctx) p-              pure (Just (Rect px py pw ph))-            else go p
− lib/NanoUI/Frame/Paint/Widgets.hs
@@ -1,529 +0,0 @@--- Widget chrome painters for NanoUI, extracted from NanoUI.Frame.Paint so the--- recursive node walker stays small. Every exported painter carries the paint--- env built by Paint.buildPaintEnv; the walker's explicit dispatch hands each--- widget node to one of these NOINLINE seams instead of inlining a monolithic--- body into the loop.-{-# OPTIONS_GHC -fasm -fno-specialise-aggressively #-}--{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Paint.Widgets-  ( paintWidget-  , paintTextInputNode-  , paintTextAreaNode-  ) where--import Control.Monad (unless, when)-import Data.IORef (readIORef)-import Data.Maybe (fromMaybe)-import qualified Data.Text as T-import NanoUI.Context (Context (..), getStore)-import NanoUI.Draw-  ( DrawArena (..)-  , pushCircle-  , pushFilledTriangle-  , pushLine-  , pushRoundedRect-  , pushRoundedRectRaw-  , pushRoundedStroke-  , pushStrokeAA-  , pushText-  , withClip-  )-import NanoUI.Font-  ( FontMetrics (..)-  , centeredTextY-  , checkboxBoxSize-  , sliderHandleDiameter-  , sliderTrackBounds-  , tableCellInset-  , treeChevronRect-  )-import NanoUI.Frame.Chrome-  ( fillStyledRect-  , paintMenuAccent-  , paintTabHeader-  , paintTableHeader-  , strokeStyledRect-  , paintStyledRect-  , textInputFocused-  , textInputValue-  , widgetVisualStyle-  )-import NanoUI.Frame.Node (resolveFontFor)-import NanoUI.Frame.Paint.Types (PaintEnv (..), popupPanelRect)-import NanoUI.Frame.Spans (forWidgetTextPlacements_, selectableTextGeometry, widgetTextSpans)-import NanoUI.Frame.TextArea (drawTextAreaContentWith)-import NanoUI.Frame.TextArea.Content (resolveTextAreaFont)-import NanoUI.Frame.TextInput-  ( FieldEdit-  , drawTextInputCaret-  , drawTextInputSelection-  , readFieldEdit-  , syncTextInputScroll-  , textInputFieldRect-  , textInputFieldTextClip-  )-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , getNodeFontColor-  , getNodeFontSize-  , getNodeValue-  , getOptions-  , getStyleIdx-  , getText-  , getWidgetId-  )-import NanoUI.Style (Style, styleBg, styleBorder, styleFg, themeAccent, themeInput, themeOnAccent)-import NanoUI.Types (Color (..), Rect (..), clamp01, colorA, lerpColor, onGrid)-import NanoUI.WidgetText-  ( buttonCloseTrailing-  , buttonVisualStyle-  , comboTextClip-  , isCloseButtonStyle-  , isMenuBarStyle-  , isMenuItemStyle-  , isTabButtonStyle-  , isTableHeaderStyle-  , numericStepperRects-  , numericTextClip-  , searchFieldIconRects-  , searchFieldTextClip-  , selectChevronCenterX-  , selectChevronReserve-  , tableSortMarkOf-  , textInputNumericMode-  , textInputFieldText-  , textInputSearchMode-  , textInputSelectableMode-  , treeDecodeStyle-  )-import NanoUI.Widgets.ColorPicker (drawColorPickerPart)---- | Single-line text input: selectable, bare, search, combo or captioned field--- depending on the node's visual style.-{-# NOINLINE paintTextInputNode #-}-paintTextInputNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintTextInputNode env idx rect@(Rect x y w h) = do-  let ctx = peContext env-      da = peDrawArena env-      fm = peFontMetrics env-  style <- widgetVisualStyle ctx NodeTextInput idx-  focus <- textInputFocused ctx idx-  si <- getStyleIdx (peNodeArena env) idx-  if textInputNumericMode si-    then paintNumericField ctx da fm style idx focus rect-    else-      if textInputSelectableMode si-        then paintSelectableText env style idx rect-        else-          if textInputSearchMode si-            then do-              opts <- getOptions (peNodeArena env) idx-              if null opts-                then paintSearchField ctx da fm style idx focus rect-                else paintComboField ctx da fm style idx focus rect-            else do-              let field = textInputFieldRect fm x y w h-              paintStyledRect da style field-              spans <- widgetTextSpans ctx NodeTextInput idx x y w h-              case spans of-                (Rect fx fy _ _, txt, ffg, _) : _ -> do-                  mEdit <- readFieldEdit ctx idx x y w h =<< syncTextInputScroll ctx idx x y w h-                  paintClippedFieldText ctx da fm style idx mEdit (textInputFieldTextClip fm field) fx fy txt ffg-                [] -> pure ()---- | Multi-line text area.-{-# NOINLINE paintTextAreaNode #-}-paintTextAreaNode :: PaintEnv -> NodeIdx -> Rect -> IO ()-paintTextAreaNode env idx (Rect x y w h) = do-  let ctx = peContext env-      da = peDrawArena env-  style <- widgetVisualStyle ctx NodeTextArea idx-  areaFm <- resolveTextAreaFont ctx idx-  paintStyledRect da style (Rect x y w h)-  drawTextAreaContentWith da ctx areaFm idx x y w h style---- | Generic foreground / chrome widget (button, checkbox, radio, slider,--- select, tree row, color swatch, table / tab header, ...). Splits into a--- background pass and a label pass, both behind NOINLINE seams.-{-# NOINLINE paintWidget #-}-paintWidget :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()-paintWidget env idx nt rect@(Rect _ ry _ rh) = do-  let ctx = peContext env-  style <- widgetVisualStyle ctx nt idx-  value <- getNodeValue (peNodeArena env) idx-  si <- getStyleIdx (peNodeArena env) idx-  -- Menu rows paint edge-to-edge across the popup panel, exactly like the-  -- text-field context menu painter: the hover fill and the accent marker-  -- span the panel width instead of the (padded) node rect.-  menuRowRect <--    if nt == NodeButton && isMenuItemStyle si-      then maybe rect (\(Rect px _ pw _) -> Rect px ry pw rh) <$> popupPanelRect ctx idx-      else pure rect-  paintWidgetBackground env idx nt style si menuRowRect value rect-  paintWidgetForeground env idx nt style si rect---- The button kind flags are re-derived here from the style bits rather than--- passed in: a flags record crossing this NOINLINE seam would be allocated--- for every widget on every painted frame.-{-# NOINLINE paintWidgetBackground #-}-paintWidgetBackground :: PaintEnv -> NodeIdx -> NodeType -> Style -> Int -> Rect -> Float -> Rect -> IO ()-paintWidgetBackground env idx nt style si menuRowRect value (Rect x y w h) = do-  let ctx = peContext env-      da = peDrawArena env-      fm = peFontMetrics env-      theme = peTheme env-      -- Strict: lazy Bools here would allocate thunks per widget per frame.-      !isButton = nt == NodeButton-      !isClose = isButton && isCloseButtonStyle si-      !isTab = isButton && isTabButtonStyle si-      !isTable = isButton && isTableHeaderStyle si-      !isMenuItem = isButton && isMenuItemStyle si-      !isMenu = isMenuItem || (isButton && isMenuBarStyle si)-      !hasBg = colorA (styleBg style) > 0-      !opaqueBg-        | isMenu = hasBg-        | isClose || isTab = False-        | isTable || nt == NodeTree = hasBg-        | otherwise =-            nt /= NodeCheckbox && nt /= NodeRadio && nt /= NodeSlider-              && nt /= NodeTextInput && nt /= NodeTextArea && nt /= NodeColorPicker-  when opaqueBg $ fillStyledRect da style menuRowRect-  when (opaqueBg && not (isTab || isTable || isMenu) && nt /= NodeTree) $-    strokeStyledRect da style (Rect x y w h)-  when isMenuItem $ do-    wid <- getWidgetId (peNodeArena env) idx-    hot <- readIORef (ctxHotId ctx)-    -- Same marker as the text-field context menu, from the shared menu-    -- metrics, so the two painters cannot drift.-    when (wid == hot) $ paintMenuAccent da theme menuRowRect-  when isTab $-    paintTabHeader da theme (buttonVisualStyle si `mod` 4) (value > 0.5) style x y w h-  when isTable $-    paintTableHeader da theme (value > 0.5) style x y w h-  case nt of-    NodeCheckbox -> drawCheckbox da fm style x y h value (themeAccent theme) (styleBg (themeInput theme)) (themeOnAccent theme)-    NodeRadio -> drawRadio da fm style x y h value (themeAccent theme) (styleBg (themeInput theme))-    NodeTree -> do-      let (_, depth, hasKids, expanded) = treeDecodeStyle si-      when hasKids $-        drawTreeChevron da fm x y w h depth expanded (styleFg style)-    NodeSlider -> paintSliderBody env x y w h value-    NodeButton -> when isClose $ drawCloseIcon da (buttonVisualStyle si == buttonCloseTrailing) x y w h (styleFg style)-    NodeSelect -> drawSelectChevron da False x y w h (styleFg style)-    NodeColorPicker -> do-      store <- getStore ctx-      drawColorPickerPart (peNodeArena env) idx fm da store style (Rect x y w h)-    _ -> pure ()--{-# NOINLINE paintSliderBody #-}-paintSliderBody :: PaintEnv -> Float -> Float -> Float -> Float -> Float -> IO ()-paintSliderBody env x y w h value = do-  let da = peDrawArena env-      theme = peTheme env-      track@(Rect tx ty tw th) = sliderTrackBounds x y w h-      trackR = 3-      fillW = max 0 (tw * clamp01 value)-      outline = styleBorder (themeInput theme)-      well = lerpColor (styleBg (themeInput theme)) outline 0.35-      bw = 1-      innerR = max 0 (trackR - bw)-      innerX = tx + bw-      innerY = ty + bw-      innerW = tw - 2 * bw-      innerH = th - 2 * bw-      innerFillW = max 0 (innerW * clamp01 value)-  pushRoundedStroke da track trackR bw outline-  when (innerW > 0 && innerH > 0) $-    pushRoundedRect da (Rect innerX innerY innerW innerH) innerR well-  when (innerFillW > 0) $ do-    let fillR =-          if innerFillW >= innerW - 0.5-            then innerR-            else min innerR (innerFillW / 2)-    pushRoundedRect da (Rect innerX innerY innerFillW innerH) fillR (themeAccent theme)-  let handleD = sliderHandleDiameter-      handleCx = tx + max (handleD / 2) (min (tw - handleD / 2) fillW)-      handleHy = ty + (th - handleD) / 2-      innerD = handleD - 2-  pushRoundedRect-    da-    (Rect (handleCx - innerD / 2) (handleHy + (handleD - innerD) / 2) innerD innerD)-    (innerD / 2)-    (themeOnAccent theme)-  pushRoundedStroke da (Rect (handleCx - handleD / 2) handleHy handleD handleD) (handleD / 2) bw outline--{-# NOINLINE paintWidgetForeground #-}-paintWidgetForeground :: PaintEnv -> NodeIdx -> NodeType -> Style -> Int -> Rect -> IO ()-paintWidgetForeground env idx nt style si (Rect x y w h) = do-  let ctx = peContext env-      da = peDrawArena env-  mFontColor <- getNodeFontColor (peNodeArena env) idx-  fontSize <- getNodeFontSize (peNodeArena env) idx-  (fm, _, _) <- resolveFontFor ctx nt fontSize si-  let widgetFg = fromMaybe (styleFg style) mFontColor-      sortMark = if nt == NodeButton && isTableHeaderStyle si then tableSortMarkOf si else 0-      -- Table sort arrow: pinned to the header's right edge, inside the cell-      -- inset, whatever the label's alignment. The label still ends in a-      -- blank reserve slot (the ▲/▼ codepoint is not in the pruned UI font),-      -- which keeps the column wide enough for the text and the arrow.-      sortArrowX = x + w - tableCellInset - 5-      drawPlacement lastLine txt px py _ th =-        unless (T.null txt) $ do-          pushText da fm px py txt widgetFg-          when (sortMark /= 0 && lastLine) $-            drawSortTriangle da sortArrowX (py + th / 2) (sortMark == 2) widgetFg-  forWidgetTextPlacements_ ctx nt idx x y w h drawPlacement---- | Sort direction triangle for a table header: up when ascending, down when--- descending, centered on the label line in the header's reserved slot.-drawSortTriangle :: DrawArena -> Float -> Float -> Bool -> Color -> IO ()-drawSortTriangle da cx cy down col =-  if down-    then pushFilledTriangle da (cx - 5) (cy - 3.5) (cx + 5) (cy - 3.5) cx (cy + 3.5) col-    else pushFilledTriangle da (cx - 5) (cy + 3.5) (cx + 5) (cy + 3.5) cx (cy - 3.5) col---- | Draw a single-line field's text, and its selection and caret while it is--- being edited, inside @clip@. @penX/penY@ locate @txt@ (absolute).-{-# INLINE paintClippedFieldText #-}-paintClippedFieldText ::-  Context ->-  DrawArena ->-  FontMetrics ->-  Style ->-  NodeIdx ->-  Maybe FieldEdit ->-  Rect ->-  Float ->-  Float ->-  T.Text ->-  Color ->-  IO ()-paintClippedFieldText ctx da fm style idx mEdit clip penX penY txt fg =-  withClip da clip $ do-    mapM_ (drawTextInputSelection da ctx idx) mEdit-    unless (T.null txt) $-      pushText da fm penX penY txt fg-    mapM_ (\edit -> drawTextInputCaret da edit (styleFg style)) mEdit---- | A caption-less field's value, or @placeholder@ (dimmed) while empty and--- unfocused, scrolled to keep the caret in @clip@.-paintFieldValue :: Context -> DrawArena -> FontMetrics -> Style -> NodeIdx -> Bool -> Rect -> Rect -> T.Text -> T.Text -> IO ()-paintFieldValue ctx da fm style idx focus (Rect x y w h) clip@(Rect clipX _ _ _) placeholder value = do-  let display = textInputFieldText placeholder value focus-      baseFg = styleFg style-  scrollX <- syncTextInputScroll ctx idx x y w h-  (ty, fg) <--    if T.null display-      then pure (0, baseFg)-      else do-        (_, th) <- ctxMeasureText ctx display-        pure-          ( centeredTextY fm y h th-          , if T.null value && not focus then lerpColor baseFg (styleBg style) 0.5 else baseFg-          )-  mEdit <- readFieldEdit ctx idx x y w h scrollX-  paintClippedFieldText ctx da fm style idx mEdit clip (clipX - scrollX) ty display fg---- | Numeric field: the box, its value clipped left of the stepper, and the--- stepper's up and down arrows beside a rule.-paintNumericField :: Context -> DrawArena -> FontMetrics -> Style -> NodeIdx -> Bool -> Rect -> IO ()-paintNumericField ctx da fm style idx focus box@(Rect x y w h) = do-  paintStyledRect da style box-  value <- textInputValue ctx idx-  let (up@(Rect ux _ _ _), down) = numericStepperRects x y w h-      iconCol = lerpColor (styleFg style) (styleBg style) 0.4-      ruleCol = lerpColor (styleBorder style) (styleBg style) 0.4-  pushLine da ux (y + 4) ux (y + h - 4) 1 ruleCol-  drawStepArrow da True up iconCol-  drawStepArrow da False down iconCol-  paintFieldValue ctx da fm style idx focus box (numericTextClip fm x y w h) "" value---- | A stepper arrow in its half of the stepper, nudged toward the other half so--- the pair reads as one control.-drawStepArrow :: DrawArena -> Bool -> Rect -> Color -> IO ()-drawStepArrow da up (Rect sx sy sw sh) col = do-  let cx = sx + sw / 2-      cy = sy + sh / 2 + (if up then 1 else -1)-      hw = 3.6-      tip = if up then -2.4 else 2.4-  pushFilledTriangle da (cx - hw) (cy - tip * 0.35) (cx + hw) (cy - tip * 0.35) cx (cy + tip) col---- | Caption-less search field: box fills the node rect, magnifier on the left,--- clear (×) on the right when there is text, and the editable value / caret /--- selection confined to the space between them.-paintSearchField :: Context -> DrawArena -> FontMetrics -> Style -> NodeIdx -> Bool -> Rect -> IO ()-paintSearchField ctx da fm style idx focus box@(Rect x y w h) = do-  let (magRect, Rect cx cy cw ch) = searchFieldIconRects fm x y w h-      iconCol = lerpColor (styleFg style) (styleBg style) 0.45-  paintStyledRect da style box-  value <- textInputValue ctx idx-  lbl <- getText (ctxNodeArena ctx) idx-  drawSearchMagnifier da magRect iconCol-  paintFieldValue ctx da fm style idx focus box (searchFieldTextClip fm x y w h) lbl value-  unless (T.null value) $-    drawCloseIcon da False cx cy cw ch iconCol---- | Selectable text: chrome-less, border-less, naturally sized text field--- that supports mouse drag selection and text copying without an insertion caret.-paintSelectableText :: PaintEnv -> Style -> NodeIdx -> Rect -> IO ()-paintSelectableText env style idx rect@(Rect x y w h) = do-  let ctx = peContext env-      da = peDrawArena env-      arena = peNodeArena env-  si <- getStyleIdx arena idx-  mFontColor <- getNodeFontColor arena idx-  fontSize <- getNodeFontSize arena idx-  (fm, _, _) <- resolveFontFor ctx NodeTextInput fontSize si-  value <- textInputValue ctx idx-  let (penX, ty, _) = selectableTextGeometry fm x y h-  mEdit <- readFieldEdit ctx idx x y w h 0-  withClip da rect $ do-    mapM_ (drawTextInputSelection da ctx idx) mEdit-    unless (T.null value) $-      pushText da fm penX ty value (fromMaybe (styleFg style) mFontColor)--drawSearchMagnifier :: DrawArena -> Rect -> Color -> IO ()-drawSearchMagnifier da (Rect x y w h) col = do-  let cx = x + w / 2-      cy = y + h / 2-      s = min w h-      r0 = s * 0.36-      t = max 1.4 (s * 0.15)-      startOff = r0 * 0.7071-      endOff = r0 * 0.7071 + s * 0.22-  pushRoundedStroke da (Rect (cx - r0) (cy - r0) (2 * r0) (2 * r0)) r0 t col-  pushLine da (cx + startOff) (cy + startOff) (cx + endOff) (cy + endOff) (t * 0.8) col---- | Combo box field: the search field's full-rect editable box, but styled--- like a dropdown: no magnifier or clear chrome, and a select chevron in the--- right reserve that flips up while the dropdown is open (i.e. focused).-paintComboField :: Context -> DrawArena -> FontMetrics -> Style -> NodeIdx -> Bool -> Rect -> IO ()-paintComboField ctx da fm style idx focus box@(Rect x y w h) = do-  paintStyledRect da style box-  value <- textInputValue ctx idx-  lbl <- getText (ctxNodeArena ctx) idx-  drawSelectChevron-    da-    focus-    (x + w - selectChevronReserve)-    y-    selectChevronReserve-    h-    (lerpColor (styleFg style) (styleBg style) 0.45)-  paintFieldValue ctx da fm style idx focus box (comboTextClip fm x y w h) lbl value--verticallyCenteredBox :: Float -> Float -> Float -> Float-verticallyCenteredBox y h box =-  let slotH = min h (box + 4)-   in y + max 0 ((slotH - box) / 2)--drawChoiceControl ::-  DrawArena ->-  FontMetrics ->-  Style ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Color ->-  Color ->-  Bool ->-  (Float -> Float -> Float -> IO ()) ->-  IO ()-drawChoiceControl da fm style x y h r bw value accent well solidChecked postMark = do-  let box = checkboxBoxSize fm-      bx = x-      by = verticallyCenteredBox y h box-      outer = Rect bx by box box-      checked = value >= 0.5-  if checked && solidChecked-    then do-      pushRoundedRect da outer r accent-      pushRoundedStroke da outer r bw accent-      postMark bx by box-    else do-      let inner = Rect (bx + bw) (by + bw) (box - 2 * bw) (box - 2 * bw)-          innerR = max 0 (r - bw)-          strokeCol = if checked then accent else styleBorder style-      pushRoundedRect da inner innerR well-      pushRoundedStroke da outer r bw strokeCol-      when checked $ postMark bx by box--drawCheckbox :: DrawArena -> FontMetrics -> Style -> Float -> Float -> Float -> Float -> Color -> Color -> Color -> IO ()-drawCheckbox da fm style x y h value accent well mark =-  let box = checkboxBoxSize fm-      r = min 6 (box / 3.5)-      bw = 1.5-   in drawChoiceControl da fm style x y h r bw value accent well True $ \bx by b ->-        drawCheckboxMark da bx by b mark--drawCheckboxMark :: DrawArena -> Float -> Float -> Float -> Color -> IO ()-drawCheckboxMark da bx by box markCol = do-  let t = max 1.6 (box * 0.11)-      x0 = bx + box * 0.22-      y0 = by + box * 0.52-      x1 = bx + box * 0.42-      y1 = by + box * 0.72-      x2 = bx + box * 0.78-      y2 = by + box * 0.28-      -- Caps snap their centres, as the strokes snap their ends; snapping a-      -- cap's corner lands it up to a pixel off the stroke at a fractional-      -- scale.-      cap cx cy = pushCircle da cx cy (t / 2) markCol-  pushStrokeAA da x0 y0 x1 y1 t markCol-  pushStrokeAA da x1 y1 x2 y2 t markCol-  cap x0 y0-  cap x1 y1-  cap x2 y2--drawRadio :: DrawArena -> FontMetrics -> Style -> Float -> Float -> Float -> Float -> Color -> Color -> IO ()-drawRadio da fm style x y h value accent well =-  let box = checkboxBoxSize fm-      r = box / 2-      bw = 2-   in drawChoiceControl da fm style x y h r bw value accent well False $ \bx by b -> do-        s <- readIORef (daSnapScale da)-        let !dot = b * 0.72-            !dx = onGrid s bx + (b - dot) / 2-            !dy = onGrid s by + (b - dot) / 2-        pushRoundedRectRaw da (Rect dx dy dot dot) (dot / 2) accent---- | A cross centered in the box, or against its right edge when @trailing@.-drawCloseIcon :: DrawArena -> Bool -> Float -> Float -> Float -> Float -> Color -> IO ()-drawCloseIcon da trailing x y w h col = do-  let arm = min w h * 0.21-      t = max 1.3 (min w h * 0.064)-      cx = if trailing then x + w - arm - t / 2 else x + w / 2-      cy = y + h / 2-  pushLine da (cx - arm) (cy - arm) (cx + arm) (cy + arm) t col-  pushLine da (cx - arm) (cy + arm) (cx + arm) (cy - arm) t col---- | Select chevron centered in the right reserve of @x w@; points up when--- @up@ (an open combo dropdown), down otherwise.-drawSelectChevron :: DrawArena -> Bool -> Float -> Float -> Float -> Float -> Color -> IO ()-drawSelectChevron da up x y w h col = do-  let cx = selectChevronCenterX x w-      cy = y + h / 2-      hw = 4.2-      tip = if up then -2.6 else 2.6-  pushFilledTriangle da (cx - hw) (cy - tip * 0.35) (cx + hw) (cy - tip * 0.35) cx (cy + tip) col--drawTreeChevron :: DrawArena -> FontMetrics -> Float -> Float -> Float -> Float -> Int -> Bool -> Color -> IO ()-drawTreeChevron da fm x y w h depth expanded col = do-  let Rect cx cy cw ch = treeChevronRect fm x y w h depth-      mx = cx + cw / 2-      my = cy + ch / 2-      s = min 4.5 (min cw ch * 0.28)-      t = max 1.0 (s * 0.16)-  if expanded-    then do-      pushLine da (mx - s) (my - s * 0.45) mx (my + s * 0.7) t col-      pushLine da mx (my + s * 0.7) (mx + s) (my - s * 0.45) t col-    else do-      pushLine da (mx - s * 0.45) (my - s) (mx + s * 0.7) my t col-      pushLine da (mx + s * 0.7) my (mx - s * 0.45) (my + s) t col
− lib/NanoUI/Frame/Redraw.hs
@@ -1,161 +0,0 @@-{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Redraw-  ( needsRedraw-  , pointerDragActive-  , textFieldActive-  , floatingPanelActive-  , debugPanelOpen-  , overlayMenuOpen-  , probeHotId-  ) where--import Data.IORef (IORef, readIORef)-import Data.Maybe (isJust)-import NanoUI.Context-  ( Context (..)-  , anyAnimating-  , anySelectOpen-  , getMenuPointerGesture-  , getScrollDrag-  , getStore-  , getTextInputMenu-  , getWindowDrag-  , getWindowResize-  , isDirty-  , modalActive-  )-import NanoUI.Frame.Hit (findNodeByWidgetId, nodePointVisible, overlayHitAllowed)-import NanoUI.Frame.Select (overlayMenuOwnerAt)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (Input (..), inputInteracted, inputMousePos, inputPointerHeld)-import NanoUI.Layout.Arena-  ( NodeType (..)-  , findNodeM-  , getNodeType-  , getOptions-  , getWidgetId-  , isFloatingNode-  , isWidgetNode-  )-import NanoUI.Types (V2 (..))--needsRedraw :: Context -> Input -> Input -> IO Bool-needsRedraw ctx prev inp = do-  dirty <- isDirty ctx-  anim <- anyAnimating ctx-  mDrag <- getScrollDrag ctx-  mWinDrag <- getWindowDrag ctx-  overlay <- overlayMenuOpen ctx-  edit <- textFieldActive ctx-  let moved = inputMousePos prev /= inputMousePos inp-  if dirty-    || anim-    || inputInteracted prev inp-    || inputWindowRedraw inp-    || inputPointerHeld inp-    || isJust mDrag-    || isJust mWinDrag-    || (overlay && moved)-    || edit-    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.-      if not moved-        then pure False-        else do-          lastHot <- readIORef (ctxLastHotId ctx)-          (/= lastHot) <$> probeHotId ctx (inputMousePos inp)---- Window/scroll/resize drag marks dirty every frame, so input must still be--- polled on those frames.--- Color picker and slider hold ctxActiveId without extra window/scroll refs.-pointerDragActive :: Context -> IO Bool-pointerDragActive ctx = do-  winDrag <- isJust <$> getWindowDrag ctx-  scrollDrag <- isJust <$> getScrollDrag ctx-  winResize <- isJust <$> getWindowResize ctx-  sliderOrPicker <- focusedNodeIs ctx ctxActiveId (\nt -> nt == NodeSlider || nt == NodeColorPicker)-  pure (winDrag || scrollDrag || winResize || 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)-  if hashWidgetId wid == 0-    then pure False-    else do-      mIdx <- findNodeByWidgetId ctx wid-      case mIdx of-        Nothing -> pure False-        Just idx -> p <$> getNodeType (ctxNodeArena ctx) idx---- Select dropdown or text-input menu is open. Overlay hover is not a widget id.--- A focused combo (a search-style field carrying options) also owns an open--- dropdown: report it so every frame while it is up redraws with full damage:--- the floating list is painted by an overlay, so clip-damage frames would--- leave stale rows in the retained texture.-overlayMenuOpen :: Context -> IO Bool-overlayMenuOpen ctx = do-  store <- getStore ctx-  menu <- getTextInputMenu ctx-  if anySelectOpen store || isJust menu-    then pure True-    else do-      focus <- readIORef (ctxFocusId ctx)-      if hashWidgetId focus == 0-        then pure False-        else do-          mIdx <- findNodeByWidgetId ctx focus-          case mIdx of-            Nothing -> pure False-            Just idx -> do-              nt <- getNodeType (ctxNodeArena ctx) idx-              if nt /= NodeTextInput-                then pure False-                else not . null <$> getOptions (ctxNodeArena ctx) idx---- Focused text field or its context menu. Keep the loop live so typed bytes--- are not stuck behind SDL_WaitEvent.-textFieldActive :: Context -> IO Bool-textFieldActive ctx = do-  menu <- getTextInputMenu ctx-  if isJust menu-    then pure True-    else focusedNodeIs ctx ctxFocusId (\nt -> nt == NodeTextInput || nt == NodeTextArea)---- Last frame still has a floating node (modal or window). Used by backends to--- decide whether overlay content might need periodic refresh (debug HUD).-floatingPanelActive :: Context -> IO Bool-floatingPanelActive ctx = do-  modal <- modalActive ctx-  if modal-    then pure True-    else isJust <$> findNodeM (ctxNodeArena ctx) (fmap isFloatingNode . getNodeType (ctxNodeArena ctx))---- Floating window overlay (debug HUD). Prev floating rects persist across idle frames.-debugPanelOpen :: Context -> IO Bool-debugPanelOpen ctx =-  isJust <$> findNodeM (ctxNodeArena ctx) (fmap (== NodeWindow) . getNodeType (ctxNodeArena ctx))--probeHotId :: Context -> V2 -> IO WidgetId-probeHotId ctx mouse = do-  gesture <- getMenuPointerGesture ctx-  if gesture-    then pure (WidgetId 0)-    else do-      mOverlay <- overlayMenuOwnerAt ctx mouse-      case mOverlay of-        Just wid -> pure wid-        -- Earlier siblings paint over later ones, so the first hit wins.-        Nothing -> maybe (pure (WidgetId 0)) (getWidgetId na) =<< findNodeM na hits-  where-    na = ctxNodeArena ctx-    hits idx = do-      nt <- getNodeType na idx-      if not (isWidgetNode nt)-        then pure False-        else do-          visible <- nodePointVisible ctx idx mouse-          if visible then overlayHitAllowed ctx idx mouse else pure False
− lib/NanoUI/Frame/Scroll.hs
@@ -1,418 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Scroll input: offsets baked into the arena, wheel routing, and scrollbar--- thumb drags and track jumps.-module NanoUI.Frame.Scroll-  ( applyScrollOffsets-  , updateScrollWheel-  , updateScrollDrag-  , scrollBarsFor-  , scrollBarLayout-  , ScrollBarLayout (..)-  ) where--import Control.Applicative ((<|>))-import Control.Monad (forM_, void, when)-import Data.Foldable (find)-import Data.Maybe (fromMaybe)-import NanoUI.Context-  ( Context (..)-  , ScrollAxes (..)-  , ScrollBehavior (..)-  , applyScrollTarget-  , beginScrollMetrics-  , cacheScrollMetrics-  , clampScrollOffset-  , getMenuPointerGesture-  , getScrollDrag-  , getScrollOffset-  , getScrollOffset2D-  , getScrollOffsetIn-  , resolveScrollStep-  , scrollTargetOffset-  , setScrollOffset-  , setScrollOffset2D-  , nodeTheme-  , InteractionState (..)-  , getsInteraction-  , modifyInteraction-  )-import NanoUI.Frame.Hit (topmostModalAtMouse, topmostOverlayAtMouse)-import NanoUI.Frame.Node (ScrollNode (..), readScrollNode, scrollNodeViewport)-import NanoUI.Frame.Scroll.Geometry-  ( ScrollBarLayout (..)-  , ScrollConfig-  , borderContentClip-  , decodeScrollConfig-  , isScrollStyle2D-  , scrollAxisRange-  , scrollBarLayout-  , scrollBarLayouts2D-  , scrollChromeLane-  , scrollChromeSuppressed-  , scrollOffsetFromThumb-  , scrollWheelSuppressed-  )-import NanoUI.Frame.TextArea.Content (textAreaContentGeom)-import NanoUI.Frame.TextArea.Geometry (TextAreaBars (..), TextAreaScrollBarLayouts (..), textAreaBars, textAreaScrollBarLayouts)-import NanoUI.Id (WidgetId)-import NanoUI.Input (Input (..), inputMouseDown, inputMousePos, inputMousePressed, inputMouseReleased, inputScroll)-import NanoUI.Layout.Arena-  ( DirTag (..)-  , NodeIdx-  , NodeType (..)-  , arenaCount-  , findNodeM-  , forChildNodes_-  , getDirection-  , getFirstChild-  , getLayoutRect-  , getNextSibling-  , getNodeType-  , getParent-  , getRect-  , getStyleIdx-  , getWidgetId-  , isFloatingNode-  , isScrollNode-  , setClipRect-  , setRect-  , snapshotLayoutRects-  )-import NanoUI.Style (Padding (..), themePanel)-import NanoUI.Types (Rect (..), V2 (..), rectContains, rectIntersect, rectUnion)--applyScrollOffsets :: Context -> IO ()-applyScrollOffsets ctx = do-  beginScrollMetrics ctx-  snapshotLayoutRects (ctxNodeArena ctx)-  -- A frame that added no widgets has no root to walk.-  count <- arenaCount (ctxNodeArena ctx)-  when (count > 0) $ do-    (wx, wy, ww, wh) <- getRect (ctxNodeArena ctx) 0-    transformSubtree ctx 0 0 0 (Rect wx wy ww wh)--transformSubtree :: Context -> NodeIdx -> Float -> Float -> Rect -> IO ()-transformSubtree ctx idx scrollX scrollY parentClip = do-  let na = ctxNodeArena ctx-  nt <- getNodeType na idx-  (lx, ly, lw, lh) <- getLayoutRect na idx-  let floating = isFloatingNode nt-      (sx, sy) = if floating then (0, 0) else (scrollX, scrollY)-      within r = fromMaybe parentClip (rectIntersect parentClip r)-  (vx, vy, vw, vh) <--    if floating-      then getRect na idx-      else pure (lx + sx, ly + sy, lw, lh)-  when (not floating) $ setRect na idx vx vy vw vh-  (!childScrollX, !childScrollY, !childClip) <--    if isScrollNode nt-      then do-        (axes, viewport, range) <- scrollNodeGeometry ctx idx (Rect vx vy lw lh)-        wid <- getWidgetId na idx-        -- The only pass that sees a scroller's placed geometry. Everything-        -- that scrolls one between frames reads it back from here.-        cacheScrollMetrics ctx wid axes viewport range-        V2 dx dy <- getScrollOffsetIn ctx wid axes-        let clip = within viewport-        setClipRect na idx clip-        pure (sx - dx, sy - dy, clip)-      else do-        clip <--          case nt of-            NodePanel -> do-              theme <- nodeTheme ctx idx-              pure (within (borderContentClip (themePanel theme) (Rect vx vy vw vh)))-            _ -> pure $! if floating then Rect vx vy vw vh else parentClip-        setClipRect na idx clip-        pure (sx, sy, clip)-  forChildNodes_ na idx $ \ci ->-    transformSubtree ctx ci childScrollX childScrollY childClip---- | Axes, content viewport and reachable offset range of the scroll container--- at @idx@ placed at @rect@, in window axes. The wheel, the programmatic--- commands and the transform pass all size a scroll off this, so a scroller--- cannot disagree with itself about how far it reaches.-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-      rangeH = scrollAxisRange contentMain (rectH viewport) (padB pad)-  pure $-    if sn2D sn-      then (ScrollAxisXY, viewport, V2 (scrollAxisRange (snContentW sn) (rectW viewport) (padR pad)) rangeH)-      else case snDir sn of-        DirColumn -> (ScrollAxisY, viewport, V2 0 rangeH)-        DirRow -> (ScrollAxisX, viewport, V2 (scrollAxisRange contentMain (rectW viewport) (padR pad)) 0)--updateScrollWheel :: Context -> Input -> IO ()-updateScrollWheel ctx inp = do-  let scroll@(V2 wheelX wheelY) = inputScroll inp-  when (wheelY /= 0 || wheelX /= 0) $ do-    -- An open dropdown (select menu or combo suggestions) owns the wheel:-    -- the combo widget scrolls its own window, and the scroller underneath-    -- the floating list must not move with it.-    mDrop <- getsInteraction ctx isOpenSelectDrop-    let overDrop = maybe False (\(_, r) -> rectContains r (inputMousePos inp)) mDrop-    when (not overDrop) $ do-      mNode <- findScrollNodeUnderMouse ctx (inputMousePos inp)-      forM_ mNode $ \idx -> do-        wid <- getWidgetId (ctxNodeArena ctx) idx-        void (tryApplyScrollWheelDelta ctx wid scroll)-        applyCrossAxisScroll ctx idx scroll---- Nested 2D: apply the unused axis to a paired scroller in the same panel.--- Do not walk past panel/window/modal into the page scroller.-applyCrossAxisScroll :: Context -> NodeIdx -> V2 -> IO ()-applyCrossAxisScroll ctx idx scroll = do-  dir <- getDirection (ctxNodeArena ctx) idx-  mAnc <- walkOppositeAncestor ctx idx dir-  case mAnc of-    Just pwid -> void (tryApplyScrollWheelDelta ctx pwid scroll)-    Nothing -> do-      mDesc <- findOppositeScrollDescendant ctx idx dir-      forM_ mDesc $ \dwid -> tryApplyScrollWheelDelta ctx dwid scroll--scrollCrossAxisStop :: NodeType -> Bool-scrollCrossAxisStop nt =-  nt == NodePanel || nt == NodeWindow || nt == NodeModal--walkOppositeAncestor :: Context -> NodeIdx -> DirTag -> IO (Maybe WidgetId)-walkOppositeAncestor ctx idx childDir = do-  p <- getParent (ctxNodeArena ctx) idx-  if p < 0-    then pure Nothing-    else do-      nt <- getNodeType (ctxNodeArena ctx) p-      if scrollCrossAxisStop nt-        then pure Nothing-        else-          if not (isScrollNode nt)-            then walkOppositeAncestor ctx p childDir-            else do-              pdir <- getDirection (ctxNodeArena ctx) p-              if pdir == childDir-                then walkOppositeAncestor ctx p childDir-                else Just <$> getWidgetId (ctxNodeArena ctx) p--findOppositeScrollDescendant :: Context -> NodeIdx -> DirTag -> IO (Maybe WidgetId)-findOppositeScrollDescendant ctx idx childDir = goChildren idx-  where-    want = if childDir == DirColumn then DirRow else DirColumn-    goChildren parent = getFirstChild (ctxNodeArena ctx) parent >>= go-    go ci-      | ci < 0 = pure Nothing-      | otherwise = do-          nt <- getNodeType (ctxNodeArena ctx) ci-          found <--            if isScrollNode nt-              then do-                d <- getDirection (ctxNodeArena ctx) ci-                if d == want-                  then Just <$> getWidgetId (ctxNodeArena ctx) ci-                  else goChildren ci-              else goChildren ci-          case found of-            Just w -> pure (Just w)-            Nothing -> getNextSibling (ctxNodeArena ctx) ci >>= go---- | 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 ctx wid =-  findNodeM na $ \idx -> do-    nt <- getNodeType na idx-    if nt /= NodeTextArea && not (isScrollNode nt)-      then pure False-      else do-        owner <- getWidgetId na idx-        if owner /= wid-          then pure False-          else-            if nt == NodeTextArea-              then pure True-              else do-                si <- getStyleIdx na idx-                dir <- getDirection na idx-                pure (not (suppressed (decodeScrollConfig si) (isScrollStyle2D si) dir))-  where-    na = ctxNodeArena ctx--tryApplyScrollWheelDelta :: Context -> WidgetId -> V2 -> IO Bool-tryApplyScrollWheelDelta ctx wid (V2 wheelX wheelY) = do-  mIdx <- scrollOwnerNode scrollWheelSuppressed ctx wid-  case mIdx of-    Nothing -> pure False-    Just idx -> do-      nt <- getNodeType na idx-      (axes, range) <--        if nt == NodeTextArea-          then do-            (fm, field, contentW, contentH) <- textAreaContentGeom ctx idx-            let bars = textAreaBars fm field contentW contentH-            pure-              ( ScrollAxisXY-              , V2 (max 0 (contentW - tabViewW bars)) (max 0 (contentH - tabViewH bars))-              )-          else do-            (x, y, w, h) <- getRect na idx-            (axes, _, range) <- scrollNodeGeometry ctx idx (Rect x y w h)-            pure (axes, range)-      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))-      if next == base && next == cur-        then pure False-        else True <$ applyScrollTarget ctx wid axes next ScrollSmooth-  where-    na = ctxNodeArena ctx--findScrollNodeUnderMouse :: Context -> V2 -> IO (Maybe NodeIdx)-findScrollNodeUnderMouse ctx mouse = do-  count <- arenaCount (ctxNodeArena ctx)-  if count <= 0-    then pure Nothing-    else do-      mModal <- topmostModalAtMouse ctx mouse-      mTop <- topmostOverlayAtMouse ctx mouse-      let start = fromMaybe 0 (mModal <|> mTop)-      (x, y, w, h) <- getRect (ctxNodeArena ctx) start-      queryScrollTarget ctx start mouse (Rect x y w h)--queryScrollTarget :: Context -> NodeIdx -> V2 -> Rect -> IO (Maybe NodeIdx)-queryScrollTarget ctx idx mouse parentClip = do-  nt <- getNodeType (ctxNodeArena ctx) idx-  mClipHere <- scrollHitClip ctx idx nt parentClip-  case mClipHere of-    Nothing -> pure Nothing-    Just clip -> do-      childHit <- walkScrollSiblings ctx idx mouse clip-      case childHit of-        Just hit -> pure (Just hit)-        Nothing -> scrollHitSelf ctx idx nt mouse clip--walkScrollSiblings :: Context -> NodeIdx -> V2 -> Rect -> IO (Maybe NodeIdx)-walkScrollSiblings ctx parent mouse clip = getFirstChild (ctxNodeArena ctx) parent >>= go-  where-    go ci-      | ci < 0 = pure Nothing-      | otherwise = do-          hit <- queryScrollTarget ctx ci mouse clip-          case hit of-            Just found -> pure (Just found)-            Nothing -> getNextSibling (ctxNodeArena ctx) ci >>= go--scrollHitSelf :: Context -> NodeIdx -> NodeType -> V2 -> Rect -> IO (Maybe NodeIdx)-scrollHitSelf ctx idx nt mouse clip-  | nt == NodeTextArea = do-      (fm, field, contentW, contentH) <- textAreaContentGeom ctx idx-      let bars = textAreaBars fm field contentW contentH-      pure $ case rectIntersect clip field of-        Just fclip-          | visibleHit fclip && (tabVertical bars || tabHorizontal bars) -> Just idx-        _ -> Nothing-  | isScrollNode nt && visibleHit clip = pure (Just idx)-  | otherwise = pure Nothing-  where-    visibleHit r@(Rect _ _ rw rh) = rw > 0 && rh > 0 && rectContains r mouse---- Same clip stack as the span walk: scroll viewport (plus its bar lanes),--- then panel bounds.-scrollHitClip :: Context -> NodeIdx -> NodeType -> Rect -> IO (Maybe Rect)-scrollHitClip ctx idx nt parentClip-  | isScrollNode nt = do-      (x, y, w, h) <- getRect 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))-      pure (rectIntersect parentClip hit)-  | nt == NodePanel = do-      (x, y, w, h) <- getRect na idx-      pure (rectIntersect parentClip (Rect x y w h))-  | otherwise = pure (Just parentClip)-  where-    na = ctxNodeArena ctx---- | 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 idx wid = do-  nt <- getNodeType na idx-  if nt == NodeTextArea-    then do-      (fm, field, contentW, contentH) <- textAreaContentGeom ctx idx-      cur@(V2 curX curY) <- getScrollOffset2D ctx wid-      let layouts = textAreaScrollBarLayouts fm field contentW contentH curX curY-      pure (axes2D cur (tasbVertical layouts) (tasbHorizontal layouts))-    else do-      (x, y, w, h) <- getRect na idx-      ScrollNode slot cfg native2D dir pad contentMain contentW <- readScrollNode na idx-      if native2D-        then do-          cur@(V2 offX offY) <- getScrollOffset2D ctx wid-          let (mV, mH) = scrollBarLayouts2D slot cfg x y w h pad contentW contentMain offX offY-          pure (axes2D cur mV mH)-        else-          if scrollChromeSuppressed cfg dir-            then pure []-            else do-              off <- getScrollOffset ctx wid-              pure-                [ (dir, layout, \new -> when (new /= off) (setScrollOffset ctx wid new))-                | Just layout <- [scrollBarLayout slot dir x y w h pad contentMain off]-                ]-  where-    na = ctxNodeArena ctx-    axes2D (V2 curX curY) mV mH =-      [(DirColumn, layout, \new -> when (new /= curY) (setScrollOffset2D ctx wid (V2 curX new))) | Just layout <- [mV]]-        ++ [(DirRow, layout, \new -> when (new /= curX) (setScrollOffset2D ctx wid (V2 new curY))) | Just layout <- [mH]]--updateScrollDrag :: Context -> Input -> IO ()-updateScrollDrag ctx inp-  | inputMouseReleased inp = modifyInteraction ctx (\s -> s {isScrollDrag = Nothing})-  | otherwise = do-      gesture <- getMenuPointerGesture ctx-      mDrag <- getScrollDrag ctx-      case mDrag of-        _ | gesture -> pure ()-        Just (wid, dragDir, grabOff)-          | inputMouseDown inp -> do-              -- A hidden bar has no lane to grab.-              bars <- maybe (pure []) (\idx -> scrollBarsFor ctx idx wid) =<< scrollOwnerNode (\cfg _ dir -> scrollChromeSuppressed cfg dir) ctx wid-              forM_ bars $ \(dir, layout, setOffset) ->-                when (dir == dragDir) $-                  setOffset (scrollOffsetFromThumb dir layout grabOff (inputMousePos inp))-        Nothing | inputMousePressed 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 mouse-  forM_ mIdx $ \hitIdx -> do-    wid <- getWidgetId (ctxNodeArena ctx) hitIdx-    bars <- maybe (pure []) (\idx -> scrollBarsFor ctx idx wid) =<< scrollOwnerNode (\cfg _ dir -> scrollChromeSuppressed cfg dir) ctx wid-    forM_ (find (\(_, l, _) -> rectContains (sbThumb l) mouse || rectContains (sbTrack l) mouse) bars) $-        \(dir, layout, setOffset) -> do-          let thumb = sbThumb layout-              along (V2 mx my) = if dir == DirColumn then my else mx-              Rect tx ty tw th = thumb-          if rectContains thumb mouse-            then modifyInteraction ctx (\s -> s {isScrollDrag = Just (wid, dir, along mouse - along (V2 tx ty))})-            else do-              let half = along (V2 tw th) / 2-              setOffset (scrollOffsetFromThumb dir layout half mouse)-              modifyInteraction ctx (\s -> s {isScrollDrag = Just (wid, dir, half)})
− lib/NanoUI/Frame/Scroll/Geometry.hs
@@ -1,461 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Scrollbar geometry: gutters, viewport clips, and track and thumb layout.-module NanoUI.Frame.Scroll.Geometry-  ( ScrollPolicy (..)-  , ScrollConfig (..)-  , defaultScrollConfig-  , ScrollBarLayout (..)-  , scrollContentClip-  , scrollViewportClip2D-  , scrollChromeLane-  , scrollBarLayout-  , scrollBarLayouts2D-  , scrollAxisRange-  , scrollOffsetFromThumb-  , padContentClip-  , encodeScrollConfig-  , decodeScrollConfig-  , scrollConfigNative2D-  , scrollDefault1D-  , scrollVerticalAuto-  , scrollVerticalHidden-  , scrollHorizontalHidden-  , scrollAxisGutter-  , scrollGutters2D-  , scrollChromeSuppressed-  , scrollWheelSuppressed-  , scrollLineFor-  , scrollAxisOverflows-  , scrollChromeActive-  , isScrollStyle2D-  , tagClippedSpans-  , padTextClipRect-  , borderContentClip-  ) where--import Data.Bits ((.&.), shiftL, shiftR)-import Data.Maybe (mapMaybe)-import Data.Text (Text)-import NanoUI.Font-  ( ScrollBarSlot (..)-  , scrollBarGap-  , scrollBarGeomFor-  , scrollBarGutter-  , scrollBarSideGap-  , scrollLayoutGutter-  )-import NanoUI.Types (Color, Rect (..), V2 (..), rectH, rectIntersect, rectW, rectX, rectY, v2X, v2Y)-import NanoUI.Layout.Arena (DirTag (..))-import NanoUI.Style (Direction (..), Padding (..), Style (..), styleBorderWidth, windowPad)---- | Axis scrollbar visibility and interaction policy.-data ScrollPolicy-  = ScrollAuto-  | ScrollAlways-  | ScrollNone-  | ScrollHidden-  deriving (Eq, Show, Enum, Bounded)---- | 2D scroll configuration (policy per axis).-data ScrollConfig = ScrollConfig-  { scrollPolicyX :: !ScrollPolicy-  , scrollPolicyY :: !ScrollPolicy-  , scrollClamp :: !Bool-  -- | A bare scroller paints no well of its own: no input background, no-  -- border, no window fill. Only the clipped children render, so a strip that-  -- borrows the scroller for its offset and clip (tab headers) looks exactly-  -- like it did before it started scrolling. Chrome policies still apply on-  -- top: 'ScrollHidden' plus bare is the fully chrome-less scroller.-  , scrollBare :: !Bool-  }-  deriving (Eq, Show)--defaultScrollConfig :: ScrollConfig-defaultScrollConfig =-  ScrollConfig-    { scrollPolicyX = ScrollAuto-    , scrollPolicyY = ScrollAuto-    , scrollClamp = True-    , scrollBare = False-    }--scrollConfigNative2D :: ScrollConfig -> Bool-scrollConfigNative2D cfg =-  scrollAxisActive (scrollPolicyX cfg) && scrollAxisActive (scrollPolicyY cfg)-  where-    scrollAxisActive = \case-      ScrollNone -> False-      _ -> True--encodeScrollConfig :: ScrollConfig -> Int-encodeScrollConfig cfg =-  policyBits (scrollPolicyX cfg)-    + shiftL (policyBits (scrollPolicyY cfg)) 2-    + (if scrollClamp cfg then 16 else 0)-    + (if scrollBare cfg then 32 else 0)-  where-    policyBits = \case-      ScrollAuto -> 0-      ScrollAlways -> 1-      ScrollNone -> 2-      ScrollHidden -> 3--decodeScrollConfig :: Int -> ScrollConfig-decodeScrollConfig bits =-  ScrollConfig-    { scrollPolicyX = decodePolicy (bits .&. 3)-    , scrollPolicyY = decodePolicy (shiftR bits 2 .&. 3)-    , scrollClamp = bits .&. 16 /= 0-    , scrollBare = bits .&. 32 /= 0-    }-  where-    decodePolicy 1 = ScrollAlways-    decodePolicy 2 = ScrollNone-    decodePolicy 3 = ScrollHidden-    decodePolicy _ = ScrollAuto--scrollDefault1D :: Direction -> ScrollConfig-scrollDefault1D Column = scrollVerticalAuto-scrollDefault1D Row = scrollHorizontalAuto--scrollVerticalAuto :: ScrollConfig-scrollVerticalAuto = ScrollConfig ScrollNone ScrollAuto True False--scrollHorizontalAuto :: ScrollConfig-scrollHorizontalAuto = ScrollConfig ScrollAuto ScrollNone True False--scrollVerticalHidden :: ScrollConfig-scrollVerticalHidden = ScrollConfig ScrollNone ScrollHidden True False--scrollHorizontalHidden :: ScrollConfig-scrollHorizontalHidden = ScrollConfig ScrollHidden ScrollNone True False---- | Cross-axis gutter for one bar. @trailPad@ is the scroller's padding on--- the bar's side (right for the vertical bar, bottom for the horizontal one).-scrollAxisGutter ::-  ScrollPolicy ->-  ScrollBarSlot ->-  Float ->-  Float ->-  Float ->-  Float-scrollAxisGutter policy slot trailPad contentSize innerMain =-  case policy of-    ScrollNone -> 0-    ScrollHidden -> 0-    ScrollAuto -> scrollLayoutGutter slot trailPad contentSize innerMain-    ScrollAlways -> scrollBarGutter slot trailPad---- Vertical bar takes width. Horizontal bar takes height. Second pass--- covers the corner case where one bar makes the other axis overflow.-scrollGutters2D ::-  ScrollBarSlot ->-  ScrollConfig ->-  Padding ->-  Float ->-  Float ->-  Float ->-  Float ->-  (Float, Float)-scrollGutters2D slot cfg pad contentW contentH innerW innerH =-  let gVert inner = scrollAxisGutter (scrollPolicyY cfg) slot (padR pad) contentH inner-      gHorz inner = scrollAxisGutter (scrollPolicyX cfg) slot (padB pad) contentW inner-      gW0 = gVert innerH-      gH0 = gHorz innerW-      gW = gVert (innerH - gH0)-      gH = gHorz (innerW - gW0)-   in (gW, gH)--isScrollStyle2D :: Int -> Bool-isScrollStyle2D si = si /= 0 && scrollConfigNative2D (decodeScrollConfig si)--scrollShowsChrome :: ScrollConfig -> DirTag -> Bool-scrollShowsChrome cfg dir =-  case dir of-    DirColumn -> axisShows (scrollPolicyY cfg)-    DirRow -> axisShows (scrollPolicyX cfg)-  where-    axisShows = \case-      ScrollAuto -> True-      ScrollAlways -> True-      _ -> False--scrollChromeSuppressed :: ScrollConfig -> DirTag -> Bool-scrollChromeSuppressed cfg dir = not (scrollShowsChrome cfg dir)---- | Distance one wheel notch scrolls along a live axis. Window hosts step a--- text line. Widgets that map wheel notches onto a scroller's offset share--- this so the step cannot drift per caller.-scrollLineFor :: Float-scrollLineFor = 20---- | Wheel eligibility is wider than chrome eligibility: a hidden bar never--- paints or drags, but it still scrolls. Only a dead axis ('ScrollNone')--- ignores the wheel outright. Native 2D scrollers always keep both axes--- live by construction.-scrollWheelSuppressed :: ScrollConfig -> Bool -> DirTag -> Bool-scrollWheelSuppressed cfg native2D dir =-  not native2D-    && ( case dir of-           DirColumn -> scrollPolicyY cfg == ScrollNone-           DirRow -> scrollPolicyX cfg == ScrollNone-       )--scrollAxisOverflows :: ScrollPolicy -> Float -> Float -> Bool-scrollAxisOverflows policy contentSize innerMain =-  case policy of-    ScrollNone -> False-    ScrollHidden -> False-    ScrollAlways -> True-    ScrollAuto -> contentSize > innerMain + 0.5---- | Scroll range along one axis. Content that fits (modulo the trailing--- padding, which must not surface a bar by itself) does not scroll; genuine--- overflow extends the range past the last child by the trailing padding so--- scrolling to the end still reveals it. Stored content sizes exclude the--- trailing padding (see positionScrollChildren); this is where it is added--- back into the reachable range.-scrollAxisRange :: Float -> Float -> Float -> Float-scrollAxisRange contentSize innerMain trailingPad-  | contentSize > innerMain + 0.5 = max 0 (contentSize + trailingPad - innerMain)-  | otherwise = 0--scrollChromeActive :: ScrollConfig -> DirTag -> Float -> Float -> Bool-scrollChromeActive cfg dir contentSize innerMain =-  scrollShowsChrome cfg dir-    && scrollAxisOverflows-      (case dir of-         DirColumn -> scrollPolicyY cfg-         DirRow -> scrollPolicyX cfg)-      contentSize-      innerMain--data ScrollBarLayout = ScrollBarLayout-  { sbTrack :: Rect-  , sbThumb :: Rect-  , sbMaxOff :: Float-  }-  deriving (Eq, Show)--padContentClip :: Float -> Float -> Float -> Float -> Padding -> Rect-padContentClip x y w h pad =-  Rect-    (x + padL pad)-    (y + padT pad)-    (max 0 (w - padL pad - padR pad))-    (max 0 (h - padT pad - padB pad))--scrollContentClip ::-  ScrollBarSlot ->-  ScrollConfig ->-  DirTag ->-  Float ->-  Float ->-  Float ->-  Float ->-  Padding ->-  Float ->-  Rect-scrollContentClip slot cfg dir x y w h pad contentSize =-  let base = padContentClip x y w h pad-      innerMain =-        case dir of-          DirColumn -> rectH base-          DirRow -> rectW base-      (policy, trailPad) =-        case dir of-          DirColumn -> (scrollPolicyY cfg, padR pad)-          DirRow -> (scrollPolicyX cfg, padB pad)-      gutter = scrollAxisGutter policy slot trailPad contentSize innerMain-   in case dir of-        DirColumn -> Rect (rectX base) (rectY base) (max 0 (rectW base - gutter)) (rectH base)-        DirRow -> Rect (rectX base) (rectY base) (rectW base) (max 0 (rectH base - gutter))--scrollViewportClip2D ::-  ScrollBarSlot ->-  ScrollConfig ->-  Float ->-  Float ->-  Float ->-  Float ->-  Padding ->-  Float ->-  Float ->-  Rect-scrollViewportClip2D slot cfg x y w h pad contentW contentH =-  let base = padContentClip x y w h pad-      innerW = rectW base-      innerH = rectH base-      (gutterW, gutterH) = scrollGutters2D slot cfg pad contentW contentH innerW innerH-   in Rect (rectX base) (rectY base) (max 0 (innerW - gutterW)) (max 0 (innerH - gutterH))---- | The strip a bar sits in. A list bar sits one gap (see 'scrollBarGap')--- inside its well's edge. A page bar sits a side gap inside the page's edge,--- and a window body's bar a side gap inside the window's edge, out in the--- window's padding. The gutter keeps the content one gap before each of them.-scrollChromeLane ::-  ScrollBarSlot -> DirTag -> Float -> Float -> Float -> Float -> Padding -> Rect-scrollChromeLane slot dir x y w h pad =-  let (barW, _) = scrollBarGeomFor slot-      -- From the scroller's edge in to the bar's far side. Window and modal-      -- bodies only scroll vertically, so the window's side padding is the-      -- one that places their bar.-      inset trailPad = case slot of-        ScrollBarList -> scrollBarGap trailPad-        ScrollBarPage -> scrollBarSideGap-        ScrollBarWindow -> scrollBarSideGap - padR windowPad-   in case dir of-        DirColumn ->-          Rect (max x (x + w - inset (padR pad) - barW)) (y + padT pad) barW (max 0 (h - padT pad - padB pad))-        DirRow ->-          Rect (x + padL pad) (max y (y + h - inset (padB pad) - barW)) (max 0 (w - padL pad - padR pad)) barW--scrollBarLayout ::-  ScrollBarSlot ->-  DirTag ->-  Float ->-  Float ->-  Float ->-  Float ->-  Padding ->-  Float ->-  Float ->-  Maybe ScrollBarLayout-scrollBarLayout slot dir x y w h pad contentSize off =-  let innerW = w - padL pad - padR pad-      innerH = h - padT pad - padB pad-      viewMain = case dir of-        DirColumn -> innerH-        DirRow -> innerW-   in scrollBarLayoutIn slot dir x y w h pad viewMain contentSize off---- | 'scrollBarLayout' with an explicit visible main extent. A native 2D--- scroller passes the padding box minus the cross-axis lane (see--- 'scrollGutters2D'), so its reachable range and thumb reflect the viewport--- that is actually visible rather than the lane-underlapped padding box. On a--- one-dimensional scroller @viewMain@ is just the padding box on that axis.-scrollBarLayoutIn ::-  ScrollBarSlot ->-  DirTag ->-  Float ->-  Float ->-  Float ->-  Float ->-  Padding ->-  Float ->-  Float ->-  Float ->-  Maybe ScrollBarLayout-scrollBarLayoutIn slot dir x y w h pad viewMain contentSize off =-  let (barW, barMargin) = scrollBarGeomFor slot-      minThumb = 16-   in case dir of-        DirColumn ->-          let trailH = padB pad-              extentH = contentSize + trailH-              maxOff = scrollAxisRange contentSize viewMain trailH-           in if maxOff <= 0-                then Nothing-                else-                  let lane = scrollChromeLane slot DirColumn x y w h pad-                      trackX = rectX lane-                      trackY = y + padT pad + barMargin-                      trackH = max 0 (viewMain - 2 * barMargin)-                      thumbH = max minThumb (trackH * viewMain / extentH)-                      ratio = off / maxOff-                      thumbY = trackY + ratio * (trackH - thumbH)-                   in-                    Just-                      ScrollBarLayout-                        { sbTrack = Rect trackX trackY barW trackH-                        , sbThumb = Rect trackX thumbY barW thumbH-                        , sbMaxOff = maxOff-                        }-        DirRow ->-          let trailW = padR pad-              extentW = contentSize + trailW-              maxOff = scrollAxisRange contentSize viewMain trailW-           in if maxOff <= 0-                then Nothing-                else-                  let lane = scrollChromeLane slot DirRow x y w h pad-                      trackY = rectY lane-                      trackX = x + padL pad + barMargin-                      trackW = max 0 (viewMain - 2 * barMargin)-                      thumbW = max minThumb (trackW * viewMain / extentW)-                      ratio = off / maxOff-                      thumbX = trackX + ratio * (trackW - thumbW)-                   in-                    Just-                      ScrollBarLayout-                        { sbTrack = Rect trackX trackY trackW barW-                        , sbThumb = Rect thumbX trackY thumbW barW-                        , sbMaxOff = maxOff-                        }---- | Both-axis layouts for a native 2D scroller: (vertical, horizontal). Each--- axis's visible main extent is reduced by the other axis's live gutter, so--- the range and thumb are computed against the viewport minus the opposite--- scrollbar lane.-scrollBarLayouts2D ::-  ScrollBarSlot ->-  ScrollConfig ->-  Float ->-  Float ->-  Float ->-  Float ->-  Padding ->-  Float ->-  Float ->-  Float ->-  Float ->-  (Maybe ScrollBarLayout, Maybe ScrollBarLayout)-scrollBarLayouts2D slot cfg x y w h pad contentW contentH offX offY =-  let innerW = w - padL pad - padR pad-      innerH = h - padT pad - padB pad-      (gutterW, gutterH) = scrollGutters2D slot cfg pad contentW contentH innerW innerH-      viewW = max 0 (innerW - gutterW)-      viewH = max 0 (innerH - gutterH)-      v = scrollBarLayoutIn slot DirColumn x y w h pad viewH contentH offY-      hr = scrollBarLayoutIn slot DirRow x y w h pad viewW contentW offX-   in (v, hr)--scrollOffsetFromThumb :: DirTag -> ScrollBarLayout -> Float -> V2 -> Float-scrollOffsetFromThumb dir layout grabOff mouse =-  let maxOff = sbMaxOff layout-      track = sbTrack layout-      thumb = sbThumb layout-   in case dir of-        DirColumn ->-          let trackY = rectY track-              trackH = rectH track-              thumbH = rectH thumb-              thumbTop = v2Y mouse - grabOff-              ratio = (thumbTop - trackY) / max 1 (trackH - thumbH)-           in max 0 (min maxOff (ratio * maxOff))-        DirRow ->-          let trackX = rectX track-              trackW = rectW track-              thumbW = rectW thumb-              thumbLeft = v2X mouse - grabOff-              ratio = (thumbLeft - trackX) / max 1 (trackW - thumbW)-           in max 0 (min maxOff (ratio * maxOff))--textClipSlop :: Float-textClipSlop = 4--tagClippedSpans :: Rect -> [(Rect, Text, Color, Color)] -> [(Rect, Text, Color, Color, Rect)]-tagClippedSpans clip =-  mapMaybe (\(rect, txt, fg, bg) -> (rect, txt, fg, bg,) <$> rectIntersect clip (padTextClipRect rect))--padTextClipRect :: Rect -> Rect-padTextClipRect (Rect x y w h) = Rect x y (w + textClipSlop) h--borderContentClip :: Style -> Rect -> Rect-borderContentClip style (Rect x y w h) =-  if styleBorderWidth style <= 0-    then Rect x y w h-    else-      let bw = max 1 (styleBorderWidth style)-       in Rect (x + bw) (y + bw) (max 0 (w - 2 * bw)) (max 0 (h - 2 * bw))
− lib/NanoUI/Frame/Select.hs
@@ -1,473 +0,0 @@-{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Select-  ( selectDropRect-  , selectDropPickIndex-  , closeSelectOnOutsideClick-  , finalizeSelectKeyboard-  , finalizeSelectPick-  , markSelectDropPress-  , drawSelectOverlays-  , collectSelectDropdownSpans-  , findSelectUnderMouse-  , overlayMenuOwnerAt-  , cacheOpenSelectDrop-  , tagSelectClippedSpans-  , comboDropRect-  , comboDropPickIndex-  , comboScrollGeom-  ) where--import Control.Monad (forM, forM_, unless, when)-import Data.Foldable (find)-import Data.IORef (readIORef, writeIORef)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (catMaybes, listToMaybe, maybeToList)-import qualified Data.Text as T-import NanoUI.Context-  ( Context (..)-  , TextInputMenu (..)-  , WidgetStore (..)-  , anySelectOpen-  , closeSelects-  , getStore-  , getTextInputMenu-  , intKey-  , isSelectOpen-  , markDirty-  , markEscapeConsumed-  , setSelectOpen-  , setStore-  , widgetTheme-  , isDisabled-  , InteractionState (..)-  , modifyInteraction-  )-import NanoUI.Draw (pushRect, pushRoundedRect, pushText, withClip)-import NanoUI.Font (FontMetrics, centeredTextY, menuItemPadX, menuItemRowH, menuOuterPad, widgetContentInset)-import NanoUI.Frame.Chrome (overlayMenuStyle, paintMenuAccent, paintMenuPanel)-import NanoUI.Frame.Hit (findNodeByWidgetId, widgetOverlayAllowed)-import NanoUI.Frame.Scroll.Geometry (padTextClipRect)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (Input (..), Key (..), foldInputKeys, inputKeys, inputMouseDown, inputMousePos, inputMousePressed)-import NanoUI.Layout.Arena (NodeType (NodeSelect, NodeTextInput), findNodeM, foldNodeRevM, getNodeType, lookupNodeByWidgetId, getOptions, getRect, getWidgetId)-import NanoUI.Store (Slot (..), slotKey)-import NanoUI.Style (Style (..), Theme (..), scrollBarThumbColor, scrollBarTrackColor, themeAccent, themeInput)-import NanoUI.Types (Color (..), Rect (..), V2 (..), rectContains, rectIntersect)-import NanoUI.WidgetText (selectChevronReserve)---- | An open dropdown: a select with its open flag set, or a combo box (a--- search field carrying options) exactly while it holds focus.-data Dropdown = Dropdown-  { ddWidget :: !WidgetId-  , ddCombo :: !Bool-  , ddOptions :: [T.Text]-  , ddAnchor :: !Rect-  , ddRect :: !Rect-  , ddPicked :: !Int-  -- ^ Row shown as picked: the select's value, or the combo's keyboard-  -- highlight relative to its window (-1 highlights nothing).-  , ddComboRows :: !Int-  , ddComboWindow :: !Int-  , ddComboScrollX :: !Float-  , ddComboContentW :: !Float-  }---- | Every open dropdown, in arena order.-openDropdowns :: Context -> IO [Dropdown]-openDropdowns ctx = do-  store <- getStore ctx-  focus <- readIORef (ctxFocusId ctx)-  -- Selects open only through the store flag and combos only while focused.-  -- With no select open, the focused node is the only candidate, so only an-  -- open select walks the arena.-  if anySelectOpen store-    then foldNodeRevM na (\acc idx -> maybe acc (: acc) <$> dropdownAt store focus idx) []-    else-      if hashWidgetId focus == 0-        then pure []-        else maybe (pure []) (fmap maybeToList . dropdownAt store focus) =<< lookupNodeByWidgetId na focus-  where-    na = ctxNodeArena ctx-    dropdownAt store focus idx =-      getNodeType na idx >>= \case-        NodeSelect -> do-          wid <- getWidgetId na idx-          if isSelectOpen store (intKey wid) then Just <$> build store idx wid False else pure Nothing-        NodeTextInput -> do-          wid <- getWidgetId na idx-          opts <- getOptions na idx-          if wid /= focus || null opts then pure Nothing else Just <$> build store idx wid True-        _ -> pure Nothing-    build store idx wid combo = do-      opts <- getOptions na idx-      (x, y, w, h) <- getRect na idx-      let key = intKey wid-          slotInt slot def = IM.findWithDefault def (slotKey slot key) (storeInt store)-          slotFloat slot = IM.findWithDefault 0 (slotKey slot key) (storeFloat store)-          nOpts = length opts-          rows = slotInt SlotComboCount nOpts-          window = slotInt SlotComboScroll 0-          contentW = slotFloat SlotComboContentW-      pure-        Dropdown-          { ddWidget = wid-          , ddCombo = combo-          , ddOptions = opts-          , ddAnchor = Rect x y w h-          , ddRect =-              if combo-                then comboDropRect x y w h nOpts rows contentW-                else selectDropRect x y w h nOpts-          , ddPicked =-              if combo-                then slotInt SlotComboHighlight (-1) - window-                else IM.findWithDefault 0 key (storeInt store)-          , ddComboRows = rows-          , ddComboWindow = window-          , ddComboScrollX = slotFloat SlotComboScrollX-          , ddComboContentW = contentW-          }---- | One placed row of an open dropdown.-data DropdownRow = DropdownRow-  { drIndex :: !Int-  , drOption :: T.Text-  , drRect :: !Rect-  , drTextX :: !Float-  , drHovered :: !Bool-  }---- | Rows of an open dropdown, shared by its painter and its text spans. Combo--- rows sit flush at the drop rect's top edge (no outer margin) and scroll--- horizontally; select rows keep their padded layout.-dropdownRows :: FontMetrics -> V2 -> Dropdown -> [DropdownRow]-dropdownRows fm mouse dd =-  let Rect dx dy dw _ = ddRect dd-      top = if ddCombo dd then dy else dy + menuOuterPad-      textX0 = dx + menuItemPadX + fst (widgetContentInset fm)-      textX = if ddCombo dd then textX0 - ddComboScrollX dd else textX0-   in [ DropdownRow i opt row textX (rectContains row mouse)-      | (i, opt) <- zip [0 ..] (ddOptions dd)-      , let row = Rect dx (top + menuItemRowH * fromIntegral i) dw menuItemRowH-      ]--overlayMenuOwnerAt :: Context -> V2 -> IO (Maybe WidgetId)-overlayMenuOwnerAt ctx mouse = do-  mMenu <- getTextInputMenu ctx-  case mMenu of-    Just m | rectContains (textInputMenuRect m) mouse -> pure (Just (textInputMenuWidget m))-    _ -> fmap ddWidget . find (\dd -> rectContains (ddRect dd) mouse) <$> openDropdowns ctx--cacheOpenSelectDrop :: Context -> IO ()-cacheOpenSelectDrop ctx = do-  dropdowns <- openDropdowns ctx-  modifyInteraction ctx (\s -> s {isOpenSelectDrop = (\dd -> (ddWidget dd, ddRect dd)) <$> listToMaybe dropdowns})--markSelectDropPress :: Context -> Input -> IO ()-markSelectDropPress ctx inp =-  when (inputMouseDown inp) $ do-    store <- getStore ctx-    when (anySelectOpen store) $ do-      let mouse = inputMousePos inp-      dropdowns <- openDropdowns ctx-      when (any (\dd -> rectContains (ddAnchor dd) mouse || rectContains (ddRect dd) mouse) dropdowns) $-        modifyInteraction ctx (\s -> s {isSelectDropPress = True})--closeSelectOnOutsideClick :: Context -> Input -> IO ()-closeSelectOnOutsideClick ctx inp =-  when (inputMousePressed inp || inputMouseReleased inp) $ do-    store <- getStore ctx-    when (anySelectOpen store) $ do-      let mouse = inputMousePos inp-      dropdowns <- openDropdowns ctx-      unless (any (\dd -> rectContains (ddAnchor dd) mouse || rectContains (ddRect dd) mouse) dropdowns) $-        setStore ctx (closeSelects store)--finalizeSelectKeyboard :: Context -> Input -> IO ()-finalizeSelectKeyboard ctx inp = do-  let (wantNext, wantPrev, wantEsc, wantEnter) =-        foldInputKeys-          ( \(n, p, e, r) k ->-              ( n || k == KeyDown || k == KeyRight-              , p || k == KeyUp || k == KeyLeft-              , e || k == KeyEscape-              , r || k == KeyEnter-              )-          )-          (False, False, False, False)-          (inputKeys inp)-      wantStep = wantNext || wantPrev-  when (wantStep || wantEsc || wantEnter) $ do-    focus <- readIORef (ctxFocusId ctx)-    store <- getStore ctx-    mTarget <- pickSelectKeyboardTarget ctx focus store wantStep-    forM_ mTarget $ \(wid, open) -> do-      allow <- widgetOverlayAllowed ctx wid-      when allow $-        if wantEsc || wantEnter-          then when open $ do-            setStore ctx (setSelectOpen store (intKey wid) False)-            when wantEsc $ markEscapeConsumed ctx-            markDirty ctx-          else do-            mIdx <- findNodeByWidgetId ctx wid-            forM_ mIdx $ \idx -> do-              n <- length <$> getOptions (ctxNodeArena ctx) idx-              when (n > 0) $ do-                let key = intKey wid-                    cur = IM.findWithDefault 0 key (storeInt store)-                    next = max 0 (min (n - 1) (cur + if wantNext then 1 else -1))-                when (next /= cur) $ do-                  setStore ctx (store {storeInt = IM.insert key next (storeInt store)})-                  markDirty ctx--pickSelectKeyboardTarget :: Context -> WidgetId -> WidgetStore -> Bool -> IO (Maybe (WidgetId, Bool))-pickSelectKeyboardTarget ctx focus store wantStep = do-  mFocus <- if wantStep then selectWidgetIfAny ctx focus else pure Nothing-  case mFocus of-    Just wid -> pure (Just (wid, isSelectOpen store (intKey wid)))-    Nothing -> fmap (,True) <$> findOpenSelectWidget ctx--selectWidgetIfAny :: Context -> WidgetId -> IO (Maybe WidgetId)-selectWidgetIfAny ctx wid-  | hashWidgetId wid == 0 = pure Nothing-  | otherwise = do-      mIdx <- findNodeByWidgetId ctx wid-      case mIdx of-        Nothing -> pure Nothing-        Just idx -> do-          nt <- getNodeType (ctxNodeArena ctx) idx-          disabled <- isDisabled ctx wid-          pure (if nt == NodeSelect && not disabled then Just wid else Nothing)--findOpenSelectWidget :: Context -> IO (Maybe WidgetId)-findOpenSelectWidget ctx = do-  store <- getStore ctx-  let na = ctxNodeArena ctx-  mIdx <--    findNodeM na $ \idx -> do-      nt <- getNodeType na idx-      if nt /= NodeSelect-        then pure False-        else isSelectOpen store . intKey <$> getWidgetId na idx-  traverse (getWidgetId na) mIdx--finalizeSelectPick :: Context -> Input -> IO ()-finalizeSelectPick ctx inp =-  when (inputMousePressed inp || inputMouseReleased inp) $ do-    let mouse@(V2 _ mouseY) = inputMousePos inp-    dropdowns <- openDropdowns ctx-    forM_ dropdowns $ \dd -> do-      allow <- widgetOverlayAllowed ctx (ddWidget dd)-      when (allow && rectContains (ddRect dd) mouse) $ do-        st <- getStore ctx-        let wid = ddWidget dd-            key = intKey wid-            nOpts = length (ddOptions dd)-        if ddCombo dd-          then do-            -- Combo: pick on press only, never from the scrollbar lanes, so-            -- finishing a thumb drag cannot commit a row. Picking commits the-            -- option text into the field and defocuses it: the combo's-            -- dropdown is visible exactly while focused, so the menu-            -- disappears with the pick.-            let (_, vSb, hSb, _) = comboScrollGeom (ddRect dd) (ddComboRows dd) nOpts (ddComboWindow dd) (ddComboScrollX dd) (ddComboContentW dd)-                onLane = any (\(track, _) -> rectContains track mouse) (catMaybes [vSb, hSb])-            when (inputMousePressed inp && not onLane) $-              forM_ (comboDropPickIndex (ddRect dd) menuItemRowH nOpts mouseY) $ \picked -> do-                let txt = maybe "" id (listToMaybe (drop picked (ddOptions dd)))-                    len = T.length txt-                setStore-                  ctx-                  ( st-                      { storeText = IM.insert key txt (storeText st)-                      , storeInt =-                          IM.insert (slotKey SlotCursor key) len $-                            IM.insert (slotKey SlotAnchor key) len (storeInt st)-                      }-                  )-                writeIORef (ctxFocusId ctx) (WidgetId 0)-                markDirty ctx-          else-            forM_ (selectDropPickIndex (ddRect dd) menuItemRowH nOpts mouseY) $ \picked -> do-              setStore ctx (setSelectOpen (st {storeInt = IM.insert key picked (storeInt st)}) key False)-              writeIORef (ctxFocusId ctx) wid-              markDirty ctx---- | Topmost open dropdown owner (in reverse arena order) whose anchor or menu--- is under @mouse@ and that the modal state lets receive input.-findSelectUnderMouse :: Context -> V2 -> IO (Maybe WidgetId)-findSelectUnderMouse ctx mouse = do-  dropdowns <- openDropdowns ctx-  firstAllowed [dd | dd <- reverse dropdowns, rectContains (ddAnchor dd) mouse || rectContains (ddRect dd) mouse]-  where-    firstAllowed [] = pure Nothing-    firstAllowed (dd : rest) = do-      allow <- widgetOverlayAllowed ctx (ddWidget dd)-      if allow then pure (Just (ddWidget dd)) else firstAllowed rest---- | Vertical gap between the select widget and its dropdown menu.-selectDropGap :: Float-selectDropGap = 4--selectDropRect :: Float -> Float -> Float -> Float -> Int -> Rect-selectDropRect x y w h nOpts =-  Rect x (y + h + selectDropGap) w (menuItemRowH * fromIntegral nOpts + 2 * menuOuterPad)--selectDropPickIndex :: Rect -> Float -> Int -> Float -> Maybe Int-selectDropPickIndex dropRect itemH nOpts mouseY =-  let Rect _ dy _ dh = dropRect-      innerH = itemH * fromIntegral nOpts-      rel = mouseY - dy - max 0 ((dh - innerH) / 2)-   in if rel < 0 || rel >= innerH-        then Nothing-        else Just (max 0 (min (nOpts - 1) (floor (rel / max itemH 1))))---- Combo dropdown scrollbar sizes: lane thickness and the shortest a thumb--- ever gets.-comboSbW, comboSbMinThumb :: Float-comboSbW = 10-comboSbMinThumb = 24---- | Scrollbar geometry for a combo dropdown, shared by the overlay painter,--- the pick guard, and the widget's thumb-drag gesture. The list has no outer--- margin: rows fill the drop rect edge to edge, and a vertical lane sits on--- the right when rows overflow the window, a horizontal one on the bottom--- when the widest row overflows the width. Returns (inner rows area,--- vertical (track, thumb), horizontal (track, thumb), usable content width).-comboScrollGeom ::-  Rect ->-  Int ->-  Int ->-  Int ->-  Float ->-  Float ->-  (Rect, Maybe (Rect, Rect), Maybe (Rect, Rect), Float)-comboScrollGeom (Rect dx dy dw dh) n vis win xOff contentW =-  let-    vScroll = n > vis && vis > 0-    vLaneW = if vScroll then comboSbW else 0-    usableW = max 0 (dw - vLaneW)-    hScroll = contentW > usableW && contentW > 0-    hLaneH = if hScroll then comboSbW else 0-    -- Rows fill the drop rect from the top, stopping short of the lanes.-    inner = Rect dx dy (max 0 (dw - vLaneW)) (max 0 (dh - hLaneH))-    -- Lanes sit flush against the dropdown border and share the corner.-    vTrack = Rect (dx + dw - comboSbW) dy comboSbW (max 0 (dh - hLaneH))-    hTrack = Rect dx (dy + dh - comboSbW) (max 0 (dw - vLaneW)) comboSbW-    vSb =-      if vScroll-        then-          let Rect vx vy _ vh = vTrack-              trackH = max 1 vh-              thumbH = max (min comboSbMinThumb trackH) (min trackH (trackH * fromIntegral vis / fromIntegral n))-              maxWin = max 1 (n - vis)-              ty = vy + (trackH - thumbH) * fromIntegral (max 0 (min maxWin win)) / fromIntegral maxWin-           in Just (vTrack, Rect (vx + 2) ty (comboSbW - 4) thumbH)-        else Nothing-    hSb =-      if hScroll-        then-          let Rect hx hy hw _ = hTrack-              trackW = max 1 hw-              thumbW = max (min comboSbMinThumb trackW) (min trackW (trackW * usableW / contentW))-              maxOff = max 1 (contentW - usableW)-              tx = hx + (trackW - thumbW) * max 0 (min maxOff xOff) / maxOff-           in Just (hTrack, Rect tx (hy + 2) thumbW (comboSbW - 4))-        else Nothing-   in (inner, vSb, hSb, usableW)---- | Combo dropdown rect: like 'selectDropRect', but with no outer margin--- (rows start flush at the top), and the height reserves a flush bottom--- scrollbar lane when the widest row overflows, so the horizontal bar never--- covers the bottommost row. Must agree with 'comboScrollGeom' on when lanes--- appear (same inputs, same formulas).-comboDropRect :: Float -> Float -> Float -> Float -> Int -> Int -> Float -> Rect-comboDropRect x y w h nRows nTotal contentW =-  let vLaneW = if nTotal > nRows then comboSbW else 0-      hScroll = contentW > max 0 (w - vLaneW) && contentW > 0-   in Rect x (y + h + selectDropGap) w (fromIntegral nRows * menuItemRowH + (if hScroll then comboSbW else 0))---- | Row index at @mouseY@ for a combo dropdown, whose rows start flush at the--- drop rect's top (unlike 'selectDropPickIndex', which centers them).-comboDropPickIndex :: Rect -> Float -> Int -> Float -> Maybe Int-comboDropPickIndex (Rect _ dy _ _) itemH nOpts mouseY =-  let rel = mouseY - dy-   in if rel < 0 || rel >= itemH * fromIntegral nOpts-        then Nothing-        else Just (max 0 (min (nOpts - 1) (floor (rel / max itemH 1))))--drawSelectOverlays :: Context -> Input -> IO ()-drawSelectOverlays ctx inp = do-  dropdowns <- openDropdowns ctx-  forM_ dropdowns $ \dd -> do-    allow <- widgetOverlayAllowed ctx (ddWidget dd)-    when allow $ do-      theme <- widgetTheme ctx (ddWidget dd)-      drawDropdownMenu ctx inp theme dd---- | Paint one open dropdown (select or combo). The combo list clips to its--- inner area (so x-shifted text and row fills stop at the scrollbar lanes)--- and gets vertical / horizontal scrollbars when the filtered rows or the--- widest row overflow the window.-drawDropdownMenu :: Context -> Input -> Theme -> Dropdown -> IO ()-drawDropdownMenu ctx inp theme dd = do-  let da = ctxDrawArena ctx-      fm = ctxFontMetrics ctx-      style = overlayMenuStyle theme-      paintRows =-        forM_ (dropdownRows fm (inputMousePos inp) dd) $ \row -> do-          let picked = drIndex row == ddPicked dd-              Rect _ ry _ rh = drRect row-          if drHovered row-            then do-              pushRect da (drRect row) (styleHoverBg style)-              paintMenuAccent da theme (drRect row)-            else when picked $ pushRect da (drRect row) (styleActiveBg style)-          unless (T.null (drOption row)) $ do-            (_, th) <- ctxMeasureText ctx (drOption row)-            pushText da fm (drTextX row) (centeredTextY fm ry rh th) (drOption row) $-              if picked then themeAccent theme else styleFg style-  paintMenuPanel da theme style (ddRect dd)-  if ddCombo dd-    then do-      let (inner, vSb, hSb, _) = comboScrollGeom (ddRect dd) (ddComboRows dd) (length (ddOptions dd)) (ddComboWindow dd) (ddComboScrollX dd) (ddComboContentW dd)-          base = themeInput theme-          drawBar (track, thumb) = do-            pushRect da track (scrollBarTrackColor base theme)-            pushRoundedRect da thumb 3 (scrollBarThumbColor base theme)-      withClip da inner paintRows-      mapM_ drawBar vSb-      mapM_ drawBar hSb-    else paintRows--collectSelectDropdownSpans :: Context -> Input -> IO [(Rect, T.Text, Color, Color, Rect)]-collectSelectDropdownSpans ctx inp = do-  dropdowns <- openDropdowns ctx-  let fm = ctxFontMetrics ctx-  fmap concat . forM dropdowns $ \dd -> do-    allow <- widgetOverlayAllowed ctx (ddWidget dd)-    style <- overlayMenuStyle <$> widgetTheme ctx (ddWidget dd)-    if not allow-      then pure []-      else fmap concat . forM (dropdownRows fm (inputMousePos inp) dd) $ \row ->-        if T.null (drOption row)-          then pure []-          else do-            (tw, th) <- ctxMeasureText ctx (drOption row)-            let Rect _ ry _ rh = drRect row-                bg-                  | drHovered row = styleHoverBg style-                  | drIndex row == ddPicked dd = styleActiveBg style-                  | otherwise = styleBg style-            pure [(Rect (drTextX row) (centeredTextY fm ry rh th) tw th, drOption row, styleFg style, bg, ddRect dd)]--tagSelectClippedSpans ::-  Rect -> Float -> Float -> Float -> Float -> FontMetrics -> [(Rect, T.Text, Color, Color)] -> [(Rect, T.Text, Color, Color, Rect)]-tagSelectClippedSpans parentClip x y w h fm spans =-  let (ix, _) = widgetContentInset fm-      textClip = padTextClipRect (Rect (x + ix) y (max 0 (w - ix - selectChevronReserve)) (max 0 h))-   in case rectIntersect parentClip textClip of-        Nothing -> []-        Just clip -> [(rect, txt, fg, bg, clip) | (rect, txt, fg, bg) <- spans]
− lib/NanoUI/Frame/SpanArena.hs
@@ -1,151 +0,0 @@-{-# LANGUAGE RecordWildCards #-}---- | Flat span buffer: strided prim arrays for geometry and colors, boxed texts.-module NanoUI.Frame.SpanArena-  ( SpanArena-  , newSpanArena-  , resetSpanArena-  , pushSpan-  , spanArenaCount-  , spanArenaToList-  , spanArenaToListOccluded-  , foldSpanArena-  ) where--import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import qualified Data.IntMap.Strict as IM-import Data.Primitive.Array (MutableArray, copyMutableArray, newArray, readArray, sizeofMutableArray, writeArray)-import Data.Primitive.PrimArray-  ( MutablePrimArray-  , newPrimArray-  , readPrimArray-  , resizeMutablePrimArray-  , writePrimArray-  )-import Data.Text (Text)-import qualified Data.Text as T-import Data.Word (Word32)-import GHC.Exts (RealWorld)-import NanoUI.Types (Color (..), Rect (..), colorToWord32, rectFullyInside, rectIntersect)--data SpanArena = SpanArena-  { saCount :: IORef Int-  , saArrays :: IORef SpanArenaArrays-  }---- | Span columns. @saRects@ holds 'rectStride' floats per span (the span rect,--- then its clip), @saColors@ the foreground and background, and @saTexts@ one--- text per span; its size is the capacity.-data SpanArenaArrays = SpanArenaArrays-  { saRects :: !(MutablePrimArray RealWorld Float)-  , saColors :: !(MutablePrimArray RealWorld Word32)-  , saTexts :: !(MutableArray RealWorld Text)-  }--rectStride :: Int-rectStride = 8--newSpanArena :: Int -> IO SpanArena-newSpanArena cap0 = do-  let cap = max 16 cap0-  saCount <- newIORef 0-  saRects <- newPrimArray (cap * rectStride)-  saColors <- newPrimArray (cap * 2)-  saTexts <- newArray cap T.empty-  saArrays <- newIORef SpanArenaArrays {..}-  pure SpanArena {..}--resetSpanArena :: SpanArena -> IO ()-resetSpanArena sa = writeIORef (saCount sa) 0--spanArenaCount :: SpanArena -> IO Int-spanArenaCount sa = readIORef (saCount sa)--{-# NOINLINE growSpanArena #-}-growSpanArena :: SpanArena -> SpanArenaArrays -> Int -> IO SpanArenaArrays-growSpanArena sa SpanArenaArrays {saRects = rects, saColors = colors, saTexts = texts} needed = do-  let cap = sizeofMutableArray texts-      newCap = max needed (cap * 2)-  saRects <- resizeMutablePrimArray rects (newCap * rectStride)-  saColors <- resizeMutablePrimArray colors (newCap * 2)-  saTexts <- newArray newCap T.empty-  copyMutableArray saTexts 0 texts 0 cap-  let a = SpanArenaArrays {..}-  writeIORef (saArrays sa) a-  pure a--{-# INLINE pushSpan #-}-pushSpan :: SpanArena -> Rect -> Text -> Color -> Color -> Rect -> IO ()-pushSpan sa (Rect x y w h) txt fg bg (Rect cx cy cw ch) = do-  i <- readIORef (saCount sa)-  a0 <- readIORef (saArrays sa)-  SpanArenaArrays {..} <--    if i < sizeofMutableArray (saTexts a0) then pure a0 else growSpanArena sa a0 (i + 1)-  let !r = i * rectStride-  writePrimArray saRects r x-  writePrimArray saRects (r + 1) y-  writePrimArray saRects (r + 2) w-  writePrimArray saRects (r + 3) h-  writePrimArray saRects (r + 4) cx-  writePrimArray saRects (r + 5) cy-  writePrimArray saRects (r + 6) cw-  writePrimArray saRects (r + 7) ch-  writePrimArray saColors (2 * i) (colorToWord32 fg)-  writePrimArray saColors (2 * i + 1) (colorToWord32 bg)-  writeArray saTexts i txt-  writeIORef (saCount sa) (i + 1)--spanArenaToList :: SpanArena -> IO [(Rect, Text, Color, Color, Rect)]-spanArenaToList = spanArenaToListOccluded IM.empty---- | Spans in push order, dropping those hidden behind @panels@.-spanArenaToListOccluded :: IM.IntMap Rect -> SpanArena -> IO [(Rect, Text, Color, Color, Rect)]-spanArenaToListOccluded panels sa =-  foldSpans panels sa True (\acc r t fg bg c -> pure ((r, t, fg, bg, c) : acc)) []--foldSpanArena :: SpanArena -> (Rect -> Text -> Color -> Color -> Rect -> IO ()) -> IO ()-foldSpanArena sa f = foldSpans IM.empty sa False (\_ r t fg bg c -> f r t fg bg c) ()---- | Fold over the spans not hidden behind @panels@, first to last, or last to--- first when @backwards@ (so a consing fold builds a list in push order).-{-# INLINE foldSpans #-}-foldSpans ::-  IM.IntMap Rect ->-  SpanArena ->-  Bool ->-  (acc -> Rect -> Text -> Color -> Color -> Rect -> IO acc) ->-  acc ->-  IO acc-foldSpans panels sa backwards f z = do-  n <- readIORef (saCount sa)-  SpanArenaArrays {..} <- readIORef (saArrays sa)-  let panelRects = IM.elems panels-      go !i !acc-        | i < 0 || i >= n = pure acc-        | otherwise = do-            let !r = i * rectStride-            x <- readPrimArray saRects r-            y <- readPrimArray saRects (r + 1)-            w <- readPrimArray saRects (r + 2)-            h <- readPrimArray saRects (r + 3)-            cx <- readPrimArray saRects (r + 4)-            cy <- readPrimArray saRects (r + 5)-            cw <- readPrimArray saRects (r + 6)-            ch <- readPrimArray saRects (r + 7)-            fg <- readPrimArray saColors (2 * i)-            bg <- readPrimArray saColors (2 * i + 1)-            txt <- readArray saTexts i-            let rect = Rect x y w h-                clip = Rect cx cy cw ch-            acc' <--              if not (null panelRects) && spanOccluded panelRects rect clip-                then pure acc-                else f acc rect txt (Color fg) (Color bg) clip-            go (if backwards then i - 1 else i + 1) acc'-  go (if backwards then n - 1 else 0) z--spanOccluded :: [Rect] -> Rect -> Rect -> Bool-spanOccluded panelRects rect clip =-  case rectIntersect rect clip of-    Nothing -> True-    Just visible -> any (rectFullyInside visible) panelRects
− lib/NanoUI/Frame/Spans.hs
@@ -1,463 +0,0 @@-{-# LANGUAGE DataKinds #-}--module NanoUI.Frame.Spans-  ( collectTextSpans-  , collectOverlayTextSpans-  , collectRasterSpans-  , widgetNodeCount-  , widgetHitRect-  , widgetTextSpans-  , forWidgetTextPlacements_-  , selectableTextGeometry-  , collectNodeTextSpans-  ) where--import Control.Monad (forM, unless, when)-import Data.IORef (readIORef, writeIORef)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (fromMaybe, isJust)-import qualified Data.Text as T-import NanoUI.Context-  ( Context (..)-  , SpanCacheEntry (..)-  , WidgetTextCacheEntry (..)-  , WidgetTextPlacement (..)-  , nodeTheme-  )-import NanoUI.Damage (floatingPanelRects)-import NanoUI.Font-  ( FontMetrics (..)-  , alignedTextPen-  , centeredTextY-  , checkboxLeading-  , menuItemPadX-  , prepareFontMetrics-  , tableCellInset-  , treeRowLeading-  , truncateTextIO-  , widgetContentInset-  , wrapTextLinesIO-  )-import NanoUI.Frame.Chrome (displayText, textInputFocused, textInputValue, widgetVisualStyle)-import NanoUI.Frame.Node (readScrollNode, resolveFontFor, scrollNodeViewport)-import NanoUI.Frame.Scroll.Geometry (padContentClip, tagClippedSpans)-import NanoUI.Frame.Select (collectSelectDropdownSpans, tagSelectClippedSpans)-import NanoUI.Frame.SpanArena (SpanArena, pushSpan, resetSpanArena, spanArenaToList, spanArenaToListOccluded)-import NanoUI.Frame.TextEdit.Menu (collectTextEditMenuSpans)-import NanoUI.Frame.TextInput (syncTextInputScroll, tagTextInputClippedSpans, textInputFieldRect)-import NanoUI.Input (Input)-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , SizingTag (..)-  , arenaCount-  , forNodes_-  , getAlignX-  , getClipRect-  , getFirstChild-  , getMinMax-  , getNextSibling-  , getNodeFontColor-  , getNodeFontSize-  , getNodeType-  , getPadding-  , getRect-  , getStyleIdx-  , getText-  , getWidthSizing-  , isFloatingNode-  , isScrollNode-  , hasCenteredLabel-  , isWidgetNode-  , parentIsRow-  )-import NanoUI.Layout.Solve (findAncestorMaxW, textWrapCap)-import NanoUI.Style (AlignX (..), FontVariant (..), Style (..), Theme (..), themeAccent, themeMuted, themePanel)-import NanoUI.Types (Color (..), Rect (..), lerpColor, onGrid, rectIntersect)-import NanoUI.Widgets.ColorPicker (ColorPickerPart (..), colorPickerPartOf, colorPickerPartRect, colorPickerPreviewGeom)-import NanoUI.WidgetText-  ( colorPickerCurrentLabel-  , colorPickerNewLabel-  , isCloseButtonStyle-  , isMenuItemStyle-  , isTableHeaderStyle-  , numericTextClip-  , selectChevronReserve-  , tableStripeColor-  , textInputNumericMode-  , textInputFieldText-  , textInputSearchMode-  , textInputSelectableMode-  , textNodeFontVariant-  , treeDecodeStyle-  )--collectTextSpans :: Context -> IO [(Rect, T.Text, Color, Color, Rect)]-collectTextSpans ctx = do-  count <- arenaCount (ctxNodeArena ctx)-  let arena = ctxSpanBase ctx-  resetSpanArena arena-  when (count > 0) $-    collectClippedSpans ctx 0 (Rect 0 0 1e9 1e9) arena-  panels <- floatingPanelRects ctx-  spanArenaToListOccluded panels arena--collectOverlayTextSpans :: Context -> Input -> IO [(Rect, T.Text, Color, Color, Rect)]-collectOverlayTextSpans ctx inp = do-  let arena = ctxSpanOverlay ctx-      push (r, t, fg, bg, c) = pushSpan arena r t fg bg c-  resetSpanArena arena-  collectFloatingSpansInto ctx NodeWindow arena-  collectFloatingSpansInto ctx NodeModal arena-  collectFloatingSpansInto ctx NodePopup arena-  drops <- collectSelectDropdownSpans ctx inp-  menu <- collectTextEditMenuSpans ctx inp-  mapM_ push drops-  mapM_ push menu-  spanArenaToList arena--collectRasterSpans :: Context -> Input -> IO ([(Rect, T.Text, Color, Color, Rect)], [(Rect, T.Text, Color, Color, Rect)])-collectRasterSpans ctx inp = (,) <$> collectTextSpans ctx <*> collectOverlayTextSpans ctx inp--widgetNodeCount :: Context -> IO Int-widgetNodeCount ctx = arenaCount (ctxNodeArena ctx)--{-# INLINE collectClippedSpans #-}-collectClippedSpans :: Context -> NodeIdx -> Rect -> SpanArena -> IO ()-collectClippedSpans ctx idx clip arena = do-  nt <- getNodeType (ctxNodeArena ctx) idx-  unless (isFloatingNode nt) $-    collectClippedSpans' ctx idx nt clip arena--collectClippedSpans' :: Context -> NodeIdx -> NodeType -> Rect -> SpanArena -> IO ()-collectClippedSpans' ctx idx nt clip arena = do-  (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-  mClipChildren <--    if isScrollNode nt-      then-        getClipRect (ctxNodeArena ctx) idx >>= \case-          Just live -> pure (rectIntersect clip live)-          Nothing -> (\sn -> rectIntersect clip (scrollNodeViewport sn x y w h)) <$> readScrollNode (ctxNodeArena ctx) idx-      else pure (if nt == NodePanel then rectIntersect clip (Rect x y w h) else Just clip)-  case mClipChildren of-    Nothing -> pure ()-    Just clipHere -> do-      let fm = ctxFontMetrics ctx-      spans <- collectNodeTextSpans ctx idx-      here <--        case nt of-          NodeSelect -> pure (tagSelectClippedSpans clipHere x y w h fm spans)-          NodeTextInput -> do-            si <- getStyleIdx (ctxNodeArena ctx) idx-            pure $-              if textInputNumericMode si-                then maybe [] (`tagClippedSpans` spans) (rectIntersect clipHere (numericTextClip fm x y w h))-                else-                  if textInputSelectableMode si-                    then tagClippedSpans clipHere spans-                    else tagTextInputClippedSpans clipHere x y w h fm spans-          _ -> pure (tagClippedSpans clipHere spans)-      mapM_ (\(r, t, fg, bg, c) -> pushSpan arena r t fg bg c) here-      walkChildSpans ctx idx clipHere arena--walkChildSpans :: Context -> NodeIdx -> Rect -> SpanArena -> IO ()-walkChildSpans ctx idx clip arena = getFirstChild (ctxNodeArena ctx) idx >>= go-  where-    go ci-      | ci < 0 = pure ()-      | otherwise = do-          ns <- getNextSibling (ctxNodeArena ctx) ci-          -- Later siblings paint under earlier ones; walk reverse then collect.-          go ns-          collectClippedSpans ctx ci clip arena---- | Text spans of one node. A text node's spans are cached per node until--- its inputs change. Placement uses glyph ink ('alignedTextPen'), not--- TTF_GetStringSize; wrapping still measures with the host so line breaks--- stay on the TTF width.-collectNodeTextSpans :: Context -> NodeIdx -> IO [(Rect, T.Text, Color, Color)]-collectNodeTextSpans ctx idx = do-  let arena = ctxNodeArena ctx-  nt <- getNodeType arena idx-  (x, y, w, h) <- getRect arena idx-  if nt /= NodeText-    then if isWidgetNode nt then widgetTextSpans ctx nt idx x y w h else pure []-    else do-      theme <- nodeTheme ctx idx-      raw <- getText arena idx-      si <- getStyleIdx arena idx-      mCustomCol <- getNodeFontColor arena idx-      fontSize <- getNodeFontSize arena idx-      ax <- getAlignX arena idx-      (_, _, maxW, _) <- getMinMax arena idx-      (wTag, _) <- getWidthSizing arena idx-      isRowChild <- parentIsRow arena idx-      effMaxW <- if maxW < 1e8 then pure maxW else findAncestorMaxW arena idx-      let rect = Rect x y w h-          mStripe = tableStripeColor theme si-          variantFg = case textNodeFontVariant si of-            FontHeading -> themeAccent theme-            FontMuted -> themeMuted theme-            FontDanger -> themeRed theme-            _ -> styleFg (themePanel theme)-          fg = fromMaybe variantFg mCustomCol-          bg = fromMaybe (styleBg (themePanel theme)) mStripe-      cache <- readIORef (ctxSpanCache ctx)-      case IM.lookup idx cache of-        Just e-          | sceText e == raw-              && sceFg e == fg-              && sceBg e == bg-              && sceStyle e == si-              && sceFontSize e == fontSize-              && sceAlign e == fromEnum ax-              && sceWidthTag e == fromEnum wTag-              && sceRect e == rect-              && sceEffMaxW e == effMaxW-              && sceRowChild e == isRowChild ->-              pure (sceSpans e)-        _ -> do-          placed <--            if T.null raw-              then pure []-              else do-                (fm, _, measure) <- resolveFontFor ctx NodeText fontSize si-                let ix = if isJust mStripe then tableCellInset else 0-                    measureW = fmap fst . measure-                    lineH = fmLineHeight fm-                    contentW = max 0 (w - 2 * ix)-                    wrapCap = textWrapCap effMaxW wTag w-                tw <- measureW raw-                if T.any (== '\n') raw || (not isRowChild && wrapCap < 1e8 && wrapCap + 0.5 < tw)-                  then do-                    textLines <- wrapTextLinesIO measureW raw (max 0 (wrapCap - 2 * ix))-                    forM (zip [(0 :: Int) ..] textLines) $ \(i, line) -> do-                      prepared <- prepareFontMetrics fm line-                      let (tx, used) = alignedTextPen ax x w ix prepared line-                          ty = centeredTextY fm (y + onGrid (fmSnapScale fm) (fromIntegral i * lineH)) lineH lineH-                      pure (Rect tx ty used lineH, line)-                  else do-                    shown <--                      if tw > contentW && contentW > 0 && (wTag == SizingGrow || maxW < 1e8)-                        then truncateTextIO measureW contentW raw-                        else pure raw-                    prepared <- prepareFontMetrics fm shown-                    let (tx, used) = alignedTextPen ax x w ix prepared shown-                    pure [(Rect tx (centeredTextY fm y h lineH) used lineH, shown)]-          let spans = [(r, line, fg, bg) | (r, line) <- placed]-          writeIORef (ctxSpanCache ctx) $-            IM.insert-              idx-              SpanCacheEntry-                { sceText = raw-                , sceFg = fg-                , sceBg = bg-                , sceStyle = si-                , sceFontSize = fontSize-                , sceAlign = fromEnum ax-                , sceWidthTag = fromEnum wTag-                , sceRect = rect-                , sceEffMaxW = effMaxW-                , sceRowChild = isRowChild-                , sceSpans = spans-                }-              cache-          pure spans--widgetHitRect :: Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO Rect-widgetHitRect ctx nt idx x y w h = do-  let fm = ctxFontMetrics ctx-  case nt of-    NodeTextInput -> do-      si <- getStyleIdx (ctxNodeArena ctx) idx-      if textInputSearchMode si || textInputSelectableMode si || textInputNumericMode si-        then pure (Rect x y w h)-        else pure (textInputFieldRect fm x y w h)-    NodeTextArea -> pure (Rect x y w h)-    NodeButton -> do-      si <- getStyleIdx (ctxNodeArena ctx) idx-      -- Close buttons get a padded target that stays inside the title bar, so-      -- the inner east resize still works below the control.-      if isCloseButtonStyle si-        then pure (Rect (x - 8) (y - 4) (w + 10) (h + 4))-        else pure (Rect x y w h)-    _ -> pure (Rect x y w h)--widgetTextSpans ::-  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(Rect, T.Text, Color, Color)]-widgetTextSpans ctx nt idx x y w h = do-  style <- widgetVisualStyle ctx nt idx-  mFontColor <- getNodeFontColor (ctxNodeArena ctx) idx-  placements <- widgetTextPlacements ctx nt idx x y w h-  let fg = fromMaybe (styleFg style) mFontColor-      bg = styleBg style-  case nt of-    NodeTextInput -> do-      value <- textInputValue ctx idx-      focus <- textInputFocused ctx idx-      let fieldFg = if T.null value && not focus then lerpColor fg bg 0.40 else fg-      pure [(Rect px py tw th, txt, fieldFg, bg) | (txt, px, py, tw, th) <- placements]-    _ ->-      pure [(Rect px py tw th, txt, fg, bg) | (txt, px, py, tw, th) <- placements, not (T.null txt)]---- | Cacheable widget labels depend on text, style, font size, alignment and--- dimensions, but not the absolute node origin. Text--- fields / areas / colour pickers / sliders are data-dependent and stay out.-cacheableWidgetLabel :: NodeType -> Bool-cacheableWidgetLabel = hasCenteredLabel--widgetTextPlacements ::-  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(T.Text, Float, Float, Float, Float)]-widgetTextPlacements ctx nt idx x y w h-  | cacheableWidgetLabel nt = do-      placement <- cachedWidgetLabel ctx nt idx w h-      pure [(txt, x + px, y + py, tw, th) | Just (WidgetTextPlacement txt px py tw th) <- [placement]]-  | otherwise = computeWidgetTextPlacements ctx nt idx x y w h---- | Runtime consumer API. The Bool marks the last placement (for table sort--- arrows); cached labels are translated directly into the consumer.-{-# INLINE forWidgetTextPlacements_ #-}-forWidgetTextPlacements_ ::-  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float ->-  (Bool -> T.Text -> Float -> Float -> Float -> Float -> IO ()) -> IO ()-forWidgetTextPlacements_ ctx nt idx x y w h emit-  | cacheableWidgetLabel nt = do-      placement <- cachedWidgetLabel ctx nt idx w h-      case placement of-        Nothing -> pure ()-        Just (WidgetTextPlacement txt px py tw th) -> emit True txt (x + px) (y + py) tw th-  | otherwise = do-      placements <- computeWidgetTextPlacements ctx nt idx x y w h-      let go [] = pure ()-          go ((txt, px, py, tw, th) : rest) =-            emit (null rest) txt px py tw th >> go rest-      go placements--cachedWidgetLabel :: Context -> NodeType -> NodeIdx -> Float -> Float -> IO (Maybe WidgetTextPlacement)-cachedWidgetLabel ctx nt idx w h = do-  fontSizeVal <- getNodeFontSize (ctxNodeArena ctx) idx-  si <- getStyleIdx (ctxNodeArena ctx) idx-  txt <- displayText ctx nt idx-  ax <--    if nt == NodeButton && isTableHeaderStyle si-      then getAlignX (ctxNodeArena ctx) idx-      else pure AlignStart-  let ntTag = fromEnum nt-  cache <- readIORef (ctxWidgetTextCache ctx)-  case IM.lookup idx cache of-    Just e-      | wtcNodeType e == ntTag-          && wtcStyle e == si-          && wtcFontSize e == fontSizeVal-          && wtcText e == txt-          && wtcWidth e == w-          && wtcHeight e == h-          && wtcAlign e == fromEnum ax -> pure (wtcPlacement e)-    _ -> do-      placement <- computeWidgetLabel ctx nt txt si fontSizeVal ax w h-      writeIORef-        (ctxWidgetTextCache ctx)-        (IM.insert idx (WidgetTextCacheEntry ntTag si fontSizeVal txt w h (fromEnum ax) placement) cache)-      pure placement---- All coordinates here are local. centeredTextY snaps the baseline offset,--- not the origin; final device-pixel snapping stays in the draw backend.-computeWidgetLabel :: Context -> NodeType -> T.Text -> Int -> Float -> AlignX -> Float -> Float -> IO (Maybe WidgetTextPlacement)-computeWidgetLabel ctx nt txt si fontSizeVal ax w h-  | nt == NodeButton && isCloseButtonStyle si = pure Nothing-  | otherwise = do-      (source, _, measure) <- resolveFontFor ctx nt fontSizeVal si-      fm <- prepareFontMetrics source txt-      (tw, th) <- measure txt-      let (ix, _) = widgetContentInset fm-          (tx, used) = case nt of-            NodeButton-              | isTableHeaderStyle si -> alignedTextPen ax 0 w tableCellInset fm txt-              | isMenuItemStyle si ->-                  let inset = menuItemPadX + ix-                   in (inset, min tw (max 0 (w - inset - ix)))-              | otherwise -> alignedTextPen AlignCenter 0 w 0 fm txt-            NodeSelect -> (ix, min tw (w - ix - selectChevronReserve))-            NodeTree ->-              let (_, depth, _, _) = treeDecodeStyle si-               in (treeRowLeading fm depth, tw)-            _ -> (checkboxLeading fm, tw)-      let !placement = WidgetTextPlacement txt tx (centeredTextY fm 0 h th) used th-      pure (Just placement)---- | Pure geometry of selectable text: the pen origin, centered baseline box and--- line height. Selectable text never scrolls, so the pen is just the node x.--- Paint uses this and skips the width measure; span placement adds it.-selectableTextGeometry :: FontMetrics -> Float -> Float -> Float -> (Float, Float, Float)-selectableTextGeometry fm x y h =-  let lineH = fmLineHeight fm-   in (x, centeredTextY fm y h lineH, lineH)--computeWidgetTextPlacements ::-  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(T.Text, Float, Float, Float, Float)]-computeWidgetTextPlacements ctx nt idx x y w h = do-  fontSizeVal <- getNodeFontSize (ctxNodeArena ctx) idx-  si <- getStyleIdx (ctxNodeArena ctx) idx-  (fm, _, measureTxt) <- resolveFontFor ctx nt fontSizeVal si-  let (ix, iy) = widgetContentInset fm-      lineH = fmLineHeight fm-  case nt of-    NodeColorPicker-      | colorPickerPartOf si /= PickerPreview -> pure []-      | otherwise -> do-          band@(Rect bx _ _ _) <- colorPickerPartRect (ctxNodeArena ctx) idx (Rect x y w h)-          let (currentY, _, newY, _) = colorPickerPreviewGeom fm band-              labelH = fmLineHeight fm-          (cw, ch) <- measureTxt colorPickerCurrentLabel-          (nw, nh) <- measureTxt colorPickerNewLabel-          pure-            [ (colorPickerCurrentLabel, bx, centeredTextY fm currentY labelH ch, cw, ch)-            , (colorPickerNewLabel, bx, centeredTextY fm newY labelH nh, nw, nh)-            ]-    NodeSlider -> pure []-    NodeTextInput-      | textInputSelectableMode si -> do-          value <- textInputValue ctx idx-          let (penX, ty, selLineH) = selectableTextGeometry fm x y h-          (fw, _) <- measureTxt value-          pure [(value, penX, ty, fw, selLineH)]-      | otherwise -> do-          let numeric = textInputNumericMode si-          ph <- if numeric then pure "" else getText (ctxNodeArena ctx) idx-          value <- textInputValue ctx idx-          focus <- textInputFocused ctx idx-          let fieldTxt = textInputFieldText ph value focus-              Rect _ fieldY _ fieldH = if numeric then Rect x y w h else textInputFieldRect fm x y w h-          (fw, _) <- measureTxt fieldTxt-          scrollX <- syncTextInputScroll ctx idx x y w h-          pure [(fieldTxt, x + ix - scrollX, centeredTextY fm fieldY fieldH lineH, fw, lineH)]-    NodeTextArea -> do-      lbl <- getText (ctxNodeArena ctx) idx-      value <- textInputValue ctx idx-      (lw, lh) <- measureTxt lbl-      (fw, _) <- measureTxt (if T.null value then " " else value)-      pure-        [ (lbl, x, centeredTextY fm y lineH lh, lw, lh)-        , (value, x + ix, y + iy, fw, h)-        ]-    NodeDrawing -> pure []-    _ -> do-      txt <- displayText ctx nt idx-      ax <- getAlignX (ctxNodeArena ctx) idx-      (_, th) <- measureTxt txt-      prepared <- prepareFontMetrics fm txt-      let (tx, used) = alignedTextPen ax x w ix prepared txt-      pure [(txt, tx, centeredTextY fm y h th, used, th)]---- | Spans inside every floating panel of one kind, clipped to its content box.-collectFloatingSpansInto :: Context -> NodeType -> SpanArena -> IO ()-collectFloatingSpansInto ctx wanted arena =-  forNodes_ (ctxNodeArena ctx) $ \idx -> do-    nt <- getNodeType (ctxNodeArena ctx) idx-    when (nt == wanted) $ do-      (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-      clip <--        if isScrollNode nt-          then (\sn -> scrollNodeViewport sn x y w h) <$> readScrollNode (ctxNodeArena ctx) idx-          else padContentClip x y w h <$> getPadding (ctxNodeArena ctx) idx-      walkChildSpans ctx idx clip arena
− lib/NanoUI/Frame/TextArea.hs
@@ -1,326 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Multi-line text areas: content painting (lines, selection, caret and--- scrollbars) and mouse selection.-module NanoUI.Frame.TextArea-  ( TextAreaHit (..)-  , textAreaHitForWidget-  , drawTextAreaContentWith-  , finalizeTextAreaMouse-  , collapseTextAreaSelection-  ) where--import Control.Monad (forM_, unless, when)-import Data.IORef (writeIORef)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (catMaybes, isJust)-import qualified Data.Text as T-import NanoUI.Context-  ( Context (..)-  , TextInputDrag (..)-  , WidgetStore (..)-  , getStore-  , intKey-  , markDirty-  , setStore-  , setTextInputDrag-  , slotKey-  , nodeTheme-  , getsInteraction-  , InteractionState (..)-  )-import NanoUI.Draw (DrawArena, getDrawSnapScale, pushText, withClip)-import NanoUI.Font (FontMetrics, caretXIO, prepareFontMetrics, selectionSpans, textIndexAtX, widgetContentInset)-import NanoUI.Frame.Chrome (paintScrollBarLayout, textInputFocused)-import NanoUI.Frame.Hit (findNodeByWidgetId)-import NanoUI.Frame.TextArea.Content-  ( ensureTextAreaBuffer-  , isMouseOnTextAreaScrollBarAt-  , resolveTextAreaFont-  , textAreaContentMetrics-  )-import NanoUI.Frame.TextArea.Geometry-import NanoUI.Frame.TextInput (drawTextCaret, drawTextSelectionLine, normalizeTextFieldClicks)-import NanoUI.Id (WidgetId)-import NanoUI.Input-  ( Input (..)-  , inputMouseClicks-  , inputMouseDown-  , inputMousePos-  , inputMousePressed-  , inputMouseReleased-  )-import NanoUI.Layout.Arena (NodeIdx, NodeType (NodeTextArea), getNodeType, getRect, getWidgetId)-import NanoUI.Store (Slot (..))-import NanoUI.Style (Style (..), Theme, scrollBarThumbColor, scrollBarTrackColor, themePanel, themeSelection)-import NanoUI.Types (Rect (..), V2 (..), onGrid, rectContains)-import NanoUI.Widgets.TextArea (TextAreaState (..), loadTextAreaState, saveTextAreaState)-import qualified NanoUI.Widgets.TextArea as TA-import qualified NanoUI.Widgets.TextBuffer as TB-import NanoUI.Widgets.TextCommon (selectionCaretGeom, textWordBounds)--data TextAreaHit = TextAreaHit-  { tahNodeIdx :: !NodeIdx-  , tahFieldRect :: !Rect-  , tahContentX :: !Float-  , tahLineH :: !Float-  , tahWidgetX :: !Float-  , tahWidgetY :: !Float-  , tahWidgetW :: !Float-  , tahWidgetH :: !Float-  }---- | Editor state of the text area at @idx@, its viewport set from the field--- clip.-loadTextAreaStateAt :: Context -> NodeIdx -> FontMetrics -> Float -> Float -> Float -> Float -> IO TA.TextAreaState-loadTextAreaStateAt ctx idx fm x y w h = do-  wid <- getWidgetId (ctxNodeArena ctx) idx-  let key = intKey wid-  store <- getStore ctx-  let initial = IM.findWithDefault "" key (storeText store)-  buf <- ensureTextAreaBuffer ctx key initial-  let Rect _ _ vpW vpH = textAreaFieldClip fm (Rect x y w h)-      state0 = TA.loadTextAreaStateWithBuffer store key buf-  pure (TA.setTextAreaViewport (realToFrac vpW, realToFrac vpH) (realToFrac (textAreaLineHeight fm)) state0)--loadHitState :: Context -> TextAreaHit -> IO TA.TextAreaState-loadHitState ctx hit = do-  fm <- resolveTextAreaFont ctx (tahNodeIdx hit)-  loadTextAreaStateAt ctx (tahNodeIdx hit) fm (tahWidgetX hit) (tahWidgetY hit) (tahWidgetW hit) (tahWidgetH hit)---- | Record the text viewport and clamp the stored scroll to the content.--- This paint already reflects both, so the write marks nothing dirty: a--- window resize would otherwise request a second frame that has nothing to--- repaint.-syncTextAreaViewport :: Context -> NodeIdx -> FontMetrics -> Float -> Float -> Float -> Float -> IO ()-syncTextAreaViewport ctx idx fm x y w h = do-  wid <- getWidgetId (ctxNodeArena ctx) idx-  (contentW, contentH) <- textAreaContentMetrics ctx idx-  -- Read after the metrics query: a cold query caches into the store.-  store <- getStore ctx-  let key = intKey wid-      Rect _ _ clipW clipH = textAreaFieldClip fm (Rect x y w h)-      bars = textAreaBars fm (Rect x y w h) contentW contentH-      (sx, sy) = IM.findWithDefault (0, 0) (slotKey SlotTextAreaScroll key) (storePoint store)-      sx' = max 0 (min (max 0 (contentW - tabViewW bars)) sx)-      sy' = max 0 (min (max 0 (contentH - tabViewH bars)) sy)-      viewportKey = slotKey SlotTextAreaViewport key-      pts0 = IM.insert viewportKey (clipW, clipH) (storePoint store)-      pts1-        | sx' /= sx || sy' /= sy = IM.insert (slotKey SlotTextAreaScroll key) (sx', sy') pts0-        | otherwise = pts0-  unless (sx' == sx && sy' == sy && IM.lookup viewportKey (storePoint store) == Just (clipW, clipH)) $-    writeIORef (ctxStore ctx) $! store {storePoint = pts1}---- | Snap a text-area scroll offset to the device pixel grid, the same grid--- 'pushText' snaps to, so line pens and hit-testing stay in lockstep (and in--- agreement with each other) while the text area scrolls. The raw 'Double'--- offset keeps sub-pixel wheel deltas; only the applied value is quantized.-textAreaSnap :: DrawArena -> IO (Float -> Float)-textAreaSnap da = onGrid <$> getDrawSnapScale da---- | The selection highlight on the rows between @firstRow@ and @lastRow@,--- the ones in view.-drawTextAreaSelectionLines :: DrawArena -> Int -> Int -> TA.TextAreaState -> Rect -> FontMetrics -> Theme -> IO ()-drawTextAreaSelectionLines da firstRow lastRow state (Rect fieldX fieldY _ _) fm theme = do-  snap <- textAreaSnap da-  let anchor = TA.selectionAnchor state-      cursor = TB.getCursor (TA.buffer state)-  when (anchor /= cursor) $ do-    let (lo, hi) = TB.selectionRange anchor cursor-        lineH = textAreaLineHeight fm-        (ix, iy) = widgetContentInset fm-        (scrollX, scrollY) = TA.scrollOffset state-        scrollXf = snap (realToFrac scrollX)-        scrollYf = snap (realToFrac scrollY)-        contentTop = fieldY + iy-        selBg = themeSelection theme-        loRow = TB.cursorRow lo-        hiRow = TB.cursorRow hi-    forM_ [max loRow firstRow .. min hiRow lastRow] $ \row -> do-      let line = TB.lineAt row (TA.buffer state)-          clampCol c = max 0 (min (T.length line) c)-          startCol = clampCol (if row == loRow then TB.cursorCol lo else 0)-          endCol = clampCol (if row == hiRow then TB.cursorCol hi else T.length line)-      when (startCol < endCol) $ do-        prepared <- prepareFontMetrics fm line-        let ly = contentTop + fromIntegral row * lineH - scrollYf-        forM_ (selectionSpans prepared line startCol endCol) $ \(wLo, wHi) ->-          drawTextSelectionLine da (fieldX + ix + wLo - scrollXf) ly (wHi - wLo) (max 4 lineH) selBg---- | Text-area content with the node font already resolved, so a paint pass--- that also needs it (for the field frame) resolves it once.-drawTextAreaContentWith :: DrawArena -> Context -> FontMetrics -> NodeIdx -> Float -> Float -> Float -> Float -> Style -> IO ()-drawTextAreaContentWith da ctx fm idx x y w h style = do-  snap <- textAreaSnap da-  syncTextAreaViewport ctx idx fm x y w h-  focus <- textInputFocused ctx idx-  theme <- nodeTheme ctx idx-  let field = Rect x y w h-      lineH = textAreaLineHeight fm-      Rect clipX contentTop clipW clipH = textAreaFieldClip fm field-      fg = styleFg style-  state <- loadTextAreaStateAt ctx idx fm x y w h-  (contentW, contentH) <- textAreaContentMetrics ctx idx-  let buf = TA.buffer state-      (scrollX, scrollY) = TA.scrollOffset state-      scrollXf = snap (realToFrac scrollX)-      scrollYf = snap (realToFrac scrollY)-      contentX = clipX - scrollXf-      layouts = textAreaScrollBarLayouts fm field contentW contentH scrollXf scrollYf-      textClip =-        Rect-          clipX-          contentTop-          (if isJust (tasbVertical layouts) then max 0 (clipW - textAreaBarLane) else clipW)-          (if isJust (tasbHorizontal layouts) then max 0 (clipH - textAreaBarLane) else clipH)-      -- Only the rows in view are read, so painting costs the same however-      -- long the document is.-      rowAt py = floor ((py - contentTop + scrollYf) / max 1 lineH) :: Int-      firstRow = max 0 (rowAt y)-      lastRow = min (TB.getLineCount buf - 1) (rowAt (y + h))-  withClip da textClip $ do-    when focus $-      drawTextAreaSelectionLines da firstRow lastRow state field fm theme-    forM_ [firstRow .. lastRow] $ \row -> do-      let line = TB.lineAt row buf-          ly = contentTop + fromIntegral row * lineH - scrollYf-      unless (T.null line) $-        pushText da fm contentX ly line fg-    when focus $ do-      let TB.Cursor row col = TB.getCursor buf-          currentLine = TB.lineAt row buf-      pw <- caretXIO fm currentLine col-      let (caretX, caretY, caretH) = selectionCaretGeom contentX (contentTop + fromIntegral row * lineH - scrollYf) pw lineH-      drawTextCaret da caretX caretY caretH fg-  let base = themePanel theme-  mapM_-    (paintScrollBarLayout da (scrollBarTrackColor base theme) (scrollBarThumbColor base theme))-    (catMaybes [tasbVertical layouts, tasbHorizontal layouts])--textAreaHitForWidget :: Context -> WidgetId -> IO (Maybe TextAreaHit)-textAreaHitForWidget ctx wid = do-  mIdx <- findNodeByWidgetId ctx wid-  case mIdx of-    Nothing -> pure Nothing-    Just idx -> do-      nt <- getNodeType (ctxNodeArena ctx) idx-      if nt /= NodeTextArea-        then pure Nothing-        else do-          (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-          fm <- resolveTextAreaFont ctx idx-          let field = Rect x y w h-              Rect clipX _ _ _ = textAreaFieldClip fm field-          pure-            ( Just-                TextAreaHit-                  { tahNodeIdx = idx-                  , tahFieldRect = field-                  , tahContentX = clipX-                  , tahLineH = textAreaLineHeight fm-                  , tahWidgetX = x-                  , tahWidgetY = y-                  , tahWidgetW = w-                  , tahWidgetH = h-                  }-            )--textAreaCursorAt :: Context -> TA.TextAreaState -> TextAreaHit -> V2 -> IO (Int, Int)-textAreaCursorAt ctx state hit (V2 mouseX mouseY) = do-  snap <- textAreaSnap (ctxDrawArena ctx)-  fm <- resolveTextAreaFont ctx (tahNodeIdx hit)-  let buf = TA.buffer state-      lineCount = max 1 (TB.getLineCount buf)-      (scrollX, scrollY) = TA.scrollOffset state-      scrollXf = snap (realToFrac scrollX)-      scrollYf = snap (realToFrac scrollY)-      (_, iy) = widgetContentInset fm-      Rect _ fieldY _ _ = tahFieldRect hit-      relY = mouseY - (fieldY + iy) + scrollYf-      row = max 0 (min (lineCount - 1) (floor (relY / max 1 (tahLineH hit))))-      line = TB.lineAt row buf-  prepared <- prepareFontMetrics fm line-  pure (row, textIndexAtX prepared line (max 0 (mouseX - (tahContentX hit - scrollXf))))--updateTextAreaSelection :: Context -> WidgetId -> TextAreaHit -> TB.Cursor -> TB.Cursor -> IO ()-updateTextAreaSelection ctx wid hit anchor cursor = do-  state0 <- loadHitState ctx hit-  store <- getStore ctx-  -- A selection change keeps the stored text, so the document is not rejoined.-  let key = intKey wid-      text = IM.findWithDefault "" key (storeText store)-  setStore ctx (TA.saveTextAreaState key text (TA.setTextAreaSelection anchor cursor state0) store)-  markDirty ctx--applyTextAreaClick :: Context -> WidgetId -> TextAreaHit -> Int -> Int -> Int -> IO ()-applyTextAreaClick ctx wid hit row col clicks-  | clicks >= 3 = do-      state <- loadHitState ctx hit-      updateTextAreaSelection ctx wid hit (TB.Cursor 0 0) (TB.documentEnd (TA.buffer state))-  | clicks == 2 = do-      state <- loadHitState ctx hit-      let (lo, hi) = textWordBounds (TB.lineAt row (TA.buffer state)) col-      updateTextAreaSelection ctx wid hit (TB.Cursor row lo) (TB.Cursor row hi)-  | otherwise =-      updateTextAreaSelection ctx wid hit (TB.Cursor row col) (TB.Cursor row col)--applyTextAreaDrag :: Context -> WidgetId -> TextAreaHit -> Int -> Int -> Int -> Int -> Int -> IO ()-applyTextAreaDrag ctx wid hit anchorRow anchorCol row col clicks-  | clicks >= 3 = applyTextAreaClick ctx wid hit row col clicks-  | clicks == 2 = do-      state <- loadHitState ctx hit-      let buf = TA.buffer state-          (a0, a1) = textWordBounds (TB.lineAt anchorRow buf) anchorCol-          (c0, c1) = textWordBounds (TB.lineAt row buf) col-      updateTextAreaSelection ctx wid hit (TB.Cursor anchorRow (min a0 c0)) (TB.Cursor row (max a1 c1))-  | otherwise =-      updateTextAreaSelection ctx wid hit (TB.Cursor anchorRow anchorCol) (TB.Cursor row col)---- | Mouse selection in text area @wid@: press (with word and document--- multi-clicks) and drag. Presses on the scrollbars are left to the scroller.-finalizeTextAreaMouse :: Context -> Input -> WidgetId -> IO ()-finalizeTextAreaMouse ctx inp wid = do-  mHit <- textAreaHitForWidget ctx wid-  case mHit of-    Nothing -> pure ()-    Just hit -> do-      let mouse = inputMousePos inp-      onScroll <- isMouseOnTextAreaScrollBarAt ctx (tahNodeIdx hit) mouse-      let cursorAtMouse = do-            state <- loadHitState ctx hit-            textAreaCursorAt ctx state hit mouse-      if inputMousePressed inp && rectContains (tahFieldRect hit) mouse && not onScroll-        then do-          (row, col) <- cursorAtMouse-          clicks <- normalizeTextFieldClicks ctx wid 0 row col True (max 1 (inputMouseClicks inp))-          applyTextAreaClick ctx wid hit row col clicks-          setTextInputDrag ctx (Just (TextInputDrag wid 0 row col True clicks))-        else do-          mDrag <- getsInteraction ctx isTextInputDrag-          case mDrag of-            Just drag-              | textInputDragWidget drag == wid-                  , textInputDragMultiline drag-                  , inputMouseDown inp || inputMouseReleased inp -> do-                  (row, col) <- cursorAtMouse-                  applyTextAreaDrag-                    ctx-                    wid-                    hit-                    (textInputDragAnchorRow drag)-                    (textInputDragAnchorCol drag)-                    row-                    col-                    (textInputDragClicks drag)-            _ -> pure ()--collapseTextAreaSelection :: Context -> WidgetId -> IO ()-collapseTextAreaSelection ctx wid = do-  store <- getStore ctx-  let key = intKey wid-      text = IM.findWithDefault "" key (storeText store)-      row = IM.findWithDefault 0 (slotKey SlotTextAreaRow key) (storeInt store)-      col = IM.findWithDefault 0 (slotKey SlotTextAreaCol key) (storeInt store)-      state = loadTextAreaState store key text-  setStore ctx (saveTextAreaState key text state {selectionAnchor = TB.Cursor row col} store)
− lib/NanoUI/Frame/TextArea/Content.hs
@@ -1,142 +0,0 @@-{-# LANGUAGE BangPatterns #-}---- | Store-backed text-area content shared by painting, scrolling and hit--- testing: the node font, the cached document buffer and the cached content--- extent. Free of the editor widget modules so scroll code stays light.-module NanoUI.Frame.TextArea.Content-  ( resolveTextAreaFont-  , ensureTextAreaBuffer-  , textAreaContentMetrics-  , textAreaContentGeom-  , isMouseOnTextAreaScrollBarAt-  ) where--import Data.Dynamic (fromDynamic, toDyn)-import Data.IORef (readIORef)-import qualified Data.IntMap.Strict as IM-import Data.Sequence (Seq)-import qualified Data.Sequence as Seq-import Data.Text (Text)-import NanoUI.Context (Context (..), WidgetStore (..), getStore, intKey, setStore, slotKey)-import NanoUI.Font (FontMetrics (..), lineWidthIO)-import NanoUI.Frame.TextArea.Geometry (isMouseOnTextAreaScrollBar)-import NanoUI.Layout.Arena (NodeIdx, getNodeFontSize, getRect, getWidgetId)-import NanoUI.Store-  ( Slot (..)-  )-import NanoUI.Style (FontStyle (..), FontVariant (..), FontWeight (..))-import NanoUI.Types (Rect (..), V2, onGrid)-import qualified NanoUI.Widgets.TextBuffer as TB---- | Font the text-area content is laid out and painted in. Honors the node's--- @layoutFontSize@ (set via 'fontSize' on the editor layout) so a single text--- area can zoom without changing the rest of the UI. A size of 0 means the--- base UI font.-resolveTextAreaFont :: Context -> NodeIdx -> IO FontMetrics-resolveTextAreaFont ctx idx = do-  size <- getNodeFontSize (ctxNodeArena ctx) idx-  if size <= 0-    then pure (ctxFontMetrics ctx)-    else fst <$> ctxResolveFont ctx size WeightNormal FontStyleNormal FontRegular---- | Return the text area's 'TB.TextBuffer', building it from the flat text only--- when the cache is cold. Rebuilding splits the whole document into lines, so--- caching it keeps loads and paint O(1) here. The cache is written together--- with the flat text by 'saveTextAreaState', so a present entry is always the--- buffer for the stored text.-ensureTextAreaBuffer :: Context -> Int -> Text -> IO TB.TextBuffer-ensureTextAreaBuffer ctx key text = do-  store <- getStore ctx-  case IM.lookup (slotKey SlotTextAreaBuffer key) (storeDyn store) >>= fromDynamic of-    Just buf -> pure buf-    Nothing -> do-      let buf = TB.fromText text-      setStore ctx store {storeDyn = IM.insert (slotKey SlotTextAreaBuffer key) (toDyn buf) (storeDyn store)}-      pure buf---- | Content extent of a text area, @(contentWidth, contentHeight)@. Measuring--- the width scans every character of the document, so the result is cached per--- widget and only refreshed when the text changes (the editor clears--- 'SlotTextAreaContentFont') or the node font changes.-textAreaContentMetrics :: Context -> NodeIdx -> IO (Float, Float)-textAreaContentMetrics ctx idx = do-  wid <- getWidgetId (ctxNodeArena ctx) idx-  size <- getNodeFontSize (ctxNodeArena ctx) idx-  store <- getStore ctx-  let key = intKey wid-      cacheKeyF = slotKey SlotTextAreaContentFont key-      cacheKeyW = slotKey SlotTextAreaContentW key-      cacheKeyH = slotKey SlotTextAreaContentH key-      widthsKey = slotKey SlotTextAreaWidths key-      cachedFont = IM.findWithDefault (-1) cacheKeyF (storeFloat store)-      cachedW = IM.findWithDefault (-1) cacheKeyW (storeFloat store)-  if cachedFont == size && cachedW >= 0-    then pure (cachedW, IM.findWithDefault 0 cacheKeyH (storeFloat store))-    else do-      fm <- resolveTextAreaFont ctx idx-      gen <- readIORef (ctxMetricGen ctx)-      buf <- ensureTextAreaBuffer ctx key (IM.findWithDefault "" key (storeText store))-      let lns = TB.bufferLines buf-          lineH = onGrid (fmSnapScale fm) (fmLineHeight fm)-          contentH = fromIntegral (max 1 (Seq.length lns)) * lineH-          (seenHead, seenTail) = TB.changedLines buf-          previous = case IM.lookup widthsKey (storeDyn store) >>= fromDynamic of-            Just lw@(LineWidths font fontGen _ _ _) | font == size && fontGen == gen -> lw-            _ -> LineWidths size gen Seq.empty (-1) 0-          LineWidths _ _ measured widest widestW = previous-          -- Keep the widths of the lines no edit touched since the last-          -- measurement and measure the rest.-          keepHead = min seenHead (Seq.length measured)-          keepTail = min seenTail (Seq.length measured - keepHead)-          changed = Seq.take (Seq.length lns - keepHead - keepTail) (Seq.drop keepHead lns)-      fresh <- traverse (lineWidthIO fm) changed-      let widths = Seq.take keepHead measured <> fresh <> Seq.drop (Seq.length measured - keepTail) measured-          shift = Seq.length lns - Seq.length measured-          freshWidest = Seq.foldlWithIndex (\best i w -> if w > snd best then (keepHead + i, w) else best) (-1, 0) fresh-          -- The widest line so far still counts when it was kept; only when-          -- an edit touched it do the widths need a full pass.-          -- A changed line at least as wide as the old widest also still wins.-          (widest', contentW)-            | widest >= 0 && widest < keepHead = pick (widest, widestW) freshWidest-            | widest >= 0 && widest >= Seq.length measured - keepTail = pick (widest + shift, widestW) freshWidest-            | widest >= 0 && snd freshWidest >= widestW = freshWidest-            | otherwise = Seq.foldlWithIndex (\best i w -> if w > snd best then (i, w) else best) (-1, 0) widths-          pick a b = if snd b > snd a then b else a-      store' <- getStore ctx-      setStore-        ctx-        ( store'-            { storeFloat =-                IM.insert cacheKeyF size $-                  IM.insert cacheKeyH contentH $-                    IM.insert cacheKeyW contentW (storeFloat store')-            , storeDyn =-                IM.insert widthsKey (toDyn (LineWidths size gen widths widest' contentW)) $-                  IM.insert (slotKey SlotTextAreaBuffer key) (toDyn (TB.markLinesSeen buf)) (storeDyn store')-            }-        )-      pure (contentW, contentH)---- | Measured widths of a text area's lines, the font size and metric--- generation they were measured at, and the widest line with its width.-data LineWidths = LineWidths !Float !Int !(Seq Float) !Int !Float---- | Node font, field rect and content extent @(width, height)@ of a text area.--- Zoom changes the node font, so scroll and hit math resolve it here rather--- than using the base font, or the scroll range would clamp short.-textAreaContentGeom :: Context -> NodeIdx -> IO (FontMetrics, Rect, Float, Float)-textAreaContentGeom ctx idx = do-  fm <- resolveTextAreaFont ctx idx-  (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-  (contentW, contentH) <- textAreaContentMetrics ctx idx-  pure (fm, Rect x y w h, contentW, contentH)---- | Whether @mouse@ is over one of the text area's shown scrollbars. Uses the--- cached content extent: this runs on every hover through the cursor query.-isMouseOnTextAreaScrollBarAt :: Context -> NodeIdx -> V2 -> IO Bool-isMouseOnTextAreaScrollBarAt ctx idx mouse = do-  (fm, field, contentW, contentH) <- textAreaContentGeom ctx idx-  wid <- getWidgetId (ctxNodeArena ctx) idx-  store <- getStore ctx-  let (sx, sy) = IM.findWithDefault (0, 0) (slotKey SlotTextAreaScroll (intKey wid)) (storePoint store)-  pure (isMouseOnTextAreaScrollBar fm field contentW contentH sx sy mouse)
− lib/NanoUI/Frame/TextArea/Geometry.hs
@@ -1,103 +0,0 @@--- | Pure text-area geometry: the field box, content clip, and which scrollbars--- show where for a given content extent.-module NanoUI.Frame.TextArea.Geometry-  ( textAreaLineHeight-  , textAreaFieldClip-  , textAreaBarLane-  , TextAreaBars (..)-  , textAreaBars-  , TextAreaScrollBarLayouts (..)-  , textAreaScrollBarLayouts-  , textAreaScrollBarLayout-  , textAreaHScrollBarLayout-  , isMouseOnTextAreaScrollBar-  ) where--import NanoUI.Font (FontMetrics (..), ScrollBarSlot (..), scrollBarGeomFor, scrollBarSideGap, widgetContentInset)-import NanoUI.Frame.Scroll.Geometry (ScrollBarLayout (..), scrollBarLayout, scrollChromeLane)-import NanoUI.Layout.Arena (DirTag (..))-import NanoUI.Style (Padding (..))-import NanoUI.Types (Rect (..), V2, onGrid, rectContains)---- | Text area row height, snapped to the device pixel grid.-textAreaLineHeight :: FontMetrics -> Float-textAreaLineHeight fm = onGrid (fmSnapScale fm) (fmLineHeight fm)---- | Text clip of a text area field. A caption-less text area's field is its--- whole node rect.-textAreaFieldClip :: FontMetrics -> Rect -> Rect-textAreaFieldClip fm (Rect fx fy fw fh) =-  let s = fmSnapScale fm-      (ix, iy) = widgetContentInset fm-   in Rect (fx + onGrid s ix) (fy + onGrid s iy) (max 0 (fw - 2 * ix)) (max 0 (fh - 2 * iy))---- | Width of the vertical and height of the horizontal scrollbar lane.-textAreaBarLane :: Float-textAreaBarLane = fst (scrollBarGeomFor ScrollBarList) + scrollBarSideGap---- | Which scrollbars a text area shows for its content extent, the text--- viewport they leave, and the paddings that place each bar's lane.-data TextAreaBars = TextAreaBars-  { tabVertical :: !Bool-  , tabHorizontal :: !Bool-  , tabViewW :: !Float-  , tabViewH :: !Float-  , tabPadV :: !Padding-  , tabPadH :: !Padding-  }--textAreaBars :: FontMetrics -> Rect -> Float -> Float -> TextAreaBars-textAreaBars fm (Rect _ _ fw fh) contentW contentH =-  let (ix, iy) = widgetContentInset fm-      innerW = max 0 (fw - 2 * ix)-      innerH = max 0 (fh - 2 * iy)-      laneW = textAreaBarLane-      laneH = textAreaBarLane-      -- Either bar's lane can push the other axis into overflow.-      hasV = contentH > (if contentW > innerW then max 0 (innerH - laneH) else innerH)-      hasH = contentW > (if contentH > innerH then max 0 (innerW - laneW) else innerW)-   in TextAreaBars-        { tabVertical = hasV-        , tabHorizontal = hasH-        , tabViewW = if hasV then max 0 (innerW - laneW) else innerW-        , tabViewH = if hasH then max 0 (innerH - laneH) else innerH-        , tabPadV = Padding 0 0 iy (if hasH then iy + laneH else iy)-        , tabPadH = Padding ix (if hasV then ix + laneW else ix) 0 0-        }--data TextAreaScrollBarLayouts = TextAreaScrollBarLayouts-  { tasbVertical :: !(Maybe ScrollBarLayout)-  , tasbHorizontal :: !(Maybe ScrollBarLayout)-  }-  deriving (Eq, Show)--textAreaScrollBarLayouts :: FontMetrics -> Rect -> Float -> Float -> Float -> Float -> TextAreaScrollBarLayouts-textAreaScrollBarLayouts fm field@(Rect x y w h) contentW contentH scrollX scrollY =-  let bars = textAreaBars fm field contentW contentH-      layout shown dir pad content off-        | shown = scrollBarLayout ScrollBarList dir x y w h pad content off-        | otherwise = Nothing-   in TextAreaScrollBarLayouts-        { tasbVertical = layout (tabVertical bars) DirColumn (tabPadV bars) contentH scrollY-        , tasbHorizontal = layout (tabHorizontal bars) DirRow (tabPadH bars) contentW scrollX-        }--textAreaScrollBarLayout :: FontMetrics -> Rect -> Float -> Float -> Maybe ScrollBarLayout-textAreaScrollBarLayout fm field contentH scrollY =-  tasbVertical (textAreaScrollBarLayouts fm field 0 contentH 0 scrollY)--textAreaHScrollBarLayout :: FontMetrics -> Rect -> Float -> Float -> Maybe ScrollBarLayout-textAreaHScrollBarLayout fm field contentW scrollX =-  tasbHorizontal (textAreaScrollBarLayouts fm field contentW 0 scrollX 0)---- | Whether @mouse@ is over a shown bar's lane or track.-isMouseOnTextAreaScrollBar :: FontMetrics -> Rect -> Float -> Float -> Float -> Float -> V2 -> Bool-isMouseOnTextAreaScrollBar fm field@(Rect x y w h) contentW contentH scrollX scrollY mouse =-  let bars = textAreaBars fm field contentW contentH-      layouts = textAreaScrollBarLayouts fm field contentW contentH scrollX scrollY-      onBar dir pad =-        maybe False $ \layout ->-          rectContains (scrollChromeLane ScrollBarList dir x y w h pad) mouse-            || rectContains (sbTrack layout) mouse-   in onBar DirColumn (tabPadV bars) (tasbVertical layouts)-        || onBar DirRow (tabPadH bars) (tasbHorizontal layouts)
− lib/NanoUI/Frame/TextEdit.hs
@@ -1,64 +0,0 @@--- | Text-field editing facade: single-line fields ("NanoUI.Frame.TextInput"),--- text areas ("NanoUI.Frame.TextArea") and their context menu--- ("NanoUI.Frame.TextEdit.Menu"), plus the dispatchers that pick between the--- two field kinds.-module NanoUI.Frame.TextEdit-  ( -- * Dispatch between field kinds-    finalizeTextFieldMouse-  , collapseTextFieldSelection-    -- * Context menu-  , applyTextFieldMenuAction-  , textEditMenuRectAt-  , textEditMenuWidth-    -- * Shared field helpers-  , normalizeTextFieldClicks-  , textWordBounds-    -- * Text areas-  , TextAreaHit (..)-  , TextAreaScrollBarLayouts (..)-  , resolveTextAreaFont-  , textAreaContentMetrics-  , textAreaBarLane-  , textAreaLineHeight-  , textAreaHitForWidget-  , textAreaScrollBarLayout-  , textAreaHScrollBarLayout-  , textAreaScrollBarLayouts-  ) where--import Control.Monad (unless, when)-import Data.IORef (readIORef)-import NanoUI.Context (Context (..), setTextInputDrag)-import NanoUI.Frame.Hit (findNodeByWidgetId)-import NanoUI.Frame.TextArea-import NanoUI.Frame.TextArea.Content (resolveTextAreaFont, textAreaContentMetrics)-import NanoUI.Frame.TextArea.Geometry-import NanoUI.Frame.TextEdit.Menu (applyTextFieldMenuAction, textEditMenuRectAt, textEditMenuWidth)-import NanoUI.Frame.TextInput-import NanoUI.Id (WidgetId, hashWidgetId)-import NanoUI.Input (Input, inputMouseReleased)-import NanoUI.Layout.Arena (NodeType (NodeTextArea, NodeTextInput), getNodeType)-import NanoUI.Widgets.TextCommon (textWordBounds)---- | Mouse selection in the focused field, whichever kind it is. A release--- ends any drag.-finalizeTextFieldMouse :: Context -> Input -> IO ()-finalizeTextFieldMouse ctx inp = do-  focus <- readIORef (ctxFocusId ctx)-  when (hashWidgetId focus /= 0) $ do-    handled <- finalizeTextInputMouse ctx inp focus-    unless handled $ finalizeTextAreaMouse ctx inp focus-  when (inputMouseReleased inp) $-    setTextInputDrag ctx Nothing--collapseTextFieldSelection :: Context -> WidgetId -> IO ()-collapseTextFieldSelection ctx wid =-  when (hashWidgetId wid /= 0) $ do-    mIdx <- findNodeByWidgetId ctx wid-    case mIdx of-      Nothing -> pure ()-      Just idx ->-        getNodeType (ctxNodeArena ctx) idx >>= \case-          NodeTextInput -> collapseTextInputSelection ctx wid-          NodeTextArea -> collapseTextAreaSelection ctx wid-          _ -> pure ()
− lib/NanoUI/Frame/TextEdit/Menu.hs
@@ -1,309 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Text-field context menu (Cut / Copy / Paste / Select All): opening,--- picking, painting, spans and cursor.-module NanoUI.Frame.TextEdit.Menu-  ( textEditMenuWidth-  , textEditMenuRectAt-  , openTextEditMenu-  , finalizeTextEditMenuPick-  , closeTextEditMenuOnOutsideClick-  , closeTextEditMenuOnEscape-  , drawTextEditMenuOverlays-  , collectTextEditMenuSpans-  , textEditMenuCursorKind-  , textFieldWidgetAtMouse-  , applyTextFieldMenuAction-  ) where--import Control.Monad (forM, forM_, unless, when)-import Data.IORef (writeIORef)-import qualified Data.IntMap.Strict as IM-import qualified Data.Text as T-import NanoUI.Context-  ( Context (..)-  , TextInputMenu (..)-  , WidgetStore (..)-  , getStore-  , getTextInputMenu-  , intKey-  , isDisabled-  , markDirty-  , markEscapeConsumed-  , setTextInputMenu-  , widgetTheme-  , InteractionState (..)-  , modifyInteraction-  )-import NanoUI.Draw (pushRect, pushText)-import NanoUI.Font-  ( centeredTextY-  , menuItemPadX-  , menuItemRowH-  , menuMinW-  , menuOuterPad-  , menuSepH-  , widgetContentInset-  )-import NanoUI.Frame.Chrome (overlayMenuStyle, paintMenuAccent, paintMenuPanel)-import NanoUI.Frame.Hit (nodeClippedHit, overlayHitAllowed, widgetOverlayAllowed)-import NanoUI.Frame.TextArea.Content (isMouseOnTextAreaScrollBarAt)-import NanoUI.Id (WidgetId)-import NanoUI.Input-  ( Input (..)-  , Key (..)-  , UiCursorKind (..)-  , inputKeys-  , inputKeysElem-  , inputMousePos-  , inputMousePressed-  , inputMouseRightPressed-  , inputWindowSize-  )-import NanoUI.Layout.Arena (NodeType (NodeTextArea, NodeTextInput), findNodeRevM, getNodeType, getRect, getWidgetId)-import NanoUI.Style (Style (..), themeSeparator)-import NanoUI.Types (Color (..), Rect (..), Size (..), V2 (..), lerpColor, rectContains)-import NanoUI.Widgets.TextEditor (EditorMode (..), TextCommand (..), canRedo, canUndo)-import NanoUI.Widgets.TextField (applyTextFieldCommand, textFieldHistory, textFieldMode)--data TextEditMenuRow-  = TextEditMenuSep-  | TextEditMenuItem Int T.Text---- | The menu's commands, in row order; a row's index is its item number.-textEditMenuCommands :: [TextCommand]-textEditMenuCommands = [Undo, Redo, Cut, Copy, Paste, SelectAll]--textEditMenuRows :: [TextEditMenuRow]-textEditMenuRows =-  [ TextEditMenuItem 0 "Undo"-  , TextEditMenuItem 1 "Redo"-  , TextEditMenuSep-  , TextEditMenuItem 2 "Cut"-  , TextEditMenuItem 3 "Copy"-  , TextEditMenuItem 4 "Paste"-  , TextEditMenuSep-  , TextEditMenuItem 5 "Select All"-  ]---- Use the same row metrics as generic popup menus.-textEditMenuRowH :: TextEditMenuRow -> Float-textEditMenuRowH = \case-  TextEditMenuSep -> menuSepH-  TextEditMenuItem {} -> menuItemRowH--textEditMenuContentH :: Float-textEditMenuContentH = sum (map textEditMenuRowH textEditMenuRows)--textEditMenuWidth :: Context -> IO Float-textEditMenuWidth ctx = do-  ws <- mapM (fmap fst . ctxMeasureText ctx) [lbl | TextEditMenuItem _ lbl <- textEditMenuRows]-  pure (max menuMinW (maximum ws + 2 * menuItemPadX + 2 * menuOuterPad))---- | Menu rect at the pointer, kept inside the window.-textEditMenuRectAt :: Float -> Float -> Float -> Size -> Rect-textEditMenuRectAt x y menuW (Size ww wh) =-  let h = 2 * menuOuterPad + textEditMenuContentH-   in Rect (max 0 (min x (ww - menuW))) (max 0 (min y (wh - h))) menuW h--textEditMenuContentRect :: Rect -> Rect-textEditMenuContentRect (Rect x y w _) =-  Rect (x + menuOuterPad) (y + menuOuterPad) (w - 2 * menuOuterPad) textEditMenuContentH---- | Every row with its band spanning the full menu width.-textEditMenuLayout :: Rect -> [(TextEditMenuRow, Rect)]-textEditMenuLayout menuRect@(Rect mx _ mw _) =-  let Rect _ top _ _ = textEditMenuContentRect menuRect-      go _ [] = []-      go relY (entry : rest) =-        let h = textEditMenuRowH entry-         in (entry, Rect mx (top + relY) mw h) : go (relY + h) rest-   in go 0 textEditMenuRows--textEditMenuPickAction :: Rect -> V2 -> Maybe Int-textEditMenuPickAction menuRect mouse@(V2 _ my) =-  let Rect _ top _ _ = textEditMenuContentRect menuRect-   in if my < top || my >= top + textEditMenuContentH-        then Nothing-        else-          case [entry | (entry, row) <- textEditMenuLayout menuRect, rectContainsY row] of-            TextEditMenuItem action _ : _ -> Just action-            _ -> Nothing-  where-    rectContainsY (Rect _ ry _ rh) = let V2 _ py = mouse in py >= ry && py < ry + rh--textEditMenuItemFg :: Style -> Bool -> Color-textEditMenuItemFg style enabled =-  if enabled-    then styleFg style-    else lerpColor (styleFg style) (styleBg style) 0.55--openTextEditMenu :: Context -> Input -> IO ()-openTextEditMenu ctx inp =-  when (inputMouseRightPressed inp) $ do-    let mouse@(V2 mx my) = inputMousePos inp-    mWid <- textFieldWidgetAtMouse ctx mouse-    case mWid of-      Nothing -> pure ()-      Just wid -> do-        writeIORef (ctxFocusId ctx) wid-        menuW <- textEditMenuWidth ctx-        let menuRect = textEditMenuRectAt mx my menuW (inputWindowSize inp)-        setTextInputMenu ctx (Just (TextInputMenu wid menuRect))-        markDirty ctx--textFieldWidgetAtMouse :: Context -> V2 -> IO (Maybe WidgetId)-textFieldWidgetAtMouse ctx mouse = do-  let na = ctxNodeArena ctx-  mIdx <--    findNodeRevM na $ \idx -> do-      nt <- getNodeType na idx-      if nt /= NodeTextInput && nt /= NodeTextArea-        then pure False-        else do-          wid <- getWidgetId na idx-          disabled <- isDisabled ctx wid-          if disabled-            then pure False-            else do-              (x, y, w, h) <- getRect na idx-              hit <- nodeClippedHit ctx idx (Rect x y w h) mouse-              if not hit-                then pure False-                else do-                  allowed <- overlayHitAllowed ctx idx mouse-                  if not allowed-                    then pure False-                    else-                      if nt == NodeTextArea-                        then not <$> isMouseOnTextAreaScrollBarAt ctx idx mouse-                        else pure True-  traverse (getWidgetId na) mIdx--finalizeTextEditMenuPick :: Context -> Input -> IO ()-finalizeTextEditMenuPick ctx inp =-  when (inputMousePressed inp) $ do-    mMenu <- getTextInputMenu ctx-    case mMenu of-      Just menu-        | rectContains (textInputMenuRect menu) (inputMousePos inp) ->-            case textEditMenuPickAction (textInputMenuRect menu) (inputMousePos inp) of-              Nothing -> setTextInputMenu ctx Nothing-              Just action -> do-                enabled <- textFieldMenuActionEnabled ctx (textInputMenuWidget menu) action-                if enabled-                  then applyTextFieldMenuAction ctx (textInputMenuWidget menu) action-                  else do-                    setTextInputMenu ctx Nothing-                    markDirty ctx-      _ -> pure ()--closeTextEditMenuOnOutsideClick :: Context -> Input -> IO ()-closeTextEditMenuOnOutsideClick ctx inp =-  when (inputMousePressed inp || inputMouseRightPressed inp) $ do-    mMenu <- getTextInputMenu ctx-    case mMenu of-      Just menu-        | not (rectContains (textInputMenuRect menu) (inputMousePos inp)) ->-            setTextInputMenu ctx Nothing-      _ -> pure ()--closeTextEditMenuOnEscape :: Context -> Input -> IO ()-closeTextEditMenuOnEscape ctx inp =-  when (inputKeysElem KeyEscape (inputKeys inp)) $-    getTextInputMenu ctx >>= \case-      Nothing -> pure ()-      Just _ -> do-        setTextInputMenu ctx Nothing-        markEscapeConsumed ctx-        markDirty ctx--textEditMenuCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)-textEditMenuCursorKind ctx inp = do-  mMenu <- getTextInputMenu ctx-  let mouse = inputMousePos inp-  case mMenu of-    Just menu-      | rectContains (textInputMenuRect menu) mouse-      , Just action <- textEditMenuPickAction (textInputMenuRect menu) mouse -> do-          enabled <- textFieldMenuActionEnabled ctx (textInputMenuWidget menu) action-          pure (Just (if enabled then UiCursorPointer else UiCursorDefault))-    _ -> pure Nothing--drawTextEditMenuOverlays :: Context -> Input -> IO ()-drawTextEditMenuOverlays ctx inp = do-  mMenu <- getTextInputMenu ctx-  forM_ mMenu $ \menu -> do-    let wid = textInputMenuWidget menu-    allow <- widgetOverlayAllowed ctx wid-    when allow $ do-      theme <- widgetTheme ctx wid-      let da = ctxDrawArena ctx-          fm = ctxFontMetrics ctx-          menuRect = textInputMenuRect menu-          style = overlayMenuStyle theme-          Rect contentX _ _ _ = textEditMenuContentRect menuRect-          labelX = contentX + menuItemPadX + fst (widgetContentInset fm)-      paintMenuPanel da theme style menuRect-      forM_ (textEditMenuLayout menuRect) $ \case-        (TextEditMenuSep, Rect rx ry rw rh) ->-          pushRect da (Rect (rx + menuItemPadX) (ry + rh / 2) (rw - 2 * menuItemPadX) 1) (themeSeparator theme)-        (TextEditMenuItem action lbl, row@(Rect _ ry _ rh)) -> do-          enabled <- textFieldMenuActionEnabled ctx wid action-          when (enabled && rectContains row (inputMousePos inp)) $ do-            pushRect da row (styleHoverBg style)-            paintMenuAccent da theme row-          unless (T.null lbl) $ do-            (_, th) <- ctxMeasureText ctx lbl-            pushText da fm labelX (centeredTextY fm ry rh th) lbl (textEditMenuItemFg style enabled)--collectTextEditMenuSpans :: Context -> Input -> IO [(Rect, T.Text, Color, Color, Rect)]-collectTextEditMenuSpans ctx inp = do-  mMenu <- getTextInputMenu ctx-  case mMenu of-    Nothing -> pure []-    Just menu -> do-      let wid = textInputMenuWidget menu-      allow <- widgetOverlayAllowed ctx wid-      if not allow-        then pure []-        else do-          theme <- widgetTheme ctx wid-          let fm = ctxFontMetrics ctx-              menuRect = textInputMenuRect menu-              style = overlayMenuStyle theme-              Rect contentX _ _ _ = textEditMenuContentRect menuRect-              labelX = contentX + menuItemPadX + fst (widgetContentInset fm)-          fmap concat . forM (textEditMenuLayout menuRect) $ \case-            (TextEditMenuSep, _) -> pure []-            (TextEditMenuItem action lbl, row@(Rect _ ry _ rh)) -> do-              enabled <- textFieldMenuActionEnabled ctx wid action-              (tw, th) <- ctxMeasureText ctx lbl-              let bg-                    | enabled && rectContains row (inputMousePos inp) = styleHoverBg style-                    | otherwise = styleBg style-              pure [(Rect labelX (centeredTextY fm ry rh th) tw th, lbl, textEditMenuItemFg style enabled, bg, menuRect)]--applyTextFieldMenuAction :: Context -> WidgetId -> Int -> IO ()-applyTextFieldMenuAction ctx wid item =-  forM_ (take 1 (drop item textEditMenuCommands)) $ \cmd -> do-    modifyInteraction ctx (\s -> s {isTextEditLastAction = Just (wid, cmd)})-    applyTextFieldCommand ctx wid cmd--textFieldMenuActionEnabled :: Context -> WidgetId -> Int -> IO Bool-textFieldMenuActionEnabled ctx wid item = do-  store <- getStore ctx-  mMode <- textFieldMode ctx wid-  history <- textFieldHistory ctx wid-  let hasText = not (T.null (IM.findWithDefault "" (intKey wid) (storeText store)))-  case (mMode, drop item textEditMenuCommands) of-    (Just mode, cmd : _) -> case cmd of-      Undo -> pure (modeEditable mode && canUndo history)-      Redo -> pure (modeEditable mode && canRedo history)-      Cut -> pure (modeEditable mode && modeCopyable mode && hasText)-      Copy -> pure (modeCopyable mode && hasText)-      Paste-        | modeEditable mode -> maybe False (not . T.null) <$> ctxClipboardGet ctx-        | otherwise -> pure False-      _ -> pure hasText-    _ -> pure False
− lib/NanoUI/Frame/TextInput.hs
@@ -1,361 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Single-line text fields: field geometry, horizontal scroll, caret and--- selection painting, and mouse selection. Also holds the click-count and--- caret primitives the text area shares.-module NanoUI.Frame.TextInput-  ( textInputFieldRect-  , textInputFieldTextClip-  , nodeTextFieldGeom-  , tagTextInputClippedSpans-  , syncTextInputScroll-  , FieldEdit-  , readFieldEdit-  , drawTextInputSelection-  , drawTextInputCaret-  , drawTextCaret-  , drawTextSelectionLine-  , searchClearHit-  , normalizeTextFieldClicks-  , finalizeTextInputMouse-  , collapseTextInputSelection-  ) where--import Control.Monad (forM_, when)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (mapMaybe)-import Data.Text (Text)-import qualified Data.Text as T-import NanoUI.Context-  ( Context (..)-  , TextFieldClickCell (..)-  , TextInputDrag (..)-  , WidgetStore (..)-  , getStore-  , intKey-  , markDirty-  , setStore-  , setTextInputDrag-  , Slot (..)-  , slotKey-  , nodeTheme-  , InteractionState (..)-  , getsInteraction-  , modifyInteraction-  )-import NanoUI.Draw (DrawArena, pushRect)-import NanoUI.Font (FontMetrics (..), caretXIO, centeredTextY, lineWidthIO, prepareFontMetrics, selectionSpans, textIndexAtX, widgetContentInset)-import NanoUI.Frame.Chrome (textInputFocused, textInputValue)-import NanoUI.Frame.Hit (findNodeByWidgetId)-import NanoUI.Frame.Node (nodeFontMetrics)-import NanoUI.Frame.Scroll.Geometry (padTextClipRect)-import NanoUI.Id (WidgetId)-import NanoUI.Input-  ( Input (..)-  , inputMouseClicks-  , inputMouseDown-  , inputMousePos-  , inputMousePressed-  , inputMouseReleased-  )-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (NodeTextInput)-  , getNodeType-  , getOptions-  , getRect-  , getStyleIdx-  , getWidgetId-  )-import NanoUI.Style (themeSelection)-import NanoUI.Types (Color (..), Rect (..), V2 (..), rectContains, rectIntersect, rectOverlapArea, rectW)-import NanoUI.WidgetText-  ( comboTextClip-  , numericTextClip-  , searchFieldIconRects-  , searchFieldTextClip-  , textInputNumericMode-  , textInputFieldHeight-  , textInputSearchMode-  , textInputSelectableMode-  )-import NanoUI.Widgets.TextCommon-  ( selectionCaretGeom-  , textSelectionForClick-  , textSelectionForDrag-  )--textInputFieldRect :: FontMetrics -> Float -> Float -> Float -> Float -> Rect-textInputFieldRect fm x y w h =-  let fieldH = if h > 0 then h else textInputFieldHeight fm-   in Rect x y w fieldH--textInputFieldTextClip :: FontMetrics -> Rect -> Rect-textInputFieldTextClip fm (Rect fx fy fw fh) =-  let (ix, iy) = widgetContentInset fm-   in Rect (fx + ix) (fy + iy) (max 0 (fw - 2 * ix)) (max 0 (fh - 2 * iy))---- | Resolve the box a field paints/hits and the clip its text is confined to.--- Search fields are caption-less: the whole node rect is the box and text is--- clipped around the magnifier / clear chrome. Combo boxes (search fields--- carrying dropdown options) clip to the left of the chevron instead.-nodeTextFieldGeom :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> IO (Rect, Rect)-nodeTextFieldGeom ctx idx x y w h = do-  si <- getStyleIdx (ctxNodeArena ctx) idx-  opts <- getOptions (ctxNodeArena ctx) idx-  let fm = ctxFontMetrics ctx-      box = Rect x y w h-      field = textInputFieldRect fm x y w h-  pure $-    if textInputSelectableMode si-      then (box, box)-      else-        if textInputNumericMode si-          then (box, numericTextClip fm x y w h)-          else-            if textInputSearchMode si-              then (box, if null opts then searchFieldTextClip fm x y w h else comboTextClip fm x y w h)-              else (field, textInputFieldTextClip fm field)---- | Whether the pointer is over the clear (×) button of a non-empty search--- field. Search fields reserve that slot even when empty, but the button is--- only active when there is text to clear.-searchClearHit :: Context -> WidgetId -> V2 -> IO Bool-searchClearHit ctx wid mouse = do-  mIdx <- findNodeByWidgetId ctx wid-  case mIdx of-    Nothing -> pure False-    Just idx -> do-      si <- getStyleIdx (ctxNodeArena ctx) idx-      opts <- getOptions (ctxNodeArena ctx) idx-      if not (textInputSearchMode si) || not (null opts)-        then pure False-        else do-          value <- textInputValue ctx idx-          if T.null value-            then pure False-            else do-              (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-              let (_, clearRect) = searchFieldIconRects (ctxFontMetrics ctx) x y w h-              pure (rectContains clearRect mouse)---- | Clear a search field. The debounced pulse picks the empty text up as an--- immediate (empty) commit on the next frame.-clearSearchField :: Context -> WidgetId -> IO ()-clearSearchField ctx wid = do-  store <- getStore ctx-  let key = intKey wid-      storeInt' =-        IM.insert (slotKey SlotAnchor key) 0 $-          IM.insert (slotKey SlotCursor key) 0 (storeInt store)-      store' = store {storeText = IM.insert key "" (storeText store), storeInt = storeInt'}-  setStore ctx store'-  markDirty ctx--tagTextInputClippedSpans ::-  Rect -> Float -> Float -> Float -> Float -> FontMetrics -> [(Rect, T.Text, Color, Color)] -> [(Rect, T.Text, Color, Color, Rect)]-tagTextInputClippedSpans parentClip x y w h fm spans =-  let fieldClip = textInputFieldTextClip fm (textInputFieldRect fm x y w h)-      labelClip = Rect x y w (fmLineHeight fm)-      tagOne (rect, txt, fg, bg) =-        let clipRect = padTextClipRect rect-            isField = rectOverlapArea fieldClip clipRect > rectOverlapArea labelClip clipRect-            area = if isField then fieldClip else labelClip-         in (rect, txt, fg, bg,) <$> (rectIntersect area clipRect >>= rectIntersect parentClip)-   in mapMaybe tagOne spans--drawTextCaret :: DrawArena -> Float -> Float -> Float -> Color -> IO ()-drawTextCaret da caretX caretY caretH fg =-  pushRect da (Rect caretX caretY 1 caretH) fg--drawTextSelectionLine :: DrawArena -> Float -> Float -> Float -> Float -> Color -> IO ()-drawTextSelectionLine da selX selY selW selH selBg =-  when (selW > 0) $-    pushRect da (Rect selX selY (max 1 selW) (max 4 selH)) selBg--computeTextInputScroll :: FontMetrics -> Float -> Text -> Int -> Float -> Bool -> IO Float-computeTextInputScroll fm viewportW value cursor oldScroll isFocused-  | not isFocused = pure 0-  | viewportW <= 0 = pure 0-  | otherwise = do-      caretRelX <- caretXIO fm value cursor-      totalTextW <- lineWidthIO fm value-      let maxScroll = max 0 (totalTextW + 1 - viewportW)-          s0-            | caretRelX < oldScroll = caretRelX-            | caretRelX + 1 > oldScroll + viewportW = caretRelX + 1 - viewportW-            | otherwise = oldScroll-      pure (max 0 (min maxScroll s0))--syncTextInputScroll :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> IO Float-syncTextInputScroll ctx idx x y w h = do-  si <- getStyleIdx (ctxNodeArena ctx) idx-  if textInputSelectableMode si-    then pure 0-    else do-      wid <- getWidgetId (ctxNodeArena ctx) idx-      store <- getStore ctx-      let key = intKey wid-      value <- textInputValue ctx idx-      focus <- textInputFocused ctx idx-      (_, clip) <- nodeTextFieldGeom ctx idx x y w h-      let cursor = IM.findWithDefault (T.length value) (slotKey SlotCursor key) (storeInt store)-          oldScroll = IM.findWithDefault 0 (slotKey SlotTextInputScroll key) (storeFloat store)-      newScroll <- computeTextInputScroll (ctxFontMetrics ctx) (rectW clip) value cursor oldScroll focus-      when (newScroll /= oldScroll) $-        setStore ctx (store {storeFloat = IM.insert (slotKey SlotTextInputScroll key) newScroll (storeFloat store)})-      pure newScroll---- | What a focused single-line field paints its selection and caret from: the--- displayed value, cursor and anchor, the node font, the field box's top and--- height, and the x its text starts at with the scroll applied.-data FieldEdit = FieldEdit !Text !Int !Int !FontMetrics !Float !Float !Float---- | Editing state of field @idx@ at @x y w h@ scrolled by @scrollX@ (see--- 'syncTextInputScroll'), or Nothing while it is unfocused.-readFieldEdit :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> Float -> IO (Maybe FieldEdit)-readFieldEdit ctx idx x y w h scrollX = do-  focus <- textInputFocused ctx idx-  if not focus-    then pure Nothing-    else do-      value <- textInputValue ctx idx-      wid <- getWidgetId (ctxNodeArena ctx) idx-      store <- getStore ctx-      (Rect _ boxY _ boxH, Rect clipX _ _ _) <- nodeTextFieldGeom ctx idx x y w h-      fm <- nodeFontMetrics ctx idx-      let key = intKey wid-          !cursor = IM.findWithDefault (T.length value) (slotKey SlotCursor key) (storeInt store)-          !anchor = IM.findWithDefault cursor (slotKey SlotAnchor key) (storeInt store)-      pure $! Just (FieldEdit value cursor anchor fm boxY boxH (clipX - scrollX))--drawTextInputSelection :: DrawArena -> Context -> NodeIdx -> FieldEdit -> IO ()-drawTextInputSelection da ctx idx (FieldEdit value cursor anchor fm boxY boxH textX) = do-  let selLo = min anchor cursor-      selHi = max anchor cursor-      lineH = fmLineHeight fm-  when (selLo < selHi) $ do-    theme <- nodeTheme ctx idx-    prepared <- prepareFontMetrics fm value-    forM_ (selectionSpans prepared value selLo selHi) $ \(wLo, wHi) ->-      drawTextSelectionLine-        da-        (textX + wLo)-        (centeredTextY fm boxY boxH lineH)-        (wHi - wLo)-        lineH-        (themeSelection theme)--drawTextInputCaret :: DrawArena -> FieldEdit -> Color -> IO ()-drawTextInputCaret da (FieldEdit value cursor _ fm boxY boxH textX) fg = do-  let lineH = fmLineHeight fm-  pw <- caretXIO fm value cursor-  let (caretX, caretY, caretH) =-        selectionCaretGeom textX (centeredTextY fm boxY boxH lineH) pw lineH-  drawTextCaret da caretX caretY caretH fg--updateTextInputSelection :: Context -> WidgetId -> Int -> Int -> IO ()-updateTextInputSelection ctx wid anchor cursor = do-  store <- getStore ctx-  let key = intKey wid-      oldAnchor = IM.findWithDefault cursor (slotKey SlotAnchor key) (storeInt store)-      oldCursor = IM.findWithDefault 0 (slotKey SlotCursor key) (storeInt store)-  when (oldAnchor /= anchor || oldCursor /= cursor) $ do-    setStore-      ctx-      ( store-          { storeInt =-              IM.insert (slotKey SlotAnchor key) anchor $-                IM.insert (slotKey SlotCursor key) cursor (storeInt store)-          }-      )-    markDirty ctx---- | Field box, text origin x (scroll applied), value and font of a single-line--- field.-textInputGeomForWidget :: Context -> WidgetId -> IO (Maybe (Rect, Float, Text, FontMetrics))-textInputGeomForWidget ctx wid = do-  mIdx <- findNodeByWidgetId ctx wid-  case mIdx of-    Nothing -> pure Nothing-    Just idx -> do-      nt <- getNodeType (ctxNodeArena ctx) idx-      if nt /= NodeTextInput-        then pure Nothing-        else do-          (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-          (field, Rect clipX _ _ _) <- nodeTextFieldGeom ctx idx x y w h-          scrollX <- syncTextInputScroll ctx idx x y w h-          fm <- nodeFontMetrics ctx idx-          value <- textInputValue ctx idx-          pure (Just (field, clipX - scrollX, value, fm))---- | Mouse selection in single-line field @wid@: click (with word and line--- multi-clicks), drag, and the search clear button. False when @wid@ is not a--- single-line field.-finalizeTextInputMouse :: Context -> Input -> WidgetId -> IO Bool-finalizeTextInputMouse ctx inp wid = do-  mGeom <- textInputGeomForWidget ctx wid-  case mGeom of-    Nothing -> pure False-    Just (fieldRect, contentX, value, fm) -> do-      let mouse@(V2 mouseX _) = inputMousePos inp-          charAt = do-            prepared <- prepareFontMetrics fm value-            pure (textIndexAtX prepared value (max 0 (mouseX - contentX)))-      if inputMousePressed inp && rectContains fieldRect mouse-        then do-          cleared <- searchClearHit ctx wid mouse-          if cleared-            then clearSearchField ctx wid-            else do-              idx <- charAt-              clicks <- normalizeTextFieldClicks ctx wid idx 0 0 False (max 1 (inputMouseClicks inp))-              uncurry (updateTextInputSelection ctx wid) (textSelectionForClick value idx clicks)-              setTextInputDrag ctx (Just (TextInputDrag wid idx 0 0 False clicks))-        else do-          mDrag <- getsInteraction ctx isTextInputDrag-          case mDrag of-            Just drag-              | textInputDragWidget drag == wid-                  , not (textInputDragMultiline drag)-                  , inputMouseDown inp || inputMouseReleased inp -> do-                  idx <- charAt-                  uncurry (updateTextInputSelection ctx wid) $-                    textSelectionForDrag value (textInputDragAnchor drag) idx (textInputDragClicks drag)-            _ -> pure ()-      pure True--collapseTextInputSelection :: Context -> WidgetId -> IO ()-collapseTextInputSelection ctx wid = do-  store <- getStore ctx-  let key = intKey wid-      cur = IM.findWithDefault 0 (slotKey SlotCursor key) (storeInt store)-  setStore ctx (store {storeInt = IM.insert (slotKey SlotAnchor key) cur (storeInt store)})---- | Count a press as a multi-click only when it lands on the same cell as the--- previous press; anything else restarts the count at one.-normalizeTextFieldClicks :: Context -> WidgetId -> Int -> Int -> Int -> Bool -> Int -> IO Int-normalizeTextFieldClicks ctx wid flat row col multiline rawClicks = do-  let cell =-        TextFieldClickCell-          { textFieldClickWidget = wid-          , textFieldClickFlat = flat-          , textFieldClickRow = row-          , textFieldClickCol = col-          , textFieldClickMultiline = multiline-          }-  if rawClicks <= 1-    then modifyInteraction ctx (\s -> s {isTextFieldClickCell = Just cell}) >> pure rawClicks-    else do-      mPrev <- getsInteraction ctx isTextFieldClickCell-      if maybe False (sameCell cell) mPrev-        then pure rawClicks-        else modifyInteraction ctx (\s -> s {isTextFieldClickCell = Just cell}) >> pure 1-  where-    sameCell a b =-      textFieldClickWidget a == textFieldClickWidget b-        && textFieldClickMultiline a == textFieldClickMultiline b-        && if textFieldClickMultiline a-          then textFieldClickRow a == textFieldClickRow b && textFieldClickCol a == textFieldClickCol b-          else textFieldClickFlat a == textFieldClickFlat b
− lib/NanoUI/Frame/Window.hs
@@ -1,448 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | Floating window input: dragging by the title bar, edge and inner-east--- resizing, the resize cursor, and persisting window placement.-module NanoUI.Frame.Window-  ( contextMeasurers-  , lookupWindowPos-  , lookupWindowSize-  , persistWindowPositions-  , updateWindowDrag-  , updateWindowResize-  , WindowResizeEdge (..)-  , windowResizeCursorKind-  ) where--import Control.Monad (when)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (fromMaybe, isJust)-import NanoUI.Context-  ( Context (..)-  , WidgetStore (..)-  , WindowResizeDrag (..)-  , WindowResizeEdge (..)-  , damageWidget-  , getStore-  , getWindowDrag-  , getWindowResize-  , intKey-  , markDirty-  , setStore-  , slotKey-  , Slot (..)-  , InteractionState (..)-  , modifyInteraction-  , lookupCustomMeasure-  )-import NanoUI.Font (ScrollBarSlot (..))-import NanoUI.Frame.Hit (findNodeByWidgetId, nodeInSubtree, topmostOverlayAtMouse)-import NanoUI.Frame.Input (findTopWidgetUnderMouse, isInteractiveNode)-import NanoUI.Frame.Redraw (probeHotId)-import NanoUI.Frame.Scroll.Geometry (scrollChromeLane)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (Input (..), UiCursorKind (..), inputMouseDown, inputMousePos, inputMousePressed)-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , findChildM-  , findNodeRevM-  , foldNodesM-  , getDirection-  , getFirstChild-  , getMinMax-  , getNextSibling-  , getNodeType-  , getNodeValue-  , getPadding-  , getRect-  , getWidgetId-  )-import NanoUI.Layout.Solve (Measurers (..), placeWindowNode, scrollBarSlotOf)-import NanoUI.Style (Padding (..))-import NanoUI.Types (DamageBounds (..), Rect (..), V2 (..), haloDamageSlop, rectContains, rectInflate)--topmostWindowAtResizeHalo :: Context -> V2 -> IO (Maybe NodeIdx)-topmostWindowAtResizeHalo ctx mouse =-  findNodeRevM (ctxNodeArena ctx) $ \idx -> do-    nt <- getNodeType (ctxNodeArena ctx) idx-    if nt /= NodeWindow-      then pure False-      else do-        (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-        if w <= 0 || h <= 0-          then pure False-          else do-            let rect = Rect x y w h-            if rectContains (rectInflate windowResizeHandleFor rect) mouse-              then pure True-              else windowInnerEastResizeHit ctx idx rect mouse--windowInnerEastResizeHit :: Context -> NodeIdx -> Rect -> V2 -> IO Bool-windowInnerEastResizeHit ctx winIdx (Rect x _ w _) mouse@(V2 mx _) = do-  pad <- getPadding (ctxNodeArena ctx) winIdx-  if mx < x + w - padR pad || mx > x + w-    then pure False-    else do-      mLane <- windowBodyScrollLane ctx winIdx-      pure (not (maybe False (`rectContains` mouse) mLane))--lookupWindowPos :: Context -> WidgetId -> IO (Maybe (Float, Float))-lookupWindowPos ctx wid = do-  store <- getStore ctx-  pure (IM.lookup (intKey wid) (storePoint store))--lookupWindowSize :: Context -> WidgetId -> IO (Maybe (Float, Float))-lookupWindowSize ctx wid = do-  store <- getStore ctx-  pure (IM.lookup (slotKey SlotWinSize (intKey wid)) (storePoint store))--persistWindowPositions :: Context -> IO ()-persistWindowPositions ctx = do-  store0 <- getStore ctx-  let na = ctxNodeArena ctx-      record acc idx = do-        nt <- getNodeType na idx-        if nt /= NodeWindow-          then pure acc-          else do-            wid <- getWidgetId na idx-            (x, y, w, h) <- getRect na idx-            let k = intKey wid-                sizeKey = slotKey SlotWinSize k-                points = storePoint acc-            -- Keep an unchanged map as is, so the store comparison below-            -- short-circuits on pointer equality.-            pure $-              if IM.lookup k points == Just (x, y) && IM.lookup sizeKey points == Just (w, h)-                then acc-                else acc {storePoint = IM.insert k (x, y) (IM.insert sizeKey (w, h) points)}-  store1 <- foldNodesM na record store0-  when (store1 /= store0) $ setStore ctx store1--updateWindowDrag :: Context -> Input -> IO Bool-updateWindowDrag ctx inp = do-  resizing <- isJust <$> getWindowResize ctx-  if resizing-    then pure False-    else do-      drag <- getWindowDrag ctx-      case drag of-        Just (wid, gx, gy)-          | inputMouseDown inp -> do-              let V2 mx my = inputMousePos inp-              store <- getStore ctx-              setStore ctx (store {storePoint = IM.insert (intKey wid) (mx - gx, my - gy) (storePoint store)})-              damageWidget ctx wid (DamageInflated haloDamageSlop)-              markDirty ctx-              pure True-          | otherwise -> do-              modifyInteraction ctx (\s -> s {isWindowDrag = Nothing})-              pure False-        Nothing-          | inputMousePressed inp -> tryStartWindowDrag ctx (inputMousePos inp)-          | otherwise -> pure False--windowResizeHandleFor :: Float-windowResizeHandleFor = 12---- Handles sit outside the window. The right pad strip also resizes beside the bar.-windowResizeEdgeAt :: Rect -> V2 -> Maybe WindowResizeEdge-windowResizeEdgeAt (Rect x y w h) (V2 mx my) =-  let s = windowResizeHandleFor-      onL = mx >= x - s && mx < x-      onR = mx > x + w && mx <= x + w + s-      onT = my >= y - s && my < y-      onB = my > y + h && my <= y + h + s-   in if not (onL || onR || onT || onB)-        then Nothing-        else-          Just $-            case (onT, onB, onL, onR) of-              (True, _, True, _) -> ResizeNW-              (True, _, _, True) -> ResizeNE-              (_, True, True, _) -> ResizeSW-              (_, True, _, True) -> ResizeSE-              (True, _, _, _) -> ResizeN-              (_, True, _, _) -> ResizeS-              (_, _, True, _) -> ResizeW-              _ -> ResizeE--innerEastCornerEdge :: Padding -> Rect -> Float -> WindowResizeEdge-innerEastCornerEdge pad (Rect _ y _ h) my =-  let s = windowResizeHandleFor-      minBand = 6-      topBand = max minBand (min s (padT pad))-      botBand = max minBand (min s (padB pad))-   in if my >= y && my < y + topBand-        then ResizeNE-        else if my > y + h - botBand && my <= y + h then ResizeSE else ResizeE---- | Lane of the window body's scrollbar while its content overflows.-windowBodyScrollLane :: Context -> NodeIdx -> IO (Maybe Rect)-windowBodyScrollLane ctx winIdx = do-  let na = ctxNodeArena ctx-  mBody <--    findChildM na winIdx $ \ci -> do-      nt <- getNodeType na ci-      if nt /= NodeScrollContainer-        then pure False-        else do-          slot <- scrollBarSlotOf na ci-          if slot /= ScrollBarWindow-            then pure False-            else do-              (_, _, _, h) <- getRect na ci-              pad <- getPadding na ci-              contentSize <- getNodeValue na ci-              pure (contentSize > h - padT pad - padB pad)-  traverse-    ( \ci -> do-        (x, y, w, h) <- getRect na ci-        pad <- getPadding na ci-        dir <- getDirection na ci-        pure (scrollChromeLane ScrollBarWindow dir x y w h pad)-    )-    mBody--windowInnerResizeEdgeAt :: Context -> NodeIdx -> Rect -> V2 -> IO (Maybe WindowResizeEdge)-windowInnerResizeEdgeAt ctx winIdx winRect@(Rect x y w h) mouse@(V2 mx my) = do-  hit <- windowInnerEastResizeHit ctx winIdx winRect mouse-  if hit-    then do-      pad <- getPadding (ctxNodeArena ctx) winIdx-      pure (Just (innerEastCornerEdge pad winRect my))-    else do-      let cornerW = min 16 (w / 3)-          cornerH = min 16 (h / 3)-          botH = min 6 (h / 3)-          inBotRightCorner = mx >= x + w - cornerW && mx <= x + w && my >= y + h - cornerH && my <= y + h-          inBotEdge = mx >= x && mx <= x + w && my >= y + h - botH && my <= y + h-      pure $-        if inBotRightCorner-          then Just ResizeSE-          else if inBotEdge then Just ResizeS else Nothing--windowResizeEdgeFor :: Context -> NodeIdx -> Rect -> V2 -> IO (Maybe WindowResizeEdge)-windowResizeEdgeFor ctx winIdx winRect mouse =-  case windowResizeEdgeAt winRect mouse of-    Just edge -> pure (Just edge)-    Nothing -> windowInnerResizeEdgeAt ctx winIdx winRect mouse--cursorForResizeEdge :: WindowResizeEdge -> UiCursorKind-cursorForResizeEdge = \case-  ResizeN -> UiCursorNsResize-  ResizeS -> UiCursorNsResize-  ResizeE -> UiCursorEwResize-  ResizeW -> UiCursorEwResize-  ResizeNW -> UiCursorNwseResize-  ResizeSE -> UiCursorNwseResize-  ResizeNE -> UiCursorNeswResize-  ResizeSW -> UiCursorNeswResize--resizeFromEdge :: WindowResizeDrag -> V2 -> Float -> Float -> (Float, Float, Float, Float)-resizeFromEdge wrd (V2 mx my) winW winH =-  let !dx = mx - wrdGrabX wrd-      !dy = my - wrdGrabY wrd-      !minW = max (wrdMinW wrd) 1.0-      !minH = max (wrdMinH wrd) 1.0-      !maxW = min (wrdMaxW wrd) winW-      !maxH = min (wrdMaxH wrd) winH-      !right0 = wrdStartX wrd + wrdStartW wrd-      !bottom0 = wrdStartY wrd + wrdStartH wrd-      edge = wrdEdge wrd-      !fromE = edge `elem` [ResizeE, ResizeNE, ResizeSE]-      !fromW = edge `elem` [ResizeW, ResizeNW, ResizeSW]-      !fromS = edge `elem` [ResizeS, ResizeSE, ResizeSW]-      !fromN = edge `elem` [ResizeN, ResizeNE, ResizeNW]-      !w0-        | fromE = wrdStartW wrd + dx-        | fromW = wrdStartW wrd - dx-        | otherwise = wrdStartW wrd-      !h0-        | fromS = wrdStartH wrd + dy-        | fromN = wrdStartH wrd - dy-        | otherwise = wrdStartH wrd-      !w = max minW (min maxW w0)-      !h = max minH (min maxH h0)-      !x0 = if fromW then right0 - w else wrdStartX wrd-      !y0 = if fromN then bottom0 - h else wrdStartY wrd-      !x = max 0 (min x0 (max 0 (winW - w)))-      !y = max 0 (min y0 (max 0 (winH - h)))-   in (w, h, x, y)--updateWindowResize :: Context -> Input -> Float -> Float -> IO Bool-updateWindowResize ctx inp winW winH = do-  drag <- getWindowResize ctx-  case drag of-    Just wrd-      | inputMouseDown inp -> do-          let (nw, nh, nx, ny) = resizeFromEdge wrd (inputMousePos inp) winW winH-              key = intKey (wrdWidget wrd)-          store <- getStore ctx-          setStore ctx (store {storePoint = IM.insert (slotKey SlotWinSize key) (nw, nh) (IM.insert key (nx, ny) (storePoint store))})-          relayoutWindow ctx winW winH (wrdWidget wrd) nw nh-          damageWidget ctx (wrdWidget wrd) (DamageInflated haloDamageSlop)-          markDirty ctx-          pure True-      | otherwise -> do-          modifyInteraction ctx (\s -> s {isWindowResize = Nothing})-          pure False-    Nothing-      | inputMousePressed inp -> tryStartWindowResize ctx (inputMousePos inp)-      | otherwise -> pure False--relayoutWindow :: Context -> Float -> Float -> WidgetId -> Float -> Float -> IO ()-relayoutWindow ctx winW winH wid nw nh = do-  mIdx <- findNodeByWidgetId ctx wid-  case mIdx of-    Nothing -> pure ()-    Just idx -> do-      mpos <- lookupWindowPos ctx wid-      (x, y, _, _) <- getRect (ctxNodeArena ctx) idx-      placeWindowNode (ctxNodeArena ctx) (contextMeasurers ctx) winW winH idx nw nh (const (fromMaybe (x, y) mpos))---- | Resize edge under @mouse@ for the topmost window whose halo holds it,--- unless the halo is blocked or the pointer is on the title bar or one of its--- controls.-resizeEdgeTarget :: Context -> V2 -> IO (Maybe (NodeIdx, Rect, WindowResizeEdge))-resizeEdgeTarget ctx mouse = do-  mWin <- topmostWindowAtResizeHalo ctx mouse-  case mWin of-    Nothing -> pure Nothing-    Just idx -> do-      (x, y, w, h) <- getRect (ctxNodeArena ctx) idx-      let rect = Rect x y w h-      -- The halo covers the window interior, so find the edge first and run-      -- the hover probe and node scans only when there is one.-      mEdge <- windowResizeEdgeFor ctx idx rect mouse-      case mEdge of-        Nothing -> pure Nothing-        Just edge -> do-          mTitle <- windowTitleRect ctx idx-          if maybe False (`rectContains` mouse) mTitle-            then pure Nothing-            else do-              blocked <- resizeHaloBlocked ctx mouse idx-              overControl <- if blocked then pure False else windowTitleHasInteractive ctx idx mouse-              pure (if blocked || overControl then Nothing else Just (idx, rect, edge))--tryStartWindowResize :: Context -> V2 -> IO Bool-tryStartWindowResize ctx mouse@(V2 mx my) = do-  mTarget <- resizeEdgeTarget ctx mouse-  case mTarget of-    Nothing -> pure False-    Just (idx, Rect x y w h, edge) -> do-      wid <- getWidgetId (ctxNodeArena ctx) idx-      (minW, minH, maxW, maxH) <- getMinMax (ctxNodeArena ctx) idx-      modifyInteraction ctx $ \s ->-        s-          { isWindowResize =-              Just-                WindowResizeDrag-                  { wrdWidget = wid-                  , wrdEdge = edge-                  , wrdGrabX = mx-                  , wrdGrabY = my-                  , wrdStartX = x-                  , wrdStartY = y-                  , wrdStartW = w-                  , wrdStartH = h-                  , wrdMinW = minW-                  , wrdMinH = minH-                  , wrdMaxW = maxW-                  , wrdMaxH = maxH-                  }-          }-      markDirty ctx-      pure True--windowResizeCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)-windowResizeCursorKind ctx inp = do-  mDrag <- getWindowResize ctx-  case mDrag of-    Just wrd-      | inputMouseDown inp -> pure (Just (cursorForResizeEdge (wrdEdge wrd)))-      | otherwise -> pure Nothing-    Nothing -> fmap (\(_, _, edge) -> cursorForResizeEdge edge) <$> resizeEdgeTarget ctx (inputMousePos inp)---- Halo must not steal hits from page widgets or another window's interior.-resizeHaloBlocked :: Context -> V2 -> NodeIdx -> IO Bool-resizeHaloBlocked ctx mouse winIdx = do-  mInside <- topmostOverlayAtMouse ctx mouse-  case mInside of-    Just other | other /= winIdx -> pure True-    _ -> do-      hot <- probeHotId ctx mouse-      if hashWidgetId hot == 0-        then pure False-        else do-          mHot <- findNodeByWidgetId ctx hot-          case mHot of-            Nothing -> pure False-            Just hotIdx -> not <$> nodeInSubtree ctx hotIdx winIdx--tryStartWindowDrag :: Context -> V2 -> IO Bool-tryStartWindowDrag ctx mouse@(V2 mx my) = do-  mTop <- topmostOverlayAtMouse ctx mouse-  case mTop of-    Nothing -> pure False-    Just idx -> do-      nt <- getNodeType (ctxNodeArena ctx) idx-      mTitle <- if nt == NodeWindow then windowTitleRect ctx idx else pure Nothing-      case mTitle of-        Just title | rectContains title mouse -> do-          overClose <- windowTitleHasInteractive ctx idx mouse-          if overClose-            then pure False-            else do-              wid <- getWidgetId (ctxNodeArena ctx) idx-              (wx, wy, _, _) <- getRect (ctxNodeArena ctx) idx-              modifyInteraction ctx (\s -> s {isWindowDrag = Just (wid, mx - wx, my - wy)})-              markDirty ctx-              pure True-        _ -> pure False---- | Title bar: the window's topmost child, stretched up to the window top.-windowTitleRect :: Context -> NodeIdx -> IO (Maybe Rect)-windowTitleRect ctx idx = do-  (_, wy, _, _) <- getRect (ctxNodeArena ctx) idx-  fc <- getFirstChild (ctxNodeArena ctx) idx-  mBest <- go fc Nothing-  pure $ case mBest of-    Nothing -> Nothing-    Just (Rect cx cy cw ch) ->-      let topY = min wy cy-       in Just (Rect cx topY cw ((cy - topY) + ch))-  where-    go ci best-      | ci < 0 = pure best-      | otherwise = do-          (x, y, w, h) <- getRect (ctxNodeArena ctx) ci-          ns <- getNextSibling (ctxNodeArena ctx) ci-          let here = Rect x y w h-          go ns $ case best of-            Just b@(Rect _ by _ _) | y >= by -> Just b-            _ -> Just here--windowTitleHasInteractive :: Context -> NodeIdx -> V2 -> IO Bool-windowTitleHasInteractive ctx idx mouse = do-  mWid <- findTopWidgetUnderMouse ctx mouse isInteractiveNode-  case mWid of-    Nothing -> pure False-    Just wid -> do-      mNode <- findNodeByWidgetId ctx wid-      maybe (pure False) (\wi -> nodeInSubtree ctx wi idx) mNode---- | How the context measures text and custom widgets, for the solve and for--- placing floating nodes after it.-contextMeasurers :: Context -> Measurers-contextMeasurers ctx =-  Measurers-    { msFm = ctxFontMetrics ctx-    , msMonoFm = ctxMonoFontMetrics ctx-    , msMeasure = ctxMeasureText ctx-    , msResolveFont = \sz weight style var -> do-        (fm, _) <- ctxResolveFont ctx sz weight style var-        pure (fm, ctxResolveMeasure ctx sz weight style var)-    , msLookupMeasure = lookupCustomMeasure ctx-    }
− lib/NanoUI/Hooks.hs
@@ -1,84 +0,0 @@--- | Local state hooks. The store representation varies by value type, but--- identity, equality checks, and invalidation follow one policy.-module NanoUI.Hooks-  ( useState-  , useFlag-  , useInt-  , useFloat-  , useEnum-  , useText-  , useToggle-  )-where--import Control.Monad (when)-import Data.Dynamic (fromDynamic, toDyn)-import Data.IntMap.Strict qualified as IM-import Data.Maybe (fromMaybe)-import Data.Text (Text)-import Data.Typeable (Typeable)-import Effectful (Eff, type (:>))-import NanoUI.Context (getStore, intKey, setStore)-import NanoUI.Monad (Ui, askContext, nextId, uiIO)-import NanoUI.Store (WidgetStore (..), boolInt, bumpMirror, intBool)--useState :: (Typeable a, Eq a, Ui :> es) => a -> Eff es (a, a -> Eff es ())-useState =-  useStored-    (\key store -> IM.lookup key (storeDyn store) >>= fromDynamic)-    ( \key value store -> store {storeDyn = IM.insert key (toDyn value) (storeDyn store)}-    )--useStored ::-  (Eq a, Ui :> es) =>-  (Int -> WidgetStore -> Maybe a)-  -> (Int -> a -> WidgetStore -> WidgetStore)-  -> a-  -> Eff es (a, a -> Eff es ())-useStored lookupValue update initial = do-  wid <- nextId-  ctx <- askContext-  let-    key = intKey wid-    valueIn = fromMaybe initial . lookupValue key-    setValue value = uiIO $ do-      -- A setter can run more than once in a frame. Compare with the latest-      -- store, not the value captured when the hook was evaluated.-      store <- getStore ctx-      when (valueIn store /= value) $-        setStore ctx (bumpMirror (update key value store))-  value <- valueIn <$> uiIO (getStore ctx)-  pure (value, setValue)--useFlag :: Ui :> es => Bool -> Eff es (Bool, Bool -> Eff es ())-useFlag initial = do-  (value, setValue) <- useInt (boolInt initial)-  pure (intBool value, setValue . boolInt)--useInt :: Ui :> es => Int -> Eff es (Int, Int -> Eff es ())-useInt =-  useStored-    (\key -> IM.lookup key . storeInt)-    (\key value store -> store {storeInt = IM.insert key value (storeInt store)})--useFloat :: Ui :> es => Float -> Eff es (Float, Float -> Eff es ())-useFloat =-  useStored-    (\key -> IM.lookup key . storeFloat)-    (\key value store -> store {storeFloat = IM.insert key value (storeFloat store)})--useEnum :: (Enum a, Ui :> es) => a -> Eff es (a, a -> Eff es ())-useEnum initial = do-  (index, setIndex) <- useInt (fromEnum initial)-  pure (toEnum index, setIndex . fromEnum)--useText :: Ui :> es => Text -> Eff es (Text, Text -> Eff es ())-useText =-  useStored-    (\key -> IM.lookup key . storeText)-    (\key value store -> store {storeText = IM.insert key value (storeText store)})--useToggle :: Ui :> es => Bool -> Eff es (Bool, Eff es ())-useToggle initial = do-  (value, setValue) <- useFlag initial-  pure (value, setValue (not value))
− lib/NanoUI/Id.hs
@@ -1,131 +0,0 @@-{-# LANGUAGE DerivingStrategies #-}-{-# LANGUAGE StrictData #-}---- | Widget ids and the id context they are derived from. See the--- "Widget identity" section of "NanoUI" for how ids are assigned.-module NanoUI.Id-  ( WidgetId (..)-  , IdContext (..)-  , initialIdContext-  , idContextWidgetId-  , widgetId-  , hashWidgetId-  , fnv1a-  , mix64-  , mixFnv-  , scopeTag-  , enterScope-  , enterKeyed-  )-where--import Data.Bits (shiftR, xor)-import Data.Char (ord)-import Data.Hashable (Hashable)-import Data.Primitive.Types (Prim)-import Data.Word (Word64, Word8)-import GHC.Stack (HasCallStack, SrcLoc (..), callStack, getCallStack)--newtype WidgetId = WidgetId Word64-  deriving stock (Eq, Ord, Show)-  deriving newtype (Hashable, Prim)--data IdContext = IdContext-  { currentId :: {-# UNPACK #-} !Word64-  , siblingId :: {-# UNPACK #-} !Word64-  }-  deriving stock (Eq, Show)--initialIdContext :: IdContext-initialIdContext = IdContext 0x243F6A8885A308D3 0---- | Id of the next sibling in this context. A zero hash becomes 1, so--- @WidgetId 0@ never names a real widget.-{-# INLINE idContextWidgetId #-}-idContextWidgetId :: IdContext -> WidgetId-idContextWidgetId (IdContext cid sid) =-  let-    raw = mix64 cid sid-   in-    if raw == 0 then WidgetId 1 else WidgetId raw--scopeTag :: Word64-scopeTag = 0x9E3779B185EBCA87--keyedTag :: Word64-keyedTag = 0xC2B2AE3D27D4EB4F--{-# INLINE enterScope #-}-enterScope :: Word64 -> IdContext -> (IdContext, IdContext)-enterScope tag parent =-  let-    IdContext pid sib = parent-    child = IdContext (mix64 (mix64 pid sib) tag) 0-    parent' = parent {siblingId = sib + 1}-   in-    (parent', child)--{-# INLINE enterKeyed #-}-enterKeyed :: Word64 -> IdContext -> (IdContext, IdContext)-enterKeyed tag parent =-  let-    IdContext pid sid = parent-    child = IdContext (mix64 (mix64 pid tag) keyedTag) 0-    parent' = parent {siblingId = sid + 1}-   in-    (parent', child)--{-# INLINE widgetId #-}-widgetId :: HasCallStack => WidgetId-widgetId =-  let-    stack = getCallStack callStack-    loc = case stack of-      (_, loc') : _ -> loc'-      [] -> error "widgetId: empty CallStack"-   in-    hashSrcLoc loc--hashSrcLoc :: SrcLoc -> WidgetId-hashSrcLoc-  ( SrcLoc-      { srcLocPackage-      , srcLocModule-      , srcLocFile-      , srcLocStartLine-      , srcLocStartCol-      }-    ) =-    WidgetId $-      fnv1a srcLocPackage-        `mixFnv` fnv1a srcLocModule-        `mixFnv` fnv1a srcLocFile-        `mixFnv` fromIntegral srcLocStartLine-        `mixFnv` fromIntegral srcLocStartCol--{-# INLINE hashWidgetId #-}-hashWidgetId :: WidgetId -> Word64-hashWidgetId (WidgetId w) = w--{-# INLINE fnv1a #-}-fnv1a :: String -> Word64-fnv1a s =-  foldl'-    (\acc c -> (fromIntegral @Word8 @Word64 (fromIntegral (ord c)) `xor` acc) * 0x00000100000001B3)-    0xcbf29ce484222325-    s--{-# INLINE mix64 #-}-mix64 :: Word64 -> Word64 -> Word64-mix64 x y =-  let-    z = x + (y * 0x9E3779B97F4A7C15)-    z1 = z `xor` (z `shiftR` 30)-    z2 = z1 * 0xBF58476D1CE4E5B9-    z3 = z2 `xor` (z2 `shiftR` 27)-   in-    z3 * 0x94D049BB133111EB--{-# INLINE mixFnv #-}-mixFnv :: Word64 -> Word64 -> Word64-mixFnv x y = (x `xor` y) * 1099511628211
lib/NanoUI/Input.hs view
@@ -1,250 +1,62 @@-{-# LANGUAGE StrictData #-}---- | The per-frame 'Input' record backends fill in: pointer state, keys and--- modifiers, typed characters, scroll, window size, and file drops.+-- | The per-frame 'Input' record backends fill in and views read: pointer+-- state, keys and modifiers, typed characters, scroll, window size, file+-- drops and input-method composition, plus the cursor kinds a widget can+-- request. module NanoUI.Input-  ( Key (..)-  , Modifiers (..)-  , Input (..)-  , DropType (..)-  , DropEvent (..)-  , emptyDropEvents+  ( -- * Input+    Input (..)+  , Pressable (..)   , emptyInput+  , clearEphemeral   , inputInteracted   , inputPointerHeld-  , appendInputKey-  , appendDropEvent++    -- * Mouse buttons   , MouseButton (..)+  , mouseButtonNumber+  , MouseButtons+  , noButtons+  , buttonsMember+  , buttonsNull+  , buttonsInsert+  , buttonsDelete+  , buttonsToList+  , buttonsFromList+  , anyButtonPressed+  , anyButtonReleased   , applyMouseButton+  , applyPointerLeave++    -- * Keys+  , Key (..)+  , Modifiers (..)+  , appendInputKey+  , inputKeysFromList   , inputKeysNull   , inputKeysElem   , foldInputKeys-  , inputKeysFromList-  , emptyInputKeys-  , stripInteractionInput+  , applyKey+  , releaseAllKeys+  , noModifiers+  , modPrimary+  , primaryModifiers+  , modJump+  , modMacCommand++    -- * File drops+  , DropType (..)+  , DropEvent (..)+  , appendDropEvent++    -- * Cursors   , UiCursorKind (..)   , grabHoverKind   , grabDragKind-  , clearEphemeral-  , isHardQuitInput-  , splitFrame-  ) where -import Data.Text (Text)-import qualified Data.Text as T-import Data.Primitive.SmallArray (SmallArray, copySmallArray, emptySmallArray, newSmallArray, runSmallArray, sizeofSmallArray, smallArrayFromList)-import NanoUI.Types (Size (..), V2 (..))--data Key-  = KeyBackspace-  | KeyDelete-  | KeyEnter-  | KeyEscape-  | KeyTab-  | KeyLeft-  | KeyRight-  | KeyUp-  | KeyDown-  | KeyHome-  | KeyEnd-  deriving (Eq, Show, Enum, Bounded)--data Modifiers = Modifiers-  { modShift :: !Bool-  , modCtrl :: !Bool-  , modAlt :: !Bool-  }-  deriving (Eq, Show)---- | OS-level drag-and-drop event kind, mirroring @SDL_EventType@ drop codes.-data DropType-  = DropBegin     -- ^ A drag enters the window; no position or payload yet.-  | DropPosition  -- ^ The drag pointer moved over the window; position available.-  | DropFile      -- ^ A file path was dropped; 'dropEventData' holds the path.-  | DropText      -- ^ Text was dropped; 'dropEventData' holds the text.-  | DropComplete  -- ^ The OS drag operation finished.-  deriving (Eq, Show)---- | A single normalized drop payload surfaced to widgets.-data DropEvent = DropEvent-  { dropEventType :: !DropType-  , dropEventPos :: !(Maybe V2)-  , dropEventData :: !Text-  }-  deriving (Eq, Show)--data Input = Input-  { inputMousePos :: {-# UNPACK #-} !V2-  , inputMouseDown :: {-# UNPACK #-} !Bool-  , inputMousePressed :: {-# UNPACK #-} !Bool-  , inputMouseReleased :: {-# UNPACK #-} !Bool-  , inputMouseRightDown :: {-# UNPACK #-} !Bool-  , inputMouseRightPressed :: {-# UNPACK #-} !Bool-  , inputMouseRightReleased :: {-# UNPACK #-} !Bool-  , inputMouseClicks :: {-# UNPACK #-} !Int-  , inputScroll :: {-# UNPACK #-} !V2-  , inputKeys :: SmallArray Key-  , inputChars :: !Text-  , inputModifiers :: !Modifiers-  , inputWindowSize :: {-# UNPACK #-} !Size-  , inputDeltaTime :: {-# UNPACK #-} !Float-  , inputDrops :: SmallArray DropEvent-  , inputWindowRedraw :: {-# UNPACK #-} !Bool-  }-  deriving (Eq, Show)--emptyInput :: Input-emptyInput =-  Input-    { inputMousePos = V2 0 0-    , inputMouseDown = False-    , inputMousePressed = False-    , inputMouseReleased = False-    , inputMouseRightDown = False-    , inputMouseRightPressed = False-    , inputMouseRightReleased = False-    , inputMouseClicks = 1-    , inputScroll = V2 0 0-    , inputKeys = emptyInputKeys-    , inputChars = ""-    , inputModifiers = Modifiers False False False-    , inputWindowSize = Size 800 600-    , inputDeltaTime = 0-    , inputDrops = emptyDropEvents-    , inputWindowRedraw = False-    }--data UiCursorKind-  = UiCursorDefault-  | UiCursorPointer-  | UiCursorText-  | UiCursorGrab-  | UiCursorGrabbing-  | UiCursorNsResize-  | UiCursorEwResize-  | UiCursorNwseResize-  | UiCursorNeswResize-  deriving (Eq, Show)--grabHoverKind :: Bool -> Input -> UiCursorKind-grabHoverKind onTarget inp = grabDragKind onTarget False inp--grabDragKind :: Bool -> Bool -> Input -> UiCursorKind-grabDragKind onTarget dragging inp-  | dragging = UiCursorGrabbing-  | onTarget, inputMouseDown inp = UiCursorGrabbing-  | onTarget = UiCursorGrab-  | otherwise = UiCursorDefault--clearEphemeral :: Input -> Input-clearEphemeral inp =-  inp-    { inputKeys = emptyInputKeys-    , inputChars = ""-    , inputMousePressed = False-    , inputMouseReleased = False-    , inputMouseRightPressed = False-    , inputMouseRightReleased = False-    , inputMouseClicks = 1-    , inputScroll = V2 0 0-    , inputDrops = emptyDropEvents-    , inputWindowRedraw = False-    }--isHardQuitInput :: Input -> Bool-isHardQuitInput inp =-  modCtrl (inputModifiers inp)-    && (T.elem 'c' (inputChars inp) || T.elem '\ETX' (inputChars inp))--splitFrame :: (a -> Bool) -> [a] -> ([a], [a])-splitFrame isEdge events =-  case break isEdge events of-    (before, edge : rest) -> (before ++ [edge], rest)-    (before, []) -> (before, [])--{-# INLINE appendInputKey #-}-appendInputKey :: Key -> SmallArray Key -> SmallArray Key-appendInputKey k ks = snocSmallArray ks k---- | The drops with one more at the end.-{-# INLINE appendDropEvent #-}-appendDropEvent :: DropEvent -> SmallArray DropEvent -> SmallArray DropEvent-appendDropEvent ev evs = snocSmallArray evs ev---- A frame holds a few keys and drops, so each append copies.-snocSmallArray :: SmallArray a -> a -> SmallArray a-snocSmallArray xs x = runSmallArray $ do-  let n = sizeofSmallArray xs-  out <- newSmallArray (n + 1) x-  copySmallArray out 0 xs 0 n-  pure out---- | Mouse buttons tracked by 'Input'.-data MouseButton = MouseLeft | MouseRight-  deriving (Eq, Show)---- | Apply a button transition: the held state plus that frame's one-shot--- pressed or released flag.-applyMouseButton :: MouseButton -> Bool -> Input -> Input-applyMouseButton MouseLeft True inp = inp {inputMouseDown = True, inputMousePressed = True}-applyMouseButton MouseLeft False inp = inp {inputMouseDown = False, inputMouseReleased = True}-applyMouseButton MouseRight True inp = inp {inputMouseRightDown = True, inputMouseRightPressed = True}-applyMouseButton MouseRight False inp = inp {inputMouseRightDown = False, inputMouseRightReleased = True}--{-# INLINE inputKeysFromList #-}-inputKeysFromList :: [Key] -> SmallArray Key-inputKeysFromList = smallArrayFromList--emptyInputKeys :: SmallArray Key-emptyInputKeys = emptySmallArray--emptyDropEvents :: SmallArray DropEvent-emptyDropEvents = emptySmallArray--{-# INLINE inputKeysNull #-}-inputKeysNull :: SmallArray Key -> Bool-inputKeysNull ks = sizeofSmallArray ks == 0--{-# INLINE inputKeysElem #-}-inputKeysElem :: Key -> SmallArray Key -> Bool-inputKeysElem = elem--{-# INLINE foldInputKeys #-}-foldInputKeys :: (a -> Key -> a) -> a -> SmallArray Key -> a-foldInputKeys = foldl'---- Buttons, keys, scroll, resize. Mouse motion alone does not count.-inputInteracted :: Input -> Input -> Bool-inputInteracted a b =-  inputMouseDown a /= inputMouseDown b-    || inputMousePressed a /= inputMousePressed b-    || inputMouseReleased a /= inputMouseReleased b-    || inputMouseRightDown a /= inputMouseRightDown b-    || inputMouseRightPressed a /= inputMouseRightPressed b-    || inputMouseRightReleased a /= inputMouseRightReleased b-    || inputMouseClicks a /= inputMouseClicks b-    || inputScroll a /= inputScroll b-    || inputKeys a /= inputKeys b-    || inputChars a /= inputChars b-    || inputModifiers a /= inputModifiers b-    || inputWindowSize a /= inputWindowSize b-    || inputDrops a /= inputDrops b--{-# INLINE inputPointerHeld #-}-inputPointerHeld :: Input -> Bool-inputPointerHeld inp =-  inputMouseDown inp || inputMouseRightDown inp+    -- * Input methods+  , Composition (..)+  , applyComposition+  , InputPurpose (..)+  ) where --- Rebuild UI after store mirrors update. Keep hover/drag; drop one-shot input.-stripInteractionInput :: Input -> Input-stripInteractionInput inp =-  inp-    { inputMousePressed = False-    , inputMouseReleased = False-    , inputMouseRightPressed = False-    , inputMouseRightReleased = False-    , inputKeys = emptyInputKeys-    , inputChars = ""-    , inputScroll = V2 0 0-    , inputDrops = emptyDropEvents-    }+import NanoUI.Internal.Input
+ lib/NanoUI/Internal/Animatable.hs view
@@ -0,0 +1,39 @@+-- | Indexed traversal of scalar channels for tween and spring animations.+module NanoUI.Internal.Animatable+  ( Animatable (..)+  )+where++import NanoUI.Internal.Types (Color, V2 (..), clamp01, colorA, colorB, colorG, colorR, colorRGBA)++-- | Visit each scalar channel once, in stable index order starting at zero.+-- Channel indices become animation keys. Reconstruction has the same shape as+-- the input, without an intermediate list. The animation engine uses 'Float';+-- the 'Double' instance therefore retains only single-precision channel values.+class Animatable a where+  -- | Transform scalar channels; colours use RGBA normalised to 0-1 and clamp+  -- and round transformed channels back to bytes.+  traverseChannels :: Applicative f => (Int -> Float -> f Float) -> a -> f a++instance Animatable Float where+  {-# INLINE traverseChannels #-}+  traverseChannels f = f 0++instance Animatable Double where+  {-# INLINE traverseChannels #-}+  traverseChannels f v = realToFrac <$> f 0 (realToFrac v)++instance Animatable V2 where+  {-# INLINE traverseChannels #-}+  traverseChannels f (V2 x y) = V2 <$> f 0 x <*> f 1 y++instance Animatable Color where+  {-# INLINE traverseChannels #-}+  traverseChannels f c =+    colorRGBA+      <$> channel 0 (colorR c)+      <*> channel 1 (colorG c)+      <*> channel 2 (colorB c)+      <*> channel 3 (colorA c)+   where+    channel i w = (\x -> fromIntegral (round (clamp01 x * 255) :: Int)) <$> f i (fromIntegral w / 255)
+ lib/NanoUI/Internal/Animation.hs view
@@ -0,0 +1,250 @@+-- | Scalar easing and spring integration. Durations and elapsed time use seconds.+module NanoUI.Internal.Animation+  ( Ease (..)+  , Animation (..)+  , SpringParams (..)+  , presetBouncy+  , presetSmooth+  , presetStiff+  , springEps+  , applyEase+  , approxEq+  , animInProgress+  , animationValue+  , easeSameSpec+  , stepAnim+  ) where++import NanoUI.Internal.Types (clamp01)++-- Cubic Bezier easing. X control points are clamped to [0, 1] (CSS-style).+-- t=0 and t=1 return the endpoints so Newton cannot pop the first/last frame.+evaluateBezier :: Float -> Float -> Float -> Float -> Float -> Float+evaluateBezier x1 y1 x2 y2 t0+  | t0 <= 0 = 0+  | t0 >= 1 = 1+  | otherwise =+      let p1 = clamp01 x1+          p2 = clamp01 x2+          tau = solveBezierX p1 p2 t0 0.5 0+       in sampleBezier y1 y2 tau++sampleBezier :: Float -> Float -> Float -> Float+sampleBezier p1 p2 u =+  let one = 1 - u+   in 3 * one * one * u * p1 + 3 * one * u * u * p2 + u * u * u++bezierDeriv :: Float -> Float -> Float -> Float+bezierDeriv p1 p2 u =+  let one = 1 - u+   in 3 * one * one * p1 + 6 * one * u * (p2 - p1) + 3 * u * u * (1 - p2)++solveBezierX :: Float -> Float -> Float -> Float -> Int -> Float+solveBezierX p1 p2 targetT estimate iter+  | iter >= 8 = estimate+  | otherwise =+      let currentX = sampleBezier p1 p2 estimate+          errorVal = currentX - targetT+       in if abs errorVal < 1e-4+            then estimate+            else+              let deriv = bezierDeriv p1 p2 estimate+                  safeDeriv =+                    if abs deriv < 1e-6+                      then if deriv >= 0 then 1e-6 else -1e-6+                      else deriv+                  nextEst = clamp01 (estimate - errorVal / safeDeriv)+               in solveBezierX p1 p2 targetT nextEst (iter + 1)++-- | Spring stiffness, damping, and mass. Time uses seconds. Integration clamps+-- stiffness/damping to non-negative values and mass to at least 1e-6. A+-- spring too stiff or light to follow in 32 steps a frame lands on its target.+data SpringParams = SpringParams+  { springStiffness :: {-# UNPACK #-} !Float+  , springDamping :: {-# UNPACK #-} !Float+  , springMass :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | Lightly damped spring: stiffness 180, damping 12, mass 1.+presetBouncy :: SpringParams+presetBouncy = SpringParams {springStiffness = 180, springDamping = 12, springMass = 1}++-- | Near-critically damped spring: stiffness 120, damping 20, mass 1.+presetSmooth :: SpringParams+presetSmooth = SpringParams {springStiffness = 120, springDamping = 20, springMass = 1}++-- | Faster spring: stiffness 300, damping 30, mass 1.+presetStiff :: SpringParams+presetStiff = SpringParams {springStiffness = 300, springDamping = 30, springMass = 1}++springEps :: Float+springEps = 1e-3++maxSubstep :: Float+maxSubstep = 1 / 30++maxSubsteps :: Int+maxSubsteps = 32++-- | Advance the displacement from the target and the velocity by elapsed+-- seconds. Non-positive time leaves both unchanged. Substeps are at most+-- 1/30 s, and short enough for the spring to stay stable; one that needs more+-- than 32 lands on the target.+stepSpring :: SpringParams -> Float -> Float -> Float -> (Float, Float)+stepSpring params x v dt+  | dt <= 0 = (x, v)+  | otherwise = go x v dt 0+  where+    k = max 0 (springStiffness params)+    c = max 0 (springDamping params)+    m = max 1e-6 (springMass params)+    -- RK4 is stable while a step times the spring's fastest rate, at most+    -- c/m + sqrt (k/m), stays under about 2.8.+    hMax = min maxSubstep (2 / (c / m + sqrt (k / m)))+    go !pos !vel remain n+      | remain <= 1e-8 = (pos, vel)+      | n >= maxSubsteps = (0, 0)+      | otherwise =+          let h = min hMax remain+              (pos', vel') = rk4 k c m pos vel h+           in go pos' vel' (remain - h) (n + 1)++rk4 :: Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float)+rk4 k c m x v dt =+  let k1v = accel x v+      k1x = v+      k2v = accel (x + 0.5 * dt * k1x) (v + 0.5 * dt * k1v)+      k2x = v + 0.5 * dt * k1v+      k3v = accel (x + 0.5 * dt * k2x) (v + 0.5 * dt * k2v)+      k3x = v + 0.5 * dt * k2v+      k4v = accel (x + dt * k3x) (v + dt * k3v)+      k4x = v + dt * k3v+      xNext = x + (dt / 6) * (k1x + 2 * k2x + 2 * k3x + k4x)+      vNext = v + (dt / 6) * (k1v + 2 * k2v + 2 * k3v + k4v)+   in (xNext, vNext)+  where+    accel pos vel = (-k * pos - c * vel) / m++-- | Progress curves. Cubic Bezier arguments are @x1 y1 x2 y2@ for the two+-- control points between endpoints (0,0) and (1,1).+data Ease+  = EaseLinear+  | EaseInQuad+  | EaseOutQuad+  | EaseInOutQuad+  | EaseInCubic+  | EaseOutCubic+  | EaseInOutCubic+  | EaseOutBack+  | EaseCubicBezier+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  deriving (Eq, Show)++-- | Running scalar animation. 'EaseAnim' stores start, end, duration, elapsed+-- time, curve, remaining delay, and requested delay (times in seconds).+-- 'SpringAnim' stores displacement from the target, velocity, target, and+-- spring parameters. Integrating the displacement keeps a spring toward a+-- large target from stalling a few float steps short of it.+data Animation+  = EaseAnim+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      !Ease+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  | SpringAnim+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      !SpringParams+  deriving (Eq, Show)++-- | Whether a tween matches curve, duration, requested delay, and target.+-- Numeric comparisons use 'approxEq'; springs never match.+easeSameSpec :: Animation -> Ease -> Float -> Float -> Float -> Bool+easeSameSpec (EaseAnim _ end dur _ ease _ delayReq) wantEase wantDur delay target =+  ease == wantEase+    && approxEq dur wantDur+    && approxEq delay delayReq+    && approxEq end target+easeSameSpec _ _ _ _ _ = False++-- | Map unit progress through an easing curve. Input is clamped to [0, 1].+-- EaseOutBack may return a value outside that range (overshoot).+applyEase :: Ease -> Float -> Float+applyEase ease t0 =+  let t = clamp01 t0+   in case ease of+        EaseLinear -> t+        EaseInQuad -> t * t+        EaseOutQuad -> t * (2 - t)+        EaseInOutQuad+          | t < 0.5 -> 2 * t * t+          | otherwise -> -1 + (4 - 2 * t) * t+        EaseInCubic -> t * t * t+        EaseOutCubic ->+          let u = 1 - t+           in 1 - u * u * u+        EaseInOutCubic+          | t < 0.5 -> 4 * t * t * t+          | otherwise ->+              let u = -2 * t + 2+               in 1 - (u * u * u) / 2+        EaseOutBack ->+          let c1 = 1.70158+              c3 = c1 + 1+              u = t - 1+           in 1 + c3 * u * u * u + c1 * u * u+        EaseCubicBezier x1 y1 x2 y2 -> evaluateBezier x1 y1 x2 y2 t++-- | Absolute difference no greater than 1e-4.+approxEq :: Float -> Float -> Bool+approxEq a b = abs (a - b) <= 1e-4++-- | Whether a tween has time remaining or a spring has position/velocity+-- error greater than 1e-3. Delayed nontrivial tweens count as running.+{-# INLINE animInProgress #-}+animInProgress :: Animation -> Bool+animInProgress (EaseAnim start end dur elapsed _ delay _) =+  not (approxEq start end)+    && dur > 0+    && (delay > 0 || elapsed < dur)+animInProgress (SpringAnim d vel _ _) =+  abs d > springEps || abs vel > springEps++-- | Current interpolated value, or the target for a completed tween.+{-# INLINE animationValue #-}+animationValue :: Animation -> Float+animationValue a@(EaseAnim start end dur elapsed ease delay _)+  | not (animInProgress a) = end+  | delay > 0 = start+  | otherwise =+      let t = min 1 (elapsed / max 0.001 dur)+       in start + (end - start) * applyEase ease t+animationValue (SpringAnim d _ target _) = target + d++-- | Advance an animation by elapsed seconds, including its delay.+stepAnim :: Float -> Animation -> Animation+stepAnim dt a@(EaseAnim start end dur elapsed ease delay delayReq)+  | not (animInProgress a) = a+  | delay > 0 =+      let remain = delay - dt+       in if remain > 0+            then EaseAnim start end dur elapsed ease remain delayReq+            else stepAnim (negate remain) (EaseAnim start end dur elapsed ease 0 delayReq)+  | otherwise =+      let next = elapsed + dt+       in if next >= dur+            then EaseAnim end end 0 0 ease 0 0+            else EaseAnim start end dur next ease 0 delayReq+stepAnim dt (SpringAnim d vel target params) =+  let (d', vel') = stepSpring params d vel dt+   in if abs d' <= springEps && abs vel' <= springEps+        then SpringAnim 0 0 target params+        else SpringAnim d' vel' target params
+ lib/NanoUI/Internal/Atlas.hs view
@@ -0,0 +1,390 @@+-- | Context-owned RGBA image atlas with shelf packing and versioned pixel+-- snapshots. Space freed by 'releaseImage' is reused by later images that fit.+module NanoUI.Internal.Atlas+  ( ImageAtlas+  , newImageAtlas+  , atlasTextureId+  , registerImage+  , releaseImage+  , freshImageId+  , lookupImageUv+  , lookupImageSize+  , withImageSlot+  , AtlasToken+  , atlasToken+  , atlasReleases+  , atlasSnapshot+  , AtlasUpload (..)+  , atlasChanges+  )+where++import Control.Applicative ((<|>))+import Control.Monad (forM_)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Unsafe qualified as BSU+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.Word (Word8)+import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtrBytes, withForeignPtr)+import Foreign.Marshal.Utils (copyBytes, fillBytes)+import Foreign.Ptr (Ptr, plusPtr)+import NanoUI.Internal.Draw.Types (glyphAtlasPages, glyphPageTextureId)+import NanoUI.Internal.Store (ptrEq)+import NanoUI.Internal.Types (ImageId (..))++-- | GPU texture id shared by every packed image so draw cmds batch. It is+-- reserved, like the glyph atlas pages' ids above it+-- ('NanoUI.Backend.glyphPageTextureId'), rather than a small+-- number: a drawing's image op names a registered 'ImageId' or a raw+-- texture, and 'freshImageId' starts at 1, so an unregistered image id must+-- not also name the atlas. It is the id below the last glyph page's, so more+-- pages move it down rather than onto a page.+atlasTextureId :: Int+atlasTextureId = glyphPageTextureId glyphAtlasPages++atlasPad :: Int+atlasPad = 1++atlasStart :: Int+atlasStart = 256++atlasMax :: Int+atlasMax = 4096++data AtlasSlot = AtlasSlot+  { slotX :: {-# UNPACK #-} !Int+  , slotY :: {-# UNPACK #-} !Int+  , slotW :: {-# UNPACK #-} !Int+  , slotH :: {-# UNPACK #-} !Int+  }++data AtlasState = AtlasState+  { asW :: {-# UNPACK #-} !Int+  , asH :: {-# UNPACK #-} !Int+  , asPtr :: ForeignPtr Word8+  , asSlots :: IM.IntMap AtlasSlot+  , asX :: {-# UNPACK #-} !Int+  , asY :: {-# UNPACK #-} !Int+  , asRowH :: {-# UNPACK #-} !Int+  , asGen :: {-# UNPACK #-} !Int+  , asLastFresh :: {-# UNPACK #-} !Int+  -- ^ The last id 'freshImageId' returned.+  , asResizedGen :: {-# UNPACK #-} !Int+  -- ^ Generation of the last atlas resize.+  , asWrites :: [AtlasSlot]+  -- ^ The slot each recent generation wrote (each writes one), newest first:+  -- at least the last 'atlasWriteLog', and fewer than twice as many.+  , asWriteCount :: {-# UNPACK #-} !Int+  , asFree :: [AtlasSlot]+  -- ^ Space freed by released images, including each one's trailing padding.+  -- 'takeFree' tries these before the shelves.+  , asReleased :: {-# UNPACK #-} !Int+  -- ^ How many images 'releaseImage' has removed ('atlasReleases').+  }++newtype ImageAtlas = ImageAtlas (IORef AtlasState)++-- | The atlas as it is at one moment. Two tokens are equal only while no+-- image was registered or released between them: each write installs a new+-- state.+newtype AtlasToken = AtlasToken AtlasState++instance Eq AtlasToken where+  AtlasToken a == AtlasToken b = ptrEq a b++atlasToken :: ImageAtlas -> IO AtlasToken+atlasToken (ImageAtlas ref) = AtlasToken <$> readIORef ref++-- | How many images have been released, so one that did not fit can be tried+-- again once room may have come free.+atlasReleases :: ImageAtlas -> IO Int+atlasReleases (ImageAtlas ref) = asReleased <$> readIORef ref++newImageAtlas :: IO ImageAtlas+newImageAtlas = do+  fp <- allocPixels atlasStart atlasStart+  ImageAtlas+    <$> newIORef+      AtlasState+        { asW = atlasStart+        , asH = atlasStart+        , asPtr = fp+        , asSlots = IM.empty+        , asX = atlasPad+        , asY = atlasPad+        , asRowH = 0+        , asGen = 0+        , asLastFresh = 0+        , asResizedGen = 0+        , asWrites = []+        , asWriteCount = 0+        , asFree = []+        , asReleased = 0+        }++registerImage :: ImageAtlas -> ImageId -> Int -> Int -> ByteString -> IO Bool+registerImage (ImageAtlas ref) (ImageId tid) w h pixels+  | tid <= 0 || w <= 0 || h <= 0 = pure False+  | w > atlasMax - 2 * atlasPad || h > atlasMax - 2 * atlasPad = pure False+  | BS.length pixels < w * h * 4 = pure False+  | otherwise = do+      st0 <- readIORef ref+      case IM.lookup tid (asSlots st0) of+        Just slot+          | slotW slot == w && slotH slot == h -> do+              blitPixels (asPtr st0) (asW st0) (slotX slot) (slotY slot) w h pixels+              writeIORef ref (recordWrite slot st0)+              pure True+          | otherwise -> pure False+        Nothing -> case takeFree st0 w h of+          Just (x, y, st1) -> True <$ (writeIORef ref =<< placeInFree st1 tid x y w h pixels)+          Nothing ->+            fitImage st0 tid w h pixels+              >>= maybe (pure False) (\st1 -> True <$ writeIORef ref st1)++-- | Remove an image. Its id stops drawing and its space goes on the free+-- list. The old pixels stay until another image overwrites them, and+-- 'freshImageId' never returns the id again. Unregistered ids are ignored.+-- Returns whether the id was registered.+releaseImage :: ImageAtlas -> ImageId -> IO Bool+releaseImage (ImageAtlas ref) (ImageId tid) = do+  st <- readIORef ref+  case IM.lookup tid (asSlots st) of+    Nothing -> pure False+    Just (AtlasSlot x y w h) -> do+      let slots' = IM.delete tid (asSlots st)+          emptyAtlas = IM.null slots'+      writeIORef ref $!+        st+          { asSlots = slots'+          , asX = if emptyAtlas then atlasPad else asX st+          , asY = if emptyAtlas then atlasPad else asY st+          , asRowH = if emptyAtlas then 0 else asRowH st+          , asFree = if emptyAtlas then [] else mergeFree (AtlasSlot x y (w + atlasPad) (h + atlasPad)) (asFree st)+          , asLastFresh = max tid (asLastFresh st)+          , asReleased = asReleased st + 1+          }+      pure True++-- | Put @slot@ on the free list joined with the free slots it shares a whole+-- edge with, so space split up for smaller images is whole again once they+-- are all released.+mergeFree :: AtlasSlot -> [AtlasSlot] -> [AtlasSlot]+mergeFree slot@(AtlasSlot x y w h) frees = case break beside frees of+  (before, AtlasSlot fx fy fw fh : after)+    | fy == y -> mergeFree (AtlasSlot (min x fx) y (w + fw) h) (before ++ after)+    | otherwise -> mergeFree (AtlasSlot x (min y fy) w (h + fh)) (before ++ after)+  _ -> slot : frees+  where+    beside (AtlasSlot fx fy fw fh) =+      (fy == y && fh == h && (fx + fw == x || x + w == fx))+        || (fx == x && fw == w && (fy + fh == y || y + h == fy))++-- | Find the first free slot that fits a @w@ x @h@ image plus padding, and+-- return the image position and the updated state. The leftover space is+-- split into a strip to the right (image height plus padding) and a strip+-- below (full slot width). A strip too thin for any image is kept for+-- 'mergeFree' to join back.+takeFree :: AtlasState -> Int -> Int -> Maybe (Int, Int, AtlasState)+takeFree st w h = go [] (asFree st)+  where+    go _ [] = Nothing+    go seen (slot@(AtlasSlot fx fy fw fh) : rest)+      | w + atlasPad <= fw && h + atlasPad <= fh =+          let right = [AtlasSlot (fx + w + atlasPad) fy (fw - w - atlasPad) (h + atlasPad) | fw - w - atlasPad > 0]+              below = [AtlasSlot fx (fy + h + atlasPad) fw (fh - h - atlasPad) | fh - h - atlasPad > 0]+           in Just (fx, fy, st {asFree = foldl' (flip (:)) (right ++ below ++ rest) seen})+      | otherwise = go (slot : seen) rest++-- | Write an image into freed space at @x@ @y@ and zero the padding around+-- it. The previous image may have drawn there, and texture filtering at the+-- edge samples the padding. The recorded write includes the padding so the+-- upload clears it on the GPU too.+placeInFree :: AtlasState -> Int -> Int -> Int -> Int -> Int -> ByteString -> IO AtlasState+placeInFree st tid x y w h pixels = do+  blitPixels (asPtr st) (asW st) x y w h pixels+  withForeignPtr (asPtr st) $ \p -> do+    let clear px py n = fillBytes (p `plusPtr` ((py * asW st + px) * 4)) 0 (n * 4)+    clear (x - atlasPad) (y - atlasPad) (w + 2 * atlasPad)+    clear (x - atlasPad) (y + h) (w + 2 * atlasPad)+    forM_ [y .. y + h - 1] $ \row -> clear (x - atlasPad) row atlasPad >> clear (x + w) row atlasPad+  pure+    ( recordWrite+        (AtlasSlot (x - atlasPad) (y - atlasPad) (w + 2 * atlasPad) (h + 2 * atlasPad))+        st {asSlots = IM.insert tid (AtlasSlot x y w h) (asSlots st)}+    )++-- | An id above every registered image's and every id this returned before.+-- An id the app picks itself can still collide with one returned and not yet+-- registered, so register those first.+freshImageId :: ImageAtlas -> IO ImageId+freshImageId (ImageAtlas ref) = do+  st <- readIORef ref+  let tid = 1 + maybe (asLastFresh st) (max (asLastFresh st) . fst) (IM.lookupMax (asSlots st))+  writeIORef ref st {asLastFresh = tid}+  pure (ImageId tid)++lookupImageUv ::+  ImageAtlas -> ImageId -> IO (Maybe (Float, Float, Float, Float))+lookupImageUv atlas iid = withImageSlot atlas iid (pure Nothing) $ \_ _ u0 v0 u1 v1 -> pure (Just (u0, v0, u1, v1))++-- | A registered image's pixel size and atlas UV bounds, from one lookup,+-- passed to @k@; @none@ when the image is not registered.+{-# INLINE withImageSlot #-}+withImageSlot :: ImageAtlas -> ImageId -> IO r -> (Int -> Int -> Float -> Float -> Float -> Float -> IO r) -> IO r+withImageSlot (ImageAtlas ref) (ImageId tid) none k = do+  st <- readIORef ref+  case IM.lookup tid (asSlots st) of+    Nothing -> none+    Just (AtlasSlot x y w h) -> do+      let !fw = fromIntegral (asW st) :: Float+          !fh = fromIntegral (asH st) :: Float+          !u0 = fromIntegral x / fw+          !v0 = fromIntegral y / fh+          !u1 = fromIntegral (x + w) / fw+          !v1 = fromIntegral (y + h) / fh+      k w h u0 v0 u1 v1++-- | Pixel width and height of a registered image.+lookupImageSize :: ImageAtlas -> ImageId -> IO (Maybe (Int, Int))+lookupImageSize atlas iid = withImageSlot atlas iid (pure Nothing) $ \w h _ _ _ _ -> pure (Just (w, h))++-- | Writes 'asWrites' keeps: enough for a few frames of a few changing+-- images between two uploads.+atlasWriteLog :: Int+atlasWriteLog = 64++-- | Advance the generation for a write to @slot@, and log it. The log is cut+-- back to 'atlasWriteLog' only once it holds twice that, so a write copies+-- no list.+recordWrite :: AtlasSlot -> AtlasState -> AtlasState+recordWrite slot st+  | n < 2 * atlasWriteLog = st {asGen = gen, asWrites = logged, asWriteCount = n}+  -- The cut is forced: left lazy, it would keep the whole log behind it.+  | otherwise = let cut = take atlasWriteLog logged in length cut `seq` st {asGen = gen, asWrites = cut, asWriteCount = atlasWriteLog}+  where+    n = asWriteCount st + 1+    gen = asGen st + 1+    logged = slot : asWrites st++-- | Upload required to bring a GPU texture up to the current atlas generation.+data AtlasUpload+  = AtlasWhole+  -- ^ Upload the full buffer at the current atlas size (no texture yet,+  -- resized since @since@, or written since longer ago than the atlas's+  -- recent write log reaches).+  | AtlasRegions [(Int, Int, Int, Int)]+  -- ^ Upload only these @(x, y, width, height)@ pixel rects into the existing texture.+  deriving (Eq, Show)++-- | Current atlas dimensions, pixel buffer, generation, and the upload+-- required since generation @since@ (0 when uninitialized). 'Nothing' until+-- the first image is registered, and when the atlas is already at @since@.+atlasChanges :: ImageAtlas -> Int -> IO (Maybe (Int, Int, ForeignPtr Word8, Int, AtlasUpload))+atlasChanges (ImageAtlas ref) since = do+  st <- readIORef ref+  let gen = asGen st+      upload+        | since <= 0 || since > gen || since < asResizedGen st = AtlasWhole+        -- The log holds one write a generation, newest first.+        | gen - since > asWriteCount st = AtlasWhole+        | otherwise =+            AtlasRegions [(x, y, w, h) | AtlasSlot x y w h <- take (gen - since) (asWrites st)]+  pure $+    if gen == 0 || gen == since+      then Nothing+      else Just (asW st, asH st, asPtr st, gen, upload)++-- | The atlas's width, height, pinned pixels and generation; 'Nothing' until+-- the first image is registered. SDL uploads the pointer; do not copy to+-- ByteString first.+atlasSnapshot :: ImageAtlas -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))+atlasSnapshot atlas = fmap (\(w, h, p, gen, _) -> (w, h, p, gen)) <$> atlasChanges atlas 0++fitImage ::+  AtlasState -> Int -> Int -> Int -> ByteString -> IO (Maybe AtlasState)+fitImage st0 tid w h pixels =+  -- Plan the shelf position before allocating or copying the atlas. A full+  -- atlas must reject an image without repeatedly allocating doomed growth.+  case cursorFor st0 w h <|> firstGrowth <|> secondGrowth of+    Nothing -> pure Nothing+    Just (x, y, placed) -> do+      let resized = asW placed /= asW st0 || asH placed /= asH st0+      fp <-+        if resized+          then do+            buf <- allocPixels (asW placed) (asH placed)+            withForeignPtr (asPtr st0) $ \sp ->+              withForeignPtr buf $ \dp -> copyRows dp (asW placed) 0 sp (asW st0) (asW st0) (asH st0)+            pure buf+          else pure (asPtr st0)+      blitPixels fp (asW placed) x y w h pixels+      let slot = AtlasSlot x y w h+          written = recordWrite slot placed+      pure $+        Just+          written+            { asPtr = fp+            , asSlots = IM.insert tid slot (asSlots placed)+            , asX = x + w + atlasPad+            , asY = y+            , asRowH = max (asRowH placed) h+            , asResizedGen = if resized then asGen written else asResizedGen placed+            }+ where+  -- Grow the shorter side first. Widening gives the current shelf room on+  -- its right and later shelves the full width; growing only taller would+  -- stack narrow images in one column until the height limit, with the rest+  -- of the allowed area unused.+  wider = st0 {asW = growDim (asW st0) (max (w + 2 * atlasPad) (asX st0 + w + atlasPad))}+  taller = st0 {asH = growDim (asH st0) (asY st0 + asRowH st0 + h + 2 * atlasPad)}+  both = taller {asW = asW wider}+  (firstGrowth, secondGrowth)+    | asW st0 <= asH st0 = (cursorFor wider w h, cursorFor taller w h <|> cursorFor both w h)+    | otherwise = (cursorFor taller w h, cursorFor wider w h <|> cursorFor both w h)++cursorFor :: AtlasState -> Int -> Int -> Maybe (Int, Int, AtlasState)+cursorFor st w h+  | asX st + w + atlasPad <= asW st && asY st + h + atlasPad <= asH st =+      Just (asX st, asY st, st)+  | asY st + asRowH st + atlasPad + h + atlasPad <= asH st+      && w + 2 * atlasPad <= asW st =+      let+        y = asY st + asRowH st + atlasPad+       in+        Just (atlasPad, y, st {asX = atlasPad, asY = y, asRowH = 0})+  | otherwise = Nothing++growDim :: Int -> Int -> Int+growDim cur need+  | need <= cur = cur+  | otherwise = min atlasMax (max need (cur * 2))++allocPixels :: Int -> Int -> IO (ForeignPtr Word8)+allocPixels w h = do+  let+    n = w * h * 4+  fp <- mallocForeignPtrBytes n+  withForeignPtr fp $ \p -> fillBytes p 0 n+  pure fp++blitPixels ::+  ForeignPtr Word8 -> Int -> Int -> Int -> Int -> Int -> ByteString -> IO ()+blitPixels dest destW destX destY w h pixels =+  withForeignPtr dest $ \dp ->+    BSU.unsafeUseAsCString pixels $ \sp ->+      copyRows dp destW (destY * destW + destX) sp w w h++-- | Copy @rows@ rows of @w@ RGBA pixels from @src@, @srcW@ pixels a row, to+-- @dst@, @dstW@ pixels a row, starting @dstOff@ pixels in.+copyRows :: Ptr a -> Int -> Int -> Ptr b -> Int -> Int -> Int -> IO ()+copyRows dst dstW dstOff src srcW w rows =+  mapM_ copyRow [0 .. rows - 1]+ where+  copyRow row =+    copyBytes+      (dst `plusPtr` ((dstOff + row * dstW) * 4))+      (src `plusPtr` (row * srcW * 4))+      (w * 4)
+ lib/NanoUI/Internal/BackendSession.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE TypeFamilies #-}++-- | The value a backend keeps for its session (an SDL window's environment,+-- say), stored on the context and read back at its own type. A backend is+-- named at the type level; its singleton picks the value out, and matching+-- two singletons proves their backends the same, so the lookup needs no+-- runtime type representation or cast.+module NanoUI.Internal.BackendSession+  ( Backend (..)+  , SBackend (..)+  , BackendSession+  , SomeBackendSession (..)+  , sessionFor+  ) where++import Data.Kind (Type)+import Data.Type.Equality (TestEquality (..), (:~:) (..))+import GHC.TypeLits (SSymbol, Symbol)++-- | The backends that keep a session on the context, as a kind. SDL has its+-- own constructor; every other backend, RGFW included, names itself with+-- 'Custom'.+data Backend = Sdl | Custom Symbol++-- | The singleton of a 'Backend'.+type SBackend :: Backend -> Type+data SBackend b where+  SSdl :: SBackend 'Sdl+  SCustom :: SSymbol s -> SBackend ('Custom s)++instance TestEquality SBackend where+  testEquality SSdl SSdl = Just Refl+  testEquality (SCustom a) (SCustom b) = (\Refl -> Refl) <$> testEquality a b+  testEquality _ _ = Nothing++-- | What a backend keeps for its session. Each backend package gives its own+-- instance, such as @type instance BackendSession 'Sdl = SdlEnv@.+type family BackendSession (b :: Backend) :: Type++-- | A session value together with the backend it belongs to.+data SomeBackendSession = forall b. SomeBackendSession !(SBackend b) (BackendSession b)++-- | The session value, if it belongs to the backend asked for.+sessionFor :: SBackend b -> SomeBackendSession -> Maybe (BackendSession b)+sessionFor want (SomeBackendSession have session) = (\Refl -> session) <$> testEquality want have
+ lib/NanoUI/Internal/Canvas.hs view
@@ -0,0 +1,380 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | 'CanvasM', the monad custom widgets draw with. "NanoUI.Widgets.Custom"+-- exports the API; this module also exposes the representation for tools+-- that build their own draw ops.+module NanoUI.Internal.Canvas+  ( -- * Canvas blocks+    CanvasM (..)+  , CanvasEnv (..)+  , runCanvasFor+  , runCanvasScaled+  , emitOp+  , emitWith+  , drawContext+    -- * Shapes+  , drawRect+  , drawRoundedRect+  , drawCircle+  , drawStroke+  , drawStrokeRoundedRect+  , drawStrokeCircle+  , drawStrokeAA+  , drawQuadGradient+  , drawLinearGradientH+  , drawLinearGradientV+  , drawImage+  , drawImageUV+  , ImageDraw (..)+  , imageDraw+  , drawImageWith+  , drawText+  , drawTextWith+  , drawTextClipped+  , drawTextClippedWith+  , drawCheckbox+    -- * Paths, clips and transforms+  , drawPath+  , drawPathWith+  , drawStrokePath+  , drawStrokePathWith+  , withTransform+  , withClip+  ) where++import Control.Monad (when)+import Control.Monad.ST (ST, runST)+import Data.Maybe (fromMaybe)+import Data.Primitive.PrimVar (PrimVar, newPrimVar, readPrimVar, writePrimVar)+import Data.Primitive.SmallArray+  ( SmallArray+  , SmallMutableArray+  , copySmallMutableArray+  , emptySmallArray+  , getSizeofSmallMutableArray+  , newSmallArray+  , shrinkSmallMutableArray+  , unsafeFreezeSmallArray+  , writeSmallArray+  )+import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Context.Types (CustomDrawContext (..))+import NanoUI.Internal.Draw (DrawOp (..), TextFont (..), checkboxOps, defaultTextFont)+import NanoUI.Internal.Font (FontMetrics (fmAscent, fmSnapScale), tabularFontMetrics, truncateTextPure)+import NanoUI.Internal.Image (ImageDraw (..), imageDraw, imageDrawOp)+import NanoUI.Internal.Path (FillRule (..), Paint (..), Path, Stroke, Transform, curveTolerance, fillPathOps, stroke, strokePathOps, transformOp)+import NanoUI.Internal.Style (AlignX (..), AlignY (..), Style (..), TextEllipsis (..), Theme (..), alignXFraction)+import NanoUI.Internal.Types (Color, ImageId, Rect (..), V2 (..))++-- | Growable op buffer written directly during 'runCanvasScaled' without+-- intermediate lists or difference-list closures.+data CanvasBuf s+  = CanvasBuf+      {-# UNPACK #-} !(STRef s (SmallMutableArray s DrawOp))+      {-# UNPACK #-} !(PrimVar s Int)++-- | A drawing block that appends draw ops directly into a growable array.+-- Run it with 'runCanvasFor'.+newtype CanvasM a = CanvasM (forall s. CanvasEnv -> CanvasBuf s -> ST s a)++instance Functor CanvasM where+  {-# INLINE fmap #-}+  fmap f (CanvasM m) = CanvasM $ \env buf -> f <$> m env buf++instance Applicative CanvasM where+  {-# INLINE pure #-}+  pure a = CanvasM $ \_ _ -> pure a+  {-# INLINE (<*>) #-}+  CanvasM mf <*> CanvasM ma = CanvasM $ \env buf -> mf env buf <*> ma env buf+  {-# INLINE (*>) #-}+  CanvasM ma *> CanvasM mb = CanvasM $ \env buf -> ma env buf *> mb env buf+  {-# INLINE (<*) #-}+  CanvasM ma <* CanvasM mb = CanvasM $ \env buf -> ma env buf <* mb env buf++instance Monad CanvasM where+  {-# INLINE (>>=) #-}+  CanvasM ma >>= f = CanvasM $ \env buf -> do+    a <- ma env buf+    case f a of+      CanvasM mb -> mb env buf++-- | The environment of a canvas block: the current 'withTransform'+-- transform, the curve flattening tolerance in logical pixels, and the+-- widget's draw context. The last two are lazy, so a block that draws no+-- curve or never calls 'drawContext' does not compute them.+data CanvasEnv = CanvasEnv+  { ceTransform :: !(Maybe Transform)+  , ceTolerance :: Float+  , ceContext :: CustomDrawContext+  }++-- | Run a custom widget's drawing. Curves are flattened to within a quarter+-- of a device pixel at the context's display scale, and 'drawContext'+-- returns the context:+--+-- > widgetDraw = \cdc rect -> runCanvasFor cdc (drawPath (P.circle (V2 20 20) 12) accent)+{-# INLINE runCanvasFor #-}+runCanvasFor :: CustomDrawContext -> CanvasM a -> SmallArray DrawOp+runCanvasFor cdc = runCanvasScaled cdc (fmSnapScale (cdcFont cdc))++-- | Run a block at an explicit display scale (device pixels per logical+-- pixel).+{-# INLINE runCanvasScaled #-}+runCanvasScaled :: CustomDrawContext -> Float -> CanvasM a -> SmallArray DrawOp+runCanvasScaled cdc scale (CanvasM m) = runST $ do+  arr0 <- newSmallArray 16 PopClip+  arrRef <- newSTRef arr0+  lenVar <- newPrimVar 0+  _ <- m (CanvasEnv Nothing (curveTolerance scale) cdc) (CanvasBuf arrRef lenVar)+  n <- readPrimVar lenVar+  if n <= 0+    then pure emptySmallArray+    else do+      arr <- readSTRef arrRef+      cap <- getSizeofSmallMutableArray arr+      when (n < cap) (shrinkSmallMutableArray arr n)+      unsafeFreezeSmallArray arr++{-# NOINLINE growCanvasBuf #-}+growCanvasBuf :: STRef s (SmallMutableArray s DrawOp) -> Int -> ST s (SmallMutableArray s DrawOp)+growCanvasBuf ref needed = do+  arr <- readSTRef ref+  cap <- getSizeofSmallMutableArray arr+  let !newCap = max needed (cap * 2)+  grown <- newSmallArray newCap PopClip+  copySmallMutableArray grown 0 arr 0 cap+  writeSTRef ref grown+  pure grown++{-# INLINE pushRawOp #-}+pushRawOp :: CanvasBuf s -> DrawOp -> ST s ()+pushRawOp (CanvasBuf arrRef lenVar) !op = do+  n <- readPrimVar lenVar+  arr0 <- readSTRef arrRef+  cap <- getSizeofSmallMutableArray arr0+  arr <- if n < cap then pure arr0 else growCanvasBuf arrRef (n + 1)+  writeSmallArray arr n op+  writePrimVar lenVar (n + 1)++-- | Emit an op, applying the block's transform.+{-# INLINE emitOp #-}+emitOp :: DrawOp -> CanvasM ()+emitOp op = CanvasM $ \env buf ->+  case ceTransform env of+    Nothing -> pushRawOp buf op+    Just t -> pushList buf (transformOp (ceTolerance env) t op)++{-# INLINE pushList #-}+pushList :: CanvasBuf s -> [DrawOp] -> ST s ()+pushList buf = go+  where+    go [] = pure ()+    go (y : ys) = pushRawOp buf y >> go ys++-- | Emit ops built from the block's transform (identity if none) and curve+-- tolerance.+{-# INLINE emitWith #-}+emitWith :: (Transform -> Float -> [DrawOp]) -> CanvasM ()+emitWith build = CanvasM $ \env buf ->+  pushList buf (build (fromMaybe mempty (ceTransform env)) (ceTolerance env))++-- | The draw context of the widget being drawn: hover, press and focus+-- state, theme, and text font.+--+-- > canvas (fixedWH 40 40) $ \r -> do+-- >   cdc <- drawContext+-- >   drawRoundedRect r 6 (if cdcHovered cdc then themeAccent (cdcTheme cdc) else themeMuted (cdcTheme cdc))+{-# INLINE drawContext #-}+drawContext :: CanvasM CustomDrawContext+drawContext = CanvasM $ \env _ -> pure (ceContext env)++-- | Fill a solid rectangle.+{-# INLINE drawRect #-}+drawRect :: Rect -> Color -> CanvasM ()+drawRect r c = emitOp (FillRect r c)++-- | Fill a rounded rectangle with given corner radius.+{-# INLINE drawRoundedRect #-}+drawRoundedRect :: Rect -> Float -> Color -> CanvasM ()+drawRoundedRect r radius c = emitOp (FillRoundedRect r radius c)++-- | Fill a solid circle at center with given radius.+{-# INLINE drawCircle #-}+drawCircle :: V2 -> Float -> Color -> CanvasM ()+drawCircle (V2 cx cy) radius c = emitOp (FillCircle cx cy radius c)++-- | A straight line of the given thickness. It is not anti-aliased, so+-- slanted lines look jagged; 'drawStrokeAA' draws them smooth.+{-# INLINE drawStroke #-}+drawStroke :: V2 -> V2 -> Float -> Color -> CanvasM ()+drawStroke (V2 x0 y0) (V2 x1 y1) thickness c = emitOp (Stroke x0 y0 x1 y1 thickness c)++-- | Stroke a rounded rectangle's border with the given corner radius and+-- width. The border lies inside the rectangle, unlike 'drawStrokePath',+-- which centres the stroke on the path.+{-# INLINE drawStrokeRoundedRect #-}+drawStrokeRoundedRect :: Rect -> Float -> Float -> Color -> CanvasM ()+drawStrokeRoundedRect r radius thickness c = emitOp (StrokeRoundedRect r radius thickness c)++-- | Stroke a circle's outline with the given width. Like+-- 'drawStrokeRoundedRect', the outline lies inside the circle.+{-# INLINE drawStrokeCircle #-}+drawStrokeCircle :: V2 -> Float -> Float -> Color -> CanvasM ()+drawStrokeCircle (V2 cx cy) radius thickness c = emitOp (StrokeCircle cx cy radius thickness c)++-- | An anti-aliased straight line of the given thickness, with square ends.+{-# INLINE drawStrokeAA #-}+drawStrokeAA :: V2 -> V2 -> Float -> Color -> CanvasM ()+drawStrokeAA (V2 x0 y0) (V2 x1 y1) thickness c = emitOp (StrokeLineAA x0 y0 x1 y1 thickness c)++-- | Four-corner gradient fill (top-left, top-right, bottom-right,+-- bottom-left), blended over two triangles split from the top-left corner.+-- For a gradient along any line or over a path, use 'drawPathWith' with a+-- 'NanoUI.Path.Linear' paint.+{-# INLINE drawQuadGradient #-}+drawQuadGradient :: Rect -> Color -> Color -> Color -> Color -> CanvasM ()+drawQuadGradient r tl tr br bl = emitOp (FillQuadGradient r tl tr br bl)++-- | Horizontal 2-color linear gradient fill (left to right).+{-# INLINE drawLinearGradientH #-}+drawLinearGradientH :: Rect -> Color -> Color -> CanvasM ()+drawLinearGradientH r leftCol rightCol = emitOp (FillQuadGradient r leftCol rightCol rightCol leftCol)++-- | Vertical 2-color linear gradient fill (top to bottom).+{-# INLINE drawLinearGradientV #-}+drawLinearGradientV :: Rect -> Color -> Color -> CanvasM ()+drawLinearGradientV r topCol botCol = emitOp (FillQuadGradient r topCol topCol botCol botCol)++-- | Draw an image stretched over a rectangle, tinted. See 'drawImageWith'.+{-# INLINE drawImage #-}+drawImage :: Rect -> ImageId -> Color -> CanvasM ()+drawImage r iid c = drawImageWith (imageDraw r iid) {imageTint = c}++-- | Draw the region of an image from UV @(u0, v0)@ to @(u1, v1)@. See+-- 'drawImageWith'.+{-# INLINE drawImageUV #-}+drawImageUV :: Rect -> ImageId -> Float -> Float -> Float -> Float -> Color -> CanvasM ()+drawImageUV r iid u0 v0 u1 v1 c = drawImageWith (imageDraw r iid) {imageUV = Rect u0 v0 (u1 - u0) (v1 - v0), imageTint = c}++-- | Draw an image with a source region ('imageUV'), rotation about the+-- rect's centre ('imageAngle'), tint and opacity. Anything outside the+-- canvas is clipped, and a fully transparent image draws nothing:+--+-- > drawImageWith (imageDraw r photo) {imageAngle = pi / 8, imageOpacity = 0.6}+{-# INLINE drawImageWith #-}+drawImageWith :: ImageDraw -> CanvasM ()+drawImageWith = mapM_ emitOp . imageDrawOp++-- | Draw text in the context's font, anchored to a point by alignment:+-- 'AlignStart' puts the point at the text's left edge, 'AlignTop' at the+-- line's top, and 'AlignBaseline' on the baseline.+{-# INLINE drawText #-}+drawText :: V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()+drawText (V2 x y) alignX alignY txt col = emitOp (DrawText x y (alignXFraction alignX) (alignYFrac alignY) txt col)++-- | 'drawText' with an explicit font: size, variant (such as 'NanoUI.FontMono'),+-- weight, slant and decoration.+--+-- > drawTextWith defaultTextFont {textFontSize = 20, textFontWeight = WeightBold} (V2 cx cy) AlignCenter AlignMiddle "42" ink+--+-- Under a transform the point moves and the font scales by the square root+-- of the transform's area scale. Glyphs do not rotate.+{-# INLINE drawTextWith #-}+drawTextWith :: TextFont -> V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()+drawTextWith font (V2 x y) alignX alignY txt col = emitOp (DrawTextAligned x y (alignXFraction alignX) (alignYFrac alignY) 1 font txt col)++-- | Draw single-line text in the default font inside @r@, truncating with a+-- trailing ellipsis and clipping to @r@ when narrower than the text's width.+drawTextClipped :: Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()+drawTextClipped r alignX alignY txt col = do+  cdc <- drawContext+  drawTextClippedWith (cdcFont cdc) defaultTextFont EllipsisEnd r alignX alignY txt col++-- | Draw single-line text inside @r@ using explicit 'FontMetrics' (obtained+-- from 'NanoUI.resolveFontUi' or 'NanoUI.uiFontMetrics'), 'TextFont', and+-- 'TextEllipsis' mode. Truncates against @fm@ (applying tabular digit widths+-- when 'textFontTabular' is set) and clips to @r@.+drawTextClippedWith :: FontMetrics -> TextFont -> TextEllipsis -> Rect -> AlignX -> AlignY -> Text -> Color -> CanvasM ()+drawTextClippedWith fm0 font ell r@(Rect rx ry rw rh) alignX alignY txt col =+  when (rw > 0 && rh > 0 && not (T.null txt)) $ do+    let fm = if textFontTabular font then tabularFontMetrics fm0 else fm0+        cut = truncateTextPure ell fm rw txt+        ax = rx + rw * alignXFraction alignX+        ay = case alignY of+          AlignTop -> ry+          AlignMiddle -> ry + rh * 0.5+          AlignBottom -> ry + rh+          AlignBaseline -> ry + fmAscent fm+    when (not (T.null cut)) $+      withClip r (drawTextWith font (V2 ax ay) alignX alignY cut col)++-- | Anchor position up the line: 0 is the bottom, 1 the top, and a negative+-- value the baseline.+alignYFrac :: AlignY -> Float+alignYFrac = \case AlignTop -> 1; AlignMiddle -> 0.5; AlignBottom -> 0; AlignBaseline -> -1++-- | The checkbox widget's box, drawn in a square at the rect's top-left+-- sized to the rect's shorter side. Checked, it is the theme accent with a+-- check mark; unchecked, an input well with the button border. The widget+-- itself draws it 'NanoUI.Widgets.Custom.checkboxBoxSize' wide.+drawCheckbox :: Theme -> Rect -> Bool -> CanvasM ()+drawCheckbox theme (Rect x y w h) = checkboxOps emitOp theme (styleBorder (themeButton theme)) x y (min w h)++-- | Fill a "NanoUI.Path" path with a colour, using the+-- 'NanoUI.Path.NonZero' fill rule.+drawPath :: Path -> Color -> CanvasM ()+drawPath path col = drawPathWith NonZero path (Solid col)++-- | Fill a path with a fill rule and paint. Each subpath is closed, and+-- regions the rule leaves unfilled are holes. All edges, including hole+-- edges, are anti-aliased.+--+-- > drawPathWith P.EvenOdd (P.circle c 20 <> P.circle c 12) (P.Solid ink)  -- a ring+drawPathWith :: FillRule -> Path -> Paint -> CanvasM ()+drawPathWith rule path paint = emitWith (\t tol -> fillPathOps tol t rule path paint)++-- | Stroke a "NanoUI.Path" path with a width and colour, centred on the+-- path. Shorthand for 'drawStrokePathWith' with 'NanoUI.Path.stroke'.+drawStrokePath :: Path -> Float -> Color -> CanvasM ()+drawStrokePath path w col = drawStrokePathWith (stroke w) path (Solid col)++-- | Stroke a path, centred on it, with a 'NanoUI.Path.Stroke' (width, caps,+-- joins, dashes). Each subpath or dash is one anti-aliased shape, so a+-- translucent stroke does not darken where it overlaps itself at a corner+-- or cap.+--+-- > drawStrokePathWith (P.stroke 3) {P.strokeCap = P.RoundCap, P.strokeJoin = P.RoundJoin} path (P.Solid ink)+drawStrokePathWith :: Stroke -> Path -> Paint -> CanvasM ()+drawStrokePathWith st path paint = emitWith (\t tol -> strokePathOps tol t st path paint)++-- | Draw a block through a "NanoUI.Path" transform. Nested transforms+-- compose, with the inner one applied first.+-- @withTransform (P.translate 40 40 <> P.rotate a)@ rotates the block by+-- @a@ about the origin, then moves it 40 right and 40 down.+--+-- Paths are transformed before flattening, so scaled-up curves stay+-- smooth. Stroke widths, dashes and gradients scale with the transform (by+-- the square root of its area scale when x and y scale differently). Other+-- ops:+--+-- * Rects, rounded rects, circles and their outlines keep their own ops+--   while the transform preserves their shape, and otherwise become paths.+--   A rect rotated by other than quarter turns becomes a polygon; a circle+--   scaled on one axis becomes an ellipse.+-- * Lines and triangles transform their points. A four-corner gradient+--   rotates with its rect.+-- * Images rotate, scale and flip, but stay rectangular under a skew.+-- * Text moves its anchor point and scales its font. Glyphs do not rotate.+-- * A clip ('withClip') becomes the bounding box of its transformed rect.+withTransform :: Transform -> CanvasM a -> CanvasM a+withTransform t (CanvasM m) =+  CanvasM $ \env -> m (env {ceTransform = Just (maybe t (<> t) (ceTransform env))})++-- | Draw a block clipped to a rect, intersected with the current clip+-- (which is at most the widget's rect).+--+-- > withClip (Rect x y w 20) (drawText (V2 x y) AlignStart AlignTop longTitle ink)+withClip :: Rect -> CanvasM a -> CanvasM a+withClip r body = emitOp (PushClip r) *> body <* emitOp PopClip
+ lib/NanoUI/Internal/ChildWindow.hs view
@@ -0,0 +1,54 @@+-- | Further native windows, declared from a view as an overlay is: the+-- backend opens one for each declaration a frame makes and closes it when+-- the declarations stop.+module NanoUI.Internal.ChildWindow+  ( nativeWindow+  , ChildWindow (..)+  , childWindows+  , childView+  ) where++import Control.Monad (when)+import Data.IORef (modifyIORef', readIORef)+import NanoUI.Internal.Context.Types (ChildWindow (..), Context (..))+import NanoUI.Internal.Monad (NanoUI, askFrameInput, nextId, runNanoUI, withContext)+import NanoUI.Internal.NativeWindow.Types (WindowSettings)+import NanoUI.Internal.Var (readVar)+import NanoUI.Internal.Var.Types (Var)++-- | A separate native window running @body@ as its view, open while the+-- 'Var' holds 'True'. Call it unconditionally every frame, as for+-- 'NanoUI.modal': a frame that skips the call closes the window. The desktop's+-- close button, and 'NanoUI.quit' from @body@, write 'False'; with+-- 'NanoUI.wsExitOnCloseRequest' off, the close button sets+-- 'NanoUI.winCloseRequested' in @body@ instead.+--+-- The window has its own focus, widget state and positional 'NanoUI.useVar'+-- slots, and runs its own frames. It starts with this view's theme and the+-- settings, which take effect when it opens; set its title or theme later+-- from @body@ ('NanoUI.setWindowTitle', 'NanoUI.setTheme').+--+-- @body@ runs in the window's own frames. It may close over this view's+-- values: the window runs it again after each frame of this view. A 'Var'+-- either window writes shows in the other on its next frame. In an+-- emitting view (@NanoUI.Emit@), @body@ emits to the session's reducer.+-- There, to keep the open state in the model, pass a 'NanoUI.constVar',+-- turn 'NanoUI.wsExitOnCloseRequest' off, and emit a message from @body@+-- when 'NanoUI.winCloseRequested' is set.+--+-- The SDL and RGFW backends open the window; in tests nothing opens and+-- @body@ does not run.+nativeWindow :: Var Bool -> WindowSettings -> NanoUI () -> NanoUI ()+nativeWindow open settings body = do+  key <- nextId+  isOpen <- readVar open+  when isOpen $ withContext $ \ctx ->+    modifyIORef' (ctxChildWindows ctx) (ChildWindow key open settings (\c inp -> runNanoUI c inp body) :)++-- | The native windows the last view run declared open, in call order.+childWindows :: Context -> IO [ChildWindow]+childWindows ctx = reverse <$> readIORef (ctxChildWindows ctx)++-- | A declared window's view, to run as the view of its own frames.+childView :: ChildWindow -> NanoUI ()+childView child = askFrameInput >>= \inp -> withContext (\ctx -> childRun child ctx inp)
+ lib/NanoUI/Internal/Compact.hs view
@@ -0,0 +1,20 @@+-- | Store immutable, read-heavy host data in a GHC compact region to reduce GC scanning.+module NanoUI.Internal.Compact+  ( Compact+  , compactHost+  , askCompact+  ) where++import GHC.Compact (Compact, compact, getCompact)+import NanoUI.Internal.Host (Host, setHost)+import NanoUI.Internal.Monad (NanoUI, askHost)++-- | Copy data into a compact region and retain it in an explicit typed slot.+-- GHC's 'compact' restrictions apply: values containing functions or mutable+-- objects cannot be compacted. This is not an FFI buffer-pinning operation.+compactHost :: Host (Compact a) -> a -> IO (Compact a)+compactHost owner a = compact a >>= \region -> region <$ setHost owner region++-- | Read a compacted value from its typed owner, or 'Nothing' if uninstalled.+askCompact :: Host (Compact a) -> NanoUI (Maybe a)+askCompact owner = fmap getCompact <$> askHost owner
+ lib/NanoUI/Internal/Context.hs view
@@ -0,0 +1,995 @@+{-# LANGUAGE RecordWildCards #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | The 'Context' a view runs against, and the operations on its state:+-- focus, dirty flags and damage, the widget store, drawing and measure+-- caches, overlays, and host hooks. Backends and advanced widgets use this+-- module; views normally only need "NanoUI".+module NanoUI.Internal.Context+  ( Context (..)+  , withBackendSession+  , setBackendSession+  , backendSession+  , frameNumber+  -- Accessors, interaction, damage and wakes ("NanoUI.Internal.Context.Core")+  , getsInteraction+  , modifyInteraction+  , getsOverlay+  , modifyOverlay+  , getsDamage+  , modifyDamage+  -- Interaction+  , takeTextEditLastAction+  , pointerHeldOffLayers+  -- Damage+  , markDirty+  , recordLayoutRead+  , settleLayoutReads+  , clearDirty+  , isDirty+  , setWakeLoop+  , setWakeLoopChecked+  , wakeAction+  , wakeFromThread+  , takeWakes+  , takeThreadWake+  , requestWakeAt+  , requestWakeAfter+  , getWakeAt+  , clearWakeAt+  , takeDamage+  , takeDamagePieces+  , requestDamage+  , damageWidget+  , damageKey+  , damageRect+  , damagePeers+  , damageFull+  , traceDamage+  , getPrevRect+  , getPrevRectAt+  , pointerCovered+  , getPrevClipRect+  -- Store+  , getStore+  , setStore+  , modifyStore+  , writeSlots+  , publishLayoutSlots+  , writeSlot+  , adoptSlot+  , recordSlot+  , writeStoreBool+  , isDisabled+  , isInert+  -- Theme scopes+  , newThemeScopes+  , beginThemeScopes+  , pushThemeScope+  , themeScopesChanged+  , scopeTheme+  , scopeRawTheme+  , currentTheme+  , nodeTheme+  , widgetTheme+  -- Scroll offsets ("NanoUI.Internal.Context.Scroll")+  , getScrollOffset+  , setScrollOffset+  , getScrollOffset2D+  , setScrollOffset2D+  , linkScrollAxes+  -- Scroll tuning+  , ScrollTuning (..)+  , defaultScrollTuning+  , getScrollTuning+  , setScrollTuning+  , getScrollStep+  , setScrollStep+  , resolveScrollStep+  -- Scroll geometry+  , ScrollAxes (..)+  , ScrollMetrics (..)+  , getScrollMetrics+  , readScrollMetrics+  , cacheScrollMetrics+  , placeScrollContent+  , beginScrollMetrics+  , getScrollOffsetIn+  , setScrollOffsetIn+  , setScrollOffsetPending+  , applyPendingScrollOffset+  -- Scroll commands+  , ScrollBehavior (..)+  , ScrollAlign (..)+  , scrollTo+  , scrollBy+  , scrollPages+  , scrollToStart+  , scrollToEnd+  , scrollIntoView+  , scrollRectIntoView+  -- Scroll glide+  , applyScrollTarget+  , scrollTargetOffset+  , scrollGliding+  , clampScrollGlide+  , clampScrollOffset+  , stepScrollGlides+  -- Animations ("NanoUI.Internal.Context.Animation")+  , anyAnimating+  , liveAnimationKeys+  , isAnimatingKey+  , takeAnimSettled+  , lookupAnimation+  , startAnimation+  , startAnimationEase+  , startAnimationEaseDelay+  , startSpring+  , keepAnimationAlive+  , repaintIfOrphan+  , setAnimationValue+  , tickAnimations+  , getAnimationValue+  , getViewAnimationValue+  -- Popups, hover zones, drawing caches ("NanoUI.Internal.Context.Drawing")+  , registerPopupConfig+  , lookupPopupConfig+  , registerDropdownPopup+  , dropdownPopups+  , registerHoverZone+  , hoverZoneCrossed+  , registerDrawing+  , lookupDrawingAt+  , cachedDrawingOps+  , cachedWidgetLayout+  , lookupDrawFitEnvelope+  , pruneDrawOpCache+  , registerCustomDrawing+  , registerCustomEntry+  , lookupCustomDrawing+  , lookupCustomDrawingAt+  , customDrawingOffNode+  , cachedCustomDrawingOps+  , refreshCustomDrawingOps+  , drawingOpsStale+  , registerCustomMeasure+  , lookupCustomMeasure+  , lookupCustomMeasureAt+  , customMeasureHooks+  , lookupCustomDamageSlop+  , resetDrawingScopeCache+  , registerNodeShaderAt+  , lookupNodeShaderAt+  , registerShaderEffectAt+  , lookupShaderEffectAt+  , activeEffectNodes+  , getShaderCapabilities+  , setShaderCapabilities+  -- Overlays, modals and key routing ("NanoUI.Internal.Context.Overlay")+  , textInputEditActive+  , modalActive+  , overlayConsumesQuit+  , escapeReserved+  , markEscapeConsumed+  , markTabConsumed+  , tabConsumed+  , pointerBlockedByModal+  , routedInput+  , floatingLayerAt+  , beginModal+  , endModal+  , beginFrameModal+  , modalDamageFlip+  , takeKeyPress+  -- State records ("NanoUI.Internal.Context.Types"), images, fonts, theme,+  -- the layout overlay and host hooks+  , TextInputMenu (..)+  , TextInputDrag (..)+  , TextFieldClickCell (..)+  , WindowResizeEdge (..)+  , WindowResizeDrag (..)+  , DamageState (..)+  , PrevFrame (..)+  , emptyPrevFrame+  , PrevWalk (..)+  , PressPoint (..)+  , OverlayState (..)+  , DrawingCacheState (..)+  , NodeCustom (..)+  , DrawingEntry (..)+  , SpanCacheEntry (..)+  , SpanLines (..)+  , WidgetTextCacheEntry (..)+  , WidgetTextPlacement (..)+  , InteractionState (..)+  , PointerRoute (..)+  , FocusKind (..)+  , KeyClaim (..)+  , InputMethodRequest (..)+  , FocusRequest (..)+  , intKey+  , DamageRequest (..)+  , CustomMeasureFn+  , CustomDrawContext (..)+  , CustomDrawBuild+  , CustomDrawingEntry (..)+  , DropdownPopup (..)+  , atlasTextureId+  , registerImage+  , releaseImage+  , registerImages+  , lookupImageUv+  , lookupImageSize+  , withImageSlot+  , atlasSnapshot+  , atlasChanges+  , AtlasUpload (..)+  , withFontMetrics+  , withMonoFontMetrics+  , withFontSize+  , withMeasureText+  , withFontResolver+  , wrapMeasureCache+  , clearMeasureCache+  , cachedWrapText+  , ensureMetricCaches+  , withTheme+  , setTheme+  , getTheme+  , ExplainState (..)+  , DrawReuse (..)+  , DrawReuseKey (..)+  , ExplainedNode (..)+  , setExplainLayout+  , setDrawReuse+  , getExplainLayout+  , getExplainedNode+  , followSystemTheme+  , setThemeInView+  , settleViewTheme+  , setSystemAppearance+  , getSystemAppearance+  , withClipboard+  , enableMeasureCache+  , setHost+  , Host+  , newHost+  , withFramePaint+  , retainedFrameStale+  , setDrawSnapScale+  , setDrawPixelScale+  , setDrawSquareGeometry+  , setDrawExternalText+  , setDrawRecordOps+  , getDrawRecordOps+  , drawRecordedOps+  , RecordedOp (..)+  , askHostIO+  , hostOrInit+  -- Constructors+  , newContext+  , newPixelContext+  -- Focus+  , getFocusId+  , getFocusVisible+  , getHotId+  , registerFocusable+  , getFocusables+  , isFocusable+  , requestInputMethod+  , fieldComposition+  , AnimationState (..)+  , WidgetStore (..)+  , slotKey+  , Slot (..)+  , intBool+  , anySelectOpen+  , isSelectOpen+  , setSelectOpen+  , closeSelects+  , Ease (..)+  , Animation (..)+  , SpringParams (..)+  , presetBouncy+  , presetSmooth+  , presetStiff+  , applyEase+  , easeSameSpec+  , approxEq+  )+where++import Control.Monad (foldM, forM, unless, when)+import Data.Bits ((.&.))+import Data.ByteString (ByteString)+import NanoUI.Internal.Derived (emptyDerivedCache)+import NanoUI.Internal.Resource (Held (..), newHeld)+import Data.Primitive.Array (newArray)+import Data.Primitive.PrimVar (readPrimVar)+import NanoUI.Internal.Host (Host, newHost, setHost, clearHost, askHostIO, hostOrInit)+import Data.List (find)+import Control.Exception (bracket, finally)+import NanoUI.Internal.BackendSession (BackendSession, SBackend, SomeBackendSession (..), sessionFor)+import Data.Maybe (fromMaybe, isJust)+import Data.HashMap.Strict qualified as HashMap+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.Map.Strict qualified as Map+import Data.Primitive.PrimArray+  ( newPrimArray+  , readPrimArray+  , writePrimArray+  , getSizeofMutablePrimArray+  , resizeMutablePrimArray+  )+import Data.Primitive.PrimVar (newPrimVar, writePrimVar)+import Data.Text (Text)+import Data.Word (Word8)+import Foreign.ForeignPtr (ForeignPtr)++import NanoUI.Internal.Animation+import NanoUI.Internal.Atlas (AtlasUpload (..), atlasTextureId)+import NanoUI.Internal.Atlas qualified as Atlas+import NanoUI.Internal.Context.Animation+import NanoUI.Internal.Context.Core+import NanoUI.Internal.Context.Drawing+import NanoUI.Internal.Context.Overlay+import NanoUI.Internal.Context.Scroll+import NanoUI.Internal.Context.Types+import NanoUI.Internal.Draw (RecordedOp (..), newDrawArena)+import NanoUI.Internal.Draw qualified as Draw+import NanoUI.Internal.Font (FontMetrics, WrapResult (..), fmLineHeight, measureTextIO, monospaceMetrics, scaleFontMetrics, wrapTextIO)+import NanoUI.Internal.Frame.SpanArena (newSpanArena)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId, initialIdContext)+import NanoUI.Internal.Id.Cursor (newIdCursor)+import NanoUI.Internal.Input (Composition, Input (..), InputPurpose)+import NanoUI.Internal.Shader (ShaderCapabilities)+import NanoUI.Internal.Layout.Arena (getArenaScope, newNodeArena)+import NanoUI.Internal.Shader (noShaderCapabilities)+import NanoUI.Internal.Store+import NanoUI.Internal.Style (Appearance (..), FontStyle, FontVariant (..), FontWeight, Theme, defaultTheme)+import NanoUI.Internal.Types (ImageId, Rect, newZeroedPrimArray)+import NanoUI.Internal.Var.Cell (frameSlots, newStamps)++-- | Register tightly packed RGBA8 pixels under an image id. Width and height+-- are positive pixel counts. Returns 'False' for invalid data or atlas limits;+-- success requests a full repaint and wakes the loop. An id registered at+-- another size is rejected; release it first.+{-# INLINE registerImage #-}+registerImage :: Context -> ImageId -> Int -> Int -> ByteString -> IO Bool+registerImage ctx iid w h px = do+  ok <- Atlas.registerImage (ctxImageAtlas ctx) iid w h px+  -- New pixels under an id already on screen change no rect or text, and+  -- packing can move other images' texels, so nothing narrower is safe.+  when ok (damageFull ctx >> markDirty ctx)+  pure ok++-- | Remove an image from the atlas and free its space for later+-- registrations. Anything still using the id draws the unknown-image+-- placeholder. Releasing a registered image requests a full repaint and+-- wakes the loop, as registering one does.+{-# INLINE releaseImage #-}+releaseImage :: Context -> ImageId -> IO ()+releaseImage ctx iid = do+  released <- Atlas.releaseImage (ctxImageAtlas ctx) iid+  -- The id may still be on screen, drawn by a node whose rect is unchanged.+  when released (damageFull ctx >> markDirty ctx)++-- | Register every image and return whether all succeeded. Successful earlier+-- registrations remain in place if another image fails.+registerImages :: Foldable f => Context -> f (ImageId, Int, Int, ByteString) -> IO Bool+registerImages ctx =+  foldM (\ok (iid, w, h, px) -> (ok &&) <$> registerImage ctx iid w h px) True++-- | Current normalised atlas UV bounds, or 'Nothing' for an unknown image.+-- Atlas growth can change these coordinates; do not cache them across uploads.+{-# INLINE lookupImageUv #-}+lookupImageUv :: Context -> ImageId -> IO (Maybe (Float, Float, Float, Float))+lookupImageUv ctx = Atlas.lookupImageUv (ctxImageAtlas ctx)++-- | A registered image's size in pixels, or 'Nothing' if unknown.+{-# INLINE lookupImageSize #-}+lookupImageSize :: Context -> ImageId -> IO (Maybe (Int, Int))+lookupImageSize ctx = Atlas.lookupImageSize (ctxImageAtlas ctx)++-- | A registered image's size in pixels and atlas UV bounds, passed to @k@,+-- or @none@ if unknown ('Atlas.withImageSlot').+{-# INLINE withImageSlot #-}+withImageSlot :: Context -> ImageId -> IO r -> (Int -> Int -> Float -> Float -> Float -> Float -> IO r) -> IO r+withImageSlot ctx = Atlas.withImageSlot (ctxImageAtlas ctx)++-- | What a texture of the image atlas uploaded at generation @since@ (0 for+-- none) needs, with the atlas's size, pixels and generation.+{-# INLINE atlasChanges #-}+atlasChanges :: Context -> Int -> IO (Maybe (Int, Int, ForeignPtr Word8, Int, AtlasUpload))+atlasChanges ctx = Atlas.atlasChanges (ctxImageAtlas ctx)++-- | Atlas width, height, RGBA8 buffer, and revision for backend upload.+-- 'Nothing' until the first image is registered. Treat the buffer as+-- borrowed mutable storage and upload it before further image registration.+{-# INLINE atlasSnapshot #-}+atlasSnapshot :: Context -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))+atlasSnapshot ctx = Atlas.atlasSnapshot (ctxImageAtlas ctx)++-- | Metrics for a font variant scaled to line height @sz@, and the scale+-- factor applied (1 when @sz@ or the base line height is not positive).+{-# INLINE resolveScale #-}+resolveScale :: Context -> Float -> FontVariant -> (FontMetrics, Float)+resolveScale ctx sz var =+  let baseFm = if var == FontMono then ctxMonoFontMetrics ctx else ctxFontMetrics ctx+      scale =+        if sz > 0 && fmLineHeight baseFm > 0+          then sz / fmLineHeight baseFm+          else 1.0+   in (if scale /= 1.0 then scaleFontMetrics scale baseFm else baseFm, scale)++defaultResolveFont :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)+defaultResolveFont ctx sz _w _st var = pure (fst (resolveScale ctx sz var), False)++defaultResolveMeasure :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)+defaultResolveMeasure ctx sz _w _st var txt+  | var == FontMono = measureTextIO textFm txt+  | scale /= 1.0 = (\(w, h) -> (w * scale, h * scale)) <$> ctxMeasureText ctx txt+  | otherwise = ctxMeasureText ctx txt+  where+    (textFm, scale) = resolveScale ctx sz var++-- | Return a context with size/weight/style/variant font and measurement+-- callbacks. Use the returned context for later frames; shared text caches+-- are invalidated at the next frame boundary.+{-# INLINE withFontResolver #-}+withFontResolver ::+  Context ->+  (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) ->+  (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) ->+  Context+withFontResolver ctx rf rm = trackMetricSource ctx {ctxResolveFont = rf, ctxResolveMeasure = rm}++-- | Replace base metrics and rebuild default measurement/resolution callbacks.+-- These replace any installed with 'withFontResolver', and the measurement is+-- uncached ('enableMeasureCache').+-- Returns a configured context sharing the original session state. The+-- default resolver treats a font size as a line height, so the default size+-- becomes the metrics' line height ('withFontSize').+withFontMetrics :: Context -> FontMetrics -> Context+withFontMetrics ctx fm =+  withDefaultResolvers ctx {ctxFontMetrics = fm, ctxMeasureText = measureTextIO fm, ctxFontSize = fmLineHeight fm}++-- | Set the default text size, in the font resolver's units. Backends whose+-- base font size differs from its line height call this.+withFontSize :: Context -> Float -> Context+withFontSize ctx size = trackMetricSource ctx {ctxFontSize = size}++-- | Replace monospace metrics and rebuild default font-resolution callbacks.+withMonoFontMetrics :: Context -> FontMetrics -> Context+withMonoFontMetrics ctx mono = withDefaultResolvers ctx {ctxMonoFontMetrics = mono}++-- | Rebuild the default font and measurement resolvers over @ctx@'s metrics.+withDefaultResolvers :: Context -> Context+withDefaultResolvers ctx =+  trackMetricSource ctx+    { ctxResolveFont = defaultResolveFont ctx+    , ctxResolveMeasure = defaultResolveMeasure ctx+    }++-- | Replace proportional text measurement, returning logical width/height.+-- The callback must agree with the font used for painting. Sized, bold and+-- italic text goes back to the default measurement, scaled from this one,+-- while a 'withFontResolver' font resolver stays: install that after this.+withMeasureText :: Context -> (Text -> IO (Float, Float)) -> Context+withMeasureText ctx fn =+  let ctx' = ctx {ctxMeasureText = fn}+   in trackMetricSource ctx'+        { ctxResolveMeasure = defaultResolveMeasure ctx'+        }++-- Keep the identity boxed. No structural callback comparison or unsafe pure+-- mutation is needed, and repeated frames with the same Context do no work.+trackMetricSource :: Context -> Context+trackMetricSource ctx =+  ctx {ctxMetricSource = MetricSource+    (ctxFontMetrics ctx) (ctxMonoFontMetrics ctx) (ctxMeasureText ctx)+    (ctxResolveFont ctx) (ctxResolveMeasure ctx)}++-- | Called once before building a frame. Context configuration remains pure;+-- cache invalidation happens at the IO boundary, including when alternating+-- between differently configured Contexts that share their backing stores.+ensureMetricCaches :: Context -> IO ()+ensureMetricCaches ctx = do+  -- Compare evaluated identities: passed unevaluated, the selector application+  -- is a fresh thunk without optimisation, so the check would miss every+  -- frame and force full damage with cleared caches.+  let !current = ctxMetricSource ctx+  previous <- readIORef (ctxLastMetricSource ctx)+  case previous of+    Just source | ptrEq source current -> pure ()+    _ -> do+      clearMeasureCache ctx+      damageFull ctx+      markDirty ctx++cacheMeasureText ::+  IORef MeasureCache ->+  Float ->+  (Text -> IO (Float, Float)) ->+  Text ->+  IO (Float, Float)+cacheMeasureText ref scale base txt = cachedGen measureCacheCap (const 1) ref (txt, scale) (base txt)++-- | Measurements per generation of the measure cache.+measureCacheCap :: Int+measureCacheCap = 4096++-- | 'wrapTextIO' through the context's wrap cache ('ctxWrapCache'). @font@+-- names the font @lineW@ measures in ('NanoUI.Internal.WidgetText.textNodeFontKey').+-- Caches the last few wrapped widths per text along with the width range+-- each result holds for, so wrapping again at a width with the same line+-- breaks (e.g. while dragging a window or pane edge) skips measurement,+-- and the layout solve and text spans share one wrap. A change of font metrics+-- ('ctxMetricGen') clears the cache.+cachedWrapText :: Context -> Int -> (Text -> IO Float) -> Text -> Float -> IO WrapResult+cachedWrapText ctx font lineW txt maxW+  | maxW <= 0 = wrapTextIO lineW txt maxW+  | otherwise = do+      gen <- readIORef (ctxMetricGen ctx)+      WrapCache wrapGen cache0 <- readIORef (ctxWrapCache ctx)+      let key = (txt, font)+          holds r = wrFitW r <= maxW && maxW < wrBreakW r+          cache@(GenCache young _ old)+            | wrapGen == gen = cache0+            | otherwise = emptyGenCache+          mine = HashMap.lookup key young+      case mine >>= find holds of+        Just r -> pure r+        Nothing -> do+          -- A hit in the old generation moves up to the young one.+          r <- maybe (wrapTextIO lineW txt maxW) pure (HashMap.lookup key old >>= find holds)+          let entries = r : take (wrapsPerText - 1) (fromMaybe [] mine)+          writeIORef (ctxWrapCache ctx) $!+            WrapCache gen (insertGen wrapCacheCap (if isJust mine then 0 else 1) key entries cache)+          pure r++-- | Texts per generation of the wrap cache.+wrapCacheCap :: Int+wrapCacheCap = 1024++-- | Widths the wrap cache keeps for one text.+wrapsPerText :: Int+wrapsPerText = 8++-- | Install measurement under a scale-specific cache key when caching is+-- enabled. Otherwise install the callback directly.+wrapMeasureCache :: Float -> Context -> (Text -> IO (Float, Float)) -> Context+wrapMeasureCache scale ctx measure =+  withMeasureText ctx $+    case ctxMeasureCache ctx of+      Nothing -> measure+      Just ref -> cacheMeasureText ref scale measure++-- | Drop text span, widget text and whole-layout caches and bump the metric+-- generation, for changes that alter how text lays out.+invalidateTextCaches :: Context -> IO ()+invalidateTextCaches ctx = do+  writeIORef (ctxSpanCache ctx) IM.empty+  writeIORef (ctxWidgetTextCache ctx) IM.empty+  writeIORef (ctxDerivedCache ctx) emptyDerivedCache+  writeIORef (ctxLayoutCache ctx) Nothing+  modifyIORef' (ctxMetricGen ctx) (+ 1)++-- | Clear measurement, text-placement, and whole-layout caches and advance the+-- metric generation. Does not itself request a repaint or wake the loop.+clearMeasureCache :: Context -> IO ()+clearMeasureCache ctx = do+  -- Store the evaluated source so 'ensureMetricCaches' can match its identity.+  let !source = ctxMetricSource ctx+  writeIORef (ctxLastMetricSource ctx) (Just source)+  invalidateTextCaches ctx+  mapM_ (`writeIORef` emptyGenCache) (ctxMeasureCache ctx)++-- | Apply 'setTheme' and return the same context for configuration pipelines.+withTheme :: Context -> Theme -> IO Context+withTheme ctx theme = ctx <$ setTheme ctx theme++-- | Set a fixed base theme, invalidate text/layout caches, and request a+-- full repaint. Setting the same theme is a no-op. Stops+-- 'followSystemTheme'.+setTheme :: Context -> Theme -> IO ()+setTheme ctx th = do+  writeIORef (ctxThemeFor ctx) Nothing+  applyBaseTheme ctx th++-- | 'setTheme' without leaving 'followSystemTheme'.+applyBaseTheme :: Context -> Theme -> IO ()+applyBaseTheme ctx th = do+  cur <- readIORef (ctxTheme ctx)+  when (cur /= th) $ do+    writeIORef (ctxTheme ctx) th+    repaintForTheme ctx++-- | Drop text caches, repaint the whole window and request a frame.+repaintForTheme :: Context -> IO ()+repaintForTheme ctx = do+  invalidateTextCaches ctx+  damageFull ctx+  markDirty ctx++-- | 'setTheme' from a view. The new theme is visible immediately, but the+-- repaint waits until the view is built ('settleViewTheme') and happens only+-- if the frame ends on a different theme than it began with. A view can set+-- the theme every frame, even twice, without repainting.+setThemeInView :: Context -> Theme -> IO ()+setThemeInView ctx th = do+  writeIORef (ctxThemeFor ctx) Nothing+  writeIORef (ctxTheme ctx) th++-- | Repaint if a view changed the base theme ('setThemeInView') this frame.+settleViewTheme :: Context -> Theme -> IO ()+settleViewTheme ctx before = do+  now <- readIORef (ctxTheme ctx)+  when (now /= before) (repaintForTheme ctx)++-- | Base session theme. Use 'currentTheme' to include the current paint scope.+getTheme :: Context -> IO Theme+getTheme ctx = readIORef (ctxTheme ctx)++-- | Whether a full frame with no damage, built from the same view output+-- as the last, takes the last frame's draw data instead of painting again+-- (on by default). A benchmark that times paint on a still scene turns it+-- off.+setDrawReuse :: Context -> Bool -> IO ()+setDrawReuse ctx on = writeIORef (ctxDrawReuse ctx) (DrawReuse on Nothing)++-- | Set the shader capabilities supported by the active backend. When the+-- capabilities change, invalidate cached draw reuse and force a full repaint.+setShaderCapabilities :: Context -> ShaderCapabilities -> IO ()+setShaderCapabilities ctx caps = do+  cur <- readIORef (ctxShaderCaps ctx)+  when (cur /= caps) $ do+    writeIORef (ctxShaderCaps ctx) caps+    modifyIORef' (ctxDrawReuse ctx) (\dr -> dr {drLast = Nothing})+    damageFull ctx+    markDirty ctx++-- | Toggle the layout overlay ("NanoUI.Internal.Frame.Explain"): a one-pixel+-- outline inside every layout node, coloured by depth, and a tint on the+-- hovered node. A change repaints the window and wakes the loop.+setExplainLayout :: Context -> Bool -> IO ()+setExplainLayout ctx on = do+  cur <- getExplainLayout ctx+  when (cur /= on) $ do+    writeIORef (ctxExplain ctx) initialExplainState {esOn = on}+    damageFull ctx+    markDirty ctx++-- | Whether the layout overlay is on ('setExplainLayout').+{-# INLINE getExplainLayout #-}+getExplainLayout :: Context -> IO Bool+getExplainLayout ctx = esOn <$> readIORef (ctxExplain ctx)++-- | The node under the pointer at the end of the last frame, while the layout+-- overlay is on. 'Nothing' when it is off or no node is hovered.+getExplainedNode :: Context -> IO (Maybe ExplainedNode)+getExplainedNode ctx = fmap fst . esHover <$> readIORef (ctxExplain ctx)++-- | Derive the base theme from the system appearance ('Nothing' when the+-- backend cannot tell), e.g. with @'NanoUI.lightDark' light+-- dark@. Applies now and on every 'setSystemAppearance' change, until+-- 'setTheme' sets a fixed theme. A view can instead pick the theme itself+-- each frame:+--+-- > setTheme . lightDark defaultLightTheme defaultTheme =<< systemAppearance+followSystemTheme :: Context -> (Maybe Appearance -> Theme) -> IO ()+followSystemTheme ctx pick = do+  writeIORef (ctxThemeFor ctx) (Just pick)+  applyBaseTheme ctx . pick =<< readIORef (ctxSystemAppearance ctx)++-- | Record the system's light or dark preference ('Nothing' if unknown).+-- Backends call this on the UI thread; SDL reports at startup and on change,+-- RGFW does not report it. A change repaints the window, wakes the loop, and+-- updates a theme set by 'followSystemTheme'. The same value again is a no-op.+setSystemAppearance :: Context -> Maybe Appearance -> IO ()+setSystemAppearance ctx appearance = do+  cur <- readIORef (ctxSystemAppearance ctx)+  when (cur /= appearance) $ do+    writeIORef (ctxSystemAppearance ctx) appearance+    readIORef (ctxThemeFor ctx) >>= mapM_ (\pick -> applyBaseTheme ctx (pick appearance))+    -- Repaint even without followSystemTheme: views may read the appearance.+    damageFull ctx+    markDirty ctx++-- | The system appearance the backend last reported.+getSystemAppearance :: Context -> IO (Maybe Appearance)+getSystemAppearance ctx = readIORef (ctxSystemAppearance ctx)++-- | Install clipboard read/write callbacks. 'Nothing' means no text is+-- available; a write returns 'False' when refused or unsupported.+withClipboard :: Context -> IO (Maybe Text) -> (Text -> IO Bool) -> Context+withClipboard ctx getter setter = ctx {ctxClipboardGet = getter, ctxClipboardSet = setter}++-- | Enable memoised text measurement, or return an already cached context.+-- Use the returned context for subsequent frames. It wraps the measurement+-- installed so far, which a later 'withFontMetrics' or 'withMeasureText'+-- replaces with an uncached one; a context that has a cache already (from+-- 'newPixelContext') is returned unchanged, so install measurement on it+-- with 'wrapMeasureCache'.+enableMeasureCache :: Context -> IO Context+enableMeasureCache ctx =+  case ctxMeasureCache ctx of+    Just _ -> pure ctx+    Nothing -> do+      ref <- newIORef emptyGenCache+      let ctx' = ctx {ctxMeasureCache = Just ref, ctxMeasureText = cacheMeasureText ref 0 (ctxMeasureText ctx)}+      pure (trackMetricSource ctx' {ctxResolveMeasure = defaultResolveMeasure ctx'})++-- | Run a frame's UI pass for a host that draws it whole when @paintFull@+-- holds ('ctxPaintFull'), and repaints the whole window, whatever the+-- frame's damage, when @presentFull@ holds. A frame presented whole works+-- out no damage ('ctxDamageWanted' is off for its pass), since the host+-- would not read it. The context wants damage again after the pass, even+-- one that throws, so frames run outside a draw still work it out.+{-# INLINE withFramePaint #-}+withFramePaint :: Context -> Bool -> Bool -> IO a -> IO a+withFramePaint ctx paintFull presentFull pass = do+  writeIORef (ctxPaintFull ctx) paintFull+  writeIORef (ctxDamageWanted ctx) (not presentFull)+  pass `finally` writeIORef (ctxDamageWanted ctx) True++-- | Whether a host that keeps its last presented frame must paint this one+-- whole: the caller forces it, the window asked to be redrawn+-- ('inputWindowRedraw'), or the kept frame's pixel width, height and scale+-- (@presented@) differ from this frame's (@current@), so it holds nothing+-- this frame can keep.+{-# INLINE retainedFrameStale #-}+retainedFrameStale :: Bool -> Input -> (Int, Int, Float) -> (Int, Int, Float) -> Bool+retainedFrameStale force inp presented current = force || inputWindowRedraw inp || presented /= current++-- | Set the device pixel scale used to snap geometry origins/endpoints to+-- whole pixels. The SDL backend calls this when the window pixel density is synced.+{-# INLINE setDrawSnapScale #-}+setDrawSnapScale :: Context -> Float -> IO ()+setDrawSnapScale ctx s = Draw.setDrawSnapScale (ctxDrawArena ctx) s++-- | Set the device pixel scale forwarded to shaders (@uMeta.x@) without+-- enabling pixel-grid snapping.+{-# INLINE setDrawPixelScale #-}+setDrawPixelScale :: Context -> Float -> IO ()+setDrawPixelScale ctx s = Draw.setDrawPixelScale (ctxDrawArena ctx) s++-- | Emit rounded shapes and AA strokes as flat, axis-aligned fills. Software+-- framebuffer hosts enable this so every primitive is a solid quad.+{-# INLINE setDrawSquareGeometry #-}+setDrawSquareGeometry :: Context -> Bool -> IO ()+setDrawSquareGeometry ctx = Draw.setDrawSquareGeometry (ctxDrawArena ctx)++-- | Skip text quads in the draw buffer. Hosts that rasterize text from the+-- collected text spans enable this; drawing text ops are then returned by+-- 'NanoUI.Internal.Frame.Spans.collectRasterSpans' instead of drawn as quads.+{-# INLINE setDrawExternalText #-}+setDrawExternalText :: Context -> Bool -> IO ()+setDrawExternalText ctx = Draw.setDrawExternalText (ctxDrawArena ctx)++-- | Record the shapes and images each paint draws, as ops, for exporters that+-- redraw a frame as vectors ('drawRecordedOps').+{-# INLINE setDrawRecordOps #-}+setDrawRecordOps :: Context -> Bool -> IO ()+setDrawRecordOps ctx = Draw.setDrawRecordOps (ctxDrawArena ctx)++-- | Whether 'setDrawRecordOps' is on.+{-# INLINE getDrawRecordOps #-}+getDrawRecordOps :: Context -> IO Bool+getDrawRecordOps ctx = Draw.getDrawRecordOps (ctxDrawArena ctx)++-- | The shapes and images the last paint drew while 'setDrawRecordOps' was on, in+-- paint order, each with its layer and clip.+drawRecordedOps :: Context -> IO [RecordedOp]+drawRecordedOps ctx = Draw.recordedOps (ctxDrawArena ctx)++-- =============================================================================+-- Constructors+-- =============================================================================++-- | Fresh headless context with default theme, 12-unit monospace metrics,+-- empty state, and no native clipboard or wake callbacks. Backends configure+-- it before the first frame; each independent session needs its own context.+newContext :: IO Context+newContext = do+  nodeArena <- newNodeArena+  drawArena <- newDrawArena+  ctxHotId <- newIORef (WidgetId 0)+  ctxLastHotId <- newIORef (WidgetId 0)+  ctxPointerReach <- newIORef Nothing+  ctxActiveId <- newIORef (WidgetId 0)+  ctxClickedId <- newIORef (WidgetId 0)+  ctxPressPos <- newIORef Map.empty+  ctxFocusId <- newIORef (WidgetId 0)+  ctxFocusVisible <- newIORef False+  ctxFocusRequest <- newIORef Nothing+  ctxInputMethod <- newIORef Nothing+  ctxStore <- newIORef emptyWidgetStore+  ctxDamageState <- newIORef initialDamageState+  ctxPrevWalk <- newIORef =<< newPrevWalk 0+  ctxStoreOwners <- newIORef IM.empty+  ctxOverlayState <- newIORef initialOverlayState+  ctxAnimationState <- newIORef initialAnimationState+  ctxScrollState <- newIORef initialScrollState+  ctxDrawingCache <- newIORef initialDrawingCacheState+  ctxNodeCustom <- newIORef =<< newArray 64 noNodeCustom+  ctxCustomPass <- newZeroedPrimArray customPassWords+  ctxIdCursor <- newIdCursor initialIdContext+  ctxVarFrame <- newStamps frameSlots+  ctxVarSlots <- newIORef IM.empty+  ctxContainerStack <- newContainerStack+  ctxFocusables <- newIORef =<< newPrimArray 64+  ctxFocusablesCount <- newPrimVar 0+  ctxSpanBase <- newSpanArena+  ctxSpanOverlay <- newSpanArena+  ctxInteractionState <- newIORef initialInteractionState+  ctxCursorZones <- newIORef []+  ctxCursorRegions <- newIORef []+  ctxImageAtlas <- Atlas.newImageAtlas+  ctxWakeLoop <- newIORef Nothing+  ctxWoken <- newIORef False+  ctxWakePending <- newIORef False+  ctxLoopThread <- newIORef Nothing+  ctxWakeAt <- newIORef 0+  ctxChildWindows <- newIORef []+  ctxShaderCaps <- newIORef noShaderCapabilities+  ctxEffectNodes <- newIORef (0, [])+  ctxTheme <- newIORef defaultTheme+  ctxThemeScopes <- newIORef =<< newThemeScopes+  ctxSystemAppearance <- newIORef Nothing+  ctxThemeFor <- newIORef Nothing+  ctxSpanCache <- newIORef IM.empty+  ctxWidgetTextCache <- newIORef IM.empty+  ctxDerivedCache <- newIORef emptyDerivedCache+  ctxHeld <- newHeld+  ctxNativeWindow <- newHost+  ctxBackendSession <- newHost+  ctxSensors <- newHost+  ctxParagraphs <- newHost+  ctxSvgRasters <- newIORef Map.empty+  ctxLayoutCache <- newIORef Nothing+  ctxMetricGen <- newIORef 0+  ctxWrapCache <- newIORef (WrapCache 0 emptyGenCache)+  ctxLastMetricSource <- newIORef Nothing+  ctxPaintFull <- newIORef True+  ctxDrawReuse <- newIORef (DrawReuse True Nothing)+  ctxDamageWanted <- newIORef True+  ctxExplain <- newIORef initialExplainState+  -- References above use their field names; font-dependent defaults stay+  -- explicit, including the resolvers that close over this context.+  let fm0 = monospaceMetrics 12+      ctx = Context+        { ctxNodeArena = nodeArena+        , ctxDrawArena = drawArena+        , ctxFontMetrics = fm0+        , ctxMonoFontMetrics = fm0+        , ctxFontSize = fmLineHeight fm0+        , ctxMeasureText = measureTextIO fm0+        , ctxResolveFont = defaultResolveFont ctx+        , ctxResolveMeasure = defaultResolveMeasure ctx+        , ctxMeasureCache = Nothing+        , ctxMetricSource = InitialMetricSource+        , ctxClipboardGet = pure Nothing+        , ctxClipboardSet = \_ -> pure False+        , ..+        }+  pure ctx++-- | Headless context with 16-unit monospace metrics, a measure cache for+-- 'wrapMeasureCache' to install measurement through (the monospace+-- measurement itself is not cached), and the default theme: for tests, and+-- the starting point of pixel-based hosts.+newPixelContext :: IO Context+newPixelContext = do+  ctx <- enableMeasureCache =<< newContext+  pure (withFontMetrics ctx (monospaceMetrics 16))++-- =============================================================================+-- Focus+-- =============================================================================++-- | Keyboard-focused widget, or @WidgetId 0@ when none has focus.+{-# INLINE getFocusId #-}+getFocusId :: Context -> IO WidgetId+getFocusId ctx = readIORef (ctxFocusId ctx)++-- | Whether the focused widget shows its focus ring: focus moved by keyboard+-- since the last pointer press.+{-# INLINE getFocusVisible #-}+getFocusVisible :: Context -> IO Bool+getFocusVisible ctx = readIORef (ctxFocusVisible ctx)++-- | Hovered widget selected by the frame, or @WidgetId 0@ for none.+{-# INLINE getHotId #-}+getHotId :: Context -> IO WidgetId+getHotId ctx = readIORef (ctxHotId ctx)++-- | Add @wid@ to this frame's keyboard focus order, unless it is declared in a+-- disabled or display-only scope.+registerFocusable :: Context -> WidgetId -> IO ()+registerFocusable ctx wid = do+  scope <- getArenaScope (ctxNodeArena ctx)+  when (scope .&. 3 == 0) $ do+    idx <- readPrimVar (ctxFocusablesCount ctx)+    arr <- readIORef (ctxFocusables ctx)+    cap <- getSizeofMutablePrimArray arr+    arr' <-+      if idx >= cap+        then do+          grown <- resizeMutablePrimArray arr (max 16 (cap * 2))+          writeIORef (ctxFocusables ctx) grown+          pure grown+        else pure arr+    writePrimArray arr' idx wid+    writePrimVar (ctxFocusablesCount ctx) (idx + 1)++-- | Enable the input method this frame for the focused widget @wid@, with its+-- caret in window coordinates ('Nothing' for a text field; the frame finds+-- its caret) and the input purpose. Next frame @wid@ gets the composition+-- ('fieldComposition'); backends read the text area from+-- 'NanoUI.Internal.Frame.TextArea.textInputArea'. With no request the input+-- method stays off; the last request of a build wins.+requestInputMethod :: Context -> WidgetId -> Maybe Rect -> InputPurpose -> IO ()+requestInputMethod ctx wid caret purpose = do+  inert <- isInert ctx wid+  disabled <- isDisabled ctx wid+  unless (inert || disabled) $+    writeIORef (ctxInputMethod ctx) $! Just (InputMethodRequest wid caret purpose)++-- | The frame's composition, if @wid@ has focus and owns it+-- ('NanoUI.Internal.Frame.TextInput.claimComposition').+fieldComposition :: Context -> WidgetId -> IO (Maybe Composition)+fieldComposition ctx wid = do+  focus <- readIORef (ctxFocusId ctx)+  getsInteraction ctx $ \s -> case isComposition s of+    Just (c, owner) | owner == wid && owner == focus && hashWidgetId owner /= 0 -> Just c+    _ -> Nothing++-- | Copy this frame's registered focus ids in declaration order. Modal+-- filtering is applied separately when moving focus.+{-# INLINE getFocusables #-}+getFocusables :: Context -> IO [WidgetId]+getFocusables ctx = do+  count <- readPrimVar (ctxFocusablesCount ctx)+  arr <- readIORef (ctxFocusables ctx)+  forM [0 .. count - 1] (readPrimArray arr)++-- | Whether @wid@ registered as focusable this frame ('registerFocusable'),+-- without copying the list.+isFocusable :: Context -> WidgetId -> IO Bool+isFocusable ctx wid = do+  count <- readPrimVar (ctxFocusablesCount ctx)+  arr <- readIORef (ctxFocusables ctx)+  let go i+        | i >= count = pure False+        | otherwise = readPrimArray arr i >>= \w -> if w == wid then pure True else go (i + 1)+  go 0++-- | Run a backend's session with its value installed on the context, where+-- the backend's view-side operations find it ('backendSession'). Every copy+-- of the context shares it, and a separate context has its own. Restores the+-- previous value on exit, including on exception.+withBackendSession :: Context -> SBackend b -> BackendSession b -> IO a -> IO a+withBackendSession ctx backend session act =+  bracket+    (askHostIO slot <* setHost slot (SomeBackendSession backend session))+    (maybe (clearHost slot) (setHost slot))+    (const act)+  where+    slot = ctxBackendSession ctx++-- | 'withBackendSession' for a session that ends with its context rather+-- than a scope, such as a further window's.+setBackendSession :: Context -> SBackend b -> BackendSession b -> IO ()+setBackendSession ctx backend session = setHost (ctxBackendSession ctx) (SomeBackendSession backend session)++-- | The session value of the backend driving this context, if it is the+-- backend asked for.+backendSession :: SBackend b -> Context -> IO (Maybe (BackendSession b))+backendSession backend ctx = (>>= sessionFor backend) <$> askHostIO (ctxBackendSession ctx)++-- | Current frame number: advances once per frame and is shared across passes+-- within the same frame.+frameNumber :: Context -> IO Int+frameNumber = readPrimVar . heldFrame . ctxHeld
+ lib/NanoUI/Internal/Context/Animation.hs view
@@ -0,0 +1,306 @@+-- | Per-widget animations: starting, ticking, settling and reading values.+module NanoUI.Internal.Context.Animation+  ( anyAnimating+  , liveAnimationKeys+  , isAnimatingKey+  , takeAnimSettled+  , lookupAnimation+  , startAnimation+  , startAnimationEase+  , startAnimationEaseDelay+  , startSpring+  , keepAnimationAlive+  , repaintIfOrphan+  , setAnimationValue+  , tickAnimations+  , getAnimationValue+  , getViewAnimationValue+  ) where++import Control.Monad (unless, when)+import Data.IORef (modifyIORef', readIORef, writeIORef)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.IntSet (IntSet)+import Data.IntSet qualified as IS++import NanoUI.Internal.Animation+import NanoUI.Internal.Context.Core (damageFull, damageKey, getsDamage, markDirty)+import NanoUI.Internal.Context.Types (AnimationState (..), Context (..), DamageState (..), PrevFrame (..), ScrollState (..), intKey)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena (getNodeRect, lookupNodeByKey)+import NanoUI.Internal.Types (DamageBounds (..), Rect, defaultDamageSlop, finite, rectNonEmpty)++-- | Whether the frame loop has to keep drawing: an animation is running, a+-- keep-alive lease is active, or a scroller is still gliding onto its target.+{-# INLINE anyAnimating #-}+anyAnimating :: Context -> IO Bool+anyAnimating ctx = do+  as <- readIORef (ctxAnimationState ctx)+  if not (IM.null (asAnimations as)) || not (IS.null (asKeepAlive as)) || not (IS.null (asKeepTouched as))+    then pure True+    else not . IM.null . ssGlides <$> readIORef (ctxScrollState ctx)++-- | Keys with a running animation or an active keep-alive lease.+{-# INLINE liveAnimationKeys #-}+liveAnimationKeys :: Context -> IO IntSet+liveAnimationKeys ctx = do+  as <- readIORef (ctxAnimationState ctx)+  pure (IM.keysSet (asAnimations as) <> asKeepAlive as <> asKeepTouched as)++-- | Whether @wid@ has a running animation or an active keep-alive lease.+{-# INLINE isAnimatingKey #-}+isAnimatingKey :: Context -> WidgetId -> IO Bool+isAnimatingKey ctx wid = do+  let k = intKey wid+  as <- readIORef (ctxAnimationState ctx)+  pure (IM.member k (asAnimations as) || IS.member k (asKeepAlive as) || IS.member k (asKeepTouched as))++-- | Read and clear the flag indicating an animation settled during the last tick.+takeAnimSettled :: Context -> IO Bool+takeAnimSettled ctx = do+  as <- readIORef (ctxAnimationState ctx)+  if asAnimSettled as+    then do+      writeIORef (ctxAnimationState ctx) $! as {asAnimSettled = False}+      pure True+    else pure False++-- | Running animation for an id, or 'Nothing'. Settled values are stored separately.+{-# INLINE lookupAnimation #-}+lookupAnimation :: Context -> WidgetId -> IO (Maybe Animation)+lookupAnimation ctx wid = IM.lookup (intKey wid) . asAnimations <$> readIORef (ctxAnimationState ctx)++-- | Linear tween from start to end over a duration in seconds. A matching+-- request preserves progress; non-positive duration settles immediately.+{-# INLINE startAnimation #-}+startAnimation :: Context -> WidgetId -> Float -> Float -> Float -> IO ()+startAnimation ctx wid start end dur = startAnimationEase ctx wid start end dur EaseLinear++-- | 'startAnimation' with a chosen easing curve and no delay.+{-# INLINE startAnimationEase #-}+startAnimationEase :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> IO ()+startAnimationEase ctx wid start end dur ease = startAnimationEaseDelay ctx wid start end dur ease 0++-- | Tween with start, end, duration, curve, and delay. Times use seconds;+-- negative delay is treated as zero. Matching requests do not restart it.+startAnimationEaseDelay :: Context -> WidgetId -> Float -> Float -> Float -> Ease -> Float -> IO ()+startAnimationEaseDelay ctx wid start end dur ease delay+  -- A NaN or infinite end/duration/delay would restart or run forever and+  -- never let the loop idle; ignore non-finite targets/durations.+  | not (finite end) || not (finite dur) || not (finite delay) = pure ()+  | not (finite start) || dur <= 0 || approxEq start end = settleKey ctx key end+  | otherwise = do+      as <- readIORef (ctxAnimationState ctx)+      let req = max 0 delay+      case IM.lookup key (asAnimations as) of+        Just a@(EaseAnim aStart _ _ _ _ _ _) | approxEq aStart start && easeSameSpec a ease dur req end -> pure ()+        _ ->+          writeIORef (ctxAnimationState ctx) $! insertRunning key (EaseAnim start end dur 0 ease req req) as+      repaintIfOrphan ctx key+  where+    key = intKey wid++-- | Advance a spring toward a target. Keeps the position and velocity of a+-- running spring; otherwise starts from the settled value or zero.+startSpring :: Context -> WidgetId -> SpringParams -> Float -> IO ()+startSpring ctx wid params target+  -- A non-finite target would leave the spring NaN for good.+  | not (finite target) = pure ()+  -- Non-positive or non-finite stiffness/damping would oscillate or diverge+  -- forever and prevent idling; settle at target immediately.+  | not (finite (springStiffness params))+      || not (finite (springDamping params))+      || springStiffness params <= 0+      || springDamping params <= 0 =+      settleKey ctx (intKey wid) target+  | otherwise = do+  let key = intKey wid+  as <- readIORef (ctxAnimationState ctx)+  case IM.lookup key (asAnimations as) of+    Just (SpringAnim _ _ t p) | t == target && p == params -> repaintIfOrphan ctx key+    running -> do+      let (pos0, vel0) = case running of+            Just (SpringAnim d v t _) -> (t + d, v)+            Just a -> (animationValue a, 0)+            Nothing -> (IM.findWithDefault 0 key (asAnimRest as), 0)+          -- A value already poisoned starts again at the target.+          (pos, vel) = if finite pos0 && finite vel0 then (pos0, vel0) else (target, 0)++      if abs (pos - target) <= springEps && abs vel <= springEps+        then settleKey ctx key target+        else do+          writeIORef (ctxAnimationState ctx) $! insertRunning key (SpringAnim (pos - target) vel target params) as+          repaintIfOrphan ctx key++-- | Run @anim@ at @key@ in place of the key's resting value, if any.+{-# INLINE insertRunning #-}+insertRunning :: Int -> Animation -> AnimationState -> AnimationState+insertRunning key anim as =+  as+    { asAnimRest = IM.delete key (asAnimRest as)+    , asAnimations = IM.insert key anim (asAnimations as)+    }++-- | Request continuous frames while the widget calls this on every view pass.+-- 'tickAnimations' removes the request after a frame without renewal.+keepAnimationAlive :: Context -> WidgetId -> IO ()+keepAnimationAlive ctx wid = do+  let key = intKey wid+  as <- readIORef (ctxAnimationState ctx)+  let live = IM.member key (asAnimations as) || IS.member key (asKeepAlive as) || IS.member key (asKeepTouched as)+  unless (IS.member key (asKeepTouched as)) $+    writeIORef (ctxAnimationState ctx) $! as {asKeepTouched = IS.insert key (asKeepTouched as)}+  unless live (repaintIfOrphan ctx key)++-- | Stop an animation at a value and damage its widget if the value changed.+{-# INLINE setAnimationValue #-}+setAnimationValue :: Context -> WidgetId -> Float -> IO ()+setAnimationValue ctx wid val = settleKey ctx (intKey wid) val++-- | Advance animations by elapsed seconds, retain settled values, and expire+-- keep-alive requests and view hooks' animations that were not renewed in the+-- view and resting values that nothing held.+tickAnimations :: Context -> Float -> IO ()+tickAnimations ctx dt = do+  rects <- getsDamage ctx (pfRects . dsPrev)+  modifyIORef' (ctxAnimationState ctx) $ \as0 ->+    let as = lapseViewAnims (lapseRest rects (lapseKeepAlive as0))+     in if IM.null (asAnimations as)+          then if asAnimSettled as then as {asAnimSettled = False} else as+          else+            let stepped = IM.map (stepAnim dt) (asAnimations as)+                (live, done) = IM.partition animInProgress stepped+             in as+                  { asAnimations = live+                  , asAnimRest = restAll (asAnimRest as) done+                  , asRestHeld = if IM.null done then asRestHeld as else asRestHeld as <> IM.keysSet done+                  , asAnimSettled = not (IM.null done)+                  }++-- | Frames between sweeps of the resting values. A value unused for a whole+-- period goes at the sweep that ends it, so within two periods of its last+-- use; one used at least once a period stays.+restLeaseFrames :: Int+restLeaseFrames = 300++-- | Count a frame toward the next sweep of the resting values and, once a+-- period is up, sweep: keep the values held since the last sweep and those+-- whose widget has a rect, drop the rest. A widget's own value (its hover)+-- stays while the widget is laid out, since a clip frame need not paint it+-- and read it. Frames without resting values do not count; they only drop+-- leases left over from values that went back to zero.+lapseRest :: IntMap Rect -> AnimationState -> AnimationState+lapseRest rects as+  | IM.null (asAnimRest as) =+      if IS.null (asRestHeld as) then as else as {asRestHeld = IS.empty, asRestFrames = 0}+  | asRestFrames as + 1 < restLeaseFrames = as {asRestFrames = asRestFrames as + 1}+  | otherwise =+      as+        { asAnimRest = IM.filterWithKey (\k _ -> IS.member k held || IM.member k rects) (asAnimRest as)+        , asRestHeld = IS.empty+        , asRestFrames = 0+        }+  where+    held = asRestHeld as++-- | Advance the keep-alive lease window by one frame: only keys renewed+-- since the previous tick stay live.+lapseKeepAlive :: AnimationState -> AnimationState+lapseKeepAlive as+  | IS.null (asKeepAlive as) && IS.null (asKeepTouched as) = as+  | otherwise = as {asKeepAlive = asKeepTouched as, asKeepTouched = IS.empty}++-- | Rest, at their current values, the view hooks' animations that the view+-- left out this frame ('getViewAnimationValue'), and start the next frame's+-- lease.+lapseViewAnims :: AnimationState -> AnimationState+lapseViewAnims as+  | IS.null (asViewAnims as) && IS.null (asViewTouched as) = as+  | otherwise =+      let lapsed = asViewAnims as `IS.difference` asViewTouched as+          gone = IM.restrictKeys (asAnimations as) lapsed+       in as+            { asAnimations = if IM.null gone then asAnimations as else IM.withoutKeys (asAnimations as) lapsed+            , asAnimRest = restAll (asAnimRest as) gone+            , asViewAnims = asViewTouched as+            , asViewTouched = IS.empty+            }++-- | Repaint the whole frame for a running animation whose key has no layout+-- node ('NanoUI.Internal.Widgets.Animate.animate' and 'animateTo' allocate a+-- fresh id): without a widget rect to bound its damage, the frame must repaint+-- in full. The running animation drives frames at the paced rate; marking the+-- context dirty would schedule them unpaced.+repaintIfOrphan :: Context -> Int -> IO ()+repaintIfOrphan ctx key = do+  hadRect <- getsDamage ctx (IM.member key . pfRects . dsPrev)+  unless hadRect $ do+    let na = ctxNodeArena ctx+    hasNow <- maybe (pure False) (fmap rectNonEmpty . getNodeRect na) =<< lookupNodeByKey na key+    unless hasNow (damageFull ctx)++settleKey :: Context -> Int -> Float -> IO ()+settleKey ctx key val = do+  as <- readIORef (ctxAnimationState ctx)+  let rest = asAnimRest as+      prevRest = IM.findWithDefault 0 key rest+      prevLive = IM.lookup key (asAnimations as)+      restChanged+        | approxEq val 0 = IM.member key rest+        | otherwise = prevRest /= val+      rest' = if restChanged then restAt key val rest else rest+      -- A value set is in use, like one read.+      hold = not (approxEq val 0) && IS.notMember key (asRestHeld as)+      held' = if hold then IS.insert key (asRestHeld as) else asRestHeld as+  -- A spring at rest settles every frame; write only what changes.+  case prevLive of+    Just _ ->+      writeIORef (ctxAnimationState ctx) $!+        as {asAnimations = IM.delete key (asAnimations as), asAnimRest = rest', asRestHeld = held'}+    Nothing ->+      when (restChanged || hold) $+        writeIORef (ctxAnimationState ctx) $! as {asAnimRest = rest', asRestHeld = held'}+  when (maybe (not (approxEq prevRest val)) (not . approxEq val . animationValue) prevLive) $ do+    -- Covered: the key's widget paints from this value and its rect is+    -- damaged. 'animate' and 'animateTo' key a fresh id with no node, and+    -- those repaint whole through 'repaintIfOrphan' while they run.+    damageKey ctx key (DamageInflated defaultDamageSlop)+    -- A zero-length tween on such a key settles here without running, so+    -- this is the frame that must repaint whole.+    repaintIfOrphan ctx key+    markDirty ctx++-- | Record a settled value; one near zero is kept as no entry, which reads as zero.+restAt :: Int -> Float -> IntMap Float -> IntMap Float+restAt key v = if approxEq v 0 then IM.delete key else IM.insert key v++restAll :: IntMap Float -> IntMap Animation -> IntMap Float+restAll = IM.foldlWithKey' (\r k a -> restAt k (animationValue a) r)++-- | Current animated or settled value; zero when the id has neither. Reading+-- a settled value holds it through the next sweep ('lapseRest').+getAnimationValue :: Context -> WidgetId -> IO Float+getAnimationValue = readAnimValue False++-- | 'getAnimationValue' for a key a view hook owns ('animate', 'animateTo').+-- An animation running there lasts while the view reads it: on the first+-- frame without a read, 'tickAnimations' rests it at its value.+getViewAnimationValue :: Context -> WidgetId -> IO Float+getViewAnimationValue = readAnimValue True++readAnimValue :: Bool -> Context -> WidgetId -> IO Float+readAnimValue touchView ctx wid = do+  let key = intKey wid+  as <- readIORef (ctxAnimationState ctx)+  case IM.lookup key (asAnimations as) of+    Just a -> do+      when (touchView && IS.notMember key (asViewTouched as)) $+        writeIORef (ctxAnimationState ctx) $! as {asViewTouched = IS.insert key (asViewTouched as)}+      pure $! animationValue a+    Nothing -> do+      -- 'restAt' keeps no zero, so a nonzero value is a stored one.+      let v = IM.findWithDefault 0 key (asAnimRest as)+      when (v /= 0 && IS.notMember key (asRestHeld as)) $+        writeIORef (ctxAnimationState ctx) $! as {asRestHeld = IS.insert key (asRestHeld as)}+      pure v
+ lib/NanoUI/Internal/Context/Core.hs view
@@ -0,0 +1,656 @@+-- | Accessors the other Context modules build on: interaction, overlay and+-- damage state, damage requests, the dirty flag, and widget store writes.+module NanoUI.Internal.Context.Core+  ( getsInteraction+  , modifyInteraction+  , getsOverlay+  , modifyOverlay+  , getsDamage+  , modifyDamage+  -- Interaction+  , takeTextEditLastAction+  , pointerHeldOffLayers+  -- Damage+  , markDirty+  , recordLayoutRead+  , settleLayoutReads+  , clearDirty+  , isDirty+  , setWakeLoop+  , setWakeLoopChecked+  , wakeAction+  , wakeFromThread+  , takeWakes+  , takeThreadWake+  , requestWakeAt+  , requestWakeAfter+  , getWakeAt+  , clearWakeAt+  , takeDamage+  , takeDamagePieces+  , requestDamage+  , damageWidget+  , damageKey+  , damageRect+  , damagePeers+  , damageFull+  , traceDamage+  , getPrevRect+  , getPrevRectAt+  , pointerCovered+  , getPrevClipRect+  -- Store+  , getStore+  , setStore+  , modifyStore+  , writeSlots+  , publishLayoutSlots+  , writeSlot+  , adoptSlot+  , recordSlot+  , writeStoreBool+  , isDisabled+  , isInert+  -- Theme scopes+  , newThemeScopes+  , beginThemeScopes+  , pushThemeScope+  , themeScopesChanged+  , scopeTheme+  , scopeRawTheme+  , currentTheme+  , nodeTheme+  , widgetTheme+  )+where++import Control.Concurrent (myThreadId)+import Control.Monad (forM_, unless, when, (<$!>))+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.IORef (IORef, atomicModifyIORef', atomicWriteIORef, modifyIORef', readIORef, writeIORef)+import Data.Primitive.Array (readArray)+import Data.Primitive.PrimArray (readPrimArray)+import Data.Primitive.PrimVar (readPrimVar)+import Data.Primitive.SmallArray (SmallMutableArray, copySmallMutableArray, newSmallArray, readSmallArray, getSizeofSmallMutableArray, writeSmallArray)+import Data.IntMap.Strict qualified as IM+import Data.Foldable (foldlM)+import Data.Maybe (fromMaybe, isJust)+import Data.IntSet qualified as IS+import GHC.Clock (getMonotonicTime)+import GHC.Exts (RealWorld)+import System.Environment (lookupEnv)+import System.IO (hPutStrLn, stderr)+import System.IO.Unsafe (unsafePerformIO)++import NanoUI.Internal.Context.Types+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Layout.Arena (NodeIdx, getArenaScope, getNodeScope, getScopeSignature, lookupNodeByWidgetId)+import NanoUI.Internal.Store+import NanoUI.Internal.Store.Slots (slotSeen)+import NanoUI.Internal.Style (Theme, disabledTheme)+import NanoUI.Internal.Types (Damage, DamageBounds (..), Rect (..), defaultDamageSlop, rectH, rectW)+import NanoUI.Widgets.TextCommand (TextCommand)++-- =============================================================================+-- State records+-- =============================================================================++-- | Read a projection of the interaction state.+{-# INLINE getsInteraction #-}+getsInteraction :: Context -> (InteractionState -> a) -> IO a+getsInteraction ctx f = f <$> readIORef (ctxInteractionState ctx)++-- | Strictly update interaction state on the UI thread. Does not request repaint.+{-# INLINE modifyInteraction #-}+modifyInteraction :: Context -> (InteractionState -> InteractionState) -> IO ()+modifyInteraction ctx = modifyIORef' (ctxInteractionState ctx)++-- | Read a projection of the overlay state.+{-# INLINE getsOverlay #-}+getsOverlay :: Context -> (OverlayState -> a) -> IO a+getsOverlay ctx f = f <$> readIORef (ctxOverlayState ctx)++-- | Strictly update overlay state on the UI thread. Does not request repaint.+{-# INLINE modifyOverlay #-}+modifyOverlay :: Context -> (OverlayState -> OverlayState) -> IO ()+modifyOverlay ctx = modifyIORef' (ctxOverlayState ctx)++-- | Read a projection of the damage bookkeeping.+{-# INLINE getsDamage #-}+getsDamage :: Context -> (DamageState -> a) -> IO a+getsDamage ctx f = f <$> readIORef (ctxDamageState ctx)++-- | Strictly update damage bookkeeping without waking the event loop.+{-# INLINE modifyDamage #-}+modifyDamage :: Context -> (DamageState -> DamageState) -> IO ()+modifyDamage ctx = modifyIORef' (ctxDamageState ctx)++-- =============================================================================+-- Interaction+-- =============================================================================++-- | Read and clear the last command run by a text-edit menu, with its target id.+takeTextEditLastAction :: Context -> IO (Maybe (WidgetId, TextCommand))+takeTextEditLastAction ctx = do+  act <- getsInteraction ctx isTextEditLastAction+  modifyInteraction ctx (\s -> s {isTextEditLastAction = Nothing})+  pure act++-- | Whether a held button went down on a menu or dropdown rather than on a+-- layer's widgets. Nothing in the layers is hot while it lasts.+{-# INLINE pointerHeldOffLayers #-}+pointerHeldOffLayers :: Context -> IO Bool+pointerHeldOffLayers ctx =+  getsInteraction ctx $ \s ->+    isPointerHeld s && case isPointerRoute s of+      RouteLayer _ -> False+      _ -> True++-- =============================================================================+-- Damage+-- =============================================================================++-- | Queue repaint bounds for the frame's damage pass. Does not wake the loop;+-- call 'markDirty' as well when a new frame must be scheduled.+{-# INLINE requestDamage #-}+requestDamage :: Context -> DamageRequest -> IO ()+requestDamage ctx req = modifyDamage ctx (\ds -> ds {dsRequests = req : dsRequests ds})++-- | Queue damage relative to a widget's previous and current bounds. Zero ids+-- are ignored. Does not itself schedule a frame.+{-# INLINE damageWidget #-}+damageWidget :: Context -> WidgetId -> DamageBounds -> IO ()+damageWidget ctx wid bounds+  | hashWidgetId wid == 0 = pure ()+  | otherwise = requestDamage ctx (ReqWidget wid bounds)++-- | Queue widget damage by integer store key. Zero keys are ignored.+{-# INLINE damageKey #-}+damageKey :: Context -> Int -> DamageBounds -> IO ()+damageKey ctx k bounds+  | k == 0 = pure ()+  | otherwise = requestDamage ctx (ReqKey k bounds)++-- | Queue an explicit logical window rectangle. Empty rectangles are ignored.+{-# INLINE damageRect #-}+damageRect :: Context -> Rect -> IO ()+damageRect ctx r+  | rectW r <= 0 || rectH r <= 0 = pure ()+  | otherwise = requestDamage ctx (ReqRect r)++-- | Queue the same damage rule for a group of nonzero widget ids.+{-# INLINE damagePeers #-}+damagePeers :: Context -> [WidgetId] -> DamageBounds -> IO ()+damagePeers ctx wids bounds =+  case filter (\w -> hashWidgetId w /= 0) wids of+    [] -> pure ()+    valid -> requestDamage ctx (ReqPeers valid bounds)++-- | Queue a whole-window repaint. Call 'markDirty' if the loop also needs waking.+{-# INLINE damageFull #-}+damageFull :: Context -> IO ()+damageFull ctx = requestDamage ctx ReqFull++-- | Whether @NANO_DAMAGE_TRACE@ is set, read once per process.+{-# NOINLINE damageTraceOn #-}+damageTraceOn :: Bool+damageTraceOn = unsafePerformIO (isJust <$> lookupEnv "NANO_DAMAGE_TRACE")++-- | With @NANO_DAMAGE_TRACE@ set, write a line to stderr. Each frame's damage+-- pass writes @DAMAGE clip@ or @DAMAGE full@ with the check that chose a+-- whole-window repaint; the fallbacks that queue one write @DAMAGE-REQ@ with+-- their name. Counting the lines over a test run shows which checks repaint+-- the window most.+traceDamage :: String -> IO ()+traceDamage msg = when damageTraceOn (hPutStrLn stderr msg)++-- | Request another view pass and wake the event loop, unless this is the+-- loop's own thread, which checks the flag before it waits.+-- Dirty state schedules work; damage determines which pixels are repainted.+-- The follow-up frame repaints what its diff finds changed: nodes whose+-- rect or paint inputs changed, store keys, and the hot, active and focused+-- widgets. A change to anything else nano-ui paints from also needs+-- 'damageFull'.+--+-- Call it on the thread that runs frames, or on one that thread is blocked+-- on (as SDL's resize watch is): the flag shares a plain 'IORef' with the+-- frame's damage bookkeeping. Other threads publish their change and call+-- 'wakeFromThread' (the action from 'NanoUI.askWake'), which is atomic.+{-# INLINE markDirty #-}+markDirty :: Context -> IO ()+markDirty ctx = do+  modifyDamage ctx (\ds -> ds {dsDirty = True})+  wakeOffLoop ctx++-- | Record a layout read for key @k@ during view construction. After layout+-- completes, 'settleLayoutReads' runs @stale@ to check whether the newly+-- computed layout differs from the value read, and schedules a follow-up frame+-- if so. Unread layout changes do not schedule a frame. Only the first read+-- of each key per settle cycle is retained.+recordLayoutRead :: Context -> Int -> IO Bool -> IO ()+recordLayoutRead ctx k stale =+  modifyDamage ctx (\ds -> ds {dsLayoutReads = IM.insertWith (\_ old -> old) k stale (dsLayoutReads ds)})++-- | Run all pending 'recordLayoutRead' checks against the completed layout+-- and clear the table. Every check is executed so callbacks can also publish+-- measured geometry ('publishLayoutSlots'). Any stale read schedules a+-- damage-covered follow-up frame.+settleLayoutReads :: Context -> IO ()+settleLayoutReads ctx = do+  pending <- getsDamage ctx dsLayoutReads+  unless (IM.null pending) $ do+    modifyDamage ctx (\ds -> ds {dsLayoutReads = IM.empty})+    stale <- foldlM (\acc check -> (acc ||) <$> check) False pending+    when stale (markDirty ctx)++-- | Clear the follow-up-frame request without clearing queued repaint bounds.+-- The whole-window repaint a 'markDirty' queued stays for the next frame.+{-# INLINE clearDirty #-}+clearDirty :: Context -> IO ()+clearDirty ctx = modifyDamage ctx (\ds -> ds {dsDirty = False})++-- | Whether state changes require another view pass.+{-# INLINE isDirty #-}+isDirty :: Context -> IO Bool+isDirty ctx = getsDamage ctx dsDirty++-- | Install the backend action that interrupts an event wait. A background+-- producer should invoke the wake action after publishing synchronised data.+-- The action runs once for a run of wakes until the loop takes them+-- ('takeWakes'), and not for the loop thread's own dirty marks, so it need+-- not filter or coalesce calls itself.+{-# INLINE setWakeLoop #-}+setWakeLoop :: Context -> IO () -> IO ()+setWakeLoop ctx wake = setWakeLoopChecked ctx (True <$ wake)++-- | 'setWakeLoop' for an action that can fail to reach the loop, such as a+-- push onto a full event queue. It returns whether it did; after a failure+-- the next wake runs it again instead of taking the loop as woken.+{-# INLINE setWakeLoopChecked #-}+setWakeLoopChecked :: Context -> IO Bool -> IO ()+setWakeLoopChecked ctx wake = writeIORef (ctxWakeLoop ctx) (Just wake)++-- | Run @loopRef@ unless @pendingRef@ already marks a wake in flight.+-- Resets @pendingRef@ when no callback is installed or the callback reports+-- delivery failure, so a later wake is not swallowed.+{-# INLINE triggerWake #-}+triggerWake :: IORef Bool -> IORef (Maybe (IO Bool)) -> IO ()+triggerWake pendingRef loopRef = do+  wasPending <- atomicModifyIORef' pendingRef (True,)+  unless wasPending $ do+    delivered <- readIORef loopRef >>= fromMaybe (pure False)+    unless delivered (atomicWriteIORef pendingRef False)++-- | Run the wake action, unless an earlier wake ran it and the loop has not+-- taken that one yet: the loop reads what both changed when it does. A wake+-- the action did not deliver, or made with no action installed, leaves+-- nothing pending, so a later wake is not swallowed waiting for it.+wakeLoop :: Context -> IO ()+wakeLoop ctx = triggerWake (ctxWakePending ctx) (ctxWakeLoop ctx)++-- | 'wakeLoop' for a dirty mark. The thread running+-- 'NanoUI.Runner.runSessionLoop' checks the dirty flag before waiting, so+-- its own marks during a frame need not wake the event wait.+wakeOffLoop :: Context -> IO ()+wakeOffLoop ctx =+  readIORef (ctxLoopThread ctx) >>= \case+    Nothing -> wakeLoop ctx+    Just loop -> myThreadId >>= \me -> unless (me == loop) (wakeLoop ctx)++-- | Clear 'ctxWakePending' so the next wake invokes the backend wake callback+-- again. Called after each event wait and at the start of every frame+-- ('takeThreadWake').+{-# INLINE takeWakes #-}+takeWakes :: Context -> IO ()+takeWakes ctx = atomicWriteIORef (ctxWakePending ctx) False++-- | Build a thread-safe wake action that retains only the wake 'IORef's and+-- never the full 'Context', preventing background jobs and callbacks from+-- pinning stale font metrics or caches across font reloads.+wakeAction :: Context -> IO ()+wakeAction ctx =+  let !wokenRef = ctxWoken ctx+      !pendingRef = ctxWakePending ctx+      !loopRef = ctxWakeLoop ctx+   in do+        atomicWriteIORef wokenRef True+        triggerWake pendingRef loopRef++-- | Wake the loop from any thread after changing state the view reads.+-- Publish the change first. The next frame runs the view, and its diff+-- repaints what the change altered.+wakeFromThread :: Context -> IO ()+wakeFromThread = wakeAction++-- | At frame start, before the view runs: take the wakes so far+-- ('takeWakes'), and clear the record of a 'wakeFromThread' call. Calls made+-- while the view runs are left for the frame they wake.+{-# INLINE takeThreadWake #-}+takeThreadWake :: Context -> IO ()+takeThreadWake ctx = do+  takeWakes ctx+  atomicWriteIORef (ctxWoken ctx) False++-- | Schedule a frame at a monotonic timestamp ('getMonotonicTime') even if no+-- input arrives. The earliest deadline wins. Cleared at the start of each+-- frame ('clearWakeAt'), so active widgets must re-register their deadline on+-- each view pass. UI thread only; background threads use 'wakeFromThread'.+requestWakeAt :: Context -> Double -> IO ()+requestWakeAt ctx t = do+  cur <- readIORef (ctxWakeAt ctx)+  when (t > 0 && (cur <= 0 || t < cur)) $ writeIORef (ctxWakeAt ctx) t++-- | 'requestWakeAt', in seconds from now.+requestWakeAfter :: Context -> Double -> IO ()+requestWakeAfter ctx sec = do+  now <- getMonotonicTime+  requestWakeAt ctx (now + max 0 sec)++-- | Pending wake timestamp, or 0 if none.+{-# INLINE getWakeAt #-}+getWakeAt :: Context -> IO Double+getWakeAt ctx = readIORef (ctxWakeAt ctx)++-- | Clear the timed wake request at frame start; live widgets request it again.+{-# INLINE clearWakeAt #-}+clearWakeAt :: Context -> IO ()+clearWakeAt ctx = writeIORef (ctxWakeAt ctx) 0++-- | Read the last computed damage. Despite the name, this does not clear it.+{-# INLINE takeDamage #-}+takeDamage :: Context -> IO Damage+takeDamage ctx = getsDamage ctx dsDamage++-- | The disjoint rects a 'NanoUI.Backend.DamageClip' frame repaints, when its damage lies in+-- two or more places far apart; empty when the whole clip repaints. A+-- backend that draws text itself must clip it to each; draw commands+-- already are.+{-# INLINE takeDamagePieces #-}+takeDamagePieces :: Context -> IO [Rect]+takeDamagePieces ctx = getsDamage ctx dsDamagePieces++-- | Last recorded widget bounds in logical window coordinates, with scrolling+-- applied. 'Nothing' means the damage pass recorded no bounds for this id.+{-# INLINE getPrevRect #-}+getPrevRect :: Context -> WidgetId -> IO (Maybe Rect)+getPrevRect ctx wid = getsDamage ctx (IM.lookup (intKey wid) . pfRects . dsPrev)++-- | 'getPrevRect' of @wid@, declared as node @idx@, or an empty rect. A+-- widget declared where it was last frame, as views rebuilt in the same+-- order are, is read by node index from the last walk's record+-- ('ctxPrevWalk'); any other from the map, whose lookup misses the cache in+-- a large view. The bang on the id keeps it unboxed in callers.+{-# NOINLINE getPrevRectAt #-}+getPrevRectAt :: Context -> NodeIdx -> WidgetId -> IO Rect+getPrevRectAt ctx !idx (WidgetId !w) = do+  walk <- readIORef (ctxPrevWalk ctx)+  valid <- readPrimVar (pwValid walk)+  let !k = fromIntegral w+  here <- if k /= 0 && idx >= 0 && idx < valid then (== k) <$> readPrimArray (pwKeys walk) idx else pure False+  if here+    then readArray (pwRects walk) idx+    else fromMaybe (Rect 0 0 0 0) <$!> getsDamage ctx (IM.lookup k . pfRects . dsPrev)++-- | Whether a pointer-taking node drawn over @wid@ (by layers or a pin) has+-- the pointer instead, in the frame the user saw ('ctxPointerReach'). Only+-- meaningful for a widget under the pointer. Widgets that hit-test presses+-- against their own rect, rather than via+-- 'NanoUI.Internal.Widgets.Node.Response', must check this too.+{-# INLINE pointerCovered #-}+pointerCovered :: Context -> WidgetId -> IO Bool+pointerCovered ctx wid = maybe False (not . IS.member (intKey wid)) <$> readIORef (ctxPointerReach ctx)++-- | Last recorded widget clip in logical window coordinates, or 'Nothing'.+{-# INLINE getPrevClipRect #-}+getPrevClipRect :: Context -> WidgetId -> IO (Maybe Rect)+getPrevClipRect ctx wid = getsDamage ctx (IM.lookup (intKey wid) . pfClips . dsPrev)++-- =============================================================================+-- Store+-- =============================================================================++-- | Current immutable store value. Mutations must be published through store+-- operations so the context can track damage and follow-up frames.+{-# INLINE getStore #-}+getStore :: Context -> IO WidgetStore+getStore ctx = readIORef (ctxStore ctx)++-- | Replace the store, diff changed slots for damage, and wake on a change.+setStore :: Context -> WidgetStore -> IO ()+setStore ctx store = modifyStore ctx (const store)++-- | Apply @f@ to the store, damage any keys whose values changed, and mark the+-- context dirty.+modifyStore :: Context -> (WidgetStore -> WidgetStore) -> IO ()+modifyStore ctx f = do+  prev <- readIORef (ctxStore ctx)+  -- WHNF-force the new record: record-update arguments are unevaluated+  -- thunks, and writeIORef would otherwise park one in the long-lived store+  -- every frame.+  let !store = f prev+  writeIORef (ctxStore ctx) store+  let changedKeys =+        slotChangedKeys prev store+          ++ diffKeys (storeFloat prev) (storeFloat store)+          ++ diffKeys (storePoint prev) (storePoint store)+  -- The key diff doubles as the store comparison: checking 'prev /= store'+  -- first would walk every changed map twice. Its lazy concatenation stops at+  -- the first changed key and allocates less than a list per map.+  when+    ( storeOpenSelect prev /= storeOpenSelect store+        || not (null changedKeys)+    )+    $ do+      forM_ changedKeys $ \k -> damageKey ctx k (DamageInflated defaultDamageSlop)+      markDirty ctx++-- | Run slot writes, unless every slot already holds its value: an idle+-- widget then neither rebuilds the store nor has it diffed.+{-# INLINE writeSlots #-}+writeSlots :: Context -> SlotWrites -> IO ()+writeSlots ctx (SlotWrites same f) = do+  st <- readIORef (ctxStore ctx)+  unless (same st) (setStore ctx (f st))++-- | Write layout-derived slots (such as scroll geometry) for the next view+-- pass without marking the context dirty; views that depend on these values+-- schedule a follow-up frame via 'recordLayoutRead'. Store diffing in+-- 'NanoUI.Internal.Damage.writeDamage' still records paint damage.+publishLayoutSlots :: Context -> SlotWrites -> IO ()+publishLayoutSlots ctx (SlotWrites same f) = do+  st <- readIORef (ctxStore ctx)+  unless (same st) (writeIORef (ctxStore ctx) $! f st)++-- | Targeted single-slot write: compares only the target slot, updates one map+-- field, damages the owning widget and wakes the loop. Unlike 'setStore' it+-- never diffs the whole store, and an equal write is a no-op.+{-# INLINE writeSlot #-}+writeSlot :: Eq a => Field a -> Context -> WidgetId -> Int -> a -> IO ()+writeSlot field ctx owner k v = do+  st <- readIORef (ctxStore ctx)+  case lookupSlot field k st of+    Just old | old == v -> pure ()+    _ -> do+      writeIORef (ctxStore ctx) $! insertSlot field k v st+      damageWidget ctx owner DamageSelf+      markDirty ctx++-- | Write a boolean at the owner's base integer key, with change detection.+{-# INLINE writeStoreBool #-}+writeStoreBool :: Context -> WidgetId -> Bool -> IO ()+writeStoreBool ctx owner v = writeSlot fieldInt ctx owner (intKey owner) (boolInt v)++-- | Controlled widgets take their value from the caller every frame. The+-- caller's value replaces the stored one only when it differs from the value+-- the widget last returned ('recordSlot'). An edit applied between frames,+-- such as a menu cut, then survives a caller that passes the previous result+-- back, while a value changed by the application still wins. Returns the+-- value of the owner's slot after adopting.+{-# INLINE adoptSlot #-}+adoptSlot :: Eq a => Field a -> Context -> WidgetId -> a -> IO a+adoptSlot field ctx owner v = do+  st <- readIORef (ctxStore ctx)+  let k = intKey owner+  if lookupSpec (slotSeen field) k st == Just v+    then pure $! findSlot field v k st+    else do+      writeIORef (ctxStore ctx) $! insertSpec (slotSeen field) k v (insertSlot field k v st)+      when (lookupSlot field k st /= Just v) $ do+        damageWidget ctx owner DamageSelf+        markDirty ctx+      pure v++-- | Remember the value a controlled widget returned this frame.+{-# INLINE recordSlot #-}+recordSlot :: Eq a => Field a -> Context -> Int -> a -> IO ()+recordSlot field ctx k v = do+  st <- readIORef (ctxStore ctx)+  when (lookupSpec (slotSeen field) k st /= Just v) $+    writeIORef (ctxStore ctx) $! insertSpec (slotSeen field) k v st++-- | Whether @wid@ is in a disabled scope. Falls back to the arena's active+-- scope when called before the widget's node is allocated.+{-# INLINE isDisabled #-}+isDisabled :: Context -> WidgetId -> IO Bool+isDisabled ctx wid = do+  ts <- readIORef (ctxThemeScopes ctx)+  if tsDisabled ts then scopeDisabled ctx wid else pure False++{-# INLINE widgetScope #-}+widgetScope :: Context -> WidgetId -> IO Int+widgetScope Context {ctxNodeArena = na} wid =+  lookupNodeByWidgetId na wid >>= maybe (getArenaScope na) (getNodeScope na)++{-# NOINLINE scopeDisabled #-}+scopeDisabled :: Context -> WidgetId -> IO Bool+scopeDisabled ctx wid = (/= 0) . (.&. 1) <$> widgetScope ctx wid++-- =============================================================================+-- Theme scopes+-- =============================================================================++-- | Display-only descendants cannot acquire focus or handle input. Before a+-- widget is added, inspect the open scope instead of its not-yet-built node.+{-# INLINE isInert #-}+isInert :: Context -> WidgetId -> IO Bool+isInert ctx wid = (/= 0) . (.&. 2) <$> widgetScope ctx wid++-- | Allocate empty current/previous scope arrays. Only entries below their+-- recorded counts are initialised and may be read.+newThemeScopes :: IO ThemeScopes+newThemeScopes = do+  let unset = error "theme scope: unset"+  cur <- newSmallArray 8 unset+  raw <- newSmallArray 8 unset+  prev <- newSmallArray 8 unset+  pure+    ThemeScopes+      { tsCount = 0+      , tsThemes = cur+      , tsRaw = raw+      , tsPrevCount = 0+      , tsPrev = prev+      , tsDisabled = False+      , tsChanged = False+      , tsPrevSig = 0+      }++-- | Start a view pass with no pushed themes. The first pass of a frame keeps+-- last frame's themes to compare against; a rebuild pass keeps comparing+-- against the same ones.+beginThemeScopes :: Context -> Bool -> IO ()+beginThemeScopes ctx newFrame = do+  ts <- readIORef (ctxThemeScopes ctx)+  if newFrame+    then do+      sig <- getScopeSignature (ctxNodeArena ctx)+      writeIORef (ctxThemeScopes ctx) $!+        ts+          { tsCount = 0+          , tsThemes = tsPrev ts+          , tsPrevCount = tsCount ts+          , tsPrev = tsThemes ts+          , tsDisabled = False+          , tsChanged = False+          , tsPrevSig = sig+          }+    else writeIORef (ctxThemeScopes ctx) $! ts {tsCount = 0, tsDisabled = False, tsChanged = False}++-- | Add a scope with its disabled status and raw theme, painted faded+-- ('disabledTheme') when disabled. Returns the packed arena scope (the+-- one-based theme index and the disabled bit) and records whether the painted+-- theme differs from the previous frame's theme at that index.+pushThemeScope :: Context -> Bool -> Theme -> IO Int+pushThemeScope ctx disabled raw = do+  ts <- readIORef (ctxThemeScopes ctx)+  let !i = tsCount ts+      theme = if disabled then disabledTheme raw else raw+      -- The two arrays grow separately: 'tsThemes' trades places with+      -- 'tsPrev' each frame, so its capacity can differ from that of 'tsRaw'.+      withRoom arr fill = do+        cap <- getSizeofSmallMutableArray arr+        if i < cap+          then pure arr+          else do+            grown <- newSmallArray (cap * 2) fill+            copySmallMutableArray grown 0 arr 0 i+            pure grown+  themes <- withRoom (tsThemes ts) theme+  raws <- withRoom (tsRaw ts) raw+  same <-+    if i < tsPrevCount ts+      then (== theme) <$> readSmallArray (tsPrev ts) i+      else pure False+  writeSmallArray themes i theme+  writeSmallArray raws i raw+  writeIORef (ctxThemeScopes ctx) $!+    ts {tsCount = i + 1, tsThemes = themes, tsRaw = raws, tsDisabled = tsDisabled ts || disabled, tsChanged = tsChanged ts || not same}+  pure (((i + 1) `shiftL` 2) .|. fromEnum disabled)++-- | Whether this frame's scopes look different from last frame's: a theme+-- changed, scopes were added or dropped, or nodes moved between scopes.+themeScopesChanged :: Context -> IO Bool+themeScopesChanged ctx = do+  ts <- readIORef (ctxThemeScopes ctx)+  sig <- getScopeSignature (ctxNodeArena ctx)+  pure (tsChanged ts || tsCount ts /= tsPrevCount ts || sig /= tsPrevSig ts)++-- | Painted theme for a packed arena scope. Theme index zero uses the base+-- theme; other indices must name a scope registered during this view pass.+{-# INLINE scopeTheme #-}+scopeTheme :: Context -> Int -> IO Theme+scopeTheme = scopeThemeIn tsThemes++-- | A scope's theme before any disabled scope faded it.+scopeRawTheme :: Context -> Int -> IO Theme+scopeRawTheme = scopeThemeIn tsRaw++-- | The theme a packed arena scope names in one of the scope arrays, or the+-- base theme for theme index zero.+{-# INLINE scopeThemeIn #-}+scopeThemeIn :: (ThemeScopes -> SmallMutableArray RealWorld Theme) -> Context -> Int -> IO Theme+scopeThemeIn arr ctx scope+  | ti == 0 = readIORef (ctxTheme ctx)+  | otherwise = do+      ts <- readIORef (ctxThemeScopes ctx)+      readSmallArray (arr ts) (ti - 1)+  where+    !ti = scope `shiftR` 2++-- | Active theme for the current arena scope.+{-# INLINE currentTheme #-}+currentTheme :: Context -> IO Theme+currentTheme ctx = getArenaScope (ctxNodeArena ctx) >>= scopeTheme ctx++-- | Painted theme recorded on a live node, including disabled styling.+{-# INLINE nodeTheme #-}+nodeTheme :: Context -> NodeIdx -> IO Theme+nodeTheme ctx idx = getNodeScope (ctxNodeArena ctx) idx >>= scopeTheme ctx++-- | The theme of @wid@'s node, or of the current scope before it has one.+widgetTheme :: Context -> WidgetId -> IO Theme+widgetTheme ctx wid = do+  ts <- readIORef (ctxThemeScopes ctx)+  if tsCount ts == 0+    then readIORef (ctxTheme ctx)+    else widgetScope ctx wid >>= scopeTheme ctx
+ lib/NanoUI/Internal/Context/Drawing.hs view
@@ -0,0 +1,510 @@+-- | Per-widget drawing registrations and the caches derived from them.+module NanoUI.Internal.Context.Drawing+  ( registerPopupConfig+  , lookupPopupConfig+  , registerDropdownPopup+  , dropdownPopups+  , registerHoverZone+  , hoverZoneCrossed+  , registerDrawing+  , cachedDrawingOps+  , cachedWidgetLayout+  , lookupDrawFitEnvelope+  , pruneDrawOpCache+  , registerCustomDrawing+  , registerCustomEntry+  , lookupCustomDrawing+  , lookupCustomDrawingAt+  , lookupDrawingAt+  , lookupCustomMeasureAt+  , customDrawingOffNode+  , cachedCustomDrawingOps+  , refreshCustomDrawingOps+  , drawingOpsStale+  , registerCustomMeasure+  , lookupCustomMeasure+  , customMeasureHooks+  , lookupCustomDamageSlop+  , resetDrawingScopeCache+  , registerNodeShaderAt+  , lookupNodeShaderAt+  , registerShaderEffectAt+  , lookupShaderEffectAt+  , activeEffectNodes+  , getShaderCapabilities+  ) where++import Control.Monad (mfilter, unless, when)+import Data.Bits (complement)+import Data.IORef (modifyIORef', readIORef, writeIORef)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.Maybe (isJust)+import Data.Primitive.Array (readArray, sizeofMutableArray, writeArray)+import Data.Primitive.PrimArray (readPrimArray, setPrimArray, writePrimArray)+import Data.Primitive.PrimVar (readPrimVar)+import Data.Primitive.SmallArray (SmallArray, mapSmallArray')+import Data.Word (Word64)++import NanoUI.Internal.Context.Animation (isAnimatingKey)+import NanoUI.Internal.Context.Types+import NanoUI.Internal.Draw (DrawOp, DrawingBuild, shiftDrawOp)+import NanoUI.Internal.Id (WidgetId, mix64)+import NanoUI.Internal.Layout.Arena (NodeArena (..), NodeIdx, NodeType (..), getNodeType, lookupNodeByKey, lookupNodeByWidgetId)+import NanoUI.Internal.Layout.Arena.Types (growBoxedStoreCopy)+import NanoUI.Internal.Shader (ShaderCapabilities, ShaderEffectEntry, ShaderNodeEntry)+import NanoUI.Internal.Store (ptrEq)+import NanoUI.Internal.Style (Layout)+import NanoUI.Internal.Types (PopupAnchor, PopupPlacement, Rect (..), V2, rectContains, rectH, rectW)++{-# INLINE lookupIn #-}+lookupIn :: (DrawingCacheState -> IntMap a) -> Context -> WidgetId -> IO (Maybe a)+lookupIn field ctx wid = IM.lookup (intKey wid) . field <$> readIORef (ctxDrawingCache ctx)++{-# INLINE registerIn #-}+registerIn ::+  (DrawingCacheState -> IntMap a) ->+  (IntMap a -> DrawingCacheState -> DrawingCacheState) ->+  Context ->+  WidgetId ->+  a ->+  IO ()+registerIn field setField ctx wid v =+  modifyIORef' (ctxDrawingCache ctx) $ \dc ->+    setField (IM.insert (intKey wid) v (field dc)) dc++-- | Register a popup anchor, preferred placement, and logical-pixel offset+-- for the current view pass.+{-# INLINE registerPopupConfig #-}+registerPopupConfig :: Context -> WidgetId -> PopupAnchor -> PopupPlacement -> Float -> IO ()+registerPopupConfig ctx wid anchor placement offset =+  registerIn dcsPopupConfigs (\m dc -> dc {dcsPopupConfigs = m}) ctx wid (PopupConfig anchor placement offset)++-- | Current popup placement registration, or 'Nothing' for an unregistered id.+{-# INLINE lookupPopupConfig #-}+lookupPopupConfig :: Context -> WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))+lookupPopupConfig ctx wid =+  fmap (\(PopupConfig anchor placement offset) -> (anchor, placement, offset))+    <$> lookupIn dcsPopupConfigs ctx wid++-- | Register popup @wid@ as a dropdown for the current view pass:+-- placement puts it where its field's rect this frame puts its dropdown, not+-- by an anchor.+registerDropdownPopup :: Context -> WidgetId -> DropdownPopup -> IO ()+registerDropdownPopup = registerIn dcsDropdowns (\m dc -> dc {dcsDropdowns = m})++-- | The dropdown popups this pass registered, by popup key+-- ('registerDropdownPopup').+{-# INLINE dropdownPopups #-}+dropdownPopups :: Context -> IO (IntMap DropdownPopup)+dropdownPopups ctx = dcsDropdowns <$> readIORef (ctxDrawingCache ctx)++-- | Request a frame when the pointer enters or leaves @rect@ this pass. Used+-- for tooltip targets, which may be non-interactive labels or containers+-- skipped by normal hit-testing. A @tracked@ rect also requests a frame on+-- every pointer move inside it, for an open tooltip that follows the pointer.+registerHoverZone :: Context -> Bool -> Rect -> IO ()+registerHoverZone ctx tracked rect =+  modifyIORef' (ctxDrawingCache ctx) $ \dc -> dc {dcsHoverZones = HoverZone rect tracked : dcsHoverZones dc}++-- | Whether a pointer move from @from@ to @to@ enters or leaves a rect+-- registered this pass, or moves over a tracked one ('registerHoverZone').+hoverZoneCrossed :: Context -> V2 -> V2 -> IO Bool+hoverZoneCrossed ctx from to =+  any crossed . dcsHoverZones <$> readIORef (ctxDrawingCache ctx)+  where+    crossed (HoverZone r tracked) = let on = rectContains r from in on /= rectContains r to || (on && tracked)++-- | Node @idx@'s registrations this view pass ('ctxNodeCustom').+{-# INLINE nodeCustomAt #-}+nodeCustomAt :: Context -> NodeIdx -> IO NodeCustom+nodeCustomAt ctx idx = do+  arr <- readIORef (ctxNodeCustom ctx)+  if idx < 0 || idx >= sizeofMutableArray arr+    then pure noNodeCustom+    else do+      nc <- readArray arr idx+      ep <- readPrimVar (naEpoch (ctxNodeArena ctx))+      pure (if ncEpoch nc == ep then nc else noNodeCustom)++-- | The registrations of the node widget @wid@ was declared as.+{-# INLINE nodeCustomOf #-}+nodeCustomOf :: Context -> WidgetId -> IO NodeCustom+nodeCustomOf ctx wid = maybe (pure noNodeCustom) (nodeCustomAt ctx) =<< lookupNodeByWidgetId (ctxNodeArena ctx) wid++-- | Change the registrations of node @idx@ directly.+{-# INLINE registerAtIdx #-}+registerAtIdx :: Context -> NodeIdx -> (NodeCustom -> IO NodeCustom) -> IO ()+registerAtIdx ctx idx f = do+  arr0 <- readIORef (ctxNodeCustom ctx)+  let size = sizeofMutableArray arr0+  arr <-+    if idx < size+      then pure arr0+      else do+        grown <- growBoxedStoreCopy noNodeCustom arr0 size (max (idx + 1) (2 * size))+        grown <$ writeIORef (ctxNodeCustom ctx) grown+  ep <- readPrimVar (naEpoch (ctxNodeArena ctx))+  old <- readArray arr idx+  new <- f (if ncEpoch old == ep then old else noNodeCustom {ncEpoch = ep})+  writeArray arr idx $! new++-- | Change the registrations of the node widget @wid@ was declared as; a+-- widget with no node this pass registers nothing.+{-# INLINE registerAt #-}+registerAt :: Context -> WidgetId -> (NodeIdx -> NodeCustom -> IO NodeCustom) -> IO ()+registerAt ctx wid f =+  lookupNodeByWidgetId (ctxNodeArena ctx) wid >>= mapM_ (\idx -> registerAtIdx ctx idx (f idx))++-- | Attach a leaf 'ShaderNodeEntry' to node @idx@ for the current view pass.+{-# INLINE registerNodeShaderAt #-}+registerNodeShaderAt :: Context -> NodeIdx -> ShaderNodeEntry -> IO ()+registerNodeShaderAt ctx idx entry =+  registerAtIdx ctx idx (\nc -> pure nc {ncShader = Just entry})++-- | Look up the leaf 'ShaderNodeEntry' on node @idx@, if any.+{-# INLINE lookupNodeShaderAt #-}+lookupNodeShaderAt :: Context -> NodeIdx -> IO (Maybe ShaderNodeEntry)+lookupNodeShaderAt ctx idx = ncShader <$> nodeCustomAt ctx idx++-- | Attach a Tier 2 'ShaderEffectEntry' to container node @idx@ for the+-- current view pass.+{-# INLINE registerShaderEffectAt #-}+registerShaderEffectAt :: Context -> NodeIdx -> ShaderEffectEntry -> IO ()+registerShaderEffectAt ctx idx entry = do+  registerAtIdx ctx idx (\nc -> pure nc {ncEffect = Just entry})+  ep <- readPrimVar (naEpoch (ctxNodeArena ctx))+  (curEp, ns) <- readIORef (ctxEffectNodes ctx)+  writeIORef (ctxEffectNodes ctx) $! if curEp == ep then (ep, idx : ns) else (ep, [idx])++-- | Look up the Tier 2 'ShaderEffectEntry' on container node @idx@, if any.+{-# INLINE lookupShaderEffectAt #-}+lookupShaderEffectAt :: Context -> NodeIdx -> IO (Maybe ShaderEffectEntry)+lookupShaderEffectAt ctx idx = ncEffect <$> nodeCustomAt ctx idx++-- | Container node indices carrying Tier 2 shader effects in the current build+-- epoch, or empty when the frame declared none.+{-# INLINE activeEffectNodes #-}+activeEffectNodes :: Context -> IO [NodeIdx]+activeEffectNodes ctx = do+  ep <- readPrimVar (naEpoch (ctxNodeArena ctx))+  (curEp, ns) <- readIORef (ctxEffectNodes ctx)+  pure (if curEp == ep then ns else [])++-- | Read the shader capabilities reported by the active backend.+{-# INLINE getShaderCapabilities #-}+getShaderCapabilities :: Context -> IO ShaderCapabilities+getShaderCapabilities ctx = readIORef (ctxShaderCaps ctx)++-- | Add @n@ to word @w@ of 'ctxCustomPass'.+{-# INLINE bumpPass #-}+bumpPass :: Context -> Int -> Word64 -> IO ()+bumpPass ctx w n = readPrimArray (ctxCustomPass ctx) w >>= writePrimArray (ctxCustomPass ctx) w . (+ n)++-- | Register a draw builder and content version. Change the version when+-- captured content changes without a size change.+{-# INLINE registerDrawing #-}+registerDrawing :: Context -> WidgetId -> Int -> DrawingBuild -> IO ()+registerDrawing ctx wid content build =+  registerAt ctx wid $ \_ nc -> do+    when (null (ncDrawing nc)) (bumpPass ctx 2 1)+    pure nc {ncDrawing = Just (DrawingEntry content build)}++-- | The 'DrawingEntry' registered on node @idx@, if any.+{-# INLINE lookupDrawingAt #-}+lookupDrawingAt :: Context -> NodeIdx -> IO (Maybe DrawingEntry)+lookupDrawingAt ctx idx = ncDrawing <$> nodeCustomAt ctx idx++{-# INLINE sameSize #-}+sameSize :: Rect -> Rect -> Bool+sameSize a b = rectW a == rectW b && rectH a == rectH b++-- | Ops built at @r@ for a same-size @rect@: as they are, or translated and+-- written back with @store@ when the widget moved.+{-# INLINE placeOps #-}+placeOps :: Rect -> Rect -> SmallArray DrawOp -> (SmallArray DrawOp -> IO ()) -> IO (SmallArray DrawOp)+placeOps r rect ops store+  | rectX r == rectX rect && rectY r == rectY rect = pure ops+  | otherwise = do+      let moved = mapSmallArray' (shiftDrawOp (rectX rect - rectX r) (rectY rect - rectY r)) ops+      store moved+      pure moved++-- | Rebuild draw ops when the content version or width/height change. A move+-- only translates. An unversioned drawing (content 0) additionally drops its+-- cache while the widget is animating, and on the frame after, since it has+-- no other invalidation signal; versioned drawings are invalidated by their+-- content key alone.+cachedDrawingOps :: Context -> WidgetId -> Int -> Rect -> DrawingBuild -> IO (SmallArray DrawOp)+cachedDrawingOps ctx wid content rect build = do+  animated <-+    if content == 0+      then isAnimatingKey ctx wid+      else pure False+  cached <- lookupIn dcsDrawOpCache ctx wid+  -- Ops built while animating are stale on the next frame, even one whose+  -- animation ended before paint: its view drew the widget again.+  let store =+        registerIn dcsDrawOpCache (\m dc -> dc {dcsDrawOpCache = m}) ctx wid+          . DrawOpCacheEntry (if animated then complement content else content) rect+  case cached of+    Just (DrawOpCacheEntry c r ops)+      | c == content && not animated && sameSize r rect -> placeOps r rect ops store+    _ -> let ops = build rect in ops <$ store ops++-- | Reuse a derived layout while envelope, font, content key, and caller layout match.+cachedWidgetLayout ::+  Context ->+  WidgetId ->+  Double ->+  Double ->+  Float ->+  Int ->+  Layout ->+  IO Layout ->+  IO Layout+cachedWidgetLayout ctx wid dw dh lh content incoming compute = do+  cached <- lookupIn dcsDrawFitCache ctx wid+  let k = intKey wid+  case cached of+    Just e+      | dfcDw e == dw+          && dfcDh e == dh+          && dfcLh e == lh+          && dfcContent e == content+          && dfcIn e == incoming ->+          pure (dfcOut e)+    _ -> do+      out <- compute+      modifyIORef' (ctxDrawingCache ctx) $ \s ->+        s { dcsDrawFitCache = IM.insert k (DrawFitCache dw dh lh content incoming out) (dcsDrawFitCache s)+          , -- Mark the ops stale rather than deleting the entry so+            -- 'drawingOpsStale' detects the change during the damage pass.+            dcsDrawOpCache = IM.adjust (\e -> e {doeContent = complement content}) k (dcsDrawOpCache s)+          }+      pure out++-- | Cached drawing-envelope width/height if line height, content key, and+-- input layout still match. 'Nothing' requires measuring the envelope again.+lookupDrawFitEnvelope ::+  Context ->+  WidgetId ->+  Float ->+  Int ->+  Layout ->+  IO (Maybe (Double, Double))+lookupDrawFitEnvelope ctx wid lh content incoming = do+  cached <- lookupIn dcsDrawFitCache ctx wid+  pure $ case cached of+    Just e+      | dfcLh e == lh+          && dfcContent e == content+          && dfcIn e == incoming ->+          Just (dfcDw e, dfcDh e)+    _ -> Nothing++-- | Drop cached ops for drawings not registered in the current view pass.+-- A cache holds an entry only for a widget that registered, so one with no+-- more entries than this pass's registrations holds none to drop, and most+-- frames compare sizes only. One that holds more keeps the keys that+-- registered.+pruneDrawOpCache :: Context -> IO ()+pruneDrawOpCache ctx = do+  dc <- readIORef (ctxDrawingCache ctx)+  unless (IM.null (dcsDrawOpCache dc) && IM.null (dcsCustomDrawOpCache dc) && IM.null (dcsDrawFitCache dc)) $+    pruneDrawOpCaches ctx dc++-- | 'pruneDrawOpCache' once some cache holds an entry.+pruneDrawOpCaches :: Context -> DrawingCacheState -> IO ()+pruneDrawOpCaches ctx dc = do+  drawings <- fromIntegral <$> readPrimArray (ctxCustomPass ctx) 2+  customs <- fromIntegral <$> readPrimArray (ctxCustomPass ctx) 3+  let keep :: Int -> (NodeCustom -> Bool) -> IntMap a -> IO (IntMap a)+      keep live registered cache+        | IM.size cache <= live = pure cache+        | otherwise = flip IM.traverseMaybeWithKey cache $ \k v -> do+            nc <- maybe (pure noNodeCustom) (nodeCustomAt ctx) =<< lookupNodeByKey (ctxNodeArena ctx) k+            pure (if registered nc then Just v else Nothing)+  ops <- keep drawings (isJust . ncDrawing) (dcsDrawOpCache dc)+  customOps <- keep customs (isJust . ncCustom) (dcsCustomDrawOpCache dc)+  fits <- keep drawings (isJust . ncDrawing) (dcsDrawFitCache dc)+  when (not (ptrEq ops (dcsDrawOpCache dc) && ptrEq customOps (dcsCustomDrawOpCache dc) && ptrEq fits (dcsDrawFitCache dc))) $+    writeIORef (ctxDrawingCache ctx) $! dc {dcsDrawOpCache = ops, dcsCustomDrawOpCache = customOps, dcsDrawFitCache = fits}++-- | Register an interaction-aware painter with the default cursor and+-- repaint margin. A nonzero content key must cover its external inputs; zero+-- requests rebuilding and comparison each frame.+{-# INLINE registerCustomDrawing #-}+registerCustomDrawing :: Context -> WidgetId -> Int -> CustomDrawBuild -> IO ()+registerCustomDrawing ctx wid content build =+  registerCustomEntry ctx wid (CustomDrawingEntry content build Nothing 0 False KeysNone)++-- | Store the widget's 'CustomDrawingEntry', replacing any earlier one.+{-# INLINE registerCustomEntry #-}+registerCustomEntry :: Context -> WidgetId -> CustomDrawingEntry -> IO ()+registerCustomEntry ctx wid entry =+  registerAt ctx wid $ \idx nc -> do+    when (null (ncCustom nc)) $ do+      bumpPass ctx 3 1+      nt <- getNodeType (ctxNodeArena ctx) idx+      when (nt /= NodeDrawing) (writePrimArray (ctxCustomPass ctx) 0 1)+    pure nc {ncCustom = Just entry}++-- | The 'CustomDrawingEntry' registered for the widget, if any.+{-# INLINE lookupCustomDrawing #-}+lookupCustomDrawing :: Context -> WidgetId -> IO (Maybe CustomDrawingEntry)+lookupCustomDrawing ctx wid = ncCustom <$> nodeCustomOf ctx wid++-- | The 'CustomDrawingEntry' registered on node @idx@, if any.+{-# INLINE lookupCustomDrawingAt #-}+lookupCustomDrawingAt :: Context -> NodeIdx -> IO (Maybe CustomDrawingEntry)+lookupCustomDrawingAt ctx idx = ncCustom <$> nodeCustomAt ctx idx++-- | Whether a custom drawing was registered this pass on a node that is no+-- drawing (a pane grid's focus ring), which paint builds afresh.+customDrawingOffNode :: Context -> IO Bool+customDrawingOffNode ctx = (/= 0) <$> readPrimArray (ctxCustomPass ctx) 0++-- | Whether a cache entry matches the given content key, size, draw context,+-- and font generation (ignoring origin, which only translates cached ops).+{-# INLINE customEntryMatches #-}+customEntryMatches :: CustomDrawOpCacheEntry -> Int -> Rect -> CustomDrawContext -> Int -> Bool+customEntryMatches e content rect cdc gen =+  customEntrySized e content rect gen+    && cdeHovered e == cdcHovered cdc+    && cdePressed e == cdcPressed cdc+    && cdeFocused e == cdcFocused cdc+    && cdeActive e == cdcActive cdc+    && cdeDisabled e == cdcDisabled cdc++-- | 'customEntryMatches' without the interaction state: the content key, the+-- size and the metrics generation.+{-# INLINE customEntrySized #-}+customEntrySized :: CustomDrawOpCacheEntry -> Int -> Rect -> Int -> Bool+customEntrySized e content rect gen =+  cdeContent e == content+    && sameSize (cdeBounds e) rect+    && cdeGen e == gen++-- | Draw ops for a custom widget's paint: the ops 'refreshCustomDrawingOps'+-- settled on this frame, translated if the widget only moved, else a fresh+-- build with the draw context from @newCdc@.+--+-- The refresh ran against this frame's interaction state, which nothing+-- changes before paint, so an entry with this content, size and metrics is+-- this frame's and paint need not build a context to check it. Two nodes+-- sharing an id at different sizes miss here, and the one painted second+-- rebuilds.+cachedCustomDrawingOps ::+  Context ->+  WidgetId ->+  Int ->+  Rect ->+  IO CustomDrawContext ->+  CustomDrawBuild ->+  IO (SmallArray DrawOp)+cachedCustomDrawingOps ctx wid content rect newCdc build = do+  gen <- readIORef (ctxMetricGen ctx)+  cached <- lookupIn dcsCustomDrawOpCache ctx wid+  case cached of+    Just e+      | customEntrySized e content rect gen ->+          placeOps (cdeBounds e) rect (cdeOps e) $ \ops ->+            registerIn dcsCustomDrawOpCache (\m dc -> dc {dcsCustomDrawOpCache = m}) ctx wid e {cdeBounds = rect, cdeOps = ops}+    _ -> do+      cdc <- newCdc+      let ops = build cdc rect+      storeCustomDrawingOps ctx wid content rect cdc gen ops+      pure ops++-- | Update the cached draw ops for a custom widget and return whether the+-- output changed in place (at the same bounds).+--+-- A non-zero content key skips rebuilding when the key, size, interaction+-- state, and font generation all match the cached entry (callers that depend+-- on an animation value must include it in the key). A key of 0 always+-- rebuilds and compares the resulting 'DrawOp' array.+--+-- When a rebuild runs, damage is determined by comparing the new ops against+-- the previous ops at the same rect; new, moved, or resized widgets return+-- 'False' because rect-diff damage already covers them.+refreshCustomDrawingOps ::+  Context ->+  WidgetId ->+  Int ->+  Rect ->+  CustomDrawContext ->+  CustomDrawBuild ->+  IO Bool+refreshCustomDrawingOps ctx wid content rect cdc build = do+  gen <- readIORef (ctxMetricGen ctx)+  cached <- lookupIn dcsCustomDrawOpCache ctx wid+  let keyed = content /= 0+  case cached of+    -- A keyed widget that only moved keeps its ops: paint translates them, and+    -- the move is damaged by the rect delta.+    Just e | keyed && customEntryMatches e content rect cdc gen -> pure False+    _ -> do+      let ops = build cdc rect+          changed = case cached of+            Just e | cdeBounds e == rect -> cdeOps e /= ops+            _ -> False+      storeCustomDrawingOps ctx wid content rect cdc gen ops+      pure changed++storeCustomDrawingOps :: Context -> WidgetId -> Int -> Rect -> CustomDrawContext -> Int -> SmallArray DrawOp -> IO ()+storeCustomDrawingOps ctx wid content rect cdc gen ops =+  registerIn dcsCustomDrawOpCache (\m dc -> dc {dcsCustomDrawOpCache = m}) ctx wid $+    CustomDrawOpCacheEntry content rect (cdcHovered cdc) (cdcPressed cdc) (cdcFocused cdc) (cdcActive cdc) (cdcDisabled cdc) gen ops++-- | Whether a versioned drawing's cached ops are for another version at the+-- same rect. Paint rebuilds them; the pixels they covered must repaint too,+-- and checking the version costs nothing next to building the ops here.+drawingOpsStale :: Context -> WidgetId -> Int -> Rect -> IO Bool+drawingOpsStale ctx wid content rect = do+  cached <- lookupIn dcsDrawOpCache ctx wid+  pure $ case cached of+    Just DrawOpCacheEntry {doeContent = c, doeBounds = r} -> c /= content && r == rect+    Nothing -> False++-- | Register a widget measurement callback for the current view pass.+{-# INLINE registerCustomMeasure #-}+registerCustomMeasure :: Context -> WidgetId -> CustomMeasureFn -> IO ()+registerCustomMeasure ctx wid fn =+  registerAt ctx wid $ \idx nc -> do+    when (null (ncMeasure nc)) (bumpPass ctx 1 (mix64 (fromIntegral idx) 0x4d454153))+    pure nc {ncMeasure = Just fn}++-- | Registered measurement callback, or 'Nothing' for default layout sizing.+{-# INLINE lookupCustomMeasure #-}+lookupCustomMeasure :: Context -> WidgetId -> IO (Maybe CustomMeasureFn)+lookupCustomMeasure ctx wid = ncMeasure <$> nodeCustomOf ctx wid++-- | The measurement callback registered on node @idx@, if any.+{-# INLINE lookupCustomMeasureAt #-}+lookupCustomMeasureAt :: Context -> NodeIdx -> IO (Maybe CustomMeasureFn)+lookupCustomMeasureAt ctx idx = ncMeasure <$> nodeCustomAt ctx idx++-- | A signature of the nodes with a measurement callback registered this+-- view pass: a sum of a hash of each one's index, so the layout cache can+-- tell when one appears or goes.+customMeasureHooks :: Context -> IO Word64+customMeasureHooks ctx = readPrimArray (ctxCustomPass ctx) 1++-- | Registered repaint margin, or 'Nothing' when no override exists.+{-# INLINE lookupCustomDamageSlop #-}+lookupCustomDamageSlop :: Context -> WidgetId -> IO (Maybe Float)+lookupCustomDamageSlop ctx wid =+  mfilter (> 0) . fmap cdrDamageSlop <$> lookupCustomDrawing ctx wid++-- | Clear per-pass registrations while retaining compiled ops and fitted+-- layouts. Call before rebuilding the view, then prune caches against new registrations.+resetDrawingScopeCache :: Context -> IO ()+resetDrawingScopeCache ctx = do+  setPrimArray (ctxCustomPass ctx) 0 customPassWords 0+  modifyIORef' (ctxDrawingCache ctx) $ \dc ->+    dc+      { dcsPopupConfigs = IM.empty+      , dcsDropdowns = IM.empty+      , dcsHoverZones = []+      }
+ lib/NanoUI/Internal/Context/Overlay.hs view
@@ -0,0 +1,153 @@+-- | Modal and floating-panel state, and which layer the pointer reaches.+module NanoUI.Internal.Context.Overlay+  ( textInputEditActive+  , modalActive+  , overlayConsumesQuit+  , escapeReserved+  , markEscapeConsumed+  , markTabConsumed+  , tabConsumed+  , pointerBlockedByModal+  , routedInput+  , floatingLayerAt+  , beginModal+  , endModal+  , beginFrameModal+  , modalDamageFlip+  , takeKeyPress+  ) where++import Data.IORef (readIORef)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.Maybe (isJust)++import NanoUI.Internal.Context.Core+import NanoUI.Internal.Context.Types (Context (..), InteractionState (..), OverlayState (..), PointerRoute (..))+import NanoUI.Internal.Id (hashWidgetId)+import NanoUI.Internal.Input (DropEvent (..), DropType (..), Input (..), Key (KeyEscape), Pressable (..), offWindow, withoutPointer)+import NanoUI.Internal.Store (anySelectOpen)+import NanoUI.Internal.Types (V2, rectContains)++-- | Whether any widget has keyboard focus or a text-edit menu is open.+-- This checks the focus id, not the focused node's type.+textInputEditActive :: Context -> IO Bool+textInputEditActive ctx = do+  focus <- readIORef (ctxFocusId ctx)+  menu <- getsInteraction ctx isTextInputMenu+  pure (hashWidgetId focus /= 0 || isJust menu)++-- | Whether a modal is declared this frame or was active on the previous frame.+modalActive :: Context -> IO Bool+modalActive ctx = getsOverlay ctx (\os -> osModalWasActive os || osModalActive os)++-- | Whether this input contains Escape already consumed by an overlay.+overlayConsumesQuit :: Context -> Input -> IO Bool+overlayConsumesQuit ctx inp = do+  consumed <- getsOverlay ctx osEscapeConsumed+  pure (pressedOnceIn KeyEscape inp && consumed)++-- | Whether this frame's Escape is spoken for: something took it already+-- ('markEscapeConsumed'), or took its press and it is still down or just+-- released, or an open text-edit menu, an open dropdown or a focused combo+-- box's list ('isFocusCombo') closes on it. The view's Escape consumers ask+-- this, so none acts on the Escape such a menu takes, wherever it is+-- declared.+escapeReserved :: Context -> IO Bool+escapeReserved ctx = do+  taken <- getsOverlay ctx osEscapeConsumed+  menuOrCombo <- getsInteraction ctx (\s -> isJust (isTextInputMenu s) || isFocusCombo s)+  dropdown <- anySelectOpen <$> getStore ctx+  pure (taken || menuOrCombo || dropdown)++-- | Mark Escape as handled so closing an overlay does not also quit the app.+markEscapeConsumed :: Context -> IO ()+markEscapeConsumed ctx = modifyOverlay ctx (\os -> os {osEscapeConsumed = True})++-- | Keep this frame's Tab from moving focus: the widget holding the keyboard+-- acts on it itself.+markTabConsumed :: Context -> IO ()+markTabConsumed ctx = modifyOverlay ctx (\os -> os {osTabConsumed = True})++-- | Whether something took this frame's Tab with 'markTabConsumed'.+tabConsumed :: Context -> IO Bool+tabConsumed ctx = getsOverlay ctx osTabConsumed++-- | Whether a modal is up and the view being declared is outside it.+pointerBlockedByModal :: Context -> IO Bool+pointerBlockedByModal ctx =+  getsOverlay ctx (\os -> osModalDepth os <= 0 && (osModalWasActive os || osModalActive os))++-- | Filter frame input for widgets in @layer@ (0 for the base page, or a+-- floating panel's key): preserves pointer state only when pointer input is+-- routed to @layer@ and not blocked by a modal. An OS drag moves no pointer,+-- so its drops go by where they land: a layer that is not on top there, or+-- that a modal blocks, sees the drag off the window.+routedInput :: Context -> Int -> Input -> IO Input+routedInput ctx layer inp = do+  routed <-+    getsInteraction ctx isPointerRoute >>= \case+      RouteLayer routed | routed == layer -> unlessBlocked+      RouteDropdown routed | routed == layer -> unlessBlocked+      _ -> pure (withoutPointer inp)+  if null (inputDrops inp)+    then pure routed+    else do+      blocked <- pointerBlockedByModal ctx+      let own ev = case dropEventPos ev of+            Just p | dropEventType ev == DropPosition -> do+              top <- floatingLayerAt ctx p+              pure (if blocked || top /= layer then ev {dropEventPos = Just offWindow} else ev)+            _ -> pure ev+      drops <- traverse own (inputDrops inp)+      pure routed {inputDrops = drops}+  where+    unlessBlocked = do+      blocked <- pointerBlockedByModal ctx+      pure (if blocked then withoutPointer inp else inp)++-- | The layer on top at @mouse@, going by where the floating panels were last+-- frame: the last panel declared that holds the point, or the page.+floatingLayerAt :: Context -> V2 -> IO Int+floatingLayerAt ctx mouse = do+  os <- readIORef (ctxOverlayState ctx)+  let rects = osPrevFloatingRects os+      hit k = maybe False (`rectContains` mouse) (IM.lookup k rects)+  pure (foldl' (\acc k -> if hit k then k else acc) 0 (osPrevFloatingOrder os))++-- | Increment modal nesting depth and mark a modal active for this frame.+beginModal :: Context -> IO ()+beginModal ctx =+  modifyOverlay ctx (\os -> os {osModalActive = True, osModalDepth = osModalDepth os + 1})++-- | Leave modal construction. Decreases depth without clearing the frame's active flag.+endModal :: Context -> IO ()+endModal ctx =+  modifyOverlay ctx (\os -> os {osModalDepth = max 0 (osModalDepth os - 1)})++-- | Save the previous modal flag, then clear current depth and Escape, Tab+-- and key consumption.+beginFrameModal :: Context -> IO ()+beginFrameModal ctx =+  modifyOverlay ctx $ \os ->+    os+      { osModalWasActive = osModalActive os+      , osModalActive = False+      , osModalDepth = 0+      , osEscapeConsumed = False+      , osTabConsumed = False+      , osKeysTaken = IS.empty+      }++-- | Claim the key press at index @i@ of this frame's keys for a shortcut.+-- Returns 'False' if another shortcut already claimed it.+takeKeyPress :: Context -> Int -> IO Bool+takeKeyPress ctx i = do+  taken <- getsOverlay ctx (IS.member i . osKeysTaken)+  if taken+    then pure False+    else True <$ modifyOverlay ctx (\os -> os {osKeysTaken = IS.insert i (osKeysTaken os)})++-- | Whether modal presence changed since the preceding frame.+modalDamageFlip :: Context -> IO Bool+modalDamageFlip ctx = getsOverlay ctx (\os -> osModalWasActive os /= osModalActive os)
+ lib/NanoUI/Internal/Context/Scroll.hs view
@@ -0,0 +1,528 @@+-- | Scroll offsets and links kept in the widget store, the+-- wheel and glide tuning kept in the context, and the commands that move a+-- scroller: to an offset, by a delta or page, or onto a widget.+module NanoUI.Internal.Context.Scroll+  ( getScrollOffset+  , setScrollOffset+  , getScrollOffset2D+  , setScrollOffset2D+  , linkScrollAxes+    -- * Tuning+  , ScrollTuning (..)+  , defaultScrollTuning+  , getScrollTuning+  , setScrollTuning+  , getScrollStep+  , setScrollStep+  , resolveScrollStep+    -- * Geometry+  , ScrollAxes (..)+  , ScrollMetrics (..)+  , getScrollMetrics+  , readScrollMetrics+  , cacheScrollMetrics+  , placeScrollContent+  , beginScrollMetrics+  , getScrollOffsetIn+  , setScrollOffsetIn+  , setScrollOffsetPending+  , applyPendingScrollOffset+    -- * Commands+  , ScrollBehavior (..)+  , ScrollAlign (..)+  , scrollTo+  , scrollBy+  , scrollPages+  , scrollToStart+  , scrollToEnd+  , scrollIntoView+  , scrollRectIntoView+    -- * Glide+  , applyScrollTarget+  , scrollTargetOffset+  , scrollGliding+  , clampScrollGlide+  , clampScrollOffset++  , stepScrollGlides+  ) where++import Control.Monad (forM_, unless, when)+import Data.IORef (modifyIORef', readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS++import Data.Maybe (fromMaybe)+import NanoUI.Internal.Context.Core (damageWidget, modifyStore, getPrevRect, getStore, publishLayoutSlots, recordLayoutRead, setStore, writeSlots)+import NanoUI.Internal.Context.Types+import NanoUI.Internal.Draw qualified as Draw+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Store (SlotSpec, SlotWrites, WidgetStore, deleteSpec, fieldFloat, findSlot, findSpec, insertSpec, lookupSpec, ownSlotSpec, slotWriteOr, specKey, specWrite, specWriteOr)+import NanoUI.Internal.Store.Slots (slotScrollAxes, slotScrollCross, slotScrollLinkX, slotScrollLinkY, slotScrollPending, slotScrollRange, slotScrollStep, slotTextAreaScroll)+import NanoUI.Internal.Types (DamageBounds (..), Rect (..), V2 (..), clamp, onGrid, v2Add, v2X, v2Y)++{-# INLINE snapScrollOffset #-}+snapScrollOffset :: Context -> Float -> IO Float+snapScrollOffset ctx v = do+  s <- Draw.getDrawSnapScale (ctxDrawArena ctx)+  pure (onGrid s v)++-- | A scroller's stored offset. A text area keeps both axes in its own point+-- slot. A scroll container keeps its main axis (the vertical one when it+-- scrolls both) under its key and the other under 'SlotScrollCross', so a 1D+-- scroller's offset reads @(cross, main)@ and a 2D one's @(x, y)@. Floats keep+-- a scroll frame a 'storeFloat'-only change, which the damage pass clips.+{-# INLINE storedScrollOffset #-}+storedScrollOffset :: Int -> WidgetStore -> V2+storedScrollOffset key s =+  fromMaybe+    (V2 (findSpec slotScrollCross 0 key s) (findSlot fieldFloat 0 key s))+    (lookupSpec slotTextAreaScroll key s)++-- | Pixel-snapped main-axis offset of a 1D scroller, or vertical offset of a+-- text area/2D scroller. Defaults to zero before state exists.+getScrollOffset :: Context -> WidgetId -> IO Float+getScrollOffset ctx wid = snapScrollOffset ctx . v2Y . storedScrollOffset (intKey wid) =<< getStore ctx++-- | Set the main-axis scroll offset and cancel any active glide.+setScrollOffset :: Context -> WidgetId -> Float -> IO ()+setScrollOffset ctx wid off = do+  cancelScrollGlide ctx wid+  writeScrollOffset ctx wid off++writeScrollOffset :: Context -> WidgetId -> Float -> IO ()+writeScrollOffset ctx wid off = do+  V2 x _ <- storedScrollOffset (intKey wid) <$> getStore ctx+  writeScrollOffset2D ctx wid (V2 x off)++-- | Pixel-snapped x/y offset for text areas and 2D scrollers. For a 1D+-- scroller, the fallback stores cross-axis in x and main-axis in y, so a row+-- scroller's offset reads @(cross, main)@: its horizontal offset is in y.+-- 'getScrollMetrics' and the scroll commands use window axes for every+-- scroller.+getScrollOffset2D :: Context -> WidgetId -> IO V2+getScrollOffset2D ctx wid = do+  V2 x y <- storedScrollOffset (intKey wid) <$> getStore ctx+  s <- Draw.getDrawSnapScale (ctxDrawArena ctx)+  pure (V2 (onGrid s x) (onGrid s y))++-- | Move a scroller to an offset on both axes, in the order+-- 'getScrollOffset2D' reads them: @(cross, main)@ for a 1D row scroller.+-- Cancels a glide in flight. 'scrollTo' takes window axes for every scroller.+setScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()+setScrollOffset2D ctx wid off = do+  cancelScrollGlide ctx wid+  writeScrollOffset2D ctx wid off++writeScrollOffset2D :: Context -> WidgetId -> V2 -> IO ()+writeScrollOffset2D ctx wid off@(V2 x y) = do+  store <- getStore ctx+  let key = intKey wid+      -- A linked scroller ('linkScrollAxes') follows along: the header's+      -- main axis is the body's cross axis.+      {-# INLINE mirror #-}+      mirror :: SlotSpec Int -> SlotSpec Float -> Float -> SlotWrites+      mirror link to v =+        let k = findSpec link 0 key store+         in if k == 0 then mempty else specWriteOr to 0 k v+  -- Text areas only reach the first branch because `textAreaWith` seeds this+  -- slot at init; without the seed a freshly mounted editor falls through to+  -- the container slots below and its offsets are never rendered. Scroll-offset+  -- damage only tracks scroll containers, so a text area damages its own bounds.+  case lookupSpec slotTextAreaScroll key store of+    Just cur ->+      when (cur /= off) $ do+        setStore ctx (insertSpec slotTextAreaScroll key off store)+        damageWidget ctx wid DamageSelf+    Nothing ->+      writeSlots ctx $+        slotWriteOr fieldFloat 0 key y+          <> specWriteOr slotScrollCross 0 key x+          <> mirror slotScrollLinkX (ownSlotSpec fieldFloat) x+          <> mirror slotScrollLinkY slotScrollCross y++-- | Link a two-axis body with a separate horizontal scroller, such as a table+-- header. Arguments are body id then horizontal id; synchronises their x offsets.+linkScrollAxes :: Context -> WidgetId -> WidgetId -> IO ()+linkScrollAxes ctx yWid xWid = do+  let yKey = intKey yWid+      xKey = intKey xWid+  writeSlots ctx $+    specWrite slotScrollLinkX yKey xKey+      <> specWrite slotScrollLinkY xKey yKey+  store <- getStore ctx+  let V2 x2 y = storedScrollOffset yKey store+      x1 = findSlot fieldFloat 0 xKey store+      x = if x2 == 0 && x1 /= 0 then x1 else x2+  when (x /= x2 || x /= x1) $+    setScrollOffset2D ctx yWid (V2 x y)++-- =============================================================================+-- Tuning+-- =============================================================================++-- | Wheel step and glide time for every scroller in this context.+getScrollTuning :: Context -> IO ScrollTuning+getScrollTuning ctx = ssTuning <$> readIORef (ctxScrollState ctx)++-- | Set the wheel step and glide time. Raising 'scrollWheelStep' makes the+-- wheel cover more ground per notch; a nonzero 'scrollSmoothTime' turns every+-- wheel notch and every 'ScrollSmooth' command into a glide.+setScrollTuning :: Context -> ScrollTuning -> IO ()+setScrollTuning ctx tuning =+  modifyIORef' (ctxScrollState ctx) $ \st -> st {ssTuning = tuning}++-- | This scroller's own wheel step, or @0@ when it follows the context's.+getScrollStep :: Context -> WidgetId -> IO Float+getScrollStep ctx wid = findSpec slotScrollStep 0 (intKey wid) <$> getStore ctx++-- | Give one scroller its own wheel step, in pixels per notch. @0@ puts it+-- back on the context's step. A list whose rows are a fixed height reads best+-- at a whole number of rows per notch.+setScrollStep :: Context -> WidgetId -> Float -> IO ()+setScrollStep ctx wid px = writeSlots ctx (specWriteOr slotScrollStep 0 (intKey wid) px)++-- | Pixels one wheel notch scrolls this scroller.+resolveScrollStep :: Context -> WidgetId -> IO Float+resolveScrollStep ctx wid = do+  own <- getScrollStep ctx wid+  if own > 0+    then pure own+    else max 1 . scrollWheelStep <$> getScrollTuning ctx++-- =============================================================================+-- Geometry+-- =============================================================================++-- | Scroll geometry from the most recent layout pass. Offsets and ranges use+-- window axes (@x@ horizontal, @y@ vertical) regardless of the scroller's+-- primary direction.+data ScrollMetrics = ScrollMetrics+  { scrollViewport :: !Rect+  -- ^ The visible content, in window coordinates, inside padding and clear of+  -- the scrollbars.+  , scrollRange :: !V2+  -- ^ Largest offset each axis reaches. @0@ on an axis that does not scroll.+  , scrollOffset :: !V2+  -- ^ The current offset, which the wheel, a glide or a command may have+  -- moved since that layout.+  , scrollAxes :: !ScrollAxes+  }+  deriving (Eq, Show)++-- | Geometry of the scroller @wid@, or 'Nothing' before it has been laid out.+-- Reads the last frame's layout, so it is safe to call while building the+-- next one, from the UI thread. A view that reads it gets another frame when+-- this frame's layout changes the metrics, so rows it picked from them catch+-- up with a resize. From a view, 'NanoUI.getScrollMetrics' is the same.+getScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)+getScrollMetrics ctx wid = do+  m <- readScrollMetrics ctx wid+  recordLayoutRead ctx (specKey slotScrollRange (intKey wid)) ((/= m) <$> readScrollMetrics ctx wid)+  pure m++-- | Read 'ScrollMetrics' without recording a layout dependency (used by scroll+-- commands rather than view construction).+readScrollMetrics :: Context -> WidgetId -> IO (Maybe ScrollMetrics)+readScrollMetrics ctx wid = do+  s <- getStore ctx+  views <- ssViews <$> readIORef (ctxScrollState ctx)+  let key = intKey wid+  case (IM.lookup key views, lookupSpec slotScrollRange key s) of+    (Just view, Just range) -> do+      let axes = toEnum (findSpec slotScrollAxes 0 key s)+      off <- getScrollOffsetIn ctx wid axes+      pure $+        Just+          ScrollMetrics+            { scrollViewport = svViewport view+            , scrollRange = range+            , scrollOffset = off+            , scrollAxes = axes+            }+    _ -> pure Nothing++-- | Start a frame's geometry pass: the first scroll node to publish under a+-- widget id wins for that frame.+beginScrollMetrics :: Context -> IO ()+beginScrollMetrics ctx =+  modifyIORef' (ctxScrollState ctx) $ \st ->+    if IS.null (ssCached st) then st else st {ssCached = IS.empty}++-- | Publish a scroll node's viewport ('ssViews') and its range (to the store)+-- for the current frame. If multiple nodes share @wid@ (such as a table's+-- frozen pane and body), only the first node to call this after+-- 'beginScrollMetrics' writes its metrics and returns 'True'; otherwise both+-- panes would overwrite each other's viewport every frame. Does not mark the+-- context dirty ('publishLayoutSlots'); views that read the metrics register+-- a layout read via 'getScrollMetrics'.+cacheScrollMetrics :: Context -> WidgetId -> ScrollAxes -> Rect -> V2 -> IO Bool+cacheScrollMetrics ctx wid axes viewport range = do+  let key = intKey wid+  st <- readIORef (ctxScrollState ctx)+  let fresh = not (IS.member key (ssCached st))+      -- The content keeps the offset it was placed at until+      -- 'placeScrollContent' records this layout's.+      views = case IM.lookup key (ssViews st) of+        Just view | svViewport view == viewport -> ssViews st+        old -> IM.insert key (ScrollView viewport (maybe (V2 0 0) svPlaced old)) (ssViews st)+  fresh <$ when fresh (do+    writeIORef (ctxScrollState ctx) $! st {ssCached = IS.insert key (ssCached st), ssViews = views}+    -- A range that just shrank (a filtered list, a narrower window) would+    -- leave a glide heading past the new end.+    clampScrollGlide ctx wid range+    publishLayoutSlots ctx $+      specWrite slotScrollRange key range+        <> specWrite slotScrollAxes key (fromEnum axes))++-- | Record the offset, in window axes, that this layout placed scroller+-- @wid@'s content at, once 'cacheScrollMetrics' has published its viewport.+-- 'scrollIntoView' reads it with the last frame's rects.+placeScrollContent :: Context -> WidgetId -> Float -> Float -> IO ()+placeScrollContent ctx wid ox oy = do+  st <- readIORef (ctxScrollState ctx)+  let key = intKey wid+  case IM.lookup key (ssViews st) of+    Just view+      | svPlaced view /= V2 ox oy ->+          writeIORef (ctxScrollState ctx) $! st {ssViews = IM.insert key view {svPlaced = V2 ox oy} (ssViews st)}+    _ -> pure ()++-- | A 1D row scroller keeps its offset in the main-axis slot, so window and+-- stored axes are swapped for it and identical for everything else. The swap+-- is its own inverse.+{-# INLINE swapAxes #-}+swapAxes :: ScrollAxes -> V2 -> V2+swapAxes ScrollAxisX (V2 x y) = V2 y x+swapAxes _ v = v++-- | Queue a window-axis scroll offset for a scroller that has not been laid+-- out yet; 'applyPendingScrollOffset' applies it once the scroller's+-- 'ScrollAxes' are known. Cancels any active glide.+setScrollOffsetPending :: Context -> WidgetId -> V2 -> IO ()+setScrollOffsetPending ctx wid off = do+  cancelScrollGlide ctx wid+  modifyStore ctx (insertSpec slotScrollPending (intKey wid) off)++-- | Apply any pending offset queued by 'setScrollOffsetPending' using the+-- scroller's resolved axes.+applyPendingScrollOffset :: Context -> WidgetId -> ScrollAxes -> IO ()+applyPendingScrollOffset ctx wid axes = do+  store <- getStore ctx+  let key = intKey wid+  case lookupSpec slotScrollPending key store of+    Nothing -> pure ()+    Just off -> do+      writeIORef (ctxStore ctx) $! deleteSpec slotScrollPending key store+      setScrollOffsetIn ctx wid axes off++-- | This scroller's offset in window axes.+getScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> IO V2+getScrollOffsetIn ctx wid axes = swapAxes axes <$> getScrollOffset2D ctx wid++-- | Set a scroller's offset in window axes and cancel any active glide. A 1D+-- scroller ignores the inactive axis.+setScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> V2 -> IO ()+setScrollOffsetIn ctx wid axes off = do+  cancelScrollGlide ctx wid+  writeScrollOffsetIn ctx wid axes off++writeScrollOffsetIn :: Context -> WidgetId -> ScrollAxes -> V2 -> IO ()+writeScrollOffsetIn ctx wid axes off+  | axes == ScrollAxisXY = writeScrollOffset2D ctx wid off+  | otherwise = writeScrollOffset ctx wid (v2Y (swapAxes axes off))++-- =============================================================================+-- Commands+-- =============================================================================++-- | Whether a scroll lands on its target at once or glides onto it.+-- 'ScrollSmooth' still lands at once when the context's 'scrollSmoothTime' is+-- @0@, so one setting turns smooth scrolling on for the whole app.+data ScrollBehavior = ScrollInstant | ScrollSmooth+  deriving (Eq, Show)++-- | Where a widget ends up in the viewport once it is scrolled into view.+data ScrollAlign+  = -- | Move as little as possible: nothing at all when it is already whole.+    ScrollNearest+  | -- | Against the leading edge, at the top or left.+    ScrollStart+  | ScrollCenter+  | -- | Against the trailing edge, at the bottom or right.+    ScrollEnd+  deriving (Eq, Show)++-- | Scroll to an absolute offset, clamped to the scroller's range.+scrollTo :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()+scrollTo ctx wid off = scrollToward ctx wid (\_ -> pure off)++-- | Scroll by a pixel delta. When a glide is already in flight, adds to the+-- glide's target offset so rapid steps accumulate.+scrollBy :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()+scrollBy ctx wid delta = scrollToward ctx wid (\m -> headedBy ctx wid m delta)++-- | Scroll by whole viewports: @V2 0 1@ is one page down, @V2 0 (-0.5)@ half+-- a page up.+scrollPages :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()+scrollPages ctx wid (V2 px py) = scrollToward ctx wid $ \m ->+  let Rect _ _ vw vh = scrollViewport m in headedBy ctx wid m (V2 (px * vw) (py * vh))++-- | Where the scroller is headed ('scrollTargetOffset'), moved by @delta@.+headedBy :: Context -> WidgetId -> ScrollMetrics -> V2 -> IO V2+headedBy ctx wid m delta = (`v2Add` delta) <$> scrollTargetOffset ctx wid (scrollOffset m)++-- | Scroll back to the top (and left).+scrollToStart :: Context -> WidgetId -> ScrollBehavior -> IO ()+scrollToStart ctx wid = scrollTo ctx wid (V2 0 0)++-- | Scroll to the end of the content.+scrollToEnd :: Context -> WidgetId -> ScrollBehavior -> IO ()+scrollToEnd ctx wid = scrollTo ctx wid (V2 (1 / 0) (1 / 0)) -- clamped to the range++-- | Scroll @target@ into the viewport of the scroller @wid@ it is built+-- inside. Both widgets are read from the last frame's layout, so a widget+-- that was not built then, such as a row a virtualized list left out, cannot+-- be found; scroll to its content rectangle with 'scrollRectIntoView' instead.+scrollIntoView :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()+scrollIntoView ctx wid target align behavior = do+  mView <- IM.lookup (intKey wid) . ssViews <$> readIORef (ctxScrollState ctx)+  mRect <- getPrevRect ctx target+  case (mView, mRect) of+    -- The offset the last layout placed the content at, not the live one,+    -- which the wheel or a glide may have moved since the rects were taken.+    (Just (ScrollView (Rect vx vy _ _) (V2 ox oy)), Just (Rect rx ry rw rh)) ->+      scrollRectIntoView ctx wid (Rect (rx - vx + ox) (ry - vy + oy) rw rh) align behavior+    _ -> pure ()++-- | Scroll a rectangle of the content into view. The rectangle is in content+-- coordinates: the origin is where the content starts, which is where the+-- viewport shows it at offset @0@.+scrollRectIntoView :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()+scrollRectIntoView ctx wid (Rect rx ry rw rh) align = scrollToward ctx wid $ \m -> do+  let Rect _ _ vw vh = scrollViewport m+      V2 ox oy = scrollOffset m+  pure (V2 (alignAxis align vw rx rw ox) (alignAxis align vh ry rh oy))++-- | Target offset along one axis for a content span @(start, size)@ in a+-- viewport of @viewSize@.+alignAxis :: ScrollAlign -> Float -> Float -> Float -> Float -> Float+alignAxis align viewSize start size cur =+  case align of+    ScrollStart -> start+    ScrollEnd -> start + size - viewSize+    ScrollCenter -> start + (size - viewSize) / 2+    ScrollNearest+      | start < cur -> start+      | start + size > cur + viewSize -> min start (start + size - viewSize)+      | otherwise -> cur++-- | Hold an offset inside @0@ and the scroller's range on each axis.+{-# INLINE clampScrollOffset #-}+clampScrollOffset :: V2 -> V2 -> V2+clampScrollOffset (V2 mx my) (V2 x y) = V2 (clamp 0 mx x) (clamp 0 my y)++-- | Zero the inactive axis of a 1D scroller. Linked table panes share+-- cross-axis slots, so a vertical scroller can have a non-zero horizontal+-- offset in the store that its own glide will never move.+{-# INLINE projectAxes #-}+projectAxes :: ScrollAxes -> V2 -> V2+projectAxes axes (V2 x y) =+  case axes of+    ScrollAxisY -> V2 0 y+    ScrollAxisX -> V2 x 0+    ScrollAxisXY -> V2 x y++-- | Move the scroller to the offset computed by @pick@ from its metrics,+-- clamped to its range. No-op before the first layout pass.+scrollToward :: Context -> WidgetId -> (ScrollMetrics -> IO V2) -> ScrollBehavior -> IO ()+scrollToward ctx wid pick behavior = do+  mMetrics <- readScrollMetrics ctx wid+  forM_ mMetrics $ \m -> do+    target <- pick m+    applyScrollTarget ctx wid (scrollAxes m) (clampScrollOffset (scrollRange m) target) behavior++-- =============================================================================+-- Glide+-- =============================================================================++-- | Move a scroller to a clamped window-axis target, starting a smooth glide+-- when @behavior@ is 'ScrollSmooth' and 'scrollSmoothTime' is positive.+applyScrollTarget :: Context -> WidgetId -> ScrollAxes -> V2 -> ScrollBehavior -> IO ()+applyScrollTarget ctx wid axes target0 behavior = do+  st <- readIORef (ctxScrollState ctx)+  cur <- getScrollOffsetIn ctx wid axes+  let target = projectAxes axes target0+      instant = behavior == ScrollInstant || scrollSmoothTime (ssTuning st) <= 0+  if instant || nearOffset (projectAxes axes cur) target+    then setScrollOffsetIn ctx wid axes target+    else+      writeIORef (ctxScrollState ctx) $!+        st {ssGlides = IM.insert (intKey wid) (ScrollGlide wid target axes) (ssGlides st)}++-- | Where the scroller is headed: the glide's target if one is in flight, and+-- @fallback@ (normally the current offset) if not. Deltas add onto this so+-- that notches arriving mid-glide are not swallowed.+scrollTargetOffset :: Context -> WidgetId -> V2 -> IO V2+scrollTargetOffset ctx wid fallback = do+  st <- readIORef (ctxScrollState ctx)+  pure (maybe fallback sgTarget (IM.lookup (intKey wid) (ssGlides st)))++-- | Whether a smooth-scroll target is pending for this widget.+scrollGliding :: Context -> WidgetId -> IO Bool+scrollGliding ctx wid =+  IM.member (intKey wid) . ssGlides <$> readIORef (ctxScrollState ctx)++-- | Clamp an active glide's target to a newly measured range. Without this,+-- shrinking the content mid-glide (e.g. filtering a list) leaves the glide+-- coasting past the new end.+clampScrollGlide :: Context -> WidgetId -> V2 -> IO ()+clampScrollGlide ctx wid range = modifyGlides ctx (IM.adjust clampGlide (intKey wid))+  where+    clampGlide g = g {sgTarget = projectAxes (sgAxes g) (clampScrollOffset range (sgTarget g))}++cancelScrollGlide :: Context -> WidgetId -> IO ()+cancelScrollGlide ctx wid = modifyGlides ctx (IM.delete (intKey wid))++modifyGlides :: Context -> (IM.IntMap ScrollGlide -> IM.IntMap ScrollGlide) -> IO ()+modifyGlides ctx f =+  modifyIORef' (ctxScrollState ctx) $ \st ->+    if IM.null (ssGlides st) then st else st {ssGlides = f (ssGlides st)}++-- | Advance every glide by @dt@ seconds. Each one covers the same fraction of+-- what is left every second, so a long throw starts fast and eases in, and at+-- least a pixel a frame so a glide cannot stall on the pixel grid the offsets+-- snap to.+stepScrollGlides :: Context -> Float -> IO ()+stepScrollGlides ctx dt = do+  st <- readIORef (ctxScrollState ctx)+  unless (IM.null (ssGlides st)) $ do+    let alpha = glideAlpha (scrollSmoothTime (ssTuning st)) dt+    live <- IM.traverseMaybeWithKey (const (stepGlide ctx alpha)) (ssGlides st)+    modifyIORef' (ctxScrollState ctx) $ \s -> s {ssGlides = live}++-- | Fraction of the remaining distance a glide covers in @dt@ seconds.+-- 'scrollSmoothTime' is the time to cover all but a twentieth of it.+glideAlpha :: Float -> Float -> Float+glideAlpha smooth dt+  | smooth <= 0 || dt <= 0 = 1+  | otherwise = clamp 0 1 (1 - exp (negate (3 * dt / smooth)))++-- | Move a glide one step, and drop it once it lands.+stepGlide :: Context -> Float -> ScrollGlide -> IO (Maybe ScrollGlide)+stepGlide ctx alpha g@(ScrollGlide wid target axes) = do+  cur <- projectAxes axes <$> getScrollOffsetIn ctx wid axes+  let next = V2 (stepAxis (v2X cur) (v2X target)) (stepAxis (v2Y cur) (v2Y target))+  writeScrollOffsetIn ctx wid axes next+  pure (if nearOffset next target then Nothing else Just g)+  where+    stepAxis c t+      | abs (t - c) <= 1 = t+      | otherwise =+          let moved = c + (t - c) * alpha+           in if abs (moved - c) < 1+                then c + signum (t - c)+                else moved++nearOffset :: V2 -> V2 -> Bool+nearOffset (V2 ax ay) (V2 bx by) = abs (ax - bx) <= 0.01 && abs (ay - by) <= 0.01
+ lib/NanoUI/Internal/Context/Types.hs view
@@ -0,0 +1,1253 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Record types behind 'Context': interaction, damage, overlay, animation,+-- scroll and drawing-cache state, theme scopes, and frame messages.+module NanoUI.Internal.Context.Types+  ( Context (..)+  , GenCache (..)+  , emptyGenCache+  , insertGen+  , cachedGen+  , MeasureCache+  , WrapCache (..)+  , MetricSource (..)+  , TextInputMenu (..)+  , TextInputDrag (..)+  , TextFieldClickCell (..)+  , WindowResizeEdge (..)+  , WindowResizeDrag (..)+  , DamageRequest (..)+  , PressPoint (..)+  , DamageState (..)+  , initialDamageState+  , PrevFrame (..)+  , emptyPrevFrame+  , PrevWalk (..)+  , newPrevWalk+  , OverlayState (..)+  , initialOverlayState+  , ExplainState (..)+  , DrawReuse (..)+  , DrawReuseKey (..)+  , initialExplainState+  , ExplainedNode (..)+  , AnimationState (..)+  , initialAnimationState+  , ScrollTuning (..)+  , defaultScrollTuning+  , ScrollAxes (..)+  , ScrollGlide (..)+  , ScrollView (..)+  , ScrollState (..)+  , initialScrollState+  , DrawFitCache (..)+  , DrawingEntry (..)+  , DrawingCacheState (..)+  , NodeCustom (..)+  , noNodeCustom+  , customPassWords+  , PopupConfig (..)+  , DropdownPopup (..)+  , HoverZone (..)+  , DrawOpCacheEntry (..)+  , CustomDrawingEntry (..)+  , CustomDrawOpCacheEntry (..)+  , SpanCacheEntry (..)+  , SpanLines (..)+  , WidgetTextCacheEntry (..)+  , WidgetTextPlacement (..)+  , initialDrawingCacheState+  , InteractionState (..)+  , PointerRoute (..)+  , FocusKind (..)+  , KeyClaim (..)+  , InputMethodRequest (..)+  , FocusRequest (..)+  , initialInteractionState+  , CustomMeasureFn+  , CustomDrawContext (..)+  , CustomDrawBuild+  , ThemeScopes (..)+  , ContainerStack+  , newContainerStack+  , resetContainerStack+  , pushContainer+  , popContainer+  , peekContainer+  , readContainerStack+  , writeContainerStack+  , intKey+  , ChildWindow (..)+  ) where++import Control.Concurrent (ThreadId)+import NanoUI.Internal.Derived (DerivedCache)+import NanoUI.Internal.Resource (Held)+import NanoUI.Internal.Host (Host)+import NanoUI.Internal.BackendSession (SomeBackendSession)+import NanoUI.Internal.NativeWindow.Types (NativeWindow, WindowSettings)+import NanoUI.Internal.Sensor.Types (Sensors)+import NanoUI.Internal.RichText.Types (Paragraphs)+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as HashMap+import Data.Hashable (Hashable)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.IntSet (IntSet)+import Data.IntSet qualified as IS+import Data.Map.Strict (Map)+import Control.Monad (when)+import Data.Primitive.Array (MutableArray, newArray)+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , getSizeofMutablePrimArray+  , newPrimArray+  , readPrimArray+  , resizeMutablePrimArray+  , writePrimArray+  )+import Data.Primitive.PrimVar (PrimVar, newPrimVar, readPrimVar, writePrimVar)+import Data.Primitive.SmallArray (SmallArray, SmallMutableArray)+import Data.Word (Word32, Word64)+import Data.Text (Text)+import GHC.Exts (RealWorld)++import NanoUI.Internal.Animation (Animation)+import NanoUI.Internal.Atlas (AtlasToken, ImageAtlas)+import NanoUI.Internal.Draw.Types (DrawArena, DrawData, DrawOp, DrawingBuild)+import NanoUI.Internal.Font (CustomMeasureFn, FontMetrics, WrapResult)+import NanoUI.Internal.Frame.SpanArena (SpanArena)+import NanoUI.Internal.Id (WidgetId, hashWidgetId)+import NanoUI.Internal.Id.Cursor (IdCursor)+import NanoUI.Internal.Var.Types (SlotVar, Var)+import NanoUI.Internal.Input (Composition, Input, InputPurpose, MouseButton, UiCursorKind)+import NanoUI.Internal.Shader (ShaderCapabilities, ShaderEffectEntry, ShaderNodeEntry)+import NanoUI.Internal.Shortcut (Shortcut)+import NanoUI.Internal.Layout.Arena (DirTag, LayoutCache, NodeArena)+import NanoUI.Internal.Store (WidgetStore)+import NanoUI.Internal.Style (Appearance, Direction, Flow, FontStyle, FontVariant, FontWeight, Layout, Padding, PointerMode, Sizing, Theme)+import NanoUI.Widgets.TextBuffer (Cursor)+import NanoUI.Widgets.TextCommand (TextCommand)+import NanoUI.Internal.Types++-- | Growable unboxed stack of open container node indices. Pushing and+-- popping allocate nothing in steady state.+data ContainerStack+  = ContainerStack+      !(IORef (MutablePrimArray RealWorld Int))+      {-# UNPACK #-} !(PrimVar RealWorld Int)++-- | Create an empty container stack with initial room for 32 nested levels.+newContainerStack :: IO ContainerStack+newContainerStack = ContainerStack <$> (newPrimArray 32 >>= newIORef) <*> newPrimVar 0++-- | Empty the container stack without releasing its backing buffer.+{-# INLINE resetContainerStack #-}+resetContainerStack :: ContainerStack -> IO ()+resetContainerStack (ContainerStack _ dep) = writePrimVar dep 0++{-# NOINLINE growContainerStack #-}+growContainerStack :: IORef (MutablePrimArray RealWorld Int) -> Int -> IO (MutablePrimArray RealWorld Int)+growContainerStack ref needed = do+  arr <- readIORef ref+  cap <- getSizeofMutablePrimArray arr+  let !newCap = max needed (cap * 2)+  grown <- resizeMutablePrimArray arr newCap+  writeIORef ref grown+  pure grown++-- | Push a container node index onto the stack.+{-# INLINE pushContainer #-}+pushContainer :: ContainerStack -> Int -> IO ()+pushContainer (ContainerStack bufRef depVar) !idx = do+  d <- readPrimVar depVar+  arr0 <- readIORef bufRef+  cap <- getSizeofMutablePrimArray arr0+  arr <- if d < cap then pure arr0 else growContainerStack bufRef (d + 1)+  writePrimArray arr d idx+  writePrimVar depVar (d + 1)++-- | Pop the innermost container node index.+{-# INLINE popContainer #-}+popContainer :: ContainerStack -> IO ()+popContainer (ContainerStack _ depVar) = do+  d <- readPrimVar depVar+  when (d > 0) $ writePrimVar depVar (d - 1)++-- | Innermost open container node index, or @-1@ when the stack is empty.+{-# INLINE peekContainer #-}+peekContainer :: ContainerStack -> IO Int+peekContainer (ContainerStack bufRef depVar) = do+  d <- readPrimVar depVar+  if d <= 0+    then pure (-1)+    else readIORef bufRef >>= \arr -> readPrimArray arr (d - 1)++-- | Snapshot the stack as a list, innermost first.+readContainerStack :: ContainerStack -> IO [Int]+readContainerStack (ContainerStack bufRef depVar) = do+  d <- readPrimVar depVar+  arr <- readIORef bufRef+  let go !i !acc+        | i >= d = pure acc+        | otherwise = do+            x <- readPrimArray arr i+            go (i + 1) (x : acc)+  go 0 []++-- | Replace the stack contents from a list ordered innermost first.+writeContainerStack :: ContainerStack -> [Int] -> IO ()+writeContainerStack (ContainerStack bufRef depVar) xs = do+  let rev = reverse xs+      !n = length rev+  arr0 <- readIORef bufRef+  cap <- getSizeofMutablePrimArray arr0+  arr <- if n <= cap then pure arr0 else growContainerStack bufRef n+  let fill !i [] = writePrimVar depVar i+      fill !i (x : rest) = writePrimArray arr i x >> fill (i + 1) rest+  fill 0 rev++-- | Themes the view's @styled@ scopes pushed this frame, and last frame's, to+-- tell whether a frame changed only how its scopes look. A node's scope holds+-- an index into 'tsThemes' plus one; index 0 is the context theme.+data ThemeScopes = ThemeScopes+  { tsCount :: {-# UNPACK #-} !Int+  , tsThemes :: !(SmallMutableArray RealWorld Theme)+  -- ^ What each scope is drawn with.+  , tsRaw :: !(SmallMutableArray RealWorld Theme)+  -- ^ Each scope's theme before a disabled scope faded it, which nested+  -- @styled@ scopes modify.+  , tsPrevCount :: {-# UNPACK #-} !Int+  , tsPrev :: !(SmallMutableArray RealWorld Theme)+  , tsDisabled :: !Bool+  -- ^ A disabled scope was entered this pass, so some widget may be disabled.+  , tsChanged :: !Bool+  -- ^ A pushed theme differs from the one at its index last frame.+  , tsPrevSig :: {-# UNPACK #-} !Word64+  -- ^ Last frame's scope signature ('NanoUI.Internal.Layout.Arena.getScopeSignature').+  }++-- | A memo table in two generations: the young map, its size, and the old+-- map. A full young map replaces the old one, so an entry that stops being+-- used (a clock's text, a log line) is dropped while one used every+-- generation stays. It is a cheap stand-in for least recently used: inserts+-- go to the young map and a hit in the old map moves the entry up, so an+-- entry survives however many one-off keys (wrap probes, table cells) pass+-- through. Plain insertion order evicted the oldest key even when every frame+-- used it. Hashing a text key once beats comparing it at every level of a+-- tree.+data GenCache k v = GenCache !(HashMap k v) !Int !(HashMap k v)++-- | A cache with both generations empty.+emptyGenCache :: GenCache k v+emptyGenCache = GenCache HashMap.empty 0 HashMap.empty++-- | Insert an entry of weight @w@ into a cache of @cap@ per generation. The+-- young map's size is the sum of its entries' weights; an entry heavier than+-- a whole generation is not kept.+{-# INLINE insertGen #-}+insertGen :: Hashable k => Int -> Int -> k -> v -> GenCache k v -> GenCache k v+insertGen cap w k v cache@(GenCache young n old)+  | w > cap = cache+  | n + w > cap = GenCache (HashMap.singleton k v) w young+  | otherwise = GenCache (HashMap.insert k v young) (n + w) old++-- | The entry for @k@, or what @make@ returns, which is kept. Entries weigh+-- @w k@; an old one used again moves to the young map. Inlined so a hit+-- returns the stored value without boxing it in a 'Just' on the way: the SDL+-- bench's warm-lookup gate measures exactly that.+{-# INLINE cachedGen #-}+cachedGen :: Hashable k => Int -> (k -> Int) -> IORef (GenCache k v) -> k -> IO v -> IO v+cachedGen cap w ref k make = do+  cache@(GenCache young _ old) <- readIORef ref+  case HashMap.lookup k young of+    Just v -> pure v+    Nothing -> case HashMap.lookup k old of+      Just v -> do+        writeIORef ref $! insertGen cap (w k) k v cache+        pure v+      Nothing -> do+        v <- make+        modifyIORef' ref (insertGen cap (w k) k v)+        pure v++-- | Memoised measurements by text and measurement scale.+type MeasureCache = GenCache (Text, Float) (Float, Float)++-- | Wrapped text by text and font ('NanoUI.Internal.WidgetText.textNodeFontKey'),+-- each with the widths it holds for, newest first, under the metric generation+-- the results were measured in.+data WrapCache = WrapCache !Int !(GenCache (Text, Int) [WrapResult])++-- | Identity of a font/measurement configuration. Pure Context modifiers+-- replace this value; the next frame invalidates shared caches if its identity+-- differs. Holding the current inputs (not a revision counter/history) also+-- distinguishes two differently configured Contexts derived from one parent.+data MetricSource+  = InitialMetricSource+  | MetricSource+      !FontMetrics+      !FontMetrics+      !(Text -> IO (Float, Float))+      !(Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool))+      !(Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float))++-- | Where a button went down, in the frame the user saw.+data PressPoint = PressPoint+  { ppPos :: !V2+  , ppOwner :: !(Maybe WidgetId)+  -- ^ The widget the press reached, @WidgetId 0@ for a node that takes the+  -- pointer with no widget of its own, or 'Nothing' when it reached none:+  -- passive content, whose mouse area judges the press by its rect.+  , ppReached :: !IntSet+  -- ^ The keys of the reached node and its ancestors ('ppOwner'), which+  -- the press went down on: a left click belongs to these.+  }++-- | Explicit damage invalidation request queued during frame evaluation.+data DamageRequest+  = ReqWidget !WidgetId !DamageBounds      -- ^ Invalidate widget layout bounds (old & new)+  | ReqKey !Int !DamageBounds              -- ^ Invalidate widget bounds by integer key+  | ReqRect !Rect                          -- ^ Invalidate an explicit window-space rectangle+  | ReqPeers ![WidgetId] !DamageBounds     -- ^ Invalidate a collection of widgets+  | ReqFull                                -- ^ Force full window invalidation+  deriving (Eq, Show)++-- | The text field an open edit menu belongs to, the point the menu opened+-- at, and the rect its popup was drawn at (empty before it is drawn), in+-- logical window coordinates.+data TextInputMenu = TextInputMenu+  { textInputMenuWidget :: WidgetId+  , textInputMenuAt :: V2+  , textInputMenuRect :: Rect+  }+  deriving (Eq, Show)++-- | Selection-drag anchor, a position in the field's document (row 0 in a+-- single-line field). Click count selects character, word, or line selection+-- behaviour.+data TextInputDrag = TextInputDrag+  { textInputDragWidget :: WidgetId+  , textInputDragAnchor :: {-# UNPACK #-} !Cursor+  , textInputDragClicks :: {-# UNPACK #-} !Int+  }+  deriving (Eq, Show)++-- | Text position of the last click, used to group repeated clicks on one cell.+-- Positions are character indices, not UTF-8 byte offsets.+data TextFieldClickCell = TextFieldClickCell+  { textFieldClickWidget :: WidgetId+  , textFieldClickAt :: {-# UNPACK #-} !Cursor+  }+  deriving (Eq, Show)++-- | Edge or corner captured by a floating-window resize gesture, as the side+-- of each axis it moves, horizontal then vertical: -1 the left or top, 1 the+-- right or bottom, 0 neither.+data WindowResizeEdge = WindowResizeEdge Int Int+  deriving (Eq, Show)++-- | Resize gesture's initial pointer position, window bounds, and size limits.+-- All coordinates and lengths use logical pixels.+data WindowResizeDrag = WindowResizeDrag+  { wrdWidget :: WidgetId+  , wrdEdge :: WindowResizeEdge+  , wrdGrabX :: {-# UNPACK #-} !Float+  , wrdGrabY :: {-# UNPACK #-} !Float+  , wrdStartX :: {-# UNPACK #-} !Float+  , wrdStartY :: {-# UNPACK #-} !Float+  , wrdStartW :: {-# UNPACK #-} !Float+  , wrdStartH :: {-# UNPACK #-} !Float+  , wrdMinW :: {-# UNPACK #-} !Float+  , wrdMinH :: {-# UNPACK #-} !Float+  , wrdMaxW :: {-# UNPACK #-} !Float+  , wrdMaxH :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | Frame scheduling and repaint state, including previous visible geometry+-- keyed by widget id. Dirty state and pixel damage are tracked separately.+data DamageState = DamageState+  { dsDirty :: !Bool+  , dsDamage :: !Damage+  , dsDamagePieces :: ![Rect]+  -- ^ Disjoint rects inside a 'DamageClip' that together hold all of its+  -- damage, when two or more are much smaller than the clip; otherwise empty,+  -- and the clip is the one piece.+  , dsRequests :: ![DamageRequest]+  , dsLastWindowSize :: !Size+  , dsPrev :: !PrevFrame+  , dsLayoutReads :: !(IntMap (IO Bool))+  -- ^ Layout queries recorded during the frame, by key, each with an action+  -- that checks after layout whether the read is stale+  -- ('NanoUI.Internal.Context.Core.recordLayoutRead').+  }++-- | The last finished frame's layout by widget key, for the next frame's+-- damage to diff against ('NanoUI.Internal.Damage.updatePrevRects').+data PrevFrame = PrevFrame+  { pfRects :: !(IntMap Rect)+  , pfClips :: !(IntMap Rect)+  -- ^ Viewport clip, for keys that have one.+  , pfOuterClips :: !(IntMap Rect)+  -- ^ Scroll containers and panels: the enclosing clip they paint in.+  -- 'pfClips' holds their inner content clip.+  , pfHashes :: !(IntMap Word64)+  -- ^ What the view gave each key's node that paint reads+  -- ('NanoUI.Internal.Layout.Arena.getNodePaintHash'): its text, value,+  -- style, colours, scope, image and options. A key whose hash changed is+  -- repainted.+  , pfEffectRects :: !(IntMap Rect)+  -- ^ Margin-expanded bounds of each active Tier 2 'NanoUI.withShader'+  -- container by widget key, so unmounting or shrinking a shader margin+  -- damages the full previous halo. Empty when no effects are active.+  }++-- | A 'PrevFrame' with no recorded nodes, as before the first frame.+emptyPrevFrame :: PrevFrame+emptyPrevFrame = PrevFrame IM.empty IM.empty IM.empty IM.empty IM.empty++-- | What the last completed 'NanoUI.Internal.Damage.updatePrevRects' walk+-- recorded at each arena index: the key and the rect, clip and paint hash it+-- gave the 'PrevFrame' maps. A node that has not changed since skips the+-- maps, which already hold its entries, and a widget declared where it was+-- reads its last rect here ('NanoUI.Internal.Context.Core.getPrevRectAt').+-- The first 'pwValid' indices hold the walk that built 'dsPrev' (its rects+-- are 'pwFor'); none do while a walk is under way. Updated in place, so a+-- frame allocates none of it.+data PrevWalk = PrevWalk+  { pwKeys :: !(MutablePrimArray RealWorld Int)+  -- ^ The node's key, or 0 where the walk made no entries.+  , pwTags :: !(MutablePrimArray RealWorld Int)+  -- ^ Whether the node has a clip.+  , pwRects :: !(MutableArray RealWorld Rect)+  -- ^ The node's rect, the object its 'pfRects' entry holds unless the+  -- entry was already equal.+  , pwClips :: !(MutablePrimArray RealWorld Float)+  -- ^ Four per index: the node's clip.+  , pwHashes :: !(MutablePrimArray RealWorld Word64)+  -- ^ The node's paint hash.+  , pwValid :: !(PrimVar RealWorld Int)+  -- ^ How many indices hold the walk: none while a walk is under way.+  , pwFor :: !(IORef (IntMap Rect))+  }++-- | Room for @n@ nodes, with no entries.+newPrevWalk :: Int -> IO PrevWalk+newPrevWalk n = do+  keys <- newZeroedPrimArray n+  tags <- newZeroedPrimArray n+  rects <- newArray n (Rect 0 0 0 0)+  clips <- newZeroedPrimArray (4 * n)+  hashes <- newZeroedPrimArray n+  PrevWalk keys tags rects clips hashes <$> newPrimVar 0 <*> newIORef IM.empty++-- | Require a first frame and full repaint, with no previous geometry.+initialDamageState :: DamageState+initialDamageState = DamageState+  { dsDirty = True+  , dsDamage = DamageFull+  , dsDamagePieces = []+  , dsRequests = []+  , dsLastWindowSize = Size 0 0+  , dsPrev = emptyPrevFrame+  , dsLayoutReads = IM.empty+  }++-- | Current modal nesting and previous floating-panel bounds/order used for+-- routing input before the next view is built.+data OverlayState = OverlayState+  { osModalWasActive :: {-# UNPACK #-} !Bool+  , osModalActive :: {-# UNPACK #-} !Bool+  , osModalDepth :: {-# UNPACK #-} !Int+  , osEscapeConsumed :: {-# UNPACK #-} !Bool+  , osTabConsumed :: {-# UNPACK #-} !Bool+  -- | Indices into the frame's 'NanoUI.Internal.Input.inputKeys' already+  -- taken by a shortcut, so no other shortcut acts on the same press.+  , osKeysTaken :: !IntSet+  , osPrevFloatingRects :: !(IntMap Rect)+  , osPrevFloatingOrder :: ![Int]+  }++-- | No modals, floating panels, or consumed key events.+initialOverlayState :: OverlayState+initialOverlayState = OverlayState+  { osModalWasActive = False+  , osModalActive = False+  , osModalDepth = 0+  , osEscapeConsumed = False+  , osTabConsumed = False+  , osKeysTaken = IS.empty+  , osPrevFloatingRects = IM.empty+  , osPrevFloatingOrder = []+  }++-- | The last full frame's draw data and what it was drawn from, reused when+-- a full frame would draw the same output ('NanoUI.Internal.Frame.runFrameEff').+-- A reused frame returns the same 'DrawData' buffers, so the host must treat+-- them as read-only.+data DrawReuse = DrawReuse+  { drOn :: !Bool+  -- ^ Whether frames may reuse a draw at all+  -- ('NanoUI.Internal.Context.setDrawReuse').+  , drLast :: !(Maybe (DrawReuseKey, DrawData))+  -- ^ The last frame's draw, while that frame painted in full and may be+  -- reused.+  }++-- | What a full frame's draw follows besides what its damage covers.+data DrawReuseKey = DrawReuseKey+  { drkSize :: !Size+  , drkSnapScale :: !Float+  , drkSquareGeometry :: !Bool+  , drkExternalText :: !Bool+  , drkMetricGen :: !Int+  , drkFocus :: !WidgetId+  , drkFocusVisible :: !Bool+  , drkHot :: !WidgetId+  , drkActive :: !WidgetId+  , drkArena :: !Word64+  -- ^ 'NanoUI.Internal.Layout.Arena.getPaintSignature'.+  , drkAtlas :: !AtlasToken+  , drkClear :: !Color+  -- ^ The frame's clear colour ('NanoUI.Internal.Draw.Types.drawClear'):+  -- the base theme's window colour is not in the arena's signature.+  }+  deriving (Eq)++-- | Layout overlay state ('NanoUI.Internal.Frame.Explain'): whether it is on,+-- and what the last frame drew, for the next frame to diff against.+data ExplainState = ExplainState+  { esOn :: !Bool+  , esLayers :: ![(Int, [(Rect, Rect, Int)])]+  -- ^ Outlines per layer in paint order: the page (key -1) first, then+  -- floating panels keyed by root node. Each outline is (rect, clip, depth).+  , esHover :: !(Maybe (ExplainedNode, Rect))+  -- ^ The node under the pointer and its highlight's clip.+  , esScopes :: ![(Int, Int)]+  -- ^ Arena index ranges [from, below) added by @explainScope@ this build.+  -- When non-empty, only these nodes are outlined. Subtrees are contiguous+  -- in the arena, so each range covers whole subtrees.+  }++-- | Overlay off.+initialExplainState :: ExplainState+initialExplainState = ExplainState {esOn = False, esLayers = [], esHover = Nothing, esScopes = []}++-- | The innermost node under the pointer in the topmost layer, while the+-- layout overlay is on. Holds the node's requested layout next to its+-- result, so a debug panel can explain its size.+data ExplainedNode = ExplainedNode+  { explainedKind :: !Text+  -- ^ Display name such as @Container@, @Text@ or @ScrollContainer@. A+  -- container adds its flow after commas: @Container, row@,+  -- @Container, layered@, @Container, row, wrap@.+  , explainedWidget :: !(Maybe WidgetId)+  -- ^ The owning widget ('NanoUI.respId'); 'Nothing' for id-less nodes such+  -- as spacers.+  , explainedDepth :: !Int+  -- ^ Nesting depth from the layer root (0). Picks the outline colour.+  , explainedRect :: !Rect+  -- ^ Laid-out rect in logical window coordinates, after scrolling.+  , explainedPadding :: !Padding+  , explainedWidth :: !Sizing+  , explainedHeight :: !Sizing+  , explainedMin :: !V2+  , explainedMax :: !V2+  -- ^ 1e8 or more means unbounded.+  , explainedGap :: !Float+  , explainedDirection :: !Direction+  -- ^ 'NanoUI.Column' for layered containers.+  , explainedFlow :: !Flow+  -- ^ 'NanoUI.Line' for non-containers, scroll containers and grids, which+  -- place children their own way.+  , explainedPin :: !(Maybe V2)+  -- ^ Pin offset ('NanoUI.pinAt').+  , explainedPointer :: !PointerMode+  -- ^ Effective mode: 'NanoUI.PointerPass' when inside a node that passes+  -- the pointer, otherwise the node's own.+  }+  deriving (Eq, Show)++-- | Running animations, settled values with their leases, and per-frame+-- keep-alive requests, keyed by widget or animation id.+data AnimationState = AnimationState+  { asAnimations :: !(IntMap Animation)+  , asAnimRest :: !(IntMap Float)+  -- ^ Settled nonzero values.+  , asRestHeld :: !IntSet+  -- ^ Resting keys read or set since the last sweep of 'asAnimRest'. The+  -- sweep keeps these and those of laid-out widgets, drops the rest, and+  -- starts the set again.+  , asRestFrames :: {-# UNPACK #-} !Int+  -- ^ Frames with resting values since the last sweep.+  , asAnimSettled :: {-# UNPACK #-} !Bool+  , asKeepAlive :: !IntSet+  -- ^ Keys whose perpetual animation a @keepAnimating@ call holds open.+  , asKeepTouched :: !IntSet+  -- ^ The keys that asked again this frame. A held key missing from it at+  -- the end of the frame lapses: its widget is no longer built, and nothing+  -- else would ever end its animation.+  , asViewAnims :: !IntSet+  -- ^ Keys of the running animations a view hook (@animate@, @animateTo@)+  -- read last frame.+  , asViewTouched :: !IntSet+  -- ^ Those it read this frame. One missing at the end of the frame rests at+  -- its value: nothing reads it any more, and it may never end by itself.+  }++-- | Empty animation maps with no pending animation frame.+initialAnimationState :: AnimationState+initialAnimationState = AnimationState+  { asAnimations = IM.empty+  , asAnimRest = IM.empty+  , asRestHeld = IS.empty+  , asRestFrames = 0+  , asAnimSettled = False+  , asKeepAlive = IS.empty+  , asKeepTouched = IS.empty+  , asViewAnims = IS.empty+  , asViewTouched = IS.empty+  }++-- | How far one wheel notch scrolls, and how long a scroll takes to settle.+-- One setting for the whole context; a single scroller can take its own step+-- (see @setScrollStep@).+data ScrollTuning = ScrollTuning+  { scrollWheelStep :: Float+  -- ^ Pixels one wheel notch scrolls. The default, 60 logical pixels, is+  -- about three text lines, which is what Windows and most desktops send a+  -- notch as.+  , scrollSmoothTime :: Float+  -- ^ Seconds a scroll takes to cover most of the distance to its target.+  -- @0@ (the default) lands on it in the same frame.+  }+  deriving (Eq, Show)++-- | Immediate scrolling by 60 logical pixels per wheel step. An app may set a+-- font-relative step ('NanoUI.setScrollTuning').+defaultScrollTuning :: ScrollTuning+defaultScrollTuning =+  ScrollTuning+    { scrollWheelStep = 60+    , scrollSmoothTime = 0+    }++-- | Which axes a scroller moves on, and how an offset in window axes (x+-- rightwards, y downwards) maps onto its stored offset. A 1D row scroller+-- keeps its offset in the main-axis slot, so its horizontal offset is the one+-- that needs swapping.+data ScrollAxes+  = ScrollAxisY+  | ScrollAxisX+  | ScrollAxisXY+  deriving (Eq, Show, Enum)++-- | A scroller on its way to an offset it has not reached yet. The target is+-- in window axes and already clamped to the scroller's range.+data ScrollGlide = ScrollGlide+  { sgWidget :: WidgetId+  , sgTarget :: V2+  , sgAxes :: ScrollAxes+  }+  deriving (Eq, Show)++-- | Where the last layout placed a scroller: its viewport in window+-- coordinates, and the offset, in window axes, its content was placed at.+data ScrollView = ScrollView+  { svViewport :: !Rect+  , svPlaced :: !V2+  }+  deriving (Eq, Show)++-- | Context-wide scroll tuning, active glides, and geometry-publication keys.+data ScrollState = ScrollState+  { ssTuning :: !ScrollTuning+  , ssGlides :: !(IntMap ScrollGlide)+  , ssCached :: !IntSet+  -- ^ Scrollers whose geometry has been published this frame. Two scroll+  -- nodes can share a widget id (a table's frozen pane and its body), and+  -- without this the second would overwrite the first every frame, churning+  -- the store and flipping the geometry the commands read.+  , ssViews :: !(IntMap ScrollView)+  -- ^ Each scroller's last placement. Kept out of the store: a nested+  -- scroller's viewport moves whenever one around it scrolls, and a store+  -- change would keep that frame from repainting as a scroll.+  }++-- | Default tuning with no glides or published scroller geometry.+initialScrollState :: ScrollState+initialScrollState =+  ScrollState+    { ssTuning = defaultScrollTuning+    , ssGlides = IM.empty+    , ssCached = IS.empty+    , ssViews = IM.empty+    }++-- | Drawing's fitted layout keyed by envelope size, line height, content key,+-- and the caller's input layout.+data DrawFitCache = DrawFitCache+  { dfcDw :: {-# UNPACK #-} !Double+  , dfcDh :: {-# UNPACK #-} !Double+  , dfcLh :: {-# UNPACK #-} !Float+  , dfcContent :: {-# UNPACK #-} !Int+  , dfcIn :: !Layout+  , dfcOut :: !Layout+  }++-- | Cached text-span layout for one arena node. Key fields are every input+-- that changes the produced spans; 'sceSpans' is the shared result. The whole+-- cache is dropped on theme or font-scale changes.+data SpanCacheEntry = SpanCacheEntry+  { sceText :: !Text+  , sceFg :: {-# UNPACK #-} !Color+  , sceBg :: {-# UNPACK #-} !Color+  , sceStyle :: {-# UNPACK #-} !Word64+  , sceFontSize :: {-# UNPACK #-} !Float+  , sceAlign :: {-# UNPACK #-} !Int+  , sceWidthTag :: {-# UNPACK #-} !Int+  , sceRect :: !Rect+  , sceLaidW :: {-# UNPACK #-} !Float+  -- ^ The width the lines were wrapped for ('GeomLaidW').+  , sceEffMaxW :: {-# UNPACK #-} !Float+  , sceRowChild :: {-# UNPACK #-} !Bool+  , sceInset :: {-# UNPACK #-} !Float+  , sceFont :: !FontMetrics+  -- ^ The font the text is set in.+  , sceLines :: !SpanLines+  -- ^ The text laid out for the rect's width, before it is placed, so a node+  -- that only moved places the same lines again.+  , sceSpans :: ![(Rect, Text, Color, Color)]+  }++-- | A text node's lines for its width, with the metrics prepared for each.+data SpanLines+  = SpanWrapped ![(Text, FontMetrics)]+  -- ^ Wrapped lines, stacked from the node's top.+  | SpanSingle !Text !FontMetrics+  -- ^ One line, possibly truncated, centred in the node's height.++-- | A cacheable widget label is a single line (or absent for close buttons).+-- Coordinates are relative to the node origin; paint translates them without+-- rebuilding a list or invalidating the cache when a widget scrolls.+data WidgetTextPlacement = WidgetTextPlacement+  !Text+  {-# UNPACK #-} !Float+  {-# UNPACK #-} !Float+  {-# UNPACK #-} !Float+  {-# UNPACK #-} !Float++-- | Widget-label measurement inputs and optional node-relative placement.+-- Position is excluded so scrolling can reuse the measurement.+data WidgetTextCacheEntry = WidgetTextCacheEntry+  { wtcNodeType :: {-# UNPACK #-} !Int+  , wtcStyle :: {-# UNPACK #-} !Word64+  , wtcFontSize :: {-# UNPACK #-} !Float+  , wtcText :: !Text+  , wtcWidth :: {-# UNPACK #-} !Float+  , wtcHeight :: {-# UNPACK #-} !Float+  , wtcAlign :: {-# UNPACK #-} !Int+  , wtcPlacement :: {-# NOUNPACK #-} !(Maybe WidgetTextPlacement)+  }++-- | Interaction and styling snapshot supplied to a custom widget's painter.+-- Theme includes scoped/disabled styling; font metrics describe its text.+data CustomDrawContext = CustomDrawContext+  { cdcHovered  :: {-# UNPACK #-} !Bool+    -- ^ The pointer is over the widget, which is enabled.+  , cdcPressed  :: {-# UNPACK #-} !Bool+    -- ^ The left button went down on the widget, which is enabled, and is+    -- still held. When drawing, this holds wherever the pointer goes; in+    -- 'NanoUI.Widgets.Custom.widgetInteract', only while it is over the widget.+  , cdcFocused  :: {-# UNPACK #-} !Bool+    -- ^ The widget has keyboard focus.+  , cdcActive   :: {-# UNPACK #-} !Bool+    -- ^ The widget holds the left press wherever the pointer goes, even when+    -- disabled. In 'NanoUI.Widgets.Custom.widgetInteract' it is set from the+    -- frame after the press.+  , cdcDisabled :: {-# UNPACK #-} !Bool+    -- ^ The widget is in a disabled scope.+  , cdcTheme    :: !Theme+  , cdcFont     :: !FontMetrics+  }++-- | Pure draw-op builder for a solved rectangle in logical window coordinates.+-- Include changing external inputs in the widget's content key when caching.+type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp++-- | A registered custom drawing: its content key plus the op builder. A+-- non-zero key is the author's promise that the ops follow it, so a frame+-- whose key is unchanged neither rebuilds nor repaints them. Key 0 means the+-- drawing carries no key and is rebuilt every frame and compared.+data CustomDrawingEntry = CustomDrawingEntry+  { cdrContent :: {-# UNPACK #-} !Int+  , cdrBuild :: !CustomDrawBuild+  , cdrCursor :: !(Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind))+    -- ^ Cursor for a given widget rect and pointer position.+  , cdrDamageSlop :: {-# UNPACK #-} !Float+    -- ^ Repaint margin in logical pixels; anything but a positive value+    -- leaves the default margin in place.+  , cdrTracked :: !Bool+    -- ^ Whether pointer motion over the widget always schedules a frame.+  , cdrKeys :: !KeyClaim+    -- ^ The widget's actual claims, rather than a lossy style-index encoding.+  }++-- | A registered drawing: content version plus the op builder. The version+-- participates in the draw-op cache key, so a builder whose output changes+-- without its size changing must bump the version to invalidate.+data DrawingEntry = DrawingEntry+  { deContent :: {-# UNPACK #-} !Int+  , deBuild :: !DrawingBuild+  }++-- | What a node registered in this view pass ('ctxNodeCustom'): its+-- drawing, its custom drawing and its custom measure. Entries are kept for+-- the arena epoch ('NanoUI.Internal.Layout.Arena.naEpoch') they were+-- written in, so the arena's reset empties every one without a write.+data NodeCustom = NodeCustom+  { ncEpoch :: {-# UNPACK #-} !Word32+  , ncDrawing :: !(Maybe DrawingEntry)+  , ncCustom :: !(Maybe CustomDrawingEntry)+  , ncMeasure :: !(Maybe CustomMeasureFn)+  , ncShader :: !(Maybe ShaderNodeEntry)+  , ncEffect :: !(Maybe ShaderEffectEntry)+  }++-- | No registrations, in no epoch.+noNodeCustom :: NodeCustom+noNodeCustom = NodeCustom 0 Nothing Nothing Nothing Nothing Nothing++-- | Words of 'ctxCustomPass': whether a custom drawing was registered on a+-- node that is no drawing (0 or 1), a signature of the nodes that registered+-- a custom measure, and how many drawings and custom drawings registered.+customPassWords :: Int+customPassWords = 4++-- | Compiled-op and layout caches of the drawings, by widget key, kept+-- across frames. Registrations themselves are per node ('ctxNodeCustom').+data DrawingCacheState = DrawingCacheState+  { dcsPopupConfigs :: !(IntMap PopupConfig)+  , dcsDropdowns :: !(IntMap DropdownPopup)+  -- ^ Dropdown popups by key: placed by their field's rect this frame+  -- rather than by an anchor.+  , dcsDrawOpCache :: !(IntMap DrawOpCacheEntry)+  , dcsCustomDrawOpCache :: !(IntMap CustomDrawOpCacheEntry)+  , dcsDrawFitCache :: !(IntMap DrawFitCache)+  , dcsHoverZones :: ![HoverZone]+  -- ^ Tooltip targets: entering or leaving them needs a frame even when the+  -- hover probe finds no widget there.+  }++-- | What the view drew a dropdown popup from.+data DropdownPopup = DropdownPopup+  { dpField :: !WidgetId+  -- ^ The select or combo box the dropdown belongs to.+  , dpPicked :: {-# UNPACK #-} !Int+  -- ^ The row drawn picked: the select's value, or the combo's highlight+  -- within its window; -1 for none.+  , dpCombo :: !Bool+  , dpScrollX :: {-# UNPACK #-} !Float+  -- ^ How far a combo's rows are scrolled left.+  }++-- | A rect whose enter and exit need a frame. The flag is set when every+-- move inside also needs one (an open tooltip that follows the pointer).+data HoverZone = HoverZone {-# UNPACK #-} !Rect !Bool++-- | Strict cache entry for a popup's anchor configuration.+data PopupConfig = PopupConfig+  { pcAnchor :: !PopupAnchor+  , pcPlacement :: !PopupPlacement+  , pcOffset :: {-# UNPACK #-} !Float+  }++-- | Strict cache entry for a drawing's compiled draw ops.+data DrawOpCacheEntry = DrawOpCacheEntry+  { doeContent :: {-# UNPACK #-} !Int+  , doeBounds :: !Rect+  , doeOps :: !(SmallArray DrawOp)+  }++-- | Strict cache entry for a custom drawing's compiled draw ops. The key is+-- the content key, the rect, the interaction state the draw context exposes,+-- and the metric generation, which a base theme or font change bumps. A theme+-- scope change bumps nothing: the frame empties the cache instead.+data CustomDrawOpCacheEntry = CustomDrawOpCacheEntry+  { cdeContent :: {-# UNPACK #-} !Int+  , cdeBounds :: !Rect+  , cdeHovered :: {-# UNPACK #-} !Bool+  , cdePressed :: {-# UNPACK #-} !Bool+  , cdeFocused :: {-# UNPACK #-} !Bool+  , cdeActive :: {-# UNPACK #-} !Bool+  , cdeDisabled :: {-# UNPACK #-} !Bool+  , cdeGen :: {-# UNPACK #-} !Int+  , cdeOps :: !(SmallArray DrawOp)+  }++-- | No registered drawings, popup configurations, or cached results.+initialDrawingCacheState :: DrawingCacheState+initialDrawingCacheState = DrawingCacheState+  { dcsPopupConfigs = IM.empty+  , dcsDropdowns = IM.empty+  , dcsDrawOpCache = IM.empty+  , dcsCustomDrawOpCache = IM.empty+  , dcsDrawFitCache = IM.empty+  , dcsHoverZones = []+  }++-- | Target layer for a frame's pointer events (press, drag, release, wheel,+-- and hover), selected before the view runs from the topmost layer under the+-- pointer (or retained while a button is held). Other layers receive+-- 'NanoUI.Internal.Input.withoutPointer'.+data PointerRoute+  = -- | The widgets of one layer: 0 is the page, anything else the key of the+    -- floating panel (window, popup or modal) on top under the pointer.+    RouteLayer !Int+  | -- | The popup of an open select or combo dropdown, by key: its own+    -- layer gets the pointer, and the page's pointer steps see none of it,+    -- as for a menu ('NanoUI.Internal.Context.registerDropdownPopup').+    RouteDropdown !Int+  deriving (Eq, Show)++-- | Pointer route and active drag/menu gestures shared by the view and frame passes.+data InteractionState = InteractionState+  { isScrollDrag :: !(Maybe (WidgetId, DirTag, Float))+  -- | The scrollbar under the pointer, or whose thumb is being dragged: its+  -- scroller's id, its axis and its track. Its thumb paints brighter.+  , isScrollHover :: !(Maybe (WidgetId, DirTag, Rect))+  , isTextInputDrag :: !(Maybe TextInputDrag)+  , isTextFieldClickCell :: !(Maybe TextFieldClickCell)+  , isTextInputMenu :: !(Maybe TextInputMenu)+  , isTextEditLastAction :: !(Maybe (WidgetId, TextCommand))+  , isPointerRoute :: !PointerRoute+  -- | A button was down when the route was last decided, so it stands.+  , isPointerHeld :: {-# UNPACK #-} !Bool+  , isWindowDrag :: !(Maybe (WidgetId, Float, Float))+  , isWindowResize :: !(Maybe WindowResizeDrag)+  -- | A table header is resizing a column. Set by the table on the frames it+  -- does, cleared on mouse release.+  , isColumnResize :: {-# UNPACK #-} !Bool+  -- | Kind of the focused widget at frame start.+  , isFocusKind :: !FocusKind+  -- | The focused widget at frame start is a combo box showing its list (a+  -- text input carrying options), which closes on Escape. Read from last+  -- frame's nodes, like 'isFocusKind', so the view can ask before the combo+  -- is declared.+  , isFocusCombo :: !Bool+  -- | This frame's IME composition and the text field showing it (widget id+  -- 0 when unclaimed). See 'NanoUI.Internal.Frame.TextInput.claimComposition'.+  , isComposition :: !(Maybe (Composition, WidgetId))+  }+  deriving (Eq, Show)++-- | Kind of the focused widget, read from last frame's nodes before the view+-- runs. Shortcuts skip the keys it claims ('NanoUI.Internal.Widgets.Shortcut').+data FocusKind+  = FocusNone+  | -- | A control and the keys it claims. A text area claims 'KeysType'.+    FocusControl !KeyClaim+  | -- | A single-line text field: 'KeysType' plus Enter.+    FocusTextLine+  | -- | A read-only selectable text: caret motion, select-all and copy.+    FocusTextSelectable+  | -- | A text field with an active IME composition or commit this frame.+    -- The keys belong to the IME, so it claims every key and its typed+    -- text regardless of modifiers.+    FocusComposing+  deriving (Eq, Show)++-- | A focus move requested by the view: a widget, the next or previous Tab+-- stop, or no focus.+data FocusRequest = FocusOn !WidgetId | FocusNext | FocusPrevious | FocusNowhere+  deriving (Eq, Show)++-- | A widget taking IME text this frame. The caret is in window coordinates;+-- 'Nothing' for a text field, whose caret the frame derives from its node.+data InputMethodRequest = InputMethodRequest+  { imrWidget :: !WidgetId+  , imrCaret :: !(Maybe Rect)+  , imrPurpose :: !InputPurpose+  }+  deriving (Eq, Show)++-- | Keys a focused control handles itself, which shortcuts and key listeners+-- ('NanoUI.keyPressed') then skip. Enter, Space and arrows are claimed only+-- bare or with Shift ('NanoUI.Internal.Input.shiftAtMost'); with Ctrl, Alt+-- or Super they stay chords for shortcuts.+data KeyClaim+  = -- | Enter, Space, arrows, Home, End, Page Up, Page Down: a slider, list+    -- or select.+    KeysNavigate+  | -- | Enter and Space: a button, checkbox or switch.+    KeysActivate+  | -- | Multi-line text field: typing keys plus editing keys and shortcuts,+    -- under any modifiers.+    KeysType+  | -- | Every key: a terminal, or an editor with its own chords. Tab too,+    -- which then does not move focus off the widget.+    KeysAll+  | -- | No keys: focus alone does not reserve application shortcuts.+    KeysNone+  | -- | Read-only text selection: movement, select-all and copy, but no edits.+    KeysReadOnly+  | -- | Exactly these chords, including their modifiers. A chord without a+    -- key claims nothing. Presets remain available for ordinary controls.+    KeysOnly ![Shortcut]+  deriving (Eq, Show)++-- | Pointer routed to the page, with no held gesture, menu, or pending edit command.+initialInteractionState :: InteractionState+initialInteractionState = InteractionState+  { isScrollDrag = Nothing+  , isScrollHover = Nothing+  , isTextInputDrag = Nothing+  , isTextFieldClickCell = Nothing+  , isTextInputMenu = Nothing+  , isTextEditLastAction = Nothing+  , isPointerRoute = RouteLayer 0+  , isPointerHeld = False+  , isWindowDrag = Nothing+  , isWindowResize = Nothing+  , isColumnResize = False+  , isFocusKind = FocusNone+  , isFocusCombo = False+  , isComposition = Nothing+  }++-- | Mutable state for one UI session. Construct with @newContext@ and use it+-- serially on the UI thread. Record copies share arenas, stores, and IORefs;+-- a font-configured copy is not an independent session.+--+-- A field whose comment ends with the tag sentence naming+-- @resetUiBuild@ holds what one view run builds:+-- that function writes the field's initial value before each run. The+-- nano-ui-test case @per-build-reset@ checks each tagged field and fails+-- when the number of tags here differs from the fields it checks.+data Context = Context+  { ctxNodeArena :: NodeArena+  -- ^ The nodes the view declares, which layout solves and the paint pass+  -- walks. Reset by @resetUiBuild@.+  , ctxDrawArena :: DrawArena+  -- ^ The frame's draw commands and vertices, emptied before each paint.+  , ctxHotId :: IORef WidgetId+  -- ^ The widget under the pointer after this frame's layout+  -- ('NanoUI.Internal.Frame.Input.refreshHover'), or @WidgetId 0@ for none.+  -- It is @WidgetId 0@ while the view runs, and the paint pass and the+  -- draw-reuse key read it. Reset by @resetUiBuild@.+  , ctxLastHotId :: IORef WidgetId+  -- ^ The same widget as 'ctxHotId', kept through the next view run: the+  -- next 'NanoUI.Internal.Frame.Input.refreshHover' compares against it to+  -- start hover fades, and the idle check probes the pointer against it.+  -- | 'intKey's of the topmost pointer-taking node under the pointer and its+  -- ancestors, in the frame the user saw+  -- ('NanoUI.Internal.Frame.Input.recordCoveredWidgets'). Other nodes under+  -- the pointer are covered by layers or pins and get no pointer this view+  -- ('NanoUI.Internal.Context.Core.pointerCovered'). 'Nothing' when nothing+  -- is covered.+  , ctxPointerReach :: !(IORef (Maybe IntSet))+  , ctxActiveId :: IORef WidgetId+  -- ^ The widget holding the left button: set on a press before the view+  -- ('NanoUI.Internal.Frame.Input.armPointerTarget') or by a drag, and+  -- cleared to @WidgetId 0@ on the release+  -- ('NanoUI.Internal.Frame.Input.finalizePointerRelease'). While it is set,+  -- no other widget is hovered.+  , ctxClickedId :: IORef WidgetId+  -- ^ A click the view missed: a release on the active widget's solved rect+  -- that its last-frame rect did not contain. The widget reports it on the+  -- next view run ('NanoUI.Internal.Widgets.Node.resolveInteraction'),+  -- which clears it after the first pass.+  -- | The press of each held button, updated on press and release+  -- ('NanoUI.Internal.Frame.Input.armPointerPress'). Clicks and holds belong+  -- to the widget pressed, so widgets check this as well as the pointer. A+  -- button with no entry (release without a press) is judged alone.+  , ctxPressPos :: IORef (Map MouseButton PressPoint)+  , ctxFocusId :: IORef WidgetId+  -- ^ The widget with keyboard focus, or @WidgetId 0@ for none.+  -- | Focus last moved by keyboard or code, so the focused widget shows its+  -- ring. A pointer press hides it.+  , ctxFocusVisible :: IORef Bool+  -- | Focus move requested this frame ('NanoUI.Internal.Monad.requestFocus'),+  -- applied after layout ('NanoUI.Internal.Frame.Input.finalizeFocusRequest').+  , ctxFocusRequest :: IORef (Maybe FocusRequest)+  -- | The focused widget's IME request from the last view run+  -- ('NanoUI.Internal.Context.requestInputMethod'); reset each build. The+  -- next frame routes the composition to it+  -- ('NanoUI.Internal.Frame.TextInput.claimComposition'), and backends read+  -- the text input area from it ('NanoUI.Internal.Frame.TextArea.textInputArea').+  -- Reset by @resetUiBuild@.+  , ctxInputMethod :: !(IORef (Maybe InputMethodRequest))+  , ctxStore :: IORef WidgetStore+  , ctxDamageState :: IORef DamageState+  , ctxPrevWalk :: !(IORef PrevWalk)+  , ctxStoreOwners :: !(IORef (IntMap Int))+  -- ^ The widget key that owns each sub-slot store key the damage pass has+  -- resolved ('NanoUI.Internal.Damage.storeKeyChanges'). A sub-slot key is+  -- a hash of its widget's key, so an owner found once stays the owner.+  , ctxOverlayState :: IORef OverlayState+  , ctxAnimationState :: IORef AnimationState+  , ctxScrollState :: !(IORef ScrollState)+  , ctxDrawingCache :: IORef DrawingCacheState+  , ctxNodeCustom :: !(IORef (MutableArray RealWorld NodeCustom))+  -- ^ Each node's registrations ('NodeCustom'), by arena index.+  , ctxCustomPass :: !(MutablePrimArray RealWorld Word64)+  -- ^ The view pass's registration totals ('customPassWords').+  , ctxIdCursor :: !IdCursor+  -- ^ The id path and sibling position the next declared widget takes its+  -- id from. Starts at 'NanoUI.Internal.Id.initialIdContext'. Reset by+  -- @resetUiBuild@.+  , ctxVarFrame :: !(MutablePrimArray RealWorld Word64)+  -- ^ Var bookkeeping for the frame being built: current pass tick, frame+  -- base tick, pass number, flags, and the passes the last frame ran+  -- ("NanoUI.Internal.Var").+  , ctxVarSlots :: !(IORef (IntMap SlotVar))+  -- ^ Positional Vars ('NanoUI.Var.useVar'), by Var key.+  , ctxFontMetrics :: FontMetrics+  -- ^ Base proportional-font metrics used by layout and drawing.+  , ctxMonoFontMetrics :: FontMetrics+  , ctxFontSize :: !Float+  -- ^ Backend default text size, used when a layout sets none. Same units+  -- as 'NanoUI.fontSize'.+  , ctxMeasureText :: Text -> IO (Float, Float)+  , ctxResolveFont :: !(Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool))+  , ctxResolveMeasure :: !(Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float))+  , ctxMeasureCache :: Maybe (IORef MeasureCache)+  , ctxWrapCache :: !(IORef WrapCache)+  -- ^ Wrapped text, shared by the solve and the text spans across frames.+  -- See 'NanoUI.Internal.Context.cachedWrapText'.+  , ctxSpanCache :: !(IORef (IntMap SpanCacheEntry))+  , ctxWidgetTextCache :: !(IORef (IntMap WidgetTextCacheEntry))+  -- | What widgets derive from their arguments and keep between frames+  -- (a table's column widths and sort), by widget key. It is not state, so+  -- a write neither damages nor wakes the loop. Cleared with the text caches.+  , ctxDerivedCache :: !(IORef DerivedCache)+  , ctxHeld :: !Held+  , ctxNativeWindow :: !(Host NativeWindow)+  , ctxBackendSession :: !(Host SomeBackendSession)+  -- ^ What the backend driving this context keeps for its session+  -- ('NanoUI.Internal.Context.withBackendSession').+  , ctxSensors :: !(Host Sensors)+  , ctxParagraphs :: !(Host Paragraphs)+  , ctxSvgRasters :: !(IORef (Map (Int, Int, Int, Word32, (Int, Int, Int, Int)) (ImageId, Int, PrimVar RealWorld Int)))+  -- ^ SVG rasters by document, pixel size, colour and content rect (in+  -- eighths of a raster pixel), with the atlas's release count+  -- ('NanoUI.Internal.Atlas.atlasReleases') when each was made and the frame+  -- that last drew it. One no frame drew since the one before gives its room+  -- to the next raster made; one the atlas had no room for is kept as id 0+  -- until an image leaves the atlas.+  , ctxLayoutCache :: !(IORef (Maybe (LayoutCache, Size, Int)))+  -- ^ Whole-layout reuse cache: cached signature and solved rects,+  -- with the window size and font/theme generation it was captured under.+  , ctxMetricGen :: !(IORef Int)+  , ctxMetricSource :: {-# NOUNPACK #-} !MetricSource+  , ctxLastMetricSource :: !(IORef (Maybe MetricSource))+  -- | True when the next present must repaint the whole window (fresh retain+  -- texture, forced full, continuous present, or window expose). When False,+  -- a DamageClip frame culls the paint pass to the damaged region. A backend+  -- that sets it clears the target to the frame's+  -- 'NanoUI.Internal.Draw.Types.drawClear' (the page surface laid over+  -- 'NanoUI.themeWindow') before it draws the frame; the frame paints that+  -- colour as the clip backdrop otherwise.+  , ctxPaintFull :: !(IORef Bool)+  , ctxDrawReuse :: !(IORef DrawReuse)+  -- | Whether the host reads this frame's damage+  -- ('NanoUI.Internal.Context.Core.takeDamage'). A host that repaints the+  -- whole window whatever changed (a continuous session) clears it, and the+  -- frame reports 'DamageFull' without diffing anything, unless it may reuse+  -- the last frame's draw ('ctxDrawReuse'), which needs to know that nothing+  -- is damaged. A host that clears it while 'ctxPaintFull' is off gets+  -- 'DamageFull' too, so its clip frames repaint the whole window. True by+  -- default.+  , ctxDamageWanted :: !(IORef Bool)+  -- | Layout overlay state. Its 'esScopes' are ranges of this run's node+  -- arena. Reset by @resetUiBuild@.+  , ctxExplain :: !(IORef ExplainState)+  , ctxTheme :: !(IORef Theme)+  -- ^ Base theme; scoped themes live in 'ctxThemeScopes'.+  , ctxThemeScopes :: !(IORef ThemeScopes)+  , ctxSystemAppearance :: !(IORef (Maybe Appearance))+  -- ^ Last system light/dark preference reported by the backend; 'Nothing'+  -- when unknown.+  , ctxThemeFor :: !(IORef (Maybe (Maybe Appearance -> Theme)))+  -- ^ Base theme per system appearance when following the system+  -- ('NanoUI.Internal.Context.followSystemTheme'); 'Nothing' for a fixed+  -- base theme.+  , ctxContainerStack :: !ContainerStack+  -- ^ Node indices of the containers open at this point of the view,+  -- innermost first; a widget's parent is the head. Reset by+  -- @resetUiBuild@.+  , ctxFocusables :: IORef (MutablePrimArray RealWorld WidgetId)+  -- ^ The run's focus order ('NanoUI.Internal.Context.registerFocusable'),+  -- in its first 'ctxFocusablesCount' slots. The array is kept between runs+  -- and grows by doubling.+  , ctxFocusablesCount :: !(PrimVar RealWorld Int)+  -- ^ How many slots of 'ctxFocusables' this run filled. Reset by+  -- @resetUiBuild@.+  , ctxSpanBase :: SpanArena+  -- ^ Base-layer text spans for the current frame, reused on the next frame.+  , ctxSpanOverlay :: SpanArena+  -- ^ Overlay text spans for the current frame, reused on the next frame.+  , ctxInteractionState :: !(IORef InteractionState)+  -- | Rects the view asked a cursor for this build, newest first: a table's+  -- column edges. Reset by @resetUiBuild@.+  , ctxCursorZones :: !(IORef [(Rect, UiCursorKind)])+  -- | Node ranges [from, below) of this build's+  -- 'NanoUI.withCursorShape' scopes, newest first.+  -- Scopes are pushed when they end, so an outer scope precedes its inner+  -- ones. Reset by @resetUiBuild@.+  , ctxCursorRegions :: !(IORef [(Int, Int, UiCursorKind)])+  , ctxClipboardGet :: IO (Maybe Text)+  , ctxClipboardSet :: Text -> IO Bool+  , ctxImageAtlas :: ImageAtlas+  , ctxWakeLoop :: IORef (Maybe (IO Bool))+  -- ^ Wakes the event loop and returns whether the wake reached it+  -- ('NanoUI.Internal.Context.Core.setWakeLoopChecked').+  , ctxWoken :: !(IORef Bool)+  -- ^ Set from any thread by 'NanoUI.Internal.Context.Core.wakeFromThread'+  -- when view inputs changed. The next frame repaints fully and clears it.+  , ctxWakePending :: !(IORef Bool)+  -- ^ A wake ran the wake action and the loop has not taken it yet. Later+  -- wakes skip the action until a loop pass or frame takes it+  -- ('NanoUI.Internal.Context.Core.takeWakes').+  , ctxLoopThread :: !(IORef (Maybe ThreadId))+  -- ^ The thread in 'NanoUI.Runner.runSessionLoop', if one runs. Its dirty+  -- marks run no wake action: the loop checks the dirty flag before it waits.+  , ctxWakeAt :: !(IORef Double)+  -- ^ Monotonic time ('GHC.Clock.getMonotonicTime') of the earliest scheduled+  -- wake timer, or 0 for none. Reset to 0 at the start of each frame so active+  -- timers re-register each frame and the loop can sleep until the next timer.+  , ctxChildWindows :: !(IORef [ChildWindow])+  -- ^ The open native windows the last view run declared+  -- ('NanoUI.nativeWindow'), newest first. Reset by @resetUiBuild@.+  , ctxShaderCaps :: !(IORef ShaderCapabilities)+  -- ^ Shader capabilities reported by the active backend.+  , ctxEffectNodes :: !(IORef (Word32, [Int]))+  -- ^ Epoch-stamped container node indices with Tier 2 shader effects this+  -- build, so damage expansion skips scanning frames with no effects.+  }++-- | A native window a view declared open this frame, for the backend to open+-- or keep. The key is the declaring call's widget id. The view is kept run+-- against a context and input rather than as a 'NanoUI.NanoUI' action,+-- which this module cannot name.+data ChildWindow = ChildWindow+  { childKey :: !WidgetId+  , childOpen :: !(Var Bool)+  , childSettings :: !WindowSettings+  , childRun :: Context -> Input -> IO ()+  -- ^ The declared body, as @\\c inp -> 'NanoUI.Backend.runNanoUI' c inp body@+  -- ('NanoUI.nativeWindow'). A function field because+  -- the 'NanoUI.NanoUI' type is defined in @NanoUI.Internal.Monad.Core@,+  -- which imports "NanoUI.Internal.Context", which imports this module: a+  -- @NanoUI ()@ field here would make an import cycle. The backend runs it+  -- through 'NanoUI.Backend.childView'.+  }++-- | Convert a widget's hash to its store key. The representation assumes a+-- 64-bit 'Int' when preserving all identity bits.+{-# INLINE intKey #-}+intKey :: WidgetId -> Int+intKey = fromIntegral . hashWidgetId
+ lib/NanoUI/Internal/Damage.hs view
@@ -0,0 +1,1094 @@+{-# LANGUAGE DerivingVia #-}++-- | Compare completed frames and explicit invalidations to choose repaint bounds.+-- Damage is computed before painting so retained backends can redraw only a clip.+module NanoUI.Internal.Damage+  ( updatePrevRects+  , pruneUnmountedCaches+  , floatingPanelRects+  , FrameSnapshot (..)+  , captureFrameSnapshot+  , writeDamage+  , damagePieces+  , pixelEdges+  , clipPixelEdges+  , snapDamage+  ) where++import Control.Applicative ((<|>))+import Control.Exception (evaluate)+import Control.Monad (filterM, foldM, forM_, unless, when)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.Reader (ReaderT (..))+import Data.Bits (xor)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.List (partition, tails)+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)+import Data.Hashable (hashWithSalt)+import Data.Primitive.Array (readArray, sizeofMutableArray, writeArray)+import Data.Primitive.PrimArray (MutablePrimArray, readPrimArray, writePrimArray)+import Data.Primitive.PrimVar (readPrimVar, writePrimVar)+import Data.Word (Word64)+import GHC.Exts (RealWorld)+import NanoUI.Internal.Context+import NanoUI.Internal.Context.Types (ScrollState (..), newPrevWalk)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Store (diffKeys, eqByPtr, ptrEq, slotChangedKeys)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Frame.Chrome (menuPanelBounds)+import NanoUI.Internal.Layout.ScrollGeometry (decodeScrollConfig, scrollBare)+import NanoUI.Internal.Shader (ShaderEffectEntry (..))+import NanoUI.Internal.Style (PointerMode (..))+import NanoUI.Internal.WidgetText (containerFlagClip, hasFlag)+import NanoUI.Internal.Widgets.Custom (mkCustomDrawContext)+import NanoUI.Internal.Types++layoutSettleMinArea :: Float+layoutSettleMinArea = 0.25++-- Partial retain clears with the page colour. Expand interaction clips to the+-- painted panel/page backdrop so slop pixels get the correct fill, not the+-- page colour.+backdropRectFromNode :: Context -> Int -> IO (Maybe Rect)+backdropRectFromNode Context {ctxNodeArena = na} idx = walkAncestors na idx $ \i -> do+  nt <- getNodeType na i+  paints <- if isFloatingNode nt then pure True else containerPaints na i nt+  if paints then getNonzeroRect na i else pure Nothing++-- | Whether a container paints its own backdrop: a panel, or a scroll+-- container with a well (one that is not bare and does not grow on both axes).+{-# INLINE containerPaints #-}+containerPaints :: NodeArena -> NodeIdx -> NodeType -> IO Bool+containerPaints na i nt = case nt of+  NodeScrollContainer -> do+    wTag <- axTag <$> getWidthSizing na i+    hTag <- axTag <$> getHeightSizing na i+    si <- getStyleIdx na i+    pure (not ((wTag == SizingGrow && hTag == SizingGrow) || scrollBare (decodeScrollConfig si)))+  _ -> pure (nt == NodePanel)++-- | Damage key for a painting container with no widget id: its nearest keyed+-- ancestor's key mixed with its arena offset from that ancestor. It is stable+-- while nothing before it in that ancestor is added or removed. Otherwise it+-- changes and is treated as a removed and added container. An+-- ancestor whose key a later node reuses ('getIdSuperseded') is passed over,+-- or a container in each would take the same key.+containerKey :: NodeArena -> NodeIdx -> IO Int+containerKey na idx = go idx+  where+    go i = do+      p <- getParent na i+      if p < 0+        then pure (mix 0 idx)+        else do+          w <- getWidgetId na p+          keyed <- if hashWidgetId w == 0 then pure False else not <$> getIdSuperseded na p+          if keyed then pure (mix (intKey w) (idx - p)) else go p+    -- Key 0 means no widget.+    mix k off = let h = hashWithSalt k off `xor` 0x3C6EF372FE94F82A in if h == 0 then 1 else h++-- | The clip node @idx@ is painted in: its parent's content clip+-- ('NanoUI.Internal.Frame.Scroll.applyScrollOffsets'). For a scroll container+-- or panel this is wider than the node's own clip, which is the clip it gives+-- its content (its viewport or inside).+outerClip :: NodeArena -> Rect -> NodeIdx -> IO Rect+outerClip na window idx = do+  p <- getParent na idx+  if p < 0+    then pure window+    else do+      clip <- fromMaybe window <$> getClipBounds na p+      pt <- getNodeType na p+      -- A widget or clipContainer also clips its content to its own rect.+      clipSelf <-+        if isWidgetNode pt+          then pure True+          else if pt == NodeContainer then hasFlag containerFlagClip <$> getStyleIdx na p else pure False+      if clipSelf+        then do+          r <- getNodeRect na p+          pure (fromMaybe (Rect (rectX r) (rectY r) 0 0) (rectIntersect clip r))+        else pure clip++{-# INLINE getNonzeroRect #-}+getNonzeroRect :: NodeArena -> Int -> IO (Maybe Rect)+getNonzeroRect arena i = do+  r <- getNodeRect arena i+  pure (if rectNonEmpty r then Just r else Nothing)++-- | First pass of 'updatePrevRects', over scroll containers and panels+-- ('BackdropNodes'): record the clip each is painted in, and for a painting+-- container with no widget id (such as a panel) record its rect and paint+-- hash under 'containerKey', so moving, resizing or restyling it repaints+-- where it was.+{-# INLINE scanBackdropPrevRects #-}+scanBackdropPrevRects ::+  NodeArena ->+  Rect ->+  IM.IntMap Rect ->+  IM.IntMap Rect ->+  IM.IntMap Word64 ->+  IO (IM.IntMap Rect, IM.IntMap Rect, IM.IntMap Word64, Int, Int, Bool)+scanBackdropPrevRects na window oldRects oldOuters oldHashes = do+  (containerCount, containerAt) <- classNodes na BackdropNodes+  let containers !j !m !om !hm !foundOld !foundOuter !dropped+        | j >= containerCount = pure (m, om, hm, foundOld, foundOuter, dropped)+        | otherwise = do+            idx <- containerAt j+            wid <- getWidgetId na idx+            let keyless = hashWidgetId wid == 0+            skip <- if keyless then not <$> (containerPaints na idx =<< getNodeType na idx) else getIdSuperseded na idx+            if skip+              then containers (j + 1) m om hm foundOld foundOuter dropped+              else do+                k <- if keyless then containerKey na idx else pure (intKey wid)+                let isOld = keyless && IM.member k oldRects+                mRect <- getNonzeroRect na idx+                (m', om', hm', fOld', fOuter', drop') <- case mRect of+                  Nothing ->+                    pure+                      ( if isOld then IM.delete k m else m+                      , dropKey k om+                      , if keyless then dropKey k hm else hm+                      , foundOld+                      , foundOuter+                      , dropped || isOld+                      )+                  Just r -> do+                    o <- outerClip na window idx+                    h <- if keyless then getNodePaintHash na idx else pure 0+                    pure+                      ( if keyless then putNew k r m else m+                      , putNew k o om+                      , if keyless then putNew k h hm else hm+                      , foundOld + if isOld then 1 else 0+                      , foundOuter + if IM.member k oldOuters then 1 else 0+                      , dropped+                      )+                containers (j + 1) m' om' hm' fOld' fOuter' drop'+  containers 0 oldRects oldOuters oldHashes 0 0 False++-- | Record this frame's solved rects, clips and paint hashes by widget key+-- ('dsPrev') for the next frame's damage to diff against. Returns the rects+-- of the widgets this frame mounted, by key: the map 'dsPrev' now holds, or+-- an empty map for an empty arena. 'pruneUnmountedCaches' takes it.+updatePrevRects :: Context -> Size -> IO (IM.IntMap Rect)+updatePrevRects ctx@Context {ctxNodeArena = na} size@(Size winW winH) = do+  PrevFrame oldRects oldClips oldOuters oldHashes oldEffects <- getsDamage ctx dsPrev+  count <- arenaCount na+  let setPrev p = modifyDamage ctx (\ds -> ds {dsPrev = p})+  if count <= 0+    then IM.empty <$ (setPrev emptyPrevFrame >> prevWalkFor ctx 0 IM.empty)+    else do+      (m0, om, hm0, foundContainers, foundOuter, droppedContainer) <-+        scanBackdropPrevRects na (Rect 0 0 winW winH) oldRects oldOuters oldHashes+      (walk, known) <- prevWalkFor ctx count oldRects+      a <- arenaArrays na+      let !geom = naArrGeom a+          !hashes = naArrPaintHash a+          go !i !m !cm !hm !foundOld !dropped+            | i >= count =+                if dropped || foundOld /= IM.size oldRects || foundOuter /= IM.size oldOuters+                  then setPrev emptyPrevFrame >> updatePrevRects ctx size+                  else do+                    effRects <- collectEffectRects ctx oldEffects+                    writeIORef (pwFor walk) m+                    writePrimVar (pwValid walk) count+                    unless+                      ( ptrEq m oldRects+                          && ptrEq cm oldClips+                          && ptrEq om oldOuters+                          && ptrEq hm oldHashes+                          && ptrEq effRects oldEffects+                      )+                      (setPrev (PrevFrame m cm om hm effRects))+                    pure m+            | otherwise = do+                !k <- readTree a i TreeWidgetId+                superseded <- if k == 0 then pure True else readTagEnum a i TagIdSuperseded+                if superseded+                  then forgetAt walk i >> go (i + 1) m cm hm foundOld dropped+                  else do+                    let !gOff = i * geomStride+                    !rx <- readPrimArray geom gOff+                    !ry <- readPrimArray geom (gOff + 1)+                    !rw <- readPrimArray geom (gOff + 2)+                    !rh <- readPrimArray geom (gOff + 3)+                    if not (rw > 0 && rh > 0)+                      then do+                        forgetAt walk i+                        let !isOld = IM.member k oldRects+                        go (i + 1) (if isOld then IM.delete k m else m) (dropKey k cm) (dropKey k hm) foundOld (dropped || isOld)+                      else do+                        !cx <- readPrimArray geom (gOff + 4)+                        !cy <- readPrimArray geom (gOff + 5)+                        !cwRaw <- readPrimArray geom (gOff + 6)+                        !chRaw <- readPrimArray geom (gOff + 7)+                        let !posClip = cwRaw > 0 && chRaw > 0+                            !hasClip = posClip || cwRaw < 0+                            !cw = if posClip then cwRaw else 0+                            !ch = if posClip then chRaw else 0+                        same <- keepKeyAt walk known i k (if hasClip then 1 else 0)+                        -- An unchanged rect keeps the object already+                        -- stored, so a still frame allocates nothing; a new+                        -- one is boxed only when coordinates changed.+                        was@(Rect wx wy ww wh) <- readArray (pwRects walk) i+                        let !rectMoved = rx /= wx || ry /= wy || rw /= ww || rh /= wh+                        now <-+                          if not rectMoved+                            then pure was+                            else do+                              let !r = Rect rx ry rw rh+                              writeArray (pwRects walk) i r+                              pure r+                        clipMoved <- if hasClip then swapClip (pwClips walk) i cx cy cw ch else pure False+                        !h <- readPrimArray hashes i+                        !h0 <- readPrimArray (pwHashes walk) i+                        unless (h == h0) (writePrimArray (pwHashes walk) i h)+                        let !m'+                              | not same = putNew k now m+                              | rectMoved = IM.insert k now m+                              | otherwise = m+                            !cm'+                              | not same = if hasClip then putNew k (Rect cx cy cw ch) cm else dropKey k cm+                              | clipMoved = IM.insert k (Rect cx cy cw ch) cm+                              | otherwise = cm+                            !fOld'+                              | not same = foundOld + if IM.member k oldRects then 1 else 0+                              | otherwise = foundOld + 1+                            !hm'+                              | not same || h /= h0 = putHash k h hm+                              | otherwise = hm+                        go (i + 1) m' cm' hm' fOld' dropped+      go 0 m0 oldClips hm0 foundContainers droppedContainer++-- | Drop the scroll views ('ssViews') and rich-text selections+-- ('storeRichSelection') of widgets not in @live@, the map+-- 'updatePrevRects' returned. Those maps keep an entry for every widget+-- ever shown. The limit scales with @live@, so a view with more than 256+-- mounted widgets does not intersect the maps every frame. An empty arena+-- prunes nothing.+pruneUnmountedCaches :: Context -> IM.IntMap Rect -> IO ()+pruneUnmountedCaches ctx live = do+  count <- arenaCount (ctxNodeArena ctx)+  when (count > 0) $ do+    let !pruneLimit = max 256 (2 * IM.size live)+    ss <- readIORef (ctxScrollState ctx)+    when (IM.size (ssViews ss) > pruneLimit) $+      writeIORef (ctxScrollState ctx) $! ss {ssViews = IM.intersection (ssViews ss) live}+    st <- readIORef (ctxStore ctx)+    when (IM.size (storeRichSelection st) > pruneLimit) $+      writeIORef (ctxStore ctx) $! st {storeRichSelection = IM.intersection (storeRichSelection st) live}++-- | The last walk's record, with room for @count@ nodes, and how many of its+-- indices describe @oldRects@. It reads as empty until this walk completes,+-- so a walk that restarts or throws leaves nothing stale behind. Clears+-- entries past @count@.+{-# INLINE prevWalkFor #-}+prevWalkFor :: Context -> Int -> IM.IntMap Rect -> IO (PrevWalk, Int)+prevWalkFor ctx count oldRects = do+  lastWalk <- readIORef (ctxPrevWalk ctx)+  valid <- readPrimVar (pwValid lastWalk)+  for <- readIORef (pwFor lastWalk)+  if sizeofMutableArray (pwRects lastWalk) >= count+    then do+      writePrimVar (pwValid lastWalk) 0+      forgetFrom lastWalk count valid+      pure (lastWalk, if ptrEq for oldRects then valid else 0)+    else do+      walk <- newPrevWalk (max 64 (2 * count))+      writeIORef (ctxPrevWalk ctx) walk+      pure (walk, 0)++-- | 'forgetAt' each node from @i@ up to @n@.+forgetFrom :: PrevWalk -> Int -> Int -> IO ()+forgetFrom walk !i !n = when (i < n) (forgetAt walk i >> forgetFrom walk (i + 1) n)++-- | Record that the walk made no entries for node @i@.+{-# INLINE forgetAt #-}+forgetAt :: PrevWalk -> Int -> IO ()+forgetAt walk i = do+  k0 <- readPrimArray (pwKeys walk) i+  unless (k0 == 0) $ do+    writePrimArray (pwKeys walk) i 0+    writePrimArray (pwTags walk) i 0++-- | Record key @k@, and @tag@ (1 when the node has a clip), for node @i@,+-- returning whether the last walk recorded the same there (below @known@).+{-# INLINE keepKeyAt #-}+keepKeyAt :: PrevWalk -> Int -> Int -> Int -> Int -> IO Bool+keepKeyAt walk known i k tag = do+  k0 <- readPrimArray (pwKeys walk) i+  t0 <- readPrimArray (pwTags walk) i+  if k0 == k && t0 == tag+    then pure $! i < known+    else do+      writePrimArray (pwKeys walk) i k+      writePrimArray (pwTags walk) i tag+      pure False++-- | Write node @i@'s clip if it changed, and return whether it changed.+{-# INLINE swapClip #-}+swapClip :: MutablePrimArray RealWorld Float -> Int -> Float -> Float -> Float -> Float -> IO Bool+swapClip clips i x y w h = do+  let !o = 4 * i+  same <- eqRectAt clips o x y w h+  if same then pure False else True <$ writeRectAt clips o x y w h++-- | Insert, returning @m@ itself when @k@ already maps to @v@, so pointer+-- equality survives an unchanged frame.+{-# INLINE putNew #-}+putNew :: Eq a => Int -> a -> IM.IntMap a -> IM.IntMap a+putNew k v m = if IM.lookup k m == Just v then m else IM.insert k v m++-- | 'putNew' for a paint hash. Not inlined: inlined, the walk boxed every+-- node's hash whether or not it was stored.+{-# NOINLINE putHash #-}+putHash :: Int -> Word64 -> IM.IntMap Word64 -> IM.IntMap Word64+putHash = putNew++-- | Delete, returning @m@ itself when @k@ is absent.+{-# INLINE dropKey #-}+dropKey :: Int -> IM.IntMap a -> IM.IntMap a+dropKey k m = if IM.member k m then IM.delete k m else m++-- | Keyed floating panels in paint order, bottom first (every window, then+-- every modal, then every popup): key, solved rect, and whether the panel+-- intercepts pointer events (excluding 'PointerPass' panels such as tooltips).+floatingPanels :: Context -> IO [(Int, Rect, Bool)]+floatingPanels Context {ctxNodeArena = na} = do+  n <- floatingNodeCount na+  if n == 0+    then pure []+    else catMaybes <$> (mapM step =<< floatingNodesInPaintOrder na)+  where+    step idx = do+      wid <- getWidgetId na idx+      if hashWidgetId wid == 0+        then pure Nothing+        else do+          r <- getNodeRect na idx+          mode <- getPointerMode na idx+          pure (Just (intKey wid, r, mode /= PointerPass))++-- | Current floating-panel bounds keyed by widget id, in logical window coordinates.+floatingPanelRects :: Context -> IO (IM.IntMap Rect)+floatingPanelRects ctx = IM.fromList . map (\(k, r, _) -> (k, r)) <$> floatingPanels ctx++-- | State 'NanoUI.Internal.Frame' captures before the UI pass; 'writeDamage' compares+-- it against the finished frame.+data FrameSnapshot = FrameSnapshot+  { fsSize :: !Size+  , fsStore :: !WidgetStore+  , fsHot :: !WidgetId+  , fsActive :: !WidgetId+  , fsFocus :: !WidgetId+  , fsFocusVisible :: !Bool+  , fsFloatingRects :: !(IM.IntMap Rect)+  , fsPrev :: !PrevFrame+  , fsAnimKeys :: !IS.IntSet+  }++-- | Read the 'FrameSnapshot' before the UI pass.+captureFrameSnapshot :: Context -> IO FrameSnapshot+captureFrameSnapshot ctx = do+  ds <- readIORef (ctxDamageState ctx)+  evaluate+    =<< FrameSnapshot (dsLastWindowSize ds)+      <$> getStore ctx+      <*> readIORef (ctxLastHotId ctx)+      <*> readIORef (ctxActiveId ctx)+      <*> readIORef (ctxFocusId ctx)+      <*> readIORef (ctxFocusVisible ctx)+      <*> getsOverlay ctx osPrevFloatingRects+      <*> pure (dsPrev ds)+      <*> liveAnimationKeys ctx++-- | What the finished frame looks like and what changed since the snapshot.+-- Derived fields stay lazy: a frame that is already 'DamageFull' for a cheap+-- reason never pays for them.+data FrameDelta = FrameDelta+  { fdWinSize :: !Size+  , fdStore :: !WidgetStore+  , fdPrev :: !PrevFrame+  -- ^ This frame's 'dsPrev'.+  , fdFloatingRects :: !(IM.IntMap Rect)+  , fdModalFlip :: !Bool+  , fdLiveAnims :: !IS.IntSet+  , fdWindowLive :: !Bool+  , fdRequests :: ![DamageRequest]+  , fdAnimLive :: Bool+  , fdFloatingChanged :: Bool+  , fdScrollChanged :: Bool+  , fdPointsChanged :: Bool+  , fdScrollOnly :: Bool+  -- ^ Only 'storeFloat' (and the 'storeQuiet' bookkeeping) changed in the+  -- store, e.g. a floating pane scrolled, and not by a float the frame+  -- measured of its own layout.+  , fdSettledMoved :: !RectGroup+  -- ^ Changed key rects, clipped to their scroll viewports, that cover some+  -- area.+  , fdChurn :: !RectGroup+  -- ^ Rects of keys that left or joined the arena.+  , fdRedrawn :: ![Int]+  -- ^ Keys of drawings whose ops changed at an unchanged rect.+  }++-- | Work out the frame's damage against @snap@ and record it, with what the+-- next frame compares against. @mayReuse@: the frame may take the last+-- frame's draw ('NanoUI.Internal.Frame.paintOrReuse'), which it does only+-- when nothing is damaged. @layoutFloats@: the frame published a float it+-- measured of its own layout ('NanoUI.Internal.Context.Core.publishLayoutSlots'),+-- so its float change is no scroll: widgets moved with it.+writeDamage :: Context -> Input -> FrameSnapshot -> Bool -> Bool -> IO ()+writeDamage ctx inp snap mayReuse layoutFloats = do+  newStore <- getStore ctx+  panels <- floatingPanels ctx+  new <- getsDamage ctx dsPrev+  modalFlip <- modalDamageFlip ctx+  liveAnims <- liveAnimationKeys ctx+  settled <- takeAnimSettled ctx+  windowLive <- getsInteraction ctx (\s -> isJust (isWindowDrag s) || isJust (isWindowResize s))+  requests <- getsDamage ctx dsRequests+  redrawn <- refreshCustomDrawings ctx+  wanted <- readIORef (ctxDamageWanted ctx)+  let oldStore = fsStore snap+      newFloatingRects = if null panels then IM.empty else IM.fromList [(k, r) | (k, r, _) <- panels]+      floatingChanged = not (IM.null (fsFloatingRects snap) && IM.null newFloatingRects) && fsFloatingRects snap /= newFloatingRects+      changes = do+        (settledMoved, churn) <- rectDeltas (if null panels then [] else [r | (_, r, _) <- panels]) (fsPrev snap) new+        let scrollChanged = not (eqByPtr (storeFloat oldStore) (storeFloat newStore))+            pointsChanged = not (eqByPtr (storePoint oldStore) (storePoint newStore))+        let delta =+              FrameDelta+                { fdWinSize = inputWindowSize inp+                , fdStore = newStore+                , fdPrev = new+                , fdFloatingRects = newFloatingRects+                , fdModalFlip = modalFlip+                , fdLiveAnims = liveAnims+                , fdWindowLive = windowLive+                , fdRequests = requests+                , fdAnimLive = not (IS.null liveAnims) || settled+                , fdFloatingChanged = floatingChanged+                , fdScrollChanged = scrollChanged+                , fdPointsChanged = pointsChanged+                , fdScrollOnly =+                    scrollChanged+                      && not layoutFloats+                      && not pointsChanged+                      && storeOpenSelect oldStore == storeOpenSelect newStore+                      && null (slotChangedKeys oldStore newStore)+                , fdSettledMoved = settledMoved+                , fdChurn = churn+                , fdRedrawn = redrawn+                }+        -- The store diff runs only once the cheap checks would clip: a frame+        -- already repainting whole needs no per-key damage.+        case fullDamageCause snap delta of+          cause@(_ : _) -> (DamageFull, []) <$ traceDamage ("DAMAGE full " <> cause)+          [] -> do+            (misses, owners) <- storeKeyChanges ctx oldStore newStore+            -- A changed key that resolves to no node (a widget-internal key+            -- nothing in the arena carries) may have changed+            -- paint state no diff describes, so nothing narrower than the window+            -- is known to cover it. Key 0 names no widget and is damaged by+            -- nothing, so its writes cannot escalate a frame.+            if any (\k -> k /= 0 && IM.notMember k owners) misses+              then (DamageFull, []) <$ traceDamage "DAMAGE full store-key-without-owner"+              else clipDamage ctx snap delta owners+  -- A host repainting the whole window whatever changed does not read the+  -- damage, so nothing is diffed ('ctxDamageWanted'), unless the frame may+  -- reuse the last draw: that takes damage known to be empty. A frame whose+  -- recorded rects, clips, texts or images changed ('updatePrevRects' kept+  -- no record unchanged) almost always has damage, and one that redrew a+  -- drawing in view has it for sure ('clipDamage'), so those paint instead+  -- of diffing. An idle frame diffs cheaply: its maps and store compare by+  -- pointer. A drawing redrawn out of view (an animation scrolled away)+  -- leaves the frame to the diff, which finds nothing to repaint.+  let Size winW winH = inputWindowSize inp+      inView k = maybe False (rectNonEmpty . clipRectToWindow winW winH . clipToViewport (ownClip new k)) (IM.lookup k (pfRects new))+      diff = wanted || (mayReuse && samePrev (fsPrev snap) new && not (any inView redrawn))+  (dmg, pieces) <- if diff then changes else (DamageFull, []) <$ traceDamage "DAMAGE full not-diffed"+  modifyDamage ctx $ \ds ->+    ds+      { dsDamage = dmg+      , dsDamagePieces = pieces+      , dsLastWindowSize = inputWindowSize inp+      , dsRequests = []+      }+  -- Most frames have no panel now or before, and then there is nothing to write.+  prevEmpty <- getsOverlay ctx (IM.null . osPrevFloatingRects)+  unless (null panels && prevEmpty) $+    modifyOverlay ctx $ \os ->+      os {osPrevFloatingRects = newFloatingRects, osPrevFloatingOrder = [k | (k, _, True) <- panels]}+  -- The follow-up frames these request only settle placement: the flip made+  -- this frame repaint whole, and a floating change did too or, on a frame+  -- that only scrolled, damaged each moved panel where it was and is, so+  -- their pixels are not waiting on the next frame.+  when modalFlip (markDirty ctx)+  when (floatingChanged && not (IM.null (fsFloatingRects snap) && not (IM.null newFloatingRects))) $+    markDirty ctx+  -- A popup placed by its anchor's last rect ('NanoUI.respRect') is a frame+  -- behind an anchor this frame moved (a widget last had the anchor's rect+  -- and now has another), and nothing else may ask for the frame that+  -- catches it up.+  -- Forced: 'ptrEq' on a selector thunk never matches.+  let !oldRects = pfRects (fsPrev snap)+      !newRects = pfRects new+      moved a = IM.foldrWithKey (\k r rest -> (r == a && IM.lookup k newRects /= Just a) || rest) False oldRects+      anchorMoved idx =+        getNodeType (ctxNodeArena ctx) idx >>= \case+          NodePopup ->+            (\case Just (AnchorRect a, _, _) -> moved a; _ -> False)+              <$> (lookupPopupConfig ctx =<< getWidgetId (ctxNodeArena ctx) idx)+          _ -> pure False+  unless (ptrEq oldRects newRects) $+    findClassNodeM (ctxNodeArena ctx) FloatingNodes anchorMoved >>= \found ->+      when (isJust found) (markDirty ctx)++-- | Whether 'updatePrevRects' left every map of @old@ as it was. Compared by+-- map, not by record: GHC may rebuild a record passed unboxed.+samePrev :: PrevFrame -> PrevFrame -> Bool+samePrev (PrevFrame !r0 !c0 !o0 !h0 !e0) (PrevFrame !r1 !c1 !o1 !h1 !e1) =+  ptrEq r0 r1 && ptrEq c0 c1 && ptrEq o0 o1 && ptrEq h0 h1 && ptrEq e0 e1++-- | Settle every drawing's ops for this frame and return the keys of those+-- that now draw something else at an unchanged rect. A drawing follows state+-- the arena does not hold, so nothing else damages it, and paint must not+-- replay the previous frame's ops for it. What this costs per widget is the+-- widget's own choice: see 'refreshCustomDrawingOps'.+refreshCustomDrawings :: Context -> IO [Int]+refreshCustomDrawings ctx@Context {ctxNodeArena = na} =+  -- The walk visits only the drawing nodes, so a view without any skips it.+  foldClassNodesM na DrawingNodes step []+  where+    step acc i = do+      wid <- getWidgetId na i+      rect <- getNodeRect na i+      mCustom <- lookupCustomDrawingAt ctx i+      changed <- case mCustom of+        Just CustomDrawingEntry {cdrContent = content, cdrBuild = build} -> do+          cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) wid+          refreshCustomDrawingOps ctx wid content rect cdc build+        Nothing -> do+          -- A versioned drawing rebuilds in paint once its version+          -- changes, but the pixels it covered still need damage. An+          -- unversioned one is cached by contract, so it stays put.+          mDrawing <- lookupDrawingAt ctx i+          case mDrawing of+            Just (DrawingEntry content _) | content /= 0 -> drawingOpsStale ctx wid content rect+            _ -> pure False+      pure (if changed then intKey wid : acc else acc)++-- | The check that makes the frame repaint the whole window rather than a+-- clip, or the empty string for none. 'traceDamage' prints it.+--+-- Store writes and nodes whose paint inputs changed are repainted per key+-- instead ('storeKeyChanges', 'clipDamage'); 'writeDamage' escalates a+-- frame whose changed store keys do not all resolve to a node after this+-- check.+fullDamageCause :: FrameSnapshot -> FrameDelta -> String+fullDamageCause snap d+  | ReqFull `elem` fdRequests d = "request"+  | neverPainted = "first"+  -- A resize, a modal opening or closing (its dim covers the window, and a+  -- Var-bound modal writes nothing to the store) and a live window drag are+  -- window-wide whatever scrolled in the same frame.+  | sizeChanged = "resize"+  | fdModalFlip d = "modal"+  | fdWindowLive d = "window-gesture"+  | not (fdScrollOnly d) && fdFloatingChanged d = "floating"+  | not (fdScrollOnly d) && orphanAnim && fdAnimLive d = "orphan-animation"+  | not (fdScrollOnly d) && keysChanged = "key-churn"+  | not (fdScrollOnly d) && layoutSettle = "layout"+  | missingAnim && fdAnimLive d = "missing-animation"+  | otherwise = ""+  where+    oldRects = pfRects (fsPrev snap)+    newRects = pfRects (fdPrev d)+    oldSize = fsSize snap+    -- Before any frame there is nothing to diff against, and the window+    -- backdrop outside every widget rect was never painted.+    neverPainted = oldSize == Size 0 0+    sizeChanged = oldSize /= fdWinSize d+    -- A live animation repaints whole on its first frame without a rect: its+    -- widget just left, or it has none and started this frame. After that it+    -- is clipped like the rest, so a perpetual animation whose widget has+    -- left the arena (@keepAnimating@ behind a tab switch) stops repainting+    -- the window.+    animKeys = IS.toList (fdLiveAnims d)+    firstRectless k =+      IM.notMember k newRects && (IM.member k oldRects || IS.notMember k (fsAnimKeys snap))+    orphanAnim = any firstRectless animKeys+    -- One with no rect last frame either is not clipped even when only a+    -- scroller moved: the retain texture may never have shown it.+    missingAnim =+      any (\k -> k /= 0 && IM.notMember k oldRects && IM.notMember k newRects && IS.notMember k (fsAnimKeys snap)) animKeys+    keysChanged =+      not (IM.null oldRects)+        && rgAny (fdChurn d)+        && not (rgInPanels (fdChurn d))+    layoutSettle =+      not (IM.null oldRects)+        && rgAny (fdSettledMoved d)+        && not (fdAnimLive d)+        && not (fdScrollChanged d)+        && not (rgInPanels (fdSettledMoved d))++-- | Monadic builder for collecting damage rects across frames.+newtype DamageCollector a = DamageCollector (RectUnion -> IO a)+  deriving (Functor, Applicative, Monad, MonadIO) via (ReaderT RectUnion IO)++{-# INLINE collectDamage #-}+collectDamage :: DamageCollector () -> IO [Rect]+collectDamage (DamageCollector act) = do+  ref <- newIORef []+  act ref+  readIORef ref++{-# INLINE addDamageRect #-}+addDamageRect :: Rect -> DamageCollector ()+addDamageRect r = DamageCollector (`addRect` r)++{-# INLINE addDamageKey #-}+addDamageKey :: PrevFrame -> Int -> Rect -> Rect -> DamageCollector ()+addDamageKey p k r d = DamageCollector $ \ref -> addKeyDamage ref p k r d++{-# INLINE addDamageKeyGrow #-}+addDamageKeyGrow :: PrevFrame -> Int -> (Rect -> Rect) -> DamageCollector ()+addDamageKeyGrow p k grow =+  forM_ (IM.lookup k (pfRects p)) $ \r -> addDamageKey p k r (grow r)++{-# INLINE addDamageGroup #-}+addDamageGroup :: RectGroup -> DamageCollector ()+addDamageGroup g = when (rgAny g) $ addDamageRect (rgBounds g)++-- | The clip covering everything that changed, with the pieces it splits+-- into ('damagePieces'), or 'DamageFull' once the pieces cover over half the+-- window.+clipDamage ::+  Context -> FrameSnapshot -> FrameDelta -> IM.IntMap NodeIdx -> IO (Damage, [Rect])+clipDamage ctx snap d owners = do+  let old = fsPrev snap+      new = fdPrev d+      Size winW winH = fdWinSize d+      rectIn p wid = IM.lookup (intKey wid) (pfRects p)+      damageBoth k grow = addDamageKeyGrow old k grow >> addDamageKeyGrow new k grow+      resolveKey k = damageBoth k . resolveDamageRect+      resolveSlop k = resolveKey k (DamageInflated defaultDamageSlop)+      addBackdrop k = unless (k == 0) $ do+        mbNode <- liftIO (lookupNodeByKey (ctxNodeArena ctx) k)+        forM_ mbNode $ \idx ->+          liftIO (backdropRectFromNode ctx idx) >>= mapM_ addDamageRect+      hadRole wid = wid == fsHot snap || wid == fsActive snap || wid == fsFocus snap+      addInteraction wid = unless (k == 0) $ do+        slop <- fromMaybe defaultDamageSlop <$> liftIO (lookupCustomDamageSlop ctx wid)+        forM_ (if hadRole wid then rectIn old wid else Nothing) $ \r -> addDamageKey old k r (rectInflate slop r)+        forM_ (rectIn new wid) $ \r -> addDamageKey new k r (rectInflate slop r)+        addBackdrop k+        where+          k = intKey wid+      -- A parked pointer must not re-damage its hot widget every frame: only+      -- an id change (hover in/out, press, focus move) or a rect move+      -- repaints. Unchanged interaction rects kept the steady state at+      -- DamageFull whenever the hot widget sat inside a panel whose backdrop+      -- covered over half the window.+      role oldW newW = when (oldW /= newW || rectIn old oldW /= rectIn new newW) $ addInteraction oldW >> addInteraction newW+      !newHashes = pfHashes new+      !oldHashes = pfHashes old+  added <- collectDamage $ do+    forM_ (fdRequests d) $ \case+      ReqFull -> pure ()+      ReqRect r -> addDamageRect r+      ReqWidget wid bounds -> resolveKey (intKey wid) bounds+      ReqKey k bounds -> resolveKey k bounds >> addBackdrop k+      ReqPeers wids bounds -> forM_ wids $ \wid -> resolveKey (intKey wid) bounds+    role (fsHot snap) =<< liftIO (getHotId ctx)+    role (fsActive snap) =<< liftIO (readIORef (ctxActiveId ctx))+    focus <- liftIO (readIORef (ctxFocusId ctx))+    role (fsFocus snap) focus+    -- The focus ring shows or hides on the same widget.+    focusVisible <- liftIO (readIORef (ctxFocusVisible ctx))+    when (focusVisible /= fsFocusVisible snap && focus == fsFocus snap) (addInteraction focus)+    when (fdScrollChanged d || fdPointsChanged d) $+      scrollOffsetDamage ctx (fsStore snap) (fdStore d)+    forM_ (IS.toList (IS.fromList (IM.elems owners))) $ \idx ->+      resolveSlop . intKey =<< liftIO (getWidgetId (ctxNodeArena ctx) idx)+    forM_ (IS.toList (fsAnimKeys snap <> fdLiveAnims d)) $ \k ->+      unless (k == 0) (resolveSlop k)+    -- A node the view gave other paint inputs (text, value, style, colour,+    -- scope, image) repaints. A widget repaints with its halo, where it was+    -- and where it is; text, a box or an image paints inside its rect, which+    -- a move damages already.+    let repaintNode k = do+          halo <- liftIO (lookupNodeByKey (ctxNodeArena ctx) k >>= maybe (pure False) (fmap isWidgetNode . getNodeType (ctxNodeArena ctx)))+          if halo then resolveSlop k else addDamageKeyGrow new k id+    unless (ptrEq newHashes oldHashes) $+      forM_ (IM.keys (IM.differenceWith (\n o -> if n /= o then Just n else Nothing) newHashes oldHashes)) repaintNode+    forM_ (fdRedrawn d) $ \k -> addDamageKeyGrow new k id+    -- Also on a scroll-only frame: 'storeFloat' holds slider values too, and+    -- a label showing one can shrink or move what follows it. A scroll's own+    -- moves are clipped to the viewport its offset damage already covers.+    addDamageGroup (fdSettledMoved d)+    addDamageGroup (fdChurn d)+    -- A panel paints its offset shadow past its rect ('menuPanelBounds'), and+    -- Tier 2 shader effects paint halos out to their margin-expanded bounds.+    let addMapDiff f a b =+          IM.foldrWithKey (\k r rest -> unless (IM.lookup k b == Just r) (addDamageRect (f r)) >> rest) (pure ()) a+        diffBoth f a b = addMapDiff f a b >> addMapDiff f b a+    diffBoth menuPanelBounds (fsFloatingRects snap) (fdFloatingRects d)+    let oldEffects = pfEffectRects old+        newEffects = pfEffectRects new+    unless (ptrEq oldEffects newEffects) $ diffBoth id oldEffects newEffects+  -- Only what lands in the window counts: an empty rect, or one off the+  -- window, would stretch the bounds over pixels nothing changed.+  let added' = if null added then added else expandEffectDamage old new added+  let visible = filter rectNonEmpty (map (clipRectToWindow winW winH) added')+      clip = rectBounds visible+      winArea = winW * winH+      -- A frame with more rects than this repaints their bounds.+      pieces+        | null (drop 64 visible) = damagePieces visible+        | otherwise = []+      area = if null pieces then rectArea clip else sum (map rectArea pieces)+  -- A live animation with an empty clip is not DamageFull: its+  -- key was either scroll-clipped out of view (nothing visible+  -- changes; scrolling back in damages via the scroll delta) or+  -- rect-less, which missingAnim already promoted to full.+  if winArea > 0 && area > winArea * 0.5+    then (DamageFull, []) <$ traceDamage "DAMAGE full area"+    else (DamageClip clip, pieces) <$ traceDamage "DAMAGE clip"++-- | Collect margin-expanded bounds of every active Tier 2 'NanoUI.withShader'+-- container, reusing @oldEffects@ when unchanged so still frames allocate+-- nothing and frames without effects return 'IM.empty' immediately.+{-# NOINLINE collectEffectRects #-}+collectEffectRects :: Context -> IM.IntMap Rect -> IO (IM.IntMap Rect)+collectEffectRects ctx oldEffects = do+  effNodes <- activeEffectNodes ctx+  if null effNodes+    then pure (if IM.null oldEffects then oldEffects else IM.empty)+    else do+      let na = ctxNodeArena ctx+          inflateXY (V2 mx my) (Rect x y w h) = Rect (x - mx) (y - my) (w + 2 * mx) (h + 2 * my)+          step acc idx = do+            mEntry <- lookupShaderEffectAt ctx idx+            case mEntry of+              Nothing -> pure acc+              Just entry -> do+                r <- inflateXY (seeMargin entry) <$> getNodeRect na idx+                wid <- getWidgetId na idx+                let !k = intKey wid+                pure (if k /= 0 && rectNonEmpty r then IM.insert k r acc else acc)+      effs <- foldM step IM.empty effNodes+      pure (if effs == oldEffects then oldEffects else effs)++-- | When either the previous or current frame uses Tier 2 shader effects+-- ('NanoUI.withShader'), expand any damage rect touching an effect container+-- to cover its full margin-expanded bounds (at both its new and previous+-- positions) so blurs, shadows, and distortions repaint without clipped halos+-- or stale trails.+expandEffectDamage :: PrevFrame -> PrevFrame -> [Rect] -> [Rect]+expandEffectDamage old new rects+  | IM.null oldEffs && IM.null newEffs = rects+  | otherwise =+      let touches rs r = any (isJust . rectIntersect r) rs+          expandWith acc k curR =+            let mOldR = IM.lookup k oldEffs+             in if touches acc curR || maybe False (touches acc) mOldR+                  then curR : maybe acc (: acc) mOldR+                  else acc+          acc1 = IM.foldlWithKey' expandWith rects newEffs+          expandOld acc k oldR+            | IM.member k newEffs = acc+            | touches acc oldR = oldR : acc+            | otherwise = acc+       in IM.foldlWithKey' expandOld acc1 oldEffs+  where+    oldEffs = pfEffectRects old+    newEffs = pfEffectRects new++-- | Most rects a frame's damage splits into.+maxDamagePieces :: Int+maxDamagePieces = 4++-- | Rects closer than this, in logical pixels, merge into one piece. It is+-- more than the backdrop's inflation on both sides, so pieces stay disjoint+-- once each is painted a pixel past its edge.+pieceMergeGap :: Float+pieceMergeGap = 16++-- | Split damage into at most 'maxDamagePieces' disjoint rects: rects that+-- overlap or lie within 'pieceMergeGap' of each other merge, and then the+-- pair whose union grows least merges until few enough remain. Returns no+-- pieces when one or none remain, or when they cover most of their bounding+-- box, since painting the box costs about the same.+damagePieces :: [Rect] -> [Rect]+damagePieces [] = []+damagePieces [_] = []+damagePieces rects =+  case shrink (settle (filter rectNonEmpty rects)) of+    ps@(_ : _ : _)+      | sum (map rectArea ps) < 0.7 * rectArea (foldr1 rectUnion ps) -> ps+    _ -> []+  where+    near a b = isJust (rectIntersect (rectInflate pieceMergeGap a) b)+    -- Merge the first near pair until no pair is near.+    settle ps = maybe ps settle (mergeNear ps)+    mergeNear [] = Nothing+    mergeNear (p : ps) = case break (near p) ps of+      (before, q : after) -> Just (rectUnion p q : before ++ after)+      (_, []) -> (p :) <$> mergeNear ps+    shrink ps+      | length ps <= maxDamagePieces = ps+      | otherwise =+          let indexed = zip [0 :: Int ..] ps+              cost a b = rectArea (rectUnion a b) - rectArea a - rectArea b+              (_, i, j) = minimum [(cost a b, i', j') | ((i', a) : later) <- tails indexed, (j', b) <- later]+              (pair, rest) = partition (\(k, _) -> k == i || k == j) indexed+           in shrink (settle (foldr1 rectUnion (map snd pair) : map snd rest))++-- | Add damage @d@ for key @k@'s rect @r@ in frame @p@, clipped to the clip+-- @r@ is painted in there ('ownClip'). For a scroll container or panel (a key+-- in 'pfOuterClips') @d@ is also kept inside @r@: slop is for a widget's+-- halo, which those lack, and their wider outer clip would let it spill.+addKeyDamage :: RectUnion -> PrevFrame -> Int -> Rect -> Rect -> IO ()+addKeyDamage acc p k r d =+  when (rectNonEmpty clipped) $ addRect acc clipped+  where+    clipped = clipToViewport (ownClip p k) (if IM.member k (pfOuterClips p) then clipToViewport (Just r) d else d)++-- | The rects damage gathers, newest first.+type RectUnion = IORef [Rect]++{-# INLINE addRect #-}+addRect :: RectUnion -> Rect -> IO ()+addRect acc r = modifyIORef' acc (r :)++-- | The bounds of @rects@, empty ones included, or the zero rect for none.+rectBounds :: [Rect] -> Rect+rectBounds [] = Rect 0 0 0 0+rectBounds (r : rs) = foldl' rectUnion r rs++-- | A set of rects reduced to what damage needs from it.+data RectGroup = RectGroup+  { rgAny :: !Bool+  , rgInPanels :: !Bool+  -- ^ Some floating panel fully contains each rect; False for an empty group.+  , rgBounds :: !Rect+  }++-- | One pass over keys whose rect changed, split into settled moves (each+-- side clipped to its viewport in its own frame, kept above+-- 'layoutSettleMinArea') and keys that left or joined the arena.+rectDeltas :: [Rect] -> PrevFrame -> PrevFrame -> IO (RectGroup, RectGroup)+rectDeltas panelRects oldP newP+  | ptrEq old new = pure (emptyGroup, emptyGroup)+  | otherwise =+      pure $+        let (settled, churn) =+              IM.foldrWithKey+                ( \k r (!accS, !accC) ->+                    if rectNonEmpty r+                      then+                        let !accC' = if IM.notMember k new || IM.notMember k old then r : accC else accC+                            oldClip = ownClip oldP k+                            newClip = ownClip newP k+                            side clip = maybe (Rect 0 0 0 0) (clipToViewport clip)+                            clipped+                              | oldClip == newClip = clipToViewport newClip r+                              | otherwise = unionNonEmpty (side oldClip (IM.lookup k old)) (side newClip (IM.lookup k new))+                            !accS' = if rectArea clipped >= layoutSettleMinArea then clipped : accS else accS+                         in (accS', accC')+                      else (accS, accC)+                )+                ([], [])+                (IM.mergeWithKey (\_ a b -> if a /= b then Just (rectUnion a b) else Nothing) id id old new)+         in (group settled, group churn)+  where+    -- Forced, so an unchanged frame's maps compare by pointer ('ptrEq').+    !old = pfRects oldP+    !new = pfRects newP+    emptyGroup = RectGroup False False (Rect 0 0 0 0)+    unionNonEmpty a b+      | not (rectNonEmpty a) = b+      | not (rectNonEmpty b) = a+      | otherwise = rectUnion a b+    inPanels r = any (rectFullyInside r) panelRects+    group rs = RectGroup (not (null rs)) (not (null rs || null panelRects) && all inPanels rs) (rectBounds rs)++-- | The clip key @k@'s rect is painted in, in frame @p@: the outer clip for a+-- scroll container or panel, otherwise its viewport clip. Each rect uses its+-- own frame's clip because the current viewport can be smaller than the old+-- one (an enclosing widget or scroller shrank), which would cut the vacated+-- pixels out of the damage.+{-# INLINE ownClip #-}+ownClip :: PrevFrame -> Int -> Maybe Rect+ownClip p k = IM.lookup k (pfOuterClips p) <|> IM.lookup k (pfClips p)++clipToViewport :: Maybe Rect -> Rect -> Rect+clipToViewport clip r = maybe r (fromMaybe (Rect 0 0 0 0) . rectIntersect r) clip++clipRectToWindow :: Float -> Float -> Rect -> Rect+clipRectToWindow winW winH = clipToViewport (Just (Rect 0 0 winW winH))++scrollOffsetDamage :: Context -> WidgetStore -> WidgetStore -> DamageCollector ()+scrollOffsetDamage Context {ctxNodeArena = na} oldStore newStore =+  unless (null changedKeys) $ do+    -- Every store key that holds a scroll node's offset, mapped to the first+    -- such node, and every scroll range, mapped to each node with that id.+    -- Built once, only on frames where an offset or range changed.+    owners <- liftIO $ foldClassNodeRevM na PointerNodes addOwner IM.empty+    forM_ changedKeys $ \k ->+      forM_ (IM.findWithDefault [] k owners) $ \idx -> do+        -- The scroll node's rect covers the content viewport AND the+        -- scrollbar lane: offset changes move the thumb, which paints+        -- outside the content clip.+        liftIO (getNonzeroRect na idx) >>= mapM_ addDamageRect+        liftIO (walkFloatingAncestors na idx (\i _ -> getNonzeroRect na i)) >>= mapM_ addDamageRect+  where+    -- Floating-pane offsets live in storeFloat; wheel/keyboard offsets+    -- live under the SlotTextAreaScroll slot in storePoint. Both move the+    -- scroller's content and its chrome. New or removed float offsets only+    -- count when nonzero. The range the scroll pass publishes to storePoint+    -- changes with the content's size, which resizes the thumb and can show+    -- or hide a bar; content that changes but still fits keeps a zero range+    -- and repaints nothing here. Two scrollers can share an id (a table's+    -- frozen pane and body), and only the first publishes, so a range change+    -- repaints every scroller with the id.+    (oldF, newF) = (storeFloat oldStore, storeFloat newStore)+    changedKeys =+      filter (\k -> IM.findWithDefault 0 k oldF /= IM.findWithDefault 0 k newF) (diffKeys oldF newF)+        ++ diffKeys (storePoint oldStore) (storePoint newStore)+    addOwner m idx = do+      nt <- getNodeType na idx+      if not (isScrollNode nt)+        then pure m+        else do+          wid <- getWidgetId na idx+          let widKey = intKey wid+              one = [idx]+          pure $+            IM.insertWith (++) widKey one $+              IM.insertWith (++) (slotKey SlotScrollCross widKey) one $+                IM.insertWith (++) (slotKey SlotScrollRange widKey) one m++-- | The store keys (outside the scroll offsets) whose value changed and that+-- are not themselves widget keys, with the node that owns each through a+-- sub-slot spelling. Changed widget keys were already damaged by their+-- 'ReqKey' requests. An owner comes from 'ctxStoreOwners' when the widget+-- it names is in the arena; only keys it does not answer cost a walk+-- ('storeKeyOwners'), whose finds it keeps.+storeKeyChanges :: Context -> WidgetStore -> WidgetStore -> IO ([Int], IM.IntMap NodeIdx)+storeKeyChanges ctx oldStore newStore = do+  let na = ctxNodeArena ctx+  misses <- filterM (\k -> isNothing <$> lookupNodeByKey na k) (slotChangedKeys oldStore newStore)+  if null misses+    then pure ([], IM.empty)+    else do+      known <- readIORef (ctxStoreOwners ctx)+      cached <- mapM (\k -> (k,) <$> maybe (pure Nothing) (lookupNodeByKey na) (IM.lookup k known)) misses+      let hits = IM.fromList [(k, i) | (k, Just i) <- cached]+          rest = [k | (k, Nothing) <- cached]+      found <- if null rest then pure IM.empty else storeKeyOwners na (IS.fromList rest)+      unless (IM.null found) $ do+        owners <- traverse (fmap intKey . getWidgetId na) found+        writeIORef (ctxStoreOwners ctx) $! IM.union owners known+      pure (misses, IM.union hits found)++-- | Each of @wanted@ that maps to a node this frame, keyed to the node that+-- owns it: each widget's base key plus the sub-slot spellings its reads and+-- writes use. Walks the arena, so 'storeKeyChanges' runs it only for keys+-- whose owner it has not found before.+storeKeyOwners :: NodeArena -> IS.IntSet -> IO (IM.IntMap NodeIdx)+storeKeyOwners na wanted = do+  n <- arenaCount na+  -- Stops once every wanted key has an owner.+  let target = IS.size wanted+      go !i !found !m+        | i < 0 || found == target = pure m+        | otherwise = do+            wid <- getWidgetId na i+            if hashWidgetId wid == 0+              then go (i - 1) found m+              else do+                nt <- getNodeType na i+                if nt == NodeText || nt == NodeSpacer || nt == NodeSeparator || nt == NodeImage || nt == NodeBox || nt == NodeShader+                  then go (i - 1) found m+                  else do+                    let !k = intKey wid+                        add (!c, !m') sk+                          | IS.member sk wanted && IM.notMember sk m' = (c + 1, IM.insert sk i m')+                          | otherwise = (c, m')+                        -- The widget's own key first, then each sub-slot spelling.+                        (found', m'') =+                          foldl' (\acc s -> add acc (slotKey s k)) (add (found, m) k) ownerSlots+                    go (i - 1) found' m''+  go (n - 1) (0 :: Int) IM.empty++-- | The sub-slots whose writes repaint from the store at paint time: carets and+-- anchors in text fields, a text area's buffer (its document and caret),+-- line widths (its scrollbars) and history, drag targets, a colour picker's opening colour, and the seen/mode+-- records a controlled edit co-writes. Shared, so resolving an owner does not+-- build a key list per node per frame.+ownerSlots :: [Slot]+ownerSlots =+  [ SlotSeen+  , SlotCursor+  , SlotAnchor+  , SlotTextMode+  , SlotTextHistory+  , SlotSearchCommitted+  , SlotSearchAge+  , SlotTextAreaAnchorRow+  , SlotTextAreaAnchorCol+  , SlotTextAreaChanged+  , SlotTextAreaText+  , SlotTextAreaBuffer+  , SlotTextAreaWidths+  , SlotDrop+  , SlotDrag+  , SlotScrollAxes+  , SlotScrollLinkX+  , SlotScrollLinkY+  , SlotNumericHeld+  , SlotNumericRepeat+  , SlotMenuOpen+  , SlotColorBase+  ]++-- | The pixel edges of a rect at a scale, rounded outwards: left, top, right+-- and bottom.+{-# INLINE pixelEdges #-}+pixelEdges :: Float -> Rect -> (Int, Int, Int, Int)+pixelEdges s (Rect x y w h) =+  (floor (x * s), floor (y * s), ceiling ((x + w) * s), ceiling ((y + h) * s))++-- | The device pixels a clip covers at a scale, as left, top, right and+-- bottom edges: 'pixelEdges' with a tolerance of a thousandth of a pixel.+-- An edge 'snapDamage' put on a pixel comes back from layout units a+-- rounding error to either side of it, and 'pixelEdges' would then round it+-- out to take in the next pixel, past the repainted damage. This rule keeps+-- such an edge on its pixel; an edge further inside a pixel still rounds+-- outwards. The SDL and web backends clip with it.+{-# INLINE clipPixelEdges #-}+clipPixelEdges :: Float -> Rect -> (Int, Int, Int, Int)+clipPixelEdges s (Rect x y w h) =+  (lower (x * s), lower (y * s), upper ((x + w) * s), upper ((y + h) * s))+  where+    lower v = floor (v + 1.0e-3)+    upper v = ceiling (v - 1.0e-3)++-- | Grow damage to whole device pixels so its clip covers every pixel the+-- changed rect touches.+{-# INLINE snapDamage #-}+snapDamage :: Float -> Damage -> Damage+snapDamage _ DamageFull = DamageFull+snapDamage scale (DamageClip r) =+  let (x0, y0, x1, y1) = pixelEdges scale r+      at v = fromIntegral v / scale+   in DamageClip (Rect (at x0) (at y0) (at x1 - at x0) (at y1 - at y0))
+ lib/NanoUI/Internal/Debug.hs view
@@ -0,0 +1,277 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Debug readout sampling shared by the backends: frame timing and skip+-- counts, RTS statistics, draw counts, and the rows shown by the debug+-- windows and the layout overlay.+module NanoUI.Internal.Debug+  ( debugRefreshSec+  , CoreDebugSnapshot (..)+  , emptyCoreDebugSnapshot+  , DebugSamplerRef+  , newDebugSampler+  , noteDebugLoop+  , noteDebugSkip+  , debugCadence+  , noteDebugFrame+  , refreshDebugSnapshot+  , formatFpsRows+  , formatDrawRows+  , formatExplainRows+  ) where++import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word32, Word64)+import GHC.Clock (getMonotonicTime)+import GHC.Conc (getNumCapabilities, getNumProcessors)+import GHC.Stats (GCDetails (..), RTSStats (..), getRTSStats, getRTSStatsEnabled)+import NanoUI.Internal.Context.Types (ExplainedNode (..))+import NanoUI.Internal.Draw.Types (DrawData (..), drawCmdCount)+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Style (Padding (..), PointerMode (..), Sizing (..))+import NanoUI.Internal.Types (Rect (..), V2 (..), isBounded)+import Text.Printf (printf)++-- | Minimum interval between published snapshots, in seconds (0.25).+debugRefreshSec :: Double+debugRefreshSec = 0.25++-- | Fold the rate of an interval of @dt@ seconds into the exponential moving+-- average @ema@, with 15% weight on the sample. A non-positive @ema@ starts+-- over at the sample. Intervals outside 0.0001-0.25 seconds leave it unchanged.+blendRate :: Double -> Double -> Double+blendRate ema dt+  | dt > 1e-4 && dt < 0.25 = if ema <= 0 then 1 / dt else ema * 0.85 + (1 / dt) * 0.15+  | otherwise = ema++-- | Published frame rates, latest phase durations in milliseconds, cumulative+-- present/skip counts, geometry counts, backend-supplied window coordinates,+-- and runtime statistics.+data CoreDebugSnapshot = CoreDebugSnapshot+  { dbgPresentFps :: !Double+  , dbgLoopFps    :: !Double+  , dbgFrameMs    :: !Double+  , dbgUiMs       :: !Double+  , dbgRenderMs   :: !Double+  , dbgPresentMs  :: !Double+  , dbgPresents   :: !Word64+  , dbgSkips      :: !Word64+  , dbgVerts      :: !Int+  , dbgIndices    :: !Int+  , dbgCmds       :: !Int+  , dbgWinW       :: !Float+  , dbgWinH       :: !Float+  , dbgMouseX     :: !Float+  , dbgMouseY     :: !Float+  , dbgRts        :: ![(Text, Text)]+  -- ^ Label/value rows of runtime statistics, or instructions to enable+  -- @+RTS -T@ when they are off. Memory is in MiB, the last collection's+  -- duration in milliseconds, and GC time is a share of elapsed run time.+  }+  deriving (Eq, Show)++-- | Zeroed placeholder before a backend publishes a frame sample.+emptyCoreDebugSnapshot :: CoreDebugSnapshot+emptyCoreDebugSnapshot = CoreDebugSnapshot 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 []++readRtsRows :: IO [(Text, Text)]+readRtsRows = do+  caps <- getNumCapabilities+  cpus <- getNumProcessors+  rtsOn <- getRTSStatsEnabled+  let haskell = ("haskell", T.pack (printf "%2d cap / %2d cpu" caps cpus))+  if not rtsOn+    then pure [("rts", "stats off (need +RTS -T)"), haskell]+    else do+      st <- getRTSStats+      let lastGc = gc st+          count :: Word32 -> Text+          count = T.pack . printf "%10d"+          mb :: Word64 -> Text+          mb n = T.pack (printf "%6.1f MiB" (fromIntegral n / (1024 * 1024) :: Double))+          gcPct :: Double+          gcPct+            | elapsed_ns st > 0 = 100 * fromIntegral (gc_elapsed_ns st) / fromIntegral (elapsed_ns st)+            | otherwise = 0+          gcMs = fromIntegral (gcdetails_elapsed_ns lastGc) / 1.0e6 :: Double+      pure+        [ haskell+        , ("gc total", count (gcs st))+        , ("gc major", count (major_gcs st))+        , ("last gen", count (gcdetails_gen lastGc))+        , ("last gc", T.pack (printf "%7.2f ms" gcMs))+        , ("heap live", mb (gcdetails_live_bytes lastGc))+        , ("heap alloc", mb (allocated_bytes st))+        , ("copied", mb (copied_bytes st))+        , ("rss max", mb (max_mem_in_use_bytes st))+        , ("gc time", T.pack (printf "%9.1f%%" gcPct))+        ]++-- | Mutable sampler contents. Timestamp fields use monotonic seconds. Backends+-- update it through the @noteDebug*@ functions.+data DebugSampler = DebugSampler+  { smCore :: !CoreDebugSnapshot+  -- ^ Accumulates frame timings and counts between refreshes; present FPS,+  -- window coordinates, and RTS stats are filled in by 'refreshDebugSnapshot'.+  , smLastQueryT :: !Double+  , smRatePresents :: !Word64+  , smLastDebugT :: !Double+  -- ^ When the last refresh was, or the sampler was made.+  , smLastDueT :: !Double+  -- ^ When 'debugCadence' last reported a refresh due.+  }++-- | Session-owned sampler reference, updated atomically by sampling operations.+type DebugSamplerRef = IORef DebugSampler++-- | Empty sampler with its rate interval starting at the current monotonic time.+newDebugSampler :: IO DebugSamplerRef+newDebugSampler = newIORef . (\t -> DebugSampler emptyCoreDebugSnapshot 0 0 t 0) =<< getMonotonicTime++noteCore :: DebugSamplerRef -> (CoreDebugSnapshot -> CoreDebugSnapshot) -> IO ()+noteCore ref f = atomicModifyIORef' ref $ \s -> (s {smCore = f (smCore s)}, ())++-- | Record loop delta time in seconds. Intervals outside 0.0001-0.25 seconds+-- do not contribute to the loop-rate moving average.+noteDebugLoop :: DebugSamplerRef -> Float -> IO ()+noteDebugLoop ref dt =+  noteCore ref $ \c -> c {dbgLoopFps = blendRate (dbgLoopFps c) (realToFrac dt)}++-- | Increment the count of loop passes that skipped presentation.+noteDebugSkip :: DebugSamplerRef -> IO ()+noteDebugSkip ref = noteCore ref $ \c -> c {dbgSkips = dbgSkips c + 1}++-- | Whether the readout is active, and whether it is active with a published+-- snapshot older than 'debugRefreshSec'. Activity is driven by actual+-- snapshot consumption: a snapshot query ('refreshDebugSnapshot') refreshes+-- 'smLastQueryT', so the 4 Hz refresh loop only runs while a stats window is+-- being built. An open window alone does not count as activity, or the event+-- loop would wake every refresh period while any floating window is open.+--+-- A refresh is reported due at most once per period. The triggered frame+-- refreshes the snapshot only if the view still queries it, so once the+-- readout closes the snapshot stays older than 'debugRefreshSec' for the rest+-- of the active second; without 'smLastDueT', every pass in that window would+-- report due and run frames back to back.+debugCadence :: DebugSamplerRef -> IO (Bool, Bool)+debugCadence ref = do+  now <- getMonotonicTime+  atomicModifyIORef' ref $ \s ->+    let active = now - smLastQueryT s < 1.0+        due = active && snapshotDue now s && now - smLastDueT s >= debugRefreshSec+     in (if due then s {smLastDueT = now} else s, (active, due))++snapshotDue :: Double -> DebugSampler -> Bool+snapshotDue now s = now - smLastDebugT s >= debugRefreshSec++-- | Record UI, render, present, and total frame durations from clock readings+-- ('getMonotonicTime', in seconds) and geometry counts from @dd@, incrementing+-- the present count. The UI pass ran from @uiStart@ to @uiEnd@, drawing from+-- @uiEnd@ to @drawEnd@, and the present from @drawEnd@ to @presentEnd@; a+-- backend whose present is part of its draw passes @drawEnd@ twice.+noteDebugFrame :: DebugSamplerRef -> Double -> Double -> Double -> Double -> DrawData -> IO ()+noteDebugFrame ref uiStart uiEnd drawEnd presentEnd dd =+  noteCore ref $ \c ->+    c+      { dbgPresents = dbgPresents c + 1+      , dbgUiMs = ms uiStart uiEnd+      , dbgRenderMs = ms uiEnd drawEnd+      , dbgPresentMs = ms drawEnd presentEnd+      , dbgFrameMs = ms uiStart presentEnd+      , dbgVerts = drawVertexCount dd+      , dbgIndices = drawIndexCount dd+      , dbgCmds = drawCmdCount dd+      }+  where+    ms a b = (b - a) * 1000++-- | The published snapshot, rebuilt at most every 'debugRefreshSec' and kept+-- in the backend's typed reference. A due query samples the core stats for @build@ to add the+-- backend's fields to: window size and mouse position are left 0 for it.+-- Every query marks the readout active ('debugCadence').+refreshDebugSnapshot :: DebugSamplerRef -> IORef (Maybe s) -> (CoreDebugSnapshot -> IO s) -> IO s+refreshDebugSnapshot ref published build = do+  now <- getMonotonicTime+  due <- atomicModifyIORef' ref $ \cur ->+    (cur {smLastQueryT = now}, snapshotDue now cur)+  cached <- if due then pure Nothing else readIORef published+  case cached of+    Just snap -> pure snap+    Nothing -> do+      rts <- readRtsRows+      core <- atomicModifyIORef' ref $ \cur ->+        -- Actual presents per second since the previous refresh, which stays+        -- truthful when presents are sparse (idle app: ~4/s with the HUD+        -- open, not the theoretical fps of one fast frame).+        let elapsed = now - smLastDebugT cur+            presents = dbgPresents (smCore cur)+            rate+              | elapsed > 1e-3 = fromIntegral (presents - smRatePresents cur) / elapsed+              | otherwise = 0+         in ( cur {smLastDebugT = now, smRatePresents = presents}+            , (smCore cur) {dbgPresentFps = rate, dbgRts = rts}+            )+      snap <- build core+      snap <$ writeIORef published (Just snap)++-- | Label/value rows for frame rates, durations, and cumulative counts.+formatFpsRows :: CoreDebugSnapshot -> [(Text, Text)]+formatFpsRows s =+  [ ("fps present", T.pack (printf "%6.1f" (dbgPresentFps s)))+  , ("fps loop", T.pack (printf "%6.1f" (dbgLoopFps s)))+  , ("frame ms", T.pack (printf "%6.2f" (dbgFrameMs s)))+  , ("ui ms", T.pack (printf "%6.2f" (dbgUiMs s)))+  , ("render ms", T.pack (printf "%6.2f" (dbgRenderMs s)))+  , ("present ms", T.pack (printf "%6.2f" (dbgPresentMs s)))+  , ("presents", T.pack (printf "%10d" (dbgPresents s)))+  , ("skips", T.pack (printf "%10d" (dbgSkips s)))+  ]++-- | Label/value rows for vertex, index, and draw-command counts.+formatDrawRows :: CoreDebugSnapshot -> [(Text, Text)]+formatDrawRows s =+  [ ("vertices", T.pack (printf "%10d" (dbgVerts s)))+  , ("indices", T.pack (printf "%10d" (dbgIndices s)))+  , ("commands", T.pack (printf "%10d" (dbgCmds s)))+  ]++-- | Label/value rows describing the node under the pointer while the layout+-- overlay is on ('NanoUI.explainedNode'). Padding is printed left, right,+-- top, bottom. The pin and pointer rows appear only when they differ from the+-- defaults.+formatExplainRows :: Maybe ExplainedNode -> [(Text, Text)]+formatExplainRows Nothing = [("node", "none under the pointer")]+formatExplainRows (Just node) =+  [ ("node", explainedKind node)+  , ("id", maybe "none" (\(WidgetId k) -> T.pack (printf "%016x" k)) (explainedWidget node))+  , ("depth", T.pack (show (explainedDepth node)))+  , ("origin", T.pack (printf "%.1f, %.1f" x y))+  , ("size", T.pack (printf "%.1f x %.1f" w h))+  , ("padding", T.pack (printf "%.1f %.1f %.1f %.1f" l r t b))+  , ("content", T.pack (printf "%.1f x %.1f" (w - l - r) (h - t - b)))+  , ("width", sizingText (explainedWidth node) minW maxW)+  , ("height", sizingText (explainedHeight node) minH maxH)+  , ("gap", T.pack (printf "%.1f" (explainedGap node)))+  ]+    ++ [("pin", T.pack (printf "%.1f, %.1f" px py)) | Just (V2 px py) <- [explainedPin node]]+    ++ [("pointer", T.pack (show (explainedPointer node))) | explainedPointer node /= PointerAuto]+  where+    Rect x y w h = explainedRect node+    Padding l r t b = explainedPadding node+    V2 minW minH = explainedMin node+    V2 maxW maxH = explainedMax node++-- | A sizing plus any non-default limits. A min of 0 or a max of 1e8 or more+-- counts as no limit.+sizingText :: Sizing -> Float -> Float -> Text+sizingText sizing lo hi =+  T.pack (base <> (if lo > 0 then printf ", min %.1f" lo else "") <> (if isBounded hi then printf ", max %.1f" hi else ""))+  where+    base :: String+    base = case sizing of+      Fixed n -> printf "fixed %.1f" n+      Fit -> "fit"+      Grow g -> printf "grow %g" g+      Shrink k -> printf "shrink %g" k+      Percent p -> printf "%g%%" p
+ lib/NanoUI/Internal/Derived.hs view
@@ -0,0 +1,149 @@+-- | Typed, bounded caches for data derived by the built-in widgets.+module NanoUI.Internal.Derived+  ( DerivedCache+  , emptyDerivedCache+  , DerivedField+  , tableCache+  , treeCache+  , comboCache+  , lookupDerived+  , insertDerived+  , TableDerived (..)+  , Opaque (..)+  , SortKey (..)+  , SortCol (..)+  , SortDir (..)+  , TreeItem (..)+  , TreeRow+  , TreeRows (..)+  , ComboMatches (..)+  )+where++import Control.Applicative ((<|>))+import Data.Int (Int64)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.IntSet (IntSet)+import Data.Primitive.PrimArray (PrimArray)+import Data.Primitive.SmallArray (SmallArray)+import Data.Text (Text)+import Data.Vector (Vector)++-- | A table column's sort direction: ascending or descending.+data SortDir = SortAsc | SortDesc+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Source-column index, independent of display order.+data SortCol = SortCol {sortColIndex :: !Int, sortColDir :: !SortDir}+  deriving (Eq, Show)++-- | Typed sort key for a table cell, supporting exact numeric ordering alongside+-- lexicographic text ordering.+data SortKey+  = SortText !Text+  | SortNum !Double+  | SortInt !Int64+  deriving (Eq, Show)++instance Ord SortKey where+  compare a b = case (a, b) of+    (SortInt x, SortInt y) -> compare x y+    (SortNum x, SortNum y) -> cmpDouble x y+    (SortInt x, SortNum y) -> cmpDouble (fromIntegral x) y+    (SortNum x, SortInt y) -> cmpDouble x (fromIntegral y)+    (SortText x, SortText y) -> compare x y+    (SortText _, _) -> GT+    (_, SortText _) -> LT+    where+      cmpDouble x y+        | isNaN x && isNaN y = EQ+        | isNaN x = GT+        | isNaN y = LT+        | otherwise = compare x y++-- | Retained only for conservative pointer comparison, never cast or decoded.+data Opaque = forall a. Opaque a++-- | Encoded table cells, their widths, and the sorted row indices.+data TableDerived = TableDerived+  { tdRows :: !Opaque+  , tdCols :: !Opaque+  , tdFont :: !Opaque+  , tdMonoFont :: !Opaque+  , tdRowObjs :: !(SmallArray Opaque)+  , tdHeaders :: !(Vector Text)+  , tdEncoded :: !(SmallArray (Vector Text))+  , tdKeys :: !(SmallArray (Vector SortKey))+  , tdSortable :: !(SmallArray Bool)+  , tdViews :: !(SmallArray Bool)+  -- ^ Each column that has a cell with a widget view.+  , tdCellW :: !(PrimArray Float)+  , tdTextRow :: !(PrimArray Int)+  , tdWidths :: !(PrimArray Float)+  , tdNumeric :: !(SmallArray Bool)+  , tdSort :: !SortCol+  , tdOrder :: !(PrimArray Int)+  }++-- | A tree row's label and children. An empty child list makes a leaf.+data TreeItem = TreeItem {treeItemLabel :: !Text, treeItemChildren :: ![TreeItem]}+  deriving (Eq, Show)++-- | Pre-order index, depth, has-children flag, and label.+type TreeRow = (Int, Int, Bool, Text)++-- | The input container is retained only to compare identity.+data TreeRows = forall f. TreeRows !(f TreeItem) !IntSet !Int !(SmallArray TreeRow)++-- | Options, query, matches, and the widest match once measured. The options+-- container is retained only to compare identity.+data ComboMatches = forall f. ComboMatches !(f Text) !Text [Text] !(Maybe Float)++-- | Two-generation bounded map: avoids cliff wipes when live widget count+-- exceeds the per-generation cap while aging out unmounted widgets.+data DerivedGen a = DerivedGen !(IntMap a) !(IntMap a)++emptyDerivedGen :: DerivedGen a+emptyDerivedGen = DerivedGen IM.empty IM.empty++data DerivedCache = DerivedCache+  { derivedTables :: !(DerivedGen TableDerived)+  , derivedTrees :: !(DerivedGen TreeRows)+  , derivedCombos :: !(DerivedGen ComboMatches)+  }++emptyDerivedCache :: DerivedCache+emptyDerivedCache = DerivedCache emptyDerivedGen emptyDerivedGen emptyDerivedGen++-- | A concrete typed map, chosen at the call site and inlined there.+data DerivedField a+  = DerivedField+      (DerivedCache -> DerivedGen a)+      (DerivedGen a -> DerivedCache -> DerivedCache)++tableCache :: DerivedField TableDerived+tableCache = DerivedField derivedTables (\m c -> c {derivedTables = m})++treeCache :: DerivedField TreeRows+treeCache = DerivedField derivedTrees (\m c -> c {derivedTrees = m})++comboCache :: DerivedField ComboMatches+comboCache = DerivedField derivedCombos (\m c -> c {derivedCombos = m})++{-# INLINE lookupDerived #-}+lookupDerived :: DerivedField a -> Int -> DerivedCache -> Maybe a+lookupDerived (DerivedField get _) k cache =+  let DerivedGen cur prev = get cache+   in IM.lookup k cur <|> IM.lookup k prev++-- | Bound each cache generation to 64 entries. Rotating moves the current+-- generation to previous instead of wiping all live entries at once.+{-# INLINE insertDerived #-}+insertDerived :: DerivedField a -> Int -> a -> DerivedCache -> DerivedCache+insertDerived (DerivedField get set) k value cache =+  let DerivedGen cur prev = get cache+      gen'+        | IM.size cur >= 64 && IM.notMember k cur = DerivedGen (IM.singleton k value) cur+        | otherwise = DerivedGen (IM.insert k value cur) prev+   in set gen' cache
+ lib/NanoUI/Internal/Draw.hs view
@@ -0,0 +1,629 @@+{-# LANGUAGE StrictData #-}++-- | Draw layer facade: data types, arena and geometry, plus the text emitters+-- (plain and synthetic-styled) and the 'DrawOp' interpreter.+module NanoUI.Internal.Draw+  ( Layer (..)+  , DrawCmd (..)+  , ShaderCall (..)+  , EffectSpan (..)+  , emptyShaderCalls+  , emptyEffectSpans+  , emptyUniformBytes+  , DrawData (..)+  , DrawFrameExtra (..)+  , DrawArena (..)+  , RecordedOp (..)+  , DrawOp (..)+  , LineCap (..)+  , LineJoin (..)+  , Shade (..)+  , TextFont (..)+  , defaultTextFont+  , DrawingBuild+  , shiftDrawOp+  , newDrawArena+  , resetDrawArena+  , setDrawSnapScale+  , getDrawSnapScale+  , setDrawPixelScale+  , setDrawSquareGeometry+  , setDrawClear+  , getDrawClear+  , setDrawExternalText+  , setDrawRecordOps+  , getDrawRecordOps+  , withRecordOpacity+  , recordedOps+  , beginLayer+  , currentLayer+  , currentClip+  , setClip+  , setClipPieces+  , getClipPieces+  , withClip+  , pushShaderQuad+  , EffectSpanToken+  , beginEffectSpan+  , endEffectSpan+  , finishDraw+  , drawCmdCount+  , drawnVertexCount+  , drawCmdNull+  , forDrawCmdsInLayer_+  , drawCmdElems+  , cmdEffectiveClip+  , vertexSize+  , indexSize+  , backdropDimTextureId+  , glyphAtlasTextureId+  , glyphAtlasPages+  , glyphPageTextureId+  , textureGlyphPage+  , pushRect+  , pushQuadGradient+  , pushImage+  , pushRoundedRect+  , pushRoundedRectRaw+  , pushRoundedStroke+  , pushLine+  , pushFilledTriangle+  , pushPolylineAA+  , points3+  , drawTextBox+  , glyphSlackLines+  , pushText+  , pushPreparedTextStyled+  , emitDrawOps+  , pushImageOp+  , pushShapeOp+  , checkboxOps+  ) where++import Control.Monad (unless, when)+import Data.Char (isSpace)+import Data.IORef (modifyIORef', readIORef)+import Data.Maybe (fromMaybe)+import qualified Data.Text as T+import qualified Data.Text.Foreign as TF+import qualified Data.Text.Unsafe as TU+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray)+import Data.Primitive.PrimArray (PrimArray, indexPrimArray, readPrimArray, sizeofPrimArray)+import Data.Word (Word32, Word8)+import Foreign.Ptr (Ptr)+import NanoUI.Internal.Draw.Arena+import NanoUI.Internal.Draw.Shapes+import NanoUI.Internal.Draw.Types+import NanoUI.Internal.Font+import NanoUI.Internal.SIMD (pokeQuadCornersSIMD, pokeQuadSIMD)+import NanoUI.Internal.Style (FontStyle (..), FontWeight (..), TextDecoration (..), Theme (..), resolveFontSize, styleBg)+import NanoUI.Internal.Types (Color (..), Rect (..), onGrid, rectInflate, rectIntersect, spanEffectiveClip)++-- | The line box, in logical pixels, that a 'DrawText' of the text anchored+-- at @(x, y)@ by @ax@ and @ay@ occupies, measured with @fm@'s advances.+drawTextBox :: FontMetrics -> Float -> Float -> Float -> Float -> T.Text -> Rect+drawTextBox fm x y ax ay t =+  let tw = lineWidth fm t+      px = x - tw * max 0 ax+   in Rect px (textBoxTop fm y ay) tw (fmLineHeight fm)++-- | Top of a 'drawTextBox' line box anchored at @y@ by @ay@.+textBoxTop :: FontMetrics -> Float -> Float -> Float+textBoxTop fm y ay+  | ay < 0 = y - fmAscent fm+  | otherwise = y - fmLineHeight fm * (1 - ay)++-- | Intersect a command's clip rectangle with an optional damage rectangle.+-- Returns 'Nothing' when the command is culled, @Just Nothing@ when both the+-- command clip and damage are open, and @Just (Just clip)@ for a concrete clip.+{-# INLINE cmdEffectiveClip #-}+cmdEffectiveClip :: Maybe Rect -> DrawCmd -> Maybe (Maybe Rect)+cmdEffectiveClip mDamage cmd =+  spanEffectiveClip mDamage (Rect (cmdClipX cmd) (cmdClipY cmd) (cmdClipW cmd) (cmdClipH cmd))++{-# INLINE pushText #-}+pushText :: DrawArena -> FontMetrics -> Float -> Float -> T.Text -> Color -> IO ()+pushText _da _fm _x _y txt _col | T.null txt = pure ()+pushText da fm x y txt col = do+  prepared <- prepareFontMetrics fm txt+  external <- readIORef (daExternalText da)+  unless external $ pushPreparedTextQuads da prepared x y txt col++-- | Styled text with metrics already prepared for @txt@.+pushPreparedTextStyled ::+  DrawArena ->+  FontMetrics ->+  FontWeight ->+  FontStyle ->+  TextDecoration ->+  Float ->+  Float ->+  T.Text ->+  Color ->+  IO ()+pushPreparedTextStyled da prepared weight fstyle deco x y txt col = do+  external <- readIORef (daExternalText da)+  unless external $ pushPreparedTextStyledQuads da prepared weight fstyle deco x y txt col++-- Snapping the pen to the device pixel grid keeps every glyph quad on a whole+-- pixel. Advances, bearings, and ink sizes are all integer pixel counts divided+-- by the snap scale, so snapping the origin alone aligns the whole line:+-- otherwise fractional layout positions leave glyphs straddling pixel+-- boundaries, which makes nearest-sampled atlas text blurry and jitter as+-- scroll position changes.+pushPreparedTextQuads :: DrawArena -> FontMetrics -> Float -> Float -> T.Text -> Color -> IO ()+pushPreparedTextQuads da fm x y txt col = do+  let !px = onGrid (fmSnapScale fm) x+      !py = onGrid (fmSnapScale fm) y+  -- The host's shaped glyphs when it shapes, otherwise glyphs by character.+  drawShaped fm txt >>= \case+    Just glyphs -> pushShapedQuads da fm 0 px py glyphs col+    Nothing -> pushGlyphQuads da fm 0 px py txt col++-- | How far a glyph's x may fall behind a glyph before it in a line, and how+-- wide a glyph may be, in line heights. Pens only move right in visual order:+-- a glyph lands left of an earlier one only by a negative bearing or as a+-- mark over the glyph before it, and no glyph is wider than a few ems. The+-- clip skips in 'pushShapedQuads' and 'pushGlyphQuads' rely on it.+glyphSlackLines :: Float+glyphSlackLines = 4++-- | Horizontal clip bounds expanded by synthetic-oblique shear lean, plus the+-- conservative glyph slack in logical pixels.+{-# INLINE glyphClipBounds #-}+glyphClipBounds :: DrawArena -> FontMetrics -> Float -> IO (Float, Float, Float)+glyphClipBounds da fm slant = do+  cx <- readPrimArray (daCurrentClip da) 0+  cw <- readPrimArray (daCurrentClip da) 2+  let !lean = abs slant * (fmLineHeight fm + abs (fmAscent fm))+  pure (cx - lean, cx + cw + lean, glyphSlackLines * fmLineHeight fm)++-- | Binary search for the first glyph in @[lo0, hi0)@ whose x reaches @thr@.+firstGlyphReaching :: PrimArray Float -> Float -> Float -> Int -> Int -> Int+firstGlyphReaching quads !px !thr !lo0 !hi0 = go lo0 hi0+  where+    go !lo !hi+      | lo >= hi = lo+      | otherwise =+          let !mid = (lo + hi) `quot` 2+           in if px + indexPrimArray quads (mid * 8) < thr+                then go (mid + 1) hi+                else go lo mid++-- | Emit shaped glyph quads on atlas @page@ from @q0@ up to @end@, recursing+-- only when a glyph lies on another atlas page. Keeping the inner loop strictly+-- tail-recursive lets GHC compile it as a zero-allocation join point.+drawShapedPages ::+  DrawArena ->+  PrimArray Float ->+  Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float ->+  Int -> Int -> Int ->+  IO ()+drawShapedPages da quads !slant !px !py !left !right !baselineY !r !g !b !a !end !q0 !page = do+  setTexture da (glyphPageTextureId page)+  let !shown = end - q0+      !pageU = fromIntegral page+  (vp, ip, base, baseIdx) <- reserveRaw da (shown * 4) (shown * 6)+  let go !q !m+        | q >= end = do+            commitRaw da base baseIdx (m * 4) (m * 6)+            pure end+        | otherwise = do+            let !o = q * 8+                !gx = px + indexPrimArray quads o+                !gw = indexPrimArray quads (o + 2)+                !u0 = indexPrimArray quads (o + 4)+            if gx + gw < left || gx > right+              then go (q + 1) m+              else if u0 < pageU || u0 >= pageU + 1+                then+                  -- A glyph whose u is on no page is skipped.+                  if u0 < 0 || u0 >= fromIntegral glyphAtlasPages+                    then go (q + 1) m+                    else do+                      commitRaw da base baseIdx (m * 4) (m * 6)+                      pure q+                else do+                  let !gy = py + indexPrimArray quads (o + 1)+                      !gh = indexPrimArray quads (o + 3)+                      !v0 = indexPrimArray quads (o + 5)+                      !u1 = indexPrimArray quads (o + 6)+                      !v1 = indexPrimArray quads (o + 7)+                  pokeGlyphQuad vp ip base baseIdx slant baselineY r g b a m gx gy gw gh (u0 - pageU) v0 (u1 - pageU) v1+                  go (q + 1) (m + 1)+  !nextQ <- go q0 0+  when (nextQ < end) $+    drawShapedPages da quads slant px py left right baselineY r g b a end nextQ (truncate (indexPrimArray quads (nextQ * 8 + 4)))++-- | A shaped line's glyph quads from pen @(px, py)@, sheared by @slant@+-- around the baseline like 'pushGlyphQuads'. Glyphs wholly left or right of+-- the current clip emit nothing. Glyph x offsets rise in visual order, to+-- within 'glyphSlackLines', so binary searches find the first glyph that+-- can reach the clip and the first that starts well past it: a long line in+-- a narrow view costs, and reserves buffer room for, the glyphs it shows+-- plus two searches. Glyphs on another atlas page than the one before them+-- start a new draw command on that page's texture.+pushShapedQuads :: DrawArena -> FontMetrics -> Float -> Float -> Float -> ShapedGlyphs -> Color -> IO ()+pushShapedQuads da fm !slant !px !py (ShapedGlyphs quads) !col = do+  let !count = sizeofPrimArray quads `quot` 8+  when (count > 0) $ do+    (!left, !right, !slack) <- glyphClipBounds da fm slant+    let -- Every glyph before @start@ ends left of the clip, and every glyph+        -- from @end@ on starts right of it.+        !start = firstGlyphReaching quads px (left - slack) 0 count+        !end = firstGlyphReaching quads px (right + slack) start count+    when (start < end) $ do+      let !(r, g, b, a) = unpackColorF col+          !baselineY = py + fmAscent fm+          !uFirst = indexPrimArray quads (start * 8 + 4)+          !startPage =+            if uFirst >= 0 && uFirst < fromIntegral glyphAtlasPages+              then truncate uFirst+              else 0+      drawShapedPages da quads slant px py left right baselineY r g b a end start startPage++-- | Glyph quad @q@ of a text reservation whose vertices start at @base@ and+-- indices at @baseIdx@. A non-zero @slant@ shears the quad around+-- @baselineY@. INLINE: it runs per glyph and takes more arguments than GHC+-- unboxes for a call.+{-# INLINE pokeGlyphQuad #-}+pokeGlyphQuad ::+  Ptr Word8 ->+  Ptr Word8 ->+  Int ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  IO ()+pokeGlyphQuad vp ip base baseIdx slant baselineY r g b a q gx gy gw gh u0 v0 u1 v1 = do+  let !vb = (base + q * 4) * vertexSize+      !ib = (baseIdx + q * 6) * indexSize+      !i0 = fromIntegral (base + q * 4) :: Word32+  if slant == 0+    then pokeQuadSIMD vp vb ip ib gx gy gw gh u0 v0 u1 v1 r g b a i0+    else do+      let !gy1 = gy + gh+          !topDx = slant * (baselineY - gy)+          !botDx = slant * (baselineY - gy1)+      pokeQuadCornersSIMD vp vb ip ib (gx + topDx) gy (gx + gw + topDx) gy (gx + gw + botDx) gy1 (gx + botDx) gy1 u0 v0 u1 v1 r g b a i0++-- | Glyph quads for one line from pen @(px, py)@, used as given: synthetic bold+-- relies on its sub-pixel pass offsets. Every quad shares one arena+-- reservation. A non-zero @slant@ shears glyphs around the shared baseline for+-- synthetic oblique, so stems stay parallel and descenders lean left. A glyph+-- the font lacks, other than whitespace, draws an upright advance box on the+-- device grid. As in 'pushShapedQuads', glyphs wholly outside the clip emit+-- nothing, and the walk stops once the pen is well past it.+pushGlyphQuads :: DrawArena -> FontMetrics -> Float -> Float -> Float -> T.Text -> Color -> IO ()+pushGlyphQuads da fm slant px py txt col = do+  let !byteLen = TF.lengthWord8 txt+  when (byteLen > 0) $ do+    let !cap = T.length txt+    scale <- readIORef (daSnapScale da)+    cx <- readPrimArray (daCurrentClip da) 0+    cw <- readPrimArray (daCurrentClip da) 2+    let !lh = fmLineHeight fm+        !lean = abs slant * (lh + abs (fmAscent fm))+        !left = cx - lean+        !right = cx + cw + lean+        !slack = glyphSlackLines * lh+    setTexture da glyphAtlasTextureId+    withVertsReserve da (cap * 4) (cap * 6) $ \vp ip base baseIdx commit -> do+      let !(r, g, b, a) = unpackColorF col+          !baselineY = py + fmAscent fm+          !stop = right + slack+          -- A pen this far left of the clip draws nothing, whatever its glyph.+          !before = left - slack+          -- Walk UTF-8 byte offsets with 'TU.iter' to avoid per-character+          -- 'T.uncons' Text slicing and Maybe/tuple allocation.+          walk !q !ox !first !prev !off+            | off >= byteLen || ox > stop = pure q+            | otherwise = do+                let !(TU.Iter c step) = TU.iter txt off+                    !gx = if first then ox else ox + fmKerning fm prev c+                    !adv = fmAdvance fm c+                    !ox' = gx + adv+                    !off' = off + step+                if gx < before+                  then walk q ox' False c off'+                  else case fmGlyph fm c of+                    Nothing+                      | adv > 0 && not (isSpace c) && not (gx + adv < left || gx > right) -> do+                          pokeGlyphQuad vp ip base baseIdx 0 baselineY r g b a q (onGrid scale gx) (onGrid scale py) adv lh whitePixel whitePixel whitePixel whitePixel+                          walk (q + 1) ox' False c off'+                      | otherwise -> walk q ox' False c off'+                    Just gq ->+                      let !qx = gx + gqX gq+                          !qw = gqW gq+                       in if qx + qw < left || qx > right+                            then walk q ox' False c off'+                            else do+                              pokeGlyphQuad vp ip base baseIdx slant baselineY r g b a q qx (py + gqY gq) qw (gqH gq) (gqU0 gq) (gqV0 gq) (gqU1 gq) (gqV1 gq)+                              walk (q + 1) ox' False c off'+      !k <- walk 0 px True ' ' 0+      commit (k * 4) (k * 6)++-- | Run @emitAt@ at each horizontal pen offset needed to synthesize @weight@+-- with step @bOff@. Inlined so GHC fuses @emitAt@ with zero list allocation.+{-# INLINE emitWeightPasses #-}+emitWeightPasses :: FontWeight -> Float -> (Float -> IO ()) -> IO ()+emitWeightPasses weight !bOff emitAt = case weight of+  WeightNormal -> emitAt 0+  WeightLight -> emitAt 0+  WeightMedium -> emitAt 0 >> emitAt (0.5 * bOff)+  WeightSemiBold -> emitAt 0 >> emitAt (0.75 * bOff)+  WeightBold -> emitAt 0 >> emitAt bOff+  WeightExtraBold -> emitAt 0 >> emitAt bOff >> emitAt (1.5 * bOff)+  WeightBlack -> emitAt 0 >> emitAt bOff >> emitAt (1.5 * bOff) >> emitAt (2 * bOff)++-- | Emit pre-shaped glyph quads with synthetic weight and slant (no decoration).+{-# INLINE pushShapedStyledQuads #-}+pushShapedStyledQuads :: DrawArena -> FontMetrics -> FontWeight -> FontStyle -> Float -> Float -> ShapedGlyphs -> Color -> IO ()+pushShapedStyledQuads da fm weight fstyle x y glyphs col =+  let !px = onGrid (fmSnapScale fm) x+      !py = onGrid (fmSnapScale fm) y+      !bOff = max 1.0 (0.05 * fmLineHeight fm)+      !slant = if fstyle == FontStyleNormal then 0 else 0.18+   in emitWeightPasses weight bOff (\dx -> pushShapedQuads da fm slant (px + dx) py glyphs col)++-- | Synthetic weight, slant and decoration over the plain text path. Upright+-- normal weight keeps the run path; every other pass walks glyphs.+pushPreparedTextStyledQuads :: DrawArena -> FontMetrics -> FontWeight -> FontStyle -> TextDecoration -> Float -> Float -> T.Text -> Color -> IO ()+pushPreparedTextStyledQuads da fm weight fstyle deco x y txt col+  | weight == WeightNormal && fstyle == FontStyleNormal && deco == DecorationNone =+      pushPreparedTextQuads da fm x y txt col+  | otherwise = do+      let !px = onGrid (fmSnapScale fm) x+          !py = onGrid (fmSnapScale fm) y+          !lh = fmLineHeight fm+          !bOff = max 1.0 (0.05 * lh)+          !slant = if fstyle == FontStyleNormal then 0 else 0.18+      drawShaped fm txt >>= \case+        Just glyphs -> emitWeightPasses weight bOff (\dx -> pushShapedQuads da fm slant (px + dx) py glyphs col)+        Nothing -> emitWeightPasses weight bOff (\dx -> pushGlyphQuads da fm slant (px + dx) py txt col)+      when (deco /= DecorationNone) $ do+        let !textW = lineWidth fm txt+            !(thick, underOff, strikeOff) = textDecorationMetrics lh (fmAscent fm)+            underline = pushRect da (Rect px (py + underOff) textW thick) col+            strike = pushRect da (Rect px (py + strikeOff) textW thick) col+        case deco of+          DecorationUnderline -> underline+          DecorationStrikethrough -> strike+          DecorationUnderlineStrike -> underline >> strike+          DecorationNone -> pure ()++-- | Whether two 'TextFont' values resolve to the same font metrics (ignoring+-- 'textFontDecoration', which is painted as strokes rather than resolved).+{-# INLINE sameResolvedFont #-}+sameResolvedFont :: TextFont -> TextFont -> Bool+sameResolvedFont a b =+  textFontSize a == textFontSize b+    && textFontVariant a == textFontVariant b+    && textFontWeight a == textFontWeight b+    && textFontStyle a == textFontStyle b+    && textFontTabular a == textFontTabular b++-- | Emit ops with @fm@ as the default font, at @size@. @resolve@ gives the+-- font for styled text and whether it renders weight and slant natively.+-- @imageUv@ maps an image op's id to an atlas texture and UV bounds, or+-- 'Nothing' when the id is itself a texture. A 'PushClip' intersects the+-- current clip until its 'PopClip'; an unclosed one ends with the ops.+-- Under external text, text ops push no quads: each line is recorded as a+-- span ('pushTextSpan') with the current clip, filed by layer.+emitDrawOps ::+  DrawArena+  -> FontMetrics+  -> Float+  -> (TextFont -> IO (FontMetrics, Bool))+  -> (Int -> IO (Maybe (Int, (Float, Float, Float, Float))))+  -> SmallArray DrawOp+  -> IO ()+emitDrawOps da fm size resolve imageUv ops = do+  !external <- readIORef (daExternalText da)+  let !n = sizeofSmallArray ops+      -- Vertical clip test reading clip Y/H directly without boxing a Rect or+      -- allocating an action closure.+      {-# INLINE inVerticalClip #-}+      inVerticalClip lineFm !top = do+        !cy <- readPrimArray (daCurrentClip da) 1+        !ch <- readPrimArray (daCurrentClip da) 3+        let !lh = fmLineHeight lineFm+            !slack = glyphSlackLines * lh+        pure $! ch > 0 && not (top + lh + slack < cy || top - slack > cy + ch)++      {-# INLINE emitStyled #-}+      emitStyled styledFm native font !x !y t c = do+        let !deco = textFontDecoration font+            !weight = if native then WeightNormal else textFontWeight font+            !fstyle = if native then FontStyleNormal else textFontStyle font+        if not external && deco == DecorationNone+          then+            drawShaped styledFm t >>= \case+              Just glyphs -> pushShapedStyledQuads da styledFm weight fstyle x y glyphs c+              Nothing -> do+                prepared <- prepareFontMetrics styledFm t+                pushPreparedTextStyledQuads da prepared weight fstyle DecorationNone x y t c+          else do+            prepared <- prepareFontMetrics styledFm t+            if external+              then pushTextSpan da (Rect x y (lineWidth prepared t) (fmLineHeight prepared)) t c+              else pushPreparedTextStyledQuads da prepared weight fstyle deco x y t c++      {-# INLINE emitAligned #-}+      emitAligned styledFm native font !x !y !ax !ay t c = do+        let !top = textBoxTop styledFm y ay+        vis <- inVerticalClip styledFm top+        when vis $+          if not external && ax <= 0+            then emitStyled styledFm native font x top t c+            else do+              prepared <- prepareFontMetrics styledFm t+              let !box@(Rect px py _ _) = drawTextBox prepared x y ax ay t+              if external+                then pushTextSpan da box t c+                else+                  let !weight = if native then WeightNormal else textFontWeight font+                      !fstyle = if native then FontStyleNormal else textFontStyle font+                   in pushPreparedTextStyledQuads da prepared weight fstyle (textFontDecoration font) px py t c++      -- 2-slot MRU cache of resolved TextFonts (covers normal/bold alternation+      -- in syntax-highlighted text with zero per-op resolver allocation).+      -- Hitting slot 2 promotes it to slot 1 so a third font evicts the older+      -- entry rather than the active one.+      {-# INLINE withResolved #-}+      withResolved font !has1 !f1 !fm1 !nat1 !has2 !f2 !fm2 !nat2 k+        | has1 && sameResolvedFont font f1 =+            k fm1 nat1 has1 f1 fm1 nat1 has2 f2 fm2 nat2+        | has2 && sameResolvedFont font f2 =+            k fm2 nat2 True f2 fm2 nat2 has1 f1 fm1 nat1+        | otherwise = do+            (!styledFm, !native) <- resolve font+            k styledFm native True font styledFm native has1 f1 fm1 nat1++      -- Clips saved by open 'PushClip's are kept innermost first.+      go !i saved !has1 !f1 !fm1 !nat1 !has2 !f2 !fm2 !nat2+        | i >= n = unless (null saved) (setClip da (last saved))+        | otherwise = case indexSmallArray ops i of+            DrawTextStyled x y font t c+              | T.null t -> go (i + 1) saved has1 f1 fm1 nat1 has2 f2 fm2 nat2+              | otherwise ->+                  withResolved font has1 f1 fm1 nat1 has2 f2 fm2 nat2 $+                    \styledFm native h1 k1 m1 n1 h2 k2 m2 n2 -> do+                      vis <- inVerticalClip styledFm y+                      when vis $ emitStyled styledFm native font x y t c+                      go (i + 1) saved h1 k1 m1 n1 h2 k2 m2 n2+            PushClip r -> do+              prev <- currentClip da+              setClip da (fromMaybe (Rect 0 0 0 0) (rectIntersect prev r))+              go (i + 1) (prev : saved) has1 f1 fm1 nat1 has2 f2 fm2 nat2+            PopClip -> case saved of+              prev : rest -> setClip da prev >> go (i + 1) rest has1 f1 fm1 nat1 has2 f2 fm2 nat2+              [] -> go (i + 1) [] has1 f1 fm1 nat1 has2 f2 fm2 nat2+            DrawText x y ax ay t c -> do+              unless (T.null t) $+                emitAligned fm False defaultTextFont x y ax ay t c+              go (i + 1) saved has1 f1 fm1 nat1 has2 f2 fm2 nat2+            DrawTextAligned x y ax ay k font t c+              | T.null t -> go (i + 1) saved has1 f1 fm1 nat1 has2 f2 fm2 nat2+              | otherwise ->+                  let font'+                        | k == 1 = font+                        | otherwise =+                            let resolved = resolveFontSize size (textFontSize font)+                                baseSz = if resolved > 0 then resolved else size+                             in font {textFontSize = k * baseSz}+                   in withResolved font' has1 f1 fm1 nat1 has2 f2 fm2 nat2 $+                        \styledFm native h1 k1 m1 n1 h2 k2 m2 n2 -> do+                          emitAligned styledFm native font' x y ax ay t c+                          go (i + 1) saved h1 k1 m1 n1 h2 k2 m2 n2+            op@DrawImage {} -> do+              pushImageOp da imageUv op+              go (i + 1) saved has1 f1 fm1 nat1 has2 f2 fm2 nat2+            op -> do+              pushShapeOp da op+              go (i + 1) saved has1 f1 fm1 nat1 has2 f2 fm2 nat2+  go 0 [] False defaultTextFont fm False False defaultTextFont fm False++-- | Record drawing text as a host span with its line box: under external+-- text a drawing's text has no quads and no node span, so the host draws it+-- from this one ('dfeTextSpans'), in the current clip and filed by layer. An+-- empty clip records nothing, as it gets no command. Top level and out of+-- line so the local closures of 'emitDrawOps' capture nothing more for it.+{-# NOINLINE pushTextSpan #-}+pushTextSpan :: DrawArena -> Rect -> T.Text -> Color -> IO ()+pushTextSpan da !box t c = unless (T.null t) $ do+  clip@(Rect _ _ cw ch) <- currentClip da+  when (cw > 0 && ch > 0) $ do+    layer <- currentLayer da+    let entry = (box, t, c, Color 0, clip)+    modifyIORef' (daExtra da) $ \ex ->+      let (base, overlay) = dfeTextSpans ex+       in ex {dfeTextSpans = if layer >= LayerOverlay then (base, entry : overlay) else (entry : base, overlay)}++-- | Paint a 'DrawImage' op; other ops paint nothing. @imageUv@ is as for+-- 'emitDrawOps', and the op's UVs span 0 to 1 over the image. Unrotated+-- images use the snapped quad; only rotated ones compute their corners.+-- An image is recorded as the op, under its own id; a solid one (no+-- texture) records the shape it paints.+{-# INLINE pushImageOp #-}+pushImageOp :: DrawArena -> (Int -> IO (Maybe (Int, (Float, Float, Float, Float)))) -> DrawOp -> IO ()+pushImageOp da imageUv = \case+  op@(DrawImage r angle tex u0 v0 u1 v1 c) -> do+    let draw !t !a0 !b0 !a1 !b1+          | angle == 0 = pushImage da r t a0 b0 a1 b1 c+          | otherwise = pushImageRotated da r angle t a0 b0 a1 b1 c+    when (tex > 0) (recordOp da op)+    imageUv tex >>= \case+          Just (atlas, (a0, b0, a1, b1)) ->+            draw atlas (a0 + u0 * (a1 - a0)) (b0 + v0 * (b1 - b0)) (a0 + u1 * (a1 - a0)) (b0 + v1 * (b1 - b0))+          Nothing -> draw tex u0 v0 u1 v1+  _ -> pure ()++-- | Paint a fill, stroke, line or gradient op. Text, image and clip ops+-- paint nothing here ('emitDrawOps' handles them). Inlined so that an op+-- built only to be painted is optimized away.+{-# INLINE pushShapeOp #-}+pushShapeOp :: DrawArena -> DrawOp -> IO ()+pushShapeOp da = \case+  FillRect r c -> pushRect da r c+  FillRoundedRect r radius c -> pushRoundedRect da r radius c+  FillTriangle x0 y0 x1 y1 x2 y2 c -> pushFilledTriangle da x0 y0 x1 y1 x2 y2 c+  FillCircle cx cy radius c -> pushCircle da cx cy radius c+  Stroke x0 y0 x1 y1 t c -> pushStroke da x0 y0 x1 y1 t c+  StrokeRoundedRect r radius bw c -> pushRoundedStroke da r radius bw c+  StrokeCircle cx cy radius bw c -> pushCircleStroke da cx cy radius bw c+  StrokeLineAA x0 y0 x1 y1 bw c -> pushStrokeAA da x0 y0 x1 y1 bw c+  FillPolygon pts rings tris sh -> pushPolygonAA da pts rings tris sh+  StrokePolyline pts w closed cap join limit sh -> pushPolylineAA da pts w closed cap join limit sh+  FillQuadGradient r c0 c1 c2 c3 -> pushQuadGradient da r c0 c1 c2 c3+  _ -> pure ()++-- | The checkbox widget's box, @box@ wide with its top-left corner at+-- @(x, y)@, passed op by op to @op@: the theme accent with a check mark when+-- @checked@, else an input well outlined in @border@. The widget paints the+-- ops directly ('pushShapeOp'); a canvas collects them+-- ('NanoUI.Widgets.Custom.drawCheckbox').+{-# INLINE checkboxOps #-}+checkboxOps :: Applicative f => (DrawOp -> f ()) -> Theme -> Color -> Float -> Float -> Float -> Bool -> f ()+checkboxOps op theme border x y box checked+  | checked =+      op (FillRoundedRect outer r accent)+        *> op (StrokeRoundedRect outer r bw accent)+        *> stroke x0 y0 x1 y1+        *> stroke x1 y1 x2 y2+        *> cap x0 y0+        *> cap x1 y1+        *> cap x2 y2+  | otherwise =+      op (FillRoundedRect (rectInflate (-bw) outer) (max 0 (r - bw)) (styleBg (themeInput theme)))+        *> op (StrokeRoundedRect outer r bw border)+  where+    outer = Rect x y box box+    r = min 6 (box / 3.5)+    bw = 1.5+    accent = themeAccent theme+    mark = themeOnAccent theme+    t = max 1.6 (box * 0.11)+    x0 = x + box * 0.22+    y0 = y + box * 0.52+    x1 = x + box * 0.42+    y1 = y + box * 0.72+    x2 = x + box * 0.78+    y2 = y + box * 0.28+    stroke ax ay bx by = op (StrokeLineAA ax ay bx by t mark)+    -- Caps snap their centres, like the stroke ends. Snapping a cap's corner+    -- instead can land it a pixel off the stroke at fractional scales.+    cap cx cy = op (FillCircle cx cy (t / 2) mark)
+ lib/NanoUI/Internal/Draw/Arena.hs view
@@ -0,0 +1,773 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE StrictData #-}++-- | Draw arena lifecycle, command batching and vertex reservation. The shape+-- and text emitters reserve room here and poke vertices straight into the+-- pinned buffers.+module NanoUI.Internal.Draw.Arena+  ( newDrawArena+  , resetDrawArena+  , setDrawSnapScale+  , getDrawSnapScale+  , setDrawPixelScale+  , setDrawSquareGeometry+  , setDrawExternalText+  , setDrawClear+  , getDrawClear+  , setDrawRecordOps+  , getDrawRecordOps+  , withRecordOpacity+  , recordOp+  , recordOpOn+  , recordedOps+  , beginLayer+  , currentLayer+  , currentClip+  , setClip+  , setClipPieces+  , getClipPieces+  , withClip+  , setTexture+  , pushShaderQuad+  , EffectSpanToken+  , beginEffectSpan+  , endEffectSpan+  , finishDraw+  , withVerts+  , withVertsRaw+  , reserveRaw+  , commitRaw+  , withVertsReserve+  , drawnVertexCount+  , pushQuad+  , snapRectOrigin+  , unpackColorF+  , whitePixel+  ) where++import Control.Monad (forM, unless, when)+import Data.Int (Int32)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe)+import Data.Primitive.ByteArray+  ( ByteArray+  , copyByteArray+  , copyMutableByteArray+  , getSizeofMutableByteArray+  , newByteArray+  , sizeofByteArray+  , unsafeFreezeByteArray+  )+import Data.Primitive.PrimArray+  ( PrimArray+  , copyMutablePrimArray+  , indexPrimArray+  , newPrimArray+  , primArrayFromList+  , readPrimArray+  , setPrimArray+  , sizeofPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, smallArrayFromList)+import Data.Word (Word32, Word8)+import Data.Vector.Unboxed qualified as U+import Data.Vector.Unboxed.Mutable qualified as UM+import Foreign.ForeignPtr (mallocForeignPtrBytes, withForeignPtr)+import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)+import Foreign.Marshal.Array (copyArray)+import Foreign.Ptr (Ptr)+import GHC.Exts (RealWorld)+import NanoUI.Internal.Draw.Types+import NanoUI.Internal.Shader (PackedShaderPass (..))+import NanoUI.Internal.SIMD (pokeQuadSIMD)+import NanoUI.Internal.Types+  ( Color (..)+  , Rect (..)+  , V2 (..)+  , foldUpTo+  , forUpTo_+  , newZeroedPrimArray+  , onGrid+  , readRectAt+  , rectIntersect+  , unpackColorF+  , writeRectAt+  )+import NanoUI.Internal.Uniforms (alignUp, pokeSysUniforms, sysUniformBytes)++vertexCapacity :: Int+vertexCapacity = 4096++indexCapacity :: Int+indexCapacity = 8192++cmdInitialCapacity :: Int+cmdInitialCapacity = 64++newDrawArena :: IO DrawArena+newDrawArena = do+  vFPtr <- mallocForeignPtrBytes (vertexCapacity * vertexSize)+  iFPtr <- mallocForeignPtrBytes (indexCapacity * indexSize)+  daVertexFPtr <- newIORef vFPtr+  daVertexCap <- newIORef vertexCapacity+  daIndexFPtr <- newIORef iFPtr+  daIndexCap <- newIORef indexCapacity+  daCounts <- newPrimArray countSlots+  daCmdStore <- newIORef =<< UM.unsafeNew cmdInitialCapacity+  daCurrentLayer <- newIORef LayerContent+  daCurrentClip <- newPrimArray 4+  daSnapScale <- newIORef 0.0+  daSquareGeometry <- newIORef False+  daExternalText <- newIORef False+  daClear <- newIORef (Color 0)+  daRecordOps <- newIORef False+  daRecordOpacity <- newIORef 1.0+  daUniformBuf <- newIORef =<< newByteArray 0+  daPixelScale <- newIORef 1.0+  daExtra <- newIORef emptyDrawExtra+  let da = DrawArena {..}+  resetDrawArena da+  pure da++resetDrawArena :: DrawArena -> IO ()+resetDrawArena da = do+  setPrimArray (daCounts da) 0 countSlots 0+  setCount da texSlot glyphAtlasTextureId+  setCount da effectNextIdSlot 1+  writeIORef (daCurrentLayer da) LayerContent+  setClip da (Rect 0 0 1e9 1e9)+  writeIORef (daClear da) (Color 0)+  writeIORef (daRecordOpacity da) 1.0+  -- Only here: a reused frame paints nothing and keeps the last paint's.+  writeIORef (daExtra da) emptyDrawExtra++-- 'daCounts' slots.+vertexCountSlot, indexCountSlot, cmdCountSlot, cmdStartSlot :: Int+texSlot, shaderSlot, noMergeSlot, shaderCallCountSlot, uniformLenSlot, effectNextIdSlot, countSlots :: Int+vertexCountSlot = 0+indexCountSlot = 1+cmdCountSlot = 2+cmdStartSlot = 3+texSlot = 4+shaderSlot = 5+noMergeSlot = 6+shaderCallCountSlot = 7+uniformLenSlot = 8+effectNextIdSlot = 9+countSlots = 10++{-# INLINE getCount #-}+getCount :: DrawArena -> Int -> IO Int+getCount da = readPrimArray (daCounts da)++{-# INLINE setCount #-}+setCount :: DrawArena -> Int -> Int -> IO ()+setCount da = writePrimArray (daCounts da)++-- | Cut every command of this frame to each of these disjoint rects, as a+-- copy per rect it meets. A frame whose damage lies in pieces far apart+-- paints under their bounding box, and the pieces keep it from drawing over+-- the pixels between them, which it has not cleared.+setClipPieces :: DrawArena -> [Rect] -> IO ()+setClipPieces da rects =+  modifyIORef' (daExtra da) $ \e ->+    e {dfeClipPieces = primArrayFromList (concat [[x, y, x + w, y + h] | Rect x y w h <- rects])}++-- | The rects 'setClipPieces' set, as @x0, y0, x1, y1@ runs.+{-# INLINE getClipPieces #-}+getClipPieces :: DrawArena -> IO (PrimArray Float)+getClipPieces da = dfeClipPieces <$> readIORef (daExtra da)++-- | Device pixel scale used to snap primitive origins/endpoints to whole+-- device pixels. A non-positive value disables snapping. The SDL backend keeps+-- this in sync with the window pixel density. Headless contexts and the RGFW backend+-- leave it disabled.+{-# INLINE setDrawSnapScale #-}+setDrawSnapScale :: DrawArena -> Float -> IO ()+setDrawSnapScale da s = do+  writeIORef (daSnapScale da) (if s > 0 then s else 0)+  when (s > 0) $ writeIORef (daPixelScale da) s++{-# INLINE getDrawSnapScale #-}+getDrawSnapScale :: DrawArena -> IO Float+getDrawSnapScale da = readIORef (daSnapScale da)++-- | Device pixels per logical layout unit, forwarded in shader system uniforms+-- (@uMeta.x@) without enabling pixel-grid snapping.+{-# INLINE setDrawPixelScale #-}+setDrawPixelScale :: DrawArena -> Float -> IO ()+setDrawPixelScale da s = writeIORef (daPixelScale da) (if s > 0 then s else 1.0)++-- | Square geometry for hosts that draw flat, axis-aligned fills, such as the+-- RGFW backend. Rounded rects, circles and their strokes lower to+-- plain rects, and coverage-AA strips lower to solid quads with no+-- transparent fringe vertices. Persists across 'resetDrawArena'.+{-# INLINE setDrawSquareGeometry #-}+setDrawSquareGeometry :: DrawArena -> Bool -> IO ()+setDrawSquareGeometry da = writeIORef (daSquareGeometry da)++-- | The colour the backend clears a full frame to before its commands+-- ('drawClear').+{-# INLINE setDrawClear #-}+setDrawClear :: DrawArena -> Color -> IO ()+setDrawClear da = writeIORef (daClear da)++-- | This paint's clear colour, as 'setDrawClear' left it.+{-# INLINE getDrawClear #-}+getDrawClear :: DrawArena -> IO Color+getDrawClear da = readIORef (daClear da)++-- | Record every solid shape the emitters draw ('recordedOps'), for+-- exporters that redraw a frame as vectors. Off, each emitter pays one flag+-- read. Persists across 'resetDrawArena'.+{-# INLINE setDrawRecordOps #-}+setDrawRecordOps :: DrawArena -> Bool -> IO ()+setDrawRecordOps da = writeIORef (daRecordOps da)++-- | Whether 'setDrawRecordOps' is on.+{-# INLINE getDrawRecordOps #-}+getDrawRecordOps :: DrawArena -> IO Bool+getDrawRecordOps da = readIORef (daRecordOps da)++-- | Record @op@ under the current layer and clip while recording is on.+{-# INLINE recordOp #-}+recordOp :: DrawArena -> DrawOp -> IO ()+recordOp da op = do+  on <- readIORef (daRecordOps da)+  when on (recordOpOn da op)++-- | Multiply 'daRecordOpacity' by @a@ around @act@ when recording vector ops+-- for SVG export.+{-# NOINLINE withRecordOpacity #-}+withRecordOpacity :: DrawArena -> Float -> IO a -> IO a+withRecordOpacity da a act = do+  prev <- readIORef (daRecordOpacity da)+  writeIORef (daRecordOpacity da) $! max 0 (min 1 (prev * a))+  r <- act+  writeIORef (daRecordOpacity da) prev+  pure r++{-# NOINLINE recordOpOn #-}+recordOpOn :: DrawArena -> DrawOp -> IO ()+recordOpOn da op = do+  layer <- currentLayer da+  clip <- currentClip da+  alpha <- readIORef (daRecordOpacity da)+  modifyIORef' (daExtra da) $ \e -> e {dfeRecordedOps = RecordedOp layer clip alpha op : dfeRecordedOps e}++-- | The shapes the last paint recorded, in paint order.+recordedOps :: DrawArena -> IO [RecordedOp]+recordedOps da = reverse . dfeRecordedOps <$> readIORef (daExtra da)++-- | External text for hosts that rasterize text themselves from the collected+-- text spans. Text emitters push no quads, so fonts without a glyph atlas do+-- not leave per-character advance boxes in the buffer; drawing text ops are+-- recorded as spans ('daTextSpans') instead. Persists across+-- 'resetDrawArena'.+{-# INLINE setDrawExternalText #-}+setDrawExternalText :: DrawArena -> Bool -> IO ()+setDrawExternalText da = writeIORef (daExternalText da)++-- | Make room for @needV@ vertices after the first @vCount@ and @needI@+-- indices after the first @iCount@, copying each full buffer into one of at+-- least twice its capacity.+{-# NOINLINE growBuffers #-}+growBuffers :: DrawArena -> Int -> Int -> Int -> Int -> IO ()+growBuffers da vCount iCount needV needI = do+  grow (daVertexFPtr da) (daVertexCap da) vertexSize vCount needV+  grow (daIndexFPtr da) (daIndexCap da) indexSize iCount needI+  where+    grow fptrRef capRef elemBytes count needElems = do+      cap <- readIORef capRef+      let required = count + needElems+      when (required > cap) $ do+        oldFPtr <- readIORef fptrRef+        let newCap = max (cap * 2) required+        newFPtr <- mallocForeignPtrBytes (newCap * elemBytes)+        withForeignPtr newFPtr $ \newP ->+          withForeignPtr oldFPtr $ \oldP ->+            copyArray newP oldP (count * elemBytes)+        writeIORef fptrRef newFPtr+        writeIORef capRef newCap++-- | Reserve room for @needV@ vertices and @needI@ indices: the vertex and+-- index buffers and the first free vertex and index. Commit what was+-- written with 'commitRaw'. A primitive with a long body calls these+-- directly rather than passing it to 'withVertsRaw' as a closure, which it+-- would allocate on every call.+{-# INLINE reserveRaw #-}+reserveRaw :: DrawArena -> Int -> Int -> IO (Ptr Word8, Ptr Word8, Int, Int)+reserveRaw da needV needI = do+  vCount <- getCount da vertexCountSlot+  iCount <- getCount da indexCountSlot+  vCap <- readIORef (daVertexCap da)+  iCap <- readIORef (daIndexCap da)+  unless (vCount + needV <= vCap && iCount + needI <= iCap) $+    growBuffers da vCount iCount needV needI+  -- Strict, so a caller that hands the pointers on allocates no thunks.+  !vp <- unsafeForeignPtrToPtr <$> readIORef (daVertexFPtr da)+  !ip <- unsafeForeignPtrToPtr <$> readIORef (daIndexFPtr da)+  pure (vp, ip, vCount, iCount)++-- | Close the pending index run as a command. A run that continues the last+-- command's state and index range extends that command instead, and a run+-- clipped to nothing gets none: a host would still draw it into the pixel+-- the empty clip rounds to. Only reached when the layer, clip or texture+-- changes and from 'finishDraw', so it stays out of the emitters.+{-# NOINLINE flushCmd #-}+flushCmd :: DrawArena -> IO ()+flushCmd da = do+  start <- getCount da cmdStartSlot+  end <- getCount da indexCountSlot+  when (end > start) $ do+    Rect cx cy cw ch <- currentClip da+    when (cw > 0 && ch > 0) $ do+      tex <- getCount da texSlot+      layer <- readIORef (daCurrentLayer da)+      sh <- fromIntegral <$> getCount da shaderSlot+      noMerge <- getCount da noMergeSlot+      n <- getCount da cmdCountSlot+      arr <- readIORef (daCmdStore da)+      let+        off = fromIntegral start :: Word32+        cnt = fromIntegral (end - start) :: Word32+      extended <-+        if n <= noMerge+          then pure False+          else do+            prev <- UM.unsafeRead arr (n - 1)+            let+              same =+                cmdClipX prev == cx+                  && cmdClipY prev == cy+                  && cmdClipW prev == cw+                  && cmdClipH prev == ch+                  && cmdTextureId prev == tex+                  && cmdLayer prev == layer+                  && cmdShader prev == sh+                  && cmdIndexOffset prev + cmdIndexCount prev == off+            when same $+              UM.unsafeWrite arr (n - 1) prev {cmdIndexCount = cmdIndexCount prev + cnt}+            pure same+      unless extended $ do+        arr' <-+          if n < UM.length arr+            then pure arr+            else do+              grown <- UM.unsafeGrow arr (UM.length arr)+              grown <$ writeIORef (daCmdStore da) grown+        UM.unsafeWrite arr' n (DrawCmd cx cy cw ch tex off cnt layer sh)+        setCount da cmdCountSlot (n + 1)+    setCount da cmdStartSlot end++{-# INLINE currentLayer #-}+currentLayer :: DrawArena -> IO Layer+currentLayer = readIORef . daCurrentLayer++beginLayer :: DrawArena -> Layer -> IO ()+beginLayer da layer = do+  cur <- readIORef (daCurrentLayer da)+  when (cur /= layer) $ do+    flushCmd da+    writeIORef (daCurrentLayer da) layer++setClip :: DrawArena -> Rect -> IO ()+setClip da (Rect x y w h) = flushCmd da >> writeRectAt (daCurrentClip da) 0 x y w h++{-# INLINE currentClip #-}+currentClip :: DrawArena -> IO Rect+currentClip da = readRectAt (daCurrentClip da) 0++-- | Run @act@ clipped to the intersection with the current clip. Not+-- exception-safe: the frame resets the clip before the next paint anyway.+{-# INLINE withClip #-}+withClip :: DrawArena -> Rect -> IO a -> IO a+withClip da rect act = do+  prev <- currentClip da+  setClip da (fromMaybe (Rect 0 0 0 0) (rectIntersect prev rect))+  act <* setClip da prev++-- | Bind a texture. The unchanged case is the common one and stays inline; a+-- real switch closes the pending command out of line.+{-# INLINE setSlotState #-}+setSlotState :: DrawArena -> Int -> Int -> IO ()+setSlotState da slot val = do+  cur <- getCount da slot+  when (cur /= val) $ switchSlotState da slot val++{-# NOINLINE switchSlotState #-}+switchSlotState :: DrawArena -> Int -> Int -> IO ()+switchSlotState da slot val = flushCmd da >> setCount da slot val++{-# INLINE setTexture #-}+setTexture :: DrawArena -> Int -> IO ()+setTexture da = setSlotState da texSlot++-- | Bind a 1-based shader call index (@0@ for the standard pipeline).+{-# INLINE setShader #-}+setShader :: DrawArena -> Int32 -> IO ()+setShader da = setSlotState da shaderSlot . fromIntegral++-- | Pack system + user uniforms for @pass@ into 'daUniformBuf' and return the+-- resulting 'ShaderCall' without appending it to 'dfeShaderCalls'.+packShaderCall ::+  DrawArena ->+  PackedShaderPass ->+  Rect ->+  Rect ->+  Float ->+  Float ->+  Float ->+  Float ->+  IO ShaderCall+packShaderCall da pass nodeRect uvRect scale radius tw th = do+  let userBytes = pspUniforms pass+      !userLen = sizeofByteArray userBytes+      !totalLen = alignUp 16 (sysUniformBytes + userLen)+  off <- getCount da uniformLenSlot+  buf0 <- readIORef (daUniformBuf da)+  cap <- getSizeofMutableByteArray buf0+  buf <-+    if off + totalLen <= cap+      then pure buf0+      else do+        let !newCap = max 256 (max (cap * 2) (off + totalLen))+        grown <- newByteArray newCap+        when (off > 0) $ copyMutableByteArray grown 0 buf0 0 off+        grown <$ writeIORef (daUniformBuf da) grown+  pokeSysUniforms nodeRect uvRect scale radius tw th buf off+  when (userLen > 0) $ copyByteArray buf (off + sysUniformBytes) userBytes 0 userLen+  setCount da uniformLenSlot (off + totalLen)+  pure+    ShaderCall+      { scHash = pspHash pass+      , scProgram = pspProgram pass+      , scUniformOffset = off+      , scUniformLength = totalLen+      }++-- | Append one shader call's 48-byte system header and user std140 uniform+-- bytes into the draw arena, returning its 1-based 'ShaderCall' index.+{-# NOINLINE allocShaderCall #-}+allocShaderCall ::+  DrawArena ->+  PackedShaderPass ->+  Rect ->+  Rect ->+  Float ->+  Float ->+  Float ->+  Float ->+  IO Int32+allocShaderCall da pass nodeRect uvRect scale radius tw th = do+  !call <- packShaderCall da pass nodeRect uvRect scale radius tw th+  idx <- (+ 1) <$> getCount da shaderCallCountSlot+  setCount da shaderCallCountSlot idx+  modifyIORef' (daExtra da) $ \e -> e {dfeShaderCalls = call : dfeShaderCalls e}+  pure (fromIntegral idx)++-- | Emit a Tier 1 leaf surface shader quad with normalized local UVs+-- @(0, 0) .. (1, 1)@ and its packed system + user uniform block.+{-# NOINLINE pushShaderQuad #-}+pushShaderQuad :: DrawArena -> PackedShaderPass -> Rect -> Float -> Color -> IO ()+pushShaderQuad da pass rect@(Rect _ _ w h) radius tint = do+  scale <- readIORef (daPixelScale da)+  callIdx <- allocShaderCall da pass rect (Rect 0 0 1 1) scale radius w h+  setTexture da glyphAtlasTextureId+  setShader da callIdx+  pushQuad da rect 0 0 1 1 tint+  setShader da 0++-- | Token returned by 'beginEffectSpan' and passed to 'endEffectSpan'.+newtype EffectSpanToken = EffectSpanToken EffectSpan++-- | Current enclosing effect span ID, or @0@ when painting to the root target.+{-# INLINE currentEffectSpanId #-}+currentEffectSpanId :: DrawArena -> IO Int+currentEffectSpanId da = do+  stk <- dfeEffectStack <$> readIORef (daExtra da)+  pure $ case stk of+    (i : _) -> i+    [] -> 0++-- | Open a Tier 2 offscreen effect span bracketing subsequent draw commands+-- in the current layer until the matching 'endEffectSpan'.+{-# NOINLINE beginEffectSpan #-}+beginEffectSpan :: DrawArena -> Rect -> V2 -> IO EffectSpanToken+beginEffectSpan da bounds margin = do+  flushCmd da+  rawStart <- getCount da cmdCountSlot+  setCount da noMergeSlot rawStart+  layer <- readIORef (daCurrentLayer da)+  clip <- currentClip da+  parent <- currentEffectSpanId da+  esid <- getCount da effectNextIdSlot+  setCount da effectNextIdSlot (esid + 1)+  modifyIORef' (daExtra da) $ \e -> e {dfeEffectStack = esid : dfeEffectStack e}+  pure (EffectSpanToken (EffectSpan esid parent layer rawStart 0 bounds clip margin emptyShaderCalls))++-- | Close an open effect span, packing one 'ShaderCall' per pass in @passes@+-- and recording the span for 'finishDraw'.+{-# NOINLINE endEffectSpan #-}+endEffectSpan :: DrawArena -> EffectSpanToken -> [PackedShaderPass] -> IO ()+endEffectSpan da (EffectSpanToken es0) passes = do+  flushCmd da+  rawEnd <- getCount da cmdCountSlot+  setCount da noMergeSlot rawEnd+  scale <- readIORef (daPixelScale da)+  let bounds@(Rect _ _ bw bh) = esBounds es0+      V2 mx my = esMargin es0+  calls <- forM passes $ \pass ->+    packShaderCall da pass bounds (Rect 0 0 1 1) scale 0 (bw + 2 * mx) (bh + 2 * my)+  let !es = es0 {esCmdEnd = rawEnd, esPasses = smallArrayFromList calls}+  modifyIORef' (daExtra da) $ \e ->+    e {dfeEffectStack = drop 1 (dfeEffectStack e), dfeEffectSpans = es : dfeEffectSpans e}++finishDraw :: DrawArena -> IO DrawData+finishDraw da = do+  flushCmd da+  vFPtr <- readIORef (daVertexFPtr da)+  iFPtr <- readIORef (daIndexFPtr da)+  vCount <- getCount da vertexCountSlot+  iCount <- getCount da indexCountSlot+  count0 <- getCount da cmdCountSlot+  arr0 <- readIORef (daCmdStore da)+  extra <- readIORef (daExtra da)+  let pieces = dfeClipPieces extra+      pendingEffects = dfeEffectSpans extra+  (cmds, offsets, effectSpans) <-+    if null pendingEffects+      then do+        (arr, count) <-+          if sizeofPrimArray pieces == 0+            then pure (arr0, count0)+            else cutCmdsToPieces pieces arr0 count0+        (cs, offs) <- groupCmdsByLayer arr count+        pure (cs, offs, emptyEffectSpans)+      else finishWithEffects pieces arr0 count0 (reverse pendingEffects)+  callCount <- getCount da shaderCallCountSlot+  let shaderCalls+        | callCount == 0 = emptyShaderCalls+        | otherwise = smallArrayFromList (reverse (dfeShaderCalls extra))+  uLen <- getCount da uniformLenSlot+  uniformBytes <- if uLen <= 0 then pure emptyUniformBytes else freezeUniformPrefix da uLen+  clear <- readIORef (daClear da)+  pure+    DrawData+      { drawVertices = vFPtr+      , drawVertexCount = vCount+      , drawIndices = iFPtr+      , drawIndexCount = iCount+      , drawCommands = cmds+      , drawLayerOffsets = offsets+      , drawClear = clear+      , drawShaderCalls = shaderCalls+      , drawUniformBytes = uniformBytes+      , drawEffectSpans = effectSpans+      }++{-# NOINLINE freezeUniformPrefix #-}+freezeUniformPrefix :: DrawArena -> Int -> IO ByteArray+freezeUniformPrefix da uLen = do+  src <- readIORef (daUniformBuf da)+  dst <- newByteArray uLen+  copyMutableByteArray dst 0 src 0 uLen+  unsafeFreezeByteArray dst++-- | Cut commands (when damage pieces are active), group by layer, and map+-- the raw command boundaries of each pending 'EffectSpan' into final 'drawCommands'+-- indices. Only reached on frames that use Tier 2 subtree effects.+{-# NOINLINE finishWithEffects #-}+finishWithEffects ::+  PrimArray Float ->+  U.MVector RealWorld DrawCmd ->+  Int ->+  [EffectSpan] ->+  IO (U.Vector DrawCmd, PrimArray Int, SmallArray EffectSpan)+finishWithEffects pieces arr0 count0 pending = do+  let !layers = fromEnum (maxBound :: Layer) + 1+  before <- newZeroedPrimArray ((count0 + 1) * layers)+  let advanceRow i cmd emitted = do+        copyMutablePrimArray before ((i + 1) * layers) before (i * layers) layers+        when (emitted > 0) $ do+          let !slot = (i + 1) * layers + fromEnum (cmdLayer cmd)+          readPrimArray before slot >>= writePrimArray before slot . (+ emitted)+  (arr, count) <-+    if sizeofPrimArray pieces == 0+      then do+        forUpTo_ count0 $ \i -> UM.unsafeRead arr0 i >>= \cmd -> advanceRow i cmd 1+        pure (arr0, count0)+      else do+        let !k = sizeofPrimArray pieces `quot` 4+        dest <- UM.unsafeNew (max 1 (count0 * k))+        let step m i = do+              cmd <- UM.unsafeRead arr0 i+              mNext <- cutCmdAt pieces k dest m cmd+              advanceRow i cmd (mNext - m)+              pure mNext+        mFinal <- foldUpTo count0 step 0+        pure (dest, mFinal)+  (cmds, offsets) <- groupCmdsByLayer arr count+  spans <- forM pending $ \es -> do+    let !l = fromEnum (esLayer es)+        !layerOff = indexPrimArray offsets l+        !rawS = min count0 (max 0 (esCmdStart es))+        !rawE = min count0 (max rawS (esCmdEnd es))+    sOff <- readPrimArray before (rawS * layers + l)+    eOff <- readPrimArray before (rawE * layers + l)+    pure es {esCmdStart = layerOff + sOff, esCmdEnd = layerOff + eOff}+  pure (cmds, offsets, smallArrayFromList spans)++-- | Emit one copy of @cmd@ into @dest@ starting at @m@ for each disjoint clip+-- piece in @pieces@ (count @k@) that intersects @cmd@'s clip, returning the+-- next free index in @dest@.+{-# INLINE cutCmdAt #-}+cutCmdAt :: PrimArray Float -> Int -> U.MVector RealWorld DrawCmd -> Int -> DrawCmd -> IO Int+cutCmdAt pieces !k dest !m cmd =+  let !cx0 = cmdClipX cmd+      !cy0 = cmdClipY cmd+      !cx1 = cx0 + cmdClipW cmd+      !cy1 = cy0 + cmdClipH cmd+      piece m' j = do+        let !o = j * 4+            !x0 = max cx0 (indexPrimArray pieces o)+            !y0 = max cy0 (indexPrimArray pieces (o + 1))+            !x1 = min cx1 (indexPrimArray pieces (o + 2))+            !y1 = min cy1 (indexPrimArray pieces (o + 3))+        if x1 <= x0 || y1 <= y0+          then pure m'+          else do+            UM.unsafeWrite dest m' cmd {cmdClipX = x0, cmdClipY = y0, cmdClipW = x1 - x0, cmdClipH = y1 - y0}+            pure (m' + 1)+   in foldUpTo k piece m++-- | Each command once per piece its clip meets, clipped to that piece, in+-- command order. Pieces are disjoint, so the order among one command's+-- copies does not matter.+cutCmdsToPieces ::+  PrimArray Float -> U.MVector RealWorld DrawCmd -> Int -> IO (U.MVector RealWorld DrawCmd, Int)+cutCmdsToPieces pieces src n = do+  let !k = sizeofPrimArray pieces `quot` 4+  dest <- UM.unsafeNew (max 1 (n * k))+  m <- foldUpTo n (\m' i -> UM.unsafeRead src i >>= cutCmdAt pieces k dest m') 0+  pure (dest, m)++-- | Stable counting sort by layer, with cumulative offsets into the sorted+-- array. Single-command frames reuse precomputed layer-offset tables, and+-- frames whose commands are already in layer order freeze a slice directly.+groupCmdsByLayer ::+  U.MVector RealWorld DrawCmd -> Int -> IO (U.Vector DrawCmd, PrimArray Int)+groupCmdsByLayer _ 0 = pure (U.empty, emptyLayerOffsets)+groupCmdsByLayer src 1 = do+  cmd <- UM.unsafeRead src 0+  pure (U.singleton cmd, indexSmallArray singleLayerOffsets (fromEnum (cmdLayer cmd)))+groupCmdsByLayer src n = do+  let layers = fromEnum (maxBound :: Layer) + 1+  -- Check if already in non-decreasing layer order while counting per layer.+  counts <- newZeroedPrimArray layers+  let scan !i !prevL !sorted+        | i >= n = pure sorted+        | otherwise = do+            l <- fromEnum . cmdLayer <$> UM.unsafeRead src i+            readPrimArray counts l >>= writePrimArray counts l . (+ 1)+            scan (i + 1) l (sorted && l >= prevL)+  sorted <- scan 0 0 True+  offsets <- newPrimArray (layers + 1)+  let prefix !l !acc+        | l >= layers = writePrimArray offsets layers acc+        | otherwise = do+            c <- readPrimArray counts l+            writePrimArray offsets l acc+            prefix (l + 1) (acc + c)+  prefix 0 0+  if sorted+    then (,) <$> U.freeze (UM.unsafeSlice 0 n src) <*> unsafeFreezePrimArray offsets+    else do+      -- Reuse 'counts' as write cursors by copying the prefix offsets into it.+      copyMutablePrimArray counts 0 offsets 0 layers+      dest <- UM.unsafeNew n+      forUpTo_ n $ \i -> do+        cmd <- UM.unsafeRead src i+        let l = fromEnum (cmdLayer cmd)+        j <- readPrimArray counts l+        UM.unsafeWrite dest j cmd+        writePrimArray counts l (j + 1)+      (,) <$> U.unsafeFreeze dest <*> unsafeFreezePrimArray offsets++-- Empty damage frames share their immutable command index.+emptyLayerOffsets :: PrimArray Int+emptyLayerOffsets = primArrayFromList (replicate (fromEnum (maxBound :: Layer) + 2) 0)++-- Single-command frames share their immutable layer-offset table per layer.+singleLayerOffsets :: SmallArray (PrimArray Int)+singleLayerOffsets =+  let layers = fromEnum (maxBound :: Layer) + 1+   in smallArrayFromList+        [ primArrayFromList [if k <= l then 0 else 1 | k <- [0 .. layers]]+        | l <- [0 .. layers - 1]+        ]++-- Allocate room for a primitive, hand the derived offsets to the body, and+-- commit the vertex/index counts afterwards. INLINE: erased at -O.+{-# INLINE withVerts #-}+withVerts :: DrawArena -> Int -> Int -> (Ptr Word8 -> Ptr Word8 -> Int -> Int -> Word32 -> IO ()) -> IO ()+withVerts da needV needI f =+  withVertsRaw da needV needI $ \vp ip base baseIdx ->+    f vp ip (base * vertexSize) (baseIdx * indexSize) (fromIntegral base)++-- Like 'withVerts' but for primitives that index vertices relative to 'base'+-- themselves instead of using one contiguous offset.+{-# INLINE withVertsRaw #-}+withVertsRaw :: DrawArena -> Int -> Int -> (Ptr Word8 -> Ptr Word8 -> Int -> Int -> IO ()) -> IO ()+withVertsRaw da needV needI f =+  withVertsReserve da needV needI $ \vp ip base baseIdx commit -> f vp ip base baseIdx >> commit needV needI++-- | Reserve room for up to @maxV@ vertices / @maxI@ indices, hand the body a+-- commit action, then record only the counts the body reports. Batches many+-- small quads (text glyphs) into one arena reservation instead of one+-- @withVerts@ closure + capacity check per quad.+{-# INLINE withVertsReserve #-}+withVertsReserve ::+  DrawArena ->+  Int ->+  Int ->+  (Ptr Word8 -> Ptr Word8 -> Int -> Int -> (Int -> Int -> IO ()) -> IO ()) ->+  IO ()+withVertsReserve da maxV maxI f = do+  (vp, ip, base, baseIdx) <- reserveRaw da maxV maxI+  f vp ip base baseIdx (commitRaw da base baseIdx)++-- | Record @nv@ vertices and @ni@ indices written from a 'reserveRaw' at+-- @base@ and @baseIdx@.+{-# INLINE commitRaw #-}+commitRaw :: DrawArena -> Int -> Int -> Int -> Int -> IO ()+commitRaw da base baseIdx nv ni = do+  setCount da vertexCountSlot (base + nv)+  setCount da indexCountSlot (baseIdx + ni)++-- | Vertices recorded so far this frame, in every layer: 0 before the+-- frame's first geometry.+{-# INLINE drawnVertexCount #-}+drawnVertexCount :: DrawArena -> IO Int+drawnVertexCount da = getCount da vertexCountSlot++{-# INLINE pushQuad #-}+pushQuad :: DrawArena -> Rect -> Float -> Float -> Float -> Float -> Color -> IO ()+pushQuad da (Rect x y w h) u0 v0 u1 v1 col = do+  let !(r, g, b, a) = unpackColorF col+  withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->+    pokeQuadSIMD vp vOff ip iOff x y w h u0 v0 u1 v1 r g b a baseIdxWord++{-# INLINE snapRectOrigin #-}+snapRectOrigin :: DrawArena -> Rect -> IO Rect+snapRectOrigin da (Rect x y w h) = do+  s <- readIORef (daSnapScale da)+  pure (Rect (onGrid s x) (onGrid s y) w h)++-- | The u and v at which solid shapes sample glyph atlas page 0+-- ('glyphAtlasTextureId'): three texels in on the SDL host's 2048-texel+-- atlas, inside the 4x4 opaque white patch at its corner.+whitePixel :: Float+whitePixel = 1.5 / 1024.0
+ lib/NanoUI/Internal/Draw/Shapes.hs view
@@ -0,0 +1,924 @@+{-# LANGUAGE StrictData #-}++-- | Solid geometry emitters: rects, gradients, images, rounded fills and+-- borders, coverage-AA strokes, lines and triangles.+module NanoUI.Internal.Draw.Shapes+  ( pushRect+  , pushQuadGradient+  , pushImage+  , pushImageRotated+  , pushRoundedRect+  , pushRoundedRectRaw+  , pushRoundedStroke+  , pushCircle+  , pushCircleStroke+  , pushLine+  , pushStrokeAA+  , pushStroke+  , pushFilledTriangle+  , pushPolygonAA+  , pushPolylineAA+  , points3+  ) where++import Control.Monad (when)+import Data.IORef (readIORef)+import Data.Primitive.PrimArray (PrimArray, indexPrimArray, newPrimArray, primArrayFromListN, runPrimArray, sizeofPrimArray, writePrimArray)+import Data.Word (Word32, Word8)+import Foreign.Ptr (Ptr)+import Foreign.Storable (pokeByteOff)+import NanoUI.Internal.Draw.Arena+import NanoUI.Internal.Draw.Types (DrawArena (..), DrawOp (..), LineCap (..), LineJoin (..), Shade (..), glyphAtlasTextureId, indexSize, quadPolygon, shiftDrawOp, vertexSize)+import NanoUI.Internal.Path (idealArcSteps, miterOffset, shoelace)+import NanoUI.Internal.SIMD+import NanoUI.Internal.Types (Color (..), Rect (..), clamp, finite, forUpTo_, onGrid)++{-# INLINE pushRect #-}+pushRect :: DrawArena -> Rect -> Color -> IO ()+pushRect da rect col =+  snapRectOrigin da rect >>= \r -> pushRectRaw da r col++{-# INLINE pushRectRaw #-}+pushRectRaw :: DrawArena -> Rect -> Color -> IO ()+pushRectRaw da r@(Rect _ _ w h) col+  | w <= 0 || h <= 0 = pure ()+  | otherwise = do+      recordOp da (FillRect r col)+      setTexture da glyphAtlasTextureId+      pushQuad da r whitePixel whitePixel whitePixel whitePixel col++-- Quad with a color per corner. GPU interpolates across the two triangles.+-- Corners: top-left, top-right, bottom-right, bottom-left.+pushQuadGradient :: DrawArena -> Rect -> Color -> Color -> Color -> Color -> IO ()+pushQuadGradient da rect@(Rect _ _ w h) tl tr br bl+  | w <= 0 || h <= 0 = pure ()+  | otherwise = do+      Rect px py _ _ <- snapRectOrigin da rect+      recordOp da (FillQuadGradient (Rect px py w h) tl tr br bl)+      setTexture da glyphAtlasTextureId+      let !c0 = unpackColorF tl+          !c1 = unpackColorF tr+          !c2 = unpackColorF br+          !c3 = unpackColorF bl+      withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->+        pokeQuadGradientSIMD vp vOff ip iOff px py w h whitePixel whitePixel c0 c1 c2 c3 baseIdxWord++{-# INLINE pushImage #-}+pushImage :: DrawArena -> Rect -> Int -> Float -> Float -> Float -> Float -> Color -> IO ()+pushImage da rect tex u0 v0 u1 v1 col+  | tex <= 0 = pushRect da rect col+  | otherwise = do+      r <- snapRectOrigin da rect+      setTexture da tex+      pushQuad da r u0 v0 u1 v1 col++-- | 'pushImage' rotated @angle@ radians clockwise about the rect's centre.+-- Not snapped to the pixel grid.+pushImageRotated :: DrawArena -> Rect -> Float -> Int -> Float -> Float -> Float -> Float -> Color -> IO ()+pushImageRotated da (Rect x y w h) angle tex0 u0 v0 u1 v1 col = do+  -- No texture: sample the white pixel, as 'pushRect' does.+  let (!tex, !tu0, !tv0, !tu1, !tv1)+        | tex0 <= 0 = (glyphAtlasTextureId, whitePixel, whitePixel, whitePixel, whitePixel)+        | otherwise = (tex0, u0, v0, u1, v1)+      !(r, g, b, a) = unpackColorF col+      !c = cos angle+      !s = sin angle+      !cx = x + w / 2+      !cy = y + h / 2+      !hw = w / 2+      !hh = h / 2+      -- Rotated corners clockwise from top-left.+      cornerX dx dy = cx + dx * c - dy * s+      cornerY dx dy = cy + dx * s + dy * c+      !x0 = cornerX (-hw) (-hh)+      !y0 = cornerY (-hw) (-hh)+      !x1 = cornerX hw (-hh)+      !y1 = cornerY hw (-hh)+      !x2 = cornerX hw hh+      !y2 = cornerY hw hh+      !x3 = cornerX (-hw) hh+      !y3 = cornerY (-hw) hh+  -- A solid quad records as a shape; an image records as itself+  -- ('NanoUI.Internal.Draw.pushImageOp').+  when (tex0 <= 0) $+    recordOp da $ quadPolygon (primArrayFromListN 8 [x0, y0, x1, y1, x2, y2, x3, y3]) (Flat col)+  setTexture da tex+  withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->+    pokeQuadCornersSIMD vp vOff ip iOff x0 y0 x1 y1 x2 y2 x3 y3+      tu0+      tv0+      tu1+      tv1+      r+      g+      b+      a+      baseIdxWord++-- 4 segments per 90° arc, so 'cornerCosSin' has 5 points per quadrant.+cornerSegments :: Int+cornerSegments = 4++-- | How far a stroked arc fades out either side of its solid part, in+-- pixels. A quad's alpha is interpolated across it and read at the middle of+-- each pixel, so a straight side, snapped to the grid, is read at the line's+-- own alpha and comes out at full strength. An arc is not on the grid and+-- never can be: its curve passes between the pixels, and each one is read+-- some way down the fade. A whole pixel of fade on each side, with no solid+-- part between them, leaves the brightest pixel of a hairline arc at about+-- three quarters of the colour the straight sides it joins are drawn in, so+-- a rounded corner reads lighter than its own edges. Half a pixel, with the+-- rest of the width left solid, spends the same ink over a narrower band and+-- gives the pixels nearest the curve the whole of it.+arcFeather :: Float+arcFeather = 0.5++-- | Precomputed unit-circle cos/sin of point @seg@ of rounded-rect corner @q@+-- (top left, then clockwise): each corner's arc is the one before it turned a+-- quarter.+{-# INLINE cornerCosSin #-}+cornerCosSin :: Int -> Int -> (Float, Float)+cornerCosSin q seg =+  case q of+    0 -> (-c, -s)+    1 -> (s, -c)+    2 -> (c, s)+    _ -> (-s, c)+  where+    (c, s) = case seg of+      0 -> (1.0, 0.0)+      1 -> (0.9238795325, 0.3826834324)+      2 -> (0.7071067812, 0.7071067812)+      3 -> (0.3826834324, 0.9238795325)+      _ -> (0.0, 1.0)++-- | Poke one coverage-AA strip with unit normal @(nx, ny)@ into a reservation+-- at vertex offset @vi@ and index offset @ii@ (both relative to @base@/@baseIdx@).+-- Out of line as a top-level worker so 'pushRoundedStrokeRaw' stays small+-- enough for GHC to keep 'concentricOffsetsSIMD' unboxed with zero heap+-- allocation.+{-# NOINLINE pokeStripAt #-}+pokeStripAt ::+  Ptr Word8 ->+  Ptr Word8 ->+  Int ->+  Int ->+  Int ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  IO ()+pokeStripAt !vp !ip !base !baseIdx !vi !ii !x0 !y0 !x1 !y1 !nx !ny !bw !r !g !b !a = do+  let !half = bw * 0.5+      !core = max 0 (half - 0.5)+      !outer = half + 0.5+      !va = fromIntegral (base + vi) :: Word32+  pokeBandVerts vp ((base + vi) * vertexSize) True r g b a $+    concentricOffsetsSIMD x0 y0 nx ny (-outer) (-core) core outer+  pokeBandVerts vp ((base + vi + 4) * vertexSize) True r g b a $+    concentricOffsetsSIMD x1 y1 nx ny (-outer) (-core) core outer+  pokeBandIndices ip ((baseIdx + ii) * indexSize) True va (va + 4)++-- | Poke one cross-section of a coverage-AA band at byte offset @vBase@: four+-- points clear, solid, solid, clear, or with @hasCore@ off three, the two+-- solid ones sharing the second point.+{-# INLINE pokeBandVerts #-}+pokeBandVerts ::+  Ptr Word8 ->+  Int ->+  Bool ->+  Float ->+  Float ->+  Float ->+  Float ->+  ((Float, Float), (Float, Float), (Float, Float), (Float, Float)) ->+  IO ()+pokeBandVerts vp vBase hasCore r g b a ((p0x, p0y), (p1x, p1y), (p2x, p2y), (p3x, p3y)) = do+  pokeVertexSIMD vp vBase p0x p0y r g b 0 whitePixel whitePixel+  pokeVertexSIMD vp (vBase + 32) p1x p1y r g b a whitePixel whitePixel+  when hasCore $+    pokeVertexSIMD vp (vBase + 64) p2x p2y r g b a whitePixel whitePixel+  pokeVertexSIMD vp (vBase + if hasCore then 96 else 64) p3x p3y r g b 0 whitePixel whitePixel++-- | Index the quads between two 'pokeBandVerts' cross-sections starting at+-- vertices @va@ and @vb@, at byte offset @iOff@: three quads, or two without+-- @hasCore@.+{-# INLINE pokeBandIndices #-}+pokeBandIndices :: Ptr Word8 -> Int -> Bool -> Word32 -> Word32 -> IO ()+pokeBandIndices ip iOff hasCore va vb = do+  pokeQuadIndices ip iOff va (va + 1) (vb + 1) vb+  pokeQuadIndices ip (iOff + 24) (va + 1) (va + 2) (vb + 2) (vb + 1)+  when hasCore $+    pokeQuadIndices ip (iOff + 48) (va + 2) (va + 3) (vb + 3) (vb + 2)++{-# INLINE pushRoundedRect #-}+pushRoundedRect :: DrawArena -> Rect -> Float -> Color -> IO ()+pushRoundedRect da rect radius col =+  snapRectOrigin da rect >>= \r -> pushRoundedRectRaw da r radius col++-- | Unsnapped variant used when the rect is already anchored to the snapped+-- device pixel grid, e.g. a mark that must stay concentric with a border that+-- has already snapped its own origin. Re-snapping here would round the+-- off-origin inset (delta = (box - mark)/2) away, and since absolute snapping+-- rides on the fractional part of the widget position the mark would drift+-- off-center by up to a pixel as the widget scrolls.+-- Keep the fused emitter out of its many paint callers: inlining it duplicates+-- the corner loops and increases instruction-cache pressure substantially.+{-# NOINLINE pushRoundedRectRaw #-}+pushRoundedRectRaw :: DrawArena -> Rect -> Float -> Color -> IO ()+pushRoundedRectRaw da (Rect x y w h) radius col+  | w <= 0 || h <= 0 = pure ()+  | otherwise = do+      square <- readIORef (daSquareGeometry da)+      let !rad = min (max 0 radius) (min (w * 0.5) (h * 0.5))+      if square || rad <= 0.5+        then pushRectRaw da (Rect x y w h) col+        else do+          recordOp da (FillRoundedRect (Rect x y w h) rad col)+          setTexture da glyphAtlasTextureId+          let !segs = cornerSegments+              !ring = segs + 1+              !midW = max 0 (w - 2 * rad)+              !midH = max 0 (h - 2 * rad)+              !hasCenter = midW > 0 && midH > 0+              !hasTB = midW > 0+              !hasLR = midH > 0+              !quadCount =+                (if hasCenter then 1 else 0)+                  + (if hasTB then 2 else 0)+                  + (if hasLR then 2 else 0)+              !cornerV = 1 + 2 * ring+              !cornerI = segs * 9+              !needV = quadCount * 4 + 4 * cornerV+              !needI = quadCount * 6 + 4 * cornerI+          (!vp, !ip, !base, !baseIdx) <- reserveRaw da needV needI+          let !(cr, cg, cb, ca) = unpackColorF col+              !u = whitePixel+              pokeQuadAt !vi !ii !qx !qy !qw !qh =+                pokeQuadSIMD+                  vp+                  ((base + vi) * vertexSize)+                  ip+                  ((baseIdx + ii) * indexSize)+                  qx+                  qy+                  qw+                  qh+                  u+                  u+                  u+                  u+                  cr+                  cg+                  cb+                  ca+                  (fromIntegral (base + vi))+              !vi1 = if hasCenter then 4 else 0+              !ii1 = if hasCenter then 6 else 0+              !vi2 = vi1 + (if hasTB then 8 else 0)+              !ii2 = ii1 + (if hasTB then 12 else 0)+              !vi3 = vi2 + (if hasLR then 8 else 0)+              !ii3 = ii2 + (if hasLR then 12 else 0)+          when hasCenter $ pokeQuadAt 0 0 (x + rad) (y + rad) midW midH+          when hasTB $ do+            pokeQuadAt vi1 ii1 (x + rad) y midW rad+            pokeQuadAt (vi1 + 4) (ii1 + 6) (x + rad) (y + h - rad) midW rad+          when hasLR $ do+            pokeQuadAt vi2 ii2 x (y + rad) rad midH+            pokeQuadAt (vi2 + 4) (ii2 + 6) (x + w - rad) (y + rad) rad midH+          pokeCornerTop vp ip base baseIdx rad cr cg cb ca vi3 ii3 (x + rad) (y + rad) 0+          pokeCornerTop vp ip base baseIdx rad cr cg cb ca (vi3 + cornerV) (ii3 + cornerI) (x + w - rad) (y + rad) 1+          pokeCornerTop vp ip base baseIdx rad cr cg cb ca (vi3 + 2 * cornerV) (ii3 + 2 * cornerI) (x + w - rad) (y + h - rad) 2+          pokeCornerTop vp ip base baseIdx rad cr cg cb ca (vi3 + 3 * cornerV) (ii3 + 3 * cornerI) (x + rad) (y + h - rad) 3+          commitRaw da base baseIdx needV needI++-- | One corner of a rounded fill: a fan from the corner centre to the rim+-- and a feathered fringe outside it, as a top-level worker so the fill+-- allocates no closure for it.+{-# NOINLINE pokeCornerTop #-}+pokeCornerTop :: Ptr Word8 -> Ptr Word8 -> Int -> Int -> Float -> Float -> Float -> Float -> Float -> Int -> Int -> Float -> Float -> Int -> IO ()+pokeCornerTop !vp !ip !base !baseIdx !rad !cr !cg !cb !ca !vi !ii !ccx !ccy !q = do+  let !segs = cornerSegments+      !ring = segs + 1+      !u = whitePixel+      !vBase = (base + vi) * vertexSize+      !centerIdx = fromIntegral (base + vi) :: Word32+      !inRad = max 0 (rad - 1.0)+  pokeVertexSIMD vp vBase ccx ccy cr cg cb ca u u+  forUpTo_ (segs + 1) $ \i -> do+    let !(ct, st) = cornerCosSin q i+        !rimI = base + vi + 1 + i+        !outI = base + vi + 1 + ring + i+    pokeVertexSIMD vp (rimI * vertexSize) (ccx + inRad * ct) (ccy + inRad * st) cr cg cb ca u u+    pokeVertexSIMD vp (outI * vertexSize) (ccx + rad * ct) (ccy + rad * st) cr cg cb 0 u u+    when (i > 0) $ do+      let !k = i - 1+          !rim0 = fromIntegral (base + vi + i) :: Word32+          !rim1 = fromIntegral (base + vi + 1 + i) :: Word32+          !out0 = fromIntegral (base + vi + 1 + ring + k) :: Word32+          !out1 = fromIntegral (base + vi + 1 + ring + i) :: Word32+          !fillOff = (baseIdx + ii + k * 3) * indexSize+          !fringeOff = (baseIdx + ii + segs * 3 + k * 6) * indexSize+      pokeByteOff ip fillOff centerIdx+      pokeByteOff ip (fillOff + 4) rim0+      pokeByteOff ip (fillOff + 8) rim1+      pokeQuadIndices ip fringeOff rim0 out0 out1 rim1++-- | A filled circle. The centre snaps to the device pixel grid, not the+-- bounding box's origin: snapping the origin rounds @cx - radius@, so two+-- circles sharing a centre but not a radius would land up to a pixel apart.+{-# INLINE pushCircle #-}+pushCircle :: DrawArena -> Float -> Float -> Float -> Color -> IO ()+pushCircle da cx cy radius col = do+  s <- readIORef (daSnapScale da)+  pushRoundedRectRaw da (circleBox (onGrid s cx) (onGrid s cy) radius) radius col++-- | A circle's outline, its centre snapped as 'pushCircle' snaps it.+{-# INLINE pushCircleStroke #-}+pushCircleStroke :: DrawArena -> Float -> Float -> Float -> Float -> Color -> IO ()+pushCircleStroke da cx cy radius bw col = do+  s <- readIORef (daSnapScale da)+  pushRoundedStrokeRaw da (circleBox (onGrid s cx) (onGrid s cy) radius) radius bw col++circleBox :: Float -> Float -> Float -> Rect+circleBox cx cy radius = Rect (cx - radius) (cy - radius) (2 * radius) (2 * radius)++{-# INLINE pushRoundedStroke #-}+pushRoundedStroke :: DrawArena -> Rect -> Float -> Float -> Color -> IO ()+pushRoundedStroke da rect radius bw col =+  snapRectOrigin da rect >>= \r -> pushRoundedStrokeRaw da r radius bw col++-- | 'pushRoundedStroke' without snapping the origin, for a rect already+-- anchored to the grid; see 'pushRoundedRectRaw'.+{-# NOINLINE pushRoundedStrokeRaw #-}+pushRoundedStrokeRaw :: DrawArena -> Rect -> Float -> Float -> Color -> IO ()+pushRoundedStrokeRaw da (Rect px py w h) radius bw col+  | w <= 0 || h <= 0 || bw <= 0 = pure ()+  | otherwise = do+      setTexture da glyphAtlasTextureId+      square <- readIORef (daSquareGeometry da)+      let !rad = min (max 0 radius) (min (w * 0.5) (h * 0.5))+          !ibw = min bw (min (w * 0.5) (h * 0.5))+      if square+        then pushSquareStroke da px py w h ibw col+        else do+          recordOp da (StrokeRoundedRect (Rect px py w h) rad ibw col)+          let !n = cornerSegments+              -- With square corners the top and bottom run the full width+              -- and the sides fit between them, so each corner is drawn once+              -- (sides meeting at their centre lines would leave its outer+              -- quarter bare and draw the inner one twice); rounded ones end+              -- the sides where the arcs start. A border wider than the+              -- radius fits its sides between the top and bottom too, and a+              -- quad fills the band this leaves beside each arc.+              !corners = rad > 0.5+              !bands = corners && ibw > rad+              !topY = py + ibw / 2+              !leftX = px + ibw / 2+              !x0 = if corners then px + rad else px+              !y0 = if corners && not bands then py + rad else py + ibw+              !midW = max 0 (if corners then w - 2 * rad else w)+              !midH = max 0 (if corners && not bands then h - 2 * rad else h - 2 * ibw)+              !botY = py + h - ibw / 2+              !rightX = px + w - ibw / 2++              !cr = rad - ibw / 2+              !doTB = midW >= 0.001+              !doLR = midH >= 0.001+              !stripCount = (if doTB then 2 else 0) + (if doLR then 2 else 0)+              -- A stroke no wider than the feather has coincident inner/outer+              -- core rings. Share that ring and omit its zero-area triangles+              -- instead of submitting a fourth vertex and a third quad for+              -- every arc segment. A one-pixel hairline has a solid core now+              -- and takes the four-vertex path.+              !core = max 0 ((ibw - arcFeather) * 0.5)+              !hasCore = core > 0+              !arcStride = if hasCore then 4 else 3+              !arcIndices = if hasCore then 18 else 12+              !arcV = (n + 1) * arcStride+              !arcI = n * arcIndices+              !needV = stripCount * 8 + (if corners then 4 * arcV else 0) + (if bands then 16 else 0)+              !needI = stripCount * 18 + (if corners then 4 * arcI else 0) + (if bands then 24 else 0)+          (!vp, !ip, !base, !baseIdx) <- reserveRaw da needV needI+          let !(r, g, b, a) = unpackColorF col+              !viLR = if doTB then 16 else 0+              !iiLR = if doTB then 36 else 0+              !viC = stripCount * 8+              !iiC = stripCount * 18+              !solidCenter = ibw >= rad - 1.0e-4+              !inner = if solidCenter then 0 else max 0 (cr - core)+              !outerR = cr + core+              !innerAA = if solidCenter then 0 else max 0 (inner - arcFeather)+              !outerAA = outerR + arcFeather+          when doTB $ do+            pokeStripAt vp ip base baseIdx 0 0 x0 topY (x0 + midW) topY 0 1 ibw r g b a+            pokeStripAt vp ip base baseIdx 8 18 x0 botY (x0 + midW) botY 0 1 ibw r g b a+          when doLR $ do+            pokeStripAt vp ip base baseIdx viLR iiLR leftX y0 leftX (y0 + midH) (-1) 0 ibw r g b a+            pokeStripAt vp ip base baseIdx (viLR + 8) (iiLR + 18) rightX y0 rightX (y0 + midH) (-1) 0 ibw r g b a+          when corners $ do+            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a viC iiC (px + rad) (py + rad) 0+            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a (viC + arcV) (iiC + arcI) (px + w - rad) (py + rad) 1+            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a (viC + 2 * arcV) (iiC + 2 * arcI) (px + w - rad) (py + h - rad) 2+            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a (viC + 3 * arcV) (iiC + 3 * arcI) (px + rad) (py + h - rad) 3+          when bands $ do+            let band !k !bx !by =+                  let !vi = base + viC + 4 * arcV + 4 * k+                   in pokeQuadSIMD vp (vi * vertexSize) ip ((baseIdx + iiC + 4 * arcI + 6 * k) * indexSize) bx by rad (ibw - rad) whitePixel whitePixel whitePixel whitePixel r g b a (fromIntegral vi)+            band 0 px (py + rad)+            band 1 (px + w - rad) (py + rad)+            band 2 (px + w - rad) (py + h - ibw)+            band 3 px (py + h - ibw)+          commitRaw da base baseIdx needV needI++-- | One corner arc of a rounded stroke, as a top-level worker so the stroke+-- allocates no closure for it.+{-# NOINLINE pokeArcTop #-}+pokeArcTop :: Ptr Word8 -> Ptr Word8 -> Int -> Int -> Bool -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Int -> Int -> Float -> Float -> Int -> IO ()+pokeArcTop !vp !ip !base !baseIdx !hasCore !innerAA !inner !outerR !outerAA !r !g !b !a !vi !ii !ccx !ccy !q = do+  let !n = cornerSegments+      !arcStride = if hasCore then 4 else 3+      !arcIndices = if hasCore then 18 else 12+  forUpTo_ (n + 1) $ \i -> do+    let !(ct, st) = cornerCosSin q i+    pokeBandVerts vp ((base + vi + i * arcStride) * vertexSize) hasCore r g b a $+      concentricOffsetsSIMD ccx ccy ct st innerAA inner outerR outerAA+  forUpTo_ n $ \i -> do+    let !va = fromIntegral (base + vi + i * arcStride) :: Word32+    pokeBandIndices ip ((baseIdx + ii + i * arcIndices) * indexSize) hasCore va (va + fromIntegral arcStride)++-- | Border of four flat rects inside @(x, y, w, h)@, @t@ thick. The origin is+-- already snapped by the caller; the texture is already selected.+pushSquareStroke :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushSquareStroke da x y w h t col = do+  recording <- getDrawRecordOps da+  let edge qx qy qw qh =+        when (qw > 0 && qh > 0) $ do+          when recording $ recordOpOn da (FillRect (Rect qx qy qw qh) col)+          pushQuad da (Rect qx qy qw qh) whitePixel whitePixel whitePixel whitePixel col+      !innerH = h - 2 * t+  edge x y w t+  edge x (y + h - t) w t+  edge x (y + t) t innerH+  edge (x + w - t) (y + t) t innerH++-- | A line @thickness@ wide with round caps: a coverage-AA strip with a+-- round cap on each end. An axis-aligned line is a plain rect spanning its+-- caps.+{-# INLINE pushLine #-}+pushLine :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushLine da x1 y1 x2 y2 thickness col+  | thickness <= 0 = pure ()+  | otherwise = do+      square <- readIORef (daSquareGeometry da)+      let !r = thickness / 2+          cap cx cy = pushCircle da cx cy r col+      if square+        then pushStroke da x1 y1 x2 y2 thickness col+        else+          if x1 == x2 || y1 == y2+            then pushRect da (Rect (min x1 x2 - r) (min y1 y2 - r) (abs (x2 - x1) + thickness) (abs (y2 - y1) + thickness)) col+            else do+              pushStrokeAA da x1 y1 x2 y2 thickness col+              cap x1 y1+              cap x2 y2++-- | Snap segment endpoints to the arena's device pixel grid before calling @raw@.+{-# INLINE snapStrokeEndpoints #-}+snapStrokeEndpoints ::+  (DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()) ->+  DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+snapStrokeEndpoints raw da x0 y0 x1 y1 bw col+  | bw <= 0 = pure ()+  | otherwise = do+      s <- readIORef (daSnapScale da)+      raw da (onGrid s x0) (onGrid s y0) (onGrid s x1) (onGrid s y1) bw col++-- Coverage-AA strip for a straight segment, the strip a rounded stroke's+-- sides use, without the round caps 'pushLine' adds.+{-# INLINE pushStrokeAA #-}+pushStrokeAA :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushStrokeAA = snapStrokeEndpoints pushStrokeAARaw++-- | Unsnapped variant: the caller already snapped the endpoints.+pushStrokeAARaw :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushStrokeAARaw da x0 y0 x1 y1 bw col = do+  square <- readIORef (daSquareGeometry da)+  if square+    then pushStrokeRaw da x0 y0 x1 y1 bw col+    else case strokeNormal x0 y0 x1 y1 of+      Nothing -> pure ()+      Just (!nx, !ny) -> do+        recordOp da (StrokeLineAA x0 y0 x1 y1 bw col)+        setTexture da glyphAtlasTextureId+        let !(r, g, b, a) = unpackColorF col+        withVertsRaw da 8 18 $ \vp ip base baseIdx ->+          pokeStripAt vp ip base baseIdx 0 0 x0 y0 x1 y1 nx ny bw r g b a++strokeNormal :: Float -> Float -> Float -> Float -> Maybe (Float, Float)+strokeNormal x0 y0 x1 y1 =+  let !dx = x1 - x0+      !dy = y1 - y0+      !len = sqrt (dx * dx + dy * dy)+   in if not (finite len) || len < 0.001 then Nothing else Just (-dy / len, dx / len)++-- One quad per segment. Plots and diagrams use this; pushLine adds round caps.+pushStroke :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushStroke = snapStrokeEndpoints pushStrokeRaw++pushStrokeRaw :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushStrokeRaw da px1 py1 px2 py2 thickness col+  | thickness <= 0 = pure ()+  | otherwise =+      case strokeNormal px1 py1 px2 py2 of+        Nothing -> pure ()+        Just (!nx, !ny) -> do+          recordOp da (Stroke px1 py1 px2 py2 thickness col)+          setTexture da glyphAtlasTextureId+          let !half = thickness * 0.5+              !hx = nx * half+              !hy = ny * half+          withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord -> do+            let !(r, g, b, a) = unpackColorF col+                !u = whitePixel+            pokeQuadCornersSIMD vp vOff ip iOff (px1 + hx) (py1 + hy) (px2 + hx) (py2 + hy) (px2 - hx) (py2 - hy) (px1 - hx) (py1 - hy) u u u u r g b a baseIdxWord++-- | A lone filled triangle with anti-aliased edges; see 'pushPolygonAA'. It+-- moves to put the middle of its width, not its first corner, on the grid,+-- so an arrow symmetric about an upright axis stays symmetric whatever its+-- width, and its first corner's row, which an arrow's flat base passes+-- through, stays sharp.+pushFilledTriangle :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()+pushFilledTriangle da x0 y0 x1 y1 x2 y2 col =+  polygonAAFrom+    da+    ((min x0 (min x1 x2) + max x0 (max x1 x2)) * 0.5)+    y0+    (points3 x0 y0 x1 y1 x2 y2)+    triangleRing+    triangleIndices+    (Flat col)++-- | Three points as the flat coordinate array 'pushPolygonAA' and+-- 'pushPolylineAA' take, written straight into the array: a list literal+-- through 'primArrayFromListN' is not fused and boxes every coordinate.+{-# INLINE points3 #-}+points3 :: Float -> Float -> Float -> Float -> Float -> Float -> PrimArray Float+points3 x0 y0 x1 y1 x2 y2 = runPrimArray $ do+  a <- newPrimArray 6+  writePrimArray a 0 x0+  writePrimArray a 1 y0+  writePrimArray a 2 x1+  writePrimArray a 3 y1+  writePrimArray a 4 x2+  writePrimArray a 5 y2+  pure a++triangleIndices :: PrimArray Int+triangleIndices = primArrayFromListN 3 [0, 1, 2]++-- | Ring bounds for a lone triangle: one ring of three points.+triangleRing :: PrimArray Int+triangleRing = primArrayFromListN 2 [0, 3]++-- | Half the width of an anti-aliased edge's fade, in logical pixels: half a+-- device pixel, so an edge on the grid is solid on one side of it and clear+-- on the other.+{-# INLINE edgeFeather #-}+edgeFeather :: Float -> Float+edgeFeather s = if s > 0 then 0.5 / s else 0.5++-- | How far a miter may reach, as a multiple of the offset squared: a+-- join sharper than 120 degrees is cut back to twice the offset instead of+-- shooting off into a spike. Applies to polygon fringes and the inside of+-- stroke corners.+miterLimit :: Float+miterLimit = 4++-- | The offset at a vertex between two edges with unit normals @a@ and @b@,+-- scaled so moving the vertex by @d@ along it moves both edges by @d@. A zero+-- normal (a repeated point) defers to the other.+{-# INLINE miterOf #-}+miterOf :: Float -> Float -> Float -> Float -> (Float, Float)+miterOf ax ay bx by+  | ax == 0 && ay == 0 = (bx, by)+  | bx == 0 && by == 0 = (ax, ay)+  | d2 < 1.0e-6 = (ax, ay)+  | otherwise = let !k = min miterLimit (1 / d2) in (mx * k, my * k)+  where+    !mx = (ax + bx) * 0.5+    !my = (ay + by) * 0.5+    !d2 = mx * mx + my * my++-- | Unit normal of the segment from @(x0, y0)@ to @(x1, y1)@, a quarter turn+-- from its direction, or zero for a zero-length segment.+{-# INLINE segNormal #-}+segNormal :: Float -> Float -> Float -> Float -> (Float, Float)+segNormal x0 y0 x1 y1 =+  let !dx = x1 - x0+      !dy = y1 - y0+      !len = sqrt (dx * dx + dy * dy)+   in if not (finite len) || len < 1.0e-6 then (0, 0) else (-dy / len, dx / len)++-- | Whether a shade is flat or has a colour for each of @n@ points.+shadeCovers :: Shade -> Int -> Bool+shadeCovers sh n = case sh of+  Flat _ -> True+  Shaded cs -> sizeofPrimArray cs >= n++-- | Fill a polygon with holes and anti-aliased edges. @pts@ holds x/y pairs,+-- ring after ring (first point not repeated), then any interior points.+-- @rings@ holds each ring's start index plus the end of the last ring.+-- @tris@ holds index triples covering the polygon.+--+-- The first ring is the outline; the rest are holes wound the opposite way.+-- The polygon moves as a whole to put its first point on the device grid;+-- snapping points individually would bend small shapes. Ring edges fade+-- across one device pixel centred on the edge, so grid-aligned edges stay+-- sharp. Interior points get no fade.+pushPolygonAA :: DrawArena -> PrimArray Float -> PrimArray Int -> PrimArray Int -> Shade -> IO ()+pushPolygonAA da pts rings tris+  | sizeofPrimArray pts < 2 = const (pure ())+  | otherwise = polygonAAFrom da (indexPrimArray pts 0) (indexPrimArray pts 1) pts rings tris++-- | 'pushPolygonAA', moved to put @(rx, ry)@ rather than the first point on+-- the grid.+{-# NOINLINE polygonAAFrom #-}+polygonAAFrom :: DrawArena -> Float -> Float -> PrimArray Float -> PrimArray Int -> PrimArray Int -> Shade -> IO ()+polygonAAFrom da rx ry pts rings tris shade+  | n < 3 || nt < 3 || not ringsValid || not trisValid || area == 0 || not (shadeCovers shade n) = pure ()+  | otherwise = do+      s <- readIORef (daSnapScale da)+      square <- readIORef (daSquareGeometry da)+      setTexture da glyphAtlasTextureId+      let !ox = onGrid s rx - rx+          !oy = onGrid s ry - ry+      recordOp da (shiftDrawOp ox oy (FillPolygon pts rings tris shade))+      let !f = if square then 0 else edgeFeather s+          -- 'segNormal' points into a positive-area ring. Holes wind the+          -- other way, so their normals point out of the fill.+          !out = if area > 0 then -1 else 1+          {-# INLINE normalAt #-}+          normalAt i j =+            let (nx, ny) = segNormal (px i) (py i) (px j) (py j)+             in (nx * out, ny * out)+          -- Square geometry has no fade, so no fringe either.+          !fringe = if square then 0 else nOut+          !flat = case shade of+            Flat c -> unpackColorF c+            Shaded _ -> (0, 0, 0, 0)+          {-# INLINE rgbaAt #-}+          rgbaAt i = case shade of+            Flat _ -> flat+            Shaded cs -> unpackColorF (Color (indexPrimArray cs i))+      withVertsRaw da (n + fringe) (nt + 6 * fringe) $ \vp ip base baseIdx -> do+        forRings $ \from to -> forUpTo_ (to - from) $ \k -> do+          let !i = from + k+              !prev = if k == 0 then to - 1 else i - 1+              !next = if i + 1 >= to then from else i + 1+              (ax, ay) = normalAt prev i+              (bx, by) = normalAt i next+              (mx, my) = miterOf ax ay bx by+              !vx = px i + ox+              !vy = py i + oy+              !(r, g, b, a) = rgbaAt i+          pokeVertexSIMD vp ((base + i) * vertexSize) (vx - f * mx) (vy - f * my) r g b a whitePixel whitePixel+          when (fringe > 0) $+            pokeVertexSIMD vp ((base + n + i) * vertexSize) (vx + f * mx) (vy + f * my) r g b 0 whitePixel whitePixel+        forUpTo_ (n - nOut) $ \k -> do+          let !i = nOut + k+              !(r, g, b, a) = rgbaAt i+          pokeVertexSIMD vp ((base + i) * vertexSize) (px i + ox) (py i + oy) r g b a whitePixel whitePixel+        forUpTo_ nt $ \k ->+          pokeByteOff ip ((baseIdx + k) * indexSize) (fromIntegral (base + indexPrimArray tris k) :: Word32)+        when (fringe > 0) $+          forRings $ \from to -> forUpTo_ (to - from) $ \k -> do+            let !i = from + k+                !j = if i + 1 >= to then from else i + 1+                !inI = fromIntegral (base + i) :: Word32+                !inJ = fromIntegral (base + j) :: Word32+                !m = fromIntegral n :: Word32+            pokeQuadIndices ip ((baseIdx + nt + 6 * i) * indexSize) inI inJ (inJ + m) (inI + m)+  where+    !n = sizeofPrimArray pts `div` 2+    !nt = sizeofPrimArray tris - sizeofPrimArray tris `mod` 3+    !nr = sizeofPrimArray rings - 1+    ringAt r = indexPrimArray rings r+    -- First interior (non-ring) point.+    !nOut = if nr >= 1 then ringAt nr else 0+    ringsValid = nr >= 1 && ringAt 0 == 0 && nOut <= n && and [ringAt r < ringAt (r + 1) | r <- [0 .. nr - 1]]+    trisValid = and [t >= 0 && t < n | k <- [0 .. nt - 1], let t = indexPrimArray tris k]+    forRings body = forUpTo_ nr $ \r -> body (ringAt r) (ringAt (r + 1))+    px i = indexPrimArray pts (2 * i)+    py i = indexPrimArray pts (2 * i + 1)+    -- Outline area; its sign gives the winding.+    !area = shoelace (if nr >= 1 then ringAt 1 else 0) (\i -> (px i, py i))++-- | Stroke a polyline @w@ wide with anti-aliased sides. @pts@ holds x/y+-- pairs; @closed@ joins the last point to the first (do not repeat it).+-- Open ends use @cap@; corners use @join@, with miters longer than @limit@+-- times the width beveled. The inside of corners sharper than 60 degrees is+-- cut back ('miterLimit'). Near-straight corners are always mitered, so a+-- flattened curve costs no more than a straight line.+--+-- The line moves as a whole to put its first point's edges on the device+-- grid, like 'pushPolygonAA', so axis-aligned lines of whole-pixel width are+-- sharp. Lines thinner than the fade draw fainter to keep their ink. Each+-- point has a four-vertex cross-section (faded, solid, solid, faded); round+-- and bevel joins use two, one square to each segment, with the outer+-- corner filled between.+{-# NOINLINE pushPolylineAA #-}+pushPolylineAA :: DrawArena -> PrimArray Float -> Float -> Bool -> LineCap -> LineJoin -> Float -> Shade -> IO ()+pushPolylineAA da pts w closed cap join limit shade+  | n < 2 || not (w > 0) || not (shadeCovers shade n) = pure ()+  | otherwise = do+      s <- readIORef (daSnapScale da)+      square <- readIORef (daSquareGeometry da)+      setTexture da glyphAtlasTextureId+      let !hw = w * 0.5+          !ox = onGrid s (px 0 - hw) + hw - px 0+          !oy = onGrid s (py 0 - hw) + hw - py 0+      recordOp da (shiftDrawOp ox oy (StrokePolyline pts w closed cap join limit shade))+      let !f = if square then 0 else edgeFeather s+          !core = max 0 (hw - f)+          !outer = hw + f+          !thin = if core > 0 then 1 else min 1 (w / outer)+          !flat = case shade of+            Flat c -> let !(r, g, b, a) = unpackColorF c in (r, g, b, a * thin)+            Shaded _ -> (0, 0, 0, 0)+          {-# INLINE colourAt #-}+          colourAt i = case shade of+            Flat _ -> flat+            Shaded cs -> let !(r, g, b, a) = unpackColorF (Color (indexPrimArray cs i)) in (r, g, b, a * thin)+          !segs = if closed then n else n - 1+          -- Upper bound on chords per round join or cap (a half turn).+          !halfTurn = max 2 (arcChords s outer pi)+          !roundJoins = join == RoundJoin+          !roundCaps = cap == RoundCap && not closed+          !maxV = 8 * n + (if roundJoins then 2 * halfTurn * n else 0) + (if roundCaps then 4 * halfTurn else 0)+          !maxI = 18 * segs + 9 * n * (if roundJoins then halfTurn else 1) + (if roundCaps then 18 * halfTurn else 0)+          -- Corners whose miter reaches under 0.1 device pixel past the+          -- side show no join.+          !straightD2 = let q = hw / (hw + 0.1 / max 1 s) in q * q+          {-# INLINE normalAt #-}+          normalAt i =+            let !j = if i + 1 >= n then 0 else i + 1+             in segNormal (px i) (py i) (px j) (py j)+      withVertsReserve da maxV maxI $ \vp ip base baseIdx commit -> do+        let vidx k = fromIntegral (base + k) :: Word32+            vert k x y r g b a = pokeVertexSIMD vp ((base + k) * vertexSize) (x + ox) (y + oy) r g b a whitePixel whitePixel+            -- Cross-section at @(x, y)@: negative side along @(nx, ny)@,+            -- positive side along @(qx, qy)@.+            section v x y nx ny qx qy (r, g, b, a) = do+              vert v (x - nx * outer) (y - ny * outer) r g b 0+              vert (v + 1) (x - nx * core) (y - ny * core) r g b a+              vert (v + 2) (x + qx * core) (y + qy * core) r g b a+              vert (v + 3) (x + qx * outer) (y + qy * outer) r g b 0+            -- Symmetric section (the common case), via SIMD offsets.+            {-# INLINE evenSection #-}+            evenSection v x y mx my (r, g, b, a) =+              pokeBandVerts vp ((base + v) * vertexSize) True r g b a $+                concentricOffsetsSIMD (x + ox) (y + oy) mx my (-outer) (-core) core outer+            {-# INLINE band #-}+            band k va vb = do+              pokeBandIndices ip ((baseIdx + k) * indexSize) True (vidx va) (vidx vb)+              pure (k + 18)+            -- Arc about @(x, y)@ from angle @a0@ through @sweep@ in @chords@+            -- chords: a solid core fanned from vertex @centre@ plus a faded+            -- rim. Endpoints are core/edge vertices @c0@/@o0@ and @c1@/@o1@;+            -- new vertices start at @v@.+            fan v k centre c0 o0 c1 o1 x y a0 sweep chords (r, g, b, a) = do+              forUpTo_ (chords - 1) $ \j0 -> do+                let !t = a0 + sweep * fromIntegral (j0 + 1) / fromIntegral chords+                    !ct = cos t+                    !st = sin t+                vert (v + 2 * j0) (x + ct * core) (y + st * core) r g b a+                vert (v + 2 * j0 + 1) (x + ct * outer) (y + st * outer) r g b 0+              let coreAt j+                    | j == 0 = c0+                    | j == chords = c1+                    | otherwise = v + 2 * (j - 1)+                  edgeAt j+                    | j == 0 = o0+                    | j == chords = o1+                    | otherwise = v + 2 * (j - 1) + 1+              forUpTo_ chords $ \j -> do+                let !o = (baseIdx + k + 9 * j) * indexSize+                pokeByteOff ip o (vidx centre)+                pokeByteOff ip (o + 4) (vidx (coreAt j))+                pokeByteOff ip (o + 8) (vidx (coreAt (j + 1)))+                pokeQuadIndices ip (o + 12) (vidx (coreAt j)) (vidx (edgeAt j)) (vidx (edgeAt (j + 1))) (vidx (coreAt (j + 1)))+              pure (v + 2 * (chords - 1), k + 9 * chords)+            -- Open end with segment normal @(nx, ny)@. A square cap moves the+            -- section half the width out; a round cap adds a fan beyond it.+            -- @dir@ is 1 at the last point, -1 at the first.+            capAt i v k nx ny dir = do+              let !col = colourAt i+                  !reach = if cap == SquareCap then hw * dir else 0+                  !x = px i + ny * reach+                  !y = py i - nx * reach+              evenSection v x y nx ny col+              if cap == RoundCap+                then do+                  (v', k') <- fan (v + 4) k (v + 2) (v + 2) (v + 3) (v + 1) v x y (atan2 ny nx) (negate dir * pi) halfTurn col+                  pure (v, v, v', k')+                else pure (v, v, v + 4, k)+            -- Corner between segments with normals @a@ and @b@. Only corners+            -- 'evenJoin' rejects come here, so both normals are nonzero and+            -- the corner needs more than one even section.+            joinAt i v k ax ay bx by = do+              let !col = colourAt i+                  !x = px i+                  !y = py i+                  -- Inner corner offset, cut back if very sharp.+                  (!ix, !iy) = miterOf ax ay bx by+                  miter = if join == MiterJoin then miterOffset limit ax ay bx by else Nothing+                  -- The outside is the side the next segment turns away from.+                  !turnsPositive = by * ax - bx * ay > 0+                  !outSign = if turnsPositive then -1 else 1+              case miter of+                Just (fx, fy) -> do+                  -- Miter within limit: outside runs to the full point.+                  if turnsPositive then section v x y fx fy ix iy col else section v x y ix iy fx fy col+                  pure (v, v, v + 4, k)+                Nothing -> do+                  let (!centre, !cIn, !oIn, !cOut, !oOut)+                        | turnsPositive = (v + 2, v + 1, v, v + 5, v + 4)+                        | otherwise = (v + 1, v + 2, v + 3, v + 6, v + 7)+                      !ux = outSign * ax+                      !uy = outSign * ay+                      -- Turning the way the corner turns: at a half turn+                      -- the cross product is a signed zero, and atan2 would+                      -- follow its sign back through the stroke instead.+                      !turned = abs (atan2 (ax * by - ay * bx) (ax * bx + ay * by))+                      !sweep = if turnsPositive then turned else negate turned+                      !chords = if join == RoundJoin then arcChords s outer turned else 1+                  if turnsPositive+                    then section v x y ax ay ix iy col >> section (v + 4) x y bx by ix iy col+                    else section v x y ix iy ax ay col >> section (v + 4) x y ix iy bx by col+                  (v', k') <- fan (v + 8) k centre cIn oIn cOut oOut x y (atan2 uy ux) sweep chords col+                  pure (v, v + 4, v', k')+            -- An end's cap faces along the nearest segment of nonzero+            -- length, stepping by @step@ from segment @i@.+            endNormal i step+              | i >= 0 && i < n - 1+              , (0, 0) <- normalAt i =+                  endNormal (i + step) step+              | otherwise = normalAt (max 0 (min (n - 2) i))+            pointAt i v k+              | not closed && i == 0 = let (nx, ny) = endNormal 0 1 in capAt i v k nx ny (-1)+              | not closed && i == n - 1 = let (nx, ny) = endNormal (n - 2) (-1) in capAt i v k nx ny 1+              | otherwise =+                  let (ax, ay) = normalAt (if i == 0 then n - 1 else i - 1)+                      (bx, by) = normalAt i+                   in joinAt i v k ax ay bx by+            loop !i !v !k !prevOut !firstIn+              | i >= n = do+                  k' <- if closed then band k prevOut firstIn else pure k+                  commit v k'+              -- Fast path: one even section, no tuple allocated.+              | closed || (i > 0 && i < n - 1)+              , (ax, ay) <- normalAt (if i == 0 then n - 1 else i - 1)+              , (bx, by) <- normalAt i+              , evenJoin ax ay bx by = do+                  let (mx, my) = miterOf ax ay bx by+                  evenSection v (px i) (py i) mx my (colourAt i)+                  k' <- if i > 0 then band k prevOut v else pure k+                  loop (i + 1) (v + 4) k' v (if i == 0 then v else firstIn)+              | otherwise = do+                  (inV, outV, v', k') <- pointAt i v k+                  k'' <- if i > 0 then band k' prevOut inV else pure k'+                  loop (i + 1) v' k'' outV (if i == 0 then inV else firstIn)+            -- A corner one section can draw: near-straight, or a miter within+            -- its limit that needs no inner cut-back.+            evenJoin ax ay bx by+              | (ax == 0 && ay == 0) || (bx == 0 && by == 0) = True+              | otherwise =+                  let !mx = (ax + bx) * 0.5+                      !my = (ay + by) * 0.5+                      !d2 = mx * mx + my * my+                   in d2 >= straightD2 || (join == MiterJoin && d2 >= 0.25 && d2 * limit * limit >= 1)+        loop 0 0 0 0 0+  where+    !n = sizeofPrimArray pts `div` 2+    px i = indexPrimArray pts (2 * i)+    py i = indexPrimArray pts (2 * i + 1)++-- | Chords needed for @sweep@ radians of an arc of radius @r@ (logical px) at+-- scale @s@, keeping each within a quarter device pixel. Clamped to 1..32.+arcChords :: Float -> Float -> Float -> Int+arcChords s r sweep+  | not (rd > 0.25) || not (finite sweep) = 1+  -- Bounded before rounding, so a huge radius cannot overflow the 'Int'.+  | otherwise = clamp 1 32 (ceiling (min 32 (idealArcSteps 0.25 rd sweep)))+  where+    rd = r * max 1 s
+ lib/NanoUI/Internal/Draw/Types.hs view
@@ -0,0 +1,521 @@+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE TypeFamilies #-}++-- | Draw-layer data: immediate vector ops, batched draw commands, the finished+-- per-frame draw data and the arena record. Free of font and emitter code so+-- the context types can name these without depending on the emitters.+module NanoUI.Internal.Draw.Types+  ( Layer (..)+  , DrawOp (.., DrawImageRect)+  , LineCap (..)+  , LineJoin (..)+  , Shade (..)+  , TextFont (..)+  , defaultTextFont+  , DrawingBuild+  , shiftDrawOp+  , quadPolygon+  , DrawCmd (..)+  , ShaderCall (..)+  , EffectSpan (..)+  , emptyShaderCalls+  , emptyEffectSpans+  , emptyUniformBytes+  , DrawData (..)+  , drawCmdCount+  , drawCmdNull+  , forDrawCmdsInLayer_+  , drawCmdElems+  , DrawFrameExtra (..)+  , emptyDrawExtra+  , DrawArena (..)+  , RecordedOp (..)+  , vertexSize+  , indexSize+  , backdropDimTextureId+  , glyphAtlasTextureId+  , glyphAtlasPages+  , glyphPageTextureId+  , textureGlyphPage+  )+where++import Data.Int (Int32)+import Data.IORef (IORef)+import Data.Primitive.ByteArray (ByteArray, MutableByteArray, emptyByteArray)+import Data.Primitive.PrimArray (MutablePrimArray, PrimArray, emptyPrimArray, imapPrimArray, indexPrimArray, primArrayFromListN)+import qualified Data.Text as T+import Data.Primitive.SmallArray (SmallArray, smallArrayFromList)+import Data.Word (Word32, Word64, Word8)+import Data.Vector.Generic qualified as G+import Data.Vector.Generic.Mutable qualified as GM+import Data.Vector.Unboxed qualified as U+import Foreign.ForeignPtr (ForeignPtr)+import GHC.Exts (RealWorld)+import NanoUI.Internal.Shader (ShaderProgram)+import NanoUI.Internal.Style (FontStyle (..), FontVariant (..), FontWeight (..), TextDecoration (..))+import NanoUI.Internal.Types (Color (..), Rect (..), V2 (..))++-- | Painting order from background through content and overlays to chrome.+data Layer = LayerBackground | LayerContent | LayerOverlay | LayerChrome+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | Vector drawing operations in logical pixels. Builders receive a solved+-- window-space rectangle and should place operations within it. Circles use+-- centre/radius; strokes use endpoints and width. Image UVs are normalised.+--+-- Build ops with the canvas ("NanoUI.Widgets.Custom"), which fills and+-- strokes paths, clips, and draws through transforms. Constructors after+-- 'DrawTextStyled' are the canvas's building blocks and may change.+data DrawOp+  = FillRect {-# UNPACK #-} !Rect {-# UNPACK #-} !Color+  -- ^ Solid rectangle.+  | FillRoundedRect {-# UNPACK #-} !Rect {-# UNPACK #-} !Float {-# UNPACK #-} !Color+  -- ^ Rectangle, corner radius, and fill colour.+  | FillTriangle+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Color+  -- ^ Three x/y pairs followed by the fill colour. The edges are+  -- anti-aliased, so a shape tessellated into triangles shows faint seams+  -- along the shared edges; fill a path on a canvas instead.+  | FillCircle+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Color+  -- ^ Centre x/y, radius, and fill colour.+  | Stroke+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Color+  -- ^ Endpoint x0/y0/x1/y1, width, and colour. Not anti-aliased; see+  -- 'StrokeLineAA'.+  | StrokeRoundedRect {-# UNPACK #-} !Rect {-# UNPACK #-} !Float {-# UNPACK #-} !Float {-# UNPACK #-} !Color+  -- ^ Rectangle, corner radius, border width, and colour. The border lies+  -- inside the rectangle.+  | StrokeCircle+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Color+  -- ^ Centre x/y, radius, border width, and colour. The border lies inside+  -- the circle.+  | StrokeLineAA+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Color+  -- ^ Anti-aliased line: endpoint x0/y0/x1/y1, width, and colour.+  | FillQuadGradient {-# UNPACK #-} !Rect {-# UNPACK #-} !Color {-# UNPACK #-} !Color {-# UNPACK #-} !Color {-# UNPACK #-} !Color+  -- ^ Rectangle with colours at top-left, top-right, bottom-right, bottom-left.+  | DrawImage+      {-# UNPACK #-} !Rect+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Int+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Color+  -- ^ Destination rectangle, rotation about its centre in radians+  -- (clockwise on screen), texture id, u0/v0/u1/v1, and tint colour. In a+  -- drawing the texture id may be a registered 'NanoUI.ImageId', with UVs+  -- from 0 to 1. An unrotated image snaps to the pixel grid; a rotated one+  -- does not. Canvas code uses 'NanoUI.Widgets.Custom.drawImageWith'.+  | DrawText+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      !T.Text+      {-# UNPACK #-} !Color+  -- ^ Pen at (x, y) is the alignment point. ax 0..1 is left..right. ay 0..1 is+  -- bottom..top. ay < 0 means baseline (x is left, y is the baseline). Glyph size+  -- is the host font (`drawTextBox`).+  | DrawTextStyled+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      !TextFont+      !T.Text+      {-# UNPACK #-} !Color+  -- ^ Text in a font of its own, its line box's top left corner at (x, y).+  | FillPolygon !(PrimArray Float) !(PrimArray Int) !(PrimArray Int) !Shade+  -- ^ A polygon with holes, anti-aliased along its rings (outline and+  -- holes), not along the edges between its triangles. Fields:+  -- points as x/y pairs, ring after ring, then any interior points the+  -- triangles need; each ring's start offset plus the last ring's end;+  -- index triples into the points; and the shade. The first ring is the+  -- outline; the rest are holes, wound the opposite way.+  | StrokePolyline+      !(PrimArray Float)+      {-# UNPACK #-} !Float+      !Bool+      !LineCap+      !LineJoin+      {-# UNPACK #-} !Float+      !Shade+  -- ^ A polyline anti-aliased along its sides. Fields: points as x/y+  -- pairs; width; whether it closes back to the first point (not+  -- repeated); cap for open ends; corner join; miter limit as a multiple of+  -- the width, beyond which a miter becomes a bevel; and the shade.+  | DrawTextAligned+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      !TextFont+      !T.Text+      {-# UNPACK #-} !Color+  -- ^ Text in its own font, anchored at (x, y) by ax/ay as in 'DrawText',+  -- with the font size scaled. Fields: x, y, ax, ay, scale, font, text,+  -- colour.+  | PushClip {-# UNPACK #-} !Rect+  -- ^ Clip ops up to the matching 'PopClip' to this rectangle, intersected+  -- with the current clip.+  | PopClip+  -- ^ End the innermost open 'PushClip'.+  deriving (Eq, Show)++-- | An unrotated 'DrawImage': destination rectangle, texture id,+-- u0/v0/u1/v1, and tint colour. As a pattern it matches only angle 0.+pattern DrawImageRect :: Rect -> Int -> Float -> Float -> Float -> Float -> Color -> DrawOp+pattern DrawImageRect r tex u0 v0 u1 v1 c = DrawImage r 0 tex u0 v0 u1 v1 c++-- | How a stroke ends an open subpath.+data LineCap+  = ButtCap+  -- ^ Flat at the end point.+  | SquareCap+  -- ^ Flat, half the width past the end point.+  | RoundCap+  -- ^ A half disc past the end point.+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | How a stroke turns a corner.+data LineJoin+  = MiterJoin+  -- ^ Sides extend until they meet in a point, or bevel if that point is+  -- beyond the miter limit.+  | RoundJoin+  -- ^ A circular arc around the corner.+  | BevelJoin+  -- ^ Corner cut straight across.+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | Colour of a 'FillPolygon' or 'StrokePolyline': one for the whole shape,+-- or one per point, blended across the triangles. A stroke uses each+-- point's colour across the line's width there.+data Shade+  = Flat !Color+  | Shaded !(PrimArray Word32)+  deriving (Eq, Show)++-- | The font a 'DrawTextStyled' draws with: the same choices a label's+-- layout makes.+data TextFont = TextFont+  { textFontSize :: {-# UNPACK #-} !Float+  -- ^ Requested logical font size, @0@ for the backend default.+  , textFontVariant :: !FontVariant+  , textFontWeight :: !FontWeight+  , textFontStyle :: !FontStyle+  , textFontDecoration :: !TextDecoration+  , textFontTabular :: !Bool+  -- ^ Uniform-width ASCII digits ('NanoUI.fontTabular').+  }+  deriving (Eq, Show)++-- | Regular text using the backend's default size, weight, and upright style.+defaultTextFont :: TextFont+defaultTextFont = TextFont 0 FontRegular WeightNormal FontStyleNormal DecorationNone False++-- | A quad as a 'FillPolygon': its four corners' x/y pairs in order round+-- it, cut into two triangles from the first.+quadPolygon :: PrimArray Float -> Shade -> DrawOp+quadPolygon corners = FillPolygon corners (primArrayFromListN 2 [0, 4]) (primArrayFromListN 6 [0, 1, 2, 0, 2, 3])++-- | Translate every vertex in a 'DrawOp'. Paint reuses ops when only (x, y) moved.+shiftDrawOp :: Float -> Float -> DrawOp -> DrawOp+shiftDrawOp dx dy op =+  case op of+    FillRect (Rect x y w h) c -> FillRect (Rect (x + dx) (y + dy) w h) c+    FillRoundedRect (Rect x y w h) r c -> FillRoundedRect (Rect (x + dx) (y + dy) w h) r c+    FillTriangle x0 y0 x1 y1 x2 y2 c ->+      FillTriangle (x0 + dx) (y0 + dy) (x1 + dx) (y1 + dy) (x2 + dx) (y2 + dy) c+    FillCircle cx cy r c -> FillCircle (cx + dx) (cy + dy) r c+    Stroke x0 y0 x1 y1 t c -> Stroke (x0 + dx) (y0 + dy) (x1 + dx) (y1 + dy) t c+    StrokeRoundedRect (Rect x y w h) r bw c -> StrokeRoundedRect (Rect (x + dx) (y + dy) w h) r bw c+    StrokeCircle cx cy r bw c -> StrokeCircle (cx + dx) (cy + dy) r bw c+    StrokeLineAA x0 y0 x1 y1 bw c -> StrokeLineAA (x0 + dx) (y0 + dy) (x1 + dx) (y1 + dy) bw c+    FillPolygon pts rings tris c -> FillPolygon (shiftPoints dx dy pts) rings tris c+    StrokePolyline pts w closed cap join limit c -> StrokePolyline (shiftPoints dx dy pts) w closed cap join limit c+    FillQuadGradient (Rect x y w h) c0 c1 c2 c3 -> FillQuadGradient (Rect (x + dx) (y + dy) w h) c0 c1 c2 c3+    DrawImage (Rect x y w h) angle tex u0 v0 u1 v1 c -> DrawImage (Rect (x + dx) (y + dy) w h) angle tex u0 v0 u1 v1 c+    DrawText x y ax ay t c -> DrawText (x + dx) (y + dy) ax ay t c+    DrawTextStyled x y font t c -> DrawTextStyled (x + dx) (y + dy) font t c+    DrawTextAligned x y ax ay k font t c -> DrawTextAligned (x + dx) (y + dy) ax ay k font t c+    PushClip (Rect x y w h) -> PushClip (Rect (x + dx) (y + dy) w h)+    PopClip -> PopClip++-- | Translate x/y pairs.+shiftPoints :: Float -> Float -> PrimArray Float -> PrimArray Float+shiftPoints dx dy = imapPrimArray (\i v -> v + (if even i then dx else dy))++-- | Pure painter from solved logical window bounds to draw operations.+type DrawingBuild = Rect -> SmallArray DrawOp++-- | Indexed draw batch with logical clip, texture id, layer, and optional+-- shader call index. Index offset and count are elements, not byte offsets;+-- multiply by 'indexSize' for FFI use.+data DrawCmd = DrawCmd+  { cmdClipX :: {-# UNPACK #-} !Float+  , cmdClipY :: {-# UNPACK #-} !Float+  , cmdClipW :: {-# UNPACK #-} !Float+  , cmdClipH :: {-# UNPACK #-} !Float+  , cmdTextureId :: {-# UNPACK #-} !Int+  , cmdIndexOffset :: {-# UNPACK #-} !Word32+  , cmdIndexCount :: {-# UNPACK #-} !Word32+  , cmdLayer :: !Layer+  , cmdShader :: {-# UNPACK #-} !Int32+  -- ^ @0@ for the standard UI pipeline; 1-based index into 'drawShaderCalls'.+  }+  deriving (Eq, Show)++-- Vector's tuple representation stores each field in a primitive array. The+-- isomorphism is inlined at command reads and writes.+type DrawCmdRep = ((Float, Float, Float, Float), Int, Word32, Word32, Word8, Int32)++instance U.IsoUnbox DrawCmd DrawCmdRep where+  {-# INLINE toURepr #-}+  toURepr (DrawCmd x y w h tex off count layer sh) =+    ((x, y, w, h), tex, off, count, fromIntegral (fromEnum layer), sh)+  {-# INLINE fromURepr #-}+  fromURepr ((x, y, w, h), tex, off, count, layer, sh) =+    DrawCmd x y w h tex off count (toEnum (fromIntegral layer)) sh++newtype instance U.MVector s DrawCmd = MVDrawCmd (U.MVector s (U.As DrawCmd DrawCmdRep))++newtype instance U.Vector DrawCmd = VDrawCmd (U.Vector (U.As DrawCmd DrawCmdRep))++deriving via (U.As DrawCmd DrawCmdRep) instance GM.MVector U.MVector DrawCmd++deriving via (U.As DrawCmd DrawCmdRep) instance G.Vector U.Vector DrawCmd++instance U.Unbox DrawCmd++-- | One fragment shader invocation referenced by 'cmdShader' (1-based) or an+-- 'EffectSpan'.+data ShaderCall = ShaderCall+  { scHash :: {-# UNPACK #-} !Word64+  -- ^ Content hash of 'scProgram', used by backends to cache compiled programs.+  , scProgram :: !ShaderProgram+  -- ^ Lazy target shader payloads (GLSL 150, GLSL ES 300, SPIR-V, MSL).+  , scUniformOffset :: {-# UNPACK #-} !Int+  -- ^ Byte offset into 'drawUniformBytes' (16-byte aligned).+  , scUniformLength :: {-# UNPACK #-} !Int+  -- ^ Byte length in 'drawUniformBytes': @48 + userUniformBytes@.+  }++-- | Brackets a contiguous slice of 'drawCommands' rendered into a pooled+-- offscreen target and composited back through one or more shader passes.+data EffectSpan = EffectSpan+  { esId :: {-# UNPACK #-} !Int+  -- ^ 1-based identifier of this effect span within the frame.+  , esParent :: {-# UNPACK #-} !Int+  -- ^ Enclosing 'esId', or @0@ for the root target.+  , esLayer :: !Layer+  -- ^ Layer whose commands this span brackets.+  , esCmdStart :: {-# UNPACK #-} !Int+  -- ^ Inclusive start index into 'drawCommands'.+  , esCmdEnd :: {-# UNPACK #-} !Int+  -- ^ Exclusive end index into 'drawCommands'.+  , esBounds :: !Rect+  -- ^ Logical node rectangle before margin expansion.+  , esClip :: !Rect+  -- ^ Enclosing logical clip rectangle active when the span opened.+  , esMargin :: !V2+  -- ^ Maximum sample offset in logical pixels (X and Y).+  , esPasses :: !(SmallArray ShaderCall)+  -- ^ Shader passes applied in order to the offscreen texture.+  }++-- | Shared empty 'SmallArray' for frames without shader calls.+emptyShaderCalls :: SmallArray ShaderCall+emptyShaderCalls = smallArrayFromList []++-- | Shared empty 'SmallArray' for frames without offscreen effect spans.+emptyEffectSpans :: SmallArray EffectSpan+emptyEffectSpans = smallArrayFromList []++-- | Shared empty 'ByteArray' for frames without shader uniforms.+emptyUniformBytes :: ByteArray+emptyUniformBytes = emptyByteArray++-- | One frame's geometry and batches. Vertex/index pointers refer to reusable+-- arena storage: render or copy them before running another frame on the+-- context. Counts describe the used prefix, not buffer capacity.+data DrawData = DrawData+  { drawVertices :: ForeignPtr Word8+  , drawVertexCount :: {-# UNPACK #-} !Int+  , drawIndices :: ForeignPtr Word8+  , drawIndexCount :: {-# UNPACK #-} !Int+  , drawCommands :: !(U.Vector DrawCmd)+  , drawLayerOffsets :: !(PrimArray Int)+  -- ^ Cumulative command offsets: layer @i@ occupies @[offsets[i], offsets[i+1])@.+  -- Includes a final sentinel equal to 'drawCmdCount'; empty layers repeat offsets.+  , drawClear :: !Color+  -- ^ The colour a full frame clears the target to before 'drawCommands':+  -- the page surface ('NanoUI.pageBackground') laid over the window colour+  -- ('NanoUI.themeWindow'). A clip frame's commands paint it as their own+  -- backdrop.+  , drawShaderCalls :: !(SmallArray ShaderCall)+  -- ^ Shader invocations referenced by 1-based 'cmdShader' indices; empty+  -- when the frame draws no shaders.+  , drawUniformBytes :: !ByteArray+  -- ^ Flat std140 uniform byte arena sliced by 'ShaderCall'; empty when the+  -- frame draws no shaders.+  , drawEffectSpans :: !(SmallArray EffectSpan)+  -- ^ Subtree effect spans in open order; empty when the frame uses no+  -- offscreen effects.+  }++-- | Number of batches across all layers.+{-# INLINE drawCmdCount #-}+drawCmdCount :: DrawData -> Int+drawCmdCount dd = U.length (drawCommands dd)++-- | Whether there are no draw batches.+{-# INLINE drawCmdNull #-}+drawCmdNull :: DrawData -> Bool+drawCmdNull dd = drawCmdCount dd == 0++-- | Visit one layer's commands in recorded order without constructing a list.+{-# INLINE forDrawCmdsInLayer_ #-}+forDrawCmdsInLayer_ :: Layer -> DrawData -> (DrawCmd -> IO ()) -> IO ()+forDrawCmdsInLayer_ ly dd f =+  let+    offsets = drawLayerOffsets dd+    off = indexPrimArray offsets (fromEnum ly)+    end = indexPrimArray offsets (fromEnum ly + 1)+    cmds = drawCommands dd+    go !i+      | i >= end = pure ()+      | otherwise = f (U.unsafeIndex cmds i) >> go (i + 1)+   in+    go off++-- | Copy command values into a list in recorded order.+drawCmdElems :: DrawData -> [DrawCmd]+drawCmdElems = U.toList . drawCommands++-- | Per-paint cold state reset as a single CAF on 'resetDrawArena'.+data DrawFrameExtra = DrawFrameExtra+  { dfeClipPieces :: !(PrimArray Float)+  -- ^ Damage pieces as @x0, y0, x1, y1@ runs; empty when the clip is the one piece.+  , dfeTextSpans :: !([(Rect, T.Text, Color, Color, Rect)], [(Rect, T.Text, Color, Color, Rect)])+  -- ^ Drawing text spans recorded under external text (base, overlay) in reverse order.+  , dfeRecordedOps :: ![RecordedOp]+  -- ^ Solid shapes recorded in reverse order when 'daRecordOps' is enabled.+  , dfeShaderCalls :: ![ShaderCall]+  -- ^ Shader dispatch metadata accumulated in reverse order during paint.+  , dfeEffectSpans :: ![EffectSpan]+  -- ^ Tier 2 effect spans accumulated in reverse order during paint.+  , dfeEffectStack :: ![Int]+  -- ^ Stack of currently open Tier 2 effect span IDs.+  }++-- | Initial 'DrawFrameExtra' shared by 'newDrawArena' and 'resetDrawArena'.+emptyDrawExtra :: DrawFrameExtra+emptyDrawExtra = DrawFrameExtra emptyPrimArray ([], []) [] [] [] []++data DrawArena = DrawArena+  { daVertexFPtr :: !(IORef (ForeignPtr Word8))+  , daVertexCap :: !(IORef Int)+  , daIndexFPtr :: !(IORef (ForeignPtr Word8))+  , daIndexCap :: !(IORef Int)+  , daCounts :: !(MutablePrimArray RealWorld Int)+  -- ^ Unboxed integer state: vertex/index/cmd counts, pending command start,+  -- current texture, current shader, no-merge floor, shader call count,+  -- uniform byte length, and next effect span ID.+  , daCmdStore :: !(IORef (U.MVector RealWorld DrawCmd))+  , daCurrentLayer :: !(IORef Layer)+  , daCurrentClip :: !(MutablePrimArray RealWorld Float)+  -- ^ Four floats: x, y, w, h of the active clip rect.+  , daSnapScale :: !(IORef Float)+  , daSquareGeometry :: !(IORef Bool)+  , daExternalText :: !(IORef Bool)+  , daClear :: !(IORef Color)+  -- ^ Background colour the frame clears with.+  , daRecordOps :: !(IORef Bool)+  -- ^ When 'True', emitters also append the solid shapes they draw to 'dfeRecordedOps'.+  , daRecordOpacity :: !(IORef Float)+  -- ^ Active group opacity recorded into 'RecordedOp' (1.0 outside opacity effects).+  , daUniformBuf :: !(IORef (MutableByteArray RealWorld))+  -- ^ Flat growable byte buffer holding packed user uniform payloads for shader calls.+  , daPixelScale :: !(IORef Float)+  -- ^ Physical pixels per logical pixel, written into shader system uniforms.+  , daExtra :: !(IORef DrawFrameExtra)+  -- ^ Per-paint cold state reset on 'resetDrawArena'.+  }++-- | A solid shape as an emitter drew it: its layer, the clip it drew under,+-- its active group opacity (@1.0@ outside opacity effects), and the shape as+-- the op that draws it. Exporters read these in place of the tessellated+-- vertices ('NanoUI.Internal.Draw.Arena.setDrawRecordOps').+data RecordedOp = RecordedOp !Layer !Rect !Float !DrawOp++-- | Packed vertex stride in bytes: 32. A vertex is eight 32-bit floats: x+-- and y in logical pixels, red, green, blue and alpha from 0 to 1 with+-- straight (not premultiplied) alpha, then the texture's u and v.+vertexSize :: Int+vertexSize = 32++-- | Index stride in bytes: 4, for a 32-bit unsigned index.+indexSize :: Int+indexSize = 4++-- | Reserved texture id. nano-ui emits no command with it: a modal's+-- backdrop dim is a plain translucent fill.+backdropDimTextureId :: Int+backdropDimTextureId = 0x7ffffffe++-- | Reserved texture id for page 0 of the host's glyph atlas+-- ('glyphPageTextureId'). The renderer binds its atlas texture when it sees+-- this id. Glyphs are cached as white-on-alpha so vertex color tints them at+-- draw time. Solid shapes (rects, rounded shapes, strokes, polygons) draw+-- with this id too and sample u = v = 1.5/1024, so a host that samples the+-- atlas for them keeps that point opaque white.+glyphAtlasTextureId :: Int+glyphAtlasTextureId = 0x7ffffffd++-- | Pages a glyph atlas can have. A glyph's page is the whole part of its+-- u coordinates ('NanoUI.Backend.ShapedGlyphs'), so page 0's UVs are+-- the plain ones.+glyphAtlasPages :: Int+glyphAtlasPages = 4++-- | The reserved texture id of glyph atlas page @page@: 'glyphAtlasTextureId'+-- for page 0, and the ids below it for the others.+{-# INLINE glyphPageTextureId #-}+glyphPageTextureId :: Int -> Int+glyphPageTextureId page = glyphAtlasTextureId - page++-- | The glyph atlas page a texture id names, or -1 for any other texture.+{-# INLINE textureGlyphPage #-}+textureGlyphPage :: Int -> Int+textureGlyphPage tex =+  let page = glyphAtlasTextureId - tex+   in if page >= 0 && page < glyphAtlasPages then page else -1
+ lib/NanoUI/Internal/EffectDriver.hs view
@@ -0,0 +1,258 @@+-- | Shared Tier 2 'EffectSpan' execution engine and uniform-header patcher for+-- GPU backends (SDL3, WebGL2, OpenGL 3.2).+--+-- Handles recursive span tree walking, damage culling, pixel-grid bounding,+-- UV calculation (both top-down and bottom-up FBO conventions), multi-pass+-- ping-pong target pooling, graceful fallback when a pass is unsupported or+-- target acquisition fails, and std140 system-uniform header patching.+module NanoUI.Internal.EffectDriver+  ( EffectPassDraw (..)+  , EffectDriver (..)+  , spanEffectiveClip+  , shiftClip+  , execEffectSpans+  , withEffectUniforms+  ) where++import Control.Exception (finally)+import Control.Monad (when)+import Data.Foldable (for_)+import Data.List (sortOn)+import Data.Maybe (isJust)+import Data.Primitive.ByteArray (ByteArray, copyByteArrayToAddr, sizeofByteArray)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray)+import Data.Word (Word8)+import Foreign.C.Types (CFloat (..))+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Utils (fillBytes)+import Foreign.Ptr (Ptr)+import Foreign.Storable (pokeByteOff)+import NanoUI.Internal.Draw.Types (EffectSpan (..), ShaderCall (..))+import NanoUI.Internal.Types (Rect (..), V2 (..), rectIntersect, shiftClip, spanEffectiveClip)+import NanoUI.Internal.Uniforms (sysUniformBytes)++-- | Geometry, UVs, and clipping state for compositing one Tier 2 shader pass.+data EffectPassDraw = EffectPassDraw+  { epdSrcSlot :: !Int+  , epdDstX :: !Float+  , epdDstY :: !Float+  , epdDstW :: !Float+  , epdDstH :: !Float+  , epdU0 :: !Float+  , epdV0 :: !Float+  , epdU1 :: !Float+  , epdV1 :: !Float+  , epdNodeU0 :: !Float+  , epdNodeV0 :: !Float+  , epdNodeUSpan :: !Float+  , epdNodeVSpan :: !Float+  , epdSrcCapW :: !Float+  , epdSrcCapH :: !Float+  , epdIntermediate :: !Bool+    -- ^ 'True' when writing to a pooled ping-pong target (replace blend);+    -- 'False' on the final composite into the parent target (alpha blend).+  , epdClip :: !(Maybe Rect)+    -- ^ Effective scissor rectangle shifted to the parent target's local+    -- logical coordinates; 'Nothing' means unclipped.+  }++-- | Backend callbacks plugging a GPU renderer into 'execEffectSpans'.+data EffectDriver passHandle = EffectDriver+  { edScale :: !Float+  , edFlipY :: !Bool+    -- ^ 'True' when offscreen FBO textures have @V=1@ at the top (OpenGL /+    -- WebGL2); 'False' when @V=0@ is at the top (SDL3).+  , edPreparePasses :: SmallArray ShaderCall -> IO (Maybe (SmallArray passHandle))+    -- ^ Validate or compile all passes for a span. Returning 'Nothing' falls+    -- back to rendering child commands directly into the parent target.+  , edAcquireTarget :: Int -> Int -> IO (Int, Int, Int)+    -- ^ Acquire a pooled offscreen target at least @(pw, ph)@ pixels; returns+    -- @(slot, capW, capH)@ or @(-1, 0, 0)@ on allocation failure.+  , edReleaseTarget :: Int -> IO ()+  , edBindTarget :: Int -> Bool -> Float -> Float -> IO Bool+    -- ^ Bind target @slot@ (@-1@ = root target) with @clear@ flag and logical+    -- origin @(ox, oy)@. Returns 'False' if binding failed.+  , edFlush :: IO ()+    -- ^ Flush any pending batched geometry before switching targets.+  , edEmitPlain :: Int -> Int -> Int -> Float -> Float -> Maybe Rect -> Int -> Int -> IO ()+    -- ^ Emit plain draw commands in @[from, to)@ onto the bound target+    -- @(slot, capW, capH, ox, oy, mDamage)@.+  , edAfterSpanContent :: Int -> IO ()+    -- ^ Hook invoked right after a span's child commands finish (used by+    -- external-text backends such as RGFW to emit text belonging to the span).+  , edCompositePass :: passHandle -> ShaderCall -> EffectPassDraw -> Int -> Int -> IO ()+    -- ^ Composite one pass onto the currently bound target of size @(dstW, dstH)@.+  }++-- | Recursively execute draw commands in @[rangeStart, rangeEnd)@ with Tier 2+-- 'EffectSpan' capture, multi-pass ping-pong shader execution, and compositing.+{-# NOINLINE execEffectSpans #-}+execEffectSpans ::+  EffectDriver passHandle ->+  SmallArray EffectSpan ->+  Int ->+  Int ->+  (Int, Int) ->+  Float ->+  Float ->+  Maybe Rect ->+  Int ->+  Int ->+  IO ()+execEffectSpans drv spans parentId parentSlot parentSize@(parentW, parentH) parentOx parentOy parentDmg rangeStart rangeEnd =+  go rangeStart directChildren+  where+    !scale = edScale drv+    !flipY = edFlipY drv++    directChildren =+      sortOn (\sp -> (esCmdStart sp, esId sp))+        [ sp+        | i <- [0 .. sizeofSmallArray spans - 1]+        , let sp = indexSmallArray spans i+        , esParent sp == parentId+        , esCmdStart sp >= rangeStart+        , esCmdEnd sp <= rangeEnd+        ]++    emitPlain from to =+      when (to > from) $+        edEmitPlain drv parentSlot parentW parentH parentOx parentOy parentDmg from to++    go !cur [] = emitPlain cur rangeEnd+    go !cur (sp : rest) = do+      let !s = max cur (esCmdStart sp)+          !e = min rangeEnd (esCmdEnd sp)+      when (s > cur) (emitPlain cur s)+      when (e > s) (runSpan sp s e)+      go (max cur e) rest++    fallbackSpan sp s e = do+      execEffectSpans drv spans (esId sp) parentSlot parentSize parentOx parentOy parentDmg s e+      edAfterSpanContent drv (esId sp)++    runSpan sp s e = do+      let Rect bx by bw bh = esBounds sp+          V2 mx my = esMargin sp+          expanded@(Rect ex ey ew eh) = Rect (bx - mx) (by - my) (bw + 2 * mx) (bh + 2 * my)+          passes = esPasses sp+          !nPasses = sizeofSmallArray passes+          inDamage = maybe True (isJust . rectIntersect expanded) parentDmg+      when inDamage $ do+        mHandles <-+          if nPasses <= 0 || ew <= 0 || eh <= 0+            then pure Nothing+            else edPreparePasses drv passes+        case mHandles of+          Nothing -> fallbackSpan sp s e+          Just handles -> do+            let !px0 = floor (ex * scale) :: Int+                !py0 = floor (ey * scale) :: Int+                !px1 = ceiling ((ex + ew) * scale) :: Int+                !py1 = ceiling ((ey + eh) * scale) :: Int+                !pw = max 1 (px1 - px0)+                !ph = max 1 (py1 - py0)+                !ox = fromIntegral px0 / scale+                !oy = fromIntegral py0 / scale+            (slot0, cap0W, cap0H) <- edAcquireTarget drv pw ph+            if slot0 < 0+              then fallbackSpan sp s e+              else do+                let restoreParent = do+                      edFlush drv+                      _ <- edBindTarget drv parentSlot False parentOx parentOy+                      pure ()+                    runOffscreen = do+                      edFlush drv+                      okBind <- edBindTarget drv slot0 True ox oy+                      when okBind $ do+                        execEffectSpans drv spans (esId sp) slot0 (cap0W, cap0H) ox oy Nothing s e+                        edAfterSpanContent drv (esId sp)+                        edFlush drv+                        let !nodePx = bx * scale - fromIntegral px0+                            !nodePy = by * scale - fromIntegral py0+                            !nodePw = max 1.0e-4 (bw * scale)+                            !nodePh = max 1.0e-4 (bh * scale)+                            !destPx = fromIntegral px0 - parentOx * scale+                            !destPy = fromIntegral py0 - parentOy * scale+                            mkPassDraw !srcSlot !srcCapW !srcCapH !dx !dy !inter mClip =+                              let !fcw = fromIntegral srcCapW+                                  !fch = fromIntegral srcCapH+                                  !u1 = fromIntegral pw / fcw+                                  !v0 = if flipY then 1.0 else 0.0+                                  !v1 = if flipY then 1.0 - fromIntegral ph / fch else fromIntegral ph / fch+                                  !nodeU0 = nodePx / fcw+                                  !nodeV0 = if flipY then 1.0 - nodePy / fch else nodePy / fch+                                  !nodeUSpan = nodePw / fcw+                                  !nodeVSpan = if flipY then negate (nodePh / fch) else nodePh / fch+                               in EffectPassDraw+                                    { epdSrcSlot = srcSlot+                                    , epdDstX = dx+                                    , epdDstY = dy+                                    , epdDstW = fromIntegral pw+                                    , epdDstH = fromIntegral ph+                                    , epdU0 = 0+                                    , epdV0 = v0+                                    , epdU1 = u1+                                    , epdV1 = v1+                                    , epdNodeU0 = nodeU0+                                    , epdNodeV0 = nodeV0+                                    , epdNodeUSpan = nodeUSpan+                                    , epdNodeVSpan = nodeVSpan+                                    , epdSrcCapW = fcw+                                    , epdSrcCapH = fch+                                    , epdIntermediate = inter+                                    , epdClip = mClip+                                    }+                            runPasses !srcSlot !srcCapW !srcCapH !dstSlot !dstCapW !dstCapH !passIdx+                              | passIdx >= nPasses = pure ()+                              | otherwise = do+                                  let sc = indexSmallArray passes passIdx+                                      handle = indexSmallArray handles passIdx+                                  if passIdx < nPasses - 1 && dstSlot >= 0+                                    then do+                                      okDst <- edBindTarget drv dstSlot True 0 0+                                      when okDst $ do+                                        let pd = mkPassDraw srcSlot srcCapW srcCapH 0 0 True Nothing+                                        edCompositePass drv handle sc pd dstCapW dstCapH+                                        runPasses dstSlot dstCapW dstCapH srcSlot srcCapW srcCapH (passIdx + 1)+                                    else do+                                      okPar <- edBindTarget drv parentSlot False parentOx parentOy+                                      when okPar $+                                        for_ (spanEffectiveClip parentDmg (esClip sp)) $ \mClip -> do+                                          let pd = mkPassDraw srcSlot srcCapW srcCapH destPx destPy False (shiftClip parentOx parentOy mClip)+                                          edCompositePass drv handle sc pd parentW parentH+                        if nPasses > 1+                          then do+                            (slot1, cap1W, cap1H) <- edAcquireTarget drv pw ph+                            runPasses slot0 cap0W cap0H slot1 cap1W cap1H 0+                              `finally` when (slot1 >= 0) (edReleaseTarget drv slot1)+                          else+                            runPasses slot0 cap0W cap0H (-1) 0 0 0+                runOffscreen+                  `finally` (restoreParent >> edReleaseTarget drv slot0)++-- | Copy the packed std140 uniform block of a 'ShaderCall' into a temporary buffer,+-- patch the per-pass @uUvRect@ (bytes 16..31) and @uMeta.zw@ target capacity+-- (bytes 40..47) from 'EffectPassDraw', and pass @(ptr, byteLen)@ to @k@.+withEffectUniforms ::+  ShaderCall ->+  ByteArray ->+  EffectPassDraw ->+  (Ptr Word8 -> Int -> IO a) ->+  IO a+withEffectUniforms sc uniformBytes pd k = do+  let !uOff = scUniformOffset sc+      !avail = max 0 (sizeofByteArray uniformBytes - uOff)+      !uLen = max sysUniformBytes (min (scUniformLength sc) avail)+      !copyLen = min uLen avail+  allocaBytes uLen $ \uPtr -> do+    when (copyLen < uLen) $ fillBytes uPtr 0 uLen+    when (copyLen > 0) $ copyByteArrayToAddr uPtr uniformBytes uOff copyLen+    pokeByteOff uPtr 16 (CFloat (epdNodeU0 pd))+    pokeByteOff uPtr 20 (CFloat (epdNodeV0 pd))+    pokeByteOff uPtr 24 (CFloat (epdNodeUSpan pd))+    pokeByteOff uPtr 28 (CFloat (epdNodeVSpan pd))+    pokeByteOff uPtr 40 (CFloat (epdSrcCapW pd))+    pokeByteOff uPtr 44 (CFloat (epdSrcCapH pd))+    k uPtr uLen
+ lib/NanoUI/Internal/Equality.hs view
@@ -0,0 +1,35 @@+-- | Conservative physical-equality shortcuts for immutable values, and the+-- equalities inputs compare their values with.+module NanoUI.Internal.Equality (ptrEq, eqByPtr, sameFloat, sameDouble, sameEnum) where++import GHC.Exts (isTrue#, reallyUnsafePtrEquality#)+import GHC.Float (castDoubleToWord64, castFloatToWord32)++-- | True implies the closures are identical; False requires a real comparison.+-- Forces neither argument. Callers comparing evaluated values must force them+-- before calling, rather than comparing selector thunks.+{-# INLINE ptrEq #-}+ptrEq :: a -> b -> Bool+ptrEq a b = isTrue# (reallyUnsafePtrEquality# a b)++-- | Structural equality with a physical-equality fast path.+{-# INLINE eqByPtr #-}+eqByPtr :: Eq a => a -> a -> Bool+eqByPtr !a !b = ptrEq a b || a == b++-- | '==', except that a NaN equals the same NaN, so an input holding one+-- does not count as changed on every frame.+{-# INLINE sameFloat #-}+sameFloat :: Float -> Float -> Bool+sameFloat a b = a == b || castFloatToWord32 a == castFloatToWord32 b++-- | 'sameFloat' for 'Double': equal values, or identical bits (so a NaN+-- equals itself).+{-# INLINE sameDouble #-}+sameDouble :: Double -> Double -> Bool+sameDouble a b = a == b || castDoubleToWord64 a == castDoubleToWord64 b++-- | Equality by index, for enumerations without an 'Eq' instance.+{-# INLINE sameEnum #-}+sameEnum :: Enum a => a -> a -> Bool+sameEnum a b = fromEnum a == fromEnum b
+ lib/NanoUI/Internal/Font.hs view
@@ -0,0 +1,328 @@+{-# LANGUAGE StrictData #-}++-- | Font measurement, wrapping, truncation, and shared widget metrics.+module NanoUI.Internal.Font+  ( module NanoUI.Internal.Font.Types+  , module NanoUI.Internal.Metrics+  , WrapResult (..)+  , wrapMeasure+  , wrapTextIO+  , wrapTextLinesIO+  , truncateTextIO+  , truncateTextWithIO+  , truncateTextPure+  ) where++import Control.Monad (unless)+import Data.Functor.Identity (Identity (..))+import Data.Primitive.PrimVar (newPrimVar, readPrimVar, writePrimVar)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Unsafe (Iter (..), iter)+import Data.Text.Foreign (lengthWord8)+import NanoUI.Internal.Font.Types+import NanoUI.Internal.Metrics+import NanoUI.Internal.Style (TextEllipsis (..))+import NanoUI.Internal.TextCluster (clusterBounds, clusterLength)+import NanoUI.Internal.Types (clamp)++-- | The size of text wrapped to @maxW@ into the lines of @wrap@.+wrapMeasure :: FontMetrics -> Float -> WrapResult -> (Float, Float)+wrapMeasure fm maxW wrap =+  let lineH = fmLineHeight fm+   in case wrLines wrap of+        [] -> (0, lineH)+        textLines -> (min maxW (wrWidest wrap), lineH * fromIntegral (length textLines))++-- | Text wrapped to a width, and the widths it wraps the same at.+data WrapResult = WrapResult+  { wrLines :: [Text]+  -- ^ The lines, as 'wrapTextLinesIO' gives them.+  , wrWidest :: Float+  -- ^ The widest line, which is wider than the width asked for when a+  -- single character is.+  , wrFitW :: Float+  -- ^ The widest line that fit.+  , wrBreakW :: Float+  -- ^ The narrowest width at which some line would take another word or+  -- character, or a paragraph would fit whole.+  }+  deriving (Eq, Show)++-- | Wrap each paragraph to @maxW@ using the host line measure.+wrapTextLinesIO :: (Text -> IO Float) -> Text -> Float -> IO [Text]+wrapTextLinesIO lineW txt maxW = wrLines <$> wrapTextIO lineW txt maxW++-- | 'wrapTextLinesIO' with the widths its result holds for.+wrapTextIO :: (Text -> IO Float) -> Text -> Float -> IO WrapResult+wrapTextIO lineW txt maxW = do+  widestVar <- newPrimVar (0 :: Float)+  fitVar <- newPrimVar (0 :: Float)+  breakVar <- newPrimVar (1 / 0 :: Float)+  let lineOf !w = do+        curW <- readPrimVar widestVar+        if w > curW then writePrimVar widestVar w else pure ()+        if w <= maxW+          then do+            curF <- readPrimVar fitVar+            if w > curF then writePrimVar fitVar w else pure ()+          else breakAt w+      breakAt !w = do+        curB <- readPrimVar breakVar+        if w < curB then writePrimVar breakVar w else pure ()+      wrapParagraph para+        | T.null para = pure [""]+        | otherwise = do+            w <- lineW para+            let !perLine = charsPerWidth w para maxW+            if w <= maxW+              then [para] <$ lineOf w+              else do+                breakAt w+                if T.any (== ' ') para+                  then wrapWords perLine para []+                  else reverse <$> charLines perLine para []+      wrapWords !perLine = startLine+        where+          startLine rest acc+            | T.null rest = pure (reverse acc)+            | otherwise = do+                let !wEnd = wordEnd rest+                    word = T.take wEnd rest+                width <- lineW word+                if width <= maxW+                  then extend rest wEnd width acc+                  else do+                    breakAt width+                    pieces <- charLines perLine word []+                    case pieces of+                      piece : done -> do+                        let !pLen = T.length piece+                            rest' = T.drop (wEnd - pLen) rest+                        pw <- lineW piece+                        extend rest' pLen pw (done ++ acc)+                      [] -> startLine (T.dropWhile (== ' ') (T.drop wEnd rest)) acc+          extend fromLine !lineLen !lineWidth0 acc = do+            let !guess =+                  if T.compareLength fromLine perLine /= GT+                    then T.length (T.dropWhileEnd (== ' ') fromLine)+                    else max lineLen (prevWordEnd fromLine (perLine + 1))+                -- Carry both the last fitting (end, width) and the first+                -- overflowing width so neither is measured a second time.+                up !end !endW = case nextWordEnd fromLine end of+                  Nothing -> pure (end, endW, 1 / 0)+                  Just end' -> do+                    w' <- lineW (T.take end' fromLine)+                    if w' <= maxW then up end' w' else pure (end, endW, w')+                down !end !overW+                  | end' <= lineLen = pure (lineLen, lineWidth0, overW)+                  | otherwise = do+                      w' <- lineW (T.take end' fromLine)+                      if w' <= maxW then pure (end', w', overW) else down end' w'+                  where+                    !end' = prevWordEnd fromLine end+            (!end, !endW, !overW) <-+              if guess <= lineLen+                then up lineLen lineWidth0+                else do+                  gw <- lineW (T.take guess fromLine)+                  if gw <= maxW+                    then up guess gw+                    else down guess gw+            let line = T.take end fromLine+                rest = T.dropWhile (== ' ') (T.drop end fromLine)+            lineOf endW+            if overW < 1 / 0+              then breakAt overW+              else pure ()+            if T.null rest then pure (reverse (line : acc)) else startLine rest (line : acc)+      charLines !perLine chunk acc+        | T.null chunk = pure acc+        | otherwise = do+            (line, rest) <- takeWidth perLine lineW maxW chunk+            if T.null line+              then pure acc+              else do+                lineW line >>= lineOf+                unless (T.null rest) $+                  lineW (T.take (snd (clusterBounds chunk (T.length line + 1))) chunk) >>= breakAt+                charLines perLine rest (line : acc)+  if maxW <= 0+    then pure (WrapResult [] 0 1 0)+    else do+      textLines <- concat <$> mapM wrapParagraph (T.lines txt)+      WrapResult textLines <$> readPrimVar widestVar <*> readPrimVar fitVar <*> readPrimVar breakVar++wordEnd :: Text -> Int+wordEnd t = goSpaces 0 0+  where+    !lenB = lengthWord8 t+    goSpaces !b !chars+      | b >= lenB = chars+      | otherwise = case iter t b of+          Iter c d+            | c == ' ' -> goSpaces (b + d) (chars + 1)+            | otherwise -> goWord (b + d) (chars + 1)+    goWord !b !chars+      | b >= lenB = chars+      | otherwise = case iter t b of+          Iter c d+            | c == ' ' -> chars+            | otherwise -> goWord (b + d) (chars + 1)++nextWordEnd :: Text -> Int -> Maybe Int+nextWordEnd fromLine !end = skipSpaces after 0 0+  where+    after = T.drop end fromLine+    !lenB = lengthWord8 after+    skipSpaces !t !b !chars+      | b >= lenB = Nothing+      | otherwise = case iter t b of+          Iter c d+            | c == ' ' -> skipSpaces t (b + d) (chars + 1)+            | otherwise -> Just (end + scanWord t (b + d) (chars + 1))+    scanWord !t !b !chars+      | b >= lenB = chars+      | otherwise = case iter t b of+          Iter c d+            | c == ' ' -> chars+            | otherwise -> scanWord t (b + d) (chars + 1)++prevWordEnd :: Text -> Int -> Int+prevWordEnd fromLine end =+  T.length (T.dropWhileEnd (== ' ') (T.dropWhileEnd (/= ' ') (T.take end fromLine)))++charsPerWidth :: Float -> Text -> Float -> Int+charsPerWidth w txt maxW+  | w <= 0 = maxBound `div` 2+  | otherwise = floor (maxW * fromIntegral (T.length txt) / w)++largestFitting :: Monad m => (Int -> m Bool) -> Int -> Int -> Int -> m Int+largestFitting fits lo0 hi0 guess+  | hi0 <= lo0 = pure lo0+  | otherwise = do+      let g = clamp (lo0 + 1) hi0 guess+      ok <- fits g+      if ok then up g 1 else down g 1+  where+    up !lo !step+      | lo >= hi0 = pure lo+      | otherwise = do+          let p = min hi0 (lo + step)+          ok <- fits p+          if ok then up p (step * 2) else bisect lo p+    down !hi !step+      | p <= lo0 = bisect lo0 hi+      | otherwise = do+          ok <- fits p+          if ok then bisect p hi else down p (step * 2)+      where+        p = hi - step+    bisect !lo !hi+      | hi - lo <= 1 = pure lo+      | otherwise = do+          let mid = (lo + hi) `div` 2+          ok <- fits mid+          if ok then bisect mid hi else bisect lo mid++takeWidth :: Monad m => Int -> (Text -> m Float) -> Float -> Text -> m (Text, Text)+takeWidth guess lineW maxW txt+  | T.null txt = pure (txt, T.empty)+  | otherwise = do+      k <- largestFitting fits 1 (T.length txt) guess+      let (start, end) = clusterBounds txt k+      pure (T.splitAt (if start > 0 then start else end) txt)+  where+    fits k+      | T.compareLength txt k == LT = pure False+      | otherwise = (<= maxW) <$> lineW (T.take k txt)++takeFitPrefix :: Monad m => Int -> (Text -> m Float) -> Float -> Text -> m Text+takeFitPrefix guess lineW maxW txt+  | T.null txt || maxW <= 0 = pure T.empty+  | otherwise = do+      let (_, end1) = clusterBounds txt 0+      ok1 <- (<= maxW) <$> lineW (T.take end1 txt)+      if not ok1+        then pure T.empty+        else fst <$> takeWidth guess lineW maxW txt++takeTailWidth :: Monad m => Int -> (Text -> m Float) -> Float -> Text -> m Text+takeTailWidth guess lineW maxW txt+  | T.null txt || maxW <= 0 = pure T.empty+  | otherwise = do+      let !len = T.length txt+          startAt k =+            let raw = max 0 (len - k)+                (cs, ce) = clusterBounds txt raw+             in if cs == raw then cs else ce+          fits k =+            let idx = startAt k+             in if idx >= len then pure False else (<= maxW) <$> lineW (T.drop idx txt)+      ok1 <- fits 1+      if not ok1+        then pure T.empty+        else do+          k <- largestFitting fits 1 len guess+          pure (T.drop (startAt k) txt)++-- | Truncate @txt@ with a trailing ellipsis if it exceeds @maxW@ using @lineW@.+truncateTextIO :: (Text -> IO Float) -> Float -> Text -> IO Text+truncateTextIO = truncateTextWithM EllipsisEnd++-- | Truncate @txt@ according to an explicit 'TextEllipsis' mode.+truncateTextWithIO :: TextEllipsis -> (Text -> IO Float) -> Float -> Text -> IO Text+truncateTextWithIO = truncateTextWithM++-- | Pure single-line truncation against prepared 'FontMetrics'.+truncateTextPure :: TextEllipsis -> FontMetrics -> Float -> Text -> Text+truncateTextPure ell fm maxW txt =+  runIdentity (truncateTextWithM ell (Identity . lineWidth fm) maxW txt)++truncateTextWithM :: Monad m => TextEllipsis -> (Text -> m Float) -> Float -> Text -> m Text+truncateTextWithM ell lineW maxW txt+  | maxW <= 0 = pure ""+  | otherwise = do+      w <- lineW txt+      if w <= maxW+        then pure txt+        else do+          ellW <- lineW "..."+          let fitHead lim = fst <$> takeWidth (charsPerWidth w txt lim) lineW lim txt+              fitTail lim = takeTailWidth (charsPerWidth w txt lim) lineW lim txt+              remW = maxW - ellW+              endCase = do+                fit <- fitHead remW+                let dotted = T.dropWhileEnd (== '.') fit <> "..."+                tooWide <- if clusterLength fit == T.length fit then (> maxW) <$> lineW dotted else pure False+                if tooWide then fitHead maxW else pure dotted+              startCase = do+                suf <- fitTail remW+                let dotted = "..." <> T.dropWhile (== '.') suf+                tooWide <- (> maxW) <$> lineW dotted+                if tooWide then fitTail maxW else pure dotted+          if maxW <= ellW+            then (if ell == EllipsisStart then fitTail else fitHead) maxW+            else case ell of+              EllipsisEnd -> endCase+              EllipsisStart -> startCase+              EllipsisMiddle -> do+                suf <- fitTail (remW * 0.5)+                sufW <- if T.null suf then pure 0 else lineW suf+                let preBudget = max 0 (remW - sufW)+                    prePool = T.take (max 0 (T.length txt - T.length suf)) txt+                pre0 <- takeFitPrefix (charsPerWidth w txt preBudget) lineW preBudget prePool+                if T.null pre0 && T.null suf+                  then fitHead maxW+                  else do+                    let dotted0 = T.dropWhileEnd (== '.') pre0 <> "..." <> suf+                    ok0 <- (<= maxW) <$> lineW dotted0+                    if ok0+                      then pure dotted0+                      else if not (T.null pre0)+                        then do+                          let (s, _) = clusterBounds pre0 (max 0 (T.length pre0 - 1))+                              dotted1 = T.dropWhileEnd (== '.') (T.take s pre0) <> "..." <> suf+                          ok1 <- (<= maxW) <$> lineW dotted1+                          if ok1 then pure dotted1 else endCase+                        else startCase
+ lib/NanoUI/Internal/Font/Types.hs view
@@ -0,0 +1,468 @@+{-# LANGUAGE StrictData #-}++-- | Font metric types, pure text measurement, caret geometry, and decoration+-- offsets. Backend callbacks populate 'FontBackend' to prepare snapshots and+-- rasterise glyph runs.+module NanoUI.Internal.Font.Types+  ( GlyphQuad (..)+  , ShapedText (..)+  , ShapedGlyphs (..)+  , FontMetrics (..)+  , FontBackend (..)+  , CustomMeasureFn+  , prepareFontMetrics+  , prepareFontMetricsMany+  , measureTextIO+  , lineWidthIO+  , drawShaped+  , drawGlyph+  , caretX+  , caretXIO+  , selectionSpans+  , monospaceMetrics+  , scaleFontMetrics+  , tabularFontMetrics+  , lineWidth+  , textIndexAtX+  , centeredTextY+  , alignedTextPen+  , textInkEnd+  , textDecorationMetrics+  , revealSpanInViewport+  , isDefaultNodeFont+  ) where++import Control.Monad.ST (runST)+import Data.Map.Strict qualified as Map+import Data.Maybe (isJust)+import Data.Primitive.PrimArray (PrimArray, imapPrimArray, indexPrimArray, mapPrimArray, newPrimArray, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Foreign qualified as TF+import Data.Text.Unsafe qualified as TU+import NanoUI.Internal.Style (AlignX (..), FontStyle (..), FontVariant (..), FontWeight (..))+import NanoUI.Internal.TextCluster (clusterBounds)+import NanoUI.Internal.Types (clamp, onGrid)++-- | Glyph ink rectangle relative to the pen, in logical pixels, with normalised+-- atlas UV bounds. Valid only while the backend's atlas placement remains valid.+data GlyphQuad = GlyphQuad+  { gqX :: {-# UNPACK #-} !Float+  , gqY :: {-# UNPACK #-} !Float+  , gqW :: {-# UNPACK #-} !Float+  , gqH :: {-# UNPACK #-} !Float+  , gqU0 :: {-# UNPACK #-} !Float+  , gqV0 :: {-# UNPACK #-} !Float+  , gqU1 :: {-# UNPACK #-} !Float+  , gqV1 :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | A line of text as the host's shaper laid it out: glyphs chosen and placed+-- with the font's kerning, ligatures and contextual forms, in fallback fonts+-- where the font lacks a character, and right-to-left runs reordered.+data ShapedText = ShapedText+  { stAdvance :: {-# UNPACK #-} !Float+  , stInkEnd :: {-# UNPACK #-} !Float+  -- ^ The right edge of the rightmost glyph's ink.+  , stCarets :: !(PrimArray Float)+  -- ^ Where the caret sits before each character, and after the last: one+  -- more entry than the text has characters. A right-to-left run's carets+  -- decrease, and the characters of a cluster share its width.+  }+  deriving (Eq, Show)++-- | The glyph quads that draw a shaped line: eight numbers a glyph (x, y,+-- width and height from the pen, then the atlas UVs u0 v0 u1 v1), in logical+-- pixels.+newtype ShapedGlyphs = ShapedGlyphs (PrimArray Float)+  deriving (Eq, Show)++-- | Logical-pixel font measurements and pure lookup snapshots. Prepare the+-- metrics for the text before pure layout. Native loading and atlas mutation+-- belong in the optional 'FontBackend' IO callbacks.+data FontMetrics = FontMetrics+  { fmLineHeight :: {-# UNPACK #-} !Float+  , fmAscent :: {-# UNPACK #-} !Float+  -- | Device pixels per logical unit used to snap glyph quads to the pixel grid.+  , fmSnapScale :: {-# UNPACK #-} !Float+  , fmAdvance :: Char -> Float+  -- ^ A character's advance. A font whose @\' \'@, @\'x\'@ and @\'M\'@ share one,+  -- with no kerning between @\'x\'@ and @\'M\'@, is taken as monospace.+  , fmKerning :: Char -> Char -> Float+  , fmShape :: Text -> Maybe ShapedText+  -- ^ Shaped line metrics when the host prepared metrics for this text.+  , fmGlyph :: Char -> Maybe GlyphQuad+  -- ^ Glyph quad for fallback unshaped rendering.+  , fmBackend :: Maybe FontBackend+  }++-- | Backend IO hooks for preparing metrics and rasterising shaped glyph runs.+data FontBackend = FontBackend+  { fbPrepare :: Text -> IO FontMetrics+  , fbDrawShaped :: Text -> IO (Maybe ShapedGlyphs)+  }++-- | Pure measurement callback used by custom widgets: takes font metrics and+-- available @(width, height)@ and returns desired @(width, height)@.+type CustomMeasureFn = FontMetrics -> (Float, Float) -> (Float, Float)++-- | Prepare an immutable measurement snapshot for text through the backend,+-- or return the supplied metrics when no backend is attached.+{-# INLINE prepareFontMetrics #-}+prepareFontMetrics :: FontMetrics -> Text -> IO FontMetrics+prepareFontMetrics fm txt = maybe (pure fm) (`fbPrepare` txt) (fmBackend fm)++-- | Prepare a finite text workspace for pure multi-label layout algorithms.+prepareFontMetricsMany :: FontMetrics -> [Text] -> IO FontMetrics+prepareFontMetricsMany fm texts = case fmBackend fm of+  Nothing -> pure fm+  Just _ -> case texts of+    [] -> pure fm+    _ -> do+      preparedList <- mapM (\t -> (t,) <$> prepareFontMetrics fm t) texts+      let !base = case preparedList of+            (_, p) : _ -> p+            [] -> fm+          !byText = Map.fromList [(t, fmShape p t) | (t, p) <- preparedList]+      pure base {fmShape = \t -> Map.findWithDefault Nothing t byText}++-- | Prepare metrics and measure a single line's advance in logical pixels.+{-# INLINE lineWidthIO #-}+lineWidthIO :: FontMetrics -> Text -> IO Float+lineWidthIO fm txt = do+  prepared <- prepareFontMetrics fm txt+  pure $! lineWidth prepared txt++-- | Prepare metrics and measure a single line's advance and the line height,+-- in logical pixels. Split text at newlines first.+{-# INLINE measureTextIO #-}+measureTextIO :: FontMetrics -> Text -> IO (Float, Float)+measureTextIO fm txt = do+  prepared <- prepareFontMetrics fm txt+  pure $! (lineWidth prepared txt, fmLineHeight prepared)++-- | The glyph quads of a shaped line, placing glyphs in the host's atlas as+-- needed; 'Nothing' when the host does not shape.+{-# INLINE drawShaped #-}+drawShaped :: FontMetrics -> Text -> IO (Maybe ShapedGlyphs)+drawShaped fm txt = maybe (pure Nothing) (`fbDrawShaped` txt) (fmBackend fm)++-- | A glyph's quad from the metrics snapshot.+{-# INLINE drawGlyph #-}+drawGlyph :: FontMetrics -> Char -> IO (Maybe GlyphQuad)+drawGlyph fm c = pure (fmGlyph fm c)++-- | Headless metrics with square cells of the given logical size, ascent 80%+-- of cell height, and no drawable glyphs or shaping backend.+monospaceMetrics :: Float -> FontMetrics+monospaceMetrics cell =+  FontMetrics+    { fmLineHeight = cell+    , fmAscent = cell * 0.8+    , fmSnapScale = 1.0+    , fmAdvance = \_ -> cell+    , fmKerning = \_ _ -> 0+    , fmShape = \_ -> Nothing+    , fmGlyph = \_ -> Nothing+    , fmBackend = Nothing+    }++-- | Scale logical measurements and glyph geometry by a positive factor.+-- Atlas UVs and display snap scale remain unchanged.+scaleFontMetrics :: Float -> FontMetrics -> FontMetrics+scaleFontMetrics s fm+  | s == 1.0 = fm+  | otherwise =+      fm+        { fmLineHeight = fmLineHeight fm * s+        , fmAscent = fmAscent fm * s+        , fmAdvance = \c -> fmAdvance fm c * s+        , fmKerning = \a b -> fmKerning fm a b * s+        , fmShape = \t -> fmap scaleShape (fmShape fm t)+        , fmGlyph = fmap scaleGlyph . fmGlyph fm+        , fmBackend = fmap scaleBackend (fmBackend fm)+        }+  where+    scaleBackend backend = FontBackend+      { fbPrepare = \t -> scaleFontMetrics s <$> fbPrepare backend t+      , fbDrawShaped = \t -> fmap (fmap scaleGlyphs) (fbDrawShaped backend t)+      }+    scaleGlyph gq = gq+      { gqX = gqX gq * s, gqY = gqY gq * s+      , gqW = gqW gq * s, gqH = gqH gq * s+      }+    scaleShape st =+      st+        { stAdvance = stAdvance st * s+        , stInkEnd = stInkEnd st * s+        , stCarets = mapPrimArray (* s) (stCarets st)+        }+    scaleGlyphs (ShapedGlyphs quads) =+      ShapedGlyphs (imapPrimArray (\i v -> if i `mod` 8 < 4 then v * s else v) quads)++-- | Give ASCII digits (@'0'@ to @'9'@) a uniform tabular advance equal to the+-- widest digit in @fm@, centring each digit's glyph ink inside that cell and+-- zeroing kerning around digits so numeric columns align and live counters+-- never jitter horizontally. Returns @fm@ unchanged when the font is already+-- monospace.+tabularFontMetrics :: FontMetrics -> FontMetrics+tabularFontMetrics fm+  | isJust (monospaceAdvance fm) = fm+  | otherwise = wrap fm+  where+    !snap = fmSnapScale fm+    !digitAdv = onGrid snap (maximum [fmAdvance fm d | d <- ['0' .. '9']])+    isTabDigit c = c >= '0' && c <= '9'+    wrap src =+      src+        { fmAdvance = \c -> if isTabDigit c then digitAdv else fmAdvance src c+        , fmKerning = \a b -> if isTabDigit a || isTabDigit b then 0 else fmKerning src a b+        , fmShape = \t ->+            if T.any isTabDigit t+              then fmap (tabularShape snap digitAdv t) (fmShape src t)+              else fmShape src t+        , fmGlyph = \c ->+            if isTabDigit c+              then fmap (\gq -> gq {gqX = gqX gq + onGrid snap ((digitAdv - fmAdvance src c) * 0.5)}) (fmGlyph src c)+              else fmGlyph src c+        , fmBackend = fmap wrapBackend (fmBackend src)+        }+    wrapBackend backend =+      FontBackend+        { fbPrepare = \t -> wrap <$> fbPrepare backend t+        , fbDrawShaped = \t ->+            if not (T.any isTabDigit t)+              then fbDrawShaped backend t+              else do+                prepared <- fbPrepare backend t+                mGlyphs <- fbDrawShaped backend t+                pure $ case (fmShape prepared t, mGlyphs) of+                  (Just st, Just gs) -> Just (tabularGlyphs snap digitAdv t st gs)+                  (_, m) -> m+        }++tabularOffsets :: Float -> Float -> Text -> PrimArray Float -> (Float, PrimArray Float, PrimArray Float)+tabularOffsets snap digitAdv txt carets = runST $ do+  let !n = T.length txt+  shifts <- newPrimArray n+  stops <- newPrimArray (n + 1)+  writePrimArray stops 0 (indexPrimArray carets 0)+  let go !j !acc+        | j >= n = pure acc+        | otherwise = do+            let c0 = indexPrimArray carets j+                c1 = indexPrimArray carets (j + 1)+                origW = c1 - c0+                c = T.index txt j+                (!acc', !gShift)+                  | c >= '0' && c <= '9' && origW >= 0 =+                      let d = digitAdv - origW in (acc + d, acc + onGrid snap (d * 0.5))+                  | otherwise = (acc, acc)+            writePrimArray shifts j gShift+            writePrimArray stops (j + 1) (c1 + acc')+            go (j + 1) acc'+  totalDelta <- go 0 0+  (totalDelta,,) <$> unsafeFreezePrimArray shifts <*> unsafeFreezePrimArray stops++tabularShape :: Float -> Float -> Text -> ShapedText -> ShapedText+tabularShape snap digitAdv txt st@(ShapedText adv ink carets)+  | T.null txt || sizeofPrimArray carets /= T.length txt + 1 = st+  | otherwise =+      let (totalDelta, _, carets') = tabularOffsets snap digitAdv txt carets+       in ShapedText (adv + totalDelta) (max 0 (ink + totalDelta)) carets'++tabularGlyphs :: Float -> Float -> Text -> ShapedText -> ShapedGlyphs -> ShapedGlyphs+tabularGlyphs snap digitAdv txt (ShapedText _ _ carets) sg@(ShapedGlyphs quads)+  | T.null txt || sizeofPrimArray carets /= T.length txt + 1 = sg+  | otherwise =+      let !n = T.length txt+          (_, shifts, _) = tabularOffsets snap digitAdv txt carets+          shiftFor midX = go 0+            where+              go !j+                | j >= n - 1 = indexPrimArray shifts (n - 1)+                | otherwise =+                    let a = indexPrimArray carets j+                        b = indexPrimArray carets (j + 1)+                        lo = min a b+                        hi = max a b+                     in if midX <= hi + 0.01 && (j == 0 || midX >= lo - 0.01)+                          then indexPrimArray shifts j+                          else go (j + 1)+          adjust i v+            | i `mod` 8 == 0 =+                let gw = indexPrimArray quads (i + 2)+                 in v + shiftFor (v + gw * 0.5)+            | otherwise = v+       in ShapedGlyphs (imapPrimArray adjust quads)++-- | Vertical pen offset inside a box of height @h@ at top @y@ for text height @th@.+{-# INLINE centeredTextY #-}+centeredTextY :: FontMetrics -> Float -> Float -> Float -> Float+centeredTextY fm y h th =+  case fmGlyph fm 'H' of+    Nothing -> y + (h - th) / 2+    Just gq -> y + onGrid (fmSnapScale fm) (h / 2 - (gqY gq + gqH gq / 2))++-- | Last glyph ink right in the same space as 'NanoUI.Internal.Draw.pushText'.+textInkEnd :: FontMetrics -> Text -> Float+textInkEnd fm txt =+  case T.unsnoc txt of+    Nothing -> 0+    Just (_, c) ->+      case fmShape fm txt of+        Just st -> stInkEnd st+        Nothing ->+          let pen = lineWidth fm txt - fmAdvance fm c+           in case fmGlyph fm c of+                Just gq -> pen + gqX gq + gqW gq+                Nothing -> pen + fmAdvance fm c++-- | Horizontal pen X and used width inside a node box of @(x, w)@ with horizontal+-- inset @ix@.+alignedTextPen :: AlignX -> Float -> Float -> Float -> FontMetrics -> Text -> (Float, Float)+alignedTextPen ax x w ix fm txt =+  let tw = lineWidth fm txt+      contentW = max 0 (w - 2 * ix)+      used = min tw contentW+      shift = if tw > contentW then used else min (textInkEnd fm txt) contentW+      tx = case ax of+        AlignStart -> x + ix+        AlignEnd -> x + w - ix - shift+        AlignCenter -> x + ix + (contentW - shift) / 2+   in (tx, used)++-- | Decoration stroke thickness, underline offset from line top, and+-- strikethrough offset from line top, given a font's line height and ascent.+{-# INLINE textDecorationMetrics #-}+textDecorationMetrics :: Float -> Float -> (Float, Float, Float)+textDecorationMetrics lineH ascent =+  (max 1 (0.06 * lineH), ascent + max 1 (0.1 * lineH), ascent * 0.65)++-- | Scroll offset that keeps @[spanStart, spanStart + spanSize]@ inside a+-- viewport of extent @viewExtent@ over @contentExtent@ of content, starting+-- from @oldScroll@.+{-# INLINE revealSpanInViewport #-}+revealSpanInViewport :: Float -> Float -> Float -> Float -> Float -> Float+revealSpanInViewport oldScroll viewExtent contentExtent spanStart spanSize+  | viewExtent <= 0 = 0+  | otherwise =+      let s0+            | spanStart < oldScroll = spanStart+            | spanStart + spanSize > oldScroll + viewExtent = spanStart + spanSize - viewExtent+            | otherwise = oldScroll+       in clamp 0 (max 0 (contentExtent - viewExtent)) s0++-- | Whether a node uses the ambient base font metrics rather than the host+-- font resolver.+{-# INLINE isDefaultNodeFont #-}+isDefaultNodeFont :: Float -> FontWeight -> FontStyle -> FontVariant -> Bool+isDefaultNodeFont size weight style variant =+  size <= 0+    && weight == WeightNormal+    && style == FontStyleNormal+    && (variant == FontRegular || variant == FontMono)++-- | Advance of @c@ plus its kerning against the previous character.+{-# INLINE kernedAdvance #-}+kernedAdvance :: FontMetrics -> Maybe Char -> Char -> Float+kernedAdvance fm prev c = case prev of+  Nothing -> fmAdvance fm c+  Just p -> fmAdvance fm c + fmKerning fm p c++-- | The character index whose caret is nearest @x@.+textIndexAtX :: FontMetrics -> Text -> Float -> Int+textIndexAtX fm txt x+  | s == e = nearestIdx+  | abs (caretX fm txt s - x) <= abs (caretX fm txt e - x) = s+  | otherwise = e+  where+    (s, e) = clusterBounds txt nearestIdx+    nearestIdx+      | T.null txt = 0+      | Just st <- fmShape fm txt =+          let carets = stCarets st+              n = sizeofPrimArray carets+              nearest !best !bestD !i+                | i >= n = best+                | otherwise =+                    let d = abs (indexPrimArray carets i - x)+                     in if d < bestD then nearest i d (i + 1) else nearest best bestD (i + 1)+           in nearest 0 (1 / 0) 0+      | x <= 0 = 0+      | Just adv <- monospaceAdvance fm, adv > 0 = clamp 0 (T.length txt) (floor (x / adv + 0.5))+      | otherwise = go 0 0.0 Nothing txt+    go !i !acc prev t =+      case T.uncons t of+        Nothing -> i+        Just (c, rest) ->+          let adv = kernedAdvance fm prev c+              mid = acc + adv * 0.5+           in if x < mid then i else go (i + 1) (acc + adv) (Just c) rest++-- | Where the caret before character @i@ of @txt@ sits.+caretX :: FontMetrics -> Text -> Int -> Float+caretX fm txt i = case fmShape fm txt of+  Just st ->+    let carets = stCarets st+     in if sizeofPrimArray carets == 0 then 0 else indexPrimArray carets (clamp 0 (sizeofPrimArray carets - 1) i)+  Nothing -> lineWidth fm (T.take i txt)++-- | Prepare metrics and compute the caret X offset before character @i@.+caretXIO :: FontMetrics -> Text -> Int -> IO Float+caretXIO fm txt i = do+  prepared <- prepareFontMetrics fm txt+  pure $! caretX prepared txt i++-- | The horizontal extents covering characters @lo@ to @hi@, splitting across+-- directional runs when a selection crosses bidi boundaries.+selectionSpans :: FontMetrics -> Text -> Int -> Int -> [(Float, Float)]+selectionSpans fm txt lo hi+  | hi <= lo = []+  | Just st <- fmShape fm txt =+      let carets = stCarets st+          n = sizeofPrimArray carets - 1+          charSpan i =+            let a = indexPrimArray carets i+                b = indexPrimArray carets (i + 1)+             in (min a b, max a b)+          merge [] = []+          merge [one] = [one]+          merge ((a0, a1) : (b0, b1) : rest)+            | b0 <= a1 + 0.5 && b1 >= a0 - 0.5 = merge ((min a0 b0, max a1 b1) : rest)+            | otherwise = (a0, a1) : merge ((b0, b1) : rest)+       in merge [charSpan i | i <- [max 0 lo .. min n hi - 1]]+  | otherwise = [(caretX fm txt lo, caretX fm txt hi)]++-- | Pure single-line advance in logical pixels. Metrics from a shaping+-- backend shape only the text they were prepared for; for any other text+-- this adds per-glyph advances, which can differ from the drawn run on a+-- long line. In a view, measure with 'NanoUI.lineWidthUi', which prepares+-- the metrics first.+lineWidth :: FontMetrics -> Text -> Float+lineWidth fm line+  | T.null line = 0+  | otherwise =+      case fmShape fm line of+        Just st -> stAdvance st+        Nothing -> case monospaceAdvance fm of+          Just adv -> fromIntegral (T.length line) * adv+          Nothing ->+            let !byteLen = TF.lengthWord8 line+                !(TU.Iter c0 step0) = TU.iter line 0+                go !acc !prev !off+                  | off >= byteLen = acc+                  | otherwise =+                      let !(TU.Iter c step) = TU.iter line off+                       in go (acc + fmAdvance fm c + fmKerning fm prev c) c (off + step)+             in go (fmAdvance fm c0) c0 step0++-- | The advance of every character of a font taken as monospace, if constant.+{-# INLINE monospaceAdvance #-}+monospaceAdvance :: FontMetrics -> Maybe Float+monospaceAdvance fm =+  let !spaceAdv = fmAdvance fm ' '+   in if spaceAdv == fmAdvance fm 'x' && spaceAdv == fmAdvance fm 'M' && fmKerning fm 'x' 'M' == 0+        then Just spaceAdv+        else Nothing
+ lib/NanoUI/Internal/Frame.hs view
@@ -0,0 +1,514 @@+-- | Complete headless frames: view construction, layout, input resolution,+-- damage, and draw-buffer generation. Backends own event waits and presentation.+module NanoUI.Internal.Frame+  ( runFrame+  , runFrameEff+  )+where++import Control.Monad (unless, when, (<$!>))+import Data.IORef (modifyIORef', readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.Maybe (isJust, isNothing)+import Data.Primitive.PrimArray (readPrimArray)+import Data.Primitive.PrimVar (writePrimVar)+import Effectful (Eff, IOE, runEff, type (:>))+import NanoUI.Internal.Atlas (atlasToken)+import NanoUI.Internal.Context+import NanoUI.Internal.Context.Types (resetContainerStack)+import NanoUI.Internal.Damage (captureFrameSnapshot, pruneUnmountedCaches, updatePrevRects, writeDamage)+import NanoUI.Internal.Draw+import NanoUI.Internal.Frame.Input+import NanoUI.Internal.Frame.Chrome (floatingSurface, paintMenuPanel)+import NanoUI.Internal.Frame.Explain (explainFrame, paintExplainHover, paintExplainLayer, paintExplainPage)+import NanoUI.Internal.Frame.Paint (lowerShapes, walkChildren)+import NanoUI.Internal.Frame.Scroll+import NanoUI.Internal.Frame.Select+import NanoUI.Internal.Frame.TextArea (finalizeTextFieldMouse)+import NanoUI.Internal.Frame.TextEdit+import NanoUI.Internal.Frame.TextInput (claimComposition, settleInputMethod)+import NanoUI.Internal.Frame.Window+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Id.Cursor (resetIdCursor)+import NanoUI.Internal.Input (Input (..), Key (..), MouseButton (..), Pressable (..), inputKeysNull, stripInteractionInput, withoutPointer)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Solve (measuredHeightAt, placeFloatingNodesWith, runCustomMeasure, solveLayout)+import NanoUI.Internal.Monad (NanoUI (..), Ui, embedNanoUI, runUi, whenM)+import NanoUI.Internal.NativeWindow (clearWindowClose)+import NanoUI.Internal.Store (ptrEq)+import NanoUI.Internal.Style (Padding (..), Theme (..), pageBackground, themeOverlayDim, themeSeparator)+import NanoUI.Internal.Tasks (sweepHeld)+import NanoUI.Internal.Types (Color, Damage (..), Rect (..), Size (..), colorA, damageIsEmpty, fadeAlpha, lerpColor, rectInflate, rectNonEmpty)+import NanoUI.Internal.Widgets.Overlay (windowChromeSepH, windowTitleBarH)+import NanoUI.Internal.Var (beginVarPass, endVarFrame, takeVarRerun)+import NanoUI.Internal.Widgets.Sensor (beginSensors, updateSensors)++-- | Build, lay out, resolve input, and paint one headless frame. Returns the+-- view result, borrowed draw buffers, and whether state+-- needs a follow-up frame. A local-state change can rebuild the view within+-- this call, with one-shot input removed. Native presentation is the host's job.+runFrame :: Context -> Input -> NanoUI a -> IO (a, DrawData, Bool)+runFrame ctx inp ui = runFrameEff runEff ctx inp (unNanoUI ui)++-- | 'runFrame' with a runner for the effects remaining after 'Ui'. Run frames+-- serially on a context; its arenas and stores are mutable and reused.+runFrameEff ::+  IOE :> es =>+  (forall x. Eff es x -> IO x)+  -> Context+  -> Input+  -> Eff (Ui : es) a+  -> IO (a, DrawData, Bool)+runFrameEff unlift ctx rawInp ui = do+  ensureMetricCaches ctx+  snap <- captureFrameSnapshot ctx+  themeBefore <- readIORef (ctxTheme ctx)+  modifyDamage ctx (\ds -> ds {dsDirty = False})+  -- Timed wakes are re-requested by whatever is still built this frame.+  clearWakeAt ctx+  takeThreadWake ctx+  -- The focused field gets any IME composition, and while one shows, the IME+  -- owns the keys.+  (frameInp, imeKeys) <- claimComposition ctx rawInp+  -- Route pointer input before the view runs, against the previous frame's+  -- geometry. Each pass below receives input filtered to its target layer+  -- ('withoutPointer' when the pointer is routed elsewhere): @layerInp@ for+  -- scrolling, windows, presses, focus and text fields. @frameInp@ retains the+  -- unmasked pointer for window-wide checks (outside-click dismissal, hover,+  -- and overlay painting).+  route <- routePointer ctx frameInp+  -- A widget covered by another gets no pointer.+  recordCoveredWidgets ctx route frameInp+  let routedIf mine = if mine then frameInp else withoutPointer frameInp+      layerInp = routedIf (case route of RouteLayer _ -> True; _ -> False)+  -- Wheel and thumb-drag input targets the previous frame's layout, so apply+  -- it while that arena is still intact, before it is reset for the new+  -- build. Settling offsets before the UI pass keeps build-time+  -- virtualization (table body rows) materialized for the range that will+  -- actually be visible, without a second build pass.+  updateScrollWheel ctx layerInp+  -- A glide advances with the wheel, before the build, for the same reason:+  -- the offset this frame renders at is the one virtualization must see.+  stepScrollGlides ctx (inputDeltaTime frameInp)+  updateScrollDrag ctx layerInp+  -- Read from the last frame's nodes, before the build resets them.+  recordFocusKind ctx imeKeys+  armPointerPress ctx frameInp+  -- A left press makes active the widget the user saw under the pointer. A+  -- press on a menu or dropdown leaves nothing active, whatever a release+  -- that never arrived left behind.+  when (pressedIn MouseLeft frameInp && not (pressedIn MouseLeft layerInp)) $+    writeIORef (ctxActiveId ctx) (WidgetId 0)+  targets <- pressTargets ctx layerInp+  armPointerTarget ctx targets+  resetUiBuild ctx True+  escTaken <- getsOverlay ctx osEscapeConsumed+  beginFrameModal ctx+  -- An Escape the IME consumed must not also quit the app.+  when (inputKeysNull (inputKeys frameInp) && pressedIn KeyEscape rawInp) $+    markEscapeConsumed ctx+  -- One whose press was taken stays taken while it repeats and on its+  -- release, so no key listener acts on the rest of it.+  when (escTaken && not (pressedOnceIn KeyEscape rawInp) && (heldIn KeyEscape rawInp || releasedIn KeyEscape rawInp)) $+    markEscapeConsumed ctx+  focusBefore <- readIORef (ctxFocusId ctx)+  result <- runViewPasses unlift ctx frameInp ui+  -- Clear the one-shot close request ('NanoUI.winCloseRequested') after the+  -- view has run.+  clearWindowClose ctx+  -- Scopes only change how nodes look, which the rect and text diffs below+  -- do not track, and custom widgets' cached ops hold the old theme's colours.+  -- Nothing measured depends on a theme, so the caches that follow the font+  -- metrics ('ctxMetricGen') stand.+  whenM (themeScopesChanged ctx) $ do+    damageFull ctx+    modifyIORef' (ctxDrawingCache ctx) (\dc -> dc {dcsCustomDrawOpCache = IM.empty})+  settleViewTheme ctx themeBefore+  let+    size@(Size w h) = inputWindowSize frameInp+  layoutArena ctx size True+  -- A press that starts a window gesture hit-tests the page where it is+  -- drawn, scrolled and clipped.+  applyScrollOffsets ctx size+  settleDropdowns ctx size+  movedResize <- updateWindowResize ctx layerInp w h+  movedWindow <- updateWindowDrag ctx layerInp+  -- A window moved or resized changes only where the floating panels go:+  -- the solve before placement stands, so place them again over it.+  when (movedResize || movedWindow) $ do+    layoutArena ctx size False+    applyScrollOffsets ctx size+    settleDropdowns ctx size+  persistWindowPositions ctx+  finalizeFrameInput ctx frameInp layerInp targets focusBefore+  settleDropdowns ctx size+  -- Layout is final, so the sensors record what the next view reads.+  updateSensors ctx size+  pruneUnmountedCaches ctx =<< updatePrevRects ctx size+  -- With the layout recorded, what the view read of the last one is checked+  -- against it. A check that publishes a float it measured (a tab strip's+  -- range) marks the frame as a layout change, not a scroll, for its damage.+  -- Both maps are forced: 'ptrEq' on an unforced selection compares a fresh+  -- thunk, which never matches, and every frame would be a layout change.+  !floatsBefore <- storeFloat <$> getStore ctx+  settleLayoutReads ctx+  !floatsAfter <- storeFloat <$> getStore ctx+  let !layoutFloats = not (ptrEq floatsBefore floatsAfter)+  refreshHover ctx frameInp+  refreshScrollBarHover ctx layerInp+  tickAnimations ctx (inputDeltaTime frameInp)+  sweepHeld ctx+  pruneDrawOpCache ctx+  -- The layout overlay damages its own outlines, since the rect diffs below+  -- miss rows and columns that moved.+  explain <- getExplainLayout ctx+  when explain (explainFrame ctx frameInp)+  -- The draw this frame may reuse is decided before its damage: a frame+  -- that may reuse it needs its damage worked out even for a host that does+  -- not read it ('ctxDamageWanted'). A frame that paints only a clip, or+  -- shows the layout overlay, can neither keep its draw nor reuse one.+  reuse <- readIORef (ctxDrawReuse ctx)+  paintFull <- readIORef (ctxPaintFull ctx)+  clear <- frameClearColor ctx+  key <- if drOn reuse && paintFull && not explain then drawReuseKey ctx size clear else pure Nothing+  let !mayReuse = case (key, drLast reuse) of+        (Just k, Just (lastKey, _)) -> k == lastKey+        _ -> False+  writeDamage ctx frameInp snap mayReuse layoutFloats+  drawData <- paintOrReuse ctx size explain paintFull clear reuse key mayReuse+  dirtyAfterUi <- isDirty ctx+  pure (result, drawData, dirtyAfterUi)++-- | Run the view pass, and re-run without interaction input if a backwards+-- 'Var' write invalidated what pass 1 drew.+{-# INLINE runViewPasses #-}+runViewPasses ::+  IOE :> es =>+  (forall x. Eff es x -> IO x) ->+  Context ->+  Input ->+  Eff (Ui : es) a ->+  IO a+runViewPasses unlift ctx frameInp ui = do+  beginVarPass ctx 1+  -- Opened only after layout, so whether it shows is known before the view.+  menuOpen <- isJust <$> getsInteraction ctx isTextInputMenu+  -- Two calls rather than a wrapper chosen at run time, so the usual one+  -- runs the view as it is.+  let runPass inp = if menuOpen then unlift (runUi ctx inp (withTextEditMenu ui)) else unlift (runUi ctx inp ui)+  result0 <- runPass frameInp+  -- Pending click is one-shot. Clear before a rerun so toggles do not fire twice.+  writeIORef (ctxClickedId ctx) (WidgetId 0)+  rerun <- takeVarRerun ctx+  r <-+    if rerun+      then do+        resetUiBuild ctx False+        -- A modal is active only if this pass builds it.+        modifyOverlay ctx (\os -> os {osModalActive = False, osModalDepth = 0})+        beginVarPass ctx 2+        runPass (stripInteractionInput frameInp)+      else pure result0+  endVarFrame ctx+  pure r++-- | The view, then the open text-edit menu ('textEditMenuView'), which+-- belongs to no widget of the view.+{-# INLINE withTextEditMenu #-}+withTextEditMenu :: Eff (Ui : es) a -> Eff (Ui : es) a+withTextEditMenu ui = ui <* embedNanoUI textEditMenuView++-- | Settle pointer presses/releases, focus transitions, IME, text-edit menu,+-- and select dropdowns against the solved layout.+--+-- The steps run in this order because each reads what the ones before it+-- settled:+--+-- 1. The release step clears the active widget, which the press set before+--    the view from the layout the user saw ('pressTargets', which also+--    gives @targets@ for the focus steps).+-- 2. 'finalizeTextInputFocus' clears focus for a press outside every text+--    field, so 'finalizeSelectFocus' and 'finalizeDrawingFocus' after it can+--    give focus to the select or custom widget the press landed on.+-- 3. The text-edit menu steps close the menu on an outside press before a+--    right press opens it again, and take a pick before Escape closes it.+-- 4. 'finalizeFocusRequest' applies focus asked for from code after the+--    pointer has moved focus, so a request in the view wins over the press.+-- 5. 'constrainFocusToModal' then drops focus a modal hides or no widget+--    holds, before 'finalizeTabFocus' moves it, so Tab starts from a widget+--    that is there.+-- 6. The select steps act on the dropdown focus now points at.+-- 7. 'settleInputMethod' runs last: it moves the input-method request to+--    wherever focus ended up.+{-# INLINE finalizeFrameInput #-}+finalizeFrameInput ::+  Context -> Input -> Input -> PressTargets -> WidgetId -> IO ()+finalizeFrameInput ctx frameInp layerInp targets focusBefore = do+  finalizePointerRelease ctx layerInp+  disarmPointerPress ctx frameInp+  finalizeTextInputFocus ctx layerInp targets+  finalizeSelectFocus ctx targets+  finalizeDrawingFocus ctx targets+  finalizeScrollFocus ctx layerInp targets+  finalizeTextFieldMouse ctx layerInp (ptFieldControl targets)+  closeTextEditMenuOnOutsideClick ctx frameInp+  openTextEditMenu ctx layerInp+  closeTextEditMenuOnEscape ctx frameInp+  finalizeFocusRequest ctx+  constrainFocusToModal ctx+  finalizeTabFocus ctx frameInp+  finalizeSelectKeyboard ctx frameInp+  closeSelectOnOutsideClick ctx frameInp+  settleInputMethod ctx focusBefore++-- | The frame's draw data. A full frame with no damage whose 'DrawReuseKey'+-- (@key@) matches the last full frame's (@mayReuse@) returns the previous+-- frame's 'DrawData' without repainting: an idle continuous frame paints+-- nothing. Other frames paint, and a full frame caches its output for the+-- next. Paint that reads state nano-ui does not track must call 'damageFull'+-- when that state changes.+paintOrReuse :: Context -> Size -> Bool -> Bool -> Color -> DrawReuse -> Maybe DrawReuseKey -> Bool -> IO DrawData+paintOrReuse ctx size explain paintFull clear reuse key mayReuse = do+  damage <- getsDamage ctx dsDamage+  case drLast reuse of+    Just (_, lastDraw) | mayReuse && damageIsEmpty damage -> pure lastDraw+    _ -> do+      -- The kept draw borrows the draw arena's buffers, which paint+      -- overwrites: drop it first, so a paint that throws leaves none behind.+      when (isJust (drLast reuse)) $ writeIORef (ctxDrawReuse ctx) $! reuse {drLast = Nothing}+      drawData <- paintFrame ctx size explain paintFull clear+      -- Nothing to keep now or before: leave the state as it is.+      unless (isNothing key && isNothing (drLast reuse)) $+        writeIORef (ctxDrawReuse ctx) $! reuse {drLast = (\k -> (k, drawData)) <$!> key}+      pure drawData++-- | What a full frame's draw follows besides its damage ('DrawReuseKey'), or+-- 'Nothing' when it cannot be reused: paint builds a custom drawing on a+-- node that is not a drawing (a pane grid's focus ring) afresh, and no+-- damage says when it changes.+drawReuseKey :: Context -> Size -> Color -> IO (Maybe DrawReuseKey)+drawReuseKey ctx@Context {ctxNodeArena = na, ctxDrawArena = da} size clear = do+  offNode <- customDrawingOffNode ctx+  if offNode+    then pure Nothing+    else+      fmap Just $+        DrawReuseKey size+          <$> getDrawSnapScale da+          <*> readIORef (daSquareGeometry da)+          <*> readIORef (daExternalText da)+          <*> readIORef (ctxMetricGen ctx)+          <*> readIORef (ctxFocusId ctx)+          <*> readIORef (ctxFocusVisible ctx)+          <*> readIORef (ctxHotId ctx)+          <*> readIORef (ctxActiveId ctx)+          <*> getPaintSignature na+          <*> atlasToken (ctxImageAtlas ctx)+          <*> pure clear++-- | The colour of the page surface this frame: the root node's theme, so a+-- scope around the whole view applies, or the base theme's for an empty view.+framePageBackground :: Context -> IO Color+framePageBackground ctx = do+  base <- readIORef (ctxTheme ctx)+  n <- arenaCount (ctxNodeArena ctx)+  if n > 0+    then pageBackground <$> nodeTheme ctx 0+    else pure (pageBackground base)++-- | The colour a full frame clears to ('drawClear'): the page surface laid+-- over the window colour as the backends blend a draw, so an opaque page+-- replaces the window's and a translucent one tints it. The default page is+-- the window itself, so a translucent window keeps its own alpha.+frameClearColor :: Context -> IO Color+frameClearColor ctx = do+  page <- framePageBackground ctx+  window <- themeWindow <$> readIORef (ctxTheme ctx)+  pure (if page == window then window else blendOver page window)++-- | @top@ over @bottom@ with straight alpha, as SDL's and the GL backend's+-- blend lays a draw over the target: the colour mixed by the top's alpha,+-- and the alphas combined.+blendOver :: Color -> Color -> Color+blendOver top bottom = fadeAlpha (lerpColor bottom top ta) (round (255 * (ta + ba * (1 - ta))))+  where+    unit c = fromIntegral c / 255 :: Float+    ta = unit (colorA top)+    ba = unit (colorA bottom)++-- | Paint the frame. Clip frames repaint the damaged region of the retained+-- texture, which preserves the other pixels ('paintDamageClip'). Full-present+-- frames (fresh retain, forced full, continuous) paint everything.+paintFrame :: Context -> Size -> Bool -> Bool -> Color -> IO DrawData+paintFrame ctx size explain paintFull clear = do+  let da = ctxDrawArena ctx+  resetDrawArena da+  setDrawClear da clear+  beginLayer da LayerBackground+  unless paintFull $ do+    damage <- takeDamage ctx+    paintDamageClip da clear damage =<< takeDamagePieces ctx+  lowerShapes ctx+  -- Page outlines go above the page's scrollbars and below floating panels.+  when explain $ do+    beginLayer da LayerContent+    paintExplainPage ctx+  beginLayer da LayerOverlay+  drawFloatingPanels ctx size explain+  when explain (paintExplainHover ctx)+  finishDraw da++-- | Reset what a view run builds: the node arena, sensors, input method+-- request, and the container, id, focus, hover, cursor-zone, drawing and+-- layout-overlay scopes. A second run after a backwards Var write+-- (@newFrame@ 'False') keeps the store, animations, prev rects, and the+-- theme scopes it compares against.+--+-- Each 'Context' field this resets in full ends its Haddock with the+-- sentence "Reset by" and this function's qualified name. A field added+-- here gets that sentence and an entry in the nano-ui-test case+-- @per-build-reset@, which counts the sentences.+resetUiBuild :: Context -> Bool -> IO ()+resetUiBuild ctx newFrame = do+  beginThemeScopes ctx newFrame+  resetNodeArena (ctxNodeArena ctx)+  resetContainerStack (ctxContainerStack ctx)+  resetIdCursor (ctxIdCursor ctx)+  writePrimVar (ctxFocusablesCount ctx) 0+  -- The view re-requests the input method each run while a widget takes text.+  readIORef (ctxInputMethod ctx) >>= mapM_ (\_ -> writeIORef (ctxInputMethod ctx) Nothing)+  writeIORef (ctxHotId ctx) (WidgetId 0)+  writeIORef (ctxCursorZones ctx) []+  writeIORef (ctxCursorRegions ctx) []+  readIORef (ctxChildWindows ctx) >>= \ws -> unless (null ws) (writeIORef (ctxChildWindows ctx) [])+  resetDrawingScopeCache ctx+  -- The layout overlay's scopes are ranges of the arena just emptied.+  explain <- readIORef (ctxExplain ctx)+  unless (null (esScopes explain)) $ writeIORef (ctxExplain ctx) explain {esScopes = []}+  beginSensors ctx++-- | Paint the floating panels over the page: windows with their title-bar+-- separator, the modal backdrop and the modals, then popups. Each is a+-- menu-style panel in its node's theme with its subtree clipped inside.+-- With @explain@, the layout overlay's outlines are drawn over each.+drawFloatingPanels :: Context -> Size -> Bool -> IO ()+drawFloatingPanels ctx@Context {ctxNodeArena = na, ctxDrawArena = da} (Size ww wh) explain = do+  let panels nt after = forFloatingNodes_ na nt $ \idx -> do+        rect <- getNodeRect na idx+        theme <- nodeTheme ctx idx+        paintMenuPanel da theme (floatingSurface theme nt) rect+        withClip da rect (walkChildren ctx idx)+        after theme idx rect+        when explain (paintExplainLayer ctx idx)+      plain _ _ _ = pure ()+  panels NodeWindow $ \theme idx (Rect x y w _) -> do+    pad <- getPadding na idx+    let sepY = y + padT pad + windowTitleBarH - windowChromeSepH+        sepW = max 0 (w - padL pad - padR pad)+    pushRect da (Rect (x + padL pad) sepY sepW windowChromeSepH) (themeSeparator theme)+  whenM (isJust <$> topModalNode na) $ do+    theme <- readIORef (ctxTheme ctx)+    pushRect da (Rect 0 0 ww wh) (themeOverlayDim theme)+    panels NodeModal plain+  panels NodePopup plain++-- | Start a clip frame from the page surface, as a full frame lays it over the+-- window clear. Widgets with a transparent fill, such as an idle menu-bar+-- title, draw nothing over the pixels they covered, so without the backdrop a+-- hover that just ended would stay in the retain texture. Damage in pieces+-- paints a backdrop over each, and every command is cut to them. Each is+-- inflated by a logical pixel to cover the runner's outward snap. An empty clip+-- stays empty, so a frame with nothing damaged paints nothing.+paintDamageClip :: DrawArena -> Color -> Damage -> [Rect] -> IO ()+paintDamageClip _ _ DamageFull _ = pure ()+paintDamageClip da clear (DamageClip r) pieces = do+  let clip = if rectNonEmpty r then rectInflate 1 r else r+      pieceClips = map (rectInflate 1) pieces+      backdrops = if null pieces then [clip] else pieceClips+  setClip da clip+  setClipPieces da pieceClips+  when (rectNonEmpty r) $ mapM_ (flip (pushRect da) clear) backdrops++-- | Lay out the arena and place the floating panels over it. The cached solve+-- is restored when it was taken at this size and font generation and @check@+-- accepts it ('layoutReuseValid'); otherwise the arena is solved and the+-- result, before placement, captured for the next frame. The solve measures+-- only the nodes whose restore keys changed since the cache's capture; the+-- keys are folded here, so frames that reuse the whole layout never compute+-- them. A cache taken under other font metrics measured text differently, so+-- none of it is restored. Floating panels depend on state outside the arena+-- (window positions, popup anchors), so each is placed after the solve, or,+-- over a reused solve, restores the cached placement ('lcPlaced') when its+-- inputs are unchanged.+layoutArena :: Context -> Size -> Bool -> IO ()+layoutArena ctx@Context {ctxNodeArena = na} size@(Size w h) check = do+  let ms = contextMeasurers ctx+  gen <- readIORef (ctxMetricGen ctx)+  cached <- readIORef (ctxLayoutCache ctx)+  reused <- case cached of+    Just (c, cachedSize, cachedGen)+      | cachedSize == size && cachedGen == gen -> do+          ok <- if check then layoutReuseValid ctx c else pure True+          when ok (restoreLayoutCache na c)+          pure ok+    _ -> pure False+  unless reused $ do+    computeSubtreeHashes na+    measures <- solveLayout na ms w h $ case cached of+      Just (c, _, cachedGen) | cachedGen == gen -> Just c+      _ -> Nothing+    n <- arenaCount na+    if n <= 0+      then writeIORef (ctxLayoutCache ctx) Nothing+      else do+        c <- captureLayoutCache na =<< maybe (newLayoutCache 64) (\(old, _, _) -> pure old) cached+        -- The registered hooks, so reuse can tell when one appears or goes.+        hooks <- customMeasureHooks ctx+        let c' = c {lcMeasures = measures, lcMeasureHooks = hooks}+        writeIORef (ctxLayoutCache ctx) (Just (c', size, gen))+  floating <- floatingNodeCount na+  when (floating > 0) $ do+    -- Placing over a solve is kept once a frame reuses it: content that+    -- changes every frame solves every frame, and would keep what no frame+    -- puts back.+    placed <- if reused then fmap (\(c, _, _) -> lcPlaced c) <$> readIORef (ctxLayoutCache ctx) else pure Nothing+    placeFloatingNodesWith na ms w h (lookupWindowPos ctx) (lookupWindowSize ctx) (lookupPopupConfig ctx) (dropdownPlacement ctx size) placed++-- | Layout reuse is sound when the frame's layout inputs hash to what the+-- cache captured, the same widgets register custom measures, and every custom+-- measure still returns the sizes the captured solve recorded. The signature+-- covers the measure's declared inputs, but neither a hook's presence nor+-- what its closure reads is arena state, which only comparing the hooks and+-- running them again can check.+layoutReuseValid :: Context -> LayoutCache -> IO Bool+layoutReuseValid ctx@Context {ctxNodeArena = na} lc = do+  okSig <- layoutSigMatches na lc+  hooks <- customMeasureHooks ctx+  -- A matching signature means the same node count, so every recorded index+  -- is in range. Each recorded measure runs again and must match: the+  -- drawing node's measure as 'runCustomMeasure' records it.+  let measureOf idx = do+        nt <- getNodeType na idx+        if nt /= NodeDrawing+          then pure Nothing+          else do+            mFn <- lookupCustomMeasureAt ctx idx+            traverse (\fn -> runCustomMeasure na (ctxFontMetrics ctx) fn idx) mFn+      stable (idx, r) rest = measureOf idx >>= \c -> if c == Just r then placedStable idx >>= \ok -> if ok then rest else pure False else pure False+      -- The solve also ran the measure at the width the drawing was placed+      -- at, when that differs from its measured width ('drawingHeightAt'),+      -- and a closure reading outside state can answer differently there+      -- with the same answer at the offered width.+      placedStable idx = do+        hAx <- getHeightSizing na idx+        mFn <- lookupCustomMeasureAt ctx idx+        case mFn of+          Just fn | axTag hAx == SizingFit -> do+            measuredW <- readPrimArray (lcMeasured lc) (idx * 2)+            placedW <- readPrimArray (lcUnsnapped lc) (idx * 4 + 2)+            placedH <- readPrimArray (lcUnsnapped lc) (idx * 4 + 3)+            pure (placedW == measuredW || measuredHeightAt (ctxFontMetrics ctx) fn placedW hAx == placedH)+          _ -> pure True+  if not okSig || hooks /= lcMeasureHooks lc+    then pure False+    else foldr stable (pure True) (IM.toList (lcMeasures lc))
+ lib/NanoUI/Internal/Frame/Chrome.hs view
@@ -0,0 +1,509 @@+-- | Widget paint helpers: labels, styles, rects, menu panels and display text.+module NanoUI.Internal.Frame.Chrome+  ( floatingAncestor+  , displayText+  , widgetVisualStyle+  , widgetVisualStyleWith+  , widgetVisualStyleWithTheme+  , textInputValue+  , maskPassword+  , textInputFocused+  , fillStyledRect+  , strokeStyledRect+  , paintStyledRect+  , paintGroupedButton+  , floatingSurface+  , overlayMenuStyle+  , paintMenuPanel+  , menuPanelBounds+  , paintMenuAccent+  , paintScrollBars+  , paintScrollBarsConfigured+  , paintTabHeader+  , paintTabChrome+  , tabHeaderVisualStyle+  , paintTableHeader+  ) where++import Control.Monad (when)+import Data.Bits (xor)+import Data.IORef (readIORef)+import Data.Maybe (fromMaybe, listToMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Draw (DrawArena, pushRect, pushRoundedRect, pushRoundedStroke, withClip)+import NanoUI.Internal.Layout.ScrollGeometry (ScrollBarLayout (..), ScrollConfig (..), ScrollPolicy (..), scroll2DConfig)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Store (fieldInt, fieldText, findSlot)+import NanoUI.Internal.Style+import NanoUI.Internal.Types (Color (..), Rect (..), clamp, colorA, colorLuminance, colorTransparent, lerpColor)+import NanoUI.Internal.WidgetText++floatingAncestor :: Context -> NodeIdx -> IO (Maybe NodeType)+floatingAncestor ctx idx = walkFloatingAncestors (ctxNodeArena ctx) idx (\_ nt -> pure (Just nt))++displayText :: Context -> NodeType -> NodeIdx -> IO Text+displayText ctx nt idx = do+  txt <- getText (ctxNodeArena ctx) idx+  case nt of+    NodeTextInput -> textInputFieldText txt <$> textInputValue ctx idx <*> textInputFocused ctx idx+    NodeTextArea -> textInputValue ctx idx+    NodeSelect -> selectDisplayText txt <$> selectCurrentOption ctx idx+    NodeButton -> pure txt+    NodeText -> pure txt+    NodeContainer -> pure txt+    NodeSpacer -> pure txt+    NodeSeparator -> pure txt+    NodeSlider -> pure txt+    NodeScrollContainer -> pure txt+    NodeModal -> pure txt+    NodeImage -> pure txt+    NodePanel -> pure txt+    NodeWindow -> pure txt+    NodeBox -> pure txt+    NodeColorPicker -> pure txt+    NodePopup -> pure txt+    NodeDrawing -> pure txt+    NodeShader -> pure txt++selectCurrentOption :: Context -> NodeIdx -> IO Text+selectCurrentOption ctx idx = do+  store <- getStore ctx+  opts <- getOptions (ctxNodeArena ctx) idx+  wid <- getWidgetId (ctxNodeArena ctx) idx+  -- An index the options do not reach shows clamped, as the select reads it.+  let picked = clamp 0 (length opts - 1) (findSlot fieldInt 0 (intKey wid) store)+  pure (fromMaybe "" (listToMaybe (drop picked opts)))++-- | The text a field displays: its stored value, masked one character per+-- character for password inputs so caret and selection offsets still line up.+textInputValue :: Context -> NodeIdx -> IO Text+textInputValue ctx@Context {ctxNodeArena = na} idx = do+  wid <- getWidgetId na idx+  nt <- getNodeType na idx+  si <- getStyleIdx na idx+  store <- getStore ctx+  let value = findSlot fieldText "" (intKey wid) store+  pure $+    if nt == NodeTextInput && hasFlag textInputFlagPassword si+      then maskPassword value+      else value++-- | A password field's text as shown: one @*@ per character.+maskPassword :: Text -> Text+maskPassword t = T.replicate (T.length t) "*"++textInputFocused :: Context -> NodeIdx -> IO Bool+textInputFocused ctx idx = do+  wid <- getWidgetId (ctxNodeArena ctx) idx+  focus <- readIORef (ctxFocusId ctx)+  pure (focus == wid)++-- | Transparent fills and no border.+clearStyle :: Style -> Style+clearStyle s = s {styleBg = colorTransparent, styleHoverBg = colorTransparent, styleActiveBg = colorTransparent, styleBorderWidth = 0}++-- | Close button style; the cross goes from muted to full colour as @hotT@+-- goes from 0 to 1.+closeButtonStyle :: Theme -> Float -> Style+closeButtonStyle theme hotT =+  let btn = themeButton theme+      muted = lerpColor (styleFg btn) (styleBg (themePanel theme)) 0.42+   in (clearStyle btn) {styleFg = lerpColor muted (styleFg btn) hotT}++-- | A tab header's surface for packed tab style @packed@ ('tabDecodeStyle').+-- Fills are the label colour at a low alpha where they can, so a strip reads+-- the same on a panel, a card or the window. The label is muted until the+-- tab is selected.+tabHeaderVisualStyle :: Theme -> Word64 -> Bool -> Style+tabHeaderVisualStyle theme packed isActive =+  let panel = themePanel theme+      fg = styleFg panel+      idle = lerpColor (themeMuted theme) fg 0.35+      clear = fadeAlpha fg 0+      accent = themeAccent theme+      raised = tabRaisedColor theme+      flat c = panel {styleBg = c, styleHoverBg = c, styleActiveBg = c, styleBorderWidth = 0, styleBorder = clear}+      quiet tint =+        panel+          { styleBg = fadeAlpha fg tint+          , styleHoverBg = fadeAlpha fg (tint + 16)+          , styleActiveBg = fadeAlpha fg (tint + 28)+          , styleFg = idle+          , styleBorder = clear+          , styleBorderWidth = 0+          }+      radius s r = s {styleCornerRadius = r}+   in case (fst (tabDecodeStyle packed), isActive) of+        (1, True) -> radius ((flat accent) {styleFg = themeOnAccent theme}) tabPillRadius+        (1, False) -> radius (quiet 0) tabPillRadius+        (2, True) -> radius ((flat raised) {styleBorder = styleBorder (themeButton theme), styleBorderWidth = 1}) 6+        (2, False) -> radius (quiet 0) 6+        (3, True) -> radius ((flat (styleBg panel)) {styleBorder = styleBorder panel, styleBorderWidth = 1}) 7+        (3, False) -> radius (quiet 12) 7+        (_, True) -> radius ((quiet 0) {styleFg = fg}) 6+        _ -> radius (quiet 0) 6++-- | Large enough to round a pill header's ends fully; painters clamp it.+tabPillRadius :: Float+tabPillRadius = 100++-- | A selected segment's fill: whichever of the button and panel colours is+-- lighter, so it stands out of its track in light and dark themes alike.+tabRaisedColor :: Theme -> Color+tabRaisedColor theme =+  let b = styleBg (themeButton theme)+      p = styleBg (themePanel theme)+   in if colorLuminance b >= colorLuminance p then b else p++-- | Flat menu row / menu-bar entry. Transparent at rest, a hover highlight+-- (matching the text-field context menu), and an accent-tinted fill while it+-- owns an open drop-down (@val > 0.5@, menu-bar titles only).+menuItemVisualStyle :: Theme -> Float -> Style+menuItemVisualStyle theme val =+  let menu = overlayMenuStyle theme+      accent = themeAccent theme+      openBg = lerpColor (styleBg menu) accent 0.3+      isOpen = val > 0.5+   in menu+        { styleBg = if isOpen then openBg else colorTransparent+        , styleHoverBg = if isOpen then openBg else styleHoverBg menu+        , styleActiveBg = lerpColor (styleBg menu) accent 0.4+        , styleBorder = colorTransparent+        , styleBorderWidth = 0+        -- The text-field context menu fills hovered rows with a square+        -- pushRect; keep the generic menu identical.+        , styleCornerRadius = 0+        }++tableHeaderVisualStyle :: Theme -> Bool -> Style+tableHeaderVisualStyle theme isSorted =+  let btn = themeButton theme+      accent = themeAccent theme+      headerBg = lerpColor (styleBg (themePanel theme)) (styleBg btn) 0.55+   in btn+        { styleBg = headerBg+        , styleHoverBg = lerpColor headerBg accent 0.18+        , styleActiveBg = lerpColor headerBg accent 0.28+        , styleFg = if isSorted then styleFg btn else themeMuted theme+        , styleBorderWidth = 0+        , styleCornerRadius = 0+        }++-- | A tab header's fill, outline and selection mark. Underlined and+-- contained headers meet the strip's rule on the side facing the body+-- ('tabEdgeStrip'): an underlined header marks the selection with an accent bar+-- there, and a contained one opens onto the body through it.+paintTabHeader :: DrawArena -> Theme -> Word64 -> Bool -> Style -> Rect -> IO ()+paintTabHeader da theme packed isActive style rect@(Rect x y w h) = do+  let (tabStyle, orient) = tabDecodeStyle packed+      bg = styleBg style+      r = min (styleCornerRadius style) (min w h / 2)+      hasBg = colorA bg > 0+  case tabStyle of+    1 -> when hasBg $ pushRoundedRect da rect r bg+    2 -> do+      -- A selected segment stands a pixel above its shadow, inside its rect.+      let shadow = themeShadow theme+          raised = if isActive && colorA shadow > 0 then Rect x y w (h - 1) else rect+      when (raised /= rect) $+        pushRoundedRect da rect r (fadeAlpha shadow (colorA shadow `div` 2))+      when hasBg $ pushRoundedRect da raised r bg+      when isActive $ strokeStyledRect da style raised+    3 ->+      -- Rounded on the outer corners only: the shape runs a radius past the+      -- edge facing the body, and the header's rect clips that side off.+      withClip da rect $ do+        let open = tabEdgeGrow orient (r + 1) rect+        when hasBg $ pushRoundedRect da open r bg+        when isActive $ pushRoundedStroke da open r 1 (styleBorder style)+    _ -> do+      -- The hover fill stops short of the rule and the selection bar.+      when hasBg $ pushRoundedRect da (tabEdgeGrow orient (-3) rect) r bg+      when isActive $ pushRoundedRect da (tabEdgeStrip orient 2 rect) 1 (themeAccent theme)++-- | What a tab strip's container paints under its headers or body+-- ('tabChromeDecode'): the rule the headers sit on, the segmented track, or a+-- contained body's fill and its border on the sides away from the headers.+{-# NOINLINE paintTabChrome #-}+paintTabChrome :: DrawArena -> Theme -> Word64 -> Rect -> IO ()+paintTabChrome da theme si rect@(Rect _ _ w h) = do+  let (part, tabStyle, orient) = tabChromeDecode si+      panel = themePanel theme+      fg = styleFg panel+  case part of+    TabChromeRule ->+      pushRect da (tabEdgeStrip orient 1 rect) (if tabStyle == 3 then styleBorder panel else themeSeparator theme)+    TabChromeTrack -> pushRoundedRect da rect (min 9 (min w h / 2)) (fadeAlpha fg 16)+    TabChromeBody -> withClip da rect $ do+      -- A body below its headers opens upward: the opposite orientation.+      let open = tabEdgeGrow (orient `xor` 1) 9 rect+      pushRoundedRect da open 8 (styleBg panel)+      pushRoundedStroke da open 8 1 (styleBorder panel)+    TabChromeNone -> pure ()++-- | @rect@ grown by @d@ on the side facing the body of a strip with+-- orientation @orient@ (0-3: top, bottom, left, right), or shrunk for a+-- negative @d@.+tabEdgeGrow :: Int -> Float -> Rect -> Rect+tabEdgeGrow orient d (Rect x y w h) = case orient of+  1 -> Rect x (y - d) w (h + d)+  2 -> Rect x y (w + d) h+  3 -> Rect (x - d) y (w + d) h+  _ -> Rect x y w (h + d)++-- | The @t@ thick strip of @rect@ along the side facing the body.+tabEdgeStrip :: Int -> Float -> Rect -> Rect+tabEdgeStrip orient t (Rect x y w h) = case orient of+  1 -> Rect x y w t+  2 -> Rect (x + w - t) y t h+  3 -> Rect x y t h+  _ -> Rect x (y + h - t) w t++paintTableHeader :: DrawArena -> Theme -> Bool -> Style -> Float -> Float -> Float -> Float -> IO ()+paintTableHeader da theme isSorted style x y w h = do+  pushRect da (Rect x y w h) (styleBg style)+  when isSorted $+    pushRect da (Rect x (y + h - 2) w 2) (themeAccent theme)++widgetVisualStyle :: Context -> NodeType -> NodeIdx -> IO Style+widgetVisualStyle ctx nt idx = do+  hot <- readIORef (ctxHotId ctx)+  active <- readIORef (ctxActiveId ctx)+  focus <- readIORef (ctxFocusId ctx)+  widgetVisualStyleWith ctx hot active focus nt idx++-- | 'widgetVisualStyle' using caller-cached interaction ids so the paint+-- walk does not re-read 'ctxHotId', 'ctxActiveId' and 'ctxFocusId' per node.+widgetVisualStyleWith :: Context -> WidgetId -> WidgetId -> WidgetId -> NodeType -> NodeIdx -> IO Style+widgetVisualStyleWith ctx hot active focus nt idx = do+  theme <- nodeTheme ctx idx+  widgetVisualStyleWithTheme ctx theme hot active focus nt idx++-- | 'widgetVisualStyleWith' using the caller's already-resolved scoped 'Theme'+-- so the paint pass avoids re-reading the node's scope and theme table.+widgetVisualStyleWithTheme :: Context -> Theme -> WidgetId -> WidgetId -> WidgetId -> NodeType -> NodeIdx -> IO Style+widgetVisualStyleWithTheme ctx theme hot active focus nt idx = do+  a <- arenaArrays (ctxNodeArena ctx)+  wid <- WidgetId . fromIntegral <$> readTree a idx TreeWidgetId+  val <- readStyle a idx StyleNodeValue+  animT <- getAnimationValue ctx wid+  styleIdx <- if nt == NodeButton then readStyleIdx a idx else pure 0+  let !bkind = if nt == NodeButton then buttonKindOf styleIdx else ButtonPlain+      !isChoice = bkind == ButtonChoice+      !isRow = bkind == ButtonRow+      !isClose = bkind == ButtonClose+      !isMenu = bkind == ButtonMenu || bkind == ButtonMenuBar+      -- Only these consult the floating ancestor; skip the parent walk for+      -- the common panel/text/button path.+      !modalAware = isChoice || isRow || nt == NodeSlider+  mFloat <- if modalAware then floatingAncestor ctx idx else pure Nothing+  let !isFocus = focus == wid+      !isHot = wid == hot+      !hotT = if isHot && not (animT > 0) then 1 else animT+      focusBorder s = if isFocus then s {styleBorder = themeAccent theme} else s+      !base =+        case nt of+          NodeTextInput -> focusBorder (themeInput theme)+          NodeTextArea -> focusBorder (themeInput theme)+          NodeSelect -> focusBorder (themeButton theme)+          NodeColorPicker -> focusBorder (themeInput theme)+          NodeSlider -> clearStyle (themeInput theme)+          NodeButton -> case bkind of+            ButtonChoice -> clearStyle (themeButton theme)+            ButtonRow ->+                let btn = themeButton theme+                    accent = themeAccent theme+                    surface = if mFloat == Just NodeModal then overlayMenuStyle theme else themePanel theme+                    unselectedBg = fromMaybe (styleBg surface) (stripeColor theme (treeDecodeStripe styleIdx))+                    rowStyle fill hoverT activeT =+                      btn+                        { styleBg = fill+                        , styleHoverBg = lerpColor unselectedBg accent hoverT+                        , styleActiveBg = lerpColor unselectedBg accent activeT+                        , styleBorderWidth = 0+                        , styleCornerRadius = 0+                        }+                 in if val > 0.5+                      then rowStyle (lerpColor unselectedBg accent 0.25) 0.35 0.45+                      else rowStyle unselectedBg 0.12 0.22+            ButtonMenu -> menuItemVisualStyle theme val+            ButtonMenuBar -> menuItemVisualStyle theme val+            ButtonClose -> closeButtonStyle theme hotT+            ButtonTab -> tabHeaderVisualStyle theme (buttonVisualStyle styleIdx) (val > 0.5)+            ButtonTable -> tableHeaderVisualStyle theme (val > 0.5)+            _ | val > 0.5 ->+                let (fill, label) = case buttonToneOf styleIdx of+                      Nothing -> (themeAccent theme, themeOnAccent theme)+                      Just t -> let c = toneColor theme t in (c, readableOn theme c)+                 in (themeButton theme)+                  { styleBg = fill+                  , styleHoverBg = fill+                  , styleFg = label+                  , styleBorder = fill+                  }+              | otherwise -> themeButton theme+          -- A drawing's chrome, and the default for the node types that+          -- paint none of their own.+          NodeDrawing -> themeButton theme+          NodeContainer -> themeButton theme+          NodeText -> themeButton theme+          NodeSpacer -> themeButton theme+          NodeSeparator -> themeButton theme+          NodeScrollContainer -> themeButton theme+          NodeModal -> themeButton theme+          NodeImage -> themeButton theme+          NodePanel -> themeButton theme+          NodeWindow -> themeButton theme+          NodeBox -> themeButton theme+          NodePopup -> themeButton theme+          NodeShader -> themeButton theme+      !widgetBase =+        case mFloat of+          -- Rows keep their selection and stripes, on the modal's surface.+          Just NodeModal | modalAware && not isRow -> overlayMenuStyle theme+          _ -> base+      !bg+        | isFocus, nt == NodeTextInput || nt == NodeTextArea = styleActiveBg widgetBase+        | hashWidgetId wid == hashWidgetId active = styleActiveBg widgetBase+        | isChoice || isClose || nt == NodeSlider = styleBg widgetBase+        | isMenu = if isHot then styleHoverBg widgetBase else styleBg widgetBase+        | hotT <= 0 || styleBg widgetBase == styleHoverBg widgetBase = styleBg widgetBase+        | otherwise = lerpColor (styleBg widgetBase) (styleHoverBg widgetBase) hotT+  -- Idle widgets (no hover/active tint change) reuse the base style record+  -- rather than allocating a fresh Style through a record update.+  pure $! if bg == styleBg widgetBase then widgetBase else widgetBase {styleBg = bg}++{-# INLINE fillStyledRect #-}+fillStyledRect :: DrawArena -> Style -> Rect -> IO ()+fillStyledRect da style rect =+  if styleCornerRadius style <= 0+    then pushRect da rect (styleBg style)+    else pushRoundedRect da rect (styleCornerRadius style) (styleBg style)++{-# INLINE strokeStyledRect #-}+strokeStyledRect :: DrawArena -> Style -> Rect -> IO ()+strokeStyledRect da style rect@(Rect _ _ w h) =+  when (styleBorderWidth style > 0) $+    if styleBorderSides style == 15+      then do+        let rr = clamp 0 (min (w / 2) (h / 2)) (styleCornerRadius style)+        pushRoundedStroke da rect rr (max 1 (styleBorderWidth style)) (styleBorder style)+      else strokeStyledSides da style rect++-- | The border bars of a style drawn on some sides only ('borderSides').+{-# NOINLINE strokeStyledSides #-}+strokeStyledSides :: DrawArena -> Style -> Rect -> IO ()+strokeStyledSides da style (Rect x y w h) = do+  let bw = max 1 (styleBorderWidth style)+      side s r = when (styleHasSide s style) (pushRect da r (styleBorder style))+  side SideLeft (Rect x y bw h)+  side SideRight (Rect (x + w - bw) y bw h)+  side SideTop (Rect x y w bw)+  side SideBottom (Rect x (y + h - bw) w bw)++-- | A style's fill, then its border.+{-# INLINE paintStyledRect #-}+paintStyledRect :: DrawArena -> Style -> Rect -> IO ()+paintStyledRect da style rect = do+  fillStyledRect da style rect+  strokeStyledRect da style rect++-- | Paint a button or select inside a connected 'NanoUI.buttonGroup':+-- outer-only corner rounding and a shared internal border along the leading+-- seam of every item after the first.+{-# NOINLINE paintGroupedButton #-}+paintGroupedButton :: DrawArena -> Style -> DirTag -> Bool -> Bool -> Rect -> IO ()+paintGroupedButton da style dir isFirst isLast rect@(Rect x y w h)+  | isFirst && isLast = paintStyledRect da style rect+  | otherwise = do+      let bw = if styleBorderWidth style > 0 then max 1 (styleBorderWidth style) else 0+          rr = clamp 0 (min (w / 2) (h / 2)) (styleCornerRadius style)+          pad = rr + max 1 bw+          ext0 = if isFirst then 0 else pad+          ext1 = if isLast then 0 else pad+          open = case dir of+            DirRow -> Rect (x - ext0) y (w + ext0 + ext1) h+            DirColumn -> Rect x (y - ext0) w (h + ext0 + ext1)+      withClip da rect $ do+        if rr <= 0+          then pushRect da open (styleBg style)+          else pushRoundedRect da open rr (styleBg style)+        when (bw > 0) $+          pushRoundedStroke da open rr bw (styleBorder style)+      when (not isFirst && bw > 0 && colorA (styleBorder style) > 0) $+        pushRect da (case dir of DirRow -> Rect x y bw h; DirColumn -> Rect x y w bw) (styleBorder style)++-- | Popups, modals, dropdowns and menus: 'themePopup', with a row hover+-- that shows on it and a pressed row tinted toward the accent.+overlayMenuStyle :: Theme -> Style+overlayMenuStyle theme =+  let popup = themePopup theme+      hover =+        if styleHoverBg popup == styleBg popup+          then styleHoverBg (themeButton theme)+          else styleHoverBg popup+   in popup+        { styleHoverBg = hover+        , styleActiveBg = lerpColor (styleBg popup) (themeAccent theme) 0.22+        }++-- | The surface a floating node is drawn on: a floating window's+-- 'themeFloatingWindow', or a modal's or popup's 'overlayMenuStyle'.+floatingSurface :: Theme -> NodeType -> Style+floatingSurface theme nt = if nt == NodeWindow then themeFloatingWindow theme else overlayMenuStyle theme++-- | Panel behind menus, dropdowns and floating windows: the theme's offset+-- shadow, then the styled fill and border.+paintMenuPanel :: DrawArena -> Theme -> Style -> Rect -> IO ()+paintMenuPanel da theme style rect@(Rect x y w h) = do+  when (colorA (themeShadow theme) > 0) $+    pushRoundedRect da (Rect (x + menuShadowOffset) (y + menuShadowOffset) w h) (styleCornerRadius style) (themeShadow theme)+  paintStyledRect da style rect++-- | Everything 'paintMenuPanel' can touch for a panel at @rect@: the panel,+-- its offset shadow, and a pixel of antialiasing around both.+menuPanelBounds :: Rect -> Rect+menuPanelBounds (Rect x y w h) = Rect (x - 1) (y - 1) (w + menuShadowOffset + 2) (h + menuShadowOffset + 2)++menuShadowOffset :: Float+menuShadowOffset = 3++-- | Accent marker, 2 pixels wide, at a menu row's left edge, inset 3 pixels+-- from its top and bottom.+paintMenuAccent :: DrawArena -> Theme -> Rect -> IO ()+paintMenuAccent da theme (Rect x y _ h) =+  pushRoundedRect da (Rect x (y + 3) 2 (max 0 (h - 6))) 1 (themeAccent theme)++-- | The vertical and horizontal bars of scroller @wid@ on surface @base@.+-- The one under the pointer or being dragged ('isScrollHover') paints its+-- thumb in 'scrollBarThumbHoverColor'.+paintScrollBars ::+  Context -> DrawArena -> Theme -> Style -> WidgetId -> Maybe ScrollBarLayout -> Maybe ScrollBarLayout -> IO ()+paintScrollBars ctx da theme base = paintScrollBarsConfigured ctx da theme base scroll2DConfig++-- | 'paintScrollBars' honouring 'ScrollOverlay' per axis (painting the thumb+-- without an opaque track pill).+paintScrollBarsConfigured ::+  Context -> DrawArena -> Theme -> Style -> ScrollConfig -> WidgetId -> Maybe ScrollBarLayout -> Maybe ScrollBarLayout -> IO ()+paintScrollBarsConfigured ctx da theme base cfg wid mV mH = do+  hover <- getsInteraction ctx isScrollHover+  let track policy = if policy == ScrollOverlay then colorTransparent else scrollBarTrackColor base theme+      paint dir policy = mapM_ (paintScrollBarLayout da (track policy) (thumb dir))+      thumb dir = case hover of+        Just (hw, hd, _) | hw == wid && hd == dir -> scrollBarThumbHoverColor base theme+        _ -> scrollBarThumbColor base theme+  paint DirColumn (scrollPolicyY cfg) mV+  paint DirRow (scrollPolicyX cfg) mH++-- | Scrollbar track and thumb, each rounded to at most 4px.+paintScrollBarLayout :: DrawArena -> Color -> Color -> ScrollBarLayout -> IO ()+paintScrollBarLayout da trackCol thumbCol layout = do+  when (colorA trackCol > 0) $ pill (sbTrack layout) trackCol+  pill (sbThumb layout) thumbCol+  where+    pill r@(Rect _ _ rw rh) = pushRoundedRect da r (min 4 (min rw rh / 2))+
+ lib/NanoUI/Internal/Frame/Cursor.hs view
@@ -0,0 +1,241 @@+-- | Choose a cursor from active gestures and the solved widget geometry.+module NanoUI.Internal.Frame.Cursor+  ( UiCursorKind (..)+  , uiCursorKind+  , pointerCursorWanted+  , cursorKindIs+  )+where++import Control.Monad (forM)+import Control.Monad.Trans.Maybe (MaybeT (..))+import Data.Foldable (asum, find)+import Data.IORef (readIORef)+import Data.Maybe (fromMaybe, isJust)+import NanoUI.Internal.Context+import NanoUI.Internal.Font (sliderHitBounds)+import NanoUI.Internal.Frame.Hit+import NanoUI.Internal.Frame.Scroll (ScrollBarLayout (..), probeScrollBarHover, scrollBarsFor)+import NanoUI.Internal.Frame.Select (dropdownOwnerAt)+import NanoUI.Internal.Frame.TextArea (isMouseOnTextAreaScrollBarAt)+import NanoUI.Internal.Frame.TextEdit+import NanoUI.Internal.Frame.TextInput (nodeTextFieldGeom, searchClearHit)+import NanoUI.Internal.Frame.Window (windowResizeCursorKind)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (ifM, inArenaRange, (<&&>))+import NanoUI.Internal.Types (Rect (..), V2 (..), rectContains)+import NanoUI.Internal.WidgetText (hasFlag, numericStepperRects, textInputFlagNumeric)+import NanoUI.Internal.Widgets.Custom (mkCustomDrawContext)++-- | Cursor requested by current gestures and hit tests against the solved arena.+-- The backend maps this result to a native cursor shape.+uiCursorKind :: Context -> Input -> IO UiCursorKind+uiCursorKind ctx inp =+  -- The first non-'UiCursorDefault' query wins; later queries do not run.+  -- 'withCursorShape' scopes apply only as a fallback.+  fmap (fromMaybe UiCursorDefault) . runMaybeT . asum . map MaybeT $+    [ selectDropdownCursorKind ctx inp+    , windowResizeCursorKind ctx inp+    , cursorZoneKind ctx inp+    , scrollThumbCursorKind ctx inp+    , textFieldHoverCursorKind ctx inp+    , widgetKind =<< readIORef (ctxActiveId ctx)+    , widgetKind =<< getHotId ctx+    , cursorRegionKind ctx inp+    ]+  where+    widgetKind wid = do+      kind <- cursorKindAt ctx wid (inputMousePos inp) inp+      pure (if kind == UiCursorDefault then Nothing else Just kind)++selectDropdownCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)+selectDropdownCursorKind ctx inp = do+  -- A pick closes the dropdown with the button still down, and the pointer+  -- stays a pointer until it comes up.+  pickHeld <- getsInteraction ctx $ \s ->+    isPointerHeld s && case isPointerRoute s of+      RouteDropdown _ -> True+      _ -> False+  -- Over an open select's dropdown or a focused combo's, also while the+  -- press that opened a select is held.+  onPopup <- if pickHeld then pure True else isJust <$> dropdownOwnerAt ctx (inputMousePos inp)+  pure (if onPopup then Just UiCursorPointer else Nothing)++scrollThumbCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)+scrollThumbCursorKind ctx inp = do+  mDrag <- getsInteraction ctx isScrollDrag+  if heldIn MouseLeft inp && isJust mDrag+    then pure (Just UiCursorGrabbing)+    else do+      -- The bar a press would grab, past modals, floating panels and clips.+      onThumb <- probeScrollBarHover ctx inp >>= \case+        Nothing -> pure False+        Just (wid, dir, _) -> withWidgetNode ctx wid False $ \idx ->+          any (\(d, layout, _) -> d == dir && rectContains (sbThumb layout) (inputMousePos inp))+            <$> scrollBarsFor ctx idx wid+      pure (if onThumb then Just (grabHoverKind True inp) else Nothing)++-- Field well, not the label. Independent of focus and hot. A search field's+-- clear button raises the pointer cursor; everywhere else over a field is text.+-- A drag that another kind of widget holds (a slider's, a divider's) keeps+-- its own cursor over a field; a text selection drag keeps the text cursor.+textFieldHoverCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)+textFieldHoverCursorKind ctx inp = do+  let+    mouse = inputMousePos inp+  active <- readIORef (ctxActiveId ctx)+  othersDrag <-+    if heldIn MouseLeft inp && hashWidgetId active /= 0+      then withWidgetNode ctx active False $ \idx ->+        (\nt -> nt /= NodeTextInput && nt /= NodeTextArea) <$> getNodeType (ctxNodeArena ctx) idx+      else pure False+  mWid <- if othersDrag then pure Nothing else textFieldWidgetAtMouse ctx mouse+  forM mWid $ \wid -> do+    onClear <- searchClearHit ctx wid mouse+    onStepper <- withWidgetNode ctx wid False $ \idx -> numericStepperHit ctx idx mouse+    pure (if onClear || onStepper then UiCursorPointer else UiCursorText)++-- | Whether the pointer is over a numeric field's stepper, which takes the+-- pointer cursor rather than the text cursor.+numericStepperHit :: Context -> NodeIdx -> V2 -> IO Bool+numericStepperHit ctx idx mouse = do+  si <- getStyleIdx (ctxNodeArena ctx) idx+  if not (hasFlag textInputFlagNumeric si)+    then pure False+    else do+      Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx+      let+        (up, down) = numericStepperRects x y w h+      pure (rectContains up mouse || rectContains down mouse)++-- | Cursor for widget @wid@ with the pointer at @mouse@: 'UiCursorDefault'+-- unless the pointer is on the visible part of its node (or a custom widget's+-- callback overrides it while dragged off its node).+cursorKindAt :: Context -> WidgetId -> V2 -> Input -> IO UiCursorKind+cursorKindAt ctx wid mouse inp+  | hashWidgetId wid == 0 = pure UiCursorDefault+  | otherwise =+      ifM (isDisabled ctx wid) (pure UiCursorDefault) $+        -- Resolve the node through the arena's id index rather than building+        -- a type table of every widget for two lookups.+        withWidgetNode ctx wid UiCursorDefault $ \idx -> do+          visible <- nodePointVisible ctx idx mouse+          -- The widget's hit rect, where the pointer is not clipped off it.+          let hitRect = if visible then getPrevRect ctx wid else pure Nothing+              over kind r = if rectContains r mouse then kind else UiCursorDefault+              whenVisible kind = pure (if visible then kind else UiCursorDefault)+          mCursorFn <- (>>= cdrCursor) <$> lookupCustomDrawing ctx wid+          case mCursorFn of+            Just cursorFn -> do+              dragging <- pure (heldIn MouseLeft inp) <&&> ((== wid) <$> readIORef (ctxActiveId ctx))+              if visible || dragging+                then do+                  rect <- getNodeRect (ctxNodeArena ctx) idx+                  cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) wid+                  pure (cursorFn cdc rect mouse)+                else pure UiCursorDefault+            Nothing ->+              getNodeType (ctxNodeArena ctx) idx >>= \case+                NodeButton -> whenVisible UiCursorPointer+                NodeSelect -> maybe UiCursorDefault (over UiCursorPointer) <$> hitRect+                NodeColorPicker -> pure UiCursorPointer+                NodeTextInput ->+                  hitRect >>= \case+                    Nothing -> pure UiCursorDefault+                    Just (Rect x y w h) -> do+                      (field, _) <- nodeTextFieldGeom ctx idx x y w h+                      onStepper <- numericStepperHit ctx idx mouse+                      pure (if onStepper then UiCursorPointer else over UiCursorText field)+                NodeTextArea ->+                  ifM (isMouseOnTextAreaScrollBarAt ctx idx mouse) (pure UiCursorDefault) $+                    maybe UiCursorDefault (over UiCursorText) <$> hitRect+                NodeSlider -> do+                  active <- readIORef (ctxActiveId ctx)+                  if active == wid && heldIn MouseLeft inp+                    then pure UiCursorGrabbing+                    else do+                      let onTrack (Rect x y w h) = rectContains (sliderHitBounds x y w h) mouse+                      maybe UiCursorDefault (\r -> grabDragKind (onTrack r) False inp) <$> hitRect+                NodeContainer -> pure UiCursorDefault+                NodeText -> pure UiCursorDefault+                NodeSpacer -> pure UiCursorDefault+                NodeSeparator -> pure UiCursorDefault+                NodeScrollContainer -> pure UiCursorDefault+                NodeModal -> pure UiCursorDefault+                NodeImage -> pure UiCursorDefault+                NodePanel -> pure UiCursorDefault+                NodeWindow -> pure UiCursorDefault+                NodeBox -> pure UiCursorDefault+                NodePopup -> pure UiCursorDefault+                NodeDrawing -> pure UiCursorDefault+                NodeShader -> pure UiCursorDefault++-- | The cursor of the newest zone the view registered under the pointer+-- ('ctxCursorZones'), or the resize arrow for a whole column-resize drag.+cursorZoneKind :: Context -> Input -> IO (Maybe UiCursorKind)+cursorZoneKind ctx inp = do+  dragging <- getsInteraction ctx isColumnResize+  if heldIn MouseLeft inp && dragging+    then pure (Just UiCursorColResize)+    else do+      let mouse = inputMousePos inp+      fmap snd . find (\(r, _) -> rectContains r mouse) <$> readIORef (ctxCursorZones ctx)++-- | The shape of the innermost+-- 'NanoUI.Internal.Widgets.Cursor.withCursorShape' scope ('ctxCursorRegions')+-- containing the topmost node under the pointer ('nodeOnTopAt'), searching+-- only the floating panel the pointer is confined to, if any.+cursorRegionKind :: Context -> Input -> IO (Maybe UiCursorKind)+cursorRegionKind ctx inp =+  readIORef (ctxCursorRegions ctx) >>= \case+    [] -> pure Nothing+    regions -> do+      let mouse = inputMousePos inp+          covered = foldl' (\n (from, to, _) -> n + (to - from)) 0 regions+      count <- arenaCount (ctxNodeArena ctx)+      -- 'nodeOnTopAt' finds only a node the pointer is on, so when it is on+      -- none of the scopes' nodes no scope can match and the page walk is+      -- skipped. The scopes' nodes are tested only while they are the smaller+      -- set, so a scope around most of the page costs no more than the walk.+      reach <- if 2 * covered <= count then anyScopeNodeAt ctx mouse regions else pure True+      if not reach+        then pure Nothing+        else do+          top <- overlayHitRoot ctx mouse+          mIdx <- nodeOnTopAt ctx top mouse+          -- Outer scopes are listed first, so the last match is innermost.+          pure $ mIdx >>= \idx ->+            foldl' (\found (from, to, kind) -> if inArenaRange from to idx then Just kind else found) Nothing regions++-- | Whether @mouse@ is on the visible part of any node in the scopes' ranges.+anyScopeNodeAt :: Context -> V2 -> [(Int, Int, UiCursorKind)] -> IO Bool+anyScopeNodeAt ctx mouse = go+  where+    go [] = pure False+    go ((from, to, _) : rest) = scan from+      where+        scan !i+          | i >= to = go rest+          | otherwise = ifM (nodePointVisible ctx i mouse) (pure True) (scan (i + 1))++-- | The node drawn on top whose visible part contains @mouse@+-- ('innermostNodeAt'), searching the floating panel @top@ if the pointer is+-- confined to one, else the page. Non-container nodes clip their children,+-- so a miss skips the subtree.+nodeOnTopAt :: Context -> Maybe NodeIdx -> V2 -> IO (Maybe NodeIdx)+nodeOnTopAt ctx top mouse = fmap fst <$> innermostNodeAt ctx top visit ()+  where+    visit () i = do+      hit <- nodePointVisible ctx i mouse+      nt <- getNodeType (ctxNodeArena ctx) i+      pure (hit, if hit || nt == NodeContainer then Just () else Nothing)++-- | Whether 'uiCursorKind' requests the link/button pointer cursor.+pointerCursorWanted :: Context -> Input -> IO Bool+pointerCursorWanted ctx inp = cursorKindIs ctx inp UiCursorPointer++-- | Test the resolved cursor against a requested shape.+cursorKindIs :: Context -> Input -> UiCursorKind -> IO Bool+cursorKindIs ctx inp want = (== want) <$> uiCursorKind ctx inp
+ lib/NanoUI/Internal/Frame/Explain.hs view
@@ -0,0 +1,192 @@+-- | The layout overlay ('NanoUI.Internal.Context.setExplainLayout'): a+-- one-pixel outline just inside every layout node, coloured by depth, and a+-- tint over the node under the pointer with its content box outlined. Each+-- layer's outlines are drawn in that layer, so a floating window hides the+-- outlines of the nodes it covers. If the view marked scopes ('esScopes'),+-- only nodes in them are shown. The overlay only paints; it does not affect+-- layout or hit testing, and none of this runs while it is off.+module NanoUI.Internal.Frame.Explain+  ( explainFrame+  , paintExplainPage+  , paintExplainLayer+  , paintExplainHover+  ) where++import Control.Monad (forM_, when)+import Data.IORef (modifyIORef', readIORef)+import Data.Maybe (mapMaybe)+import Data.Text qualified as T+import NanoUI.Internal.Context+import NanoUI.Internal.Draw (DrawArena, Layer (..), beginLayer, pushRect)+import NanoUI.Internal.Frame.Hit (innermostNodeAt, topmostFloating)+import NanoUI.Internal.Frame.Node (childPaintClip)+import NanoUI.Internal.Input (Input (..))+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (inArenaRange)+import NanoUI.Internal.Id (hashWidgetId)+import NanoUI.Internal.Style (Direction (..), Flow (..), Padding (..), Theme (themeAccent), fadeAlpha, themeSeries)+import NanoUI.Internal.Types (Color, Rect (..), Size (..), V2 (..), rectContains, rectIntersect)++-- | Compute what the overlay draws this frame and damage what changed: every+-- layer's outlines and the hover highlight. The frame's rect diffs track only+-- widgets, and rows and columns can move without one, so the outlines are+-- diffed here. A new hovered node also requests a frame so the view sees it+-- ('getExplainedNode'). Runs after layout, before damage is written.+explainFrame :: Context -> Input -> IO ()+explainFrame ctx@Context {ctxNodeArena = na} inp = do+  scopes <- esScopes <$> readIORef (ctxExplain ctx)+  let mouse = inputMousePos inp+      Size w h = inputWindowSize inp+      window = Rect 0 0 w h+      -- Whether the overlay shows node @idx@: it is in a scope, or there are none.+      inScope idx = null scopes || any (\(from, below) -> inArenaRange from below idx) scopes+      -- Outlines of node @idx@ and its descendants in declaration order,+      -- prepended to @rest@. Children, pinned ones included, are visited in+      -- reverse so the result comes out in order.+      outlines !depth !clip idx rest = do+        !rect <- getNodeRect na idx+        inner <- childClip ctx idx clip rect+        below <- case inner of+          Nothing -> pure rest+          Just c -> foldPlacedChildrenM na idx (\acc ci -> outlines (depth + 1) c ci acc) rest+        pure (if inScope idx then (rect, clip, depth) : below else below)+      -- Node @idx@, at @depth@ in its layer and painted in @clip@, for+      -- 'innermostNodeAt': whether the overlay shows it under the pointer,+      -- and its children's depth and clip. A child can paint outside its row+      -- or column, so every child whose clip is not empty is searched.+      atPointer (!depth, clip) idx = do+        rect <- getNodeRect na idx+        inner <- childClip ctx idx clip rect+        pure (inScope idx && rectContains rect mouse && rectContains clip mouse, (depth + 1,) <$> inner)+  count <- arenaCount na+  -- Layers in paint order: the page, then windows, modals and popups, each+  -- kind in arena order. The page root is node 0, unless the view has no+  -- page and node 0 is a panel.+  floating <- floatingNodesInPaintOrder na+  page <- if count > 0 then not . isFloatingNode <$> getNodeType na 0 else pure False+  let roots = [(pageLayer, 0) | page] ++ [(idx, idx) | idx <- floating]+  layers <- mapM (\(key, root) -> (key,) <$> outlines (0 :: Int) window root []) roots+  route <- getsInteraction ctx isPointerRoute+  hover <- case route of+    RouteLayer _ | count > 0 -> do+      let panelAt nt rest = topmostFloating ctx (== nt) (`rectContains` mouse) >>= maybe rest (pure . Just)+      top <- foldr panelAt (pure Nothing) [NodePopup, NodeModal, NodeWindow]+      found <- innermostNodeAt ctx top atPointer (0 :: Int, window)+      traverse (\(idx, (depth, clip)) -> (,clip) <$> describeNode na depth idx) found+    -- Any other route means a dropdown or the text-edit menu has the pointer.+    _ -> pure Nothing+  ExplainState {esLayers = prevLayers, esHover = prevHover} <- readIORef (ctxExplain ctx)+  let changed (a : as) (b : bs)+        | a == b = changed as bs+        | otherwise = a : b : changed as bs+      changed as bs = as ++ bs+      shown (rect, clip, _) = rectIntersect clip rect+      highlight (node, clip) = rectIntersect clip (explainedRect node)+  mapM_ (damageRect ctx) (mapMaybe shown (changed (concatMap snd prevLayers) (concatMap snd layers)))+  when (hover /= prevHover) $ do+    mapM_ (damageRect ctx) (prevHover >>= highlight)+    mapM_ (damageRect ctx) (hover >>= highlight)+    markDirty ctx+  modifyIORef' (ctxExplain ctx) (\es -> es {esLayers = layers, esHover = hover})++-- | The 'esLayers' key for the page's outlines. It cannot be 0, since node 0+-- can be a floating panel's root.+pageLayer :: Int+pageLayer = -1++-- | Draw the outlines 'explainFrame' found for the page.+paintExplainPage :: Context -> IO ()+paintExplainPage ctx = paintExplainLayer ctx pageLayer++-- | Draw the outlines 'explainFrame' found for the floating panel rooted at @root@.+paintExplainLayer :: Context -> NodeIdx -> IO ()+paintExplainLayer ctx@Context {ctxDrawArena = da} root = do+  colour <- depthColor <$> getTheme ctx+  layers <- esLayers <$> readIORef (ctxExplain ctx)+  forM_ (lookup root layers) $ mapM_ $ \(rect, clip, depth) -> outline da clip rect (colour depth)++-- | Tint the node under the pointer and outline its content box, above+-- everything else.+paintExplainHover :: Context -> IO ()+paintExplainHover ctx@Context {ctxDrawArena = da} = do+  hover <- esHover <$> readIORef (ctxExplain ctx)+  forM_ hover $ \(ExplainedNode {explainedDepth = depth, explainedRect = rect@(Rect x y w h), explainedPadding = Padding l r t b}, clip) -> do+    col <- (`depthColor` depth) <$> getTheme ctx+    beginLayer da LayerChrome+    forM_ (rectIntersect clip rect) $ \tint -> pushRect da tint (fadeAlpha col 0x40)+    when (l > 0 || r > 0 || t > 0 || b > 0) $+      outline da clip (Rect (x + l) (y + t) (max 0 (w - l - r)) (max 0 (h - t - b))) col++-- | The clip node @idx@'s children paint in, given the node paints in @clip@+-- at @rect@ ('childPaintClip'). 'Nothing' when no child can show.+childClip :: Context -> NodeIdx -> Rect -> Rect -> IO (Maybe Rect)+childClip ctx idx clip rect = do+  nt <- getNodeType (ctxNodeArena ctx) idx+  maybe (Just clip) (rectIntersect clip) <$> childPaintClip ctx idx nt rect++-- | The overlay's description of node @idx@, at @depth@ in its layer.+describeNode :: NodeArena -> Int -> NodeIdx -> IO ExplainedNode+describeNode na depth idx = do+  a <- arenaArrays na+  nt <- readTagEnum a idx TagNodeType+  wid <- getWidgetId na idx+  rect <- getNodeRect na idx+  pad <- getPadding na idx+  wAx <- readAxisSizing a idx True+  hAx <- readAxisSizing a idx False+  gap <- readStyle a idx StyleGap+  dir <- readTagEnum a idx TagDirection+  flow <- readTagEnum a idx TagFlow+  pinned <- readTagEnum a idx TagPinned+  pin <- if pinned then Just <$> (V2 <$> readStyle a idx StylePinX <*> readStyle a idx StylePinY) else pure Nothing+  mode <- readTagEnum a idx TagPointer+  let direction = case dir of DirRow -> Row; DirColumn -> Column+  pure+    ExplainedNode+      { explainedKind = nodeKind nt direction flow+      , explainedWidget = if hashWidgetId wid == 0 then Nothing else Just wid+      , explainedDepth = depth+      , explainedRect = rect+      , explainedPadding = pad+      , explainedWidth = axisSizing wAx+      , explainedHeight = axisSizing hAx+      , explainedMin = V2 (axMin wAx) (axMin hAx)+      , explainedMax = V2 (axMax wAx) (axMax hAx)+      , explainedGap = gap+      , explainedDirection = direction+      , explainedFlow = flow+      , explainedPin = pin+      , explainedPointer = mode+      }++-- | A node's type without the @Node@ prefix, plus a container's flow: its+-- direction, @layered@, or its direction followed by @wrap@.+nodeKind :: NodeType -> Direction -> Flow -> T.Text+nodeKind nt dir flow+  | not (isContainerNode nt) = kind+  | otherwise = kind <> ", " <> case flow of+      Layered -> "layered"+      Wrap -> direction <> ", wrap"+      Line -> direction+  where+    kind = T.pack (drop 4 (show nt))+    direction = T.toLower (T.pack (show dir))++-- | Outline colour for a depth, cycling through the theme's series colours.+depthColor :: Theme -> Int -> Color+depthColor theme depth = case themeSeries theme of+  [] -> themeAccent theme+  series -> series !! (depth `rem` length series)++-- | A one-pixel border just inside @rect@, cut to @clip@.+outline :: DrawArena -> Rect -> Rect -> Color -> IO ()+outline da clip (Rect x y w h) col =+  when (w > 0 && h > 0) $+    forM_ edges $ \edge -> forM_ (rectIntersect clip edge) $ \r -> pushRect da r col+  where+    edges =+      [ Rect x y w 1+      , Rect x (y + h - 1) w 1+      , Rect x (y + 1) 1 (h - 2)+      , Rect (x + w - 1) (y + 1) 1 (h - 2)+      ]
+ lib/NanoUI/Internal/Frame/Hit.hs view
@@ -0,0 +1,330 @@+{-# 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)
+ lib/NanoUI/Internal/Frame/Input.hs view
@@ -0,0 +1,679 @@+-- | 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'
+ lib/NanoUI/Internal/Frame/Node.hs view
@@ -0,0 +1,129 @@+-- | Per-node queries shared by the paint, span, scroll and hit passes: the+-- font a node renders and measures in, a scroll node's fields, the clip for+-- a node's children, and the room a widget's adornments take.+module NanoUI.Internal.Frame.Node+  ( resolveFontFor+  , nodeFontNative+  , packedTextFont+  , resolveTextFont+  , nodeFontMetrics+  , readScrollNode+  , childPaintClip+  , nodeAdornmentInsets+  ) where++import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Context (Context (..), nodeTheme)+import NanoUI.Internal.Draw.Types (TextFont (..))+import NanoUI.Internal.Font (FontMetrics, isDefaultNodeFont, measureTextIO, tabularFontMetrics)+import NanoUI.Internal.Layout.ScrollGeometry+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Solve (scrollBarSlotOf)+import NanoUI.Internal.Style (FontVariant (..), TextDecoration (..), resolveFontSize)+import NanoUI.Internal.Types (Rect (..))+import NanoUI.Internal.WidgetText (containerFlagClip, hasFlag, panelSurface, textNodeFontStyle, textNodeFontTabular, textNodeFontVariant, textNodeFontWeight)++-- | Font for a node of type @nt@ with an explicit size and packed style: the+-- metrics, whether the host returned a native styled face (paint then skips+-- synthetic weight and slant), and the matching measure. Base sans and mono+-- resolve to the pre-read metrics; everything else defers to the host+-- resolver. INLINE: it runs for every text-bearing node painted, and inlining+-- lets the result triple fold away at each call site (measured: 30 MB less+-- allocation over the 3000-frame profile).+--+-- Only the font bits of the style are read ('nodeFontBits'): a label's or+-- field's whole style, a button's or select's label font.+{-# INLINE resolveFontFor #-}+resolveFontFor :: Context -> NodeType -> Float -> Word64 -> IO (FontMetrics, Bool, Text -> IO (Float, Float))+resolveFontFor ctx nt rawSize packed = do+  let !size = resolveFontSize (ctxFontSize ctx) rawSize+      font@(TextFont _ variant weight style _ tabular) =+        packedTextFont size (nodeFontBits nt packed)+  (fm, native) <- resolveTextFont ctx font+  let measure+        | tabular = measureTextIO fm+        | not (isDefaultNodeFont size weight style variant) = ctxResolveMeasure ctx size weight style variant+        | variant == FontMono = measureTextIO fm+        | otherwise = ctxMeasureText ctx+  pure (fm, native, measure)++-- | Whether the host draws the weight and slant of the font a text node of+-- @size@ and packed style @si@ is set in ('resolveFontFor'), for paint, which+-- takes the metrics from the span cache.+{-# INLINE nodeFontNative #-}+nodeFontNative :: Context -> Float -> Word64 -> IO Bool+nodeFontNative ctx size si = snd <$> resolveTextFont ctx (packedTextFont size si)++-- | The font of a text node of @size@ and packed style @si@.+{-# INLINE packedTextFont #-}+packedTextFont :: Float -> Word64 -> TextFont+packedTextFont size si =+  TextFont size (textNodeFontVariant si) (textNodeFontWeight si) (textNodeFontStyle si) DecorationNone (textNodeFontTabular si)++-- | The font a @DrawTextStyled@ op names, and whether the host draws its+-- weight and slant natively. Base sans and mono resolve to the pre-read+-- metrics; everything else defers to the host resolver.+{-# INLINE resolveTextFont #-}+resolveTextFont :: Context -> TextFont -> IO (FontMetrics, Bool)+resolveTextFont ctx (TextFont rawSize variant weight style _ tabular) = do+  let !size = resolveFontSize (ctxFontSize ctx) rawSize+  (fm0, native) <-+    if isDefaultNodeFont size weight style variant+      then pure (if variant == FontMono then ctxMonoFontMetrics ctx else ctxFontMetrics ctx, False)+      else ctxResolveFont ctx size weight style variant+  pure (if tabular then tabularFontMetrics fm0 else fm0, native)++-- | Metrics of the font node @idx@ is styled with.+nodeFontMetrics :: Context -> NodeIdx -> IO FontMetrics+nodeFontMetrics ctx idx = do+  nt <- getNodeType (ctxNodeArena ctx) idx+  si <- getStyleIdx (ctxNodeArena ctx) idx+  size <- getNodeFontSize (ctxNodeArena ctx) idx+  (fm, _, _) <- resolveFontFor ctx nt size si+  pure fm++{-# INLINE readScrollNode #-}+readScrollNode :: NodeArena -> NodeIdx -> IO ScrollNode+readScrollNode na idx = do+  si <- getStyleIdx na idx+  slot <- scrollBarSlotOf na idx+  dir <- getDirection na idx+  pad <- getPadding na idx+  contentMain <- getNodeValue na idx+  contentW <- getScrollContentW na idx+  let cfg = decodeScrollConfig si+  pure $! ScrollNode slot cfg (si /= 0 && scrollConfigNative2D cfg) dir pad contentMain contentW++-- | The clip for the children of node @idx@ (type @nt@, placed at @rect@),+-- matching "NanoUI.Internal.Frame.Paint": a scroller's viewport, a panel's+-- inside-border rect, or the node's own rect. Plain containers (row, column,+-- grid) do not clip and return 'Nothing', unless marked 'containerFlagClip'.+childPaintClip :: Context -> NodeIdx -> NodeType -> Rect -> IO (Maybe Rect)+childPaintClip ctx idx nt rect@(Rect x y w h) = case nt of+  NodeContainer -> (\si -> if hasFlag containerFlagClip si then Just rect else Nothing) <$> getStyleIdx (ctxNodeArena ctx) idx+  NodeScrollContainer -> (\sn -> Just (scrollNodeViewport sn x y w h)) <$> readScrollNode (ctxNodeArena ctx) idx+  NodePanel -> do+    si <- getStyleIdx (ctxNodeArena ctx) idx+    (\theme -> Just (borderContentClip (panelSurface theme si) rect)) <$> nodeTheme ctx idx+  _ -> pure (Just rect)++-- | How far the adornment rows ('adornRows') of widget @idx@, whose left edge+-- is at @x@ and which is @w@ wide, reach in from its left edge and from its+-- right, each with the widget's gap beyond them: the room its text keeps+-- clear of them, 0 on a side without any. Every button and field asks, most+-- without adornments, so that check is inlined and the rest is not.+{-# INLINE nodeAdornmentInsets #-}+nodeAdornmentInsets :: NodeArena -> NodeIdx -> Float -> Float -> IO (Float, Float)+nodeAdornmentInsets na idx x w = do+  kids <- getFirstChild na idx+  if kids < 0 then pure (0, 0) else adornmentRowInsets na idx x w++{-# NOINLINE adornmentRowInsets #-}+adornmentRowInsets :: NodeArena -> NodeIdx -> Float -> Float -> IO (Float, Float)+adornmentRowInsets na idx x w = do+  AdornRows li _ ti _ _ <- adornRows na idx+  a <- arenaArrays na+  gap <- readStyle a idx StyleGap+  let reach ci edge = if ci < 0 then pure 0 else (\r -> edge r + gap) <$> getNodeRect na ci+  (,) <$> reach li (\(Rect cx _ cw _) -> cx + cw - x) <*> reach ti (\(Rect cx _ _ _) -> x + w - cx)
+ lib/NanoUI/Internal/Frame/Paint.hs view
@@ -0,0 +1,527 @@+-- The recursive walk (paintNodeWithEnv -> lowerNodeVisible -> per-node+-- painters -> walkChildrenWithOccluders) goes through NOINLINE seams, and+-- heavy painters stay out of line, so no single binding holds the whole+-- paint body inside the loop. That blew up compilation under+-- -fspecialise-aggressively with LLVM; the flags below also guard against it.+{-# OPTIONS_GHC -fasm -fno-specialise-aggressively #-}++-- | Walk solved nodes and emit geometry, respecting clips, layers, and paint+-- scopes. Widget chrome is painted in "NanoUI.Internal.Frame.Paint.Widgets".+module NanoUI.Internal.Frame.Paint+  ( lowerShapes+  , walkChildren+  ) where++import Control.Monad (forM_, unless, when)+import Data.Bits (complement, (.&.))+import Data.IORef (readIORef)+import Data.Maybe (fromMaybe, isJust)+import Data.Primitive.PrimArray+  ( PrimArray+  , emptyPrimArray+  , indexPrimArray+  , newPrimArray+  , readPrimArray+  , shrinkMutablePrimArray+  , sizeofPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Primitive.SmallArray (SmallArray)+import qualified Data.Text as T+import Data.Word (Word32, Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Draw+import NanoUI.Internal.Font (ScrollBarSlot (..), fmLineHeight)+import NanoUI.Internal.Frame.Chrome+import NanoUI.Internal.Frame.Node (nodeFontNative, readScrollNode, resolveTextFont)+import NanoUI.Internal.Frame.Paint.Widgets (PaintEnv (..), buildPaintEnv, paintTextAreaNode, paintTextInputNode, paintWidget)+import NanoUI.Internal.Layout.ScrollGeometry (ScrollNode (..), borderContentClip, scrollBare, scrollNodeBars, scrollNodeViewport)+import NanoUI.Internal.Frame.Spans (textNodeSpanEntry)+import NanoUI.Internal.Id (hashWidgetId)+import NanoUI.Internal.Image (fadeBy, withLookDraw)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Shader (ShaderCapabilities (..), ShaderEffectEntry (..), ShaderNodeEntry (..))+import NanoUI.Internal.Style hiding (fontSize)+import NanoUI.Internal.Types (Color (..), ImageId (..), Rect (..), V2 (..), colorA, colorRGBA, rectInflate)+import NanoUI.Internal.Widgets.ColorPicker (colorPickerPartRect)+import NanoUI.Internal.Widgets.Custom (mkCustomDrawContext)+import NanoUI.Internal.WidgetText++lowerShapes :: Context -> IO ()+lowerShapes ctx = do+  count <- arenaCount (ctxNodeArena ctx)+  when (count > 0) $ do+    occluders <- collectFloatingOccluders ctx+    buildPaintEnv ctx occluders >>= (`paintNodeWithEnv` 0)++-- | Rects of opaque floating panels, inset past their rounded border, that+-- hide whatever lies fully behind them, as @x0, y0, x1, y1@ runs. Frames+-- without floating nodes skip the arena walk.+collectFloatingOccluders :: Context -> IO (PrimArray Float)+collectFloatingOccluders ctx@Context {ctxNodeArena = na} = do+  floating <- floatingNodeCount na+  if floating <= 0+    then pure emptyPrimArray+    else do+      buf <- newPrimArray (floating * 4)+      n <- foldClassNodesM na FloatingNodes (addOccluder buf) 0+      shrinkMutablePrimArray buf (n * 4)+      unsafeFreezePrimArray buf+  where+    addOccluder buf !n idx = do+      nt <- getNodeType na idx+      opaque <- (\theme -> colorA (styleBg (floatingSurface theme nt)) == 255) <$> nodeTheme ctx idx+      if not opaque+        then pure n+        else do+          Rect x y w h <- getNodeRect na idx+          if not (w > 6 && h > 6)+            then pure n+            else do+              let !o = n * 4+                  Rect ox oy ow oh = rectInflate (-3) (Rect x y w h)+              writePrimArray buf o ox+              writePrimArray buf (o + 1) oy+              writePrimArray buf (o + 2) (ox + ow)+              writePrimArray buf (o + 3) (oy + oh)+              pure (n + 1)++-- | Clip + occluder short-circuit, then lower the node. NOINLINE so the+-- recursive container walk never exposes the dispatch below to the simplifier.+--+-- The clip test widens the node by 'paintOverhang': a clip frame starts from a+-- blank backdrop, so a node whose focus ring reaches into the clip must repaint+-- even when its own rect stays outside.+{-# NOINLINE paintNodeWithEnv #-}+paintNodeWithEnv :: PaintEnv -> NodeIdx -> IO ()+paintNodeWithEnv env idx = do+  a <- arenaArrays (peNodeArena env)+  let !geom = naArrGeom a+      !gOff = idx * geomStride+      !clip = daCurrentClip (peDrawArena env)+  !x <- readPrimArray geom gOff+  !y <- readPrimArray geom (gOff + 1)+  !w <- readPrimArray geom (gOff + 2)+  !h <- readPrimArray geom (gOff + 3)+  !cx <- readPrimArray clip 0+  !cy <- readPrimArray clip 1+  !cw <- readPrimArray clip 2+  !ch <- readPrimArray clip 3+  if w <= 0 || h <= 0 || not (rectVisible env x y w h paintOverhang paintOverhang cx cy cw ch)+    then+      if peHasEffects env && w > 0 && h > 0+        then paintSkippedWithEffects env idx x y w h cx cy cw ch+        else do+          pinnedBelow <- readTagEnum a idx TagPinnedBelow+          when pinnedBelow $ do+            nt <- readTagEnum a idx TagNodeType+            when (nt == NodeContainer) $ do+              si <- readStyleIdx a idx+              unless (hasFlag containerFlagClip si) $+                walkChildrenWithOccluders env idx+    else do+      nt <- readTagEnum a idx TagNodeType+      case nt of+        NodeSpacer+          | hashWidgetId (peFocusRing env) == 0 -> pure ()+        NodeModal+          | hashWidgetId (peFocusRing env) == 0 -> pure ()+        NodeWindow+          | hashWidgetId (peFocusRing env) == 0 -> pure ()+        NodePopup+          | hashWidgetId (peFocusRing env) == 0 -> pure ()+        NodeContainer+          | hashWidgetId (peFocusRing env) == 0 -> do+              scope <- (.&. complement 2) <$> readPrimArray (naArrScope a) idx+              si <- readStyleIdx a idx+              if scope == peScope env && si == 0+                then do+                  mBuild <- lookupCustomDrawingAt (peContext env) idx+                  case mBuild of+                    Nothing -> walkChildrenWithOccluders env idx+                    Just _ -> lowerNodeVisible env idx nt (Rect x y w h)+                else lowerScoped env idx nt (Rect x y w h)+        _ -> lowerScoped env idx nt (Rect x y w h)++-- | Handle a culled node on frames that contain Tier 2 shader effect+-- containers: re-check effect containers using their bleed margin+-- ('seeMargin'), and otherwise keep walking pinned descendants.+{-# NOINLINE paintSkippedWithEffects #-}+paintSkippedWithEffects ::+  PaintEnv -> NodeIdx -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> IO ()+paintSkippedWithEffects env idx !x !y !w !h !cx !cy !cw !ch = do+  nt <- getNodeType (peNodeArena env) idx+  when (nt == NodeContainer) $ do+    si <- getStyleIdx (peNodeArena env) idx+    paintedEffect <-+      if hasFlag containerFlagShaderEffect si+        then do+          mEntry <- lookupShaderEffectAt (peContext env) idx+          case mEntry of+            Just entry -> do+              let V2 mx my = seeMargin entry+                  !ox = max paintOverhang mx+                  !oy = max paintOverhang my+              if rectVisible env x y w h ox oy cx cy cw ch+                then lowerScoped env idx nt (Rect x y w h) >> pure True+                else pure False+            Nothing -> pure False+        else pure False+    unless paintedEffect $ do+      pinnedBelow <- hasPinnedBelow (peNodeArena env) idx+      when (pinnedBelow && not (hasFlag containerFlagClip si)) $+        walkChildrenWithOccluders env idx++-- | Whether a node's box expanded by @(ox, oy)@ is visible within the clip,+-- not covered by an opaque floating occluder, and meets at least one active+-- damage piece.+{-# INLINE rectVisible #-}+rectVisible ::+  PaintEnv -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Bool+rectVisible env !x !y !w !h !ox !oy !cx !cy !cw !ch =+  let !l = max (x - ox) cx+      !t = max (y - oy) cy+      !r = min (x + w + ox) (cx + cw)+      !b = min (y + h + oy) (cy + ch)+      occluded = anyRun (peOccluders env) $ \x0 y0 x1 y1 -> l >= x0 && t >= y0 && r <= x1 && b <= y1+      missesPieces =+        sizeofPrimArray (pePieces env) > 0+          && not (anyRun (pePieces env) $ \x0 y0 x1 y1 -> l < x1 && t < y1 && r > x0 && b > y0)+   in r > l && b > t && not occluded && not missesPieces++-- | Enter the node's theme scope (if different from 'peScope') and dispatch.+{-# INLINE lowerScoped #-}+lowerScoped :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()+lowerScoped env idx nt !rect = do+  scope <- (.&. complement 2) <$> getNodeScope (peNodeArena env) idx+  if scope == peScope env+    then lowerNodeVisible env idx nt rect+    else do+      theme <- scopeTheme (peContext env) scope+      lowerNodeVisible env {peTheme = theme, peScope = scope} idx nt rect++-- | Whether @p@ holds for any of the @x0, y0, x1, y1@ runs of @rects@.+{-# INLINE anyRun #-}+anyRun :: PrimArray Float -> (Float -> Float -> Float -> Float -> Bool) -> Bool+anyRun rects p = go 0+  where+    at = indexPrimArray rects+    go !o = o < sizeofPrimArray rects && (p (at o) (at (o + 1)) (at (o + 2)) (at (o + 3)) || go (o + 4))++-- | How far a node may paint outside its rect: focus rings sit 2px out with a+-- 1.5px stroke, and a 'ScrollBarWindow' track sits up to 7px past the body's+-- right/bottom edge inside the window padding.+paintOverhang :: Float+paintOverhang = 8++-- | Explicit per-node-type dispatch. Kept NOINLINE and thin so the recursive+-- loop never sees the branch bodies.+{-# NOINLINE lowerNodeVisible #-}+lowerNodeVisible :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()+lowerNodeVisible env idx nt rect = do+  case nt of+    NodeContainer -> paintContainerNode env idx rect+    NodePanel -> paintPanelNode env idx rect+    NodeScrollContainer -> paintScrollContainerNode env idx rect+    NodeText -> paintTextNode env idx rect+    NodeSeparator -> paintSeparatorNode env rect+    NodeTextInput -> paintTextInputNode env idx rect >> paintWidgetChildren env idx rect+    NodeTextArea -> paintTextAreaNode env idx rect+    NodeSpacer -> pure ()+    NodeModal -> pure ()+    NodeWindow -> pure ()+    NodePopup -> pure ()+    NodeBox -> paintBoxNode env idx rect+    NodeImage -> paintImageNode env idx rect+    NodeDrawing -> paintDrawingNode env idx rect+    NodeShader -> paintShaderNode env idx rect+    NodeButton -> paintWidget env idx nt rect >> paintWidgetChildren env idx rect+    NodeSlider -> paintWidget env idx nt rect >> paintWidgetChildren env idx rect+    NodeSelect -> paintWidget env idx nt rect >> paintWidgetChildren env idx rect+    NodeColorPicker -> paintWidget env idx nt rect >> paintWidgetChildren env idx rect+  unless (hashWidgetId (peFocusRing env) == 0) $+    paintFocusRing env idx nt rect++-- | A widget's children, its adornments or content, clipped to it. Most+-- widgets have none, so only that check is inlined.+{-# INLINE paintWidgetChildren #-}+paintWidgetChildren :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintWidgetChildren env idx rect = do+  kids <- getFirstChild (peNodeArena env) idx+  unless (kids < 0) $ paintClippedChildren env idx rect++{-# NOINLINE paintClippedChildren #-}+paintClippedChildren :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintClippedChildren env idx rect = withClip (peDrawArena env) rect (walkChildrenWithOccluders env idx)++-- | Accent ring around the widget holding keyboard focus. Text fields and+-- selects already swap in an accent border while focused, so they get none.+-- Rows ('buttonFlagRow') fill their scroller edge to edge, so their ring sits+-- just inside the row; colour picker parts ring the square or bar they draw.+{-# NOINLINE paintFocusRing #-}+paintFocusRing :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()+paintFocusRing env idx nt rect = do+  wid <- getWidgetId (peNodeArena env) idx+  when (wid == peFocusRing env && nt /= NodeTextInput && nt /= NodeTextArea && nt /= NodeSelect) $ do+    target <-+      if nt == NodeColorPicker+        then colorPickerPartRect (peNodeArena env) idx rect+        else pure rect+    isInset <-+      if nt == NodeScrollContainer+        then pure True+        else if nt == NodeButton then (== ButtonRow) . buttonKindOf <$> getStyleIdx (peNodeArena env) idx else pure False+    let (ring, radius)+          | isInset = (rectInflate (-1) target, 0)+          | otherwise = (rectInflate 2 target, 4)+    pushRoundedStroke (peDrawArena env) ring radius 1.5 (themeFocusRing (peTheme env))++paintContainerNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintContainerNode env@PaintEnv {peContext = ctx, peDrawArena = da} idx rect = do+  si <- getStyleIdx (peNodeArena env) idx+  -- A tab strip's rule, track or contained body, under its children.+  case tabChromeDecode si of+    (TabChromeNone, _, _) -> pure ()+    _ -> paintTabChrome da (peTheme env) si rect+  if hasFlag containerFlagShaderEffect si+    then paintEffectContainer env idx rect si+    else+      if hasFlag containerFlagClip si+        then paintClippedChildren env idx rect+        else walkChildrenWithOccluders env idx+  wid <- getWidgetId (peNodeArena env) idx+  mBuild <- lookupCustomDrawingAt ctx idx+  forM_ mBuild $ \CustomDrawingEntry {cdrBuild = build} -> do+    cdc <- mkCustomDrawContext ctx (peFontMetrics env) wid+    emitDrawingOps env rect (build cdc rect)++{-# NOINLINE paintEffectContainer #-}+paintEffectContainer :: PaintEnv -> NodeIdx -> Rect -> Word64 -> IO ()+paintEffectContainer env@PaintEnv {peContext = ctx, peDrawArena = da} idx rect si = do+  caps <- getShaderCapabilities ctx+  mEntry <- lookupShaderEffectAt ctx idx+  recOps <- readIORef (daRecordOps da)+  let drawKids =+        if hasFlag containerFlagClip si+          then paintClippedChildren env idx rect+          else walkChildrenWithOccluders env idx+      drawKidsWithSvg entry = case (recOps, seeSvgOpacity entry) of+        (True, Just op) -> withRecordOpacity da op drawKids+        _ -> drawKids+  case (capNodeEffects caps, mEntry) of+    (True, Just entry) -> do+      tok <- beginEffectSpan da rect (seeMargin entry)+      drawKidsWithSvg entry+      endEffectSpan da tok (seePasses entry)+    (_, Just entry) -> drawKidsWithSvg entry+    _ -> drawKids++-- | A drawing's ops clipped to its rect, in the env's default font. Image+-- ops naming a registered 'ImageId' draw from the atlas.+emitDrawingOps :: PaintEnv -> Rect -> SmallArray DrawOp -> IO ()+emitDrawingOps env rect ops = withClip (peDrawArena env) rect (emitOps env ops)++-- | Ops in the env's default font, unclipped. NOINLINE: inlined into its+-- caller, the clip action would capture these arguments and allocate more+-- per drawing.+{-# NOINLINE emitOps #-}+emitOps :: PaintEnv -> SmallArray DrawOp -> IO ()+emitOps env@PaintEnv {peDrawArena = da} = emitDrawOps da (peFontMetrics env) (ctxFontSize ctx) (resolveTextFont ctx) (atlasImageUv ctx)+  where+    ctx = peContext env++-- | The atlas texture and UV bounds of a registered image.+atlasImageUv :: Context -> Int -> IO (Maybe (Int, (Float, Float, Float, Float)))+atlasImageUv ctx tid = fmap (atlasTextureId,) <$> lookupImageUv ctx (ImageId tid)++paintPanelNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintPanelNode env@PaintEnv {peDrawArena = da} idx rect = do+  style <- panelSurface (peTheme env) <$> getStyleIdx (peNodeArena env) idx+  paintStyledRect da style rect+  withClip da (borderContentClip style rect) $ walkChildrenWithOccluders env idx++{-# NOINLINE paintScrollContainerNode #-}+paintScrollContainerNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintScrollContainerNode env idx rect@(Rect x y w h) = do+  let ctx = peContext env+      arena = peNodeArena env+      da = peDrawArena env+      tm = peTheme env+  sn <- readScrollNode arena idx+  -- A bare scroller paints nothing at all: it only lends its clip and+  -- offset, so whatever sits behind it (window, panel) keeps showing+  -- through. Grow×grow scrollers (page-level) keep no well so they blend+  -- into the page surface. A full frame lays that surface down before the+  -- view, but on clip frames (scrolling, resize) the strip vacated by+  -- scrolled content has no covering command and the retained texture would+  -- show stale pixels, a ghost of a previous scroll position. Paint the full+  -- rect with the page colour when the frame's clear does not already cover+  -- it ('drawClear'); the clip backdrop paints it on the frames that cut the+  -- view to damage.+  unless (scrollBare (snConfig sn)) $ do+    surface <- fmap (floatingSurface tm) <$> floatingAncestor ctx idx+    let inFloating = isJust surface+    wTag <- axTag <$> getWidthSizing arena idx+    hTag <- axTag <$> getHeightSizing arena idx+    if wTag == SizingGrow && hTag == SizingGrow+      then do+        let bg = maybe (pageBackground tm) styleBg surface+        -- A full frame clears to the page surface laid over the window+        -- colour before the view ('drawClear'). Drawn first, in that same+        -- opaque colour, the backdrop would only fill the same pixels again:+        -- a whole-window blend on every continuous frame. Anything drawn+        -- before it (a panel, a card, a layer below), a scope's other page+        -- colour or a translucent one still needs it, as clip frames do.+        redundant <-+          if inFloating || colorA bg /= 255+            then pure False+            else do+              full <- readIORef (ctxPaintFull ctx)+              drawn <- drawnVertexCount da+              clear <- getDrawClear da+              pure (full && drawn == 0 && bg == clear)+        unless redundant $ pushRect da rect bg+      else do+        let well = (fromMaybe (themeInput tm) surface) {styleCornerRadius = 0}+        paintStyledRect da well rect+  withClip da (scrollNodeViewport sn x y w h) $ walkChildrenWithOccluders env idx+  paintScrollChrome env idx sn rect++-- | A scroll container's scrollbars, drawn one layer above the content so+-- they stay on top of it.+paintScrollChrome :: PaintEnv -> NodeIdx -> ScrollNode -> Rect -> IO ()+paintScrollChrome env@PaintEnv {peDrawArena = da, peTheme = theme} idx sn (Rect x y w h) = do+  wid <- getWidgetId (peNodeArena env) idx+  V2 offX offY <- getScrollOffset2D (peContext env) wid+  case scrollNodeBars sn x y w h offX offY of+    (Nothing, Nothing) -> pure ()+    (mV, mH) -> do+      layer <- currentLayer da+      beginLayer da (if layer == LayerOverlay then LayerChrome else LayerContent)+      let base = case snSlot sn of+            ScrollBarWindow -> themeFloatingWindow theme+            _ -> themeInput theme+      paintScrollBarsConfigured (peContext env) da theme base (snConfig sn) wid mV mH+      beginLayer da layer++-- | A text node's lines, drawn with the metrics its span cache entry prepared+-- for each line when it was laid out.+{-# NOINLINE paintTextNode #-}+paintTextNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintTextNode env@PaintEnv {peNodeArena = arena, peDrawArena = da} idx rect@(Rect x y w h) = do+  si <- getStyleIdx arena idx+  forM_ (tableStripeColor (peTheme env) si) (pushRect da rect)+  raw <- getText arena idx+  unless (T.null raw) $ do+    e <- textNodeSpanEntry (peContext env) idx x y w h+    fontSize <- getNodeFontSize arena idx+    native <- nodeFontNative (peContext env) fontSize si+    let !deco = textNodeTextDecoration si+        !weight = if native then WeightNormal else textNodeFontWeight si+        !style = if native then FontStyleNormal else textNodeFontStyle si+        draw (Rect tx ty _ _, line, spanFg, _) prepared =+          unless (T.null line) $+            pushPreparedTextStyled da prepared weight style deco tx ty line spanFg+    case sceLines e of+      SpanWrapped lns -> do+        -- Only the lines that reach the clip draw, so a label taller than+        -- its viewport costs the lines it shows. 'placeSpanLines' makes one+        -- span per line, top down: skip the lines wholly above the clip and+        -- stop at the first one below it. The slack is the one the glyph+        -- walks allow for ink outside the line box.+        Rect _ clipY _ clipH <- currentClip da+        let !slack = glyphSlackLines * fmLineHeight (sceFont e)+            !top = clipY - slack+            !bottom = clipY + clipH + slack+            wrapped (s@(Rect _ ty _ th, _, _, _) : ss) ((_, prepared) : rest)+              | ty > bottom = pure ()+              | ty + th < top = wrapped ss rest+              | otherwise = draw s prepared >> wrapped ss rest+            wrapped _ _ = pure ()+        wrapped (sceSpans e) lns+      SpanSingle _ prepared -> mapM_ (`draw` prepared) (sceSpans e)++paintSeparatorNode :: PaintEnv -> Rect -> IO ()+paintSeparatorNode env (Rect x y w h) =+  pushRect (peDrawArena env) line (themeSeparator (peTheme env))+  where+    line+      | w >= h = Rect x (y + (h - 1) / 2) w 1+      | otherwise = Rect (x + (w - 1) / 2) y 1 h++paintBoxNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintBoxNode env idx rect = do+  si <- getStyleIdx (peNodeArena env) idx+  -- styleIdx holds RGBA Word32 bits; see `box` in NanoUI.Widgets.+  pushRect (peDrawArena env) rect (Color (fromIntegral si :: Word32))++-- | An image node. Without a look it is stretched over its rect, tinted by+-- its font colour. With a look ('getImageNode') it is fitted, cropped,+-- zoomed, faded and rotated ('withLookDraw'), and clipped to its rect when+-- rotated. Disabled images fade like disabled widget colours; unregistered+-- ones paint the accent. The image's size and UVs come from one atlas lookup.+paintImageNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintImageNode env@PaintEnv {peDrawArena = da} idx rect = do+  let na = peNodeArena env+      fade = if peScope env .&. 1 /= 0 then 1 - themeDisabledFade (peTheme env) else 1+  tid <- getImageId na idx+  node <- getImageNode na idx+  withImageSlot (peContext env) (ImageId tid) accent $ \iw ih a0 b0 a1 b1 -> do+    let slot _ = pure (Just (atlasTextureId, (a0, b0, a1, b1)))+    case node of+      Nothing -> do+        base <- fromMaybe (colorRGBA 255 255 255 255) <$> getNodeFontColor na idx+        pushImageOp da slot (DrawImage rect 0 tid 0 0 1 1 (fadeBy fade base))+      Just ImageNode {inLook = look} ->+        withLookDraw look (iw, ih) fade rect $ \turned r angle u0 v0 u1 v1 c -> do+          let emit = pushImageOp da slot (DrawImage r angle tid u0 v0 u1 v1 c)+          if turned then withClip da rect emit else emit+  where+    accent = pushRect da rect (themeAccent (peTheme env))++{-# NOINLINE paintDrawingNode #-}+paintDrawingNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintDrawingNode env@PaintEnv {peContext = ctx} idx rect = do+  wid <- getWidgetId (peNodeArena env) idx+  mCustomBuild <- lookupCustomDrawingAt ctx idx+  case mCustomBuild of+    Just CustomDrawingEntry {cdrContent = content, cdrBuild = customBuild} -> do+      ops <- cachedCustomDrawingOps ctx wid content rect (mkCustomDrawContext ctx (peFontMetrics env) wid) customBuild+      emitDrawingOps env rect ops+    Nothing -> do+      mBuild <- lookupDrawingAt ctx idx+      forM_ mBuild $ \(DrawingEntry content build) -> do+        ops <- cachedDrawingOps ctx wid content rect build+        emitDrawingOps env rect ops++{-# NOINLINE paintShaderNode #-}+paintShaderNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintShaderNode PaintEnv {peContext = ctx, peDrawArena = da} idx rect = do+  mEntry <- lookupNodeShaderAt ctx idx+  forM_ mEntry $ \entry -> do+    caps <- getShaderCapabilities ctx+    recOps <- readIORef (daRecordOps da)+    if capSurfaceShaders caps && not recOps+      then pushShaderQuad da (snePass entry) rect (sneCornerRadius entry) (sneTint entry)+      else+        let r = sneCornerRadius entry+            col = sneFallback entry+         in if r > 0+              then pushRoundedRect da rect r col+              else pushRect da rect col++-- | Lower the children of @idx@ with the current paint env, topmost last+-- ('forChildrenInPaintOrder_'). NOINLINE keeps this recursive call out+-- of the simplifier's loop analysis, so the whole walker stays a call to+-- opaque seams rather than one inlined monster.+{-# NOINLINE walkChildrenWithOccluders #-}+walkChildrenWithOccluders :: PaintEnv -> NodeIdx -> IO ()+walkChildrenWithOccluders env idx =+  forChildrenInPaintOrder_ (peNodeArena env) idx (paintNodeWithEnv env)++-- | Children walk for callers painting a subtree inside their own clip+-- (floating overlays); builds a fresh env without occluders.+{-# NOINLINE walkChildren #-}+walkChildren :: Context -> NodeIdx -> IO ()+walkChildren ctx idx = buildPaintEnv ctx emptyPrimArray >>= (`walkChildrenWithOccluders` idx)
+ lib/NanoUI/Internal/Frame/Paint/Widgets.hs view
@@ -0,0 +1,561 @@+{-# OPTIONS_GHC -fasm -fno-specialise-aggressively #-}++-- | Painters for controls and text fields, and the paint environment they+-- share with the node walk. NOINLINE keeps these large bodies out of the+-- recursive node walk.+module NanoUI.Internal.Frame.Paint.Widgets+  ( PaintEnv (..)+  , buildPaintEnv+  , paintWidget+  , paintTextInputNode+  , paintTextAreaNode+  ) where++import Control.Monad (unless, void, when)+import Data.Bits ((.&.))+import Data.IORef (readIORef)+import Data.Maybe (fromMaybe)+import Data.Primitive.PrimArray (PrimArray, readPrimArray)+import qualified Data.Text as T+import Data.Word (Word64)+import NanoUI.Internal.Context (Context (..), WidgetTextPlacement (..), activeEffectNodes, getAnimationValue, getStore)+import NanoUI.Internal.Draw+import NanoUI.Internal.Font+import NanoUI.Internal.Frame.Chrome+import NanoUI.Internal.Frame.Node (nodeAdornmentInsets, resolveFontFor)+import NanoUI.Internal.Frame.Spans (cachedWidgetLabel, forWidgetTextPlacements_, selectableTextGeometry)+import NanoUI.Internal.Frame.TextArea (drawTextAreaContentWith, resolveTextAreaFont)+import NanoUI.Internal.Frame.TextInput+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Style (AlignX (..), Style, Theme, fadeAlpha, fieldIconColor, styleBg, styleBorder, styleFg, themeAccent, themeButton, themeInput, themeOnAccent)+import NanoUI.Internal.Types (Color (..), Rect (..), clamp, clamp01, colorA, lerpColor, onGrid, rectInflate, rectNonEmpty)+import NanoUI.Internal.WidgetText+import NanoUI.Internal.Widgets.ColorPicker (drawColorPickerPart)++-- | Context, arenas, fonts, and interaction state read once for a paint pass.+-- Fields retain boxed references so compiler unboxing does not expand the+-- context and theme records at every recursive call.+data PaintEnv = PaintEnv+  { peContext :: Context+  , peNodeArena :: NodeArena+  , peDrawArena :: DrawArena+  , peTheme :: Theme+  , peScope :: Int+    -- ^ The node scope 'peTheme' belongs to. A node in another scope repaints+    -- its subtree with that scope's theme.+  , peFontMetrics :: FontMetrics+  , peOccluders :: PrimArray Float+    -- ^ Opaque floating panel rects as @x0, y0, x1, y1@ runs; empty when the+    -- frame has none.+  , peFocusRing :: WidgetId+    -- ^ The focused widget while its keyboard focus ring shows, else 0.+  , peHotId :: WidgetId+  , peActiveId :: WidgetId+  , peFocusId :: WidgetId+  , pePieces :: PrimArray Float+    -- ^ The frame's damage pieces as @x0, y0, x1, y1@ runs, of which a node+    -- must meet one to paint; empty when the clip is the one piece.+  , peHasEffects :: Bool+    -- ^ Whether the current frame declared any Tier 2 shader effect containers.+  }++-- | Locality helper for callers inside the paint frame loop; a fresh env+-- re-reads the theme once.+{-# NOINLINE buildPaintEnv #-}+buildPaintEnv :: Context -> PrimArray Float -> IO PaintEnv+buildPaintEnv ctx occluders = do+  theme <- readIORef (ctxTheme ctx)+  hot <- readIORef (ctxHotId ctx)+  active <- readIORef (ctxActiveId ctx)+  focus <- readIORef (ctxFocusId ctx)+  focusVisible <- readIORef (ctxFocusVisible ctx)+  pieces <- getClipPieces (ctxDrawArena ctx)+  hasEffects <- not . null <$> activeEffectNodes ctx+  pure PaintEnv+    { peContext = ctx+    , peNodeArena = ctxNodeArena ctx+    , peDrawArena = ctxDrawArena ctx+    , peTheme = theme+    , peScope = 0+    , peFontMetrics = ctxFontMetrics ctx+    , peOccluders = occluders+    , peFocusRing = if focusVisible then focus else WidgetId 0+    , peHotId = hot+    , peActiveId = active+    , peFocusId = focus+    , pePieces = pieces+    , peHasEffects = hasEffects+    }++-- | Single-line text input: selectable, bare, search, combo or captioned field+-- depending on the node's visual style.+{-# NOINLINE paintTextInputNode #-}+paintTextInputNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintTextInputNode env idx rect@(Rect x y w h) = do+  let ctx = peContext env+      da = peDrawArena env+      fm = peFontMetrics env+  style <- widgetVisualStyleWithTheme ctx (peTheme env) (peHotId env) (peActiveId env) (peFocusId env) NodeTextInput idx+  focus <- (== peFocusId env) <$> getWidgetId (peNodeArena env) idx+  si <- getStyleIdx (peNodeArena env) idx+  if hasFlag textInputFlagNumeric si+    then do+      -- The box, its value clipped left of the stepper, and the stepper's up+      -- and down arrows beside a rule.+      let (up@(Rect ux _ _ _), down) = numericStepperRects x y w h+          iconCol = lerpColor (styleFg style) (styleBg style) 0.4+      void $ paintCaptionlessField env style idx focus rect (numericTextClip fm x y w h) False $ do+        pushLine da ux (y + 4) ux (y + h - 4) 1 (lerpColor (styleBorder style) (styleBg style) 0.4)+        drawStepArrow da True up iconCol+        drawStepArrow da False down iconCol+    else if hasFlag textInputFlagSelectable si+      then paintSelectableText env style idx rect+      else if hasFlag textInputFlagSearch si+        then do+          opts <- getOptions (peNodeArena env) idx+          let iconCol = fieldIconColor style+              (magRect, Rect cx cy cw ch) = searchInputIconRects fm x y w h+              field clip = paintCaptionlessField env style idx focus rect clip True+          if null opts+            -- A search field: a magnifier on the left and a clear (x) on the+            -- right while there is text.+            then do+              value <- field (searchInputTextClip fm x y w h) (drawSearchMagnifier da magRect iconCol)+              unless (T.null value) $+                drawCloseIcon da False cx cy cw ch iconCol+            -- A combo box: a select chevron in the right reserve that flips up+            -- while the dropdown is open (i.e. focused).+            else void $ field (comboTextClip fm x y w h) $+              drawSelectChevron da focus (x + w - selectChevronReserve) y selectChevronReserve h iconCol+        else do+          (field, clip) <- nodeTextFieldGeom ctx idx x y w h+          void $ paintCaptionlessField env style idx focus field clip True (pure ())++-- | Multi-line text area.+{-# NOINLINE paintTextAreaNode #-}+paintTextAreaNode :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintTextAreaNode env@PaintEnv {peContext = ctx, peDrawArena = da} idx (Rect x y w h) = do+  style <- widgetVisualStyleWithTheme ctx (peTheme env) (peHotId env) (peActiveId env) (peFocusId env) NodeTextArea idx+  areaFm <- resolveTextAreaFont ctx idx+  paintStyledRect da style (Rect x y w h)+  drawTextAreaContentWith da ctx areaFm idx x y w h style++-- | Generic foreground / chrome widget (button, checkbox, radio option, tree+-- row, slider, select, color swatch, table / tab header, ...). Splits into a+-- background pass and a label pass, both behind NOINLINE seams.+{-# NOINLINE paintWidget #-}+paintWidget :: PaintEnv -> NodeIdx -> NodeType -> Rect -> IO ()+paintWidget env@PaintEnv {peContext = ctx} idx nt rect@(Rect _ ry _ rh) = do+  style <- widgetVisualStyleWithTheme ctx (peTheme env) (peHotId env) (peActiveId env) (peFocusId env) nt idx+  a <- arenaArrays (peNodeArena env)+  value <- readStyle a idx StyleNodeValue+  si <- readStyleIdx a idx+  -- Menu rows paint edge-to-edge across the popup panel, exactly like the+  -- text-field context menu painter: the hover fill and the accent marker+  -- span the panel width instead of the (padded) node rect.+  menuRowRect <-+    if nt == NodeButton && buttonKindOf si == ButtonMenu+      then do+        let na = peNodeArena env+        panel <- walkFloatingAncestors na idx $ \p pnt ->+          if pnt == NodePopup then Just <$> getNodeRect na p else pure Nothing+        pure (maybe rect (\(Rect px _ pw _) -> Rect px ry pw rh) panel)+      else pure rect+  paintWidgetBackground env idx nt style si menuRowRect value rect+  paintWidgetForeground env idx nt style si rect++-- The button kind flags are re-derived here from the style bits rather than+-- passed in: a flags record crossing this NOINLINE seam would be allocated+-- for every widget on every painted frame.+{-# NOINLINE paintWidgetBackground #-}+paintWidgetBackground :: PaintEnv -> NodeIdx -> NodeType -> Style -> Word64 -> Rect -> Float -> Rect -> IO ()+paintWidgetBackground env idx nt style si menuRowRect value rect@(Rect x y w h) = do+  let ctx = peContext env+      da = peDrawArena env+      fm = peFontMetrics env+      theme = peTheme env+      !bkind = if nt == NodeButton then buttonKindOf si else ButtonPlain+      !hasBg = colorA (styleBg style) > 0+      !opaqueBg = case bkind of+        ButtonMenu -> hasBg+        ButtonMenuBar -> hasBg+        ButtonTable -> hasBg+        ButtonRow -> hasBg+        ButtonClose -> False+        ButtonTab -> False+        ButtonChoice -> False+        _ -> nt /= NodeSlider && nt /= NodeTextInput && nt /= NodeTextArea && nt /= NodeColorPicker+      !drawStroke = case bkind of+        ButtonTab -> False+        ButtonTable -> False+        ButtonMenu -> False+        ButtonMenuBar -> False+        ButtonRow -> False+        _ -> opaqueBg+      !canGroup =+        opaqueBg+          && drawStroke+          && (nt == NodeSelect || (nt == NodeButton && (bkind == ButtonPlain || bkind == ButtonContent)))+      na = peNodeArena env+  grouped <-+    if canGroup+      then do+        a <- arenaArrays na+        p <- readTree a idx TreeParent+        if p >= 0+          then do+            pt <- readTagEnum a p TagNodeType+            if pt == NodeContainer+              then hasFlag containerFlagButtonGroup <$> readStyleIdx a p+              else pure False+          else pure False+      else pure False+  if grouped+    then do+      (firstC, lastC) <- flowChildEnds na =<< getParent na idx+      dir <- getDirection na =<< getParent na idx+      paintGroupedButton da style dir (idx == firstC) (idx == lastC) rect+    else do+      when opaqueBg $ fillStyledRect da style menuRowRect+      when drawStroke $ strokeStyledRect da style rect+  case nt of+    NodeSlider -> paintSliderBody env x y w h value+    NodeSelect -> drawSelectChevron da False x y w h (styleFg style)+    NodeColorPicker -> do+      store <- getStore ctx+      drawColorPickerPart (peNodeArena env) idx fm da store style (Rect x y w h)+    NodeButton -> case bkind of+      ButtonMenu -> do+        wid <- getWidgetId (peNodeArena env) idx+        when (wid == peHotId env) $ paintMenuAccent da theme menuRowRect+      ButtonTab ->+        paintTabHeader da theme (buttonVisualStyle si) (value > 0.5) style (Rect x y w h)+      ButtonTable ->+        paintTableHeader da theme (value > 0.5) style x y w h+      ButtonChoice -> do+        fontSize <- getNodeFontSize (peNodeArena env) idx+        choiceFm <-+          if fontSize == 0+            then pure fm+            else (\(f, _, _) -> f) <$> resolveFontFor ctx NodeButton fontSize si+        drawChoiceControl da choiceFm style theme x y h value (buttonVisualStyle si == 0)+      ButtonRow -> do+        let (depth, hasKids, expanded) = treeDecodeStyle si+        when hasKids $+          drawTreeChevron da fm x y h depth expanded (styleFg style)+      ButtonClose+        | buttonVisualStyle si == buttonCloseTab -> paintTabClose env idx (Rect x y w h)+        | otherwise -> drawCloseIcon da (buttonVisualStyle si == buttonCloseTrailing) x y w h (styleFg style)+      ButtonPlain -> pure ()+      ButtonMenuBar -> pure ()+      ButtonContent -> pure ()+    -- 'NanoUI.Internal.Frame.Paint.lowerNodeVisible' paints the other node+    -- types itself and calls this only for the four above.+    NodeContainer -> pure ()+    NodeText -> pure ()+    NodeSpacer -> pure ()+    NodeSeparator -> pure ()+    NodeTextInput -> pure ()+    NodeTextArea -> pure ()+    NodeScrollContainer -> pure ()+    NodeModal -> pure ()+    NodeImage -> pure ()+    NodePanel -> pure ()+    NodeWindow -> pure ()+    NodeBox -> pure ()+    NodePopup -> pure ()+    NodeDrawing -> pure ()+    NodeShader -> pure ()++-- | A tab header's close button: its cross in the header's label colour+-- ('NanoUI.Internal.Style.fontColor'), dimmed until the pointer is over it,+-- on a round fill while it is.+{-# NOINLINE paintTabClose #-}+paintTabClose :: PaintEnv -> NodeIdx -> Rect -> IO ()+paintTabClose env idx (Rect x y w h) = do+  let ctx = peContext env+      na = peNodeArena env+      da = peDrawArena env+  wid <- getWidgetId na idx+  let hot = peHotId env+  animT <- getAnimationValue ctx wid+  label <- fromMaybe (styleFg (themeButton (peTheme env))) <$> getNodeFontColor na idx+  let hotT = clamp01 (if wid == hot && not (animT > 0) then 1 else animT)+      d = min w h+  when (hotT > 0) $+    pushRoundedRect da (Rect (x + (w - d) / 2) (y + (h - d) / 2) d d) (d / 2) (fadeAlpha label (round (36 * hotT)))+  drawCloseIcon da False x y w h (lerpColor (fadeAlpha label 150) label hotT)++{-# NOINLINE paintSliderBody #-}+paintSliderBody :: PaintEnv -> Float -> Float -> Float -> Float -> Float -> IO ()+paintSliderBody PaintEnv {peDrawArena = da, peTheme = theme} x y w h value = do+  let track@(Rect tx ty tw th) = sliderTrackBounds x y w h+      trackR = 3+      fillW = max 0 (tw * clamp01 value)+      outline = styleBorder (themeInput theme)+      well = lerpColor (styleBg (themeInput theme)) outline 0.35+      bw = 1+      innerR = max 0 (trackR - bw)+      !inner@(Rect innerX innerY innerW innerH) = rectInflate (-bw) track+      innerFillW = max 0 (innerW * clamp01 value)+  pushRoundedStroke da track trackR bw outline+  when (rectNonEmpty inner) $+    pushRoundedRect da inner innerR well+  when (innerFillW > 0) $ do+    let fillR =+          if innerFillW >= innerW - 0.5+            then innerR+            else min innerR (innerFillW / 2)+    pushRoundedRect da (Rect innerX innerY innerFillW innerH) fillR (themeAccent theme)+  let handleD = sliderHandleDiameter+      handleCx = tx + clamp (handleD / 2) (tw - handleD / 2) fillW+      handleHy = ty + (th - handleD) / 2+      innerD = handleD - 2+  pushRoundedRect+    da+    (Rect (handleCx - innerD / 2) (handleHy + (handleD - innerD) / 2) innerD innerD)+    (innerD / 2)+    (themeOnAccent theme)+  pushRoundedStroke da (Rect (handleCx - handleD / 2) handleHy handleD handleD) (handleD / 2) bw outline++{-# NOINLINE paintWidgetForeground #-}+paintWidgetForeground :: PaintEnv -> NodeIdx -> NodeType -> Style -> Word64 -> Rect -> IO ()+paintWidgetForeground env idx nt style si (Rect x y w h) = do+  let ctx = peContext env+      na = peNodeArena env+      da = peDrawArena env+  a <- arenaArrays na+  fcWord <- readPrimArray (naArrFontColor a) idx+  fontSize <- readStyle a idx StyleFontSize+  let !font = nodeFontBits nt si+      !widgetFg =+        if (fcWord .&. 0x100000000) /= 0+          then Color (fromIntegral (fcWord .&. 0xFFFFFFFF))+          else labelColor (peTheme env) style font Nothing+  if hasCenteredLabel nt+    then do+      -- Fast path for plain buttons and selects: skip resolveFontFor when+      -- using the default font and avoid boxing labelBox tuples or+      -- drawPlacement closures.+      (fm, native) <-+        if fontSize == 0 && font == 0+          then pure (peFontMetrics env, True)+          else (\(f, nat, _) -> (f, nat)) <$> resolveFontFor ctx nt fontSize si+      kids <- if nt == NodeButton then readTree a idx TreeFirstChild else pure (-1)+      placement <-+        if kids < 0 && not (nt == NodeButton && tabLabelAtStart si)+          then cachedWidgetLabel ctx nt idx AlignCenter w h+          else paintCenteredBoxed ctx na idx nt si x w h+      case placement of+        Nothing -> pure ()+        Just (WidgetTextPlacement txt px py _ th) ->+          unless (T.null txt) $ do+            (!lx, _) <-+              if kids < 0 && not (nt == NodeButton && tabLabelAtStart si)+                then pure (x, w)+                else buttonLabelOrigin na idx nt si x w+            if font == 0+              then pushText da fm (lx + px) (y + py) txt widgetFg+              else pushStyledLabel da fm native font (lx + px) (y + py) txt widgetFg+            when (nt == NodeButton && buttonKindOf si == ButtonTable) $ do+              let !sortMark = tableSortMarkOf si+              when (sortMark /= 0) $ do+                sortAlign <- readAlignX a idx+                let !sortArrowX =+                      if sortAlign == AlignEnd+                        then x + tableCellInset + 5+                        else x + w - tableCellInset - 5+                drawSortTriangle da sortArrowX (y + py + th / 2) (sortMark == 2) widgetFg+    else do+      (fm, native, _) <- resolveFontFor ctx nt fontSize si+      forWidgetTextPlacements_ ctx nt idx x y w h $ \_ txt px py _ _ ->+        unless (T.null txt) $+          if font == 0 then pushText da fm px py txt widgetFg else pushStyledLabel da fm native font px py txt widgetFg++{-# NOINLINE paintCenteredBoxed #-}+paintCenteredBoxed :: Context -> NodeArena -> NodeIdx -> NodeType -> Word64 -> Float -> Float -> Float -> IO (Maybe WidgetTextPlacement)+paintCenteredBoxed ctx na idx nt si x w h = do+  (lead, trail) <- if nt == NodeButton then nodeAdornmentInsets na idx x w else pure (0, 0)+  let !start = if nt == NodeButton && tabLabelAtStart si then tabHeaderPadX else 0+      (!lw, !ax)+        | lead > 0 = (max 0 (w - lead - trail), AlignStart)+        | trail > 0 = (max 0 (w - trail), AlignEnd)+        | start > 0 = (max 0 (w - start), AlignStart)+        | otherwise = (w, AlignCenter)+  cachedWidgetLabel ctx nt idx ax lw h++{-# NOINLINE buttonLabelOrigin #-}+buttonLabelOrigin :: NodeArena -> NodeIdx -> NodeType -> Word64 -> Float -> Float -> IO (Float, Float)+buttonLabelOrigin na idx nt si x w = do+  (lead, trail) <- if nt == NodeButton then nodeAdornmentInsets na idx x w else pure (0, 0)+  let !start = if nt == NodeButton && tabLabelAtStart si then tabHeaderPadX else 0+  pure $!+    if lead > 0+      then (x + lead, max 0 (w - lead - trail))+      else if trail > 0+        then (x, max 0 (w - trail))+        else if start > 0+          then (x + start, max 0 (w - start))+          else (x, w)++-- | A label in the weight, slant and decoration of font bits @font@+-- ('pushFieldText'). Out of line: inlined, it costs every plain label+-- (measured: 260 bytes per label per frame).+{-# NOINLINE pushStyledLabel #-}+pushStyledLabel :: DrawArena -> FontMetrics -> Bool -> Word64 -> Float -> Float -> T.Text -> Color -> IO ()+pushStyledLabel = pushFieldText++-- | Sort direction triangle for a table header: up when ascending, down when+-- descending, centered on the label line in the header's reserved slot.+drawSortTriangle :: DrawArena -> Float -> Float -> Bool -> Color -> IO ()+drawSortTriangle da cx cy down =+  let tip = if down then 3.5 else -3.5+   in pushFilledTriangle da (cx - 5) (cy - tip) (cx + 5) (cy - tip) cx (cy + tip)++-- | Draw a single-line field's text, its selection, and (when @showCaret@ is+-- set) its caret while it is being edited, inside @clip@. @penX/penY@ locate+-- @txt@ (absolute), drawn in the font style packed in @si@ ('pushFieldText').+{-# INLINE paintClippedFieldText #-}+paintClippedFieldText ::+  Context ->+  DrawArena ->+  FontMetrics ->+  Bool ->+  Word64 ->+  Style ->+  NodeIdx ->+  Bool ->+  Maybe FieldEdit ->+  Rect ->+  Float ->+  Float ->+  T.Text ->+  Color ->+  IO ()+paintClippedFieldText ctx da fm native si style idx showCaret mEdit clip penX penY txt fg =+  withClip da clip $ do+    mapM_ (drawTextInputSelection da ctx idx) mEdit+    unless (T.null txt) $+      pushFieldText da fm native si penX penY txt fg+    when showCaret $+      mapM_ (\edit -> drawTextInputCaret da edit (styleFg style)) mEdit++-- | A caption-less field filling @box@: the box, @chrome@, then its value,+-- or its label as a placeholder (dimmed) while empty and unfocused when it+-- has one, scrolled to keep the caret in @clip@. Returns the value.+paintCaptionlessField :: PaintEnv -> Style -> NodeIdx -> Bool -> Rect -> Rect -> Bool -> IO () -> IO T.Text+paintCaptionlessField env style idx focus box clip hasPlaceholder chrome = do+  let ctx = peContext env+      da = peDrawArena env+  si <- getStyleIdx (peNodeArena env) idx+  paintStyledRect da style box+  chrome+  TextInputFrame fm native value shown penX rowY mEdit <-+    resolveTextInputFrame ctx idx si focus box clip+  placeholder <- if hasPlaceholder then getText (ctxNodeArena ctx) idx else pure ""+  let display = textInputFieldText placeholder shown focus+  fg <- textInputFg ctx idx (styleFg style) (styleBg style) value focus+  paintClippedFieldText ctx da fm native si style idx True mEdit clip penX rowY display fg+  pure value++-- | A stepper arrow in its half of the stepper, nudged toward the other half so+-- the pair reads as one control.+drawStepArrow :: DrawArena -> Bool -> Rect -> Color -> IO ()+drawStepArrow da up (Rect sx sy sw sh) col = do+  let cx = sx + sw / 2+      cy = sy + sh / 2 + (if up then 1 else -1)+      tip = if up then -2.4 else 2.4+  pushArrowhead da cx cy 3.6 tip col++-- | A filled arrowhead @2 * hw@ wide around @(cx, cy)@, its point @tip@ below+-- the centre (above for a negative @tip@) and its base a third of that the+-- other way. Shared by the stepper arrows and the select chevron.+pushArrowhead :: DrawArena -> Float -> Float -> Float -> Float -> Color -> IO ()+pushArrowhead da cx cy hw tip =+  pushFilledTriangle da (cx - hw) (cy - tip * 0.35) (cx + hw) (cy - tip * 0.35) cx (cy + tip)++-- | Selectable text: chrome-less, border-less, naturally sized text field+-- that supports mouse drag selection and text copying without an insertion caret.+paintSelectableText :: PaintEnv -> Style -> NodeIdx -> Rect -> IO ()+paintSelectableText env style idx rect@(Rect x y _ h) = do+  let ctx = peContext env+      da = peDrawArena env+  fg <- fieldTextColor ctx idx (styleFg style)+  si <- getStyleIdx (peNodeArena env) idx+  size <- getNodeFontSize (peNodeArena env) idx+  (fm, native, _) <- resolveFontFor ctx NodeTextInput size si+  value <- textInputValue ctx idx+  let (penX, ty, _) = selectableTextGeometry fm x y h+  mEdit <- readFieldEdit ctx idx rect penX+  paintClippedFieldText ctx da fm native si style idx False mEdit rect penX ty value fg++drawSearchMagnifier :: DrawArena -> Rect -> Color -> IO ()+drawSearchMagnifier da (Rect x y w h) col = do+  let cx = x + w / 2+      cy = y + h / 2+      s = min w h+      r0 = s * 0.36+      t = max 1.4 (s * 0.15)+      startOff = r0 * 0.7071+      endOff = r0 * 0.7071 + s * 0.22+  pushRoundedStroke da (Rect (cx - r0) (cy - r0) (2 * r0) (2 * r0)) r0 t col+  pushLine da (cx + startOff) (cy + startOff) (cx + endOff) (cy + endOff) (t * 0.8) col++-- | The box of a checkbox (@isCheckbox@) or radio option at @x@, centred+-- vertically within @y h@ to match its single-line label. A checkbox draws+-- like 'checkboxOps'; a radio box is a well, with an accent ring and dot when+-- checked.+drawChoiceControl :: DrawArena -> FontMetrics -> Style -> Theme -> Float -> Float -> Float -> Float -> Bool -> IO ()+drawChoiceControl da fm style theme x y h value isCheckbox = do+  let box = checkboxBoxSize fm+      by = y + max 0 ((h - box) / 2)+      checked = value >= 0.5+  if isCheckbox+    then checkboxOps (pushShapeOp da) theme (styleBorder style) x by box checked+    else do+      let !r = box / 2+          !bw = 2+          outer = Rect x by box box+          accent = themeAccent theme+      pushRoundedRect da (rectInflate (-bw) outer) (max 0 (r - bw)) (styleBg (themeInput theme))+      pushRoundedStroke da outer r bw (if checked then accent else styleBorder style)+      when checked $ do+        s <- readIORef (daSnapScale da)+        let !dot = box * 0.72+            !dx = onGrid s x + (box - dot) / 2+            !dy = onGrid s by + (box - dot) / 2+        pushRoundedRectRaw da (Rect dx dy dot dot) (dot / 2) accent++-- | A cross centered in the box, or against its right edge when @trailing@.+drawCloseIcon :: DrawArena -> Bool -> Float -> Float -> Float -> Float -> Color -> IO ()+drawCloseIcon da trailing x y w h col = do+  let arm = min w h * 0.21+      t = max 1.3 (min w h * 0.064)+      cx = if trailing then x + w - arm - t / 2 else x + w / 2+      cy = y + h / 2+  pushLine da (cx - arm) (cy - arm) (cx + arm) (cy + arm) t col+  pushLine da (cx - arm) (cy + arm) (cx + arm) (cy - arm) t col++-- | Select chevron centered in the right reserve of @x w@; points up when+-- @up@ (an open combo dropdown), down otherwise.+drawSelectChevron :: DrawArena -> Bool -> Float -> Float -> Float -> Float -> Color -> IO ()+drawSelectChevron da up x y w h col = do+  let cx = selectChevronCenterX x w+      cy = y + h / 2+      tip = if up then -2.6 else 2.6+  pushArrowhead da cx cy 4.2 tip col++drawTreeChevron :: DrawArena -> FontMetrics -> Float -> Float -> Float -> Int -> Bool -> Color -> IO ()+drawTreeChevron da fm x y h depth expanded col = do+  let Rect cx cy cw ch = treeChevronRect fm x y h depth+      mx = cx + cw / 2+      my = cy + ch / 2+      s = min 4.5 (min cw ch * 0.28)+      t = max 1.5 (s * 0.3)+      -- One mitered polyline, not two capped lines: the caps of a line this+      -- thin are single-pixel squares, and the arms snapped apart.+      pts+        | expanded = points3 (mx - s) (my - s * 0.45) mx (my + s * 0.7) (mx + s) (my - s * 0.45)+        | otherwise = points3 (mx - s * 0.45) (my - s) (mx + s * 0.7) my (mx - s * 0.45) (my + s)+  pushPolylineAA da pts t False ButtCap MiterJoin 4 (Flat col)
+ lib/NanoUI/Internal/Frame/Scroll.hs view
@@ -0,0 +1,546 @@+-- | 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})
+ lib/NanoUI/Internal/Frame/Select.hs view
@@ -0,0 +1,377 @@+-- | Dropdown popups of selects and combo boxes: their placement, rows and+-- text, pointer routing to them, and the select's keys and dismissal.+module NanoUI.Internal.Frame.Select+  ( closeSelectOnOutsideClick+  , finalizeSelectKeyboard+  , collectDropdownSpans+  , dropdownOwnerAt+  , routePointer+  , comboDropRect+  , comboDropPickIndex+  , comboScrollGeom+  , focusedComboNode+  , openSelectNode+  , dropdownPlacement+  , settleDropdowns+  , DropdownRow (..)+  , dropdownPopupRows+  , selectRowAt+  , dropdownVisibleRows+  ) where++import Control.Monad (filterM, forM, forM_, unless, when)+import Data.IORef (readIORef)+import Data.IntMap.Strict qualified as IM+import Data.Maybe (fromMaybe, isJust, listToMaybe)+import qualified Data.Text as T+import NanoUI.Internal.Context+import NanoUI.Internal.Draw (DrawArena (..))+import NanoUI.Internal.Font (FontMetrics, centeredTextY, menuItemPadX, menuItemRowH, menuOuterPad, widgetContentInset)+import NanoUI.Internal.Frame.Chrome (overlayMenuStyle)+import NanoUI.Internal.Frame.Hit (widgetOverlayAllowed)+import NanoUI.Internal.Layout.ScrollGeometry (ScrollBarLayout (..), scrollThumbSpan)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Input (Input (..), Key (..), MouseButton (..), Pressable (..), anyButtonPressed, anyButtonReleased, inputPointerHeld, shiftAtMost)+import NanoUI.Internal.Layout.Arena (NodeIdx, NodeType (NodeSelect, NodeTextInput), getClipBounds, getFirstChild, getNodeType, lookupNodeByKey, lookupNodeByWidgetId, getOptions, getNodeRect, getWidgetId, setClipRect, setRect, subtreeSpan)+import NanoUI.Internal.Layout.Solve (computePopupPosition)+import NanoUI.Internal.Monad (mfilterM, whenM, (<&&>))+import NanoUI.Internal.Store (fieldInt, findSlot, insertSlot)+import NanoUI.Internal.Style (Style (..), Theme (..), themeAccent)+import NanoUI.Internal.Types (Color (..), PopupAnchor (..), PopupPlacement (..), Rect (..), Size (..), V2 (..), clamp, rectContains, rectIntersect, rectNonEmpty)++-- | One placed row of an open dropdown, with its colours.+data DropdownRow = DropdownRow+  { drOption :: T.Text+  , drRect :: !Rect+  , drTextX :: !Float+  , drHovered :: !Bool+  , drFill :: !(Maybe Color)+  -- ^ The hover highlight, else the picked row's tint.+  , drFg :: !Color+  }++-- | The rows of dropdown @dp@ laid out at the rect given, over options+-- @opts@, that a window @winH@ tall shows ('dropdownVisibleRows'), with the+-- one @mouse@ is on hovered. A select's rows sit inside the dropdown's outer+-- margin. A combo's options are the rows of its window, which sit flush at+-- the top and scroll across by 'dpScrollX'. Shared by the dropdown's drawing+-- and its text spans.+dropdownPopupRows :: FontMetrics -> Theme -> Float -> V2 -> DropdownPopup -> [T.Text] -> Rect -> [DropdownRow]+dropdownPopupRows fm theme winH mouse dp opts (Rect x y w _) =+  [ DropdownRow opt row textX hovered fill (if picked then themeAccent theme else styleFg style)+  | (i, opt) <- zip [lo .. hi] (drop lo opts)+  , let row = Rect x (top + menuItemRowH * fromIntegral i) w menuItemRowH+        hovered = rectContains row mouse+        picked = i == dpPicked dp+        fill+          | hovered = Just (styleHoverBg style)+          | picked = Just (styleActiveBg style)+          | otherwise = Nothing+  ]+  where+    style = overlayMenuStyle theme+    top = if dpCombo dp then y else y + menuOuterPad+    textX = x + menuItemPadX + fst (widgetContentInset fm) - dpScrollX dp+    (lo, hi) = dropdownVisibleRows (length opts) winH top++-- | The first and last of @n@ dropdown rows, starting at @top@, that a window+-- @winH@ tall shows.+dropdownVisibleRows :: Int -> Float -> Float -> (Int, Int)+dropdownVisibleRows n winH top =+  (max 0 (floor ((0 - top) / menuItemRowH)), min (n - 1) (ceiling ((winH - top) / menuItemRowH)))++-- | The row of @n@ of a select dropdown laid out at @dropR@ that @mouse@ is+-- on, or -1.+selectRowAt :: Rect -> Int -> V2 -> Int+selectRowAt dropR@(Rect _ dy _ _) n mouse@(V2 _ my)+  | rectContains dropR mouse, i >= 0, i < n = i+  | otherwise = -1+  where+    i = floor ((my - dy - menuOuterPad) / menuItemRowH)++-- | Text of each dropdown popup ('registerDropdownPopup'), as its drawing+-- paints it, for a host that draws text from glyph quads. Under external+-- text the drawing records its text itself. One laid out empty+-- ('settleDropdowns') shows nothing.+collectDropdownSpans :: Context -> Input -> IO [(Rect, T.Text, Color, Color, Rect)]+collectDropdownSpans ctx@Context {ctxNodeArena = na, ctxFontMetrics = fm} inp = do+  drops <- dropdownPopups ctx+  external <- readIORef (daExternalText (ctxDrawArena ctx))+  if external || IM.null drops+    then pure []+    else fmap concat . forM (IM.toList drops) $ \(key, dp) -> do+      let field = dpField dp+      nodes <- (,) <$> lookupNodeByWidgetId na field <*> lookupNodeByKey na key+      case nodes of+        (Just fidx, Just pidx) -> do+          didx <- getFirstChild na pidx+          dropR <- if didx < 0 then pure (Rect 0 0 0 0) else getNodeRect na didx+          if not (rectNonEmpty dropR)+            then pure []+            else do+              opts <- getOptions na fidx+              theme <- widgetTheme ctx field+              let Size _ winH = inputWindowSize inp+                  rows = dropdownPopupRows fm theme winH (inputMousePos inp) dp opts dropR+              forM (filter (not . T.null . drOption) rows) $ \row -> do+                (tw, th) <- ctxMeasureText ctx (drOption row)+                let Rect _ ry _ rh = drRect row+                    bg = fromMaybe (styleBg (overlayMenuStyle theme)) (drFill row)+                pure (Rect (drTextX row) (centeredTextY fm ry rh th) tw th, drOption row, drFg row, bg, dropR)+        _ -> pure []++-- | The field whose dropdown popup, laid out this frame, @mouse@ is on.+dropdownOwnerAt :: Context -> V2 -> IO (Maybe WidgetId)+dropdownOwnerAt ctx@Context {ctxNodeArena = na} mouse = do+  drops <- dropdownPopups ctx+  if IM.null drops+    then pure Nothing+    else+      fmap (listToMaybe . map snd) . flip filterM (IM.toList (dpField <$> drops)) $ \(key, _) ->+        maybe (pure False) (fmap (`rectContains` mouse) . getNodeRect na) =<< lookupNodeByKey na key++-- | Decide where this frame's pointer goes, before the view runs. A button+-- that is already down keeps the route it went down with, through its+-- release, so a drag that wanders over something else stays where it began.+-- A press always starts over, even with the other button still down: it goes+-- to what is under it now, not through it to where the first one landed.+-- The floating panel on top is a dropdown when the last view registered it+-- as one ('registerDropdownPopup').+routePointer :: Context -> Input -> IO PointerRoute+routePointer ctx inp = do+  (held, old) <- getsInteraction ctx (\s -> (isPointerHeld s, isPointerRoute s))+  let pressed = anyButtonPressed inp+      released = anyButtonReleased inp+      -- A hold that ended without its release being seen is over too.+      holding = held && not pressed && (inputPointerHeld inp || released)+      mouse = inputMousePos inp+  route <-+    if holding+      then pure old+      else do+        layer <- floatingLayerAt ctx mouse+        drops <- dropdownPopups ctx+        pure (if layer /= 0 && IM.member layer drops then RouteDropdown layer else RouteLayer layer)+  -- Most frames change neither, and an idle frame should write nothing.+  when (route /= old || inputPointerHeld inp /= held) $+    modifyInteraction ctx $ \s ->+      s+        { isPointerRoute = route+        , isPointerHeld = inputPointerHeld inp+        , isColumnResize = isColumnResize s && inputPointerHeld inp+        }+  pure route++-- | Close the open select on a press of any button, or a left release, away+-- from its field and every dropdown. A right press on a field focuses it,+-- so a dropdown left open would take its arrows and Enter.+closeSelectOnOutsideClick :: Context -> Input -> IO ()+closeSelectOnOutsideClick ctx@Context {ctxNodeArena = na} inp =+  when (anyButtonPressed inp || releasedIn MouseLeft inp) $ do+    store <- getStore ctx+    when (anySelectOpen store) $ do+      let mouse = inputMousePos inp+      onField <- maybe (pure False) (fmap (`rectContains` mouse) . getNodeRect na) =<< openSelectNode ctx store+      onDropdown <- isJust <$> dropdownOwnerAt ctx mouse+      unless (onField || onDropdown) $+        setStore ctx (closeSelects store)++finalizeSelectKeyboard :: Context -> Input -> IO ()+finalizeSelectKeyboard ctx@Context {ctxNodeArena = na} inp = do+  -- Strict, so that a frame without these keys allocates no thunks for them.+  let has k = pressedIn k inp+      !wantNext = has KeyDown || has KeyRight+      !wantFirst = has KeyHome || has KeyPageUp+      !wantLast = has KeyEnd || has KeyPageDown+      !wantStep = wantNext || wantFirst || wantLast || has KeyUp || has KeyLeft+      !wantEsc = pressedOnceIn KeyEscape inp+      -- Enter or Space opens or closes the dropdown, as it presses a button.+      !wantEnter = pressedOnceIn KeyEnter inp || pressedOnceIn KeySpace inp+  -- With Ctrl, Alt or Super held, the keys are left to shortcuts.+  when (wantEsc || ((wantStep || wantEnter) && shiftAtMost (inputModifiers inp))) $ do+    focus <- readIORef (ctxFocusId ctx)+    store <- getStore ctx+    -- These keys act on the focused enabled select, open or not. Otherwise+    -- Escape, or any of them while nothing has focus, goes to the open+    -- select: a field that took focus without closing it keeps its keys.+    let enabledSelect idx = ((== NodeSelect) <$> getNodeType na idx) <&&> (not <$> isDisabled ctx focus)+    focused <-+      if wantStep || wantEnter then mfilterM enabledSelect =<< lookupNodeByWidgetId na focus else pure Nothing+    target <- case focused of+      Just idx -> pure (Just (idx, isSelectOpen store (intKey focus)))+      Nothing+        | wantEsc || hashWidgetId focus == 0 -> fmap (,True) <$> openSelectNode ctx store+        | otherwise -> pure Nothing+    forM_ target $ \(idx, open) -> do+      wid <- getWidgetId na idx+      whenM (widgetOverlayAllowed ctx wid) $+        if wantEsc || wantEnter+          then when (open || not wantEsc) $ do+            setStore ctx (setSelectOpen store (intKey wid) (not open))+            when wantEsc $ markEscapeConsumed ctx+            markDirty ctx+          else do+            n <- length <$> getOptions na idx+            when (n > 0) $ do+              -- The stored index can be one the options do not reach; they+              -- show it clamped, and a key that lands there still picks.+              let key = intKey wid+                  stored = findSlot fieldInt 0 key store+                  cur = clamp 0 (n - 1) stored+                  next+                    | wantFirst = 0+                    | wantLast = n - 1+                    | otherwise = clamp 0 (n - 1) (cur + if wantNext then 1 else -1)+              when (next /= stored) $ do+                setStore ctx (insertSlot fieldInt key next store)+                markDirty ctx++-- | The node of the select whose dropdown the store holds open.+openSelectNode :: Context -> WidgetStore -> IO (Maybe NodeIdx)+openSelectNode Context {ctxNodeArena = na} store+  | not (anySelectOpen store) = pure Nothing+  | otherwise =+      mfilterM (fmap (== NodeSelect) . getNodeType na) =<< lookupNodeByKey na (storeOpenSelect store)++-- | The focused node when it is a combo (a text input carrying options),+-- which owns an open dropdown for as long as it holds focus.+focusedComboNode :: Context -> IO (Maybe NodeIdx)+focusedComboNode ctx@Context {ctxNodeArena = na} =+  mfilterM (\idx -> ((== NodeTextInput) <$> getNodeType na idx) <&&> (not . null <$> getOptions na idx))+    =<< lookupNodeByWidgetId na =<< readIORef (ctxFocusId ctx)++-- | Vertical gap between the select widget and its dropdown menu.+selectDropGap :: Float+selectDropGap = 4++-- | A dropdown @dropH@ tall and as wide as the field at @x y w h@: below the+-- field, or above it when it does not fit below and there is more room+-- above, and kept inside the window of @size@ ('computePopupPosition'). A+-- list that fits on neither side runs past the window edge on the roomier+-- one rather than over its field, where the press that opens it would pick.+dropRect :: Size -> Float -> Float -> Float -> Float -> Float -> Rect+dropRect (Size winW winH) x y w h dropH =+  let (dx, dy) = computePopupPosition winW winH 0 w dropH (AnchorRect (Rect x y w h)) PlacementAuto selectDropGap+      dy'+        | dy >= y + h || dy + dropH <= y = dy+        | winH - y - h >= y = y + h + selectDropGap+        | otherwise = y - dropH - selectDropGap+   in Rect dx dy' w dropH++-- | The rect dropdown popup @wid@ goes at, @ih@ tall, when it is one+-- ('registerDropdownPopup'): where 'dropRect' puts it for its field's rect+-- in a window of @size@. Placement runs before the scroll offsets, so a+-- field in a scroller is where it would be unscrolled, and+-- 'settleDropdowns' moves the popup after them.+dropdownPlacement :: Context -> Size -> WidgetId -> Float -> Float -> IO (Maybe Rect)+dropdownPlacement ctx@Context {ctxNodeArena = na} size wid _ ih = do+  drops <- dropdownPopups ctx+  case IM.lookup (intKey wid) drops of+    Nothing -> pure Nothing+    Just dp -> lookupNodeByWidgetId na (dpField dp) >>= traverse (\idx -> do+      Rect x y w h <- getNodeRect na idx+      pure (dropRect size x y w h ih))++-- | Move each dropdown popup, with what it holds, to where 'dropRect' puts+-- it for its field's rect once the scroll offsets are applied. A dropdown+-- is laid out empty, so that it shows nothing and takes no pointer, when its+-- field closed it after the view (a key, Tab, a pick on press), a modal+-- declared after it hides its field, or its field is scrolled out of its+-- viewport. A select's dropdown is open while the store says so, a combo's+-- while its field has focus. The frame runs this once the scroll offsets+-- are applied and again once its input has acted.+settleDropdowns :: Context -> Size -> IO ()+settleDropdowns ctx@Context {ctxNodeArena = na} size = do+  drops <- dropdownPopups ctx+  unless (IM.null drops) $ do+    store <- getStore ctx+    focus <- readIORef (ctxFocusId ctx)+    forM_ (IM.toList drops) $ \(key, dp) -> do+      let field = dpField dp+      nodes <- (,) <$> lookupNodeByKey na key <*> lookupNodeByWidgetId na field+      case nodes of+        (Just idx, Just fidx) -> do+          frect@(Rect fx fy fw fh) <- getNodeRect na fidx+          nt <- getNodeType na fidx+          let open = if nt == NodeSelect then isSelectOpen store (intKey field) else focus == field+          shown <-+            pure open+              <&&> (maybe True (isJust . rectIntersect frect) <$> getClipBounds na fidx)+              <&&> widgetOverlayAllowed ctx field+          Rect px py _ ph <- getNodeRect na idx+          let Rect tx ty _ _ = dropRect size fx fy fw fh ph+          if shown+            then unless (tx == px && ty == py) $ eachInSubtree idx $ \(Rect x y w h) -> Rect (x + tx - px) (y + ty - py) w h+            else eachInSubtree idx $ \(Rect x y _ _) -> Rect x y 0 0+        _ -> pure ()+  where+    -- Apply @f@ to the rect and clip of each node of @idx@'s subtree.+    eachInSubtree idx f =+      subtreeSpan na idx >>= mapM_ (\n -> forM_ [idx .. idx + n - 1] $ \i -> do+        Rect x y w h <- f <$> getNodeRect na i+        setRect na i x y w h+        getClipBounds na i >>= mapM_ (setClipRect na i . f))++-- Combo dropdown scrollbar sizes: lane thickness and the shortest a thumb+-- ever gets.+comboSbW, comboSbMinThumb :: Float+comboSbW = 10+comboSbMinThumb = 24++-- | Scrollbar geometry for a combo dropdown, shared by its drawing, its pick+-- and the widget's thumb-drag gesture. The list has no outer margin: rows+-- fill the drop rect edge to edge, and a vertical lane sits on the right+-- when rows overflow the window, a horizontal one on the bottom when the+-- widest row overflows the width. Returns (inner rows area, vertical bar,+-- horizontal bar, usable content width).+comboScrollGeom ::+  Rect ->+  Int ->+  Int ->+  Int ->+  Float ->+  Float ->+  (Rect, Maybe ScrollBarLayout, Maybe ScrollBarLayout, Float)+comboScrollGeom (Rect dx dy dw dh) n vis win xOff contentW =+  (Rect dx dy usableW usableH, vSb, hSb, usableW)+  where+    vScroll = n > vis && vis > 0+    usableW = max 0 (dw - if vScroll then comboSbW else 0)+    hScroll = contentW > usableW && contentW > 0+    -- Rows fill the drop rect from the top, stopping short of the lanes.+    usableH = max 0 (dh - if hScroll then comboSbW else 0)+    maxWin = fromIntegral (max 0 (n - vis))+    maxOffX = max 0 (contentW - usableW)+    -- Lanes sit flush against the dropdown border and share the corner. A+    -- thumb shows @num / den@ of its track, @off@ of @maxOff@ along it.+    thumb track num den off = scrollThumbSpan track comboSbMinThumb num den off+    vx = dx + dw - comboSbW+    hy = dy + dh - comboSbW+    (ty, thumbH) = thumb usableH (fromIntegral vis) (fromIntegral n) (fromIntegral win) (max 1 maxWin)+    (tx, thumbW) = thumb usableW usableW contentW xOff (max 1 maxOffX)+    vSb+      | vScroll = Just (ScrollBarLayout (Rect vx dy comboSbW usableH) (Rect (vx + 2) (dy + ty) (comboSbW - 4) thumbH) maxWin)+      | otherwise = Nothing+    hSb+      | hScroll = Just (ScrollBarLayout (Rect dx hy usableW comboSbW) (Rect (dx + tx) (hy + 2) thumbW (comboSbW - 4)) maxOffX)+      | otherwise = Nothing++-- | Combo dropdown rect: like a select's ('dropRect'), but with no outer+-- margin (rows start flush at the top), and the height reserves a flush+-- bottom scrollbar lane when the widest row overflows, so the horizontal bar+-- never covers the bottommost row. Must agree with 'comboScrollGeom' on when+-- lanes appear (same inputs, same formulas).+comboDropRect :: Size -> Float -> Float -> Float -> Float -> Int -> Int -> Float -> Rect+comboDropRect size x y w h nRows nTotal contentW =+  let vLaneW = if nTotal > nRows then comboSbW else 0+      hScroll = contentW > max 0 (w - vLaneW) && contentW > 0+   in dropRect size x y w h (fromIntegral nRows * menuItemRowH + (if hScroll then comboSbW else 0))++-- | Row index at @mouseY@ for a combo dropdown, whose rows start flush at the+-- drop rect's top.+comboDropPickIndex :: Rect -> Float -> Int -> Float -> Maybe Int+comboDropPickIndex (Rect _ dy _ _) itemH nOpts mouseY =+  let rel = mouseY - dy+   in if rel < 0 || rel >= itemH * fromIntegral nOpts+        then Nothing+        else Just (clamp 0 (nOpts - 1) (floor (rel / max itemH 1)))
+ lib/NanoUI/Internal/Frame/SpanArena.hs view
@@ -0,0 +1,50 @@+-- | Reusable text-span storage for one frame.+module NanoUI.Internal.Frame.SpanArena+  ( SpanArena+  , newSpanArena+  , resetSpanArena+  , pushSpans+  , spanArenaCount+  , spanArenaToList+  , foldSpanArena+  ) where++import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import qualified Data.IntMap.Strict as IM+import Data.Text (Text)+import NanoUI.Internal.Types (Color, Rect, rectFullyInside)++-- | One frame's text spans, newest first. Each holds logical bounds, text,+-- foreground and background colours, and clip.+newtype SpanArena = SpanArena (IORef [(Rect, Text, Color, Color, Rect)])++newSpanArena :: IO SpanArena+newSpanArena = SpanArena <$> newIORef []++-- | Drop every span.+resetSpanArena :: SpanArena -> IO ()+resetSpanArena (SpanArena ref) = writeIORef ref []++-- | Append bounds, text, foreground, background, and clip after the spans+-- already pushed.+pushSpans :: SpanArena -> [(Rect, Text, Color, Color, Rect)] -> IO ()+pushSpans (SpanArena ref) spans = modifyIORef' ref (\acc -> foldl' (flip (:)) acc spans)++-- | Live span count.+spanArenaCount :: SpanArena -> IO Int+spanArenaCount (SpanArena ref) = length <$> readIORef ref++-- | Spans in push order, dropping those hidden behind @panels@: a span's+-- clip is where it can show, its ink overhang included.+spanArenaToList :: IM.IntMap Rect -> SpanArena -> IO [(Rect, Text, Color, Color, Rect)]+spanArenaToList panels (SpanArena ref) = foldl' keep [] <$> readIORef ref+  where+    panelRects = IM.elems panels+    keep acc s@(_, _, _, _, clip)+      | any (rectFullyInside clip) panelRects = acc+      | otherwise = s : acc++-- | Visit spans in push order.+foldSpanArena :: SpanArena -> (Rect -> Text -> Color -> Color -> Rect -> IO ()) -> IO ()+foldSpanArena (SpanArena ref) f =+  readIORef ref >>= mapM_ (\(r, t, fg, bg, c) -> f r t fg bg c) . reverse
+ lib/NanoUI/Internal/Frame/Spans.hs view
@@ -0,0 +1,506 @@+-- | Collect positioned and clipped text for external renderers and headless tests.+module NanoUI.Internal.Frame.Spans+  ( collectTextSpans+  , collectOverlayTextSpans+  , collectRasterSpans+  , widgetNodeCount+  , cachedWidgetLabel+  , forWidgetTextPlacements_+  , selectableTextGeometry+  , textNodeSpanEntry+  ) where++import Control.Monad (forM, forM_, join, unless, when)+import Data.IORef (readIORef, writeIORef)+import qualified Data.IntMap.Strict as IM+import Data.Maybe (fromMaybe)+import qualified Data.Text as T+import Data.Word (Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Damage (floatingPanelRects)+import NanoUI.Internal.Draw (DrawArena (..), DrawFrameExtra (..))+import NanoUI.Internal.Font+import NanoUI.Internal.Frame.Chrome (displayText, textInputFocused, textInputValue, widgetVisualStyle)+import NanoUI.Internal.Frame.Node (childPaintClip, nodeAdornmentInsets, readScrollNode, resolveFontFor)+import NanoUI.Internal.Layout.ScrollGeometry (padContentClip, padTextClipRect, scrollNodeViewport, tagClippedSpans)+import NanoUI.Internal.Frame.Select (collectDropdownSpans)+import NanoUI.Internal.Frame.SpanArena (SpanArena, pushSpans, resetSpanArena, spanArenaToList)+import NanoUI.Internal.Frame.TextArea (textAreaTextPlacements)+import NanoUI.Internal.Frame.TextInput (TextInputFrame (..), nodeTextColor, nodeTextFieldGeom, resolveTextInputFrame, textInputFg)+import NanoUI.Internal.Input (Input)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Solve (findAncestorMaxW, textWrapCap)+import NanoUI.Internal.Style (AlignX (..), Style (..), Theme (..), resolveFontSize, textToneColor)+import NanoUI.Internal.Types (Color (..), Rect (..), clamp, isBounded, onGrid, rectIntersect)+import NanoUI.Internal.Widgets.ColorPicker (ColorPickerPart (..), colorPickerPartOf, colorPickerPartRect, colorPickerPreviewGeom)+import NanoUI.Internal.WidgetText++-- | Collect page text after layout, omitting spans covered by opaque floating+-- panels. Each tuple is bounds, text, foreground, background, clip; coordinates+-- are logical window coordinates. Rebuilds the context's base span arena.+collectTextSpans :: Context -> IO [(Rect, T.Text, Color, Color, Rect)]+collectTextSpans ctx@Context {ctxSpanBase = arena} = do+  count <- arenaCount (ctxNodeArena ctx)+  resetSpanArena arena+  when (count > 0) $+    collectClippedSpans ctx 0 (Rect 0 0 1e9 1e9) arena+  panels <- floatingPanelRects ctx+  spanArenaToList panels arena++-- | Collect window, modal, popup, dropdown, and edit-menu text in paint order.+-- Uses the same tuple format as 'collectTextSpans' and rebuilds the overlay arena.+collectOverlayTextSpans :: Context -> Input -> IO [(Rect, T.Text, Color, Color, Rect)]+collectOverlayTextSpans ctx@Context {ctxSpanOverlay = arena} inp = do+  resetSpanArena arena+  mapM_ (\nt -> collectFloatingSpansInto ctx nt arena) [NodeWindow, NodeModal, NodePopup]+  collectDropdownSpans ctx inp >>= pushSpans arena+  spanArenaToList IM.empty arena++-- | Collect base and overlay text separately for a host that rasterises text itself.+-- Under external text, each list ends with the drawing text of the last+-- painted (or reused) frame, in paint order, as line boxes with a+-- transparent background and the drawing's clip. 'collectTextSpans' and+-- 'collectOverlayTextSpans' leave those spans out.+collectRasterSpans :: Context -> Input -> IO ([(Rect, T.Text, Color, Color, Rect)], [(Rect, T.Text, Color, Color, Rect)])+collectRasterSpans ctx inp = do+  base <- collectTextSpans ctx+  overlay <- collectOverlayTextSpans ctx inp+  (drawnBase, drawnOverlay) <- dfeTextSpans <$> readIORef (daExtra (ctxDrawArena ctx))+  -- Without drawing spans the node lists are returned as they are, uncopied.+  -- Strict, so the pair holds no thunks.+  let withDrawn xs ys = if null ys then xs else xs ++ reverse ys+      !base' = withDrawn base drawnBase+      !overlay' = withDrawn overlay drawnOverlay+  pure (base', overlay')++-- | Total live arena nodes, including containers and decorative nodes.+widgetNodeCount :: Context -> IO Int+widgetNodeCount ctx = arenaCount (ctxNodeArena ctx)++-- | Spans of node @idx@ and its subtree inside @clip@, floating subtrees left+-- out.+collectClippedSpans :: Context -> NodeIdx -> Rect -> SpanArena -> IO ()+collectClippedSpans ctx@Context {ctxFontMetrics = fm} idx clip arena = do+  nt <- getNodeType (ctxNodeArena ctx) idx+  unless (isFloatingNode nt) $ do+    Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx+    mClipChildren <-+      if isScrollNode nt+        then+          getClipBounds (ctxNodeArena ctx) idx >>= \case+            Just live -> pure (rectIntersect clip live)+            Nothing -> (\sn -> rectIntersect clip (scrollNodeViewport sn x y w h)) <$> readScrollNode (ctxNodeArena ctx) idx+        else+          if isContainerNode nt+            then maybe (Just clip) (rectIntersect clip) <$> childPaintClip ctx idx nt (Rect x y w h)+            else pure (Just clip)+    forM_ mClipChildren $ \clipHere -> do+      -- A text node's spans are cached per node until its inputs change.+      -- Placement uses glyph ink ('alignedTextPen'), not TTF_GetStringSize;+      -- wrapping still measures with the host so line breaks stay on the TTF+      -- width.+      spans <-+        if nt == NodeText+          then sceSpans <$> textNodeSpanEntry ctx idx x y w h+          else if isWidgetNode nt && nt /= NodeTextArea then widgetTextSpans ctx nt idx x y w h else pure []+      here <-+        case nt of+          -- A select's label shares one clip, short of its chevron.+          NodeSelect -> do+            let (ix, _) = widgetContentInset fm+                label = padTextClipRect (Rect (x + ix) y (max 0 (w - ix - selectChevronReserve)) (max 0 h))+            pure [(r, t, fg, bg, c) | Just c <- [rectIntersect clipHere label], (r, t, fg, bg) <- spans]+          NodeTextInput -> do+            si <- getStyleIdx (ctxNodeArena ctx) idx+            if hasFlag textInputFlagSelectable si+              then pure (tagClippedSpans clipHere spans)+              else do+                -- The text clip paint uses ('nodeTextFieldGeom').+                (_, fieldClip) <- nodeTextFieldGeom ctx idx x y w h+                pure (maybe [] (`tagClippedSpans` spans) (rectIntersect clipHere fieldClip))+          -- The document lives in the text area's buffer: its rows in view,+          -- clipped as paint clips them, short of the scrollbars.+          NodeTextArea -> do+            (textClip, rows) <- textAreaTextPlacements ctx idx (Rect x y w h)+            rowSpans <- placedTextSpans ctx nt idx rows+            pure (maybe [] (`tagClippedSpans` rowSpans) (rectIntersect clipHere textClip))+          NodeContainer -> pure (tagClippedSpans clipHere spans)+          NodeText -> pure (tagClippedSpans clipHere spans)+          NodeSpacer -> pure (tagClippedSpans clipHere spans)+          NodeSeparator -> pure (tagClippedSpans clipHere spans)+          NodeButton -> pure (tagClippedSpans clipHere spans)+          NodeSlider -> pure (tagClippedSpans clipHere spans)+          NodeScrollContainer -> pure (tagClippedSpans clipHere spans)+          NodeModal -> pure (tagClippedSpans clipHere spans)+          NodeImage -> pure (tagClippedSpans clipHere spans)+          NodePanel -> pure (tagClippedSpans clipHere spans)+          NodeWindow -> pure (tagClippedSpans clipHere spans)+          NodeBox -> pure (tagClippedSpans clipHere spans)+          NodeColorPicker -> pure (tagClippedSpans clipHere spans)+          NodePopup -> pure (tagClippedSpans clipHere spans)+          NodeDrawing -> pure (tagClippedSpans clipHere spans)+          NodeShader -> pure (tagClippedSpans clipHere spans)+      pushSpans arena here+      kids <- getFirstChild (ctxNodeArena ctx) idx+      -- A widget clips its children, as paint does.+      unless (kids < 0) $+        forM_ (if isWidgetNode nt then rectIntersect clipHere (Rect x y w h) else Just clipHere) $ \childClip ->+          walkChildSpans ctx idx childClip arena++walkChildSpans :: Context -> NodeIdx -> Rect -> SpanArena -> IO ()+walkChildSpans ctx idx clip arena = getFirstChild (ctxNodeArena ctx) idx >>= go+  where+    go ci+      | ci < 0 = pure ()+      | otherwise = do+          ns <- getNextSibling (ctxNodeArena ctx) ci+          -- Sibling links run last to first, so recursing before collecting+          -- yields declaration order, which is reading order. It is not+          -- paint order ('forChildrenInPaintOrder_'), which differs where+          -- siblings overlap.+          go ns+          collectClippedSpans ctx ci clip arena++-- | Text node @idx@'s span cache entry at @(x, y)@, @w@ by @h@, brought up to+-- date: its spans, and the metrics prepared for each line, which paint draws+-- with.+textNodeSpanEntry :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> IO SpanCacheEntry+textNodeSpanEntry ctx@Context {ctxNodeArena = arena} idx x y w h = do+  theme <- nodeTheme ctx idx+  raw <- getText arena idx+  si <- getStyleIdx arena idx+  mCustomCol <- getNodeFontColor arena idx+  fontSize <- getNodeFontSize arena idx+  ax <- getAlignX arena idx+  AxisSizing wTag wVal minW maxW <- getWidthSizing arena idx+  isRowChild <- parentIsRow arena idx+  -- 'nodeTextLines' wraps a row child only at its own newlines, and other+  -- text that is not fit at the width it was given ('textWrapCap'), so only+  -- otherwise does the ancestor cap matter; skip the walk to the root. A+  -- fixed width caps itself within its limits, as the solve measures it.+  effMaxW <-+    if wTag == SizingFixed+      then pure (clamp minW maxW wVal)+      else if isBounded maxW || (if isRowChild then not (T.any (== '\n') raw) else wTag /= SizingFit && w > 0)+        then pure maxW+        else findAncestorMaxW arena idx+  -- Wrap at the width layout laid the node out at, before its edges+  -- snapped ('GeomLaidW'), where layout wrapped it. A node restored or placed+  -- without snapping has none recorded.+  laid <- arenaArrays arena >>= \a -> readGeom a idx GeomLaidW+  let rect = Rect x y w h+      !laidW = if laid > 0 then laid else w+      mStripe = tableStripeColor theme si+      fg = fromMaybe (textToneColor theme (textNodeFontTone si)) mCustomCol+      bg = fromMaybe (styleBg (themePanel theme)) mStripe+      !ix = tableStripeInset si+      -- What the lines depend on: everything but where the node is and+      -- how tall, and the colours. Inlined at both uses, so a cache hit+      -- allocates no closure for it.+      {-# INLINE sameLines #-}+      sameLines e =+        sceText e == raw+          && sceStyle e == si+          && sceFontSize e == fontSize+          && sceWidthTag e == fromEnum wTag+          && rectW (sceRect e) == w+          && sceLaidW e == laidW+          && sceEffMaxW e == effMaxW+          && sceRowChild e == isRowChild+          && sceInset e == ix+  cache <- readIORef (ctxSpanCache ctx)+  case IM.lookup idx cache of+    Just e+      | sameLines e+          && sceRect e == rect+          && sceFg e == fg+          && sceBg e == bg+          && sceAlign e == fromEnum ax ->+          pure e+    mEntry -> do+      (fm, textLines) <- case mEntry of+        Just e | sameLines e -> pure (sceFont e, sceLines e)+        _ -> nodeTextLines ctx raw si fontSize wTag maxW effMaxW isRowChild ix laidW+      let spans = [(r, line, fg, bg) | (r, line) <- placeSpanLines ax fm ix x y w h textLines]+          entry =+            SpanCacheEntry+              { sceText = raw+              , sceFg = fg+              , sceBg = bg+              , sceStyle = si+              , sceFontSize = fontSize+              , sceAlign = fromEnum ax+              , sceWidthTag = fromEnum wTag+              , sceRect = rect+              , sceLaidW = laidW+              , sceEffMaxW = effMaxW+              , sceRowChild = isRowChild+              , sceInset = ix+              , sceFont = fm+              , sceLines = textLines+              , sceSpans = spans+              }+      writeIORef (ctxSpanCache ctx) $ IM.insert idx entry cache+      pure entry++-- | A text node's lines for width @w@ and the font they are set in: wrapped+-- where the node wraps (through the context's wrap cache, which the solve+-- shares), otherwise one line, truncated to fit a node that grows or has a+-- maximum width.+nodeTextLines ::+  Context -> T.Text -> Word64 -> Float -> SizingTag -> Float -> Float -> Bool -> Float -> Float -> IO (FontMetrics, SpanLines)+nodeTextLines ctx raw si fontSize wTag maxW effMaxW isRowChild ix w+  | T.null raw = pure (ctxFontMetrics ctx, SpanWrapped [])+  | otherwise = do+      (fm, _, measure) <- resolveFontFor ctx NodeText fontSize si+      let measureW = fmap fst . measure+          contentW = max 0 (w - 2 * ix)+          noWrap = isRowChild || textNodeSingleLine si+          -- A row child or single-line text wraps only at explicit newlines.+          wrapCap = if noWrap then effMaxW else textWrapCap effMaxW wTag w+      tw <- measureW raw+      if T.any (== '\n') raw || (not noWrap && isBounded wrapCap && wrapCap + 0.5 < tw)+        then do+          let !resolvedSize = resolveFontSize (ctxFontSize ctx) fontSize+          wrap <- cachedWrapText ctx (textNodeFontKey resolvedSize si) measureW raw (max 0 (wrapCap - 2 * ix))+          prepared <- forM (wrLines wrap) $ \line -> (,) line <$> prepareFontMetrics fm line+          pure (fm, SpanWrapped prepared)+        else do+          -- Half a pixel over the width is no reason to cut, as it is none+          -- to wrap.+          shown <-+            if tw > contentW + 0.5 && contentW > 0 && (wTag == SizingGrow || isBounded maxW || textNodeSingleLine si)+              then truncateTextWithIO (textNodeEllipsis si) measureW contentW raw+              else pure raw+          (,) fm . SpanSingle shown <$> prepareFontMetrics fm shown++-- | Where the lines of a text node at @(x, y)@, @w@ by @h@, go.+placeSpanLines :: AlignX -> FontMetrics -> Float -> Float -> Float -> Float -> Float -> SpanLines -> [(Rect, T.Text)]+placeSpanLines ax fm ix x y w h = \case+  SpanWrapped textLines ->+    [ (Rect tx ty used lineH, line)+    | (i, (line, prepared)) <- zip [(0 :: Int) ..] textLines+    , let (tx, used) = alignedTextPen ax x w ix prepared line+          ty = centeredTextY fm (y + onGrid (fmSnapScale fm) (fromIntegral i * lineH)) lineH lineH+    ]+  SpanSingle shown prepared ->+    let (tx, used) = alignedTextPen ax x w ix prepared shown+     in [(Rect tx (centeredTextY fm y h lineH) used lineH, shown)]+  where+    lineH = fmLineHeight fm++widgetTextSpans ::+  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(Rect, T.Text, Color, Color)]+widgetTextSpans ctx nt idx x y w h = do+  placements <-+    -- A centred label's placement depends on its text, style, font, alignment+    -- and size but not its origin, so it is cached. Field, picker and slider+    -- text depends on their data.+    if hasCenteredLabel nt+      then do+        (lx, lw, ax) <- labelBox ctx nt idx x w+        placement <- cachedWidgetLabel ctx nt idx ax lw h+        pure [(txt, lx + px, y + py, tw, th) | Just (WidgetTextPlacement txt px py tw th) <- [placement]]+      else computeWidgetTextPlacements ctx nt idx x y w h+  placedTextSpans ctx nt idx placements++-- | Widget @idx@'s text placements as spans in its text colour.+placedTextSpans :: Context -> NodeType -> NodeIdx -> [(T.Text, Float, Float, Float, Float)] -> IO [(Rect, T.Text, Color, Color)]+placedTextSpans ctx nt idx placements = do+  style <- widgetVisualStyle ctx nt idx+  let bg = styleBg style+  case nt of+    NodeTextInput -> do+      fg <- join (textInputFg ctx idx (styleFg style) bg <$> textInputValue ctx idx <*> textInputFocused ctx idx)+      pure [(Rect px py tw th, txt, fg, bg) | (txt, px, py, tw, th) <- placements]+    -- Only a text field fades its text while empty; every other widget's+    -- text takes its node's colour.+    _ -> do+      fg <- nodeTextColor ctx nt idx (styleFg style)+      pure [(Rect px py tw th, txt, fg, bg) | (txt, px, py, tw, th) <- placements, not (T.null txt)]++-- | Runtime consumer API. The Bool marks the last placement (for table sort+-- arrows); cached labels are translated directly into the consumer.+{-# INLINE forWidgetTextPlacements_ #-}+forWidgetTextPlacements_ ::+  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float ->+  (Bool -> T.Text -> Float -> Float -> Float -> Float -> IO ()) -> IO ()+forWidgetTextPlacements_ ctx nt idx x y w h emit+  | hasCenteredLabel nt = do+      (lx, lw, ax) <- labelBox ctx nt idx x w+      placement <- cachedWidgetLabel ctx nt idx ax lw h+      forM_ placement $ \(WidgetTextPlacement txt px py tw th) ->+        emit True txt (lx + px) (y + py) tw th+  | otherwise = do+      placements <- computeWidgetTextPlacements ctx nt idx x y w h+      let go [] = pure ()+          go ((txt, px, py, tw, th) : rest) =+            emit (null rest) txt px py tw th >> go rest+      go placements++-- | The span of widget @idx@, at @x@ and @w@ wide, its label is placed in,+-- and how a button's label aligns there: beside adornments, the room between+-- them, the label kept to their side so it never runs into one.+{-# INLINE labelBox #-}+labelBox :: Context -> NodeType -> NodeIdx -> Float -> Float -> IO (Float, Float, AlignX)+labelBox ctx nt idx x w+  | nt /= NodeButton = pure (x, w, AlignCenter)+  | otherwise = do+      insets <- nodeAdornmentInsets na idx x w+      si <- getStyleIdx na idx+      -- A vertical tab strip's header starts its label at its padding.+      pure (beside (if tabLabelAtStart si then tabHeaderPadX else 0) insets)+  where+    na = ctxNodeArena ctx+    beside start (lead, trail)+      | lead > 0 = (x + lead, max 0 (w - lead - trail), AlignStart)+      | trail > 0 = (x, max 0 (w - trail), AlignEnd)+      | start > 0 = (x + start, max 0 (w - start), AlignStart)+      | otherwise = (x, w, AlignCenter)++-- | A widget's label placed across @w@, a button's aligned by @labelAlign@.+cachedWidgetLabel :: Context -> NodeType -> NodeIdx -> AlignX -> Float -> Float -> IO (Maybe WidgetTextPlacement)+cachedWidgetLabel ctx nt idx labelAlign w h = do+  let na = ctxNodeArena ctx+  a <- arenaArrays na+  fontSizeVal <- readStyle a idx StyleFontSize+  si <- readStyleIdx a idx+  txt <- if nt == NodeButton then getText na idx else displayText ctx nt idx+  ax <-+    if nt == NodeButton && buttonKindOf si == ButtonTable+      then readAlignX a idx+      else pure labelAlign+  let !ntTag = fromEnum nt+  cache <- readIORef (ctxWidgetTextCache ctx)+  case IM.lookup idx cache of+    Just e+      | wtcNodeType e == ntTag+          && wtcStyle e == si+          && wtcFontSize e == fontSizeVal+          && wtcText e == txt+          && wtcWidth e == w+          && wtcHeight e == h+          && wtcAlign e == fromEnum ax -> pure (wtcPlacement e)+    _ -> do+      placement <- computeWidgetLabel ctx nt txt si fontSizeVal ax w h+      writeIORef+        (ctxWidgetTextCache ctx)+        (IM.insert idx (WidgetTextCacheEntry ntTag si fontSizeVal txt w h (fromEnum ax) placement) cache)+      pure placement++-- All coordinates here are local. centeredTextY snaps the baseline offset,+-- not the origin; final device-pixel snapping stays in the draw backend.+computeWidgetLabel :: Context -> NodeType -> T.Text -> Word64 -> Float -> AlignX -> Float -> Float -> IO (Maybe WidgetTextPlacement)+computeWidgetLabel ctx nt txt si fontSizeVal ax w h+  | kind == ButtonClose = pure Nothing+  | otherwise = do+      (source, _, measure) <- resolveFontFor ctx nt fontSizeVal si+      (tw0, th) <- measure txt+      let (ix, _) = widgetContentInset source+          isTable = kind == ButtonTable+          plain = nt == NodeButton && kind `notElem` [ButtonChoice, ButtonRow, ButtonTable, ButtonMenu]+          -- The room a plain button's or a select's label has: inside the+          -- padding layout gave a centred label, all of the box beside+          -- adornments, and short of a select's chevron.+          room+            | isTable = max 0 (w - tableHeaderPadX)+            | nt == NodeSelect = w - ix - selectChevronReserve+            | ax /= AlignCenter = w+            | kind == ButtonTab = w - 2 * tabHeaderPadX+            | otherwise = w - fst (buttonPadding source)+      -- A label longer than that ends in an ellipsis.+      (label, tw) <-+        if (plain || isTable || nt == NodeSelect) && tw0 > room + 0.5+          then do+            let ell = textNodeEllipsis (nodeFontBits nt si)+            cut <- truncateTextWithIO ell (fmap fst . measure) room txt+            (cut,) . fst <$> measure cut+          else pure (txt, tw0)+      -- Metrics for the label as it is shown, which places it.+      fm <- prepareFontMetrics source label+      let (tx, used)+            | nt /= NodeButton = (ix, min tw (w - ix - selectChevronReserve))+            | otherwise = case kind of+                ButtonChoice -> (checkboxLeading fm, tw)+                ButtonRow ->+                  let (depth, _, _) = treeDecodeStyle si+                   in (treeRowLeading fm depth, tw)+                ButtonTable -> alignedTextPen ax 0 w tableCellInset fm label+                ButtonMenu ->+                  let inset = menuItemPadX + ix+                   in (inset, min tw (max 0 (w - inset - ix)))+                _ -> alignedTextPen ax 0 w 0 fm label+      let !placement = WidgetTextPlacement label tx (centeredTextY fm 0 h th) used th+      pure (Just placement)+  where+    -- A select is the other widget with a centred label.+    !kind = if nt == NodeButton then buttonKindOf si else ButtonPlain++-- | Pure geometry of selectable text: the pen origin, centered baseline box and+-- line height. Selectable text never scrolls, so the pen is just the node x.+-- Paint uses this and skips the width measure; span placement adds it.+selectableTextGeometry :: FontMetrics -> Float -> Float -> Float -> (Float, Float, Float)+selectableTextGeometry fm x y h =+  let lineH = fmLineHeight fm+   in (x, centeredTextY fm y h lineH, lineH)++computeWidgetTextPlacements ::+  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(T.Text, Float, Float, Float, Float)]+computeWidgetTextPlacements ctx nt idx x y w h = do+  fontSizeVal <- getNodeFontSize (ctxNodeArena ctx) idx+  si <- getStyleIdx (ctxNodeArena ctx) idx+  (fm, _, measureTxt) <- resolveFontFor ctx nt fontSizeVal si+  let lineH = fmLineHeight fm+  case nt of+    NodeColorPicker+      | colorPickerPartOf si /= PickerPreview -> pure []+      | otherwise -> do+          band@(Rect bx _ _ _) <- colorPickerPartRect (ctxNodeArena ctx) idx (Rect x y w h)+          let (currentY, _, newY, _) = colorPickerPreviewGeom fm band+          forM [("Current", currentY), ("New", newY)] $ \(lbl, ly) -> do+            (lw, lh) <- measureTxt lbl+            pure (lbl, bx, centeredTextY fm ly lineH lh, lw, lh)+    NodeTextInput+      | hasFlag textInputFlagSelectable si -> do+          value <- textInputValue ctx idx+          let (penX, ty, selLineH) = selectableTextGeometry fm x y h+          (fw, _) <- measureTxt value+          pure [(value, penX, ty, fw, selLineH)]+      | otherwise -> do+          (box, clip) <- nodeTextFieldGeom ctx idx x y w h+          focus <- textInputFocused ctx idx+          ph <- if hasFlag textInputFlagNumeric si then pure "" else getText (ctxNodeArena ctx) idx+          TextInputFrame _ _ _ shown penX penY _ <- resolveTextInputFrame ctx idx si focus box clip+          let fieldTxt = textInputFieldText ph shown focus+          (fw, _) <- measureTxt fieldTxt+          pure [(fieldTxt, penX, penY, fw, lineH)]+    -- Text areas place their rows with their clip+    -- ('textAreaTextPlacements'), and buttons and selects have centred+    -- labels ('cachedWidgetLabel').+    NodeTextArea -> pure []+    NodeButton -> pure []+    NodeSelect -> pure []+    -- Sliders and drawings carry no text, and the other node types are not+    -- widgets.+    NodeContainer -> pure []+    NodeText -> pure []+    NodeSpacer -> pure []+    NodeSeparator -> pure []+    NodeSlider -> pure []+    NodeScrollContainer -> pure []+    NodeModal -> pure []+    NodeImage -> pure []+    NodePanel -> pure []+    NodeWindow -> pure []+    NodeBox -> pure []+    NodePopup -> pure []+    NodeDrawing -> pure []+    NodeShader -> pure []++-- | Spans inside every floating panel of one kind, clipped to its content box.+collectFloatingSpansInto :: Context -> NodeType -> SpanArena -> IO ()+collectFloatingSpansInto ctx wanted arena =+  forFloatingNodes_ (ctxNodeArena ctx) wanted $ \idx -> do+    Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx+    clip <- padContentClip x y w h <$> getPadding (ctxNodeArena ctx) idx+    walkChildSpans ctx idx clip arena
+ lib/NanoUI/Internal/Frame/TextArea.hs view
@@ -0,0 +1,560 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Multi-line text areas in the frame: their geometry (the field box,+-- content clip and which scrollbars show where), the node font and cached+-- content extent, content painting (lines, selection, caret and scrollbars)+-- and mouse selection. Also the dispatchers that pick between the two kinds+-- of text field.+module NanoUI.Internal.Frame.TextArea+  ( -- * Dispatch between field kinds+    finalizeTextFieldMouse+  , collapseTextFieldSelection+  , textWordBounds+  , TextInputArea (..)+  , textInputArea+    -- * Geometry+  , textAreaLineHeight+  , textAreaBarLane+  , TextAreaBars (..)+  , textAreaBars+  , textAreaBarLayouts+    -- * Content+  , resolveTextAreaFont+  , textAreaContentMetrics+  , textAreaScrollGeom+  , isMouseOnTextAreaScrollBarAt+  , TextAreaHit (..)+  , textAreaHitForWidget+    -- * Painting+  , drawTextAreaContentWith+  , textAreaTextPlacements+  ) where++import Control.Monad (forM, forM_, unless, when)+import Data.IORef (readIORef, writeIORef)+import Data.Maybe (isJust)+import Data.Sequence (Seq)+import qualified Data.Sequence as Seq+import qualified Data.Text as T+import NanoUI.Internal.Context+import NanoUI.Internal.Draw (DrawArena, getDrawSnapScale, withClip)+import NanoUI.Internal.Font+import NanoUI.Internal.Frame.Chrome (paintScrollBars, textInputFocused)+import NanoUI.Internal.Frame.Hit (withWidgetNode)+import NanoUI.Internal.Layout.ScrollGeometry (ScrollBarLayout (..), scrollBarLayoutIn, scrollChromeLane)+import NanoUI.Internal.Frame.Node (nodeFontMetrics, nodeFontNative, packedTextFont, resolveTextFont)+import NanoUI.Internal.Frame.TextInput (FieldDoc (..), Preedit (..), drawCaretAt, drawLineCaret, drawLinePreedit, drawLineSelection, fieldEditLine, fieldTextColor, nodeTextFieldGeom, preeditSourceIndex, pushFieldText, selectWithMouse, splicePreedit, textInputMouse, textWordBounds)+import NanoUI.Internal.Id (WidgetId, hashWidgetId)+import NanoUI.Internal.Input (Input, InputPurpose, MouseButton (..), Pressable (..), inputMousePos)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Store (collapseFieldSelection, deleteSpec, findSpec, insertSpec, lookupSpec, memberSpec)+import NanoUI.Internal.Store.Slots (slotTextAreaAnchorCol, slotTextAreaAnchorRow, slotTextAreaBuffer, slotTextAreaLineH, slotTextAreaReveal, slotTextAreaScroll, slotTextAreaViewport, slotTextAreaWidths, slotTextInputScroll)+import NanoUI.Internal.Store.Types (LineWidths (..))+import NanoUI.Internal.Style+import NanoUI.Internal.Types (Rect (..), V2 (..), clamp, onGrid, rectContains)+import NanoUI.Internal.WidgetText (textNodeFontKey)+import qualified NanoUI.Internal.Widgets.TextArea as TA+import qualified NanoUI.Widgets.TextBuffer as TB++-- | Mouse selection in the focused field, whichever kind it is. A release+-- ends any drag. @onControl@: this frame's press is on a control drawn inside+-- the field ('NanoUI.Internal.Frame.Input.ptFieldControl').+finalizeTextFieldMouse :: Context -> Input -> Bool -> IO ()+finalizeTextFieldMouse ctx inp onControl = do+  focus <- readIORef (ctxFocusId ctx)+  when (hashWidgetId focus /= 0) $+    withWidgetNode ctx focus () $ \idx -> do+      getNodeType (ctxNodeArena ctx) idx >>= \case+        NodeTextInput -> textInputMouse ctx inp onControl focus idx+        -- An edited document is measured here, not in paint, whose cache+        -- write would damage and wake the next frame. Nothing else is read+        -- until the pointer acts.+        NodeTextArea -> do+          _ <- textAreaContentMetrics ctx idx+          when (pressedIn MouseLeft inp || heldIn MouseLeft inp || releasedIn MouseLeft inp) $+            textAreaMouse ctx inp onControl focus idx+        _ -> pure ()+      -- A selection dragged past the field's edge scrolls a step a frame, as+      -- the caret follows the pointer. A pointer held still out there sends+      -- no input to run those frames, so ask for them while the drag lasts.+      when (heldIn MouseLeft inp) $ do+        mDrag <- getsInteraction ctx isTextInputDrag+        forM_ mDrag $ \drag ->+          when (textInputDragWidget drag == focus) $ do+            rect <- getNodeRect (ctxNodeArena ctx) idx+            unless (rectContains rect (inputMousePos inp)) $+              requestWakeAfter ctx (1 / 60)+  when (releasedIn MouseLeft inp) $+    modifyInteraction ctx (\s -> s {isTextInputDrag = Nothing})++-- | Collapse selection in a current single-line or multiline field onto its+-- cursor. Zero, missing, and non-text widget ids do nothing.+collapseTextFieldSelection :: Context -> WidgetId -> IO ()+collapseTextFieldSelection ctx wid =+  withWidgetNode ctx wid () $ \idx ->+    getNodeType (ctxNodeArena ctx) idx >>= \case+      NodeTextInput -> modifyStore ctx (collapseFieldSelection key)+      -- An unstored anchor reads as the cursor ('TA.loadTextAreaState').+      NodeTextArea ->+        modifyStore ctx $+          deleteSpec slotTextAreaAnchorRow key . deleteSpec slotTextAreaAnchorCol key+      _ -> pure ()+ where+  key = intKey wid++-- | Where the focused widget takes text, in logical window coordinates, so+-- the input method can place its candidate window. See 'textInputArea'.+data TextInputArea = TextInputArea+  { textInputAreaRect :: !Rect+  -- ^ The composed text's extent on its row, or a caret-wide rect when+  -- nothing is composed.+  , textInputAreaCursor :: !Float+  -- ^ Caret offset from the rect's left edge.+  , textInputAreaPurpose :: !InputPurpose+  -- ^ Kind of input, which selects an on-screen keyboard layout.+  }+  deriving (Eq, Show)++-- | The text input area of the widget that requested the input method last+-- view, or 'Nothing'. Focused text fields request it, as do custom widgets+-- via 'NanoUI.useInputMethod'. Backends read it after each frame to start or+-- stop text input and pass it on (SDL's @SDL_SetTextInputArea@) so the+-- candidate window sits beside the text, not over it. For text fields it+-- tracks scroll and composition, including right-to-left runs.+textInputArea :: Context -> IO (Maybe TextInputArea)+textInputArea ctx@Context {ctxNodeArena = na} =+  readIORef (ctxInputMethod ctx) >>= \case+    Nothing -> pure Nothing+    Just (InputMethodRequest _ (Just caret) purpose) -> pure (Just (TextInputArea caret 0 purpose))+    Just (InputMethodRequest wid Nothing purpose) -> withWidgetNode ctx wid Nothing $ \idx -> do+      store <- getStore ctx+      let key = intKey wid+      getNodeType na idx >>= \case+        NodeTextInput -> do+          Rect x y w h <- getNodeRect na idx+          (Rect _ boxY _ boxH, Rect clipX _ _ _) <- nodeTextFieldGeom ctx idx x y w h+          fm <- nodeFontMetrics ctx idx+          -- Read the scroll the frame already settled, without writing it.+          let scrollX = findSpec slotTextInputScroll 0 key store+          (line, caret, _, preedit) <- fieldEditLine ctx idx+          Just <$> lineInputArea fm line caret preedit (clipX - scrollX) (centeredTextY fm boxY boxH (fmLineHeight fm)) (fmLineHeight fm) purpose+        NodeTextArea -> do+          fm <- resolveTextAreaFont ctx idx+          field <- getNodeRect na idx+          let state = TA.loadTextAreaState store key+              buf = TA.tasBuffer state+              TB.Cursor caretRow caretCol = TB.getCursor buf+              lineH = textAreaLineHeight fm+              Rect clipX contentTop _ _ = textAreaFieldClip fm field+          (scrollXf, scrollYf) <- textAreaScrollSnapped (ctxDrawArena ctx) state+          preedit <- textAreaPreedit ctx wid state+          let (row, line, caret) = case preedit of+                Just (r, p) -> (r, preeditLine p, preeditCaret p)+                Nothing -> (caretRow, TB.lineAt caretRow buf, caretCol)+          Just <$> lineInputArea fm line caret (snd <$> preedit) (clipX - scrollXf) (contentTop + fromIntegral row * lineH - scrollYf) lineH purpose+        _ -> pure Nothing++-- | 'TextInputArea' for @line@ drawn from @penX@ on a row at @rowY@ of+-- height @lineH@, caret before character @caret@.+lineInputArea :: FontMetrics -> T.Text -> Int -> Maybe Preedit -> Float -> Float -> Float -> InputPurpose -> IO TextInputArea+lineInputArea fm line caret preedit penX rowY lineH purpose = do+  prepared <- prepareFontMetrics fm line+  let caretAt = penX + caretX prepared line caret+      runs = maybe [] (\p -> selectionSpans prepared line (preeditStart p) (preeditEnd p)) preedit+      (x0, x1)+        | null runs = (caretAt, caretAt + 1)+        | otherwise = (penX + minimum (map fst runs), penX + maximum (map snd runs))+  pure (TextInputArea (Rect x0 rowY (max 1 (x1 - x0)) lineH) (max 0 (caretAt - x0)) purpose)++-- | Text area row height, snapped to the device pixel grid.+textAreaLineHeight :: FontMetrics -> Float+textAreaLineHeight fm = onGrid (fmSnapScale fm) (fmLineHeight fm)++-- | Text clip of a text area field. A caption-less text area's field is its+-- whole node rect.+textAreaFieldClip :: FontMetrics -> Rect -> Rect+textAreaFieldClip fm (Rect fx fy fw fh) =+  let s = fmSnapScale fm+      (ix, iy) = widgetContentInset fm+   in Rect (fx + onGrid s ix) (fy + onGrid s iy) (max 0 (fw - 2 * ix)) (max 0 (fh - 2 * iy))++-- | Width of the vertical and height of the horizontal scrollbar lane.+textAreaBarLane :: Float+textAreaBarLane = fst (scrollBarGeomFor ScrollBarList) + scrollBarSideGap++-- | Which scrollbars a text area shows for its content extent, the offset+-- each axis reaches, the paddings that place each bar's lane, and the extent.+-- The extent across is a pixel wider than the widest line, for the caret+-- after its last character.+data TextAreaBars = TextAreaBars+  { tabVertical :: !Bool+  , tabHorizontal :: !Bool+  , tabRange :: {-# UNPACK #-} !V2+  , tabPadV :: !Padding+  , tabPadH :: !Padding+  , tabContent :: {-# UNPACK #-} !V2+  }++-- | The bars for a text area with font metrics @fm@ and field rect, whose+-- widest line is @widestW@ and whose lines are @contentH@ tall in total.+{-# INLINE textAreaBars #-}+textAreaBars :: FontMetrics -> Rect -> Float -> Float -> TextAreaBars+textAreaBars fm (Rect _ _ fw fh) widestW contentH =+  let (ix, iy) = widgetContentInset fm+      contentW = widestW + 1+      innerW = max 0 (fw - 2 * ix)+      innerH = max 0 (fh - 2 * iy)+      lane = textAreaBarLane+      -- Either bar's lane can push the other axis into overflow.+      hasV = contentH > (if contentW > innerW then max 0 (innerH - lane) else innerH)+      hasH = contentW > (if contentH > innerH then max 0 (innerW - lane) else innerW)+      viewW = if hasV then max 0 (innerW - lane) else innerW+      viewH = if hasH then max 0 (innerH - lane) else innerH+   in TextAreaBars+        { tabVertical = hasV+        , tabHorizontal = hasH+        , tabRange = V2 (max 0 (contentW - viewW)) (max 0 (contentH - viewH))+        , tabPadV = Padding 0 0 iy (if hasH then iy + lane else iy)+        , tabPadH = Padding ix (if hasV then ix + lane else ix) 0 0+        , tabContent = V2 contentW contentH+        }++-- | The vertical and the horizontal bar of the text area at @field@ at+-- offsets @scrollX scrollY@, in logical pixels; 'Nothing' for a bar it does+-- not show.+{-# INLINE textAreaBarLayouts #-}+textAreaBarLayouts :: Rect -> TextAreaBars -> Float -> Float -> (Maybe ScrollBarLayout, Maybe ScrollBarLayout)+textAreaBarLayouts (Rect x y w h) bars scrollX scrollY =+  let V2 contentW contentH = tabContent bars+      padV = tabPadV bars+      padH = tabPadH bars+      -- The pads only place the bars: the text has no trailing padding to+      -- scroll past, so each bar's range is its axis's 'tabRange'.+      layout shown dir pad view content off+        | shown = scrollBarLayoutIn ScrollBarList dir (Rect x y w h) pad view 0 content off+        | otherwise = Nothing+   in ( layout (tabVertical bars) DirColumn padV (h - padT padV - padB padV) contentH scrollY+      , layout (tabHorizontal bars) DirRow padH (w - padL padH - padR padH) contentW scrollX+      )++-- | Font the text-area content is laid out and painted in. Honors the+-- node's font size and the face, weight and slant packed in its style (set+-- via 'fontSize', 'fontMono' and the like on the editor layout) so a single+-- text area can zoom or set code without changing the rest of the UI. A size+-- of 0 means the base UI font's.+resolveTextAreaFont :: Context -> NodeIdx -> IO FontMetrics+resolveTextAreaFont ctx idx = do+  size <- getNodeFontSize (ctxNodeArena ctx) idx+  si <- getStyleIdx (ctxNodeArena ctx) idx+  fst <$> resolveTextFont ctx (packedTextFont size si)++-- | Content extent of a text area, @(contentWidth, contentHeight)@. Measuring+-- the width scans every character of the document, so the widths are kept+-- per line, with the extent, and only the lines an edit touched since they+-- were measured ('TB.changedLines') are measured again, or every line once the+-- node font or the metrics change.+textAreaContentMetrics :: Context -> NodeIdx -> IO (Float, Float)+textAreaContentMetrics ctx idx = do+  wid <- getWidgetId (ctxNodeArena ctx) idx+  size <- getNodeFontSize (ctxNodeArena ctx) idx+  si <- getStyleIdx (ctxNodeArena ctx) idx+  store <- getStore ctx+  gen <- readIORef (ctxMetricGen ctx)+  let key = intKey wid+      face = textNodeFontKey (resolveFontSize (ctxFontSize ctx) size) si+      buf = TA.textAreaBuffer store key+      lns = TB.bufferLines buf+      (seenHead, seenTail) = TB.changedLines buf+      cached = lookupSpec slotTextAreaWidths key store+  case cached of+    Just (LineWidths font fontGen _ _ widestW contentH)+      | font == face && fontGen == gen && seenHead >= Seq.length lns -> pure (widestW, contentH)+    _ -> do+      fm <- resolveTextAreaFont ctx idx+      let contentH = fromIntegral (max 1 (Seq.length lns)) * textAreaLineHeight fm+          LineWidths _ _ measured widest widestW _ = case cached of+            Just lw@(LineWidths font fontGen _ _ _ _) | font == face && fontGen == gen -> lw+            _ -> LineWidths face gen Seq.empty (-1) 0 0+          -- Keep the widths of the lines no edit touched since the last+          -- measurement and measure the rest.+          keepHead = min seenHead (Seq.length measured)+          keepTail = min seenTail (Seq.length measured - keepHead)+          changed = Seq.take (Seq.length lns - keepHead - keepTail) (Seq.drop keepHead lns)+      fresh <- traverse (lineWidthIO fm) changed+      let widths = Seq.take keepHead measured <> fresh <> Seq.drop (Seq.length measured - keepTail) measured+          shift = Seq.length lns - Seq.length measured+          widestFrom :: Int -> Seq Float -> (Int, Float)+          widestFrom off = Seq.foldlWithIndex (\best i w -> if w > snd best then (off + i, w) else best) (-1, 0)+          freshWidest = widestFrom keepHead fresh+          -- The widest line so far still counts when it was kept; only when+          -- an edit touched it do the widths need a full pass.+          -- A changed line at least as wide as the old widest also still wins.+          (widest', contentW)+            | widest >= 0 && widest < keepHead = pick (widest, widestW) freshWidest+            | widest >= 0 && widest >= Seq.length measured - keepTail = pick (widest + shift, widestW) freshWidest+            | widest >= 0 && snd freshWidest >= widestW = freshWidest+            | otherwise = widestFrom 0 widths+          pick a b = if snd b > snd a then b else a+      -- Line-width metrics are a derived cache; write directly so cold queries+      -- during paint do not wake a redundant extra frame.+      writeIORef (ctxStore ctx) $!+        insertSpec slotTextAreaWidths key (LineWidths face gen widths widest' contentW contentH)+          (insertSpec slotTextAreaBuffer key (TB.markLinesSeen buf) store)+      pure (contentW, contentH)++-- | Field rect and scrollbars of a text area, for its node font and content+-- extent. Zoom changes the node font, so scroll and hit math resolve it here+-- rather than using the base font, or the scroll range would clamp short.+textAreaScrollGeom :: Context -> NodeIdx -> IO (Rect, TextAreaBars)+textAreaScrollGeom ctx idx = do+  fm <- resolveTextAreaFont ctx idx+  field <- getNodeRect (ctxNodeArena ctx) idx+  (contentW, contentH) <- textAreaContentMetrics ctx idx+  pure (field, textAreaBars fm field contentW contentH)++-- | Whether @mouse@ is over a shown bar's lane or track. Uses the cached+-- content extent: this runs on every hover through the cursor query. Lanes+-- and tracks stay put as the text scrolls, so any offset places them.+isMouseOnTextAreaScrollBarAt :: Context -> NodeIdx -> V2 -> IO Bool+isMouseOnTextAreaScrollBarAt ctx idx mouse = do+  (field@(Rect x y w h), bars) <- textAreaScrollGeom ctx idx+  let (mV, mH) = textAreaBarLayouts field bars 0 0+      onBar dir pad =+        maybe False $ \layout ->+          rectContains (scrollChromeLane ScrollBarList dir x y w h pad) mouse+            || rectContains (sbTrack layout) mouse+  pure (onBar DirColumn (tabPadV bars) mV || onBar DirRow (tabPadH bars) mH)++-- | Solved text-area geometry: its node, field rect and resolved line height,+-- in logical pixels. The node index is valid only this frame.+data TextAreaHit = TextAreaHit+  { tahNodeIdx :: !NodeIdx+  , tahFieldRect :: !Rect+  , tahLineH :: !Float+  }++-- | Geometry and resolved line height for a current text-area node. Returns+-- 'Nothing' for a missing id or a different node type. Call after layout.+textAreaHitForWidget :: Context -> WidgetId -> IO (Maybe TextAreaHit)+textAreaHitForWidget ctx wid = do+  withWidgetNode ctx wid Nothing $ \idx -> do+    nt <- getNodeType (ctxNodeArena ctx) idx+    if nt /= NodeTextArea+      then pure Nothing+      else do+        field <- getNodeRect (ctxNodeArena ctx) idx+        fm <- resolveTextAreaFont ctx idx+        pure (Just (TextAreaHit idx field (textAreaLineHeight fm)))++-- | Record the text viewport and clamp the stored scroll to the content, and+-- return the content extent. A saved editor state ('SlotTextAreaReveal') has+-- its caret, 1 px wide, scrolled into view across, which takes the font, as+-- 'resolveTextInputFrame' does for a field; its x is returned too, for drawing+-- the caret. This paint already reflects all of it, so the write marks+-- nothing dirty: a window resize would otherwise request a second frame that+-- has nothing to repaint.+syncTextAreaViewport :: Context -> NodeIdx -> Int -> FontMetrics -> Rect -> IO ((Float, Float), Maybe Float)+syncTextAreaViewport ctx idx key fm field = do+  extent@(contentW, contentH) <- textAreaContentMetrics ctx idx+  -- Read after the metrics query: a cold query caches into the store.+  store <- getStore ctx+  let bars = textAreaBars fm field contentW contentH+      Rect _ _ viewW viewH = textAreaTextClip fm field bars+      V2 sx sy = findSpec slotTextAreaScroll (V2 0 0) key store+      reveal = memberSpec slotTextAreaReveal key store+  wid <- getWidgetId (ctxNodeArena ctx) idx+  let state = TA.loadTextAreaState store key+  mPre <- textAreaPreedit ctx wid state+  caretAt <-+    if reveal || isJust mPre+      then do+        let buf = TA.tasBuffer state+            TB.Cursor row col = TB.getCursor buf+            (line, caretCol) = case mPre of+              Just (_, pre) -> (preeditLine pre, preeditCaret pre)+              Nothing -> (TB.lineAt row buf, col)+        Just <$> caretXIO fm line caretCol+      else pure Nothing+  let revealX at = revealSpanInViewport sx viewW (max contentW (at + 1)) at 1+      V2 sx' sy' = clampScrollOffset (tabRange bars) (V2 (maybe sx revealX caretAt) sy)+      lineH = textAreaLineHeight fm+      scrolled = sx' /= sx || sy' /= sy+      resized = lookupSpec slotTextAreaViewport key store /= Just (V2 viewW viewH)+      relined = lookupSpec slotTextAreaLineH key store /= Just lineH+  -- Commands run between frames keep the caret in view with the viewport+  -- and the row height. Only what changed is written: every keystroke clears+  -- the reveal flag.+  when (reveal || scrolled || resized || relined) $+    writeIORef (ctxStore ctx) $!+      deleteSpec slotTextAreaReveal key+        . (if scrolled then insertSpec slotTextAreaScroll key (V2 sx' sy') else id)+        . (if relined then insertSpec slotTextAreaLineH key lineH else id)+        $ (if resized then insertSpec slotTextAreaViewport key (V2 viewW viewH) store else store)+  -- A glide aimed past a range that shrank (the text got shorter) would+  -- never land, since the offset is clamped back here every frame.+  clampScrollGlide ctx wid (tabRange bars)+  pure (extent, caretAt)+++-- | A text area's scroll offset snapped to the device pixel grid, the same+-- grid 'NanoUI.Internal.Draw.pushText' snaps to, so line pens and+-- hit-testing stay in lockstep (and in agreement with each other) while the+-- text area scrolls. The raw 'Double' offset keeps sub-pixel wheel deltas;+-- only the applied value is quantized.+{-# INLINE textAreaScrollSnapped #-}+textAreaScrollSnapped :: DrawArena -> TA.TextAreaState -> IO (Float, Float)+textAreaScrollSnapped da state = do+  s <- getDrawSnapScale da+  let (scrollX, scrollY) = TA.tasScrollOffset state+  pure (onGrid s (realToFrac scrollX), onGrid s (realToFrac scrollY))++-- | Shared per-frame view state for painting, span collection, and mouse hit-testing.+data TextAreaView+  = TextAreaView !TA.TextAreaState !(Float, Float) !(Maybe (Int, Preedit)) !TextAreaBars !Rect !Float++readTextAreaView :: DrawArena -> Context -> WidgetId -> Int -> FontMetrics -> Rect -> (Float, Float) -> IO TextAreaView+readTextAreaView da ctx wid key fm field (contentW, contentH) = do+  state <- (`TA.loadTextAreaState` key) <$> getStore ctx+  scroll <- textAreaScrollSnapped da state+  preedit <- textAreaPreedit ctx wid state+  let bars = textAreaBars fm field contentW contentH+  pure (TextAreaView state scroll preedit bars (textAreaTextClip fm field bars) (textAreaLineHeight fm))++-- | First and last document row visible inside @field@, clamped to @buf@.+-- Only the rows in view are read, so painting costs the same however long the+-- document is.+visibleRowRange :: Rect -> Float -> Float -> Float -> TB.TextBuffer -> (Int, Int)+visibleRowRange (Rect _ y _ h) contentTop scrollYf lineH buf =+  let rowAt py = floor ((py - contentTop + scrollYf) / max 1 lineH)+   in (max 0 (rowAt y), min (TB.getLineCount buf - 1) (rowAt (y + h)))++-- | Text-area content with the node font already resolved, so a paint pass+-- that also needs it (for the field frame) resolves it once.+drawTextAreaContentWith :: DrawArena -> Context -> FontMetrics -> NodeIdx -> Float -> Float -> Float -> Float -> Style -> IO ()+drawTextAreaContentWith da ctx fm idx x y w h style = do+  wid <- getWidgetId (ctxNodeArena ctx) idx+  let key = intKey wid+      field = Rect x y w h+  (extent, caretAt) <- syncTextAreaViewport ctx idx key fm field+  focus <- textInputFocused ctx idx+  theme <- nodeTheme ctx idx+  TextAreaView state (scrollXf, scrollYf) preedit bars textClip@(Rect clipX contentTop _ _) lineH <-+    readTextAreaView da ctx wid key fm field extent+  -- The layout's colour or tone, and the weight, slant and decoration the+  -- font gives no face for, as a text field's.+  fg <- fieldTextColor ctx idx (styleFg style)+  si <- getStyleIdx (ctxNodeArena ctx) idx+  size <- getNodeFontSize (ctxNodeArena ctx) idx+  native <- nodeFontNative ctx size si+  let buf = TA.tasBuffer state+      cursor@(TB.Cursor caretRow caretCol) = TB.getCursor buf+      contentX = clipX - scrollXf+      rowY row = contentTop + fromIntegral row * lineH - scrollYf+      (mV, mH) = textAreaBarLayouts field bars scrollXf scrollYf+      (firstRow, lastRow) = visibleRowRange field contentTop scrollYf lineH buf+      (lo, hi) = TB.selectionRange (TA.tasSelectionAnchor state) cursor+  withClip da textClip $ do+    when (focus && (lo /= hi || isJust preedit)) $+      forM_ [max (TB.cursorRow lo) firstRow .. min (TB.cursorRow hi) lastRow] $ \row -> do+        let line = TB.lineAt row buf+            clampCol c = clamp 0 (T.length line) c+            -- On the composition row, show the input method's selection+            -- instead of the field's.+            (shown, startCol, endCol) = case preedit of+              Just (prow, p) | prow == row -> (preeditLine p, preeditCaret p, preeditSelectionEnd p)+              _ ->+                ( line+                , clampCol (if row == TB.cursorRow lo then TB.cursorCol lo else 0)+                , clampCol (if row == TB.cursorRow hi then TB.cursorCol hi else T.length line)+                )+        when (startCol < endCol) $+          drawLineSelection da fm shown startCol endCol contentX (rowY row) lineH (themeSelection theme)+    forM_ [firstRow .. lastRow] $ \row -> do+      let line = fst (shownRow preedit buf row)+      unless (T.null line) $+        pushFieldText da fm native si contentX (rowY row) line fg+    when focus $+      case preedit of+        Just (row, p) -> drawLinePreedit da fm p contentX (rowY row) lineH fg+        -- Measured already when the sync scrolled it into view.+        Nothing -> case caretAt of+          Just at -> drawCaretAt da (contentX + at) (rowY caretRow) lineH fg+          Nothing -> drawLineCaret da fm (TB.lineAt caretRow buf) caretCol contentX (rowY caretRow) lineH fg+  paintScrollBars ctx da theme (themePanel theme) wid mV mH++-- | Text area @wid@'s composition ('fieldComposition'): its row, and that+-- row with the composition spliced over the selection ('splicePreedit'). A+-- multi-row selection stays highlighted on other rows, since a commit+-- replaces all of it.+textAreaPreedit :: Context -> WidgetId -> TA.TextAreaState -> IO (Maybe (Int, Preedit))+textAreaPreedit ctx wid state = do+  composition <- fieldComposition ctx wid+  let buf = TA.tasBuffer state+      (lo, hi) = TB.selectionRange (TA.tasSelectionAnchor state) (TB.getCursor buf)+      row = TB.cursorRow lo+      line = TB.lineAt row buf+      endCol = if TB.cursorRow hi == row then TB.cursorCol hi else T.length line+  pure $ (\c -> (row, splicePreedit c line (TB.cursorCol lo) endCol)) <$> composition++-- | Row @row@ as displayed, composition included ('textAreaPreedit'), with+-- a map from displayed columns to document columns.+shownRow :: Maybe (Int, Preedit) -> TB.TextBuffer -> Int -> (T.Text, Int -> Int)+shownRow (Just (prow, p)) _ row | prow == row = (preeditLine p, preeditSourceIndex p)+shownRow _ buf row = (TB.lineAt row buf, id)++-- | The clip the rows of the text area at @field@ showing @bars@ are painted+-- in, which is the viewport the editor keeps the caret in: its content clip,+-- short of the lane of each scrollbar it shows.+textAreaTextClip :: FontMetrics -> Rect -> TextAreaBars -> Rect+textAreaTextClip fm field bars =+  let Rect x y w h = textAreaFieldClip fm field+      short shown d = if shown then max 0 (d - textAreaBarLane) else d+   in Rect x y (short (tabVertical bars) w) (short (tabHorizontal bars) h)++-- | Text area @idx@'s rows in view as text placements @(text, x, y, width,+-- height)@, and the clip they are painted in: what 'drawTextAreaContentWith'+-- draws, for hosts that draw text themselves. Empty rows are left out.+textAreaTextPlacements :: Context -> NodeIdx -> Rect -> IO (Rect, [(T.Text, Float, Float, Float, Float)])+textAreaTextPlacements ctx idx field = do+  fm <- resolveTextAreaFont ctx idx+  wid <- getWidgetId (ctxNodeArena ctx) idx+  extent <- textAreaContentMetrics ctx idx+  TextAreaView state (scrollXf, scrollYf) preedit _ clip@(Rect clipX contentTop _ _) lineH <-+    readTextAreaView (ctxDrawArena ctx) ctx wid (intKey wid) fm field extent+  let buf = TA.tasBuffer state+      (firstRow, lastRow) = visibleRowRange field contentTop scrollYf lineH buf+  let visibleLines =+        [(row, line) | row <- [firstRow .. lastRow], let line = fst (shownRow preedit buf row), not (T.null line)]+  placements <- forM visibleLines $ \(row, line) -> do+    lw <- lineWidthIO fm line+    pure (line, clipX - scrollXf, contentTop + fromIntegral row * lineH - scrollYf, lw, lineH)+  pure (clip, placements)++-- | Mouse selection in text area @wid@ at @idx@ ('selectWithMouse'). Presses+-- on its scrollbars are left to the scroller, and a press on a control drawn+-- inside it (@onControl@) to the control.+textAreaMouse :: Context -> Input -> Bool -> WidgetId -> NodeIdx -> IO ()+textAreaMouse ctx inp onControl wid idx = do+  field <- getNodeRect (ctxNodeArena ctx) idx+  let mouse@(V2 mouseX mouseY) = inputMousePos inp+      key = intKey wid+  selectWithMouse ctx inp wid field (if onControl then pure True else isMouseOnTextAreaScrollBarAt ctx idx mouse) $ do+    fm <- resolveTextAreaFont ctx idx+    extent <- textAreaContentMetrics ctx idx+    TextAreaView state0 (scrollXf, scrollYf) preedit _ (Rect clipX contentTop vpW vpH) lineH <-+      readTextAreaView (ctxDrawArena ctx) ctx wid key fm field extent+    -- The editor keeps the caret in view, so give it the viewport it has.+    let state = TA.setTextAreaViewport (realToFrac vpW, realToFrac vpH) (realToFrac lineH) state0+        buf = TA.tasBuffer state+        row = clamp 0 (TB.getLineCount buf - 1) (floor ((mouseY - contentTop + scrollYf) / max 1 lineH))+        -- Hit-test the displayed row, then map back to a document column.+        (line, toSource) = shownRow preedit buf row+    prepared <- prepareFontMetrics fm line+    let pos = TB.Cursor row (toSource (textIndexAtX prepared line (max 0 (mouseX - (clipX - scrollXf)))))+    -- Nothing writes the store between this load and the selection write+    -- (click counting lives in the interaction state). A selection that is+    -- already stored is not written again: the write would damage the area+    -- and wake the loop on every frame a button is held still.+    pure $ FieldDoc pos buf $ \anchor cursor ->+      unless (anchor == TA.tasSelectionAnchor state && cursor == TB.getCursor buf && TB.cursorCol cursor == TB.preferredCol buf) $+        modifyStore ctx (TA.saveTextAreaState key (TA.setTextAreaSelection anchor cursor state))
+ lib/NanoUI/Internal/Frame/TextEdit.hs view
@@ -0,0 +1,205 @@+-- | Editing text fields from outside their frame: the commands an app or the+-- context menu runs on a field by its id, and the context menu itself (Undo /+-- Redo / Cut / Copy / Paste / Select All): opening it, its popup, and+-- closing it.+module NanoUI.Internal.Frame.TextEdit+  ( applyTextFieldCommand+  , textFieldEditor+  , openTextEditMenu+  , textEditMenuView+  , closeTextEditMenuOnOutsideClick+  , closeTextEditMenuOnEscape+  , textFieldWidgetAtMouse+  ) where++import Control.Monad (forM, forM_, unless, when)+import Data.IORef (readIORef, writeIORef)+import Data.Maybe (isJust, listToMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import NanoUI.Internal.Context+import NanoUI.Internal.Frame.Hit (findNodeByWidgetId, reachedWidgetAt, widgetOverlayAllowed)+import NanoUI.Internal.Frame.TextArea (collapseTextFieldSelection, isMouseOnTextAreaScrollBarAt)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (NanoUI, askContext, ifM, liftIO, themed, whenM, withKey, (<&&>))+import NanoUI.Internal.Store (insertSpec, lookupSpec)+import NanoUI.Internal.Store.Slots (slotTextChanged, slotTextMode)+import NanoUI.Internal.Style (gap, tight)+import NanoUI.Internal.Types (DamageBounds (..), PopupAnchor (..), PopupPlacement (..), Rect (..), V2 (..), rectContains)+import NanoUI.Internal.Var.Types (constVar)+import NanoUI.Internal.Widgets.Layout (columnWith)+import NanoUI.Internal.Widgets.Menu (menuItem, menuItemDisabled, menuSeparator)+import NanoUI.Internal.Widgets.Node (respClicked, respRect)+import NanoUI.Internal.Widgets.Popup (PopupConfig (..), defaultPopupConfig, popupWith')+import NanoUI.Internal.Widgets.TextArea (textAreaFieldEditor)+import NanoUI.Internal.Widgets.TextDocument (sameLines)+import NanoUI.Internal.Widgets.TextInput (textInputFieldEditor, textInputMode)+import NanoUI.Widgets.TextBuffer qualified as TB+import NanoUI.Widgets.TextEditor++-- | Run a command on the field with this id and focus it: the command comes+-- from a menu or button that may not be over the field, and the caret,+-- selection highlight and next keystroke belong to the field it edited.+-- Focus moves at the end of the frame, as with+-- 'NanoUI.Internal.Monad.requestFocus', so disabled fields and fields behind a+-- modal cannot take focus. A change to the text pulses @respChanged@ on the+-- field's next frame.+applyTextFieldCommand :: Context -> WidgetId -> TextCommand -> IO ()+applyTextFieldCommand ctx wid cmd =+  textFieldEditor ctx wid >>= mapM_ (\(mode, ed0, save) -> do+    ed <- runCommandIO ctx mode cmd ed0 {editorHistory = sealHistory (editorHistory ed0)}+    let edited = not (sameLines (TB.bufferLines (editorBuffer ed)) (TB.bufferLines (editorBuffer ed0)))+        pulse = if edited then insertSpec slotTextChanged (intKey wid) 1 else id+    modifyStore ctx (pulse . save ed)+    -- Store damage is keyed on slots, not the widget: damage the widget so a+    -- selection-only command (Select All) repaints this frame.+    damageWidget ctx wid DamageSelf+    markDirty ctx+    writeIORef (ctxFocusRequest ctx) (Just (FocusOn wid))+    modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing}))++-- | Look up a text field's 'EditorMode', stored 'Editor', and store setter by+-- 'WidgetId' for out-of-frame commands. Uses the current frame's arena node if+-- present, or falls back to the mode recorded when the field was last+-- declared.+textFieldEditor :: Context -> WidgetId -> IO (Maybe (EditorMode, Editor, Editor -> WidgetStore -> WidgetStore))+textFieldEditor ctx wid = do+  store <- getStore ctx+  let key = intKey wid+  mMode <-+    findNodeByWidgetId ctx wid >>= \case+      Just idx ->+        getNodeType (ctxNodeArena ctx) idx >>= \case+          NodeTextInput -> Just . textInputMode <$> getStyleIdx (ctxNodeArena ctx) idx+          NodeTextArea -> pure (Just multiLineMode)+          _ -> pure Nothing+      Nothing -> pure (lookupSpec slotTextMode key store)+  pure $ flip fmap mMode $ \mode ->+    let (ed, save) = (if modeMultiLine mode then textAreaFieldEditor else textInputFieldEditor) store key+     in (mode, ed, save)++-- | The menu's rows in order: a command and its label, or a separator.+textEditMenuRows :: [Maybe (TextCommand, T.Text)]+textEditMenuRows =+  [ Just (Undo, "Undo")+  , Just (Redo, "Redo")+  , Nothing+  , Just (Cut, "Cut")+  , Just (Copy, "Copy")+  , Just (Paste, "Paste")+  , Nothing+  , Just (SelectAll, "Select All")+  ]++-- | Open the menu at the pointer over the text field a right press lands+-- on, and focus that field. 'textEditMenuView' shows it from the next view+-- pass on.+openTextEditMenu :: Context -> Input -> IO ()+openTextEditMenu ctx inp =+  when (pressedIn MouseRight inp) $ do+    let V2 mx my = inputMousePos inp+    mWid <- textFieldWidgetAtMouse ctx (inputMousePos inp)+    forM_ mWid $ \wid -> do+      prevFocus <- readIORef (ctxFocusId ctx)+      when (prevFocus /= wid) (collapseTextFieldSelection ctx prevFocus)+      writeIORef (ctxFocusId ctx) wid+      modifyInteraction ctx (\s -> s {isTextInputMenu = Just (TextInputMenu wid (V2 mx my) (Rect 0 0 0 0))})+      markDirty ctx++-- | The open text-edit menu as a popup at the press that opened it, in the+-- theme of its field, with a row per command; a command the field cannot run+-- now is a dimmed row. The frame declares it after the view, in a keyed scope+-- that moves no sibling id. Picking a row (a release on the row the press+-- went down on) runs the command on the field and records it+-- ('takeTextEditLastAction'). Escape or a press outside closes it. A menu+-- whose field a modal hides is not shown.+textEditMenuView :: NanoUI ()+textEditMenuView = do+  ctx <- askContext+  liftIO (getsInteraction ctx isTextInputMenu) >>= mapM_ (\(TextInputMenu wid at _) ->+    whenM (liftIO (widgetOverlayAllowed ctx wid)) $ do+      theme <- liftIO (widgetTheme ctx wid)+      let cfg = (defaultPopupConfig (AnchorPoint at)) {popupPlacement = PlacementAtCursor, popupOffset = 0}+      (resp, picked) <- withKey textEditMenuKey . themed theme . popupWith' (constVar True) cfg id $+        columnWith (tight . gap 0) $ fmap (listToMaybe . concat) . forM textEditMenuRows $ \case+          Nothing -> [] <$ menuSeparator+          Just (cmd, lbl) -> menuRow cmd lbl =<< liftIO (textFieldMenuEnabled ctx wid cmd)+      liftIO $ case picked of+        Just (Just cmd) -> do+          modifyInteraction ctx (\s -> s {isTextEditLastAction = Just (wid, cmd)})+          applyTextFieldCommand ctx wid cmd+        -- A dismissal (Escape, or a press outside) closes it. Otherwise it+        -- keeps the rect it was drawn at, which a press outside is judged by+        -- ('closeTextEditMenuOnOutsideClick').+        _+          | respClicked resp -> modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing})+          | otherwise -> modifyInteraction ctx (\s -> s {isTextInputMenu = (\m -> m {textInputMenuRect = respRect resp}) <$> isTextInputMenu s}))+ where+  menuRow cmd lbl enabled+    | enabled = (\c -> [cmd | c]) <$> menuItem lbl+    | otherwise = [] <$ menuItemDisabled lbl++-- | The key of the scope 'textEditMenuView' declares its popup in.+textEditMenuKey :: Text+textEditMenuKey = "nano-ui text edit menu"+++-- | The enabled text field or text area the pointer at @mouse@ is on, which+-- takes the text cursor and the right-click menu: the widget hover lands on+-- ('reachedWidgetAt'), when it is one. Excludes a field covered there by a+-- stack or pinned node and one whose inner control has the pointer.+textFieldWidgetAtMouse :: Context -> V2 -> IO (Maybe WidgetId)+textFieldWidgetAtMouse ctx@Context {ctxNodeArena = na} mouse = do+  tfCount <- textFieldNodeCount na+  if tfCount <= 0+    then pure Nothing+    else+      reachedWidgetAt ctx mouse >>= \case+        Nothing -> pure Nothing+        Just idx -> do+          nt <- getNodeType na idx+          wid <- getWidgetId na idx+          ifM+            ( pure (nt == NodeTextInput || nt == NodeTextArea)+                <&&> (not <$> isDisabled ctx wid)+                <&&> (if nt == NodeTextArea then not <$> isMouseOnTextAreaScrollBarAt ctx idx mouse else pure True)+            )+            (pure (Just wid))+            (pure Nothing)++-- | A press of any button anywhere but on the menu's popup, where the user+-- saw it ('textInputMenuRect'), closes it.+closeTextEditMenuOnOutsideClick :: Context -> Input -> IO ()+closeTextEditMenuOnOutsideClick ctx inp =+  when (anyButtonPressed inp) $+    getsInteraction ctx isTextInputMenu >>= mapM_ (\m ->+      unless (rectContains (textInputMenuRect m) (inputMousePos inp)) $+        modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing}))++closeTextEditMenuOnEscape :: Context -> Input -> IO ()+closeTextEditMenuOnEscape ctx inp =+  when (pressedOnceIn KeyEscape inp) $+    whenM (isJust <$> getsInteraction ctx isTextInputMenu) $ do+      modifyInteraction ctx (\s -> s {isTextInputMenu = Nothing})+      markEscapeConsumed ctx+      markDirty ctx++-- | Whether @cmd@ can run on field @wid@ now. Paste does not look at the+-- clipboard: this runs on every paint and pointer move over the menu, a read+-- can be a round trip to the program that owns it, and pasting an empty+-- clipboard does nothing.+textFieldMenuEnabled :: Context -> WidgetId -> TextCommand -> IO Bool+textFieldMenuEnabled ctx wid cmd =+  textFieldEditor ctx wid >>= \case+    Nothing -> pure False+    Just (mode, Editor buf _ history, _) -> case cmd of+      Undo -> pure (modeEditable mode && canUndo history)+      Redo -> pure (modeEditable mode && canRedo history)+      Cut -> pure (modeEditable mode && modeCopyable mode && hasText)+      Copy -> pure (modeCopyable mode && hasText)+      Paste -> pure (modeEditable mode)+      _ -> pure hasText+     where+      hasText = TB.getLineCount buf > 1 || not (T.null (TB.lineAt 0 buf))
+ lib/NanoUI/Internal/Frame/TextInput.hs view
@@ -0,0 +1,510 @@+-- | Single-line text fields: field geometry, horizontal scroll, caret and+-- selection painting, and mouse selection. Also holds the line painting, word+-- bounds and mouse selection the text area shares, and input-method+-- composition for both.+module NanoUI.Internal.Frame.TextInput+  ( nodeTextFieldGeom+  , TextInputFrame (..)+  , resolveTextInputFrame+  , FieldEdit+  , readFieldEdit+  , fieldEditLine+  , drawTextInputSelection+  , drawTextInputCaret+  , pushFieldText+  , fieldTextColor+  , textInputFg+  , nodeTextColor+  , drawLineSelection+  , drawLineCaret+  , drawCaretAt+  , drawLinePreedit+  , searchClearHit+  , textWordBounds+  , FieldDoc (..)+  , selectWithMouse+  , textInputMouse+    -- * Input-method composition+  , claimComposition+  , settleInputMethod+  , Preedit (..)+  , splicePreedit+  , preeditSourceIndex+  ) where++import Control.Monad (forM_, mfilter, when)+import Data.Char (isAlphaNum, isMark, isSpace)+import Data.IORef (readIORef, writeIORef)+import Data.Maybe (isJust)+import Data.Sequence qualified as Seq+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Draw (DrawArena, pushPreparedTextStyled, pushRect)+import NanoUI.Internal.Font (FontMetrics (..), caretXIO, centeredTextY, lineWidthIO, prepareFontMetrics, revealSpanInViewport, selectionSpans, textDecorationMetrics, textIndexAtX, widgetContentInset)+import NanoUI.Internal.Frame.Chrome (maskPassword, textInputFocused, textInputValue)+import NanoUI.Internal.Frame.Hit (withWidgetNode)+import NanoUI.Internal.Frame.Node (nodeAdornmentInsets, nodeFontMetrics, resolveFontFor)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (NodeIdx, NodeType (..), getNodeFontColor, getNodeFontSize, getNodeRect, getNodeType, getOptions, getStyleIdx, getWidgetId, nodeFontBits)+import NanoUI.Internal.Monad (ifM, unlessM, (<&&>))+import NanoUI.Internal.Store (fieldSelection, fieldSelectionWrite, fieldText, findSpec, insertSlot, insertSpec, setFieldSelection)+import NanoUI.Internal.Store.Slots (slotTextInputScroll)+import NanoUI.Internal.Style (FontStyle (..), FontWeight (..), themeSelection, toneColor)+import NanoUI.Internal.Types (Color (..), DamageBounds (..), Rect (..), V2 (..), clamp, lerpColor, rectContains, rectW)+import NanoUI.Internal.WidgetText+import NanoUI.Widgets.TextBuffer qualified as TB++textInputFieldRect :: FontMetrics -> Float -> Float -> Float -> Float -> Rect+textInputFieldRect fm x y w h =+  let fieldH = if h > 0 then h else textInputFieldHeight fm+   in Rect x y w fieldH++-- | Where plain field @idx@'s text goes in its box @field@: inside its own+-- font's content inset and clear of its adornments.+plainFieldTextClip :: Context -> NodeIdx -> Rect -> IO Rect+plainFieldTextClip ctx idx (Rect fx fy fw fh) = do+  fm <- nodeFontMetrics ctx idx+  (lead, trail) <- nodeAdornmentInsets (ctxNodeArena ctx) idx fx fw+  let (ix, _) = widgetContentInset fm+  pure (textClipBetween fm (max ix lead) (max ix trail) fx fy fw fh)++-- | Resolve the box a field paints/hits and the clip its text is confined to.+-- Search fields are caption-less: the whole node rect is the box and text is+-- clipped around the magnifier / clear chrome. Combo boxes (search fields+-- carrying dropdown options) clip to the left of the chevron instead. A plain+-- field clips its text short of its adornments.+nodeTextFieldGeom :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> IO (Rect, Rect)+nodeTextFieldGeom ctx@Context {ctxFontMetrics = fm} idx x y w h = do+  si <- getStyleIdx (ctxNodeArena ctx) idx+  opts <- getOptions (ctxNodeArena ctx) idx+  let box = Rect x y w h+      field = textInputFieldRect fm x y w h+  if hasFlag textInputFlagSelectable si+    then pure (box, box)+    else if hasFlag textInputFlagNumeric si+      then pure (box, numericTextClip fm x y w h)+      else if hasFlag textInputFlagSearch si+        then pure (box, if null opts then searchInputTextClip fm x y w h else comboTextClip fm x y w h)+        else (field,) <$> plainFieldTextClip ctx idx field++-- | Whether the pointer is over the clear (×) button of a non-empty search+-- field. Search fields reserve that slot even when empty, but the button is+-- only active when there is text to clear.+searchClearHit :: Context -> WidgetId -> V2 -> IO Bool+searchClearHit ctx wid mouse = do+  withWidgetNode ctx wid False $ \idx -> do+    si <- getStyleIdx (ctxNodeArena ctx) idx+    opts <- getOptions (ctxNodeArena ctx) idx+    pure (hasFlag textInputFlagSearch si && null opts)+      <&&> (not . T.null <$> textInputValue ctx idx)+      <&&> do+        Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx+        let (_, clearRect) = searchInputIconRects (ctxFontMetrics ctx) x y w h+        pure (rectContains clearRect mouse)++-- | Clear a search field. The debounced pulse picks the empty text up as an+-- immediate (empty) commit on the next frame, which the store write wakes.+clearSearchInput :: Context -> WidgetId -> IO ()+clearSearchInput ctx wid = do+  let key = intKey wid+  modifyStore ctx $+    insertSlot fieldText key "" . setFieldSelection key 0 0++-- | A field's or text area's text with its pen at @(x, y)@, in the weight,+-- slant and decoration packed in its style @si@, as a label draws them. The+-- weight and slant are synthesized unless the host drew the face natively+-- (@native@, from 'NanoUI.Internal.Frame.Node.resolveFontFor').+{-# INLINE pushFieldText #-}+pushFieldText :: DrawArena -> FontMetrics -> Bool -> Word64 -> Float -> Float -> Text -> Color -> IO ()+pushFieldText da fm native si x y txt col = do+  prepared <- prepareFontMetrics fm txt+  let !weight = if native then WeightNormal else textNodeFontWeight si+      !slant = if native then FontStyleNormal else textNodeFontStyle si+  pushPreparedTextStyled da prepared weight slant (textNodeTextDecoration si) x y txt col++-- | The colour of field or text area @idx@'s text: the layout's+-- 'fontColor', else its tone's ('fontTone', 'fontMuted' and the like), else+-- @fg@.+{-# INLINE fieldTextColor #-}+fieldTextColor :: Context -> NodeIdx -> Color -> IO Color+fieldTextColor ctx = nodeTextColor ctx NodeTextArea++-- | The colour of a text input's text ('fieldTextColor'), faded toward @bg@+-- while @value@ is empty and unfocused.+{-# INLINE textInputFg #-}+textInputFg :: Context -> NodeIdx -> Color -> Color -> Text -> Bool -> IO Color+textInputFg ctx idx fgCol bgCol value focus = do+  fg <- fieldTextColor ctx idx fgCol+  pure (if T.null value && not focus then lerpColor fg bgCol 0.40 else fg)++-- | 'fieldTextColor' for node @idx@ of type @nt@, whose tone sits in its+-- font bits: all of a text area's or field's style index, the label font of+-- a button or select ('nodeFontBits').+{-# INLINE nodeTextColor #-}+nodeTextColor :: Context -> NodeType -> NodeIdx -> Color -> IO Color+nodeTextColor ctx nt idx fg =+  getNodeFontColor (ctxNodeArena ctx) idx >>= \case+    Just c -> pure c+    Nothing -> do+      si <- getStyleIdx (ctxNodeArena ctx) idx+      let font = if nt == NodeTextArea then si else nodeFontBits nt si+      maybe (pure fg) (\t -> (`toneColor` t) <$> nodeTheme ctx idx) (textNodeFontTone font)++-- | The selection highlight behind characters @lo@ to @hi@ of @line@, whose+-- pen starts at @x@, on a row at @y@ of height @lineH@.+drawLineSelection :: DrawArena -> FontMetrics -> Text -> Int -> Int -> Float -> Float -> Float -> Color -> IO ()+drawLineSelection da fm line lo hi x y lineH color = do+  prepared <- prepareFontMetrics fm line+  forM_ (selectionSpans prepared line lo hi) $ \(wLo, wHi) ->+    when (wHi > wLo) $+      pushRect da (Rect (x + wLo) y (max 1 (wHi - wLo)) (max 4 lineH)) color++-- | The caret before character @col@ of @line@, whose pen starts at @x@, on a+-- row at @y@ of height @lineH@.+drawLineCaret :: DrawArena -> FontMetrics -> Text -> Int -> Float -> Float -> Float -> Color -> IO ()+drawLineCaret da fm line col x y lineH fg = do+  pw <- caretXIO fm line col+  drawCaretAt da (x + pw) y lineH fg++-- | A caret at @x@ on a row at @y@ of height @lineH@.+drawCaretAt :: DrawArena -> Float -> Float -> Float -> Color -> IO ()+drawCaretAt da x y lineH = pushRect da (Rect x (y + 1) 1 (max 4 (lineH - 2)))++-- | Underline the composition in 'preeditLine' (pen at @x@, row at @y@ of+-- height @lineH@) and draw the input method's caret when it has no+-- selection; a selection is drawn separately ('drawLineSelection'). The+-- underline follows bidi runs, so right-to-left compositions are underlined+-- where they are drawn.+drawLinePreedit :: DrawArena -> FontMetrics -> Preedit -> Float -> Float -> Float -> Color -> IO ()+drawLinePreedit da fm p x y lineH fg = do+  let line = preeditLine p+  prepared <- prepareFontMetrics fm line+  let (thick, underOff, _) = textDecorationMetrics lineH (fmAscent fm)+      underY = y + underOff+  forM_ (selectionSpans prepared line (preeditStart p) (preeditEnd p)) $ \(wLo, wHi) ->+    pushRect da (Rect (x + wLo) underY (max 1 (wHi - wLo)) thick) fg+  when (preeditSelectionEnd p == preeditCaret p) $+    drawLineCaret da fm line (preeditCaret p) x y lineH fg++-- | Sync horizontal scroll for a field whose font, edit line, and clip width+-- are already resolved. Writes the cache directly without scheduling an extra+-- frame.+syncTextInputScrollWith :: Context -> Int -> WidgetStore -> FontMetrics -> Bool -> Float -> Text -> Int -> IO Float+syncTextInputScrollWith ctx key store fm focus viewW shown cursor = do+  let oldScroll = findSpec slotTextInputScroll 0 key store+  newScroll <-+    if not focus || viewW <= 0+      then pure 0+      else do+        caretRelX <- caretXIO fm shown cursor+        totalTextW <- lineWidthIO fm shown+        pure (revealSpanInViewport oldScroll viewW (totalTextW + 1) caretRelX 1)+  when (newScroll /= oldScroll) $+    writeIORef (ctxStore ctx) $! insertSpec slotTextInputScroll key newScroll store+  pure newScroll++-- | The horizontal scroll that keeps field @idx@'s caret in view, zero while+-- it is unfocused, stored as it changes.+syncTextInputScroll :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> IO Float+syncTextInputScroll ctx idx x y w h = do+  si <- getStyleIdx (ctxNodeArena ctx) idx+  if hasFlag textInputFlagSelectable si+    then pure 0+    else do+      wid <- getWidgetId (ctxNodeArena ctx) idx+      store <- getStore ctx+      focus <- textInputFocused ctx idx+      viewW <- if focus then rectW . snd <$> nodeTextFieldGeom ctx idx x y w h else pure 0+      if not focus || viewW <= 0+        then syncTextInputScrollWith ctx (intKey wid) store (ctxFontMetrics ctx) False 0 "" 0+        else do+          fm <- nodeFontMetrics ctx idx+          (shown, cursor, _, _) <- fieldEditLine ctx idx+          syncTextInputScrollWith ctx (intKey wid) store fm True viewW shown cursor++-- | Single-pass resolved state for painting a single-line text field.+data TextInputFrame = TextInputFrame+  { tifFont :: !FontMetrics+  , tifNative :: !Bool+  , tifValue :: !Text+  , tifShown :: !Text+  , tifPenX :: !Float+  , tifRowY :: !Float+  , tifEdit :: !(Maybe FieldEdit)+  }++-- | Resolve font, masked value, composition line, horizontal scroll, centered+-- row Y, and optional 'FieldEdit' in one pass for a captionless or plain field.+resolveTextInputFrame :: Context -> NodeIdx -> Word64 -> Bool -> Rect -> Rect -> IO TextInputFrame+resolveTextInputFrame ctx idx si focus (Rect _ boxY _ boxH) (Rect clipX _ clipW _) = do+  let na = ctxNodeArena ctx+  fontSizeVal <- getNodeFontSize na idx+  (fm, native, _) <- resolveFontFor ctx NodeTextInput fontSizeVal si+  wid <- getWidgetId na idx+  store <- getStore ctx+  value <- textInputValue ctx idx+  (shown, cursor, anchor, preedit) <- fieldEditLineWith ctx wid store si value+  scrollX <- syncTextInputScrollWith ctx (intKey wid) store fm focus clipW shown cursor+  let !penX = clipX - scrollX+      !rowY = centeredTextY fm boxY boxH (fmLineHeight fm)+      !edit = if focus then Just (FieldEdit shown cursor anchor fm rowY penX preedit) else Nothing+  pure (TextInputFrame fm native value shown penX rowY edit)++-- | What a focused single-line field paints its selection and caret from: the+-- displayed value, cursor and anchor, the node font, the top of its text row,+-- the x its text starts at with the scroll applied, and any composition.+data FieldEdit = FieldEdit !Text !Int !Int !FontMetrics !Float !Float !(Maybe Preedit)++-- | Editing state of field @idx@, whose box is @box@ ('nodeTextFieldGeom')+-- and whose text starts at @penX@, scroll applied, or Nothing while it is+-- unfocused.+readFieldEdit :: Context -> NodeIdx -> Rect -> Float -> IO (Maybe FieldEdit)+readFieldEdit ctx idx (Rect _ boxY _ boxH) penX = do+  focus <- textInputFocused ctx idx+  if not focus+    then pure Nothing+    else do+      (value, cursor, anchor, preedit) <- fieldEditLine ctx idx+      fm <- nodeFontMetrics ctx idx+      pure $! Just (FieldEdit value cursor anchor fm (centeredTextY fm boxY boxH (fmLineHeight fm)) penX preedit)++-- | Resolve the displayed edit line, cursor, anchor, and optional preedit from+-- pre-fetched field metadata (shared by 'resolveTextInputFrame' and 'fieldEditLine').+fieldEditLineWith :: Context -> WidgetId -> WidgetStore -> Word64 -> Text -> IO (Text, Int, Int, Maybe Preedit)+fieldEditLineWith ctx wid store si value = do+  -- Lazy so callers that only need the text skip the selection lookup.+  let (anchor, cursor) = fieldSelection store (intKey wid) value+  fieldComposition ctx wid >>= \case+    Nothing -> pure (value, cursor, anchor, Nothing)+    Just c ->+      -- Password fields mask the composition too.+      let shown+            | hasFlag textInputFlagPassword si = c {compositionText = maskPassword (compositionText c)}+            | otherwise = c+          p = splicePreedit shown value (min anchor cursor) (max anchor cursor)+       in pure (preeditLine p, preeditCaret p, preeditSelectionEnd p, Just p)++-- | The line field @idx@ displays ('textInputValue') with its cursor and+-- anchor. During composition ('fieldComposition') the composition replaces+-- the selection (which a commit will replace), and cursor and anchor are the+-- input method's caret and selection end.+fieldEditLine :: Context -> NodeIdx -> IO (Text, Int, Int, Maybe Preedit)+fieldEditLine ctx idx = do+  value <- textInputValue ctx idx+  wid <- getWidgetId (ctxNodeArena ctx) idx+  store <- getStore ctx+  si <- getStyleIdx (ctxNodeArena ctx) idx+  fieldEditLineWith ctx wid store si value++drawTextInputSelection :: DrawArena -> Context -> NodeIdx -> FieldEdit -> IO ()+drawTextInputSelection da ctx idx (FieldEdit value cursor anchor fm rowY textX _) =+  when (anchor /= cursor) $ do+    theme <- nodeTheme ctx idx+    drawLineSelection da fm value (min anchor cursor) (max anchor cursor) textX rowY (fmLineHeight fm) (themeSelection theme)++-- | The field's caret, or the composition underline and input-method caret+-- while composing ('drawLinePreedit').+drawTextInputCaret :: DrawArena -> FieldEdit -> Color -> IO ()+drawTextInputCaret da (FieldEdit value cursor _ fm rowY textX preedit) fg =+  case preedit of+    Just p -> drawLinePreedit da fm p textX rowY (fmLineHeight fm) fg+    Nothing -> drawLineCaret da fm value cursor textX rowY (fmLineHeight fm) fg++data CharClass = WordChar | SpaceChar | OtherChar+  deriving (Eq)++-- | The run of word characters (letters, digits, underscores, combining+-- marks and the zero-width joiners), spaces or other characters around+-- character @raw@ of @text@, clamped into it. Positions count characters,+-- not UTF-8 bytes.+textWordBounds :: Text -> Int -> (Int, Int)+textWordBounds text raw+  | T.null text = (0, 0)+  | otherwise =+      -- Split once: repeatedly indexing UTF-8 text makes long-word selection+      -- quadratic. The clamped index guarantees a non-empty suffix.+      let i = clamp 0 (T.length text - 1) raw+          (before, after) = T.splitAt i text+          sameClass = (== charClass (T.head after)) . charClass+       in ( i - T.length (T.takeWhileEnd sameClass before)+          , i + T.length (T.takeWhile sameClass after)+          )+ where+  charClass c+    | isAlphaNum c || isMark c || c == '_' || c == '\x200C' || c == '\x200D' = WordChar+    | isSpace c = SpaceChar+    | otherwise = OtherChar++-- | A field's document at the pointer: the position under it, the document,+-- and how the field stores a selection (anchor, then cursor).+data FieldDoc = FieldDoc !TB.Cursor !TB.TextBuffer (TB.Cursor -> TB.Cursor -> IO ())++-- | Mouse selection in focused field @wid@: a press in @box@, with word and+-- whole-document multi-clicks, and the drag it starts. On a press+-- @chromePress@ runs first and takes the press when it lands on the field's+-- own chrome. @atMouse@ reads the document at the pointer.+selectWithMouse :: Context -> Input -> WidgetId -> Rect -> IO Bool -> IO FieldDoc -> IO ()+selectWithMouse ctx inp wid box chromePress atMouse+  | pressedIn MouseLeft inp && rectContains box (inputMousePos inp) =+      unlessM chromePress $ do+        FieldDoc pos buf select <- atMouse+        -- A press counts as a multi-click only on the cell of the press before.+        prev <- getsInteraction ctx isTextFieldClickCell+        let cell = Just (TextFieldClickCell wid pos)+            clicks = if prev == cell then max 1 (inputMouseClicks inp) else 1+        uncurry select (dragSelection buf pos pos clicks)+        modifyInteraction ctx $ \s ->+          s {isTextFieldClickCell = cell, isTextInputDrag = Just (TextInputDrag wid pos clicks)}+  | heldIn MouseLeft inp || releasedIn MouseLeft inp =+      getsInteraction ctx isTextInputDrag >>= \case+        Just (TextInputDrag dragWid anchor clicks) | dragWid == wid -> do+          FieldDoc pos buf select <- atMouse+          uncurry select (dragSelection buf anchor pos clicks)+        _ -> pure ()+  | otherwise = pure ()++-- | The selection a drag from @anchor@ to @pos@ makes after @clicks@ clicks:+-- characters, whole words, or the whole document. A click is a drag that has+-- not moved. Words run from the start of the earlier word to the end of the+-- later one, which may be on different rows.+dragSelection :: TB.TextBuffer -> TB.Cursor -> TB.Cursor -> Int -> (TB.Cursor, TB.Cursor)+dragSelection buf anchor@(TB.Cursor ar ac) pos@(TB.Cursor r c) clicks+  | clicks >= 3 = (TB.Cursor 0 0, TB.documentEnd buf)+  | clicks == 2 =+      let (a0, a1) = textWordBounds (TB.lineAt ar buf) ac+          (c0, c1) = textWordBounds (TB.lineAt r buf) c+       in if pos < anchor+            then (TB.Cursor ar a1, TB.Cursor r c0)+            else (TB.Cursor ar a0, TB.Cursor r c1)+  | otherwise = (anchor, pos)++-- | Mouse selection in single-line field @wid@ at @idx@ ('selectWithMouse'),+-- and a search field's clear button. A press on a control drawn inside the+-- field (@onControl@) is the control's, and leaves the caret alone.+textInputMouse :: Context -> Input -> Bool -> WidgetId -> NodeIdx -> IO ()+textInputMouse ctx inp onControl wid idx = do+  Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx+  (box, Rect clipX _ _ _) <- nodeTextFieldGeom ctx idx x y w h+  scrollX <- syncTextInputScroll ctx idx x y w h+  let mouse@(V2 mouseX _) = inputMousePos inp+      key = intKey wid+      clearPress = ifM (searchClearHit ctx wid mouse) (True <$ clearSearchInput ctx wid) (pure False)+  selectWithMouse ctx inp wid box (if onControl then pure True else clearPress) $ do+    fm <- nodeFontMetrics ctx idx+    value <- textInputValue ctx idx+    -- Hit-test the displayed text, then map back to a position in the value.+    (shown, _, _, preedit) <- fieldEditLine ctx idx+    prepared <- prepareFontMetrics fm shown+    let atX = textIndexAtX prepared shown (max 0 (mouseX - (clipX - scrollX)))+        pos = TB.Cursor 0 (maybe atX (`preeditSourceIndex` atX) preedit)+    pure $ FieldDoc pos (TB.fromLines (Seq.singleton value)) $ \(TB.Cursor _ anchor) (TB.Cursor _ cursor) ->+      writeSlots ctx (fieldSelectionWrite key value anchor cursor)++-- | Before the view runs, decide which widget shows the frame's composition+-- ('inputComposition'). The owner must be focused and must have requested+-- the input method last view ('requestInputMethod'). A composition keeps its+-- owner while unchanged; if focus leaves, it shows nowhere until the input+-- method updates it, so it never jumps to the next widget. Damages the old+-- and new owners.+--+-- Returns the frame's input and whether the input method owns the focused+-- widget's keys ('FocusComposing'). While a composition shows, all key+-- state is dropped so nothing edits the field or fires a shortcut; the+-- commit still arrives as typed text. So it is on the frame a composition+-- ends with nothing committed, whose key the input method took (an Escape+-- that cancels it, a Backspace on its last character). On the commit frame,+-- keys the input method passes on (an arrow after a Korean syllable) reach+-- the field but fire no shortcut.+--+-- Inlined into its single caller so the result pair is never allocated.+{-# INLINE claimComposition #-}+claimComposition :: Context -> Input -> IO (Input, Bool)+claimComposition ctx !inp = do+  focus <- readIORef (ctxFocusId ctx)+  held <- getsInteraction ctx isComposition+  taker <- maybe (WidgetId 0) imrWidget <$> readIORef (ctxInputMethod ctx)+  let new = mfilter (not . T.null . compositionText) (inputComposition inp)+      -- An unchanged composition keeps its owner; a new one goes to focus.+      claimant = case held of+        Just (old, o) | Just old == new -> if o == focus then o else WidgetId 0+        _ -> focus+      showing = maybe False (\(_, o) -> o == focus && hashWidgetId o /= 0)+      !owner = if isJust new && claimant == taker then claimant else WidgetId 0+      next = (,owner) <$> new+  when (next /= held) $ do+    modifyInteraction ctx (\s -> s {isComposition = next})+    mapM_ (\(_, old) -> damageWidget ctx old DamageSelf) held+    damageWidget ctx owner DamageSelf+  let !ended = showing held && not (showing next)+      !committing = ended && not (T.null (inputChars inp))+  pure $+    if showing next || (ended && not committing)+      then (inp {inputKeys = mempty, inputKeysNew = mempty, inputKeysReleased = mempty, inputKeysHeld = mempty}, True)+      else (inp, committing)++-- | At the end of a frame, move the input-method request to follow focus if+-- focus left the requesting widget ('requestInputMethod'), or left @before@+-- when nobody asked. The newly focused text field gets a request (or none+-- if it is not a field) until it asks for itself next view, so the backend+-- routes text and the next composition to it from this frame on.+settleInputMethod :: Context -> WidgetId -> IO ()+settleInputMethod ctx@Context {ctxNodeArena = na} before = do+  focus <- readIORef (ctxFocusId ctx)+  asked <- readIORef (ctxInputMethod ctx)+  when (maybe (focus /= before) ((/= focus) . imrWidget) asked) $ do+    let request purpose = Just (InputMethodRequest focus Nothing purpose)+        fieldRequest si+          | hasFlag textInputFlagSelectable si = Nothing+          | hasFlag textInputFlagPassword si = request InputSecure+          | hasFlag textInputFlagNumeric si = request InputNumeric+          | otherwise = request InputNormal+    field <-+      ifM (isDisabled ctx focus) (pure Nothing) . withWidgetNode ctx focus Nothing $ \idx ->+        getNodeType na idx >>= \case+          NodeTextArea -> pure (request InputNormal)+          NodeTextInput -> fieldRequest <$> getStyleIdx na idx+          _ -> pure Nothing+    writeIORef (ctxInputMethod ctx) field++-- | A line with a composition spliced in, as shown while composing.+-- Positions are character indices into 'preeditLine'.+data Preedit = Preedit+  { preeditLine :: !Text+  , preeditStart :: !Int+  , preeditEnd :: !Int+  -- ^ Composition span.+  , preeditCaret :: !Int+  , preeditSelectionEnd :: !Int+  -- ^ Input-method caret; the selection runs from the caret to here.+  , preeditReplaced :: !Int+  -- ^ Number of original characters the composition replaces.+  }++-- | Splice a composition into @line@ over characters @lo@ to @hi@ (the+-- selection, or an empty span at the caret). Positions are clamped.+splicePreedit :: Composition -> Text -> Int -> Int -> Preedit+splicePreedit (Composition txt cursor sel) line lo0 hi0 =+  let n = T.length line+      lo = clamp 0 n lo0+      hi = clamp lo n hi0+      len = T.length txt+      caret = lo + clamp 0 len cursor+   in Preedit+        { preeditLine = T.take lo line <> txt <> T.drop hi line+        , preeditStart = lo+        , preeditEnd = lo + len+        , preeditCaret = caret+        , preeditSelectionEnd = min (lo + len) (caret + max 0 sel)+        , preeditReplaced = hi - lo+        }++-- | Map a position in the displayed line back to the original line.+-- Positions inside the composition map to its start.+preeditSourceIndex :: Preedit -> Int -> Int+preeditSourceIndex p i+  | i <= preeditStart p = i+  | i >= preeditEnd p = i - (preeditEnd p - preeditStart p) + preeditReplaced p+  | otherwise = preeditStart p
+ lib/NanoUI/Internal/Frame/Window.hs view
@@ -0,0 +1,292 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Floating window input: dragging by the title bar, resizing by the edges+-- and margins, the resize cursor, and persisting window placement.+module NanoUI.Internal.Frame.Window+  ( contextMeasurers+  , lookupWindowPos+  , lookupWindowSize+  , persistWindowPositions+  , updateWindowDrag+  , updateWindowResize+  , windowResizeCursorKind+  ) where++import Control.Monad (forM_, guard, unless, when)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Maybe (MaybeT (..))+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Maybe (isJust, isNothing)+import NanoUI.Internal.Context+import NanoUI.Internal.Font (ScrollBarSlot (..))+import NanoUI.Internal.Frame.Hit+import NanoUI.Internal.Frame.Input (PressTargets (..), probeHotId, targetsAt)+import NanoUI.Internal.Layout.ScrollGeometry (scrollChromeLane)+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Input (Input (..), MouseButton (..), Pressable (..), UiCursorKind (..))+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Solve (Measurers (..), windowBodyScroller)+import NanoUI.Internal.Monad ((<&&>))+import NanoUI.Internal.Store (fieldPoint, insertSlot, insertSpec, lookupSlot, lookupSpec, ptrEq)+import NanoUI.Internal.Store.Slots (slotWinSize)+import NanoUI.Internal.Style (Padding (..))+import NanoUI.Internal.Types (Rect (..), Size (..), V2 (..), clamp, rectContains, rectInflate, rectNonEmpty)++-- | Saved floating-window x/y in logical pixels, or 'Nothing' before placement.+lookupWindowPos :: Context -> WidgetId -> IO (Maybe (Float, Float))+lookupWindowPos ctx wid = fmap (\(V2 x y) -> (x, y)) . lookupSlot fieldPoint (intKey wid) <$> getStore ctx++-- | Saved floating-window width/height in logical pixels, or 'Nothing'.+lookupWindowSize :: Context -> WidgetId -> IO (Maybe (Float, Float))+lookupWindowSize ctx wid = fmap (\(V2 w h) -> (w, h)) . lookupSpec slotWinSize (intKey wid) <$> getStore ctx++-- | Save solved floating-window positions and sizes to the store for later frames.+persistWindowPositions :: Context -> IO ()+persistWindowPositions ctx = floatingNodeCount na >>= \floating -> when (floating > 0) $ do+  store0 <- getStore ctx+  let record acc idx = do+        nt <- getNodeType na idx+        if nt /= NodeWindow+          then pure acc+          else do+            wid <- getWidgetId na idx+            Rect x y w h <- getNodeRect na idx+            let k = intKey wid+                posV = V2 x y+                sizeV = V2 w h+            -- Keep an unchanged store as is: the write below is skipped+            -- when it is the same object.+            pure $+              if lookupSlot fieldPoint k acc == Just posV && lookupSpec slotWinSize k acc == Just sizeV+                then acc+                else insertSlot fieldPoint k posV (insertSpec slotWinSize k sizeV acc)+  !store1 <- foldClassNodesM na FloatingNodes record store0+  unless (ptrEq store1 store0) $ setStore ctx store1+ where+  na = ctxNodeArena ctx++-- | Start or continue a title-bar drag and save its position. Returns 'True'+-- while a drag starts or is held; releases clear it. Resize gestures take priority.+updateWindowDrag :: Context -> Input -> IO Bool+updateWindowDrag ctx inp =+  (isNothing <$> getsInteraction ctx isWindowResize) <&&> do+    let drag (wid, gx, gy) = do+          let V2 mx my = inputMousePos inp+              Size winW winH = inputWindowSize inp+          -- Kept on screen as placement keeps it ('windowRect'), so a pointer+          -- held past an edge stores what the window shows and moves nothing.+          Rect _ _ w h <- withWidgetNode ctx wid (Rect 0 0 0 0) (getNodeRect (ctxNodeArena ctx))+          let px = clamp 0 (max 0 (winW - w)) (mx - gx)+              py = clamp 0 (max 0 (winH - h)) (my - gy)+          moved <- (/= Just (px, py)) <$> lookupWindowPos ctx wid+          when moved $ modifyStore ctx (insertSlot fieldPoint (intKey wid) (V2 px py))+          pure moved+    windowGesture ctx inp isWindowDrag (\s -> s {isWindowDrag = Nothing}) drag tryStartWindowDrag++-- | Continue the window gesture @held@ reads while the button is down, with+-- @step@, which moves its window and says whether it moved, and end it once+-- the button is up. With none held, a press may start one. Returns 'True'+-- while one starts or is held. A held gesture that moved nothing asks for no+-- frame, so a still pointer idles.+windowGesture ::+  Context -> Input -> (InteractionState -> Maybe g) -> (InteractionState -> InteractionState)+  -> (g -> IO Bool) -> (Context -> V2 -> IO Bool) -> IO Bool+windowGesture ctx inp held release step start =+  getsInteraction ctx held >>= \case+    Just g+      | heldIn MouseLeft inp -> do+          moved <- step g+          when moved (markDirty ctx)+          pure True+      | otherwise -> False <$ modifyInteraction ctx release+    Nothing+      | pressedIn MouseLeft inp -> start ctx (inputMousePos inp)+      | otherwise -> pure False++-- | How far the resize handles reach out past the window's edges.+windowResizeHandleFor :: Float+windowResizeHandleFor = 12++-- | The least a handle reaches in from an edge, for sides with no padding.+windowResizeInnerMin :: Float+windowResizeInnerMin = 6++-- | How far along an edge from a corner its handle resizes both ways.+windowResizeCornerReach :: Float+windowResizeCornerReach = 16++-- | Edge handle under @mouse@ for a window at @rect@ with padding @pad@. Each+-- side's handle runs from 'windowResizeHandleFor' outside the edge to the+-- side's padding inside it, and near a corner the handle takes both sides.+windowResizeEdgeAt :: Padding -> Rect -> V2 -> Maybe WindowResizeEdge+windowResizeEdgeAt pad (Rect x y w h) (V2 mx my)+  | onSide || onEnd = Just (WindowResizeEdge (side west east) (side north south))+  | otherwise = Nothing+  where+    s = windowResizeHandleFor+    inner p extent = min (extent / 3) (max windowResizeInnerMin p)+    reachW = min windowResizeCornerReach (w / 3)+    reachH = min windowResizeCornerReach (h / 3)+    inX = mx >= x - s && mx <= x + w + s+    inY = my >= y - s && my <= y + h + s+    onL = inY && mx >= x - s && mx < x + inner (padL pad) w+    onR = inY && mx > x + w - inner (padR pad) w && mx <= x + w + s+    onT = inX && my >= y - s && my < y + inner (padT pad) h+    onB = inX && my > y + h - inner (padB pad) h && my <= y + h + s+    onSide = onL || onR+    onEnd = onT || onB+    north = onT || (onSide && my < y + reachH)+    south = onB || (onSide && my > y + h - reachH)+    west = onL || (onEnd && mx < x + reachW)+    east = onR || (onEnd && mx > x + w - reachW)+    side lo hi = if lo then -1 else if hi then 1 else 0++cursorForResizeEdge :: WindowResizeEdge -> UiCursorKind+cursorForResizeEdge (WindowResizeEdge sx sy)+  | sx == 0 = UiCursorNsResize+  | sy == 0 = UiCursorEwResize+  | sx == sy = UiCursorNwseResize+  | otherwise = UiCursorNeswResize++-- | Width, height, x and y of the held resize's window with the pointer at+-- @mouse@, in a logical window of @winW@ by @winH@.+resizeFromEdge :: WindowResizeDrag -> V2 -> Float -> Float -> (Float, Float, Float, Float)+resizeFromEdge wrd (V2 mx my) winW winH = (w, h, x, y)+  where+    WindowResizeEdge sx sy = wrdEdge wrd+    (x, w) = axis sx (wrdStartX wrd) (wrdStartW wrd) (mx - wrdGrabX wrd) (wrdMinW wrd) (wrdMaxW wrd) winW+    (y, h) = axis sy (wrdStartY wrd) (wrdStartH wrd) (my - wrdGrabY wrd) (wrdMinH wrd) (wrdMaxH wrd) winH+    -- The moving side follows the pointer within the size limits, the other+    -- stays put, and the window stays inside the logical window.+    axis :: Int -> Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float)+    axis side start len d lo hi limit =+      let !len' = clamp (max lo 1) (min hi limit) (len + fromIntegral side * d)+          !pos = if side < 0 then start + len - len' else start+       in (clamp 0 (max 0 (limit - len')) pos, len')++-- | Start or continue a resize within logical window width/height. Updates+-- stored bounds, which the frame places the window at once this returns.+-- Returns 'True' while starting or held.+updateWindowResize :: Context -> Input -> Float -> Float -> IO Bool+updateWindowResize ctx inp winW winH =+  windowGesture ctx inp isWindowResize (\s -> s {isWindowResize = Nothing}) resize tryStartWindowResize+  where+    resize wrd = do+      let (nw, nh, nx, ny) = resizeFromEdge wrd (inputMousePos inp) winW winH+          wid = wrdWidget wrd+          key = intKey wid+      size <- lookupWindowSize ctx wid+      pos <- lookupWindowPos ctx wid+      let moved = size /= Just (nw, nh) || pos /= Just (nx, ny)+      when moved $+        modifyStore ctx (insertSpec slotWinSize key (V2 nw nh) . insertSlot fieldPoint key (V2 nx ny))+      pure moved++-- | Resize edge under @mouse@ for the topmost window whose halo holds it,+-- unless the halo is blocked or the pointer is on one of the window's+-- controls. The top handle reaches over the title bar, which drags elsewhere.+resizeEdgeTarget :: Context -> V2 -> IO (Maybe (NodeIdx, Rect, WindowResizeEdge))+resizeEdgeTarget ctx@Context {ctxNodeArena = na} mouse = runMaybeT $ do+  let inHalo r = rectNonEmpty r && rectContains (rectInflate windowResizeHandleFor r) mouse+  idx <- MaybeT (topmostFloating ctx (== NodeWindow) inHalo)+  -- While a modal is open, only a window inside it resizes, and only off the+  -- modal's panel, which paint puts over it ('overlayHitRoot').+  modal <- liftIO (topModalNode na)+  forM_ modal $ \m -> do+    guard =<< liftIO (nodeInSubtree ctx idx m)+    guard . not . (`rectContains` mouse) =<< liftIO (getNodeRect na m)+  rect <- liftIO (getNodeRect na idx)+  -- The halo covers the window interior, so find the edge first and run the+  -- hover probe and node scans only when there is one.+  pad <- liftIO (getPadding na idx)+  edge <- MaybeT (pure (windowResizeEdgeAt pad rect mouse))+  -- The body's scrollbar, while its content overflows, scrolls instead.+  when (rectContains rect mouse) $ do+    onLane <- liftIO $ windowBodyScroller na idx >>= \case+      Nothing -> pure False+      Just ci -> do+        Rect x y w h <- getNodeRect na ci+        bodyPad <- getPadding na ci+        contentSize <- getNodeValue na ci+        dir <- getDirection na ci+        pure $+          contentSize > h - padT bodyPad - padB bodyPad+            && rectContains (scrollChromeLane ScrollBarWindow dir x y w h bodyPad) mouse+    guard (not onLane)+  -- The halo must not steal hits from another window's interior or from page+  -- widgets.+  inside <- liftIO (topmostOverlayAtMouse ctx mouse)+  guard (maybe True (== idx) inside)+  hot <- liftIO (probeHotId ctx mouse)+  guard =<< liftIO (withWidgetNode ctx hot True (\hotIdx -> nodeInSubtree ctx hotIdx idx))+  guard . not =<< liftIO (windowControlAt ctx idx mouse)+  pure (idx, rect, edge)++tryStartWindowResize :: Context -> V2 -> IO Bool+tryStartWindowResize ctx@Context {ctxNodeArena = na} mouse@(V2 mx my) = fmap isJust . runMaybeT $ do+  (idx, Rect x y w h, edge) <- MaybeT (resizeEdgeTarget ctx mouse)+  liftIO $ do+    wid <- getWidgetId na idx+    AxisSizing _ _ minW maxW <- getWidthSizing na idx+    AxisSizing _ _ minH maxH <- getHeightSizing na idx+    let drag = WindowResizeDrag wid edge mx my x y w h minW minH maxW maxH+    modifyInteraction ctx (\s -> s {isWindowResize = Just drag})+    markDirty ctx++-- | Cursor for the held resize edge or an unblocked hovered edge. 'Nothing'+-- leaves cursor selection to other controls.+windowResizeCursorKind :: Context -> Input -> IO (Maybe UiCursorKind)+windowResizeCursorKind ctx inp =+  getsInteraction ctx isWindowResize >>= \case+    Just wrd+      | heldIn MouseLeft inp -> pure (Just (cursorForResizeEdge (wrdEdge wrd)))+      | otherwise -> pure Nothing+    Nothing -> fmap (\(_, _, edge) -> cursorForResizeEdge edge) <$> resizeEdgeTarget ctx (inputMousePos inp)++tryStartWindowDrag :: Context -> V2 -> IO Bool+tryStartWindowDrag ctx mouse@(V2 mx my) = fmap isJust . runMaybeT $ do+  -- Not a window under its modal's panel ('overlayHitRoot').+  idx <- MaybeT (overlayHitRoot ctx mouse)+  nt <- liftIO (getNodeType (ctxNodeArena ctx) idx)+  guard (nt == NodeWindow)+  title <- MaybeT (windowTitleRect ctx idx)+  guard (rectContains title mouse)+  guard . not =<< liftIO (windowControlAt ctx idx mouse)+  liftIO $ do+    wid <- getWidgetId (ctxNodeArena ctx) idx+    Rect wx wy _ _ <- getNodeRect (ctxNodeArena ctx) idx+    modifyInteraction ctx (\s -> s {isWindowDrag = Just (wid, mx - wx, my - wy)})+    markDirty ctx++-- | Title bar: the window's topmost child, stretched up to the window top.+windowTitleRect :: Context -> NodeIdx -> IO (Maybe Rect)+windowTitleRect Context {ctxNodeArena = na} idx = do+  Rect _ wy _ _ <- getNodeRect na idx+  best <- newIORef Nothing+  forChildNodes_ na idx $ \ci -> do+    here@(Rect _ y _ _) <- getNodeRect na ci+    modifyIORef' best $ \case+      Just b@(Rect _ by _ _) | y >= by -> Just b+      _ -> Just here+  let stretch (Rect cx cy cw ch) = let topY = min wy cy in Rect cx topY cw (cy - topY + ch)+  fmap stretch <$> readIORef best++windowControlAt :: Context -> NodeIdx -> V2 -> IO Bool+windowControlAt ctx idx mouse =+  maybe (pure False) (widgetIdInSubtree ctx idx) . ptInteractive =<< targetsAt ctx mouse++-- | How the context measures text and custom widgets, for the solve and for+-- placing floating nodes after it.+contextMeasurers :: Context -> Measurers+contextMeasurers ctx =+  Measurers+    { msFm = ctxFontMetrics ctx+    , msMonoFm = ctxMonoFontMetrics ctx+    , msFontSize = ctxFontSize ctx+    , msMeasure = ctxMeasureText ctx+    , msResolveFont = \sz weight style var -> do+        (fm, _) <- ctxResolveFont ctx sz weight style var+        pure (fm, ctxResolveMeasure ctx sz weight style var)+    , msLookupMeasure = lookupCustomMeasure ctx+    , msWrap = cachedWrapText ctx+    }
+ lib/NanoUI/Internal/GenCache.hs view
@@ -0,0 +1,87 @@+-- | Two-generation 'Data.IntMap.Strict.IntMap' cache bounded to a small multiple of the entries+-- touched in a frame. Companion caches (@MarkdownCache@, @PlotCache@) use it+-- so churning or growing widget ids never retain unbounded stale entries.+module NanoUI.Internal.GenCache+  ( IntGenCache+  , newIntGenCache+  , intGenCacheStartFrame+  , intGenCacheLookup+  , intGenCacheTouch+  , intGenCacheInsert+  , intGenCacheSize+  ) where++import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM++-- | Mutable two-generation cache keyed by 'Int' (typically @intKey@).+newtype IntGenCache a = IntGenCache (IORef (GenState a))++data GenState a = GenState+  { gsMinBound :: !Int+  , gsBoundNow :: !Int+  , gsFrame :: !Int+  , gsCount :: !Int+  , gsMost :: !Int+  , gsCur :: !(IM.IntMap a)+  , gsOld :: !(IM.IntMap a)+  }++-- | Create an empty generational cache whose generation rotates after at least+-- @minBoundEntries@ insertions (clamped to at least 16).+newIntGenCache :: Int -> IO (IntGenCache a)+newIntGenCache minEntries = do+  let !b = max 16 minEntries+  IntGenCache <$> newIORef (GenState b b (-1) 0 0 IM.empty IM.empty)++-- | Mark the start of frame @frame@, resetting the per-frame active count+-- once per frame number while preserving the high-water mark since the last+-- generation turn.+intGenCacheStartFrame :: IntGenCache a -> Int -> IO ()+intGenCacheStartFrame (IntGenCache ref) frame = modifyIORef' ref $ \gs ->+  if gsFrame gs == frame+    then gs+    else gs {gsFrame = frame, gsCount = 0, gsMost = max (gsCount gs) (gsMost gs)}++-- | Look up key @k@ in the current generation first, falling back to the+-- previous generation.+intGenCacheLookup :: IntGenCache a -> Int -> IO (Maybe a)+intGenCacheLookup (IntGenCache ref) k = do+  gs <- readIORef ref+  pure (maybe (IM.lookup k (gsOld gs)) Just (IM.lookup k (gsCur gs)))++-- | Record a hit for @(k, val)@ in the current frame, promoting @val@ from the+-- older generation into the current one when needed.+intGenCacheTouch :: IntGenCache a -> Int -> a -> IO ()+intGenCacheTouch (IntGenCache ref) k val = do+  gs <- readIORef ref+  writeIORef ref $!+    if IM.member k (gsCur gs)+      then gs {gsCount = gsCount gs + 1}+      else insertGen gs k val++-- | Insert or update @(k, val)@ in the current generation, rotating+-- generations when the current bound is reached.+intGenCacheInsert :: IntGenCache a -> Int -> a -> IO ()+intGenCacheInsert (IntGenCache ref) k val = do+  gs <- readIORef ref+  writeIORef ref $! insertGen gs k val++insertGen :: GenState a -> Int -> a -> GenState a+insertGen gs k val+  | IM.size (gsCur gs) < gsBoundNow gs =+      gs {gsCount = gsCount gs + 1, gsCur = IM.insert k val (gsCur gs)}+  | otherwise =+      gs+        { gsCount = gsCount gs + 1+        , gsBoundNow = max (gsMinBound gs) (2 * max (gsCount gs) (gsMost gs))+        , gsMost = 0+        , gsCur = IM.singleton k val+        , gsOld = gsCur gs+        }++-- | Distinct entries retained across both generations, for diagnostics.+intGenCacheSize :: IntGenCache a -> IO Int+intGenCacheSize (IntGenCache ref) = do+  gs <- readIORef ref+  pure (IM.size (IM.union (gsCur gs) (gsOld gs)))
+ lib/NanoUI/Internal/GridNode.hs view
@@ -0,0 +1,51 @@+-- | The split tree "NanoUI.Widgets.PaneGrid" lays its panes out by. It is+-- its own module, depending on nothing but @base@, so the widget store+-- ("NanoUI.Internal.Store.Types") can keep a grid's tree without depending+-- on the widget. "NanoUI.Internal.Widgets.SplitPane" re-exports it with+-- the functions over it.+module NanoUI.Internal.GridNode+  ( GridAxis (..)+  , CenterDropMode (..)+  , GridNode (..)+  ) where++import Data.Word (Word64)++-- | Divider orientation. 'AxisV' draws a vertical divider (panes left/right),+-- 'AxisH' draws a horizontal divider (panes stacked top/bottom).+data GridAxis = AxisV | AxisH+  deriving (Eq, Ord, Show, Read, Enum, Bounded)++-- | How dropping a pane onto the center of another pane behaves in a "NanoUI.Widgets.PaneGrid".+data CenterDropMode+  = -- | Swap the dragged pane with the target pane (the default).+    CenterSwap+  | -- | Merge the dragged pane into a tabbed stack ('PaneTabs') with the target pane.+    CenterTab+  deriving (Eq, Ord, Show, Read, Enum, Bounded)++-- | Split-and-tab tree node. Pane, tab-group, and split ids share one+-- monotonic counter.+data GridNode+  = Split+      !Word64+      -- ^ Split id.+      !GridAxis+      -- ^ Orientation of the divider.+      !Float+      -- ^ Ratio in @[0,1]@ for the A side.+      !GridNode+      -- ^ Left / top subtree.+      !GridNode+      -- ^ Right / bottom subtree.+  | Pane+      !Word64+      -- ^ Pane id.+  | PaneTabs+      !Word64+      -- ^ Tab-group id.+      ![Word64]+      -- ^ Ordered pane ids in this tabbed stack.+      !Word64+      -- ^ Active (visible) pane id, an element of the pane list.+  deriving (Eq, Show, Read)
+ lib/NanoUI/Internal/Host.hs view
@@ -0,0 +1,31 @@+-- | Explicit, typed host slots. Ownership is carried by a handle rather than+-- recovered from a runtime type in a context-wide heterogeneous map.+module NanoUI.Internal.Host (Host, newHost, setHost, clearHost, askHostIO, hostOrInit) where++import Data.IORef (IORef, newIORef, readIORef, writeIORef)++-- | A single-session, UI-thread slot. An uninstalled host is absent.+newtype Host a = Host (IORef (Maybe a))++-- | A new slot with no value installed.+newHost :: IO (Host a)+newHost = Host <$> newIORef Nothing++-- | Install a value in the slot, replacing any already there.+{-# INLINE setHost #-}+setHost :: Host a -> a -> IO ()+setHost (Host ref) value = writeIORef ref (Just value)++clearHost :: Host a -> IO ()+clearHost (Host ref) = writeIORef ref Nothing++-- | The installed value, or 'Nothing' when the slot is empty.+{-# INLINE askHostIO #-}+askHostIO :: Host a -> IO (Maybe a)+askHostIO (Host ref) = readIORef ref++-- | Lazily initialize a typed slot. Call serially on its owning UI thread.+hostOrInit :: Host a -> IO a -> IO a+hostOrInit owner acquire =+  askHostIO owner+    >>= maybe (acquire >>= \value -> value <$ setHost owner value) pure
+ lib/NanoUI/Internal/Id.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Widget ids and the id context they are derived from. See the+-- "Widget identity" section of "NanoUI" for how ids are assigned.+module NanoUI.Internal.Id+  ( WidgetId (..)+  , mkWidgetId+  , IdContext (..)+  , initialIdContext+  , idContextWidgetId+  , scopeIdContext+  , widgetId+  , hashWidgetId+  , mix64+  , mixFnv+  , scopeTag+  , keyedTag+  , enterScope+  , enterKeyed+  )+where++import Data.Bits (shiftR, xor)+import Data.Char (ord)+import Data.Hashable (Hashable)+import Data.Primitive.Types (Prim)+import Data.Word (Word64, Word8)+import GHC.Stack (HasCallStack, SrcLoc (..), callStack, getCallStack)++-- | Stable store and interaction identity. Zero is reserved for no widget.+-- Make one from a hash with 'mkWidgetId', which keeps it in the range an+-- 'Int' holds.+newtype WidgetId = WidgetId Word64+  deriving stock (Eq, Ord, Show)+  deriving newtype (Hashable, Prim)++-- | The id for a hash. The node arena and the store keep ids in 'Int'+-- slots, so an id must come back unchanged from a trip through 'Int'. On a+-- 64-bit target that holds for every hash, and this is the hash itself. On a+-- target whose 'Int' is 32 bits (wasm32) the id is the hash's low 32 bits,+-- sign-extended as converting that 'Int' back does.+{-# INLINE mkWidgetId #-}+mkWidgetId :: Word64 -> WidgetId+mkWidgetId h = WidgetId (fromIntegral (fromIntegral h :: Int))++-- | Parent-path hash, the next sibling widget's position within that path,+-- and the next positional Var's position, counted separately so widgets+-- that come and go never move a Var.+data IdContext = IdContext+  { currentId :: {-# UNPACK #-} !Word64+  , siblingId :: {-# UNPACK #-} !Word64+  , varSiblingId :: {-# UNPACK #-} !Word64+  }+  deriving stock (Eq, Show)++-- | Root path and sibling position used at the start of each view pass.+initialIdContext :: IdContext+initialIdContext = IdContext 0x243F6A8885A308D3 0 0++-- | A fresh scope at path @p@, with both counts at zero.+{-# INLINE scopeIdContext #-}+scopeIdContext :: Word64 -> IdContext+scopeIdContext p = IdContext p 0 0++-- | Id of the next sibling in this context. A zero id becomes 1, so+-- @WidgetId 0@ never names a real widget.+{-# INLINE idContextWidgetId #-}+idContextWidgetId :: IdContext -> WidgetId+idContextWidgetId (IdContext cid sid _) =+  let+    wid = mkWidgetId (mix64 cid sid)+   in+    if wid == WidgetId 0 then WidgetId 1 else wid++-- | Hash salt distinguishing an ordinary child scope from a keyed scope.+scopeTag :: Word64+scopeTag = 0x9E3779B185EBCA87++-- | Hash salt distinguishing a keyed child scope from a positional scope.+keyedTag :: Word64+keyedTag = 0xC2B2AE3D27D4EB4F++-- | Return the advanced parent and a fresh child context derived from its+-- sibling position and the supplied tag.+{-# INLINE enterScope #-}+enterScope :: Word64 -> IdContext -> (IdContext, IdContext)+enterScope tag parent = enterChild (siblingId parent) tag parent++-- | Return the parent unchanged and a child path derived from the key, not+-- the sibling position. Keys must be unique within the parent. A keyed scope+-- takes no sibling position, so the widgets after a keyed list keep their ids+-- when the list grows or shrinks.+{-# INLINE enterKeyed #-}+enterKeyed :: Word64 -> IdContext -> (IdContext, IdContext)+enterKeyed tag parent@(IdContext pid _ _) = (parent, scopeIdContext (mix64 (mix64 pid tag) keyedTag))++-- | Advance the parent's sibling counter and derive a child path from the+-- parent path, @seed@ and @tag@. The child starts both counts at zero; the+-- parent's Var count is untouched, so a scope takes no Var position.+{-# INLINE enterChild #-}+enterChild :: Word64 -> Word64 -> IdContext -> (IdContext, IdContext)+enterChild seed tag (IdContext pid sib vs) = (IdContext pid (sib + 1) vs, scopeIdContext (mix64 (mix64 pid seed) tag))++-- | Hash the call site's package, module, file, line, and column. Repeated+-- calls at one source location return the same id; this is not a list-item key.+-- Throws if the call stack is empty.+{-# INLINE widgetId #-}+widgetId :: HasCallStack => WidgetId+widgetId =+  let+    stack = getCallStack callStack+    loc = case stack of+      (_, loc') : _ -> loc'+      [] -> error "widgetId: empty CallStack"+   in+    hashSrcLoc loc++hashSrcLoc :: SrcLoc -> WidgetId+hashSrcLoc loc =+  mkWidgetId $+    fnv1a (srcLocPackage loc)+      `mixFnv` fnv1a (srcLocModule loc)+      `mixFnv` fnv1a (srcLocFile loc)+      `mixFnv` fromIntegral (srcLocStartLine loc)+      `mixFnv` fromIntegral (srcLocStartCol loc)++-- | Unwrap the id's existing hash without hashing it again.+{-# INLINE hashWidgetId #-}+hashWidgetId :: WidgetId -> Word64+hashWidgetId (WidgetId w) = w++-- | FNV-1a over the low byte of each character. Intended for identifier seeds,+-- not general Unicode hashing or cryptography.+{-# INLINE fnv1a #-}+fnv1a :: String -> Word64+fnv1a s =+  foldl'+    (\acc c -> (fromIntegral @Word8 @Word64 (fromIntegral (ord c)) `xor` acc) * 0x00000100000001B3)+    0xcbf29ce484222325+    s++-- | Mix two 64-bit identifier components with wrapping arithmetic.+-- This is a non-cryptographic hash combiner.+{-# INLINE mix64 #-}+mix64 :: Word64 -> Word64 -> Word64+mix64 x y =+  let+    z = x + (y * 0x9E3779B97F4A7C15)+    z1 = z `xor` (z `shiftR` 30)+    z2 = z1 * 0xBF58476D1CE4E5B9+    z3 = z2 `xor` (z2 `shiftR` 27)+   in+    z3 * 0x94D049BB133111EB++-- | Combine two hash words with an FNV xor-and-multiply step.+{-# INLINE mixFnv #-}+mixFnv :: Word64 -> Word64 -> Word64+mixFnv x y = (x `xor` y) * 1099511628211
+ lib/NanoUI/Internal/Id/Cursor.hs view
@@ -0,0 +1,192 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | The view's position in the id tree, kept unboxed: the current path,+-- the next widget and Var positions within it, and a growable unboxed stack+-- of enclosing scopes so entering and leaving containers or keyed scopes+-- allocates nothing.+module NanoUI.Internal.Id.Cursor+  ( IdCursor+  , newIdCursor+  , readIdCursor+  , writeIdCursor+  , resetIdCursor+  , pushIdScope+  , pushKeyedIdScope+  , popIdScope+  , readIdDepth+  , writeIdDepth+  , peekWidgetId+  , takeWidgetId+  , skipSiblingIds+  , takeVarKey+  )+where++import Control.Monad (when)+import Control.Monad.Primitive (RealWorld)+import Data.Bits (xor)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , getSizeofMutablePrimArray+  , newPrimArray+  , readPrimArray+  , resizeMutablePrimArray+  , writePrimArray+  )+import Data.Primitive.PrimVar (PrimVar, newPrimVar, readPrimVar, writePrimVar)+import Data.Word (Word64)+import NanoUI.Internal.Id (IdContext (..), WidgetId, idContextWidgetId, initialIdContext, keyedTag, mix64)++-- | Active cursor slots (0 path, 1 next widget position, 2 next Var position)+-- plus an unboxed growable scope stack (3 words per pushed frame).+data IdCursor+  = IdCursor+      {-# UNPACK #-} !(MutablePrimArray RealWorld Word64)+      !(IORef (MutablePrimArray RealWorld Word64))+      {-# UNPACK #-} !(PrimVar RealWorld Int)++-- | A cursor positioned at the given 'IdContext'.+newIdCursor :: IdContext -> IO IdCursor+newIdCursor ic = do+  arr <- newPrimArray 3+  stk <- newPrimArray (32 * 3) >>= newIORef+  dep <- newPrimVar 0+  let cur = IdCursor arr stk dep+  writeIdCursor cur ic+  pure cur++-- | Reset the cursor to 'initialIdContext' and empty its scope stack.+{-# INLINE resetIdCursor #-}+resetIdCursor :: IdCursor -> IO ()+resetIdCursor cur@(IdCursor _ _ depVar) = do+  writeIdCursor cur initialIdContext+  writePrimVar depVar 0++-- | The cursor's current path and positions as an 'IdContext'.+{-# INLINE readIdCursor #-}+readIdCursor :: IdCursor -> IO IdContext+readIdCursor (IdCursor arr _ _) =+  IdContext <$> readPrimArray arr 0 <*> readPrimArray arr 1 <*> readPrimArray arr 2++-- | Move the cursor to the path and positions of an 'IdContext'.+{-# INLINE writeIdCursor #-}+writeIdCursor :: IdCursor -> IdContext -> IO ()+writeIdCursor (IdCursor arr _ _) (IdContext p s v) = do+  writePrimArray arr 0 p+  writePrimArray arr 1 s+  writePrimArray arr 2 v++-- | Current unboxed scope stack depth, for exception recovery ('catchView').+{-# INLINE readIdDepth #-}+readIdDepth :: IdCursor -> IO Int+readIdDepth (IdCursor _ _ depVar) = readPrimVar depVar++-- | Restore unboxed scope stack depth after exception recovery.+{-# INLINE writeIdDepth #-}+writeIdDepth :: IdCursor -> Int -> IO ()+writeIdDepth (IdCursor _ _ depVar) = writePrimVar depVar++{-# NOINLINE growIdStack #-}+growIdStack :: IORef (MutablePrimArray RealWorld Word64) -> Int -> IO (MutablePrimArray RealWorld Word64)+growIdStack ref needed = do+  arr <- readIORef ref+  cap <- getSizeofMutablePrimArray arr+  let !newCap = max needed (cap * 2)+  grown <- resizeMutablePrimArray arr newCap+  writeIORef ref grown+  pure grown++-- | Save the advanced parent context onto the unboxed stack and enter a fresh+-- positional child scope derived from the parent's sibling position and @tag@.+{-# INLINE pushIdScope #-}+pushIdScope :: IdCursor -> Word64 -> IO ()+pushIdScope (IdCursor arr stkRef depVar) tag = do+  p <- readPrimArray arr 0+  s <- readPrimArray arr 1+  v <- readPrimArray arr 2+  d <- readPrimVar depVar+  let !off = d * 3+  stk0 <- readIORef stkRef+  cap <- getSizeofMutablePrimArray stk0+  stk <- if off + 3 <= cap then pure stk0 else growIdStack stkRef (off + 3)+  writePrimArray stk off p+  writePrimArray stk (off + 1) (s + 1)+  writePrimArray stk (off + 2) v+  writePrimVar depVar (d + 1)+  writePrimArray arr 0 (mix64 (mix64 p s) tag)+  writePrimArray arr 1 0+  writePrimArray arr 2 0++-- | Save the parent context unchanged onto the unboxed stack and enter a fresh+-- keyed child scope derived from @keyHash@.+{-# INLINE pushKeyedIdScope #-}+pushKeyedIdScope :: IdCursor -> Word64 -> IO ()+pushKeyedIdScope (IdCursor arr stkRef depVar) keyHash = do+  p <- readPrimArray arr 0+  s <- readPrimArray arr 1+  v <- readPrimArray arr 2+  d <- readPrimVar depVar+  let !off = d * 3+  stk0 <- readIORef stkRef+  cap <- getSizeofMutablePrimArray stk0+  stk <- if off + 3 <= cap then pure stk0 else growIdStack stkRef (off + 3)+  writePrimArray stk off p+  writePrimArray stk (off + 1) s+  writePrimArray stk (off + 2) v+  writePrimVar depVar (d + 1)+  writePrimArray arr 0 (mix64 (mix64 p keyHash) keyedTag)+  writePrimArray arr 1 0+  writePrimArray arr 2 0++-- | Restore the parent context pushed by 'pushIdScope' or 'pushKeyedIdScope'.+{-# INLINE popIdScope #-}+popIdScope :: IdCursor -> IO ()+popIdScope (IdCursor arr stkRef depVar) = do+  d <- readPrimVar depVar+  when (d > 0) $ do+    let !d' = d - 1+        !off = d' * 3+    writePrimVar depVar d'+    stk <- readIORef stkRef+    p <- readPrimArray stk off+    s <- readPrimArray stk (off + 1)+    v <- readPrimArray stk (off + 2)+    writePrimArray arr 0 p+    writePrimArray arr 1 s+    writePrimArray arr 2 v++-- | The id the next widget would take, without taking it.+{-# INLINE peekWidgetId #-}+peekWidgetId :: IdCursor -> IO WidgetId+peekWidgetId (IdCursor arr _ _) = do+  p <- readPrimArray arr 0+  s <- readPrimArray arr 1+  pure $! idContextWidgetId (IdContext p s 0)++-- | The id of the next widget; advances the widget position by one.+{-# INLINE takeWidgetId #-}+takeWidgetId :: IdCursor -> IO WidgetId+takeWidgetId (IdCursor arr _ _) = do+  p <- readPrimArray arr 0+  s <- readPrimArray arr 1+  writePrimArray arr 1 (s + 1)+  pure $! idContextWidgetId (IdContext p s 0)++-- | Advance the widget position by @n@ without taking ids, for siblings a+-- reused subtree already accounts for.+{-# INLINE skipSiblingIds #-}+skipSiblingIds :: IdCursor -> Int -> IO ()+skipSiblingIds (IdCursor arr _ _) n = do+  s <- readPrimArray arr 1+  writePrimArray arr 1 (s + fromIntegral n)++-- | Allocate the next positional 'Var' key. 'Var' keys index a separate table+-- from widget ids and store keys, and use a distinct hash salt.+{-# INLINE takeVarKey #-}+takeVarKey :: IdCursor -> IO Int+takeVarKey (IdCursor arr _ _) = do+  p <- readPrimArray arr 0+  n <- readPrimArray arr 2+  writePrimArray arr 2 (n + 1)+  pure $! fromIntegral (mix64 (p `xor` 0x7661725F6B657973) n)
+ lib/NanoUI/Internal/Image.hs view
@@ -0,0 +1,307 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Pure image geometry: fit, alignment, crop, zoom, opacity and rotation.+-- Covers the user options ('ImageConfig'), the per-node paint data+-- ('ImageLook', 'withLookDraw') and the canvas image record ('ImageDraw').+module NanoUI.Internal.Image+  ( ContentFit (..)+  , Rotation (..)+  , rotationAngle+  , ImageConfig (..)+  , defaultImageConfig+  , fitRect+  , turnedRect+  , ImageLook (..)+  , imageLook+  , plainLook+  , lookSize+  , withLookDraw+  , ImageDraw (..)+  , imageDraw+  , imageDrawOp+  , fadeBy+  ) where++import Data.Maybe (fromMaybe)+import NanoUI.Internal.Draw.Types (DrawOp (..))+import NanoUI.Internal.Style (AlignX (..), AlignY (..), Layout, alignXFraction, alignYFraction, fadeAlpha)+import NanoUI.Internal.Types (Color, ImageId (..), Rect (..), clamp, clamp01, colorA, colorRGBA, finite, rectIntersect)++-- | How an image fills its layout rect, like CSS @object-fit@. Every fit but+-- 'FitFill' keeps the image's aspect ratio.+data ContentFit+  = -- | Largest size that fits inside the rect; may leave empty space.+    FitContain+  | -- | Smallest size that covers the rect, cropped to it.+    FitCover+  | -- | Stretched to the rect.+    FitFill+  | -- | Natural size, cropped to the rect.+    FitNone+  | -- | 'FitNone' when the image fits, else 'FitContain'.+    FitScaleDown+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | Clockwise rotation in radians about the centre of the drawn image, and+-- whether the rotation affects layout.+data Rotation+  = -- | Fitted as if unrotated, then rotated. Layout is unchanged and corners+    -- outside the rect are cropped. For spinning icons.+    RotateFloating !Float+  | -- | Fitted by the rotated bounding box, so the whole image stays inside+    -- its rect (unless 'FitCover' or 'FitNone' crops it). An unsized axis+    -- takes the rotated extent.+    RotateSolid !Float+  deriving (Eq, Show)++-- | The angle of either rotation, in radians.+rotationAngle :: Rotation -> Float+rotationAngle (RotateFloating a) = a+rotationAngle (RotateSolid a) = a++-- | Options for 'NanoUI.imageConfigured'.+data ImageConfig = ImageConfig+  { icLayout :: Layout -> Layout+  -- ^ Layout modifier. A 'NanoUI.Fit' axis (the default) takes the image's+  -- size: one image pixel per logical pixel, after 'icCrop' and any solid+  -- rotation. The image's ratio acts as 'NanoUI.aspect' unless the modifier+  -- sets one, so @fillW@ keeps the shape. 'NanoUI.fontColor' tints the+  -- image, as it does an SVG icon.+  , icFit :: !ContentFit+  -- ^ How the image fills its rect.+  , icAlignX :: !AlignX+  -- ^ Horizontal placement when the image does not fill its rect, and which+  -- side survives cropping.+  , icAlignY :: !AlignY+  -- ^ Vertical counterpart of 'icAlignX'. 'AlignBaseline' acts as 'AlignTop'.+  , icOpacity :: !Float+  -- ^ 0 (invisible) to 1 (opaque).+  , icRotation :: !Rotation+  -- ^ Rotation about the drawn image's centre; see 'Rotation'.+  , icCrop :: !(Maybe Rect)+  -- ^ Sub-rectangle to draw, in image pixels from the top-left, clamped to+  -- the image. Size, fit, alignment and rotation apply to this part only.+  -- 'Nothing' (the default) draws the whole image.+  , icScale :: !Float+  -- ^ Zoom about the fitted image's centre, clipped to its rect: above 1+  -- zooms in, below 1 out. Does not affect layout. Default 1.+  }++-- | Default layout, 'FitFill' (as 'NanoUI.image'), centred, opaque, with no+-- rotation, crop or zoom.+defaultImageConfig :: ImageConfig+defaultImageConfig =+  ImageConfig+    { icLayout = id+    , icFit = FitFill+    , icAlignX = AlignCenter+    , icAlignY = AlignMiddle+    , icOpacity = 1+    , icRotation = RotateFloating 0+    , icCrop = Nothing+    , icScale = 1+    }++-- | Rect of content @w@ by @h@ fitted into @box@ and aligned like CSS+-- @object-position@. The result may overflow the box ('FitCover',+-- 'FitNone'); the caller crops it.+--+-- > fitRect FitContain AlignCenter AlignMiddle (40, 20) (Rect 0 0 100 80) == Rect 0 15 100 50+fitRect :: ContentFit -> AlignX -> AlignY -> (Float, Float) -> Rect -> Rect+fitRect fit ax ay (w, h) (Rect bx by bw bh) = Rect (bx + (bw - dw) * fx) (by + (bh - dh) * fy) dw dh+  where+    empty = not (w > 0 && h > 0)+    contain = min (bw / w) (bh / h)+    scaled k = if empty then (0, 0) else (k * w, k * h)+    (dw, dh) = case fit of+      FitContain -> scaled contain+      FitCover -> scaled (max (bw / w) (bh / h))+      FitFill -> (bw, bh)+      FitNone -> scaled 1+      FitScaleDown -> scaled (min 1 contain)+    fx = alignXFraction ax+    fy = alignYFraction ay++-- | Bounding size after a solid rotation; floating rotations keep the size.+turnedSize :: Rotation -> (Float, Float) -> (Float, Float)+turnedSize (RotateSolid angle) (w, h) =+  let c = abs (cos angle)+      s = abs (sin angle)+   in (w * c + h * s, w * s + h * c)+turnedSize (RotateFloating _) size = size++-- | Unrotated draw rect of an @iw@ by @ih@ image in @box@; rotation is then+-- about its centre. Solid rotations fit by the rotated bounds. 'FitFill'+-- with a solid rotation stretches so the rotated bounds fill the box, falling+-- back to 'FitContain' at odd multiples of 45 degrees or when no stretch can+-- match the box's shape.+turnedRect :: ContentFit -> AlignX -> AlignY -> Rotation -> (Float, Float) -> Rect -> Rect+turnedRect fit ax ay rot (iw, ih) box@(Rect _ _ bw bh) = Rect (px + (pw - dw) / 2) (py + (ph - dh) / 2) dw dh+  where+    (rw, rh) = turnedSize rot (iw, ih)+    solidFill = case (fit, rot) of+      (FitFill, RotateSolid angle) ->+        let c = abs (cos angle)+            s = abs (sin angle)+            det = c * c - s * s+            w = (c * bw - s * bh) / det+            h = (c * bh - s * bw) / det+         in if abs det > 1.0e-3 && w > 0 && h > 0 then Just (w, h) else Nothing+      _ -> Nothing+    fit' = case (fit, rot, solidFill) of+      (FitFill, RotateSolid _, Nothing) -> FitContain+      _ -> fit+    Rect px py pw ph = fitRect fit' ax ay (rw, rh) box+    (dw, dh) = fromMaybe (if rw > 0 && rh > 0 then (iw * pw / rw, ih * ph / rh) else (0, 0)) solidFill++-- | Crop rect clamped to an @iw@ by @ih@ image, at least one pixel each way.+-- The whole image when there is no crop.+cropRegion :: Maybe Rect -> (Int, Int) -> Rect+cropRegion crop (iw, ih) = case crop of+  Nothing -> Rect 0 0 w h+  Just (Rect x y cw ch) ->+    let x' = clamp 0 (w - 1) x+        y' = clamp 0 (h - 1) y+     in Rect x' y' (clamp 1 (w - x') cw) (clamp 1 (h - y') ch)+  where+    w = fromIntegral iw+    h = fromIntegral ih++-- | Paint settings for an image node: its 'ImageConfig' fields plus tint.+-- Paint draws it with 'withLookDraw'; damage repaints a node when its look+-- changes.+data ImageLook = ImageLook+  { lookFit :: !ContentFit+  , lookAlignX :: !AlignX+  , lookAlignY :: !AlignY+  , lookOpacity :: !Float+  , lookRotation :: !Rotation+  , lookCrop :: !(Maybe Rect)+  , lookScale :: !Float+  , lookTint :: !Color+  }+  deriving (Eq, Show)++-- | Build a look from a config and tint. NaN opacity or scale and+-- non-finite rotation fall back to their defaults.+imageLook :: ImageConfig -> Color -> ImageLook+imageLook cfg =+  ImageLook+    (icFit cfg)+    (icAlignX cfg)+    (icAlignY cfg)+    (unitOpacity (icOpacity cfg))+    (if finite (rotationAngle (icRotation cfg)) then icRotation cfg else RotateFloating 0)+    (icCrop cfg)+    (if icScale cfg > 0 && finite (icScale cfg) then icScale cfg else 1)++-- | Whether a look is the default config's with its own tint: an image+-- stretched over its rect, drawn as a plain image.+plainLook :: ImageLook -> Bool+plainLook l =+  lookFit l == FitFill+    && lookAlignX l == AlignCenter+    && lookAlignY l == AlignMiddle+    && lookOpacity l == 1+    && lookRotation l == RotateFloating 0+    && null (lookCrop l)+    && lookScale l == 1++-- | Clamp to [0, 1], NaN to 1.+unitOpacity :: Float -> Float+unitOpacity o = if isNaN o then 1 else clamp01 o++-- | Scale a colour's alpha by an opacity in [0, 1].+fadeBy :: Float -> Color -> Color+fadeBy o c+  | o >= 1 = c+  | otherwise = fadeAlpha c (round (fromIntegral (colorA c) * o))++-- | Natural size of an image node for unsized axes: the cropped image size,+-- rotated if the rotation is solid.+lookSize :: ImageLook -> (Int, Int) -> (Float, Float)+lookSize look size =+  let Rect _ _ w h = cropRegion (lookCrop look) size in turnedSize (lookRotation look) (w, h)++-- | Resolve an image node's draw geometry in @box@ with opacity scaled by+-- @fade@, passing @(turned, rect, angle, u0, v0, u1, v1, tint)@ to @k@ when+-- visible. Unrotated images crop UVs to @box@; rotated ones keep their full+-- quad so the caller can clip to @box@.+{-# INLINE withLookDraw #-}+withLookDraw ::+  ImageLook ->+  (Int, Int) ->+  Float ->+  Rect ->+  (Bool -> Rect -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()) ->+  IO ()+withLookDraw look size fade box k+  | opacity <= 0 || colorA tint == 0 = pure ()+  | turned = let Rect u v uw vh = uv in k True dest (if finite angle then angle else 0) u v (u + uw) (v + vh) tint+  | otherwise = case cropToBox dest uv box of+      Just (r, Rect u v uw vh) -> k False r 0 u v (u + uw) (v + vh) tint+      Nothing -> pure ()+  where+    opacity = lookOpacity look * fade+    tint = fadeBy (unitOpacity opacity) (lookTint look)+    (dest, uv) = lookPlacement look size box+    angle = rotationAngle (lookRotation look)+    turned = not (angle == 0 || abs (sin angle) < 1.0e-6 && cos angle > 0)++-- | The unrotated rect an @iw@ by @ih@ image is drawn in over @box@+-- (fitted, aligned and zoomed), and the UV rect of its crop.+{-# INLINE lookPlacement #-}+lookPlacement :: ImageLook -> (Int, Int) -> Rect -> (Rect, Rect)+lookPlacement look size@(iw, ih) box = (dest, uv)+  where+    Rect cx cy cw ch = cropRegion (lookCrop look) size+    uv = Rect (cx / fromIntegral iw) (cy / fromIntegral ih) (cw / fromIntegral iw) (ch / fromIntegral ih)+    Rect fx fy fw fh = turnedRect (lookFit look) (lookAlignX look) (lookAlignY look) (lookRotation look) (cw, ch) box+    k = lookScale look+    dest = Rect (fx + fw * (1 - k) / 2) (fy + fh * (1 - k) / 2) (fw * k) (fh * k)++-- | The part of an unrotated image drawn over @dest@ with UVs @uv@ that lies+-- in @box@, with its UVs; 'Nothing' when none does.+{-# INLINE cropToBox #-}+cropToBox :: Rect -> Rect -> Rect -> Maybe (Rect, Rect)+cropToBox dest@(Rect dx dy dw dh) (Rect u v uw vh) box = case rectIntersect dest box of+  Just (Rect x y w h)+    | dw > 0 && dh > 0 && w > 0 && h > 0 ->+        Just (Rect x y w h, Rect (u + (x - dx) / dw * uw) (v + (y - dy) / dh * vh) (w / dw * uw) (h / dh * vh))+  _ -> Nothing++-- | An image for 'NanoUI.Widgets.Custom.drawImageWith'. Start from+-- 'imageDraw' and override fields:+--+-- > drawImageWith (imageDraw r photo) {imageAngle = t, imageOpacity = 0.5}+data ImageDraw = ImageDraw+  { imageRect :: !Rect+  -- ^ Destination rect, before rotation.+  , imageId :: !ImageId+  -- ^ An image registered with the context.+  , imageUV :: !Rect+  -- ^ Source region in UVs (0 to 1): @Rect 0 0 1 1@ is the whole image,+  -- @Rect 0.5 0 0.5 1@ its right half.+  , imageAngle :: !Float+  -- ^ Clockwise rotation in radians about the rect's centre. At 0 the image+  -- snaps to the pixel grid like a rect.+  , imageTint :: !Color+  -- ^ Multiplied into each pixel. White leaves the image unchanged; a+  -- single-colour white image takes the tint's colour.+  , imageOpacity :: !Float+  -- ^ 0 (invisible) to 1 (the tint's own alpha).+  }+  deriving (Eq, Show)++-- | The whole image @iid@ over @r@: unrotated, untinted, opaque.+imageDraw :: Rect -> ImageId -> ImageDraw+imageDraw r iid = ImageDraw r iid (Rect 0 0 1 1) 0 (colorRGBA 255 255 255 255) 1++-- | Draw op with opacity folded into the tint alpha and a non-finite angle+-- treated as 0. 'Nothing' when invisible.+imageDrawOp :: ImageDraw -> Maybe DrawOp+imageDrawOp (ImageDraw r (ImageId tid) (Rect u v uw vh) angle tint opacity)+  | colorA tint' == 0 = Nothing+  | otherwise = Just (DrawImage r (if finite angle then angle else 0) tid u v (u + uw) (v + vh) tint')+  where+    tint' = fadeBy (unitOpacity opacity) tint
+ lib/NanoUI/Internal/Input.hs view
@@ -0,0 +1,775 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Implementation of "NanoUI.Input", plus the input rewrites the frame uses+-- for repeated passes and covered layers, and the runner's event batching.+module NanoUI.Internal.Input+  ( Key (..)+  , Modifiers (..)+  , noModifiers+  , modifiersFromBits+  , modPrimary+  , chordModifiers+  , primaryModifiers+  , modJump+  , modMacCommand+  , onMac+  , isCommandKey+  , shiftAtMost+  , Input (..)+  , Pressable (..)+  , anyButtonPressed+  , anyButtonReleased+  , DropType (..)+  , DropEvent (..)+  , emptyInput+  , inputInteracted+  , inputPointerHeld+  , appendInputKey+  , applyKey+  , releaseAllKeys+  , keypadKey+  , appendDropEvent+  , MouseButton (..)+  , mouseButtonNumber+  , MouseButtons+  , noButtons+  , buttonsMember+  , buttonsToList+  , buttonsFromList+  , buttonsNull+  , buttonsInsert+  , buttonsDelete+  , buttonsFilterM+  , applyMouseButton+  , applyPointerLeave+  , inputKeysNull+  , inputKeysElem+  , foldInputKeys+  , inputKeysFromList+  , stripInteractionInput+  , withoutPointer+  , offWindow+  , UiCursorKind (..)+  , cursorFallback+  , syncCursorKind+  , grabHoverKind+  , grabDragKind+  , clearEphemeral+  , isHardQuitInput+  , takeFrame+  , Composition (..)+  , applyComposition+  , InputPurpose (..)+  ) where++import Control.Monad (unless, when)+import Data.Bits (Bits, clearBit, countTrailingZeros, setBit, testBit, zeroBits, (.&.), (.|.))+import Data.Foldable (toList)+import Data.IORef (IORef, readIORef, writeIORef)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Primitive.SmallArray (SmallArray, copySmallArray, indexSmallArray, newSmallArray, runSmallArray, sizeofSmallArray, smallArrayFromList)+import Data.Word (Word32)+import NanoUI.Internal.Types (Size (..), V2 (..), clamp)+import System.Info (os)++-- | A key on the keyboard. A key that types a character is 'KeyChar' of the+-- character it types with no modifier held: lower case for a letter, the+-- unshifted symbol otherwise (Shift+1 is @KeyChar \'1\'@ with 'modShift').+-- Backends read it from the keyboard layout where they can. Presses and+-- releases are reported whatever modifiers are held; any text the key types+-- also arrives in 'inputChars'.+data Key+  = KeyBackspace+  | KeyDelete+  | KeyEnter+  -- ^ Return, or Enter on the keypad.+  | KeyEscape+  | KeyTab+  | KeyLeft+  | KeyRight+  | KeyUp+  | KeyDown+  | KeyHome+  | KeyEnd+  | KeyPageUp+  | KeyPageDown+  | KeyInsert+  | KeySpace+  | KeyF !Int+  -- ^ @KeyF 1@ to @KeyF 24@.+  | KeyPrintScreen+  | KeyPause+  | KeyCapsLock+  | KeyNumLock+  | KeyScrollLock+  | KeyMenu+  -- ^ The context-menu (application) key.+  | KeyChar !Char+  -- ^ A key that types a character; see 'Key'.+  deriving (Eq, Ord, Show)++-- | Modifier keys held while the frame's input is processed.+data Modifiers = Modifiers+  { modShift :: !Bool+  , modCtrl :: !Bool+  , modAlt :: !Bool+  -- ^ Alt, which macOS calls Option.+  , modSuper :: !Bool+  -- ^ Command on macOS, the Windows key on Windows, Super elsewhere.+  }+  deriving (Eq, Ord, Show)++-- | Union: a modifier is held if either side holds it.+instance Semigroup Modifiers where+  Modifiers s c a u <> Modifiers s' c' a' u' = Modifiers (s || s') (c || c') (a || a') (u || u')++instance Monoid Modifiers where+  mempty = noModifiers++-- | No modifier held.+noModifiers :: Modifiers+noModifiers = Modifiers False False False False++-- | Read a backend's modifier bit mask, given its bits for Shift, Ctrl, Alt+-- and Super.+{-# INLINE modifiersFromBits #-}+modifiersFromBits :: Bits a => a -> a -> a -> a -> a -> Modifiers+modifiersFromBits m shift ctrl alt super = Modifiers (has shift) (has ctrl) (has alt) (has super)+  where+    has bit = m .&. bit /= zeroBits++-- | Whether the platform's command modifier is held: Command ('modSuper') on+-- macOS, Ctrl elsewhere. It is @M-@ in 'NanoUI.Shortcut.parseShortcut'.+modPrimary :: Modifiers -> Bool+modPrimary = if onMac then modSuper else modCtrl++-- | Whether a character key is a shortcut rather than typing: 'modPrimary'+-- (Command on macOS, Ctrl elsewhere) without Alt.+chordModifiers :: Modifiers -> Bool+chordModifiers mods = modPrimary mods && not (modAlt mods)++-- | Only the platform's command modifier ('modPrimary').+primaryModifiers :: Modifiers+primaryModifiers+  | onMac = noModifiers {modSuper = True}+  | otherwise = noModifiers {modCtrl = True}++-- | Whether the word-jump modifier is held: Option ('modAlt') on macOS, Ctrl+-- elsewhere. It widens caret motion and deletion to a word (iced's @jump@).+modJump :: Modifiers -> Bool+modJump = if onMac then modAlt else modCtrl++-- | Whether Command ('modSuper') is held on macOS, where it moves the caret+-- or deletes to the end of the line. Always 'False' elsewhere.+modMacCommand :: Modifiers -> Bool+modMacCommand m = onMac && modSuper m++-- | Whether this is macOS, where Command is the command modifier and Option+-- types characters.+onMac :: Bool+onMac = os == "darwin"+{-# NOINLINE onMac #-}++-- | Whether no modifier other than Shift is held. Controls use this to tell+-- a plain key, such as an arrow on a slider, from a chord.+shiftAtMost :: Modifiers -> Bool+shiftAtMost m = not (modCtrl m || modAlt m || modSuper m)++-- | Whether a key pressed with these modifiers is a command rather than+-- typing. Named keys other than Space always are. A 'KeyChar' or Space is a+-- command with Super (Command) or Ctrl held, except that outside macOS+-- Ctrl+Alt is AltGr and types, while Alt alone is a command. On macOS,+-- Option types.+isCommandKey :: Modifiers -> Key -> Bool+isCommandKey mods = \case+  KeyChar _ -> chord+  KeySpace -> chord+  _ -> True+  where+    chord = modSuper mods || if onMac then modCtrl mods else modCtrl mods /= modAlt mods++-- | OS-level drag-and-drop event kind, mirroring @SDL_EventType@ drop codes.+data DropType+  = DropBegin     -- ^ A drag enters the window; no position or payload yet.+  | DropPosition  -- ^ The drag pointer moved over the window; position available.+  | DropFile      -- ^ A file path was dropped; 'dropEventData' holds the path.+  | DropText      -- ^ Text was dropped; 'dropEventData' holds the text.+  | DropComplete  -- ^ The OS drag operation finished.+  deriving (Eq, Show)++-- | A single normalized drop payload surfaced to widgets.+data DropEvent = DropEvent+  { dropEventType :: !DropType+  , dropEventPos :: !(Maybe V2)+  , dropEventData :: !Text+  }+  deriving (Eq, Show)++-- | Input for one frame. Positions and window sizes are in logical pixels,+-- scroll in wheel steps, delta time in seconds. Held buttons, held keys and+-- the IME composition persist between frames. Presses, releases, text and+-- drops are one-shot events that backends clear with 'clearEphemeral'.+data Input = Input+  { inputMousePos :: {-# UNPACK #-} !V2+  , inputButtonsHeld :: {-# UNPACK #-} !MouseButtons+  -- ^ Buttons down after the frame's events ('heldIn').+  , inputButtonsPressed :: {-# UNPACK #-} !MouseButtons+  -- ^ Buttons that went down this frame ('pressedIn').+  , inputButtonsReleased :: {-# UNPACK #-} !MouseButtons+  -- ^ Buttons that came up this frame ('releasedIn').+  , inputMouseClicks :: {-# UNPACK #-} !Int+  -- ^ 1 for a single press; 2 or 3 for a double or triple click (a quick+  -- press near the previous one, with the same button).+  , inputScroll :: {-# UNPACK #-} !V2+  , inputKeys :: SmallArray Key+  -- ^ Keys pressed this frame in event order, auto-repeats included. A frame+  -- batched by 'takeFrame' has at most one command key ('isCommandKey'),+  -- last and possibly repeated. The frame's text came before it, and+  -- 'inputModifiers' are the ones it was pressed with.+  , inputKeysNew :: SmallArray Key+  -- ^ The presses in 'inputKeys' that are not auto-repeats, in event order.+  , inputKeysReleased :: SmallArray Key+  -- ^ Keys released this frame, in event order.+  , inputKeysHeld :: SmallArray Key+  -- ^ Keys down after the frame's events, each once, in press order.+  , inputChars :: !Text+  , inputModifiers :: !Modifiers+  , inputWindowSize :: {-# UNPACK #-} !Size+  , inputDeltaTime :: {-# UNPACK #-} !Float+  , inputDrops :: SmallArray DropEvent+  , inputWindowRedraw :: {-# UNPACK #-} !Bool+  , inputComposition :: !(Maybe Composition)+  -- ^ The IME's uncommitted text, kept until the IME changes or ends it+  -- ('applyComposition'). Committed text arrives in 'inputChars'.+  }+  deriving (Eq, Show)++-- | A key or mouse button: whether it went down this frame, came up, or is+-- held. Reads like 'NanoUI.Shortcut.shortcutIn' does for a chord:+--+-- > pressedIn KeyEscape inp+-- > heldIn MouseMiddle inp+--+-- These read raw input, regardless of focus or hover. In a view, use+-- 'NanoUI.keyPressed' and 'NanoUI.mousePressed', which only fire when the+-- view has the keyboard or the pointer.+class Pressable a where+  -- | Went down this frame, auto-repeats included.+  pressedIn :: a -> Input -> Bool++  -- | Went down this frame while up, so auto-repeats are excluded+  -- ('inputKeysNew'). Mouse buttons don't repeat, so for them this is+  -- 'pressedIn'.+  pressedOnceIn :: a -> Input -> Bool+  pressedOnceIn = pressedIn++  -- | Came up this frame.+  releasedIn :: a -> Input -> Bool++  -- | Down after the frame's events.+  heldIn :: a -> Input -> Bool++instance Pressable Key where+  {-# INLINE pressedIn #-}+  pressedIn k = inputKeysElem k . inputKeys+  {-# INLINE pressedOnceIn #-}+  pressedOnceIn k = inputKeysElem k . inputKeysNew+  {-# INLINE releasedIn #-}+  releasedIn k = inputKeysElem k . inputKeysReleased+  {-# INLINE heldIn #-}+  heldIn k = inputKeysElem k . inputKeysHeld++instance Pressable MouseButton where+  {-# INLINE pressedIn #-}+  pressedIn b = buttonsMember b . inputButtonsPressed+  {-# INLINE releasedIn #-}+  releasedIn b = buttonsMember b . inputButtonsReleased+  {-# INLINE heldIn #-}+  heldIn b = buttonsMember b . inputButtonsHeld++-- | Whether any mouse button went down this frame.+{-# INLINE anyButtonPressed #-}+anyButtonPressed :: Input -> Bool+anyButtonPressed = not . buttonsNull . inputButtonsPressed++-- | Whether any mouse button came up this frame.+{-# INLINE anyButtonReleased #-}+anyButtonReleased :: Input -> Bool+anyButtonReleased = not . buttonsNull . inputButtonsReleased++-- | No events or held buttons, with an 800x600 window and zero elapsed time.+-- Override window size and delta time when driving headless frames.+emptyInput :: Input+emptyInput =+  Input+    { inputMousePos = V2 0 0+    , inputButtonsHeld = noButtons+    , inputButtonsPressed = noButtons+    , inputButtonsReleased = noButtons+    , inputMouseClicks = 1+    , inputScroll = V2 0 0+    , inputKeys = mempty+    , inputKeysNew = mempty+    , inputKeysReleased = mempty+    , inputKeysHeld = mempty+    , inputChars = ""+    , inputModifiers = noModifiers+    , inputWindowSize = Size 800 600+    , inputDeltaTime = 0+    , inputDrops = mempty+    , inputWindowRedraw = False+    , inputComposition = Nothing+    }++-- | Backend-independent cursor shape requested by a hovered control. The+-- shapes are CSS's cursors. Where the platform lacks one, the SDL and RGFW+-- backends show its 'cursorFallback'.+data UiCursorKind+  = -- | From a widget ('NanoUI.Widgets.Custom.widgetCursor'), defers to the+    -- enclosing 'NanoUI.withCursorShape' scope, or defaults to the arrow. As a+    -- scope's own shape, the arrow.+    UiCursorDefault+  | UiCursorPointer+  | UiCursorText+  | UiCursorGrab+  | UiCursorGrabbing+  | UiCursorNsResize+  | UiCursorEwResize+  | UiCursorNwseResize+  | UiCursorNeswResize+  | -- | The action is not allowed here: a slashed circle.+    UiCursorNotAllowed+  | -- | Busy, and not taking input: an hourglass or a spinner.+    UiCursorWait+  | -- | Busy, but still taking input: the arrow with a spinner.+    UiCursorProgress+  | -- | Help is available: the arrow with a question mark.+    UiCursorHelp+  | -- | Precise selection, as over a canvas.+    UiCursorCrosshair+  | -- | A cell or a set of cells can be selected: a thick plus.+    UiCursorCell+  | -- | What is under the pointer can be moved: arrows in four directions.+    UiCursorMove+  | -- | The content can be scrolled in any direction.+    UiCursorAllScroll+  | -- | A drop here copies.+    UiCursorCopy+  | -- | A drop here makes a link or shortcut.+    UiCursorAlias+  | -- | A context menu is available.+    UiCursorContextMenu+  | -- | A click zooms in: a magnifier with a plus.+    UiCursorZoomIn+  | -- | A click zooms out: a magnifier with a minus.+    UiCursorZoomOut+  | -- | A column can be resized sideways.+    UiCursorColResize+  | -- | A row can be resized up or down.+    UiCursorRowResize+  | -- | This and the next seven are one-way resize arrows, for an edge or+    -- corner that can only move one way, such as a pane at its limit.+    -- Platforms without them show the two-way arrows.+    UiCursorNResize+  | UiCursorNeResize+  | UiCursorEResize+  | UiCursorSeResize+  | UiCursorSResize+  | UiCursorSwResize+  | UiCursorWResize+  | UiCursorNwResize+  | -- | No pointer shown, as over a video or a canvas that draws its own.+    UiCursorHidden+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | The closest shape among the cursors SDL and RGFW have. Kinds they have+-- map to themselves.+cursorFallback :: UiCursorKind -> UiCursorKind+cursorFallback = \case+  UiCursorGrab -> UiCursorMove+  UiCursorGrabbing -> UiCursorMove+  UiCursorAllScroll -> UiCursorMove+  UiCursorCell -> UiCursorCrosshair+  UiCursorColResize -> UiCursorEwResize+  UiCursorRowResize -> UiCursorNsResize+  k | k `elem` [UiCursorHelp, UiCursorCopy, UiCursorAlias, UiCursorContextMenu, UiCursorZoomIn, UiCursorZoomOut] -> UiCursorDefault+  k -> k++-- | Show the platform cursor for a kind when it differs from the kind last+-- shown, which @ref@ holds. 'UiCursorHidden' hides the pointer through+-- @setVisible False@ and sets no shape; the next other kind shows it again+-- with @setVisible True@ before @setShape@ sets that kind's shape. The+-- backend maps the kind to its own cursor in @setShape@, usually through+-- 'cursorFallback'.+syncCursorKind :: IORef UiCursorKind -> (Bool -> IO ()) -> (UiCursorKind -> IO ()) -> UiCursorKind -> IO ()+syncCursorKind ref setVisible setShape want = do+  cur <- readIORef ref+  when (want /= cur) $ do+    writeIORef ref want+    let hidden = want == UiCursorHidden+    when (hidden /= (cur == UiCursorHidden)) (setVisible (not hidden))+    unless hidden (setShape want)++-- | Grab cursor over a target, becoming a closed hand while the left button is held.+grabHoverKind :: Bool -> Input -> UiCursorKind+grabHoverKind onTarget inp = grabDragKind onTarget False inp++-- | Choose a grab cursor, keeping the closed hand during a drag outside the target.+grabDragKind :: Bool -> Bool -> Input -> UiCursorKind+grabDragKind onTarget dragging inp+  | dragging = UiCursorGrabbing+  | onTarget, heldIn MouseLeft inp = UiCursorGrabbing+  | onTarget = UiCursorGrab+  | otherwise = UiCursorDefault++-- | Clear one-shot events and the redraw flag. Keeps held buttons and keys,+-- pointer position, modifiers, window size, delta time and the composition.+clearEphemeral :: Input -> Input+clearEphemeral inp = (stripInteractionInput inp) {inputMouseClicks = 1, inputWindowRedraw = False}++-- | Whether Ctrl+C was pressed (the C key, or a typed @c@ or ETX), which+-- closes the window when nothing in the frame uses it+-- ('NanoUI.Runner.runSessionLoop'). Ctrl alone: Ctrl+Alt is AltGr on many+-- layouts, and Ctrl+Shift+C is a shortcut of its own.+isHardQuitInput :: Input -> Bool+isHardQuitInput inp =+  inputModifiers inp == noModifiers {modCtrl = True}+    && ( pressedIn (KeyChar 'c') inp+          || T.elem 'c' (inputChars inp)+          || T.elem '\ETX' (inputChars inp)+       )++-- | Fold events into one frame's input, stopping where the frame must end.+-- Returns the input, the events taken, and the rest.+--+-- A frame ends after an edge (@isEdge@, a mouse press or release), so each+-- edge gets its own frame. It also ends when the modifiers change once it+-- holds keys or text, and after a command key ('isCommandKey') when text or+-- another key follows. Within a single frame, text, keys and modifiers are+-- unordered, so text must precede the single command key, and modifiers must+-- match those active when the keys and text arrived. Auto-repeats stay in+-- the key's frame, so only mixed bursts cost extra frames.+takeFrame :: (Input -> e -> Input) -> (e -> Bool) -> Input -> [e] -> (Input, [e], [e])+takeFrame apply isEdge = go []+  where+    go taken !inp = \case+      [] -> (inp, reverse taken, [])+      events@(e : rest)+        | commandEnds inp next -> (inp, reverse taken, events)+        | isEdge e -> (next, reverse (e : taken), rest)+        | otherwise -> go (e : taken) next rest+        where+          next = apply inp e++-- | Whether the event that turned @cur@ into @next@ must wait for the next+-- frame: it changed the modifiers after @cur@ took keys or text, or @cur@+-- ends in a command key and the event typed text or pressed a different+-- key. A plain key's text read with a modifier pressed after it would turn+-- it into a chord, as typing @x@ then holding Ctrl would cut.+commandEnds :: Input -> Input -> Bool+commandEnds cur next+  | inputModifiers next /= mods = n > 0 || not (T.null (inputChars cur))+  | n == 0 || not (isCommandKey mods k) = False+  | otherwise =+      inputChars next /= inputChars cur+        || (sizeofSmallArray (inputKeys next) > n && indexSmallArray (inputKeys next) n /= k)+  where+    n = sizeofSmallArray (inputKeys cur)+    k = indexSmallArray (inputKeys cur) (n - 1)+    mods = inputModifiers cur++-- | Append a key in event order. Copies the small array.+{-# INLINE appendInputKey #-}+appendInputKey :: Key -> SmallArray Key -> SmallArray Key+appendInputKey k ks = snocSmallArray ks k++-- | Apply a key press ('True') or release. A press joins 'inputKeys', and+-- also 'inputKeysNew' and 'inputKeysHeld' unless the key is already held+-- (an auto-repeat). A release joins 'inputKeysReleased' and leaves the held+-- keys. Backends pass auto-repeats in as presses.+applyKey :: Key -> Bool -> Input -> Input+applyKey k True inp+  | inputKeysElem k held = inp {inputKeys = appendInputKey k (inputKeys inp)}+  | otherwise =+      inp+        { inputKeys = appendInputKey k (inputKeys inp)+        , inputKeysNew = appendInputKey k (inputKeysNew inp)+        , inputKeysHeld = appendInputKey k held+        }+  where+    held = inputKeysHeld inp+applyKey k False inp =+  inp+    { inputKeysReleased = appendInputKey k (inputKeysReleased inp)+    , inputKeysHeld =+        if inputKeysElem k held then smallArrayFromList (filter (/= k) (toList held)) else held+    }+  where+    held = inputKeysHeld inp++-- | Release every held key, modifier and mouse button. Backends call this+-- when the window loses keyboard focus, since a key or button released+-- elsewhere sends no release event: a button left held would keep a drag+-- going, or a stepper arrow repeating, until the next click. Held keys join+-- 'inputKeysReleased' and held buttons 'inputButtonsReleased'.+releaseAllKeys :: Input -> Input+releaseAllKeys inp =+  inp+    { inputKeysReleased = inputKeysReleased inp <> inputKeysHeld inp+    , inputKeysHeld = mempty+    , inputModifiers = noModifiers+    , inputButtonsReleased = inputButtonsReleased inp <> inputButtonsHeld inp+    , inputButtonsHeld = noButtons+    }++-- | The drops with one more at the end.+{-# INLINE appendDropEvent #-}+appendDropEvent :: DropEvent -> SmallArray DropEvent -> SmallArray DropEvent+appendDropEvent ev evs = snocSmallArray evs ev++-- A frame holds a few keys and drops, so each append copies.+snocSmallArray :: SmallArray a -> a -> SmallArray a+snocSmallArray xs x = runSmallArray $ do+  let n = sizeofSmallArray xs+  out <- newSmallArray (n + 1) x+  copySmallArray out 0 xs 0 n+  pure out++-- | The key for a keypad digit or point (@'0'@ to @'9'@, @'.'@): the typed+-- character with Num Lock on, otherwise the navigation key printed on it+-- ('Nothing' for 5).+keypadKey :: Bool -> Char -> Maybe Key+keypadKey True c = Just (KeyChar c)+keypadKey False c =+  lookup c [('0', KeyInsert), ('1', KeyEnd), ('2', KeyDown), ('3', KeyPageDown), ('4', KeyLeft), ('6', KeyRight), ('7', KeyHome), ('8', KeyUp), ('9', KeyPageUp), ('.', KeyDelete)]++-- | A mouse button. 'MouseBack' and 'MouseForward' are the side buttons (X1+-- and X2) that browsers use for navigation.+data MouseButton+  = MouseLeft+  | MouseRight+  | MouseMiddle+  | MouseBack+  | MouseForward+  | MouseOther !Int+  -- ^ Any other button, by SDL's 1-based number ('mouseButtonNumber'), so+  -- the first extra button is @MouseOther 6@. 'MouseButtons' stores+  -- @MouseOther 1@ to @5@ as the named buttons and tracks buttons up to 32.+  deriving (Eq, Ord, Show)++-- | The button for an SDL button number: 1 to 5 are left, middle, right,+-- back and forward; any other number is 'MouseOther'.+mouseButtonNumber :: Int -> MouseButton+mouseButtonNumber = \case+  1 -> MouseLeft+  2 -> MouseMiddle+  3 -> MouseRight+  4 -> MouseBack+  5 -> MouseForward+  n -> MouseOther n++-- | The button's bit in 'MouseButtons': its number minus one, or -1 past 32.+{-# INLINE buttonBit #-}+buttonBit :: MouseButton -> Int+buttonBit = \case+  MouseLeft -> 0+  MouseMiddle -> 1+  MouseRight -> 2+  MouseBack -> 3+  MouseForward -> 4+  MouseOther n+    | n >= 1 && n <= 32 -> n - 1+    | otherwise -> -1++-- | A set of mouse buttons, as held, pressed or released in an 'Input' or+-- clicked with ('NanoUI.respClickedWith'). '<>' is union.+newtype MouseButtons = MouseButtons Word32+  deriving (Eq)++instance Show MouseButtons where+  showsPrec d bs = showParen (d > 10) (showString "buttonsFromList " . showsPrec 11 (buttonsToList bs))++instance Semigroup MouseButtons where+  {-# INLINE (<>) #-}+  MouseButtons a <> MouseButtons b = MouseButtons (a .|. b)++instance Monoid MouseButtons where+  mempty = noButtons++-- | No button.+noButtons :: MouseButtons+noButtons = MouseButtons 0++-- | Whether the set holds the button.+{-# INLINE buttonsMember #-}+buttonsMember :: MouseButton -> MouseButtons -> Bool+buttonsMember b (MouseButtons w) = let i = buttonBit b in i >= 0 && testBit w i++-- | Whether the set is empty.+{-# INLINE buttonsNull #-}+buttonsNull :: MouseButtons -> Bool+buttonsNull (MouseButtons w) = w == 0++-- | The set with the button added.+{-# INLINE buttonsInsert #-}+buttonsInsert :: MouseButton -> MouseButtons -> MouseButtons+buttonsInsert b bs@(MouseButtons w) = let i = buttonBit b in if i < 0 then bs else MouseButtons (setBit w i)++-- | The set without the button.+{-# INLINE buttonsDelete #-}+buttonsDelete :: MouseButton -> MouseButtons -> MouseButtons+buttonsDelete b bs@(MouseButtons w) = let i = buttonBit b in if i < 0 then bs else MouseButtons (clearBit w i)++-- | The buttons in the set, by number.+buttonsToList :: MouseButtons -> [MouseButton]+buttonsToList (MouseButtons w)+  | w == 0 = []+  | otherwise =+      let i = countTrailingZeros w+       in mouseButtonNumber (i + 1) : buttonsToList (MouseButtons (clearBit w i))++-- | The set of the buttons listed.+buttonsFromList :: [MouseButton] -> MouseButtons+buttonsFromList = foldr buttonsInsert noButtons++-- | The buttons that pass the test, each tested once, in number order.+{-# INLINE buttonsFilterM #-}+buttonsFilterM :: Monad m => (MouseButton -> m Bool) -> MouseButtons -> m MouseButtons+buttonsFilterM p (MouseButtons w0) = go w0 0+  where+    go 0 !acc = pure (MouseButtons acc)+    go w !acc = do+      let i = countTrailingZeros w+      keep <- p (mouseButtonNumber (i + 1))+      go (clearBit w i) (if keep then setBit acc i else acc)++-- | Apply a button press ('True') or release to the held, pressed and+-- released sets.+applyMouseButton :: MouseButton -> Bool -> Input -> Input+applyMouseButton b True inp =+  inp {inputButtonsHeld = buttonsInsert b (inputButtonsHeld inp), inputButtonsPressed = buttonsInsert b (inputButtonsPressed inp)}+applyMouseButton b False inp =+  inp {inputButtonsHeld = buttonsDelete b (inputButtonsHeld inp), inputButtonsReleased = buttonsInsert b (inputButtonsReleased inp)}++-- | The pointer left the window: move it off every widget, as+-- 'withoutPointer' does, so nothing stays hovered. While a button is held+-- the pointer stays put: the drag goes on, and where no motion arrives from+-- outside the window (Windows), leaving would drop a dragged slider or+-- scrollbar to the far corner. The release and later motion move it. Held+-- buttons stay held until their releases arrive.+applyPointerLeave :: Input -> Input+applyPointerLeave inp+  | inputPointerHeld inp = inp+  | otherwise = inp {inputMousePos = offWindow}++-- | A point far outside any window.+offWindow :: V2+offWindow = V2 (-1e6) (-1e6)++-- | Copy a list of key events into the frame's array, preserving order.+{-# INLINE inputKeysFromList #-}+inputKeysFromList :: [Key] -> SmallArray Key+inputKeysFromList = smallArrayFromList++-- | Whether the frame contains no key events.+{-# INLINE inputKeysNull #-}+inputKeysNull :: SmallArray Key -> Bool+inputKeysNull ks = sizeofSmallArray ks == 0++-- | Whether a key occurs in the frame's events.+{-# INLINE inputKeysElem #-}+inputKeysElem :: Key -> SmallArray Key -> Bool+inputKeysElem = elem++-- | Strict left fold over keys in event order.+{-# INLINE foldInputKeys #-}+foldInputKeys :: (a -> Key -> a) -> a -> SmallArray Key -> a+foldInputKeys = foldl'++-- | Compare interaction fields, including buttons, keys, scroll, drops, and+-- window size. Pointer motion, elapsed time, and the redraw flag are ignored.+inputInteracted :: Input -> Input -> Bool+inputInteracted a b =+  inputButtonsHeld a /= inputButtonsHeld b+    || inputButtonsPressed a /= inputButtonsPressed b+    || inputButtonsReleased a /= inputButtonsReleased b+    || inputMouseClicks a /= inputMouseClicks b+    || inputScroll a /= inputScroll b+    || inputKeys a /= inputKeys b+    || inputKeysNew a /= inputKeysNew b+    || inputKeysReleased a /= inputKeysReleased b+    || inputKeysHeld a /= inputKeysHeld b+    || inputChars a /= inputChars b+    || inputModifiers a /= inputModifiers b+    || inputWindowSize a /= inputWindowSize b+    || inputDrops a /= inputDrops b+    || inputComposition a /= inputComposition b++-- | Whether any mouse button is held.+{-# INLINE inputPointerHeld #-}+inputPointerHeld :: Input -> Bool+inputPointerHeld = not . buttonsNull . inputButtonsHeld++-- | Remove one-shot interaction events for a repeated view pass. Retains+-- pointer position, held buttons and keys (so hover and drag survive), and+-- the composition, which the focused field still draws.+stripInteractionInput :: Input -> Input+stripInteractionInput inp =+  inp+    { inputButtonsPressed = noButtons+    , inputButtonsReleased = noButtons+    , inputKeys = mempty+    , inputKeysNew = mempty+    , inputKeysReleased = mempty+    , inputChars = ""+    , inputScroll = V2 0 0+    , inputDrops = mempty+    }++-- | Clear pointer buttons and scroll and move the pointer off-screen, for+-- layers occluded by a menu, dropdown, or panel in front, or outside the+-- layer where a held button was pressed.+withoutPointer :: Input -> Input+withoutPointer inp =+  inp+    { inputMousePos = offWindow+    , inputButtonsHeld = noButtons+    , inputButtonsPressed = noButtons+    , inputButtonsReleased = noButtons+    , inputScroll = V2 0 0+    }++-- | Text an input method (IME) is composing but has not committed, such as+-- Chinese or Japanese input before conversion. The focused text field draws+-- it underlined at the caret. The field's value changes only when the IME+-- commits, and the committed text arrives as typed text.+data Composition = Composition+  { compositionText :: !Text+  -- ^ The text being composed. Empty text counts as no composition.+  , compositionCursor :: !Int+  -- ^ The IME's caret, or the start of its selection, in characters.+  , compositionSelection :: !Int+  -- ^ Characters selected from 'compositionCursor', such as the clause+  -- being converted; 0 for a plain caret.+  }+  deriving (Eq, Show)++-- | Apply an IME composition update, as SDL's @SDL_EVENT_TEXT_EDITING@+-- reports it: text, selection start and selection length, in characters.+-- Empty text ends the composition. A start past the text is clamped; a+-- negative (unset) one puts the caret at the end.+applyComposition :: Text -> Int -> Int -> Input -> Input+applyComposition txt start len inp+  | T.null txt = inp {inputComposition = Nothing}+  | otherwise =+      let n = T.length txt+          cursor = if start < 0 then n else min n start+       in inp {inputComposition = Just (Composition txt cursor (clamp 0 (n - cursor) len))}++-- | The kind of text a widget asks the IME for (iced's+-- @input_method::Purpose@): normal text, a secret the IME should neither+-- show nor learn, or a number. On-screen keyboards pick their keys from it.+data InputPurpose = InputNormal | InputSecure | InputNumeric+  deriving (Eq, Ord, Show, Enum, Bounded)
+ lib/NanoUI/Internal/Layout/Arena.hs view
@@ -0,0 +1,879 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Layout nodes for one frame, stored in flat mutable arrays.+--+-- A node is an index ('NodeIdx') into those arrays. Indices count up in the+-- order the view adds nodes, so a parent's index is lower than its children's.+-- The strided arrays give every node a row of fixed width, and a column such+-- as 'GeomX' or 'TreeParent' names a slot in the row: node @idx@ keeps+-- geometry column @col@ at element @idx * geomStride + fromEnum col@ of+-- 'naArrGeom'. 'NodeArenaArrays' lists the arrays, and accessors such as+-- 'getNodeRect' and 'getParent' hide the arithmetic.+--+-- The widgets ("NanoUI.Internal.Widgets.Node") fill the arena while the view runs,+-- "NanoUI.Internal.Layout.Solve" writes every node's rect into it, and the frame's+-- input, paint and damage passes read it. 'resetNodeArena' empties it before+-- the view runs again, and a node index means nothing after that.+--+-- The arena also owns the solver's scratch buffers and memos, so that they+-- stay allocated from one frame to the next. The 'LayoutCache' defined here+-- lets a frame whose layout inputs did not change skip the solve.+module NanoUI.Internal.Layout.Arena+  ( NodeIdx+  , IOArr+  , NodeType (..)+  , NodeArenaArrays (..)+  , isWidgetNode+  , packsNodeFont+  , labelFontShift+  , nodeFontBits+  , hasCenteredLabel+  , isContainerNode+  , isScrollNode+  , isFloatingNode+  , NodeClass (..)+  , SizingTag (..)+  , DirTag (..)+  , NodeArena (..)+  , WidthMemo+  , IdIndex+  , FlexScratch (..)+  , newNodeArena+  , resetNodeArena+  , arenaCount+  , topModalNode+  , floatingNodeCount+  , layeredNodeCount+  , scrollableNodeCount+  , textFieldNodeCount+  , arenaArrays+  , GeomCol (..)+  , StyleCol (..)+  , TagCol (..)+  , TreeCol (..)+  , geomStride+  , styleStride+  , tagStride+  , treeStride+  , readGeom+  , writeGeom+  , readStyle+  , readTagEnum+  , writeTagEnum+  , readTree+  , writeTree+  , addNode+  , addNodeFromLayout+  , rootAttachParent+  , setNodeText+  , getParent+  , getFirstChild+  , getNextSibling+  , getNodeType+  , getDirection+  , getScrollContentW+  , setScrollContentW+  , AxisSizing (..)+  , axisSizing+  , readAxisSizing+  , getWidthSizing+  , getHeightSizing+  , readPadding+  , getPadding+  , parentIsRow+  , getAlignX+  , readAlignX+  , readAlignY+  , readItemsAlign+  , effectiveAlignX+  , effectiveAlignY+  , getFlow+  , hasPinnedBelow+  , hasScrollerBelow+  , hasBaselineChild+  , getPointerMode+  , getNodeRect+  , setRect+  , getClipRect+  , getClipBounds+  , setClipRect+  , writeClipRectRaw+  , getText+  , getOptions+  , setOptions+  , ImageNode (..)+  , setImageNode+  , getImageNode+  , setImageId+  , getImageId+  , getWidgetId+  , setWidgetId+  , lookupNodeByWidgetId+  , lookupNodeByKey+  , getIdSuperseded+  , readStyleIdx+  , getStyleIdx+  , setStyleIdx+  , getNodeValue+  , setNodeValue+  , setSolvedValue+  , getNodeFontSize+  , getNodeFontColor+  , getNodeScope+  , getArenaScope+  , setArenaScope+  , getScopeSignature+  , getNodePaintHash+  , mixNodePaintHash+  , getPaintSignature+  , ensureScratchCapacity+  , AxisSnapshot (..)+  , ensureAxisSnapshot+  , memoizeWidth+  , forFloatingNodes_+  , floatingNodesInPaintOrder+  , forChildNodes_+  , foldFlowChildrenM+  , flowChildrenInOrder+  , flowChildEnds+  , foldPlacedChildrenM+  , forChildrenInPaintOrder_+  , firstChildOnTopJustM+  , drawnOver+  , AdornRows (..)+  , adornRows+  , findNodeRevM+  , findClassNodeM+  , findClassNodeRevM+  , foldClassNodesM+  , classNodes+  , foldClassNodeRevM+  , forClassNodes_+  , walkFloatingAncestors+  , findNodeM+  , foldNodesM+  , firstChildJustM+  , walkAncestors+  , LayoutCache (..)+  , CustomMeasureRecord+  , PlacedFloat (..)+  , newLayoutCache+  , captureLayoutCache+  , layoutSigMatches+  , computeSubtreeHashes+  , restoreLayoutCache+  , restoreScrollExtents+  , subtreeSpan+  , snapshotPlaced+  , restorePlaced+  ) where++import Control.Monad (forM_, unless, when)+import Data.Bits (complement, shiftL, shiftR, xor, (.&.), (.|.))+import Data.Hashable (Hashable, hash)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe, isJust)+import Data.Primitive.Array (newArray, readArray, sizeofMutableArray, writeArray)+import Data.Primitive.PrimArray+  ( copyMutablePrimArray+  , getSizeofMutablePrimArray+  , newPrimArray+  , readPrimArray+  , setPrimArray+  , writePrimArray+  )+import Data.Primitive.PrimVar (newPrimVar, readPrimVar, writePrimVar)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word8, Word32, Word64)+import GHC.Float (castFloatToWord32)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Image (ImageLook (..), Rotation (..))+import NanoUI.Internal.Layout.Arena.Cache+import NanoUI.Internal.Layout.Arena.Query+import NanoUI.Internal.Layout.Arena.Types+import NanoUI.Internal.Store (ptrEq)+import NanoUI.Internal.Style (AlignY (..), Direction (..), Flow (..), ItemsAlign (..), Layout (..), Padding (..), PointerMode (..))+import NanoUI.Internal.Types (Color (..), Rect (..), V2 (..), forUpTo_, newZeroedPrimArray)++-- | An empty arena. It starts with room for 256 nodes (@initialCapacity@), 64+-- children of one container in the solver's buffers, and 256 nesting depths.+-- All three grow when a view needs more.+newNodeArena :: IO NodeArena+newNodeArena = do+  let cap = initialCapacity+  naCount <- newPrimVar 0+  naCapacity <- newPrimVar cap+  naArrays <- newIORef =<< newNodeArenaArrays cap+  naScratch <- newIORef =<< newFlexScratch 64+  naSnapLevels <- newIORef =<< newArray 256 =<< newAxisSnapshot 0+  naFrameTag <- newPrimVar 1+  naEpoch <- newPrimVar 1+  naIndex <- newIORef =<< newIdIndex 1024+  naScope <- newPrimVar 0+  naScopeSig <- newPrimVar 0+  naInputSig <- newZeroedPrimArray 1+  naPaintSig <- newZeroedPrimArray 1+  naClassCounts <- newZeroedPrimArray nodeClassCount+  naImages <- newIORef =<< newArray 0 noImageNode+  naImageCount <- newZeroedPrimArray 1+  naHighWater <- newPrimVar 0+  pure NodeArena {..}++-- | Begin an empty frame while retaining array capacity. Invalidates node+-- indices, width memos, and widget-id lookups, and resets paint-scope and+-- floating-panel state. 'addNode' initialises each reused slot.+resetNodeArena :: NodeArena -> IO ()+resetNodeArena na = do+  prevCount <- readPrimVar (naCount na)+  highWater <- readPrimVar (naHighWater na)+  -- Release boxed references in slots beyond the frame that just finished,+  -- while keeping live slots [0 .. prevCount - 1] intact so 'setNodeText' and+  -- 'setOptions' keep their pointer-equality hash reuse across steady frames.+  if prevCount < highWater+    then do+      a <- readIORef (naArrays na)+      let clearAt !i = when (i < highWater) $ do+            writeArray (naArrTextStore a) i T.empty+            writeArray (naArrOptionsStore a) i []+            writeArray (naArrOptionsLast a) i []+            clearAt (i + 1)+      clearAt prevCount+      setPrimArray (naArrTextHash a) prevCount (highWater - prevCount) 0+      setPrimArray (naArrOptionsHash a) prevCount (highWater - prevCount) 0+      writePrimVar (naHighWater na) prevCount+    else when (prevCount > highWater) (writePrimVar (naHighWater na) prevCount)+  prevImages <- readPrimArray (naImageCount na) 0+  when (prevImages > 0) $ do+    imgs <- readIORef (naImages na)+    forUpTo_ prevImages (\i -> writeArray imgs i noImageNode)+  writePrimVar (naCount na) 0+  writePrimVar (naScope na) 0+  writePrimVar (naScopeSig na) 0+  writePrimArray (naInputSig na) 0 0+  writePrimArray (naPaintSig na) 0 0+  setPrimArray (naClassCounts na) 0 nodeClassCount 0+  writePrimArray (naImageCount na) 0 0+  -- 0 marks a memo entry that was never written, so the tag wraps to 1. On+  -- wrap-around, entries from the previous use of tag 1 would read as live,+  -- so untag them all.+  !ft <- readPrimVar (naFrameTag na)+  writePrimVar (naFrameTag na) (if ft == maxBound then 1 else ft + 1)+  when (ft == maxBound) $ do+    a <- readIORef (naArrays na)+    forM_ [naArrWrapMemo a, naArrFitMemo a] $ \(WidthMemo tags _) ->+      getSizeofMutablePrimArray tags >>= \c -> setPrimArray tags 0 c 0+  -- Bumping the epoch empties the id index. On wrap-around, stale entries+  -- from the previous use of that epoch would read as live, so clear it.+  !ep <- readPrimVar (naEpoch na)+  let !ep' = ep + 1+  IdIndex slots mask live <- readIORef (naIndex na)+  writePrimArray live 0 0+  if ep' == 0+    then writePrimVar (naEpoch na) 1 >> setPrimArray slots 0 (2 * (mask + 1)) 0+    else writePrimVar (naEpoch na) ep'++{-# NOINLINE ensureCapacity #-}+ensureCapacity :: NodeArena -> Int -> IO ()+ensureCapacity na needed = do+  cap <- readPrimVar (naCapacity na)+  when (needed >= cap) $ do+    let newCap = cap * 2+    newA <- readIORef (naArrays na) >>= growNodeArenaArrays (naClassCounts na) cap newCap+    writeIORef (naArrays na) newA+    writePrimVar (naCapacity na) newCap++-- | Copy of @a@ with room for @newCap@ nodes; new slots are zero or empty.+growNodeArenaArrays :: IOArr Int -> Int -> Int -> NodeArenaArrays -> IO NodeArenaArrays+growNodeArenaArrays classCounts cap newCap a = do+  let growMemo (WidthMemo tags slots) =+        WidthMemo <$> growPrimArrayCopy tags cap newCap 0 <*> growPrimArrayCopy slots (cap * memoStride) (newCap * memoStride) 0+  cn <- newPrimArray (newCap * nodeClassCount)+  forM_ [0 .. nodeClassCount - 1] $ \c -> do+    k <- readPrimArray classCounts c+    copyMutablePrimArray cn (c * newCap) (naArrClassNodes a) (c * cap) k+  NodeArenaArrays+    <$> growPrimArrayCopy (naArrGeom a) (cap * geomStride) (newCap * geomStride) 0+    <*> growPrimArrayCopy (naArrStyle a) (cap * styleStride) (newCap * styleStride) 0+    <*> growPrimArrayCopy (naArrTags a) (cap * tagStride) (newCap * tagStride) 0+    <*> growPrimArrayCopy (naArrTree a) (cap * treeStride) (newCap * treeStride) 0+    <*> growPrimArrayCopy (naArrStyleIdx a) cap newCap 0+    <*> growBoxedStoreCopy T.empty (naArrTextStore a) cap newCap+    <*> growBoxedStoreCopy [] (naArrOptionsStore a) cap newCap+    <*> growBoxedStoreCopy [] (naArrOptionsLast a) cap newCap+    <*> growPrimArrayCopy (naArrFontColor a) cap newCap 0+    <*> growPrimArrayCopy (naArrScope a) cap newCap 0+    <*> growPrimArrayCopy (naArrImageId a) cap newCap 0+    <*> growPrimArrayCopy (naArrTextHash a) cap newCap 0+    <*> growPrimArrayCopy (naArrOptionsHash a) cap newCap 0+    <*> growPrimArrayCopy (naArrOwnHash a) cap newCap 0+    <*> growPrimArrayCopy (naArrPaintHash a) cap newCap 0+    <*> growPrimArrayCopy (naArrSubHash a) cap newCap 0+    <*> growPrimArrayCopy (naArrMeasured a) (cap * 2) (newCap * 2) 0+    <*> growPrimArrayCopy (naArrOffered a) (cap * 4) (newCap * 4) 0+    <*> growPrimArrayCopy (naArrUnsnapped a) (cap * 4) (newCap * 4) 0+    <*> growPrimArrayCopy (naArrSpans a) cap newCap 0+    <*> pure cn+    <*> growMemo (naArrWrapMemo a)+    <*> growMemo (naArrFitMemo a)++-- | Keep a non-negative parent; otherwise attach to node 0 if it exists, or+-- return -1 for an empty arena. This keeps top-level floating nodes reachable+-- from the page root.+rootAttachParent :: NodeArena -> Int -> IO Int+rootAttachParent na parent+  | parent >= 0 = pure parent+  | otherwise = do+      n <- arenaCount na+      pure (if n > 0 then 0 else -1)++-- | Append a node laid out by the given 'Layout' and link it at the head of+-- its parent's child list. The parent must be -1 or an existing node index.+-- The caller assigns widget identity, text and type-specific style data.+{-# INLINE addNode #-}+addNode :: NodeArena -> NodeType -> Int -> Layout -> IO NodeIdx+addNode na nt parent Layout {..} = do+  idx <- readPrimVar (naCount na)+  cap <- readPrimVar (naCapacity na)+  when (idx + 1 >= cap) $ ensureCapacity na (idx + 1)+  let (wTag0, wVal0) = sizingTag layoutWidth+      (hTag0, hVal0) = sizingTag layoutHeight+      pad = layoutPadding+      -- Scroll containers and grids have their own layout, and paint and hit+      -- tests visit their children in line order.+      !flow+        | not (isContainerNode nt) || isScrollNode nt || layoutGridCols > 0 || layoutGridMinColW > 0 = Line+        | otherwise = layoutFlow+      !lineGap = if layoutLineGap < 0 then layoutGap else layoutLineGap+      -- Floating nodes are placed separately, and a root has no parent to+      -- pin to.+      !pinned = isJust layoutPin && parent >= 0 && not (isFloatingNode nt)+      !(V2 pinX pinY) = fromMaybe (V2 0 0) layoutPin+      !axByte =+        fromIntegral (fromEnum layoutAlignX)+          .|. (if layoutAlignExplicit .&. 1 /= 0 then 0x80 else 0 :: Word8)+      !ayByte =+        fromIntegral (fromEnum layoutAlignY)+          .|. (if layoutAlignExplicit .&. 2 /= 0 then 0x80 else 0 :: Word8)+  a <- arenaArrays na+  -- 'ItemsStretch' promotes an unaligned fit-sized flow child to grow along+  -- its parent's cross axis (width in a column, height in a row or grid row).+  -- Return a plain unboxed Int tag (0 none, 1 stretch W, 2 stretch H) so the+  -- common unstretched path allocates no tuples or boxed Floats.+  !stretch <-+    if parent >= 0+      && not pinned+      && not (isFloatingNode nt)+      && ((wTag0 == SizingFit && axByte == 0) || (hTag0 == SizingFit && ayByte == 0))+      then do+        pItems <- readTagEnum a parent TagItemsAlign+        if pItems == ItemsStretch+          then stretchAxis a parent wTag0 axByte hTag0 ayByte+          else pure 0+      else pure 0+  let !wTag = if stretch == 1 then SizingGrow else wTag0+      !wVal = if stretch == 1 then 1 else wVal0+      !hTag = if stretch == 2 then SizingGrow else hTag0+      !hVal = if stretch == 2 then 1 else hVal0+  -- 'PointerPass' is inherited by all descendants.+  !pointerMode <-+    if parent < 0 || layoutPointer == PointerPass+      then pure layoutPointer+      else do+        p <- readTagEnum a parent TagPointer+        pure $! if p == PointerPass then p else layoutPointer++  setPrimArray (naArrGeom a) (idx * geomStride) geomStride 0++  writeStyle a idx StyleWVal wVal+  writeStyle a idx StyleHVal hVal+  writeStyle a idx StylePadL (padL pad)+  writeStyle a idx StylePadR (padR pad)+  writeStyle a idx StylePadT (padT pad)+  writeStyle a idx StylePadB (padB pad)+  writeStyle a idx StyleGap layoutGap+  writeStyle a idx StyleMinW layoutMinW+  writeStyle a idx StyleMinH layoutMinH+  writeStyle a idx StyleMaxW layoutMaxW+  writeStyle a idx StyleMaxH layoutMaxH+  writeStyle a idx StyleScrollContentW 0+  writeStyle a idx StyleNodeValue 0+  writeStyle a idx StyleGridMinColW layoutGridMinColW+  writeStyle a idx StyleFontSize layoutFontSize+  writeStyle a idx StyleLineGap lineGap+  writeStyle a idx StylePinX pinX+  writeStyle a idx StylePinY pinY+  writeStyle a idx StyleAspect layoutAspect++  writeTagEnum a idx TagNodeType nt+  writeTagEnum a idx TagDirection $ case layoutDirection of+    Row | flow /= Layered -> DirRow+    _ -> DirColumn+  writeTagEnum a idx TagWSizing wTag+  writeTagEnum a idx TagHSizing hTag+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagScrollBarSlot) 0+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagAlignX) axByte+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagAlignY) ayByte+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagIdSuperseded) 0+  writeTagEnum a idx TagFlow flow+  writeTagEnum a idx TagPinned pinned+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagPinnedBelow) 0+  writeTagEnum a idx TagPointer pointerMode+  writeTagEnum a idx TagLineAlign layoutLineAlign+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagScrollerBelow) 0+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagSteadyHeight) 0+  writeTagEnum a idx TagItemsAlign layoutItemsAlign+  writeTagEnum a idx TagJustify layoutJustify+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagHasOptions) 0+  writePrimArray (naArrTags a) (idx * tagStride + fromEnum TagBaselineChild) 0++  writePrimArray (naArrStyleIdx a) idx 0+  writeTree a idx TreeParent parent+  writeTree a idx TreeFirstChild (-1)+  writeTree a idx TreeNextSibling (-1)+  writeTree a idx TreeChildCount 0+  writeTree a idx TreeWidgetId 0+  writeTree a idx TreeTextIdx (-1)+  writeTree a idx TreeGridCols layoutGridCols++  -- The creation inputs from a constant seed, with no position: the node's+  -- paint hash starts here. Its own hash, the layout cache's key, adds its+  -- index and parent.+  let packW :: Word32 -> Word32 -> Word64+      packW hi lo = fromIntegral hi `shiftL` 32 .|. fromIntegral lo+      !enumsWord =+        fromIntegral (fromEnum nt)+          .|. (fromIntegral (fromEnum layoutDirection) `shiftL` 8)+          .|. (fromIntegral (fromEnum wTag) `shiftL` 16)+          .|. (fromIntegral (fromEnum hTag) `shiftL` 24)+          .|. (fromIntegral axByte `shiftL` 32)+          .|. (fromIntegral ayByte `shiftL` 40)+          .|. (fromIntegral (fromEnum layoutItemsAlign) `shiftL` 48)+          .|. (fromIntegral (fromEnum layoutJustify) `shiftL` 56)+      !flagsWord =+        fromIntegral (fromEnum flow)+          .|. (fromIntegral (fromEnum pinned) `shiftL` 8)+          .|. (fromIntegral (fromEnum layoutLineAlign) `shiftL` 16)+      !content =+        let !h1 = mixTagged 0x6E616E6F2D7569 1 enumsWord+            !h2 = mixTagged h1 2 flagsWord+            !h3 = mixTagged h2 3 (packF2 wVal hVal)+            !h4 = mixTagged h3 4 (packF2 (padL pad) (padR pad))+            !h5 = mixTagged h4 5 (packF2 (padT pad) (padB pad))+            !h6 = mixTagged h5 6 (packF2 layoutGap lineGap)+            !h7 = mixTagged h6 7 (packF2 layoutMinW layoutMinH)+            !h8 = mixTagged h7 8 (packF2 layoutMaxW layoutMaxH)+            !h9 = mixTagged h8 9 (packW (fromIntegral layoutGridCols) (castFloatToWord32 layoutGridMinColW))+            !h10 = mixTagged h9 10 (packF2 layoutFontSize layoutAspect)+         in mixTagged h10 11 (packF2 pinX pinY)+      !nodeSig = mixTagged (mixTagged content 0x4958 (fromIntegral idx)) 0x5041 (fromIntegral (parent + 1))+  mixInputSig na 0x4e4f nodeSig+  writePrimArray (naArrOwnHash a) idx nodeSig+  scope <- readPrimVar (naScope na)+  writePrimArray (naArrScope a) idx scope+  -- Bit 1 marks inert (input-only) scopes, which have no visual effect and+  -- must not trigger paint-scope invalidation.+  let !paintScope = scope .&. complement 2+  writePrimArray (naArrPaintHash a) idx (mixTagged content 0x5343 (fromIntegral paintScope))++  -- The font colour is paint state, so the input signature leaves it out.+  case layoutFontColor of+    Nothing -> writePrimArray (naArrFontColor a) idx 0+    Just (Color w) -> do+      writePrimArray (naArrFontColor a) idx (0x100000000 .|. fromIntegral w)+      mixPaintSig na idx 0x4643 (fromIntegral w)+  when (paintScope /= 0) $ do+    sig <- readPrimVar (naScopeSig na)+    writePrimVar (naScopeSig na) $! (sig * 0x100000001b3) `xor` (fromIntegral idx `shiftL` 32 .|. fromIntegral paintScope)++  when (parent >= 0) $ do+    fc <- readTree a parent TreeFirstChild+    writeTree a idx TreeNextSibling fc+    writeTree a parent TreeFirstChild idx+    cc <- readTree a parent TreeChildCount+    writeTree a parent TreeChildCount (cc + 1)+    when pinned $ markAncestorTag a TagPinnedBelow parent+    when (not pinned && not (isFloatingNode nt) && layoutAlignY == AlignBaseline) $+      writeTagEnum a parent TagBaselineChild True+  when (isFloatingNode nt) $ pushClassNode na a FloatingNodes idx+  when (nt == NodePanel || nt == NodeScrollContainer) $ pushClassNode na a BackdropNodes idx+  when (flow == Layered || pinned) $ pushClassNode na a LayeredNodes idx+  when (isWidgetNode nt || isScrollNode nt || pointerMode == PointerBlock) $ do+    pushClassNode na a PointerNodes idx+    when (isScrollNode nt || nt == NodeTextArea || pointerMode == PointerBlock) $+      markAncestorTag a TagScrollerBelow idx+  when (isScrollNode nt || nt == NodeTextArea) $ pushClassNode na a ScrollableNodes idx+  when (nt == NodeTextInput || nt == NodeTextArea) $ pushClassNode na a TextFieldNodes idx+  when (nt == NodeDrawing) $ pushClassNode na a DrawingNodes idx+  writePrimVar (naCount na) (idx + 1)+  pure idx++-- | Cross-axis stretch promotion for a flow child whose parent has+-- 'ItemsStretch': 0 for none, 1 to promote width, 2 to promote height.+{-# NOINLINE stretchAxis #-}+stretchAxis :: NodeArenaArrays -> NodeIdx -> SizingTag -> Word8 -> SizingTag -> Word8 -> IO Int+stretchAxis a parent wTag0 axByte hTag0 ayByte = do+  pFlow <- readTagEnum a parent TagFlow+  if pFlow == Layered+    then pure 0+    else do+      pDir <- readTagEnum a parent TagDirection+      pGridCols <- readTree a parent TreeGridCols+      pMinColW <- readStyle a parent StyleGridMinColW+      let !stretchY = pGridCols > 0 || pMinColW > 0 || pDir == DirRow+      pure $!+        if not stretchY && wTag0 == SizingFit && axByte == 0+          then 1+          else if stretchY && hTag0 == SizingFit && ayByte == 0+            then 2+            else 0++-- | Mark a node and its ancestors with @tag@, stopping at the first one+-- already marked. Top-level so 'addNode' allocates no closure when the+-- branch is not taken.+markAncestorTag :: NodeArenaArrays -> TagCol -> Int -> IO ()+markAncestorTag a tag = go+  where+    go !p = when (p >= 0) $ do+      marked <- readTagEnum a p tag+      unless marked $ writeTagEnum a p tag True >> readTree a p TreeParent >>= go++-- | Append node @idx@ to the list of class @c@. 'addNode' has made room.+{-# INLINE pushClassNode #-}+pushClassNode :: NodeArena -> NodeArenaArrays -> NodeClass -> NodeIdx -> IO ()+pushClassNode na a c idx = do+  let ci = fromEnum c+  k <- readPrimArray (naClassCounts na) ci+  cap <- readPrimVar (naCapacity na)+  writePrimArray (naArrClassNodes a) (ci * cap + k) idx+  writePrimArray (naClassCounts na) ci (k + 1)++-- | 'addNode' as a call instead of inlined, for the view's many call sites.+addNodeFromLayout :: NodeArena -> NodeType -> Int -> Layout -> IO NodeIdx+addNodeFromLayout na nt parent l = addNode na nt parent l++-- | Assign text to a live node and mark its text slot as present. Re-setting+-- the same 'Text' object reuses its cached hash, so a steady frame hashes no+-- text bytes.+{-# INLINE setNodeText #-}+setNodeText :: NodeArena -> NodeIdx -> Text -> IO ()+setNodeText na idx txt = do+  a <- arenaArrays na+  old <- readArray (naArrTextStore a) idx+  let !same = old `ptrEq` txt+  h <- cachedHash (naArrTextHash a) idx same 0x54455854 txt+  unless same $ writeArray (naArrTextStore a) idx txt+  writeTree a idx TreeTextIdx idx+  mixNodeInput na idx 0x5458 h++-- | Set image node @idx@'s look and natural size. The size is a layout+-- input, so it is mixed into the node's hash.+setImageNode :: NodeArena -> NodeIdx -> ImageNode -> IO ()+setImageNode na idx node@ImageNode {inWidth = w, inHeight = h} = do+  k <- readPrimArray (naImageCount na) 0+  arr0 <- readIORef (naImages na)+  let cap = sizeofMutableArray arr0+  arr <-+    if k < cap+      then pure arr0+      else do+        grown <- growBoxedStoreCopy noImageNode arr0 cap (max 16 (2 * cap))+        grown <$ writeIORef (naImages na) grown+  writeArray arr k node+  writePrimArray (naImageCount na) 0 (k + 1)+  a <- arenaArrays na+  writePrimArray (naArrStyleIdx a) idx (fromIntegral (k + 1))+  mixNodeInput na idx 0x494d (packF2 w h)+  mixPaintSig na idx 0x4c4b (lookWord (inLook node))++-- | A hash of everything a look draws with, for 'getPaintSignature'.+lookWord :: ImageLook -> Word64+lookWord look =+  let !h1 =+        mixTagged 0 1 $+          fromIntegral (fromEnum (lookFit look))+            .|. (fromIntegral (fromEnum (lookAlignX look)) `shiftL` 8)+            .|. (fromIntegral (fromEnum (lookAlignY look)) `shiftL` 16)+            .|. maybe 0 (const 0x1000000) crop+      !h2 = mixTagged h1 2 (packF2 (lookOpacity look) (lookScale look))+      !h3 =+        mixTagged h2 3 $ case lookRotation look of+          RotateFloating r -> fromIntegral (castFloatToWord32 r)+          RotateSolid r -> 0x100000000 .|. fromIntegral (castFloatToWord32 r)+      !h4 = mixTagged h3 4 (maybe 0 (\(Rect x y _ _) -> packF2 x y) crop)+      !h5 = mixTagged h4 5 (maybe 0 (\(Rect _ _ w h) -> packF2 w h) crop)+      Color tintWord = lookTint look+   in mixTagged h5 6 (fromIntegral tintWord)+  where+    crop = lookCrop look++{-# INLINE packF2 #-}+packF2 :: Float -> Float -> Word64+packF2 x y = fromIntegral (castFloatToWord32 x) `shiftL` 32 .|. fromIntegral (castFloatToWord32 y)++-- | Set image node @idx@'s image id: the 'NanoUI.ImageId'+-- it draws, or 0 for none. Layout does not read it, so it is paint state+-- ('getPaintSignature').+{-# INLINE setImageId #-}+setImageId :: NodeArena -> NodeIdx -> Int -> IO ()+setImageId na idx tid = do+  a <- arenaArrays na+  writePrimArray (naArrImageId a) idx tid+  mixPaintSig na idx 0x4944 (fromIntegral tid)++-- | Replace a node's choice labels for this frame. Re-setting the same list+-- object reuses its cached hash, like 'setNodeText'.+{-# INLINE setOptions #-}+setOptions :: NodeArena -> NodeIdx -> [Text] -> IO ()+setOptions na idx opts = do+  a <- arenaArrays na+  -- Compared with the list last hashed here, not the slot 'addNode' just+  -- cleared: against that, every list would rehash and an empty one would+  -- take an old list's hash.+  old <- readArray (naArrOptionsLast a) idx+  let !same = old `ptrEq` opts+  h <- cachedHash (naArrOptionsHash a) idx same 0x4f505453 opts+  writeTagEnum a idx TagHasOptions True+  unless same $ do+    writeArray (naArrOptionsStore a) idx opts+    writeArray (naArrOptionsLast a) idx opts+  mixNodeInput na idx 0x4f50 h++-- | The node's value hash from @arr@ when @same@ says the value is the+-- object last hashed there, else a fresh hash of @x@, salted and cached.+{-# INLINE cachedHash #-}+cachedHash :: Hashable a => IOArr Word64 -> NodeIdx -> Bool -> Word64 -> a -> IO Word64+cachedHash arr idx same salt x = do+  c <- readPrimArray arr idx+  if same && c /= 0+    then pure c+    else do+      let !h = fromIntegral (hash x) `xor` salt+      h <$ writePrimArray arr idx h++-- | Assign a node's identity and index nonzero ids for lookup. Assign once per+-- node: this does not remove a mapping previously stored under another id.+-- Lookups of the id now find this node, and an earlier node with the same id+-- is marked superseded ('getIdSuperseded').+{-# INLINE setWidgetId #-}+setWidgetId :: NodeArena -> NodeIdx -> WidgetId -> IO ()+setWidgetId na idx wid = do+  a <- arenaArrays na+  let WidgetId w = wid+  writeTree a idx TreeWidgetId (fromIntegral w)+  mixNodeInput na idx 0x5749 w+  when (hashWidgetId wid /= 0) $ do+    !ep <- readPrimVar (naEpoch na)+    prev <- indexWidgetId na ep w idx+    when (prev >= 0 && prev /= idx) $ writeTagEnum a prev TagIdSuperseded True++-- | Node most recently indexed under this id in the current frame. Returns+-- 'Nothing' for zero, an unknown id, or an entry from an earlier frame.+{-# INLINE lookupNodeByWidgetId #-}+lookupNodeByWidgetId :: NodeArena -> WidgetId -> IO (Maybe NodeIdx)+lookupNodeByWidgetId na (WidgetId key)+  | key == 0 = pure Nothing+  | otherwise = do+      !ep <- readPrimVar (naEpoch na)+      IdIndex slots mask _ <- readIORef (naIndex na)+      probeSlot slots mask ep key (\_ -> pure Nothing) (\_ v -> pure (Just (slotNode v)))++-- | Index node @idx@ under the nonzero id @key@ in epoch @ep@. Returns the+-- node previously indexed under @key@ this epoch, or -1. The insert's probe+-- finds it for free.+{-# INLINE indexWidgetId #-}+indexWidgetId :: NodeArena -> Word32 -> Word64 -> Int -> IO Int+indexWidgetId na ep key idx = do+  ii@(IdIndex slots mask live) <- readIORef (naIndex na)+  let !val = fromIntegral ep `shiftL` 32 .|. (fromIntegral idx .&. 0xFFFFFFFF)+  probeSlot slots mask ep key+    ( \s -> do+        writePrimArray slots (2 * s) key+        writePrimArray slots (2 * s + 1) val+        n <- readPrimArray live 0+        writePrimArray live 0 (n + 1)+        -- Keep the load factor at or below one half so probes stay short.+        when (2 * (n + 1) > mask + 1) $ writeIORef (naIndex na) =<< growIdIndex ep ii+        pure (-1)+    )+    (\s v -> slotNode v <$ writePrimArray slots (2 * s + 1) val)++-- | Double the table, keeping only entries of epoch @ep@.+growIdIndex :: Word32 -> IdIndex -> IO IdIndex+growIdIndex ep (IdIndex slots mask live) = do+  new@(IdIndex slots' mask' live') <- newIdIndex (2 * (mask + 1))+  writePrimArray live' 0 =<< readPrimArray live 0+  forM_ [0 .. mask] $ \s -> do+    v <- readPrimArray slots (2 * s + 1)+    when (v `shiftR` 32 == fromIntegral ep) $ do+      k <- readPrimArray slots (2 * s)+      -- Keys are distinct, so the probe always ends at a free slot.+      probeSlot slots' mask' ep k+        (\t -> writePrimArray slots' (2 * t) k >> writePrimArray slots' (2 * t + 1) v)+        (\_ _ -> pure ())+  pure new++-- | 'lookupNodeByWidgetId' using the id's integer store key.+{-# INLINE lookupNodeByKey #-}+lookupNodeByKey :: NodeArena -> Int -> IO (Maybe NodeIdx)+lookupNodeByKey na key = lookupNodeByWidgetId na (WidgetId (fromIntegral key))++-- | Set the type-specific numeric value paint reads. It is paint state+-- ('getPaintSignature'), not a layout input: values the solver works out go+-- through 'setSolvedValue'.+{-# INLINE setNodeValue #-}+setNodeValue :: NodeArena -> NodeIdx -> Float -> IO ()+setNodeValue na idx v = do+  setSolvedValue na idx v+  mixPaintSig na idx 0x5641 (fromIntegral (castFloatToWord32 v))++-- | Mix extra paint-only state (such as a shader hash and packed uniform hash)+-- into node @idx@'s paint hash and the arena's frame paint signature.+{-# INLINE mixNodePaintHash #-}+mixNodePaintHash :: NodeArena -> NodeIdx -> Word64 -> IO ()+mixNodePaintHash na idx h = mixPaintSig na idx 0x5348 h++-- | Hash over everything the view put in the arena that paint reads: the+-- input signature ('naInputSig'), the node count, the scopes+-- ('getScopeSignature'), and the paint state the input signature leaves+-- out, mixed as it is written: node values ('setNodeValue'), font colours,+-- the style index of boxes, images and drawings, and images' ids and looks.+-- Two frames with the same signature have identical arena paint inputs; the+-- damage pass covers solved layout, widget state in the store, and theme+-- changes.+getPaintSignature :: NodeArena -> IO Word64+getPaintSignature na = do+  input <- getInputSignature na+  count <- arenaCount na+  scope <- getScopeSignature na+  paint <- readPrimArray (naPaintSig na) 0+  pure (mixTagged (mixTagged (mixTagged input 1 (fromIntegral count)) 2 scope) 3 paint)++-- | Compute every node's restore key ('naArrSubHash'). A first pass, parents+-- before children, parks each node's ancestor chain (its ancestors' own+-- hashes) in its slot. A second pass, from the last node down so each child's+-- key is final before its parent reads it, folds the node's own hash and chain+-- with its children's keys. Child positions mix in, so reordering children+-- counts as a change. Run after the view has built and before the solve.+computeSubtreeHashes :: NodeArena -> IO ()+computeSubtreeHashes na = do+  n <- arenaCount na+  a <- arenaArrays na+  let own = naArrOwnHash a+      sub = naArrSubHash a+      chain !i+        | i >= n = pure ()+        | otherwise = do+            p <- readTree a i TreeParent+            anc <-+              if p < 0+                then pure 0+                else mixTagged <$> readPrimArray sub p <*> pure 0x414e <*> readPrimArray own p+            writePrimArray sub i anc+            chain (i + 1)+      fold !i+        | i < 0 = pure ()+        | otherwise = do+            o <- readPrimArray own i+            anc <- readPrimArray sub i+            fc <- readTree a i TreeFirstChild+            (cnt, acc) <- walkKids a sub 0 o fc+            writePrimArray sub i (mixTagged acc cnt (o `xor` anc))+            fold (i - 1)+  chain 0+  fold (n - 1)++-- | Fold a child list (most recently added first) into the parent's subtree+-- hash, each child's position mixed in so reordering counts as a change.+walkKids :: NodeArenaArrays -> IOArr Word64 -> Word64 -> Word64 -> NodeIdx -> IO (Word64, Word64)+walkKids a sub !pos !h !c+  | c < 0 = pure (pos, h)+  | otherwise = do+      sh <- readPrimArray sub c+      nxt <- readTree a c TreeNextSibling+      walkKids a sub (pos + 1) (mixTagged h pos sh) nxt++-- | Store a style code encoded for this node's type. Part of the layout+-- input signature, except on box, image, and drawing nodes: their style code+-- is paint data (a colour, a version), which goes in the paint signature+-- ('getPaintSignature') instead.+{-# INLINE setStyleIdx #-}+setStyleIdx :: NodeArena -> NodeIdx -> Word64 -> IO ()+setStyleIdx na idx v = do+  a <- arenaArrays na+  writePrimArray (naArrStyleIdx a) idx v+  nt <- readTagEnum a idx TagNodeType+  if nt == NodeBox || nt == NodeImage || nt == NodeDrawing || nt == NodeShader+    then mixPaintSig na idx 0x5354 v+    else mixNodeInput na idx 0x5354 v++-- | The snapshot buffers for nesting depth @depth@, with room for at least+-- @needed@ entries. Each depth keeps its buffers across frames, so nothing is+-- allocated in steady state once they are big enough, and nesting depth has+-- no fixed limit.+{-# NOINLINE ensureAxisSnapshot #-}+ensureAxisSnapshot :: NodeArena -> Int -> Int -> IO AxisSnapshot+ensureAxisSnapshot na depth needed = do+  levels0 <- readIORef (naSnapLevels na)+  let !sz = sizeofMutableArray levels0+  levels <-+    if depth < sz+      then pure levels0+      else do+        empty <- newAxisSnapshot 0+        levels <- growBoxedStoreCopy empty levels0 sz (max (depth + 1) (sz * 2))+        levels <$ writeIORef (naSnapLevels na) levels+  s@(AxisSnapshot idxArr _) <- readArray levels depth+  cap <- getSizeofMutablePrimArray idxArr+  if needed <= cap+    then pure s+    else do+      s' <- newAxisSnapshot (max needed (max 64 (cap * 2)))+      s' <$ writeArray levels depth s'++newAxisSnapshot :: Int -> IO AxisSnapshot+newAxisSnapshot cap = AxisSnapshot <$> newPrimArray cap <*> newPrimArray cap++-- | Memoize @compute@ for node @idx@ at width @key@ in one of the arena's+-- per-frame memos. Only float noise (under a thousandth of a pixel) shares+-- an entry: text that fits 144 px exactly wraps at 143.8, so a wider+-- tolerance can hand back a different line count than paint draws.+{-# INLINE memoizeWidth #-}+memoizeWidth :: NodeArena -> WidthMemo -> NodeIdx -> Float -> IO (Float, Float) -> IO (Float, Float)+memoizeWidth na (WidthMemo tags slots) idx key compute = do+  ft <- readPrimVar (naFrameTag na)+  tag <- readPrimArray tags idx+  let !base = idx * memoStride+  hit <-+    if tag /= ft+      then pure False+      else do+        k <- readPrimArray slots base+        pure (abs (k - key) <= 1.0e-3)+  if hit+    then (,) <$> readPrimArray slots (base + 1) <*> readPrimArray slots (base + 2)+    else do+      r@(x, y) <- compute+      writePrimArray tags idx ft+      writePrimArray slots base key+      writePrimArray slots (base + 1) x+      writePrimArray slots (base + 2) y+      pure r++-- | The flex scratch, with room for at least @needed@ entries. Growing it+-- replaces the buffers without copying: a container fills them only after+-- asking for room, and reads its children back from its snapshot once a+-- child may have used them.+{-# INLINE ensureScratchCapacity #-}+ensureScratchCapacity :: NodeArena -> Int -> IO FlexScratch+ensureScratchCapacity na needed = do+  s <- readIORef (naScratch na)+  if needed <= fsCap s then pure s else growScratch na (max needed (fsCap s * 2))++{-# NOINLINE growScratch #-}+growScratch :: NodeArena -> Int -> IO FlexScratch+growScratch na cap = do+  s <- newFlexScratch cap+  s <$ writeIORef (naScratch na) s
+ lib/NanoUI/Internal/Layout/Arena/Cache.hs view
@@ -0,0 +1,196 @@+{-# LANGUAGE StrictData #-}+-- | Whole-layout cache snapshots, subtree spans, and floating-subtree placement cache.+module NanoUI.Internal.Layout.Arena.Cache+  ( LayoutCache (..)+  , CustomMeasureRecord+  , PlacedFloat (..)+  , newLayoutCache+  , captureLayoutCache+  , layoutSigMatches+  , restoreLayoutCache+  , restoreScrollExtents+  , subtreeSpan+  , snapshotPlaced+  , restorePlaced+  ) where++import Control.Monad (foldM, forM_, when)+import Data.IORef (IORef, newIORef, writeIORef)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.Primitive.PrimArray+  ( PrimArray+  , copyMutablePrimArray+  , copyPrimArray+  , newPrimArray+  , readPrimArray+  , sizeofPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Word (Word8, Word32, Word64)+import NanoUI.Internal.Layout.Arena.Query (forClassNodes_)+import NanoUI.Internal.Layout.Arena.Types+import NanoUI.Internal.Types (Rect (..))++-- | Cached layout signature and solved geometry for whole-layout reuse. The+-- backing arrays are reused; only cache misses capture a new solved frame.+data LayoutCache = LayoutCache+  { lcCap :: !Int+  , lcCount :: !Int+  , lcSig :: !Word64+  -- ^ The input signature ('naInputSig') the solve was captured with.+  , lcMeasures :: !(IntMap CustomMeasureRecord)+  -- ^ Per custom-measured node, what the solve's measure recorded.+  -- Checked by the frame runner because a custom measure may read state+  -- outside the arena that is not reflected in the input signature. Empty+  -- when no node uses custom measurement.+  , lcMeasureHooks :: !Word64+  -- ^ A signature of the nodes with a custom measure registered at capture+  -- ('NanoUI.Internal.Context.customMeasureHooks'). Frame checks it is+  -- unchanged, since gaining a hook changes a node's size without touching+  -- the arena.+  , lcSub :: !(IOArr Word64)+  -- ^ The restore keys ('naSubHash') of the captured frame. A node whose+  -- current key matches this was measured the same way last solve, and the+  -- solve restores its measured size instead of measuring again.+  , lcMeasured :: !(IOArr Float)+  -- ^ Per captured node, the width and height its measure took (two floats).+  , lcOffered :: !(IOArr Float)+  -- ^ The captured 'naOffered'.+  , lcUnsnapped :: !(IOArr Float)+  -- ^ The captured 'naUnsnapped'.+  , lcGeom :: !(IOArr Float)+  -- ^ The captured 'naArrGeom'.+  , lcStyle :: !(IOArr Float)+  -- ^ Per captured scroll node, its 'StyleScrollContentW' and 'StyleNodeValue'+  -- (two floats).+  , lcTags :: !(IOArr Word8)+  -- ^ The captured 'naArrTags'. A restore reads only 'TagScrollBarSlot'.+  , lcPlaced :: !(IORef (IntMap PlacedFloat))+  -- ^ Per floating node, what placing it over the captured solve left+  -- ('NanoUI.Internal.Layout.Solve.placeFloatingNodes'). Emptied at capture.+  }++-- | What placing a floating node (modal, window, popup) at a rect left in+-- its subtree: the geometry rows and the extents its scroll containers were+-- raised to. Placing it at the same rect over the same solve leaves the+-- same, so a frame can put this back instead.+data PlacedFloat = PlacedFloat+  { pfRect :: !Rect+  -- ^ The rect placement gave the node.+  , pfGeom :: !(PrimArray Float)+  -- ^ The 'naArrGeom' rows of the subtree, which starts at the node.+  , pfScroll :: ![(NodeIdx, Float, Float)]+  -- ^ Each scroll container's 'StyleScrollContentW' and 'StyleNodeValue'.+  }++-- | A custom measure's (available width, available height, measured width,+-- measured height), as raw float words.+type CustomMeasureRecord = (Word32, Word32, Word32, Word32)++-- | Empty layout cache with at least 16 slots. Capture a solved frame before reuse.+newLayoutCache :: Int -> IO LayoutCache+newLayoutCache cap0 = do+  let !cap = max 16 cap0+  lcSub <- newPrimArray cap+  lcMeasured <- newPrimArray (cap * 2)+  lcOffered <- newPrimArray (cap * 4)+  lcUnsnapped <- newPrimArray (cap * 4)+  lcGeom <- newPrimArray (cap * geomStride)+  lcStyle <- newPrimArray (cap * 2)+  lcTags <- newPrimArray (cap * tagStride)+  lcPlaced <- newIORef IM.empty+  pure (LayoutCache cap 0 0 IM.empty 0 lcSub lcMeasured lcOffered lcUnsnapped lcGeom lcStyle lcTags lcPlaced)++-- | Snapshot the current (post-solve) arena form, constraints and rects.+captureLayoutCache :: NodeArena -> LayoutCache -> IO LayoutCache+captureLayoutCache na lc0 = do+  n <- arenaCount na+  sig <- getInputSignature na+  -- The copies below overwrite everything a capture reads, so a cache too+  -- small for the arena is replaced rather than grown.+  lc <- if n <= lcCap lc0 then pure lc0 else newLayoutCache (max n (lcCap lc0 * 2))+  a <- arenaArrays na+  copyMutablePrimArray (lcGeom lc) 0 (naArrGeom a) 0 (n * geomStride)+  forClassNodes_ na BackdropNodes $ \i -> do+    nt <- readTagEnum a i TagNodeType+    when (isScrollNode nt) $+      copyMutablePrimArray (lcStyle lc) (i * 2) (naArrStyle a) (i * styleStride + fromEnum StyleScrollContentW) 2+  copyMutablePrimArray (lcTags lc) 0 (naArrTags a) 0 (n * tagStride)+  copyMutablePrimArray (lcSub lc) 0 (naArrSubHash a) 0 n+  copyMutablePrimArray (lcMeasured lc) 0 (naArrMeasured a) 0 (n * 2)+  copyMutablePrimArray (lcOffered lc) 0 (naArrOffered a) 0 (n * 4)+  copyMutablePrimArray (lcUnsnapped lc) 0 (naArrUnsnapped a) 0 (n * 4)+  writeIORef (lcPlaced lc) IM.empty+  pure lc {lcCount = n, lcSig = sig}++-- | Whether the frame's layout inputs hash to what the cache captured.+layoutSigMatches :: NodeArena -> LayoutCache -> IO Bool+layoutSigMatches na lc = do+  n <- arenaCount na+  if n <= 0 || n /= lcCount lc+    then pure False+    else (== lcSig lc) <$> getInputSignature na++-- | Restore only solver outputs. Rebuilt paint values/colors must survive a+-- cache hit; copying the entire cached style array would revert them.+restoreLayoutCache :: NodeArena -> LayoutCache -> IO ()+restoreLayoutCache na lc = do+  a <- arenaArrays na+  let !n = lcCount lc+  copyMutablePrimArray (naArrGeom a) 0 (lcGeom lc) 0 (n * geomStride)+  -- Scroll content width, node value (the content height) and scrollbar+  -- slot. Scroll containers are backdrop nodes, so walk that class, not the+  -- whole arena.+  forClassNodes_ na BackdropNodes $ \i -> do+    nt <- readTagEnum a i TagNodeType+    when (isScrollNode nt) $ do+      let !slotOff = i * tagStride + fromEnum TagScrollBarSlot+      restoreScrollExtents a lc i+      readPrimArray (lcTags lc) slotOff >>= writePrimArray (naArrTags a) slotOff++-- | Put back scroll container @i@'s captured content width and node value+-- (the content height), which the position pass raises.+{-# INLINE restoreScrollExtents #-}+restoreScrollExtents :: NodeArenaArrays -> LayoutCache -> NodeIdx -> IO ()+restoreScrollExtents a lc i =+  copyMutablePrimArray (naArrStyle a) (i * styleStride + fromEnum StyleScrollContentW) (lcStyle lc) (i * 2) 2++-- | The number of nodes in @idx@'s subtree when they are the indices from+-- @idx@ on, as a view that adds each node under the open container leaves+-- them, or else 'Nothing'.+subtreeSpan :: NodeArena -> NodeIdx -> IO (Maybe Int)+subtreeSpan na idx = do+  a <- arenaArrays na+  let node (!count, !hi) i = readTree a i TreeFirstChild >>= kids (count + 1, max hi i)+      kids acc c+        | c < 0 = pure acc+        | otherwise = node acc c >>= \acc' -> readTree a c TreeNextSibling >>= kids acc'+  (count, hi) <- node (0 :: Int, idx) idx+  pure (if hi - idx + 1 == count then Just count else Nothing)++-- | Copy what placement left in the @n@ nodes of @idx@'s subtree, which+-- start at @idx@ ('subtreeSpan'), placed at @rect@.+snapshotPlaced :: NodeArena -> NodeIdx -> Int -> Rect -> IO PlacedFloat+snapshotPlaced na idx n rect = do+  a <- arenaArrays na+  geom <- newPrimArray (n * geomStride)+  copyMutablePrimArray geom 0 (naArrGeom a) (idx * geomStride) (n * geomStride)+  let scrollFrom i acc = do+        nt <- readTagEnum a i TagNodeType+        if isScrollNode nt+          then (\cw v -> (i, cw, v) : acc) <$> readStyle a i StyleScrollContentW <*> readStyle a i StyleNodeValue+          else pure acc+  scroll <- foldM (flip scrollFrom) [] [idx + n - 1, idx + n - 2 .. idx]+  PlacedFloat rect <$> unsafeFreezePrimArray geom <*> pure scroll++-- | Put back what 'snapshotPlaced' copied from @idx@'s subtree.+restorePlaced :: NodeArena -> NodeIdx -> PlacedFloat -> IO ()+restorePlaced na idx PlacedFloat {pfGeom, pfScroll} = do+  a <- arenaArrays na+  copyPrimArray (naArrGeom a) (idx * geomStride) pfGeom 0 (sizeofPrimArray pfGeom)+  forM_ pfScroll $ \(i, cw, v) -> do+    writeStyle a i StyleScrollContentW cw+    writeStyle a i StyleNodeValue v+
+ lib/NanoUI/Internal/Layout/Arena/Query.hs view
@@ -0,0 +1,341 @@+-- | Arena traversal, paint-order queries, ancestor walks, and node-class loops.+module NanoUI.Internal.Layout.Arena.Query+  ( topModalNode+  , forFloatingNodes_+  , floatingNodesInPaintOrder+  , forChildNodes_+  , foldFlowChildrenM+  , flowChildrenInOrder+  , flowChildEnds+  , foldPlacedChildrenM+  , forChildrenInPaintOrder_+  , firstChildOnTopJustM+  , drawnOver+  , AdornRows (..)+  , adornRows+  , findNodeRevM+  , findClassNodeM+  , findClassNodeRevM+  , foldClassNodesM+  , classNodes+  , foldClassNodeRevM+  , forClassNodes_+  , walkFloatingAncestors+  , findNodeM+  , foldNodesM+  , firstChildJustM+  , walkAncestors+  ) where++import Control.Monad (when)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Primitive.PrimArray (readPrimArray)+import Data.Primitive.PrimVar (readPrimVar)+import NanoUI.Internal.Layout.Arena.Types+import NanoUI.Internal.Style (AlignX (..), Flow (..))++-- | The topmost (last added) modal node, if any.+{-# INLINE topModalNode #-}+topModalNode :: NodeArena -> IO (Maybe NodeIdx)+topModalNode na = findClassNodeRevM na FloatingNodes (fmap (== NodeModal) . getNodeType na)++-- | Visit the nodes of a floating type (modal, window, popup) in arena+-- order, looking only at the floating nodes.+{-# INLINE forFloatingNodes_ #-}+forFloatingNodes_ :: NodeArena -> NodeType -> (NodeIdx -> IO ()) -> IO ()+forFloatingNodes_ na t f =+  forClassNodes_ na FloatingNodes $ \idx -> getNodeType na idx >>= \nt -> when (nt == t) (f idx)++-- | Floating nodes (windows, then modals, then popups, each kind in arena+-- order): bottom to top in paint order.+floatingNodesInPaintOrder :: NodeArena -> IO [NodeIdx]+floatingNodesInPaintOrder na = do+  tagged <- foldClassNodeRevM na FloatingNodes (\acc idx -> (\nt -> (nt, idx) : acc) <$> getNodeType na idx) []+  pure [idx | nt <- [NodeWindow, NodeModal, NodePopup], (t, idx) <- tagged, t == nt]++++-- | Visit direct children in reverse declaration order, including floating nodes.+{-# INLINE forChildNodes_ #-}+forChildNodes_ :: NodeArena -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()+forChildNodes_ na parentIdx f = do+  fc <- getFirstChild na parentIdx+  let go !ci+        | ci < 0 = pure ()+        | otherwise = do+            f ci+            ns <- getNextSibling na ci+            go ns+  go fc++-- | Fold over a node's children in sibling order, skipping floating+-- (modal, window, popup) and pinned children, neither of which is part of+-- the flow ('foldPlacedChildrenM' includes pinned ones).+{-# INLINE foldFlowChildrenM #-}+foldFlowChildrenM :: NodeArena -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc+foldFlowChildrenM na = foldChildrenInBoxM na True++-- | 'foldFlowChildrenM' including pinned children: every child placed+-- inside the node's box.+{-# INLINE foldPlacedChildrenM #-}+foldPlacedChildrenM :: NodeArena -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc+foldPlacedChildrenM na = foldChildrenInBoxM na False++-- | Fold over the non-floating children, also skipping pinned ones when+-- @skipPinned@ is set.+{-# INLINE foldChildrenInBoxM #-}+foldChildrenInBoxM :: NodeArena -> Bool -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc+foldChildrenInBoxM na skipPinned parentIdx f z = do+  fc <- getFirstChild na parentIdx+  let go !ci !acc+        | ci < 0 = pure acc+        | otherwise = do+            nt <- getNodeType na ci+            ns <- getNextSibling na ci+            pinned <- if skipPinned then isPinnedNode na ci else pure False+            if isFloatingNode nt || pinned+              then go ns acc+              else f acc ci >>= go ns+  go fc z++-- | A node's flow children in the order they were added. Siblings are linked+-- last first, so consing them up as they are visited restores that order.+flowChildrenInOrder :: NodeArena -> NodeIdx -> IO [NodeIdx]+flowChildrenInOrder na parentIdx = foldFlowChildrenM na parentIdx (\acc ci -> pure (ci : acc)) []++-- | First and last non-floating, non-pinned (flow) child of @parentIdx@ in+-- declaration order, or @(-1, -1)@ when the container has no flow children.+-- Sibling links run last to first, so the first flow child visited is the last+-- declared one and the final one visited is the first declared one.+flowChildEnds :: NodeArena -> NodeIdx -> IO (NodeIdx, NodeIdx)+flowChildEnds na parentIdx = do+  (lastC, firstC) <-+    foldFlowChildrenM+      na+      parentIdx+      (\(lc, _) ci -> pure (if lc < 0 then ci else lc, ci))+      (-1, -1)+  pure (firstC, lastC)++-- | Visit a node's children, floating ones included, in paint order: each is+-- drawn over those visited before it. A layered container visits unpinned+-- children in declaration order, so later ones end up on top. Other nodes+-- visit them last to first, so the earlier of two overlapping children is on+-- top. Pinned children come after the rest, in declaration order.+{-# INLINE forChildrenInPaintOrder_ #-}+forChildrenInPaintOrder_ :: NodeArena -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()+forChildrenInPaintOrder_ na parentIdx f = do+  a <- arenaArrays na+  flow <- readTagEnum a parentIdx TagFlow+  pinnedBelow <- readTagEnum a parentIdx TagPinnedBelow+  fc <- readTree a parentIdx TreeFirstChild+  case flow of+    Layered -> visitChildrenLayered a pinnedBelow fc f+    _+      | pinnedBelow -> visitChildrenPinnedLast a fc f+      | otherwise ->+          let go !ci+                | ci < 0 = pure ()+                | otherwise = do+                    f ci+                    ns <- readTree a ci TreeNextSibling+                    go ns+           in go fc++-- | Paint-order visit for a 'Layered' container (declaration order, pinned+-- children last). Kept out of line so the common non-layered path allocates+-- no closures for it.+{-# NOINLINE visitChildrenLayered #-}+visitChildrenLayered :: NodeArenaArrays -> Bool -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()+visitChildrenLayered a pinnedBelow fc f = do+  inOrderIf False fc+  when pinnedBelow (inOrderIf True fc)+  where+    inOrderIf !pinned !ci = when (ci >= 0) $ do+      readTree a ci TreeNextSibling >>= inOrderIf pinned+      p <- readTagEnum a ci TagPinned+      when (p == pinned) (f ci)++-- | Paint-order visit for a non-layered container that has pinned descendants:+-- flow children last-to-first, pinned children in declaration order on top.+{-# NOINLINE visitChildrenPinnedLast #-}+visitChildrenPinnedLast :: NodeArenaArrays -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()+visitChildrenPinnedLast a fc f = go fc+  where+    go !ci = when (ci >= 0) $ do+      ns <- readTree a ci TreeNextSibling+      pinned <- readTagEnum a ci TagPinned+      if pinned then go ns >> f ci else f ci >> go ns++-- | The first 'Just' that @f@ returns over @parentIdx@'s non-floating children+-- in topmost-first order (the reverse of 'forChildrenInPaintOrder_').+{-# INLINE firstChildOnTopJustM #-}+firstChildOnTopJustM :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Maybe a)) -> IO (Maybe a)+firstChildOnTopJustM na parentIdx f = do+  flow <- getFlow na parentIdx+  pinnedBelow <- hasPinnedBelow na parentIdx+  fc <- getFirstChild na parentIdx+  let tryIf want ci = do+        nt <- getNodeType na ci+        p <- isPinnedNode na ci+        if not (isFloatingNode nt) && want p then f ci else pure Nothing+      fwd want !ci+        | ci < 0 = pure Nothing+        | otherwise = tryIf want ci >>= maybe (getNextSibling na ci >>= fwd want) (pure . Just)+      rev want !ci+        | ci < 0 = pure Nothing+        | otherwise = getNextSibling na ci >>= rev want >>= maybe (tryIf want ci) (pure . Just)+  case flow of+    Layered -> (if pinnedBelow then fwd id fc else pure Nothing) >>= maybe (fwd not fc) (pure . Just)+    _+      | pinnedBelow -> fwd id fc >>= maybe (rev not fc) (pure . Just)+      | otherwise -> rev (const True) fc++-- | Whether paint draws node @b@ over the earlier node @a@. At their common+-- ancestor, this checks whether 'forChildrenInPaintOrder_' visits @b@'s+-- branch last. False when @b@ is inside @a@ or they are in different trees.+drawnOver :: NodeArena -> NodeIdx -> NodeIdx -> IO Bool+drawnOver na b a = climb a b (-1) (-1)+  where+    -- Parents have lower indices, so climb from the higher of @x@ and @y@+    -- until they meet, remembering the child each side came from.+    climb !x !y !ca !cb+      | x > y = getParent na x >>= \p -> climb p y x cb+      | x < y = getParent na y >>= \p -> climb x p ca y+      | x < 0 || ca < 0 = pure False+      | otherwise = do+          lastSide <- newIORef ca+          forChildrenInPaintOrder_ na x $ \ci -> when (ci == ca || ci == cb) (writeIORef lastSide ci)+          (== cb) <$> readIORef lastSide++-- | A button's or text field's adornments, the rows it holds as children+-- ("NanoUI.Internal.Widgets.Adornment"): its leading row and its trailing row+-- (-1 for a side without one), each row's width, and the taller row's height.+-- The leading row aligns to the start and the trailing one to the end.+data AdornRows = AdornRows !NodeIdx !Float !NodeIdx !Float !Float++-- | Collect the leading and trailing adornment rows and their widths and shared height.+adornRows :: NodeArena -> NodeIdx -> IO AdornRows+adornRows na idx = do+  a <- arenaArrays na+  let add (AdornRows li lw ti tw rowH) ci = do+        ax <- readAlignX a ci+        cw <- readGeom a ci GeomW+        ch <- readGeom a ci GeomH+        pure $+          if ax == AlignEnd+            then AdornRows li lw ci cw (max rowH ch)+            else AdornRows ci cw ti tw (max rowH ch)+  foldFlowChildrenM na idx add (AdornRows (-1) 0 (-1) 0 0)++-- | Strict fold over the nodes @at 0@ to @at (k - 1)@, or from the last to+-- the first with @rev@.+{-# INLINE foldSeqM #-}+foldSeqM :: Bool -> Int -> (Int -> IO NodeIdx) -> (a -> NodeIdx -> IO a) -> a -> IO a+foldSeqM rev k at f = go (if rev then k - 1 else 0)+  where+    go !i !acc+      | i < 0 || i >= k = pure acc+      | otherwise = at i >>= f acc >>= go (if rev then i - 1 else i + 1)++-- | The first of the nodes @at 0@ to @at (k - 1)@, or the last with @rev@,+-- that satisfies the predicate.+{-# INLINE findSeqM #-}+findSeqM :: Bool -> Int -> (Int -> IO NodeIdx) -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)+findSeqM rev k at p = go (if rev then k - 1 else 0)+  where+    go !i+      | i < 0 || i >= k = pure Nothing+      | otherwise = do+          idx <- at i+          ok <- p idx+          if ok then pure (Just idx) else go (if rev then i - 1 else i + 1)++-- | First node, in arena order, satisfying the predicate.+{-# INLINE findNodeM #-}+findNodeM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)+findNodeM na p = arenaCount na >>= \n -> findSeqM False n pure p++-- | Find the last declared matching node, or 'Nothing'. Stops at the first match+-- while scanning backwards.+{-# INLINE findNodeRevM #-}+findNodeRevM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)+findNodeRevM na p = arenaCount na >>= \n -> findSeqM True n pure p++-- | Left fold over every node in arena order.+{-# INLINE foldNodesM #-}+foldNodesM :: NodeArena -> (a -> NodeIdx -> IO a) -> a -> IO a+foldNodesM na f z = arenaCount na >>= \n -> foldSeqM False n pure f z+++-- | The length of the list of class @c@ in 'naArrClassNodes', and a reader for+-- its @i@th node.+{-# INLINE classNodes #-}+classNodes :: NodeArena -> NodeClass -> IO (Int, Int -> IO NodeIdx)+classNodes na c = do+  let ci = fromEnum c+  arr <- naArrClassNodes <$> arenaArrays na+  cap <- readPrimVar (naCapacity na)+  k <- readPrimArray (naClassCounts na) ci+  -- Forced here: a lazy offset would be a thunk and a box on every walk.+  let !base = ci * cap+  pure (k, \i -> readPrimArray arr (base + i))++-- | 'findNodeM' over the nodes of one class: the first in arena order that+-- satisfies the predicate.+{-# INLINE findClassNodeM #-}+findClassNodeM :: NodeArena -> NodeClass -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)+findClassNodeM na c p = classNodes na c >>= \(k, at) -> findSeqM False k at p++-- | 'findNodeRevM' over the nodes of one class: the last in arena order that+-- satisfies the predicate.+{-# INLINE findClassNodeRevM #-}+findClassNodeRevM :: NodeArena -> NodeClass -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)+findClassNodeRevM na c p = classNodes na c >>= \(k, at) -> findSeqM True k at p++-- | 'foldNodesM' over the nodes of one class, in arena order.+{-# INLINE foldClassNodesM #-}+foldClassNodesM :: NodeArena -> NodeClass -> (a -> NodeIdx -> IO a) -> a -> IO a+foldClassNodesM na c f z = classNodes na c >>= \(k, at) -> foldSeqM False k at f z++-- | 'foldClassNodesM' from last declared to first.+{-# INLINE foldClassNodeRevM #-}+foldClassNodeRevM :: NodeArena -> NodeClass -> (a -> NodeIdx -> IO a) -> a -> IO a+foldClassNodeRevM na c f z = classNodes na c >>= \(k, at) -> foldSeqM True k at f z++-- | Visit the nodes of one class in arena order.+{-# INLINE forClassNodes_ #-}+forClassNodes_ :: NodeArena -> NodeClass -> (NodeIdx -> IO ()) -> IO ()+forClassNodes_ na c f = foldClassNodesM na c (\() idx -> f idx) ()++-- | The first result @step@ finds walking up from @idx@, the node itself+-- first.+{-# INLINE walkAncestors #-}+walkAncestors :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Maybe a)) -> IO (Maybe a)+walkAncestors na idx step = go idx+  where+    go !i+      | i < 0 = pure Nothing+      | otherwise = step i >>= maybe (getParent na i >>= go) (pure . Just)++-- | 'walkAncestors' that offers @step@ only the floating nodes (modal,+-- window, popup), with their type. Most frames have no floating node, and+-- then this skips the walk.+{-# INLINE walkFloatingAncestors #-}+walkFloatingAncestors :: NodeArena -> NodeIdx -> (NodeIdx -> NodeType -> IO (Maybe a)) -> IO (Maybe a)+walkFloatingAncestors na idx step = do+  floating <- floatingNodeCount na+  if floating <= 0+    then pure Nothing+    else walkAncestors na idx $ \i -> do+      nt <- getNodeType na i+      if isFloatingNode nt then step i nt else pure Nothing++-- | First 'Just' result of @f@ over @parentIdx@'s direct children.+{-# INLINE firstChildJustM #-}+firstChildJustM :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Maybe a)) -> IO (Maybe a)+firstChildJustM na parentIdx f = getFirstChild na parentIdx >>= go+  where+    go !ci+      | ci < 0 = pure Nothing+      | otherwise = f ci >>= maybe (getNextSibling na ci >>= go) (pure . Just)
+ lib/NanoUI/Internal/Layout/Arena/Types.hs view
@@ -0,0 +1,1277 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE StrictData #-}+-- | Arena storage types, column descriptors, and typed slot accessors.+module NanoUI.Internal.Layout.Arena.Types+  ( NodeIdx+  , IOArr+  , NodeType (..)+  , NodeArenaArrays (..)+  , isWidgetNode+  , packsNodeFont+  , labelFontShift+  , nodeFontBits+  , hasCenteredLabel+  , isContainerNode+  , isScrollNode+  , isFloatingNode+  , NodeClass (..)+  , nodeClassCount+  , SizingTag (..)+  , DirTag (..)+  , NodeArena (..)+  , WidthMemo (..)+  , memoStride+  , IdIndex (..)+  , newIdIndex+  , probeSlot+  , slotNode+  , FlexScratch (..)+  , AxisSnapshot (..)+  , initialCapacity+  , GeomCol (..)+  , StyleCol (..)+  , TagCol (..)+  , TreeCol (..)+  , geomStride+  , styleStride+  , tagStride+  , treeStride+  , readGeom+  , writeGeom+  , readStyle+  , writeStyle+  , readTagEnum+  , writeTagEnum+  , readTree+  , writeTree+  , newNodeArenaArrays+  , newFlexScratch+  , arenaCount+  , floatingNodeCount+  , layeredNodeCount+  , scrollableNodeCount+  , textFieldNodeCount+  , arenaArrays+  , mixTagged+  , mixInputSig+  , mixPaintSig+  , mixNodeInput+  , getNodePaintHash+  , growPrimArrayCopy+  , growBoxedStoreCopy+  , AxisSizing (..)+  , axisSizing+  , sizingTag+  , readAxisSizing+  , getParent+  , getFirstChild+  , getNextSibling+  , getNodeType+  , getDirection+  , getWidthSizing+  , getHeightSizing+  , readPadding+  , getPadding+  , getScrollContentW+  , setScrollContentW+  , parentIsRow+  , getAlignX+  , readAlignX+  , readAlignY+  , readItemsAlign+  , effectiveAlignX+  , effectiveAlignY+  , getFlow+  , isPinnedNode+  , hasPinnedBelow+  , hasScrollerBelow+  , hasBaselineChild+  , getPointerMode+  , getNodeRect+  , setRect+  , getClipRect+  , getClipBounds+  , setClipRect+  , writeClipRectRaw+  , getText+  , ImageNode (..)+  , noImageNode+  , getImageNode+  , getImageId+  , getOptions+  , getWidgetId+  , getIdSuperseded+  , getNodeValue+  , setSolvedValue+  , getNodeFontSize+  , getNodeFontColor+  , getNodeScope+  , getArenaScope+  , setArenaScope+  , getScopeSignature+  , getInputSignature+  , readStyleIdx+  , getStyleIdx+  ) where++import Control.Monad (mfilter)+import Data.Bits (shiftL, shiftR, xor, (.&.))+import Data.IORef (IORef, readIORef)+import Data.Primitive.Array (MutableArray, copyMutableArray, newArray, readArray)+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , newPrimArray+  , readPrimArray+  , resizeMutablePrimArray+  , setPrimArray+  , writePrimArray+  )+import Data.Primitive.PrimVar (PrimVar, readPrimVar, writePrimVar)+import Data.Primitive.Types (Prim)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word8, Word32, Word64)+import GHC.Exts (RealWorld)+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Image (ImageLook, defaultImageConfig, imageLook)+import NanoUI.Internal.Style+  ( AlignX (..)+  , AlignY (..)+  , Flow (..)+  , ItemsAlign (..)+  , Padding (..)+  , PointerMode (..)+  , Sizing (..)+  )+import NanoUI.Internal.StyleBits (BitField (..))+import qualified NanoUI.Internal.StyleBits as SB+import NanoUI.Internal.Types (Color (..), Rect (..), newZeroedPrimArray, readRectAt, rectNonEmpty, writeRectAt)++-- | A node's position in the arena's arrays. It is valid from the 'addNode'+-- that returned it until the next 'resetNodeArena'. Where an index names an+-- optional node (a parent, a first child, a next sibling), -1 means none.+type NodeIdx = Int++-- | The arena's mutable unboxed arrays.+type IOArr = MutablePrimArray RealWorld++-- | Node kind, which selects how the solver measures the node and how paint+-- draws it. Stored as a 'Word8' ('TagNodeType') through the derived 'Enum'+-- instance, so there can be at most 256 constructors. Several types store+-- type-specific data in the node's style index ('getStyleIdx').+--+-- == Adding a NodeType+--+-- The dispatches that decide per node type list every constructor, so+-- @-Wincomplete-patterns@ (an error under @-Werror@) points at most of+-- the places a new type needs a decision:+--+-- * this module: 'isWidgetNode' and 'isContainerNode'; and, since they+--   compare against named types, 'packsNodeFont', 'hasCenteredLabel',+--   'isScrollNode', 'isFloatingNode' and the 'NodeClass' lists the arena+--   keeps.+-- * "NanoUI.Internal.StyleBits": the fields the type packs into its style+--   index, and its entry in @styleLayouts@.+-- * "NanoUI.Internal.Layout.Solve.Measure": @measureContent@,+--   @recomputeUnsteady@, @markSteadyHeight@ and @childBaseline@; also+--   @measureWidget@ and @measureAdorned@ for a widget.+-- * "NanoUI.Internal.Layout.Solve.Position" and+--   "NanoUI.Internal.Layout.Solve.Flex", where a type is placed apart from+--   its siblings (a separator in a column, a floating node).+-- * "NanoUI.Internal.Frame.Paint" (@lowerNodeVisible@) and, for a widget,+--   "NanoUI.Internal.Frame.Paint.Widgets" (@paintWidget@).+-- * "NanoUI.Internal.Frame.Spans": @collectClippedSpans@ and+--   @computeWidgetTextPlacements@.+-- * "NanoUI.Internal.Frame.Chrome": @displayText@ and+--   @widgetVisualStyleWith@.+-- * "NanoUI.Internal.Frame.Input" (focus kind, hit rect),+--   "NanoUI.Internal.Frame.Cursor" (pointer cursor) and+--   "NanoUI.Internal.Frame.Hit".+-- * "NanoUI.Internal.Damage", which lists the types that repaint from the+--   store and the ones that never need damage of their own.+-- * @NanoUI.Draw.FrameSvg@ in nano-ui-svg, the SVG export of a frame.+data NodeType+  = NodeContainer+  -- ^ A row, column or grid.+  | NodeText+  -- ^ A label. Its style index packs the font variant, weight, slant and+  -- text decoration.+  | NodeSpacer+  -- ^ Empty space.+  | NodeSeparator+  -- ^ A one-pixel rule.+  | NodeButton+  -- ^ A button. Flags in its style index turn it into a close button, a tab,+  -- a table header, a menu-bar title, a menu item, a checkbox or radio option+  -- (its box or ring painted beside its label), or a tree row.+  | NodeSlider+  | NodeTextInput+  -- ^ A single-line text field. Flags in its style index turn it into a search+  -- field, a numeric field, a password field or selectable read-only text.+  | NodeTextArea+  -- ^ A multi-line text field, which scrolls its own content.+  | NodeScrollContainer+  -- ^ A container that scrolls its children. Its style index holds the encoded+  -- scroll configuration.+  | NodeSelect+  -- ^ A select box. Its choices are the node's options ('getOptions').+  | NodeModal+  -- ^ A modal dialog. Floating: see 'isFloatingNode'.+  | NodeImage+  -- ^ An image. Its image id is 'getImageId', and its style index selects+  -- its look ('getImageNode').+  | NodePanel+  -- ^ A container that paints the theme's panel background and border, and+  -- clips its children to the inside of the border.+  | NodeWindow+  -- ^ A window inside the application's window. Floating.+  | NodeBox+  -- ^ A solid rectangle. Its style index is the fill colour's 32-bit word.+  | NodeColorPicker+  -- ^ One part of a colour picker. Its style index says which part.+  | NodePopup+  -- ^ A popup such as a menu or a tooltip. Floating.+  | NodeDrawing+  -- ^ A custom widget or drawing that the application paints. Its registration+  -- holds drawing behavior and keyboard claims.+  | NodeShader+  -- ^ A leaf surface shader node ('NanoUI.shaderBox'). Its registration holds+  -- its packed fragment pass, corner radius, tint, and fallback colour.+  deriving (Eq, Show, Enum, Bounded)++-- | Whether the node is a control the pointer can hover: a button, slider,+-- text field, text area, select, colour picker part or drawing. Hover+-- detection and the layout of widget labels use it. Labels, images, boxes,+-- spacers, separators and containers are not.+isWidgetNode :: NodeType -> Bool+isWidgetNode nt =+  case nt of+    NodeButton -> True+    NodeSlider -> True+    NodeTextInput -> True+    NodeTextArea -> True+    NodeSelect -> True+    NodeColorPicker -> True+    NodeDrawing -> True+    NodeContainer -> False+    NodeText -> False+    NodeSpacer -> False+    NodeSeparator -> False+    NodeScrollContainer -> False+    NodeModal -> False+    NodeImage -> False+    NodePanel -> False+    NodeWindow -> False+    NodeBox -> False+    NodePopup -> False+    NodeShader -> False++-- | Whether the node packs a font into its style index that the solver and+-- @resolveFontFor@ read: a label or a text field. A text area packs one too,+-- read only by its own paint and spans: its face through+-- 'NanoUI.Internal.Frame.TextArea.resolveTextAreaFont', its weight, slant,+-- decoration and tone through 'NanoUI.Internal.Frame.TextInput.pushFieldText'+-- and 'NanoUI.Internal.Frame.TextInput.fieldTextColor'.+-- Every other type keeps its own data there (a colour picker part, a tab's+-- look), so its style must not be read as a font; a button or select keeps+-- its label's font above that data ('nodeFontBits').+{-# INLINE packsNodeFont #-}+packsNodeFont :: NodeType -> Bool+packsNodeFont nt = nt == NodeText || nt == NodeTextInput++-- | Where a button's or select's style index keeps its label's font, packed+-- as a text node packs one: above the 32 bits its own data uses+-- ('SB.labelFont').+{-# INLINE labelFontShift #-}+labelFontShift :: Int+labelFontShift = bfShift SB.labelFont++-- | The font bits of a node's 64-bit style index @si@, in a text node's+-- packing: all of a text node's or text field's, the label font of a button+-- or select ('labelFontShift'), and none for any other type.+{-# INLINE nodeFontBits #-}+nodeFontBits :: NodeType -> Word64 -> Word64+nodeFontBits nt si+  | packsNodeFont nt = si+  | hasCenteredLabel nt = si `shiftR` labelFontShift+  | otherwise = 0++-- | Whether the node paints one line of label text centered vertically in its+-- box: a button or select. The solver takes that line's baseline as the+-- node's baseline when a row aligns its children on their baselines, and+-- "NanoUI.Internal.Frame.Spans" caches where the label goes+-- (@computeWidgetLabel@).+hasCenteredLabel :: NodeType -> Bool+hasCenteredLabel nt = nt == NodeButton || nt == NodeSelect++-- | Whether the node lays out children: a plain container, scroll container,+-- panel, modal, window or popup.+isContainerNode :: NodeType -> Bool+isContainerNode nt =+  case nt of+    NodeContainer -> True+    NodeScrollContainer -> True+    NodeModal -> True+    NodePanel -> True+    NodeWindow -> True+    NodePopup -> True+    NodeText -> False+    NodeSpacer -> False+    NodeSeparator -> False+    NodeButton -> False+    NodeSlider -> False+    NodeTextInput -> False+    NodeTextArea -> False+    NodeSelect -> False+    NodeImage -> False+    NodeBox -> False+    NodeColorPicker -> False+    NodeDrawing -> False+    NodeShader -> False++-- | Whether the node is a 'NodeScrollContainer'. A text area scrolls its own+-- content and does not count.+isScrollNode :: NodeType -> Bool+isScrollNode nt = nt == NodeScrollContainer++-- | Whether the node is a modal, window or popup. The solver leaves a floating+-- node out of its parent's flow and places it after the solve+-- ('NanoUI.Internal.Layout.Solve.placeFloatingNodes'), and paint draws it over+-- the page.+isFloatingNode :: NodeType -> Bool+isFloatingNode nt = nt == NodeModal || nt == NodeWindow || nt == NodePopup++-- | A kind of node the arena lists as the view adds them, so that a pass+-- interested only in that kind visits those nodes and not the whole arena.+-- Each list is in arena order.+data NodeClass+  = PointerNodes+  -- ^ Nodes a pointer hit test may stop at: controls ('isWidgetNode'),+  -- scroll containers ('isScrollNode') and nodes with 'PointerBlock'.+  | DrawingNodes+  -- ^ Widgets the application draws ('NodeDrawing').+  | FloatingNodes+  -- ^ Windows, modals and popups ('isFloatingNode'), so the passes that look+  -- only at floating panels skip the rest of the arena.+  | BackdropNodes+  -- ^ Panels and scroll containers. Each paints a backdrop and clips its+  -- content, so the damage pass tracks them+  -- ('NanoUI.Internal.Damage.updatePrevRects').+  | LayeredNodes+  -- ^ Layered containers and pinned nodes. Only here does paint draw a node+  -- over an earlier sibling ('forChildrenInPaintOrder_'), so only here can+  -- the later of two overlapping widgets get the pointer ('layeredNodeCount').+  | ScrollableNodes+  -- ^ Scroll containers and text areas ('isScrollNode' or 'NodeTextArea'),+  -- so scrollbar hover, wheel ownership, and scroll focus skip other pointer nodes.+  | TextFieldNodes+  -- ^ Single-line text inputs and text areas, so text-field hit tests can+  -- short-circuit when a view contains none.+  deriving (Eq, Enum, Bounded)++-- | The constructor of a 'Sizing' without its number, as the arena stores it+-- in 'TagWSizing' and 'TagHSizing'. The number goes in 'StyleWVal' or+-- 'StyleHVal'.+data SizingTag+  = SizingFixed+  | SizingFit+  | SizingGrow+  | SizingShrink+  | SizingPercent+  deriving (Eq, Show, Enum, Bounded)++-- | A 'Direction' as the arena stores it in 'TagDirection'. On a container+-- it is the axis the children are laid out along. A separator carries its+-- parent's direction, which decides whether the rule is horizontal or+-- vertical. A layered container ('TagFlow') stores 'DirColumn', so code that+-- reads the direction as an axis (a separator, a text wrap) sees a column.+data DirTag = DirRow | DirColumn+  deriving (Eq, Show, Enum, Bounded)++-- | The arena's per-node arrays. The first four are strided: node @idx@ owns+-- the half-open range @idx * stride@ to @(idx + 1) * stride@, and the columns+-- ('GeomCol', 'StyleCol', 'TagCol', 'TreeCol') name the slots of that row.+-- The other arrays hold one element per node. Growing the arena replaces all+-- of them together.+data NodeArenaArrays = NodeArenaArrays+  { naArrGeom :: !(IOArr Float)+  -- ^ Rects, 8 floats per node. See 'GeomCol'.+  , naArrStyle :: !(IOArr Float)+  -- ^ Layout inputs and a few other numbers, 20 floats per node. See+  -- 'StyleCol'.+  , naArrTags :: !(IOArr Word8)+  -- ^ Enum values, 16 bytes per node. See 'TagCol'.+  , naArrTree :: !(IOArr Int)+  -- ^ Tree links and other integers, 7 per node. See 'TreeCol'.+  , naArrStyleIdx :: !(IOArr Word64)+  -- ^ Each node's 64-bit packed style index ('getStyleIdx'). Stored in its own+  -- 'Word64' array so upper bits ('SB.labelFont') are preserved on 32-bit+  -- targets such as @wasm32@.+  , naArrTextStore :: !(MutableArray RealWorld Text)+  -- ^ Each node's text. 'addNode' does not clear a slot, so read it with+  -- 'getText', which checks that the node set a text.+  , naArrOptionsStore :: !(MutableArray RealWorld [Text])+  -- ^ Each node's option list ('getOptions'), empty unless the node set one.+  , naArrOptionsLast :: !(MutableArray RealWorld [Text])+  -- ^ The option list each node last hashed ('setOptions'), which 'addNode'+  -- leaves alone, so the same list next frame reuses its hash.+  , naArrFontColor :: !(IOArr Word64)+  -- ^ Each node's font color: 0 for none, and otherwise the color's 32-bit+  -- word with bit 32 set. Stored as 'Word64' so bit 32 is preserved on 32-bit+  -- targets such as @wasm32@. See 'getNodeFontColor'.+  , naArrScope :: !(IOArr Int)+  -- ^ The scope each node was added under: the theme that a @styled@ or+  -- @disabledWhen@ block around the node selected, whether the node is+  -- disabled, and whether it is inert. Bit 0 is the disabled flag, bit 1 is+  -- the inert flag, and the theme index sits above bit 1 (0 for the context's+  -- theme). See 'NanoUI.Internal.Context.Types.ThemeScopes'.+  , naArrImageId :: !(IOArr Int)+  -- ^ Each image node's image id ('setImageId'). Only image nodes set it.+  , naArrTextHash :: !(IOArr Word64)+  -- ^ Per node, the hash of the text the last 'setNodeText' stored.+  , naArrOptionsHash :: !(IOArr Word64)+  -- ^ Per node, the hash of the option list the last 'setOptions' stored.+  , naArrOwnHash :: !(IOArr Word64)+  -- ^ Per node, the hash of the node's own creation inputs, its index and its+  -- parent's, plus every later input ('mixNodeInput').+  , naArrPaintHash :: !(IOArr Word64)+  -- ^ Per node, a hash of everything the view gave the node that paint reads.+  , naArrSubHash :: !(IOArr Word64)+  -- ^ Per node, the key the solve restores its measurement by.+  , naArrMeasured :: !(IOArr Float)+  -- ^ Per node, the width and height the measure pass took for it (two floats).+  , naArrOffered :: !(IOArr Float)+  -- ^ Per node, the rect the position pass first offered it (four floats).+  , naArrUnsnapped :: !(IOArr Float)+  -- ^ Per node, its rect as the position pass left it, before quantizing (four floats).+  , naArrSpans :: !(IOArr Int)+  -- ^ Per node, one past the last node of its reusable subtree, or -1.+  , naArrClassNodes :: !(IOArr Int)+  -- ^ The node lists of 'NodeClass', each @capacity@ elements long.+  , naArrWrapMemo :: !WidthMemo+  -- ^ For a text node and a wrap width, the width and height of the wrapped text.+  , naArrFitMemo :: !WidthMemo+  -- ^ For a node and the width it is assigned, the height its content needs.+  }++-- | The arena: the node arrays, the number of nodes in use, and the solver's+-- working memory. 'newNodeArena' makes one for a context, and+-- 'resetNodeArena' empties it for each run of the view.+data NodeArena = NodeArena+  { naCount :: {-# UNPACK #-} !(PrimVar RealWorld Int)+  -- ^ Nodes in use. The next node gets this index.+  , naCapacity :: {-# UNPACK #-} !(PrimVar RealWorld Int)+  -- ^ Nodes the arrays have room for.+  , naArrays :: !(IORef NodeArenaArrays)+  -- ^ The current arrays. Read them through 'arenaArrays'.+  , naScratch :: !(IORef FlexScratch)+  -- ^ The solver's buffers for the container it is working on.+  , naSnapLevels :: !(IORef (MutableArray RealWorld AxisSnapshot))+  -- ^ One 'AxisSnapshot' per nesting depth of the position pass, empty+  -- until the pass first reaches that depth. Laying out a child overwrites+  -- 'naScratch', so a container copies its child list here, at its own depth,+  -- before it recurses into its children.+  , naFrameTag :: {-# UNPACK #-} !(PrimVar RealWorld Word32)+  -- ^ The tag that marks the live entries of 'naArrWrapMemo' and 'naArrFitMemo'.+  -- 'resetNodeArena' changes it, which expires every entry at once. It is never 0.+  , naEpoch :: {-# UNPACK #-} !(PrimVar RealWorld Word32)+  -- ^ The tag that marks the live entries of 'naIndex'. 'resetNodeArena'+  -- increments it. It is never 0.+  , naIndex :: !(IORef IdIndex)+  -- ^ Node index by widget id, for 'lookupNodeByWidgetId'.+  , naScope :: {-# UNPACK #-} !(PrimVar RealWorld Int)+  -- ^ The paint scope 'addNode' gives new nodes, encoded as in 'naArrScope'.+  , naScopeSig :: {-# UNPACK #-} !(PrimVar RealWorld Word64)+  -- ^ A hash over the index and scope of every node added under a scope other+  -- than 0 since the reset. See 'getScopeSignature'.+  , naPaintSig :: !(IOArr Word64)+  -- ^ Hash of the paint state the input signature leaves out, mixed as it is+  -- written ('getPaintSignature'). One unboxed slot, like 'naInputSig'.+  , naInputSig :: !(IOArr Word64)+  -- ^ The frame's input signature, which 'layoutSigMatches' compares.+  , naClassCounts :: !(IOArr Int)+  -- ^ Nodes in each list of 'naArrClassNodes', by 'fromEnum' of the class.+  , naImages :: !(IORef (MutableArray RealWorld ImageNode))+  -- ^ Looks of the image nodes that are not plain, in 'setImageNode' order.+  , naImageCount :: !(IOArr Int)+  -- ^ Entries of 'naImages' used this frame, in one slot.+  , naHighWater :: {-# UNPACK #-} !(PrimVar RealWorld Int)+  -- ^ High-water node count whose boxed text/option slots have not been cleared.+  }++-- | An image node's look ('ImageLook') and the image's natural size, used on+-- an axis the layout leaves unsized. A plain image node has no entry: it+-- stretches the image, and an unsized axis takes its minimum or 32. The+-- node's style index is its 'naImages' position plus one, or 0 when plain.+data ImageNode = ImageNode+  { inLook :: !ImageLook+  , inWidth :: {-# UNPACK #-} !Float+  , inHeight :: {-# UNPACK #-} !Float+  }++-- | The solver's buffers for the flow children of one container (its children+-- that are not floating), indexed by the child's position. The solver loads+-- the children, shares the container's spare or missing space among them+-- along its main axis, and reads the result back. One set of buffers serves+-- the whole tree, which is why a container copies what it needs into an+-- 'AxisSnapshot' before it lays out its children. Sizes are in logical pixels.+data FlexScratch = FlexScratch+  { fsCap :: !Int+  -- ^ Children that each array has room for.+  , fsIdx :: !(IOArr Int)+  -- ^ Node index of each child.+  , fsW :: !(IOArr Float)+  -- ^ Width of each child before the sharing: its measured width, or its+  -- percentage of the container's inner width.+  , fsH :: !(IOArr Float)+  -- ^ Height of each child before the sharing.+  , fsOut :: !(IOArr Float)+  -- ^ Size of each child along the main axis after the space is shared out.+  , fsGrow :: !(IOArr Float)+  -- ^ Working space for the sharing: each child's grow factor.+  }++-- | A memo with one entry per node: a width, and two results computed for the+-- node at that width. An entry counts only while its tag equals the arena's+-- 'naFrameTag', so every entry expires at the next 'resetNodeArena'.+-- 'memoizeWidth' reads and writes it.+data WidthMemo = WidthMemo+  { wmTags :: !(IOArr Word32)+  -- ^ Per node, the frame tag its entry was written under. 0 marks an entry+  -- that was never written.+  , wmSlots :: !(IOArr Float)+  -- ^ Per node, @memoStride@ floats: the width, then the two results.+  }++-- | A container's copy of its child indices and main-axis (or grid-row) sizes,+-- taken at the container's nesting depth before recursing into children.+data AxisSnapshot = AxisSnapshot !(IOArr Int) !(IOArr Float)++-- | Nodes a new arena has room for. 'ensureCapacity' doubles the capacity when+-- the view adds more.+initialCapacity :: Int+initialCapacity = 256++-- | The width of a node's row in 'naArrGeom', 'naArrStyle', 'naArrTags' and+-- 'naArrTree'. Each is at least the number of columns of 'GeomCol',+-- 'StyleCol', 'TagCol' and 'TreeCol', and the columns past those are unused.+geomStride, styleStride, tagStride, treeStride :: Int+geomStride = 9+styleStride = 20+tagStride = 19+treeStride = 7++-- | Columns of 'naArrGeom', in logical pixels and window coordinates.+--+-- * 'GeomX', 'GeomY', 'GeomW', 'GeomH': the node's rect. The solver's measure+--   pass stores the measured size in 'GeomW' and 'GeomH' with the origin at 0.+--   Its position pass then writes the placed rect. Last,+--   'NanoUI.Internal.Frame.Scroll.applyScrollOffsets' moves the origin by the offsets+--   of the scroll containers around the node.+-- * 'GeomClipX', 'GeomClipY', 'GeomClipW', 'GeomClipH': the node's clip rect,+--   in window coordinates. See 'getClipRect'.+-- * 'GeomLaidW': the width the node was laid out at, before+--   'NanoUI.Internal.Layout.Solve.snapNode' snapped its edges to the device+--   pixel grid. Text decides where it wraps at this width in layout and in+--   paint, so both break it into the same lines, wherever its edges snap.+data GeomCol+  = GeomX | GeomY | GeomW | GeomH+  | GeomClipX | GeomClipY | GeomClipW | GeomClipH+  | GeomLaidW+  deriving (Enum, Bounded)++-- | Columns of 'naArrStyle': the numbers the node was laid out with, in+-- logical pixels unless stated.+--+-- * 'StyleWVal', 'StyleHVal': the number of the width or height 'Sizing'. It+--   is the size for 'Fixed', the factor for 'Grow' and 'Shrink', the+--   percentage for 'Percent', and 0 for 'Fit'. 'TagWSizing' and 'TagHSizing'+--   say which.+-- * 'StylePadL', 'StylePadR', 'StylePadT', 'StylePadB': the padding inside the+--   left, right, top and bottom edges.+-- * 'StyleGap': the space between neighbouring children.+-- * 'StyleMinW', 'StyleMinH', 'StyleMaxW', 'StyleMaxH': the size limits. A+--   maximum of 1e8 or more means no limit, and the default layout uses 1e9.+-- * 'StyleScrollContentW': the content width of a scroll container that+--   scrolls both ways, which the solver writes ('getScrollContentW').+-- * 'StyleNodeValue': the node value ('getNodeValue').+-- * 'StyleGridMinColW': the least column width of a grid that fits as many+--   columns as it can, or 0.+-- * 'StyleFontSize': the font size, or 0 for the default ('getNodeFontSize').+-- * 'StyleLineGap': the space between a wrapping container's lines.+-- * 'StylePinX', 'StylePinY': a pinned node's offset from its parent's+--   content box.+-- * 'StyleAspect': width over height for a fit height+--   ('NanoUI.aspect'), or 0 for none.+--+-- The layout cache does not compare 'StyleScrollContentW' and+-- 'StyleNodeValue', which are not layout inputs.+data StyleCol+  = StyleWVal | StyleHVal+  | StylePadL | StylePadR | StylePadT | StylePadB+  | StyleGap | StyleMinW | StyleMinH | StyleMaxW | StyleMaxH+  | StyleScrollContentW | StyleNodeValue | StyleGridMinColW | StyleFontSize+  | StyleLineGap | StylePinX | StylePinY | StyleAspect+  deriving (Enum, Bounded)++-- | Columns of 'naArrTags'. Each holds one enum value as a 'Word8', written+-- with 'writeTagEnum'.+--+-- * 'TagNodeType': the 'NodeType'.+-- * 'TagDirection': the 'DirTag'.+-- * 'TagWSizing', 'TagHSizing': the 'SizingTag' of the width and the height.+-- * 'TagScrollBarSlot': a 'NanoUI.Internal.Font.ScrollBarSlot', which says where a+--   scroll container's bar sits. The solver's measure pass writes it, so the+--   input signature leaves it out and the layout cache restores it on a hit.+-- * 'TagAlignX', 'TagAlignY': the 'AlignX' and 'AlignY' in bits 0..6, with bit+--   7 set when the alignment was explicitly requested by a modifier.+-- * 'TagItemsAlign': the container's cross-axis 'ItemsAlign' default.+-- * 'TagIdSuperseded': whether a later node this frame reuses this node's+--   widget id, as a table's scrolling pane reuses its frozen pane's+--   ('setWidgetId', 'getIdSuperseded').+-- * 'TagFlow': the 'Flow'. Always 'Line' for scroll containers, grids and+--   non-containers.+-- * 'TagLineAlign': a wrapping container's+--   'NanoUI.LineAlign'.+-- * 'TagPinned': whether the node is pinned, as a 'Bool'.+-- * 'TagPinnedBelow': whether some descendant is pinned, as a 'Bool', set+--   when that node is added ('hasPinnedBelow'). The solver, paint and hit+--   tests look for pinned children only under such a node.+-- * 'TagPointer': the node's effective 'PointerMode' ('getPointerMode').+-- * 'TagScrollerBelow': whether the node or a descendant is a scroll+--   container, a text area or a 'PointerBlock' node, as a 'Bool', set when+--   that node is added ('hasScrollerBelow'). Wheel routing looks for its+--   target only under such a node.+-- * 'TagSteadyHeight': whether the node's height is the same at every width+--   it can be laid out at, as a 'Bool'. The solver's measure pass writes it+--   ('NanoUI.Internal.Layout.Solve.Measure.markSteadyHeight'); 'False' until+--   then, which only costs a refit.+-- * 'TagHasOptions': whether 'setOptions' populated 'naArrOptionsStore' for+--   this node in the current frame, avoiding an unconditional write barrier on+--   every 'addNode'.+-- * 'TagBaselineChild': whether any direct flow child explicitly requested+--   'AlignBaseline', allowing row measure and positioning to skip baseline+--   scans when 'ItemsAlign' is not 'ItemsBaseline' and no child asks for it.+data TagCol+  = TagNodeType | TagDirection | TagWSizing | TagHSizing+  | TagScrollBarSlot | TagAlignX | TagAlignY | TagIdSuperseded+  | TagFlow | TagPinned | TagPinnedBelow | TagPointer | TagLineAlign+  | TagScrollerBelow | TagSteadyHeight | TagItemsAlign | TagJustify+  | TagHasOptions | TagBaselineChild+  deriving (Enum, Bounded)++-- | Columns of 'naArrTree'. A link that leads nowhere is -1.+--+-- * 'TreeParent': the parent's index.+-- * 'TreeFirstChild': the child that was added last. 'addNode' puts every new+--   child at the head of its parent's list.+-- * 'TreeNextSibling': the sibling that was added before this node. Following+--   these links therefore visits a node's children from the last to the first.+-- * 'TreeChildCount': the number of children, floating ones included.+-- * 'TreeWidgetId': the 'WidgetId' converted to an 'Int', or 0 for none.+-- * 'TreeTextIdx': the node's slot in 'naArrTextStore', which is its own+--   index, or -1 when the node has no text.+-- * 'TreeGridCols': the column count of a grid, or 0.+data TreeCol+  = TreeParent | TreeFirstChild | TreeNextSibling | TreeChildCount+  | TreeWidgetId | TreeTextIdx | TreeGridCols+  deriving (Enum, Bounded)++-- | Read geometry column @col@ of node @idx@. Like the other raw accessors+-- below, it takes the arrays so that a loop can fetch them once with+-- 'arenaArrays', and it does not check that @idx@ is below 'arenaCount'.+{-# INLINE readGeom #-}+readGeom :: NodeArenaArrays -> NodeIdx -> GeomCol -> IO Float+readGeom a idx col = readPrimArray (naArrGeom a) (idx * geomStride + fromEnum col)++-- | Write geometry column @col@ of node @idx@.+{-# INLINE writeGeom #-}+writeGeom :: NodeArenaArrays -> NodeIdx -> GeomCol -> Float -> IO ()+writeGeom a idx col = writePrimArray (naArrGeom a) (idx * geomStride + fromEnum col)++-- | Read style column @col@ of node @idx@.+{-# INLINE readStyle #-}+readStyle :: NodeArenaArrays -> NodeIdx -> StyleCol -> IO Float+readStyle a idx col = readPrimArray (naArrStyle a) (idx * styleStride + fromEnum col)++-- | Write style column @col@ of node @idx@.+{-# INLINE writeStyle #-}+writeStyle :: NodeArenaArrays -> NodeIdx -> StyleCol -> Float -> IO ()+writeStyle a idx col = writePrimArray (naArrStyle a) (idx * styleStride + fromEnum col)++-- | Read tag column @col@ of node @idx@ and decode it with 'toEnum'. The+-- caller picks the result type, which must be the type the column was written+-- with: 'NodeType' for 'TagNodeType', 'DirTag' for 'TagDirection', and so on.+{-# INLINE readTagEnum #-}+readTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> TagCol -> IO e+readTagEnum a idx col = do+  t <- readPrimArray (naArrTags a) (idx * tagStride + fromEnum col)+  pure $! toEnum (fromIntegral t)++-- | Write an enum value as one byte. Its 'fromEnum' value must be in 0-255+-- and must use the type expected by the column.+{-# INLINE writeTagEnum #-}+writeTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> TagCol -> e -> IO ()+writeTagEnum a idx col v = writePrimArray (naArrTags a) (idx * tagStride + fromEnum col) (fromIntegral (fromEnum v))++-- | Read tree column @col@ of node @idx@.+{-# INLINE readTree #-}+readTree :: NodeArenaArrays -> NodeIdx -> TreeCol -> IO Int+readTree a idx col = readPrimArray (naArrTree a) (idx * treeStride + fromEnum col)++-- | Write tree column @col@ of node @idx@. Writing a link column by hand can+-- leave the child lists and the child counts inconsistent.+{-# INLINE writeTree #-}+writeTree :: NodeArenaArrays -> NodeIdx -> TreeCol -> Int -> IO ()+writeTree a idx col = writePrimArray (naArrTree a) (idx * treeStride + fromEnum col)++-- | Arrays with room for @cap@ nodes. The primitive arrays start+-- uninitialised: 'addNode' fills in a node's elements when it adds the node.+newNodeArenaArrays :: Int -> IO NodeArenaArrays+newNodeArenaArrays cap = do+  naArrGeom <- newPrimArray (cap * geomStride)+  naArrStyle <- newPrimArray (cap * styleStride)+  naArrTags <- newPrimArray (cap * tagStride)+  naArrTree <- newPrimArray (cap * treeStride)+  naArrStyleIdx <- newPrimArray cap+  naArrTextStore <- newArray cap T.empty+  naArrOptionsStore <- newArray cap []+  naArrOptionsLast <- newArray cap []+  naArrFontColor <- newPrimArray cap+  naArrScope <- newPrimArray cap+  naArrImageId <- newPrimArray cap+  naArrTextHash <- newZeroedPrimArray cap+  naArrOptionsHash <- newZeroedPrimArray cap+  naArrOwnHash <- newPrimArray cap+  naArrPaintHash <- newPrimArray cap+  naArrSubHash <- newPrimArray cap+  naArrMeasured <- newPrimArray (cap * 2)+  naArrOffered <- newPrimArray (cap * 4)+  naArrUnsnapped <- newPrimArray (cap * 4)+  naArrSpans <- newPrimArray cap+  naArrClassNodes <- newPrimArray (cap * nodeClassCount)+  naArrWrapMemo <- newWidthMemo cap+  naArrFitMemo <- newWidthMemo cap+  pure NodeArenaArrays {..}++-- | Uninitialised solver buffers with room for @fsCap@ children.+newFlexScratch :: Int -> IO FlexScratch+newFlexScratch fsCap = do+  fsIdx <- newPrimArray fsCap+  fsW <- newPrimArray fsCap+  fsH <- newPrimArray fsCap+  fsOut <- newPrimArray fsCap+  fsGrow <- newPrimArray fsCap+  pure FlexScratch {..}++-- | Floats per node in 'wmSlots': the width and the two results.+memoStride :: Int+memoStride = 3++-- | An empty memo for @cap@ nodes. Every tag starts at 0 and 'naFrameTag' is+-- never 0, so a lookup cannot hit an entry that was never written.+newWidthMemo :: Int -> IO WidthMemo+newWidthMemo cap = do+  wmTags <- newZeroedPrimArray cap+  wmSlots <- newPrimArray (cap * memoStride)+  pure WidthMemo {..}+++-- | Number of entries in 'NodeClass'.+nodeClassCount :: Int+nodeClassCount = fromEnum (maxBound :: NodeClass) + 1++-- | Fold a tagged value into a running hash. Tags separate the fields so a+-- value moving between fields of one node changes the hash.+{-# INLINE mixTagged #-}+mixTagged :: Word64 -> Word64 -> Word64 -> Word64+mixTagged acc tag v = (acc * 0x9E3779B97F4A7C15) `xor` (tag * 0x100000001b3 `xor` v)++-- | Fold one input's tag and value into 'naInputSig'.+{-# INLINE mixInputSig #-}+mixInputSig :: NodeArena -> Word64 -> Word64 -> IO ()+mixInputSig na tag v = do+  sig <- readPrimArray (naInputSig na) 0+  writePrimArray (naInputSig na) 0 (mixTagged sig tag v)++-- | Fold node @idx@'s paint state under @tag@ into 'naPaintSig' and the+-- node's 'naPaintHash'. The index goes into the frame's signature with the+-- tag, so the same value on another node mixes differently.+{-# INLINE mixPaintSig #-}+mixPaintSig :: NodeArena -> NodeIdx -> Word64 -> Word64 -> IO ()+mixPaintSig na idx tag v = do+  sig <- readPrimArray (naPaintSig na) 0+  writePrimArray (naPaintSig na) 0 (mixTagged sig (tag `xor` (fromIntegral idx `shiftL` 16)) v)+  mixNodePaint na idx tag v++-- | Fold a post-creation input change into the node's own hash, its paint+-- hash and the frame's input signature. The subtree hash a later solve+-- compares against is built from the own hashes, so a change must reach+-- both.+{-# INLINE mixNodeInput #-}+mixNodeInput :: NodeArena -> NodeIdx -> Word64 -> Word64 -> IO ()+mixNodeInput na idx tag v = do+  a <- arenaArrays na+  o <- readPrimArray (naArrOwnHash a) idx+  writePrimArray (naArrOwnHash a) idx (mixTagged o tag v)+  p <- readPrimArray (naArrPaintHash a) idx+  writePrimArray (naArrPaintHash a) idx (mixTagged p tag v)+  mixInputSig na tag v++-- | Fold @v@ under @tag@ into node @idx@'s 'naArrPaintHash'.+{-# INLINE mixNodePaint #-}+mixNodePaint :: NodeArena -> NodeIdx -> Word64 -> Word64 -> IO ()+mixNodePaint na idx tag v = do+  ph <- naArrPaintHash <$> arenaArrays na+  p <- readPrimArray ph idx+  writePrimArray ph idx (mixTagged p tag v)++-- | Node @idx@'s 'naArrPaintHash'.+{-# INLINE getNodePaintHash #-}+getNodePaintHash :: NodeArena -> NodeIdx -> IO Word64+getNodePaintHash na idx = arenaArrays na >>= \a -> readPrimArray (naArrPaintHash a) idx++-- | Number of modal, window, and popup nodes added since the last reset.+{-# INLINE floatingNodeCount #-}+floatingNodeCount :: NodeArena -> IO Int+floatingNodeCount na = readPrimArray (naClassCounts na) (fromEnum FloatingNodes)++-- | Number of layered containers and pinned nodes added since the last reset+-- ('LayeredNodes'). While it is 0, the earlier of two overlapping nodes is+-- drawn on top.+{-# INLINE layeredNodeCount #-}+layeredNodeCount :: NodeArena -> IO Int+layeredNodeCount na = readPrimArray (naClassCounts na) (fromEnum LayeredNodes)++-- | Number of scroll containers and text areas added since the last reset.+{-# INLINE scrollableNodeCount #-}+scrollableNodeCount :: NodeArena -> IO Int+scrollableNodeCount na = readPrimArray (naClassCounts na) (fromEnum ScrollableNodes)++-- | Number of single-line text inputs and text areas added since the last reset.+{-# INLINE textFieldNodeCount #-}+textFieldNodeCount :: NodeArena -> IO Int+textFieldNodeCount na = readPrimArray (naClassCounts na) (fromEnum TextFieldNodes)++-- | Live node count. Valid indices are 0 through count minus one.+{-# INLINE arenaCount #-}+arenaCount :: NodeArena -> IO Int+arenaCount na = readPrimVar (naCount na)++-- | Current backing arrays. Do not retain them across arena growth or reset.+{-# INLINE arenaArrays #-}+arenaArrays :: NodeArena -> IO NodeArenaArrays+arenaArrays na = readIORef (naArrays na)++-- | Resize a mutable primitive array to @newCap@, filling slots @[cap .. newCap - 1]@ with @defVal@.+{-# NOINLINE growPrimArrayCopy #-}+growPrimArrayCopy :: Prim a => IOArr a -> Int -> Int -> a -> IO (IOArr a)+growPrimArrayCopy oldArr cap newCap defVal = do+  newArr <- resizeMutablePrimArray oldArr newCap+  setPrimArray newArr cap (newCap - cap) defVal+  pure newArr++-- | Allocate a new boxed array of size @newCap@ and copy @oldCap@ entries into it.+{-# NOINLINE growBoxedStoreCopy #-}+growBoxedStoreCopy :: a -> MutableArray RealWorld a -> Int -> Int -> IO (MutableArray RealWorld a)+growBoxedStoreCopy emptyVal arr oldCap newCap = do+  newArr <- newArray newCap emptyVal+  copyMutableArray newArr 0 arr 0 oldCap+  pure newArr++-- | Rebuild an axis's 'Sizing' from its stored tag and value.+axisSizing :: AxisSizing -> Sizing+axisSizing (AxisSizing tag val _ _) = case tag of+  SizingFixed -> Fixed val+  SizingFit -> Fit+  SizingGrow -> Grow val+  SizingShrink -> Shrink val+  SizingPercent -> Percent val++-- | Decompose a 'Sizing' into its arena tag and scalar value.+{-# INLINE sizingTag #-}+sizingTag :: Sizing -> (SizingTag, Float)+sizingTag (Fixed v) = (SizingFixed, v)+sizingTag Fit = (SizingFit, 0)+sizingTag (Grow g) = (SizingGrow, g)+sizingTag (Shrink s) = (SizingShrink, s)+sizingTag (Percent p) = (SizingPercent, p)++-- | Parent index, or -1 for a root.+{-# INLINE getParent #-}+getParent :: NodeArena -> NodeIdx -> IO NodeIdx+getParent na idx = arenaArrays na >>= \a -> readTree a idx TreeParent++-- | Most recently added direct child, or -1 when there are none.+{-# INLINE getFirstChild #-}+getFirstChild :: NodeArena -> NodeIdx -> IO NodeIdx+getFirstChild na idx = arenaArrays na >>= \a -> readTree a idx TreeFirstChild++-- | Next sibling in reverse declaration order, or -1 at the end.+{-# INLINE getNextSibling #-}+getNextSibling :: NodeArena -> NodeIdx -> IO NodeIdx+getNextSibling na idx = arenaArrays na >>= \a -> readTree a idx TreeNextSibling++-- | Node kind assigned at insertion, which selects layout and paint behaviour.+{-# INLINE getNodeType #-}+getNodeType :: NodeArena -> NodeIdx -> IO NodeType+getNodeType na idx = arenaArrays na >>= \a -> readTagEnum a idx TagNodeType++-- | Main layout axis stored on the node.+{-# INLINE getDirection #-}+getDirection :: NodeArena -> NodeIdx -> IO DirTag+getDirection na idx = arenaArrays na >>= \a -> readTagEnum a idx TagDirection++-- | One axis of a node's layout constraints: the sizing mode, its number (see+-- 'StyleWVal' for units), and the minimum and maximum size in logical pixels.+data AxisSizing = AxisSizing+  { axTag :: !SizingTag+  , axVal :: !Float+  , axMin :: !Float+  , axMax :: !Float+  }++-- | The width's 'AxisSizing' with @horizontal@, else the height's.+{-# INLINE readAxisSizing #-}+readAxisSizing :: NodeArenaArrays -> NodeIdx -> Bool -> IO AxisSizing+readAxisSizing a idx horizontal = do+  AxisSizing+    <$> readTagEnum a idx (if horizontal then TagWSizing else TagHSizing)+    <*> readStyle a idx (if horizontal then StyleWVal else StyleHVal)+    <*> readStyle a idx (if horizontal then StyleMinW else StyleMinH)+    <*> readStyle a idx (if horizontal then StyleMaxW else StyleMaxH)++-- | The width's 'AxisSizing'.+{-# INLINE getWidthSizing #-}+getWidthSizing :: NodeArena -> NodeIdx -> IO AxisSizing+getWidthSizing na idx = arenaArrays na >>= \a -> readAxisSizing a idx True++-- | The height's 'AxisSizing'.+{-# INLINE getHeightSizing #-}+getHeightSizing :: NodeArena -> NodeIdx -> IO AxisSizing+getHeightSizing na idx = arenaArrays na >>= \a -> readAxisSizing a idx False++-- | Read padding insets from already-fetched arena arrays.+{-# INLINE readPadding #-}+readPadding :: NodeArenaArrays -> NodeIdx -> IO Padding+readPadding a idx =+  Padding <$> readStyle a idx StylePadL <*> readStyle a idx StylePadR <*> readStyle a idx StylePadT <*> readStyle a idx StylePadB++-- | Insets in logical pixels, ordered left, right, top, bottom.+{-# INLINE getPadding #-}+getPadding :: NodeArena -> NodeIdx -> IO Padding+getPadding na idx = arenaArrays na >>= \a -> readPadding a idx++-- | Solved horizontal content extent of a two-axis scroller, in logical pixels.+{-# INLINE getScrollContentW #-}+getScrollContentW :: NodeArena -> NodeIdx -> IO Float+getScrollContentW na idx = arenaArrays na >>= \a -> readStyle a idx StyleScrollContentW++-- | Store the solver's horizontal content extent for a scroller.+{-# INLINE setScrollContentW #-}+setScrollContentW :: NodeArena -> NodeIdx -> Float -> IO ()+setScrollContentW na idx v = arenaArrays na >>= \a -> writeStyle a idx StyleScrollContentW v++-- | Whether the parent has row direction. A root returns 'False'.+{-# INLINE parentIsRow #-}+parentIsRow :: NodeArena -> NodeIdx -> IO Bool+parentIsRow na idx = do+  p <- getParent na idx+  if p < 0 then pure False else (== DirRow) <$> getDirection na p++{-# INLINE readRawAlign #-}+readRawAlign :: NodeArenaArrays -> NodeIdx -> TagCol -> IO Word8+readRawAlign a idx col = readPrimArray (naArrTags a) (idx * tagStride + fromEnum col)++{-# INLINE decodeAlign #-}+decodeAlign :: Enum e => Word8 -> e+decodeAlign raw = toEnum (fromIntegral (raw .&. 0x7F))++-- | Read a node's own horizontal alignment, masking off the explicit bit.+{-# INLINE readAlignX #-}+readAlignX :: NodeArenaArrays -> NodeIdx -> IO AlignX+readAlignX a idx = decodeAlign <$> readRawAlign a idx TagAlignX++-- | Read a node's own vertical alignment, masking off the explicit bit.+{-# INLINE readAlignY #-}+readAlignY :: NodeArenaArrays -> NodeIdx -> IO AlignY+readAlignY a idx = decodeAlign <$> readRawAlign a idx TagAlignY++-- | Horizontal alignment requested by the node.+{-# INLINE getAlignX #-}+getAlignX :: NodeArena -> NodeIdx -> IO AlignX+getAlignX na idx = arenaArrays na >>= \a -> readAlignX a idx++-- | Read a container's cross-axis 'ItemsAlign' default.+{-# INLINE readItemsAlign #-}+readItemsAlign :: NodeArenaArrays -> NodeIdx -> IO ItemsAlign+readItemsAlign a idx = readTagEnum a idx TagItemsAlign++-- | Effective horizontal alignment of child @idx@ inside a column with+-- cross-axis default @pItems@. An explicit or non-default child alignment+-- overrides @pItems@.+{-# INLINE effectiveAlignX #-}+effectiveAlignX :: NodeArenaArrays -> ItemsAlign -> NodeIdx -> IO AlignX+effectiveAlignX a pItems idx = do+  raw <- readRawAlign a idx TagAlignX+  pure $! if pItems == ItemsStart || raw /= 0+    then decodeAlign raw+    else case pItems of+      ItemsCenter -> AlignCenter+      ItemsEnd -> AlignEnd+      _ -> AlignStart++-- | Effective vertical alignment of child @idx@ inside a row or grid with+-- cross-axis default @pItems@. An explicit or non-default child alignment+-- overrides @pItems@.+{-# INLINE effectiveAlignY #-}+effectiveAlignY :: NodeArenaArrays -> ItemsAlign -> NodeIdx -> IO AlignY+effectiveAlignY a pItems idx = do+  raw <- readRawAlign a idx TagAlignY+  pure $! if pItems == ItemsStart || raw /= 0+    then decodeAlign raw+    else case pItems of+      ItemsCenter -> AlignMiddle+      ItemsEnd -> AlignBottom+      ItemsBaseline -> AlignBaseline+      _ -> AlignTop++-- | How the node lays out its flow children.+{-# INLINE getFlow #-}+getFlow :: NodeArena -> NodeIdx -> IO Flow+getFlow na idx = arenaArrays na >>= \a -> readTagEnum a idx TagFlow++-- | Whether the node is pinned: out of its parent's flow, at an offset from+-- the parent's content box ('StylePinX', 'StylePinY').+{-# INLINE isPinnedNode #-}+isPinnedNode :: NodeArena -> NodeIdx -> IO Bool+isPinnedNode na idx = arenaArrays na >>= \a -> readTagEnum a idx TagPinned++-- | Whether any descendant is pinned. A pinned node can sit outside its+-- parent, so paint searches for it even under a container it would skip as+-- out of view.+{-# INLINE hasPinnedBelow #-}+hasPinnedBelow :: NodeArena -> NodeIdx -> IO Bool+hasPinnedBelow na idx = arenaArrays na >>= \a -> readTagEnum a idx TagPinnedBelow++-- | Whether the node or a descendant is a scroll container, a text area or+-- a 'PointerBlock' node: whether its subtree can take or block the wheel.+{-# INLINE hasScrollerBelow #-}+hasScrollerBelow :: NodeArena -> NodeIdx -> IO Bool+hasScrollerBelow na idx = arenaArrays na >>= \a -> readTagEnum a idx TagScrollerBelow++-- | Whether any direct flow child of @idx@ requested 'AlignBaseline'.+{-# INLINE hasBaselineChild #-}+hasBaselineChild :: NodeArenaArrays -> NodeIdx -> IO Bool+hasBaselineChild a idx = readTagEnum a idx TagBaselineChild++-- | The node's own 'PointerMode', or 'PointerPass' when an ancestor passes+-- the pointer.+{-# INLINE getPointerMode #-}+getPointerMode :: NodeArena -> NodeIdx -> IO PointerMode+getPointerMode na idx = arenaArrays na >>= \a -> readTagEnum a idx TagPointer++-- | Current x, y, width, height in logical pixels. After scroll offsets are+-- applied, the origin is in window coordinates; before layout it is unset.+{-# INLINE getNodeRect #-}+getNodeRect :: NodeArena -> NodeIdx -> IO Rect+getNodeRect na idx = arenaArrays na >>= \a -> readRectAt (naArrGeom a) (idx * geomStride)++-- | Write x, y, width and height. The clip ('setClipRect') is left alone.+{-# INLINE setRect #-}+setRect :: NodeArena -> NodeIdx -> Float -> Float -> Float -> Float -> IO ()+setRect na idx x y w h = arenaArrays na >>= \a -> writeRectAt (naArrGeom a) (idx * geomStride) x y w h++-- | Positive-area clip in logical window coordinates. 'Nothing' means the+-- stored clip is empty or unset; 'getClipBounds' tells them apart.+{-# INLINE getClipRect #-}+getClipRect :: NodeArena -> NodeIdx -> IO (Maybe Rect)+getClipRect na idx = mfilter rectNonEmpty <$> getClipBounds na idx++-- | Store a clip in logical window coordinates into already-fetched arrays+-- without boxing a 'Rect'.+{-# INLINE writeClipRectRaw #-}+writeClipRectRaw :: NodeArenaArrays -> NodeIdx -> Float -> Float -> Float -> Float -> IO ()+writeClipRectRaw a idx x y w h = do+  let !empty = not (w > 0 && h > 0)+  writeRectAt (naArrGeom a) (idx * geomStride + fromEnum GeomClipX) x y (if empty then -1 else w) (if empty then -1 else h)++-- | Store a clip in logical window coordinates. A clip without area is+-- stored as empty, which differs from the unset clip 'addNode' leaves.+-- 'getClipRect' reads both as 'Nothing'; 'getClipBounds' does not.+{-# INLINE setClipRect #-}+setClipRect :: NodeArena -> NodeIdx -> Rect -> IO ()+setClipRect na idx (Rect x y w h) =+  arenaArrays na >>= \a -> writeClipRectRaw a idx x y w h++-- | The stored clip in logical window coordinates. An empty clip reads as a+-- zero-size rect. 'Nothing' means unset, as before+-- 'NanoUI.Internal.Frame.Scroll.applyScrollOffsets' runs in a frame.+{-# INLINE getClipBounds #-}+getClipBounds :: NodeArena -> NodeIdx -> IO (Maybe Rect)+getClipBounds na idx = do+  a <- arenaArrays na+  Rect x y w h <- readRectAt (naArrGeom a) (idx * geomStride + fromEnum GeomClipX)+  pure $+    if w > 0 && h > 0+      then Just (Rect x y w h)+      else if w < 0 then Just (Rect x y 0 0) else Nothing+++-- | Node text, or empty text when no text was assigned this frame.+{-# INLINE getText #-}+getText :: NodeArena -> NodeIdx -> IO Text+getText na idx = do+  a <- arenaArrays na+  ti <- readTree a idx TreeTextIdx+  if ti < 0+    then pure T.empty+    else readArray (naArrTextStore a) ti++-- | Image node @idx@'s look and natural size, or 'Nothing' for a plain+-- image. Only valid on a 'NodeImage'; other nodes use the style index+-- differently.+{-# INLINE getImageNode #-}+getImageNode :: NodeArena -> NodeIdx -> IO (Maybe ImageNode)+getImageNode na idx = do+  si <- arenaArrays na >>= \a -> readPrimArray (naArrStyleIdx a) idx+  if si == 0 then pure Nothing else Just <$> (readIORef (naImages na) >>= \arr -> readArray arr (fromIntegral si - 1))++-- | Image node @idx@'s image id ('setImageId'). Only valid on a 'NodeImage'.+{-# INLINE getImageId #-}+getImageId :: NodeArena -> NodeIdx -> IO Int+getImageId na idx = arenaArrays na >>= \a -> readPrimArray (naArrImageId a) idx++-- | Filler for unused slots of 'naImages'.+noImageNode :: ImageNode+noImageNode = ImageNode (imageLook defaultImageConfig (Color 0xFFFFFFFF)) 0 0++-- | Choices stored on a select node, or an empty list when none were assigned.+{-# INLINE getOptions #-}+getOptions :: NodeArena -> NodeIdx -> IO [Text]+getOptions na idx = do+  a <- arenaArrays na+  has <- readTagEnum a idx TagHasOptions+  if has then readArray (naArrOptionsStore a) idx else pure []++-- | Identity assigned to the node, or @WidgetId 0@ for an untagged node.+{-# INLINE getWidgetId #-}+getWidgetId :: NodeArena -> NodeIdx -> IO WidgetId+getWidgetId na idx = arenaArrays na >>= \a -> WidgetId . fromIntegral <$> readTree a idx TreeWidgetId++-- | Whether a later node this frame reuses this node's widget id+-- ('setWidgetId'). 'lookupNodeByWidgetId' returns the last such node, and+-- arena walks that key results by id should skip superseded nodes.+{-# INLINE getIdSuperseded #-}+getIdSuperseded :: NodeArena -> NodeIdx -> IO Bool+getIdSuperseded na idx = arenaArrays na >>= \a -> readTagEnum a idx TagIdSuperseded++-- | Node index by widget id, as an open-addressing table. Each slot is two+-- words: the id, and a value packing the epoch (high 32 bits) with the node+-- index (low 32 bits). A slot from another epoch counts as free, so bumping+-- the epoch empties the table without touching it. Entries are never+-- removed within a frame, so a probe can stop at the first free slot.+--+-- Fields: the slots, the slot count (a power of two) minus one, and the+-- live entry count for the current epoch in one slot.+data IdIndex = IdIndex {-# UNPACK #-} !(IOArr Word64) {-# UNPACK #-} !Int {-# UNPACK #-} !(IOArr Int)++-- | An empty index of @n@ slots, a power of two.+newIdIndex :: Int -> IO IdIndex+newIdIndex n = do+  slots <- newZeroedPrimArray (2 * n)+  live <- newZeroedPrimArray 1+  pure (IdIndex slots (n - 1) live)++-- | Probe for @key@ in epoch @ep@. Calls @found s v@ with the matching slot+-- and its value, or @free s@ with the free slot where the probe stopped.+-- Ids are already hashes; the multiply spreads their bits so even a small+-- table uses them all.+{-# INLINE probeSlot #-}+probeSlot :: IOArr Word64 -> Int -> Word32 -> Word64 -> (Int -> IO r) -> (Int -> Word64 -> IO r) -> IO r+probeSlot slots mask ep key free found = go (fromIntegral ((key * 0x9E3779B97F4A7C15) `shiftR` 32) .&. mask)+  where+    go !s = do+      v <- readPrimArray slots (2 * s + 1)+      if v `shiftR` 32 /= fromIntegral ep+        then free s+        else do+          k <- readPrimArray slots (2 * s)+          if k == key then found s v else go ((s + 1) .&. mask)++-- | The node index in a slot's value.+{-# INLINE slotNode #-}+slotNode :: Word64 -> Int+slotNode v = fromIntegral (v .&. 0xFFFFFFFF)++-- | Type-specific numeric value, such as selection state or a scroller's+-- solved content height. Interpret it according to 'getNodeType'.+{-# INLINE getNodeValue #-}+getNodeValue :: NodeArena -> NodeIdx -> IO Float+getNodeValue na idx = arenaArrays na >>= \a -> readStyle a idx StyleNodeValue++-- | 'setNodeValue' for a value the solver works out from the layout, such as+-- a scroller's content extent, which the layout inputs already cover.+{-# INLINE setSolvedValue #-}+setSolvedValue :: NodeArena -> NodeIdx -> Float -> IO ()+setSolvedValue na idx v = arenaArrays na >>= \a -> writeStyle a idx StyleNodeValue v++-- | Explicit logical font size, or zero for the backend default.+{-# INLINE getNodeFontSize #-}+getNodeFontSize :: NodeArena -> NodeIdx -> IO Float+getNodeFontSize na idx = arenaArrays na >>= \a -> readStyle a idx StyleFontSize++-- | Explicit font colour, or 'Nothing' to use the theme. This is paint-only+-- state and does not invalidate cached layout.+{-# INLINE getNodeFontColor #-}+getNodeFontColor :: NodeArena -> NodeIdx -> IO (Maybe Color)+getNodeFontColor na idx = do+  a <- arenaArrays na+  val <- readPrimArray (naArrFontColor a) idx+  let hasColor = (val .&. 0x100000000) /= 0+  pure (if hasColor then Just (Color (fromIntegral (val .&. 0xFFFFFFFF))) else Nothing)++-- | Packed scope: theme index above bit 1, inert flag in bit 1, disabled flag in bit 0.+{-# INLINE getNodeScope #-}+getNodeScope :: NodeArena -> NodeIdx -> IO Int+getNodeScope na idx = arenaArrays na >>= \a -> readPrimArray (naArrScope a) idx++-- | Packed paint scope that newly added nodes inherit.+{-# INLINE getArenaScope #-}+getArenaScope :: NodeArena -> IO Int+getArenaScope na = readPrimVar (naScope na)++-- | Select the packed paint scope for subsequent nodes. Existing nodes keep theirs.+{-# INLINE setArenaScope #-}+setArenaScope :: NodeArena -> Int -> IO ()+setArenaScope na = writePrimVar (naScope na)++-- | Hash of non-default node scopes recorded during insertion this frame.+-- Used to detect changes in scoped painting; zero is the reset value.+{-# INLINE getScopeSignature #-}+getScopeSignature :: NodeArena -> IO Word64+getScopeSignature na = readPrimVar (naScopeSig na)++-- | Hash over every layout input written since the reset: each node's+-- layout and tree links as 'addNode' wrote them, plus every later change+-- through 'setNodeText', 'setOptions', 'setWidgetId' and 'setStyleIdx'.+-- Solver outputs ('setScrollContentW', 'TagScrollBarSlot', rects) and paint+-- state ('setNodeValue', the font colour) are excluded. Tree links need no mix+-- of their own: every node's index and parent are in its creation hash, and+-- children are prepended in index order, so the child lists follow. The node+-- count enters through the indices too; 'layoutSigMatches' also checks it+-- exactly.+{-# INLINE getInputSignature #-}+getInputSignature :: NodeArena -> IO Word64+getInputSignature na = readPrimArray (naInputSig na) 0++-- | Read the 64-bit style index of node @idx@ from already-fetched arena arrays.+{-# INLINE readStyleIdx #-}+readStyleIdx :: NodeArenaArrays -> NodeIdx -> IO Word64+readStyleIdx a = readPrimArray (naArrStyleIdx a)++-- | Type-specific 64-bit style code. Its encoding depends on 'getNodeType',+-- such as button flags, a radio option index, or packed text styling.+{-# INLINE getStyleIdx #-}+getStyleIdx :: NodeArena -> NodeIdx -> IO Word64+getStyleIdx na idx = arenaArrays na >>= \a -> readPrimArray (naArrStyleIdx a) idx
+ lib/NanoUI/Internal/Layout/ScrollGeometry.hs view
@@ -0,0 +1,373 @@+-- | Scrollbar geometry: gutters, viewport clips, and track and thumb layout.+module NanoUI.Internal.Layout.ScrollGeometry+  ( ScrollPolicy (..)+  , ScrollConfig (..)+  , defaultScrollConfig+  , scroll2DConfig+  , ScrollBarLayout (..)+  , ScrollNode (..)+  , scrollNodeViewport+  , scrollNodeBars+  , scrollChromeLane+  , scrollBarLayout+  , scrollBarLayoutIn+  , scrollThumbSpan+  , scrollAxisRange+  , scrollOffsetFromThumb+  , onScrollBar+  , padContentClip+  , encodeScrollConfig+  , decodeScrollConfig+  , scrollConfigNative2D+  , scrollDefault1D+  , scrollVerticalHidden+  , scrollHorizontalHidden+  , scrollAxisGutter+  , scrollChromeSuppressed+  , scrollWheelSuppressed+  , isScrollStyle2D+  , tagClippedSpans+  , padTextClipRect+  , borderContentClip+  ) where++import Data.Bits ((.|.))+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Font+import NanoUI.Internal.Types (Color, Rect (..), V2 (..), clamp, rectContains, rectH, rectIntersect, rectW, rectX, rectY, v2X, v2Y)+import NanoUI.Internal.Layout.Arena (DirTag (..))+import NanoUI.Internal.Style (Direction (..), Padding (..), Side (..), Style (..), styleBorderWidth, styleHasSide, windowPad)+import qualified NanoUI.Internal.StyleBits as SB++-- | Axis scrollbar visibility and interaction policy.+data ScrollPolicy+  = ScrollAuto+  | ScrollAlways+  | ScrollNone+  | ScrollHidden+  | -- | Paint a floating thumb without a background track or reserved cross-axis+    -- gutter, so content uses the full viewport width and height.+    ScrollOverlay+  deriving (Eq, Show, Enum, Bounded)++-- | 2D scroll configuration (policy per axis).+data ScrollConfig = ScrollConfig+  { scrollPolicyX :: !ScrollPolicy+  , scrollPolicyY :: !ScrollPolicy+  , scrollBare :: !Bool+  -- ^ Paint only clipped children, without a background or border. Scrollbar+  -- policies still apply; combine with 'ScrollHidden' to omit all chrome. A+  -- bare scroller with something to scroll also keeps the wheel: an axis it+  -- cannot move passes to no scroller around or inside it.+  , scrollFocusable :: !Bool+  -- ^ Register the scroll container as a keyboard Tab stop and focus it on a+  -- click inside it that did not focus a text field, select, or focusable+  -- drawing, for keyboard-driven list views ('NanoUI.useListNav').+  }+  deriving (Eq, Show)++-- | Automatic vertical scrollbar, no horizontal scrollbar, painted background,+-- and not focusable.+defaultScrollConfig :: ScrollConfig+defaultScrollConfig = ScrollConfig ScrollNone ScrollAuto False False++-- | Automatic scrollbars on both axes, painted background, and not focusable.+scroll2DConfig :: ScrollConfig+scroll2DConfig = ScrollConfig ScrollAuto ScrollAuto False False++scrollConfigNative2D :: ScrollConfig -> Bool+scrollConfigNative2D cfg = scrollPolicyX cfg /= ScrollNone && scrollPolicyY cfg /= ScrollNone++-- | A scroll node's style index. 'SB.scrollMarker' is always set, so that+-- no scroll node's style index is 0.+encodeScrollConfig :: ScrollConfig -> Word64+encodeScrollConfig (ScrollConfig px py bare focusable) =+  SB.fieldMask SB.scrollMarker+    .|. SB.placeField SB.scrollPolicyX (fromEnum px)+    .|. SB.placeField SB.scrollPolicyY (fromEnum py)+    .|. (if bare then SB.fieldMask SB.scrollBare else 0)+    .|. (if focusable then SB.fieldMask SB.scrollFocusable else 0)++decodeScrollConfig :: Word64 -> ScrollConfig+decodeScrollConfig bits =+  ScrollConfig+    (SB.decodeStyleEnum SB.scrollPolicyX ScrollAuto bits)+    (SB.decodeStyleEnum SB.scrollPolicyY ScrollAuto bits)+    (SB.testField SB.scrollBare bits)+    (SB.testField SB.scrollFocusable bits)++scrollDefault1D :: Direction -> ScrollConfig+scrollDefault1D Column = defaultScrollConfig+scrollDefault1D Row = ScrollConfig ScrollAuto ScrollNone False False++scrollVerticalHidden :: ScrollConfig+scrollVerticalHidden = ScrollConfig ScrollNone ScrollHidden False False++scrollHorizontalHidden :: ScrollConfig+scrollHorizontalHidden = ScrollConfig ScrollHidden ScrollNone False False++-- | Cross-axis gutter for one bar. @trailPad@ is the scroller's padding on+-- the bar's side (right for the vertical bar, bottom for the horizontal one).+scrollAxisGutter ::+  ScrollPolicy ->+  ScrollBarSlot ->+  Float ->+  Float ->+  Float ->+  Float+scrollAxisGutter policy slot trailPad contentSize innerMain =+  case policy of+    ScrollAuto -> if scrollOverflows contentSize innerMain then scrollBarGutter slot trailPad else 0+    ScrollAlways -> scrollBarGutter slot trailPad+    _ -> 0++-- Vertical bar takes width. Horizontal bar takes height. Second pass+-- covers the corner case where one bar makes the other axis overflow.+scrollGutters2D ::+  ScrollBarSlot ->+  ScrollConfig ->+  Padding ->+  Float ->+  Float ->+  Float ->+  Float ->+  (Float, Float)+scrollGutters2D slot cfg pad contentW contentH innerW innerH =+  let gVert inner = scrollAxisGutter (scrollPolicyY cfg) slot (padR pad) contentH inner+      gHorz inner = scrollAxisGutter (scrollPolicyX cfg) slot (padB pad) contentW inner+      gW0 = gVert innerH+      gH0 = gHorz innerW+      gW = gVert (max 0 (innerH - gH0))+      gH = gHorz (max 0 (innerW - gW0))+   in (gW, gH)++isScrollStyle2D :: Word64 -> Bool+isScrollStyle2D si = si /= 0 && scrollConfigNative2D (decodeScrollConfig si)++-- | The policy of the axis a scroller laid out along @dir@ scrolls on.+{-# INLINE scrollPolicyFor #-}+scrollPolicyFor :: ScrollConfig -> DirTag -> ScrollPolicy+scrollPolicyFor cfg = \case+  DirColumn -> scrollPolicyY cfg+  DirRow -> scrollPolicyX cfg++-- | Whether the bar along @dir@ is never painted or grabbed.+scrollChromeSuppressed :: ScrollConfig -> DirTag -> Bool+scrollChromeSuppressed cfg dir =+  let p = scrollPolicyFor cfg dir in p /= ScrollAuto && p /= ScrollAlways && p /= ScrollOverlay++-- | Wheel eligibility is wider than chrome eligibility: a hidden bar never+-- paints or drags, but it still scrolls. Only a dead axis ('ScrollNone')+-- ignores the wheel outright. Native 2D scrollers always keep both axes+-- live by construction.+scrollWheelSuppressed :: ScrollConfig -> Bool -> DirTag -> Bool+scrollWheelSuppressed cfg native2D dir = not native2D && scrollPolicyFor cfg dir == ScrollNone++-- | Scroll range along one axis. Content that fits (modulo the trailing+-- padding, which must not surface a bar by itself) does not scroll; genuine+-- overflow extends the range past the last child by the trailing padding so+-- scrolling to the end still reveals it. Stored content sizes exclude the+-- trailing padding (see positionScrollChildren); this is where it is added+-- back into the reachable range.+scrollAxisRange :: Float -> Float -> Float -> Float+scrollAxisRange contentSize innerMain trailingPad+  | scrollOverflows contentSize innerMain = max 0 (contentSize + trailingPad - innerMain)+  | otherwise = 0++-- | Whether content of @contentSize@ overflows @innerMain@ by more than half+-- a pixel, the rounding a fractional layout leaves. The range and the gutter+-- both ask this, so an auto bar never reserves a lane it does not paint.+{-# INLINE scrollOverflows #-}+scrollOverflows :: Float -> Float -> Bool+scrollOverflows contentSize innerMain = contentSize > innerMain + 0.5++-- | Logical window-space track/thumb bounds and the maximum scroll offset.+data ScrollBarLayout = ScrollBarLayout+  { sbTrack :: Rect+  , sbThumb :: Rect+  , sbMaxOff :: Float+  }+  deriving (Eq, Show)++padContentClip :: Float -> Float -> Float -> Float -> Padding -> Rect+padContentClip x y w h pad =+  Rect+    (x + padL pad)+    (y + padT pad)+    (max 0 (w - padL pad - padR pad))+    (max 0 (h - padT pad - padB pad))++-- | What the scroll passes read off a scroll container: its bar slot, scroll+-- config, whether it scrolls natively in 2D, direction, padding, the content+-- extent along its main axis (the content height for 2D) and, for 2D, the+-- content width.+data ScrollNode = ScrollNode+  { snSlot :: !ScrollBarSlot+  , snConfig :: !ScrollConfig+  , sn2D :: !Bool+  , snDir :: !DirTag+  , snPad :: {-# UNPACK #-} !Padding+  , snContentMain :: {-# UNPACK #-} !Float+  , snContentW :: {-# UNPACK #-} !Float+  }++-- | Content viewport of a scroll node placed at @x y w h@: its padding box+-- minus the live scrollbar gutters.+{-# INLINE scrollNodeViewport #-}+scrollNodeViewport :: ScrollNode -> Float -> Float -> Float -> Float -> Rect+scrollNodeViewport (ScrollNode slot cfg native2D dir pad contentMain contentW) x y w h+  | native2D = Rect bx by (max 0 (innerW - gutterW)) (max 0 (innerH - gutterH))+  | dir == DirColumn = Rect bx by (max 0 (innerW - gutter (padR pad) innerH)) innerH+  | otherwise = Rect bx by innerW (max 0 (innerH - gutter (padB pad) innerW))+  where+    Rect bx by innerW innerH = padContentClip x y w h pad+    (gutterW, gutterH) = scrollGutters2D slot cfg pad contentW contentMain innerW innerH+    -- Strict, so its two calls pass unboxed floats (measured: boxing them+    -- cost the pointer scene 100 kB).+    gutter !trailPad !innerMain = scrollAxisGutter (scrollPolicyFor cfg dir) slot trailPad contentMain innerMain++-- | The strip a bar sits in. A list bar sits one gap (see 'scrollBarGap')+-- inside its well's edge. A page bar sits a side gap inside the page's edge,+-- and a window body's bar a side gap inside the window's edge, out in the+-- window's padding. The gutter keeps the content one gap before each of them.+scrollChromeLane ::+  ScrollBarSlot -> DirTag -> Float -> Float -> Float -> Float -> Padding -> Rect+scrollChromeLane slot dir x y w h pad =+  let (barW, _) = scrollBarGeomFor slot+      -- From the scroller's edge in to the bar's far side. Window and modal+      -- bodies only scroll vertically, so the window's side padding is the+      -- one that places their bar.+      inset trailPad = case slot of+        ScrollBarList -> scrollBarGap trailPad+        ScrollBarPage -> scrollBarSideGap+        ScrollBarWindow -> scrollBarSideGap - padR windowPad+   in case dir of+        DirColumn ->+          Rect (max x (x + w - inset (padR pad) - barW)) (y + padT pad) barW (max 0 (h - padT pad - padB pad))+        DirRow ->+          Rect (x + padL pad) (max y (y + h - inset (padB pad) - barW)) (max 0 (w - padL pad - padR pad)) barW++-- | Track and thumb from slot, axis, x/y/width/height, padding, content extent,+-- and current offset. Lengths use logical pixels; 'Nothing' when the content+-- does not overflow or the track is too short for the smallest thumb.+scrollBarLayout ::+  ScrollBarSlot ->+  DirTag ->+  Float ->+  Float ->+  Float ->+  Float ->+  Padding ->+  Float ->+  Float ->+  Maybe ScrollBarLayout+scrollBarLayout slot dir x y w h pad = case dir of+  DirColumn -> scrollBarLayoutIn slot dir (Rect x y w h) pad (h - padT pad - padB pad) (padB pad)+  DirRow -> scrollBarLayoutIn slot dir (Rect x y w h) pad (w - padL pad - padR pad) (padR pad)++-- | Thumb offset along a track of @trackLen@ and clamped thumb length, from a+-- minimum thumb length, viewport numerator @num@, content denominator @den@,+-- scroll offset @off@, and range @maxOff@.+{-# INLINE scrollThumbSpan #-}+scrollThumbSpan :: Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float)+scrollThumbSpan trackLen minThumb num den off maxOff =+  let len = max 1 trackLen+      size = clamp (min minThumb len) len (len * num / den)+      clamped = clamp 0 maxOff off+   in (if maxOff > 0 then (len - size) * clamped / maxOff else 0, size)++-- | 'scrollBarLayout' with an explicit visible main extent and the trailing+-- padding the content scrolls past. A native 2D scroller passes the padding+-- box minus the cross-axis lane (see 'scrollGutters2D'), so its reachable+-- range and thumb reflect the viewport that is actually visible rather than+-- the lane-underlapped padding box. On a one-dimensional scroller @viewMain@+-- is just the padding box on that axis. A text area's padding only places+-- its bars, so it passes no trailing padding.+scrollBarLayoutIn ::+  ScrollBarSlot+  -> DirTag+  -> Rect+  -> Padding+  -> Float+  -> Float+  -> Float+  -> Float+  -> Maybe ScrollBarLayout+scrollBarLayoutIn slot dir (Rect x y w h) pad viewMain trailing contentSize off =+  let+    (barW, barMargin) = scrollBarGeomFor slot+    minThumb = 16+    lane = scrollChromeLane slot dir x y w h pad+    origin = case dir of+      DirColumn -> y + padT pad+      DirRow -> x + padL pad+    maxOff = scrollAxisRange contentSize viewMain trailing+    trackStart = origin + barMargin+    trackSize = max 0 (viewMain - 2 * barMargin)+    (thumbRel, thumbSize) = scrollThumbSpan trackSize minThumb viewMain (contentSize + trailing) off maxOff+    thumbStart = trackStart + thumbRel+    band start size = case dir of+      DirColumn -> Rect (rectX lane) start barW size+      DirRow -> Rect start (rectY lane) size barW+   in+    if maxOff <= 0 || trackSize < minThumb+      then Nothing+      else+        Just+          (ScrollBarLayout (band trackStart trackSize) (band thumbStart thumbSize) maxOff)++-- | The vertical and the horizontal bar a scroll node placed at @x y w h@+-- shows at offsets @offX offY@ (a 1D scroller's offset is @offY@, whichever+-- way it runs). An axis whose chrome is suppressed shows none. A native 2D+-- scroller's axes each take their visible main extent from the viewport, which+-- the other axis's live gutter has narrowed, so the range and thumb are+-- computed against the viewport minus the opposite scrollbar lane.+scrollNodeBars ::+  ScrollNode -> Float -> Float -> Float -> Float -> Float -> Float -> (Maybe ScrollBarLayout, Maybe ScrollBarLayout)+scrollNodeBars sn@(ScrollNode slot cfg native2D dir pad contentMain contentW) x y w h offX offY+  | native2D =+      let Rect _ _ viewW viewH = scrollNodeViewport sn x y w h+       in ( shown DirColumn (scrollBarLayoutIn slot DirColumn (Rect x y w h) pad viewH (padB pad) contentMain offY)+          , shown DirRow (scrollBarLayoutIn slot DirRow (Rect x y w h) pad viewW (padR pad) contentW offX)+          )+  | dir == DirColumn = (shown dir bar, Nothing)+  | otherwise = (Nothing, shown dir bar)+  where+    bar = scrollBarLayout slot dir x y w h pad contentMain offY+    shown d l = if scrollChromeSuppressed cfg d then Nothing else l++onScrollBar :: V2 -> ScrollBarLayout -> Bool+onScrollBar mouse l = rectContains (sbThumb l) mouse || rectContains (sbTrack l) mouse++scrollOffsetFromThumb :: DirTag -> ScrollBarLayout -> Float -> V2 -> Float+scrollOffsetFromThumb dir layout grabOff mouse =+  let+    maxOff = sbMaxOff layout+    track = sbTrack layout+    thumb = sbThumb layout+    (trackStart, trackSize, thumbSize, pointer) = case dir of+      DirColumn -> (rectY track, rectH track, rectH thumb, v2Y mouse)+      DirRow -> (rectX track, rectW track, rectW thumb, v2X mouse)+    ratio = (pointer - grabOff - trackStart) / max 1 (trackSize - thumbSize)+   in+    clamp 0 maxOff (ratio * maxOff)++textClipSlop :: Float+textClipSlop = 4++tagClippedSpans :: Rect -> [(Rect, Text, Color, Color)] -> [(Rect, Text, Color, Color, Rect)]+tagClippedSpans clip =+  mapMaybe (\(rect, txt, fg, bg) -> (rect, txt, fg, bg,) <$> rectIntersect clip (padTextClipRect rect))++padTextClipRect :: Rect -> Rect+padTextClipRect (Rect x y w h) = Rect x y (w + textClipSlop) h++borderContentClip :: Style -> Rect -> Rect+borderContentClip style (Rect x y w h) =+  if styleBorderWidth style <= 0+    then Rect x y w h+    else+      let inset side = if styleHasSide side style then max 1 (styleBorderWidth style) else 0+       in padContentClip x y w h (Padding (inset SideLeft) (inset SideRight) (inset SideTop) (inset SideBottom))
+ lib/NanoUI/Internal/Layout/Solve.hs view
@@ -0,0 +1,172 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | The layout solver: measures and places the node arena's flow tree, then+-- positions modals, windows and popups.+module NanoUI.Internal.Layout.Solve+  ( solveLayout+  , runCustomMeasure+  , measuredHeightAt+  , Measurers (..)+  , placeFloatingNodes+  , placeFloatingNodesWith+  , computePopupPosition+  , scrollBarSlotOf+  , windowBodyScroller+  , findAncestorMaxW+  , textWrapCap+  ) where++import Control.Monad (unless, when)+import Data.IORef (IORef, newIORef, readIORef)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.Primitive.PrimArray (copyMutablePrimArray, newPrimArray, readPrimArray, setPrimArray, writePrimArray)+import Data.Word (Word8)+import NanoUI.Internal.Font (FontMetrics (..))+import NanoUI.Internal.Layout.ScrollGeometry (isScrollStyle2D)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Solve.Measure+import NanoUI.Internal.Layout.Solve.Position hiding (placeFloatingNodes)+import NanoUI.Internal.Layout.Solve.Position qualified as Position+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Types (PopupAnchor, PopupPlacement, Rect (..), forUpTo_, gridSpan, onGrid)++-- | Measure nodes and place the page within the supplied logical width/height.+-- The view must have finished adding nodes, and 'computeSubtreeHashes' must+-- have run for this frame. Place floating nodes separately with+-- 'placeFloatingNodes', then apply scrolling.+-- When a layout cache captured under the same font metrics is supplied, a+-- node whose inputs, ancestors' inputs and subtree are unchanged since that+-- solve, and whose children all came out their captured sizes, takes its+-- captured measured size instead of measuring again ('restoreMeasured'). The+-- position pass then puts back, instead of placing again, each such subtree+-- that holds no drawing and is offered the rect the captured solve offered+-- it ('reusePositions'). Quantization runs over every node, so the+-- result is what a full solve computes. Returns each custom-measured node's+-- 'CustomMeasureRecord', for the layout cache.+solveLayout :: NodeArena -> Measurers -> Float -> Float -> Maybe LayoutCache -> IO (IntMap CustomMeasureRecord)+solveLayout na ms rootW rootH mCache = do+  count <- arenaCount na+  if count <= 0+    then pure IM.empty+    else do+      measureLog <- newIORef IM.empty+      env0 <- solveEnv na ms mCache+      let a = seArrays env0+          env = env0 {seMeasureLog = Just measureLog, seRecordPos = True}+      setPrimArray (naArrOffered a) 0 (count * 4) (0 / 0)+      measurePass env count+      positionNodeA env 0 0 (Rect 0 0 rootW rootH)+      forUpTo_ count $ \i ->+        copyMutablePrimArray (naArrUnsnapped a) (i * 4) (naArrGeom a) (i * geomStride) 4+      floatingCount <- floatingNodeCount na+      quantizeResultsA na a count floatingCount (fmSnapScale (msFm ms))+      readIORef measureLog++-- | Snap the solved geometry of the @count@ nodes outside floating subtrees+-- to the device pixel grid of scale @s@. @floatingCount@ is the arena's+-- floating node count.+--+-- A floating node (modal, window, popup) and everything inside it is laid+-- out by placement after the solve, which sizes the subtree from these+-- measured sizes. Rounding them here would size a dialog and its+-- content-sized parts off their content, so the subtree keeps them, and+-- 'placeFloatingNodes' snaps it once placed ('snapFloatingSubtrees').+quantizeResultsA :: NodeArena -> NodeArenaArrays -> Int -> Int -> Float -> IO ()+quantizeResultsA na a count floatingCount s+  | s <= 0 = pure ()+  -- Nothing floats, so every node snaps and none needs marking.+  | floatingCount <= 0 = forUpTo_ count (snapNode na a s)+  | otherwise = forFloatingMarks a count $ \i inFloating -> unless inFloating (snapNode na a s i)++-- | Snap every node inside a floating subtree, after placement has laid it+-- out, as 'quantizeResultsA' snaps the page.+snapFloatingSubtrees :: NodeArena -> Float -> IO ()+snapFloatingSubtrees na s = do+  count <- arenaCount na+  floatingCount <- floatingNodeCount na+  when (s > 0 && count > 0 && floatingCount > 0) $ do+    a <- arenaArrays na+    forFloatingMarks a count $ \i inFloating -> when inFloating (snapNode na a s i)++-- | Visit the @count@ nodes in arena order with whether each is a floating+-- node or inside one. A parent always precedes its children, so one pass+-- marks each node from its parent.+{-# INLINE forFloatingMarks #-}+forFloatingMarks :: NodeArenaArrays -> Int -> (Int -> Bool -> IO ()) -> IO ()+forFloatingMarks a count k = do+  floating <- newPrimArray count :: IO (IOArr Word8)+  forUpTo_ count $ \i -> do+    nt <- readTagEnum a i TagNodeType+    parent <- readTree a i TreeParent+    inFloating <-+      if isFloatingNode nt+        then pure True+        else if parent >= 0 then (/= 0) <$> readPrimArray floating parent else pure False+    writePrimArray floating i (if inFloating then 1 else 0)+    k i inFloating++-- | Snap node @i@ to the device pixel grid of scale @s@.+snapNode :: NodeArena -> NodeArenaArrays -> Float -> Int -> IO ()+snapNode na a s i = do+  x <- readGeom a i GeomX+  y <- readGeom a i GeomY+  w <- readGeom a i GeomW+  h <- readGeom a i GeomH+  -- Snap both edges and take the size between them. Rounding the size on+  -- its own can push a node's far edge a pixel past the snapped origin of+  -- the sibling that starts there, and the node then paints over it (a+  -- table cell over the column rule beside it).+  writeGeom a i GeomLaidW w+  writeGeom a i GeomX (onGrid s x)+  writeGeom a i GeomY (onGrid s y)+  writeGeom a i GeomW (max 0 (gridSpan s x (x + w)))+  writeGeom a i GeomH (max 0 (gridSpan s y (y + h)))+  nt <- readTagEnum a i TagNodeType+  when (nt == NodeScrollContainer) $ do+    si <- readStyleIdx a i+    dir <- readTagEnum a i TagDirection+    padL <- readStyle a i StylePadL+    padT <- readStyle a i StylePadT+    val <- getNodeValue na i+    if isScrollStyle2D si+      then do+        cw <- getScrollContentW na i+        setScrollContentW na i (max 0 (gridSpan s (x + padL) (x + padL + cw)))+        setSolvedValue na i (max 0 (gridSpan s (y + padT) (y + padT + val)))+      else do+        let start = if dir == DirRow then x + padL else y + padT+        setSolvedValue na i (max 0 (gridSpan s start (start + val)))++-- | Place floating nodes ('Position.placeFloatingNodes'), then snap their+-- subtrees to the device pixel grid.+placeFloatingNodes ::+  NodeArena ->+  Measurers ->+  Float ->+  Float ->+  (WidgetId -> IO (Maybe (Float, Float))) ->+  (WidgetId -> IO (Maybe (Float, Float))) ->+  (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) ->+  Maybe (IORef (IntMap PlacedFloat)) ->+  IO ()+placeFloatingNodes na ms winW winH lookupPos lookupSize lookupAnchor =+  placeFloatingNodesWith na ms winW winH lookupPos lookupSize lookupAnchor (\_ _ _ -> pure Nothing)++-- | 'placeFloatingNodes' where @lookupRect@, given a popup's id and measured+-- width and height, can return the rect it goes at, in place of the one its+-- anchor gives it.+placeFloatingNodesWith ::+  NodeArena ->+  Measurers ->+  Float ->+  Float ->+  (WidgetId -> IO (Maybe (Float, Float))) ->+  (WidgetId -> IO (Maybe (Float, Float))) ->+  (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) ->+  (WidgetId -> Float -> Float -> IO (Maybe Rect)) ->+  Maybe (IORef (IntMap PlacedFloat)) ->+  IO ()+placeFloatingNodesWith na ms winW winH lookupPos lookupSize lookupAnchor lookupRect mPlaced = do+  Position.placeFloatingNodes na ms winW winH lookupPos lookupSize lookupAnchor lookupRect mPlaced+  snapFloatingSubtrees na (fmSnapScale (msFm ms))
+ lib/NanoUI/Internal/Layout/Solve/Flex.hs view
@@ -0,0 +1,448 @@+-- | Scratch-buffer flex, grid, wrap-line, chrome-column, and alignment math.+module NanoUI.Internal.Layout.Solve.Flex+  ( FlowAcc (..)+  , containerFlow+  , isChromeColumn+  , pairColumnGap+  , columnGapSumScratch+  , foldChromeColumnScratch+  , gridColumnCount+  , gridColWidth+  , gridRowHeight+  , wrapLines+  , distributeScratch+  , resolveSize+  , alignX+  , alignY+  ) where++import Control.Monad (when)+import Data.IORef (readIORef)+import Data.Primitive.PrimArray (copyMutablePrimArray, newPrimArray, readPrimArray, writePrimArray)+import NanoUI.Internal.Layout.ScrollGeometry (isScrollStyle2D)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Style (AlignX (..), AlignY (..), Padding (..), alignXFraction, alignYFraction)+import NanoUI.Internal.Types (clamp, foldUpTo, forUpTo_, isBounded)++-- | Strict accumulator for flow-child folds: a child count and two running+-- sums or extents. The strict fields keep the folds unboxed.+data FlowAcc = FlowAcc !Int !Float !Float++-- | Greedily break items into lines no longer than @limit@, with @gap@+-- between neighbours. An item longer than the limit gets a line to itself.+wrapLines :: Float -> Float -> (a -> Float) -> [a] -> [[a]]+wrapLines limit gap len = go+  where+    go [] = []+    go (x : xs) = let (line, rest) = fill (len x) xs in (x : line) : go rest+    fill !used (y : ys)+      | used + gap + len y <= limit + 1.0e-3 =+          let (line, rest) = fill (used + gap + len y) ys in (y : line, rest)+    fill _ ys = ([], ys)++isChromeColumn :: NodeType -> DirTag -> Bool+isChromeColumn nt dir =+  dir == DirColumn && (nt == NodeWindow || nt == NodeModal)++-- | Gap before child @b@ in a column; chrome columns drop it before separators.+pairColumnGap :: NodeArena -> Bool -> NodeIdx -> Float -> IO Float+pairColumnGap _ False _ gap = pure gap+pairColumnGap na True b gap = do+  ntB <- getNodeType na b+  pure (if ntB == NodeSeparator then 0 else gap)++foldChromeColumnScratch :: NodeArena -> Int -> Float -> IO (Float, Float)+foldChromeColumnScratch na n gap = do+  FlexScratch {fsW = wArr, fsH = hArr} <- readIORef (naScratch na)+  gapSum <- columnGapSumScratch na n gap+  maxW <- foldUpTo n (\m i -> max m <$> readPrimArray wArr i) 0+  totalH <- foldUpTo n (\t i -> (t +) <$> readPrimArray hArr i) 0+  pure (maxW, totalH + gapSum)++-- | Grid column count: explicit, else as many @minColW@ columns as fit in a+-- positive @availW@, else one.+{-# INLINE gridColumnCount #-}+gridColumnCount :: Int -> Float -> Float -> Float -> Int+gridColumnCount gCols minColW availW gap+  | gCols > 0 = gCols+  | minColW > 0 && availW > 0 = max 1 (floor ((availW + gap) / (minColW + gap)))+  | otherwise = 1++-- | Height of grid row @r@: its tallest child.+-- | Width of each column in a grid of @cols@ columns across @avail@ with @gap@.+{-# INLINE gridColWidth #-}+gridColWidth :: Float -> Int -> Float -> Float+gridColWidth avail cols gap = max 0 ((avail - gap * fromIntegral (cols - 1)) / fromIntegral cols)++gridRowHeight :: IOArr Float -> Int -> Int -> Int -> IO Float+gridRowHeight hArr n cols r =+  foldUpTo (min cols (n - r * cols)) (\m j -> max m <$> readPrimArray hArr (r * cols + j)) 0++{-# INLINE containerFlow #-}+containerFlow :: NodeArenaArrays -> NodeIdx -> IO (Padding, Float, DirTag)+containerFlow a idx =+  (,,) <$> readPadding a idx <*> readStyle a idx StyleGap <*> readTagEnum a idx TagDirection++-- | The gaps between the first @n@ scratch children of a window's or modal's+-- column, where a separator takes none before it.+columnGapSumScratch :: NodeArena -> Int -> Float -> IO Float+columnGapSumScratch na n gap = do+  FlexScratch {fsIdx = idxArr} <- readIORef (naScratch na)+  let addGap acc i = readPrimArray idxArr (i + 1) >>= \b -> (acc +) <$> pairColumnGap na True b gap+  foldUpTo (n - 1) addGap 0++-- | Share the main axis among the first @n@ scratch children: 'fsOut' gets+-- each child's size along it, starting from its content size ('fsW' or+-- 'fsH') and taking its part of the space the container has spare or lacks.+distributeScratch :: NodeArena -> Int -> Float -> Float -> Bool -> IO ()+distributeScratch na n avail gapSum horizontal = do+  FlexScratch {fsIdx = idxArr, fsW = wArr, fsH = hArr, fsOut = out, fsGrow = gfArr} <- readIORef (naScratch na)+  a <- arenaArrays na+  copyMutablePrimArray out 0 (if horizontal then wArr else hArr) 0 n+  total <- foldUpTo n (\acc i -> (acc +) <$> readPrimArray out i) 0+  let slack = avail - (total + gapSum)+      sizingAt i = readPrimArray idxArr i >>= \ci -> readAxisSizing a ci horizontal+  if slack > 0.001+    then do+      -- Grow children share the free space by factor, but no child is+      -- squeezed below its content size (a min-content floor, like CSS+      -- flex with min-width:auto): two fillW columns come out equal unless+      -- one column's content needs more, and that one then takes exactly+      -- what it needs while the rest re-share what is left.+      --+      -- 'fsGrow' holds each child's factor, 0 once it is not or no longer+      -- growing (-1 once its maximum stops it, 'settleCapped'), and 'fsOut'+      -- keeps the exact content size until the shares are handed out.+      FlowAcc capped growTotal _ <- foldUpTo n (\(FlowAcc c acc _) i -> do+        AxisSizing tag val _ hi <- sizingAt i+        let gf = if tag == SizingGrow && val > 0 then val else 0+        writePrimArray gfArr i gf+        pure (FlowAcc (if gf > 0 && isBounded hi then c + 1 else c) (acc + gf) 0)) (FlowAcc 0 0 0)+      when (growTotal > 0) $ do+        (free, gfSum) <-+          if capped > 0+            then settleCapped a idxArr out gfArr horizontal avail gapSum n+            else settleGrow out gfArr avail gapSum n 0+        forUpTo_ n $ \i -> do+          gf <- readPrimArray gfArr i+          when (gf > 0) $ writePrimArray out i (max 0 (free * gf / gfSum))+    else when (slack < -0.001) $ do+      -- Shrink children by factor to make up the shortfall, none below its+      -- minimum ('shrinkScratch'). 'fsGrow' holds the factors. A scroll+      -- container that fits its content along the axis it scrolls gives+      -- space back like a grow child, and scrolls the rest: a scroll area in+      -- a popup capped by 'maxH' keeps within the cap.+      forUpTo_ n $ \i -> do+        ci <- readPrimArray idxArr i+        ax <- readAxisSizing a ci horizontal+        scrolls <-+          if axTag ax /= SizingFit+            then pure False+            else do+              nt <- readTagEnum a ci TagNodeType+              si <- readStyleIdx a ci+              dir <- readTagEnum a ci TagDirection+              pure (nt == NodeScrollContainer && (isScrollStyle2D si || (dir == DirRow) == horizontal))+        writePrimArray gfArr i (if scrolls then 1 else shrinkFactor ax)+      let minCol = if horizontal then StyleMinW else StyleMinH+      shrinkScratch out gfArr (\i -> readPrimArray idxArr i >>= \ci -> readStyle a ci minCol) n (negate slack)++-- | Take @need@ from the first @n@ sizes in @mainArr@ in proportion to their+-- factors in @factorArr@ (0 keeps a size). A child that would drop below its+-- minimum (@minAt@) stops there with its factor cleared, and the others+-- share what it could not give. Inlined, so @minAt@ is a known function and+-- the passes run unboxed.+{-# INLINE shrinkScratch #-}+shrinkScratch :: IOArr Float -> IOArr Float -> (Int -> IO Float) -> Int -> Float -> IO ()+shrinkScratch mainArr factorArr minAt n = pass 0+  where+    pass !sweep !need = when (need > 0) $ do+      total <- foldUpTo n (\acc i -> (acc +) <$> readPrimArray factorArr i) 0+      when (total > 0) $ do+        let stop !i !given !stopped+              | i >= n =+                  if stopped > (0 :: Int)+                    then do+                      need' <-+                        if sweep + 1 == waterFillAfter+                          then waterFillShrink mainArr factorArr minAt (need - given) n+                          else pure (need - given)+                      pass (sweep + 1) need'+                    else forUpTo_ n $ \j -> do+                      f <- readPrimArray factorArr j+                      when (f > 0) $ readPrimArray mainArr j >>= \main -> writePrimArray mainArr j (main - need * f / total)+              | otherwise = do+                  f <- readPrimArray factorArr i+                  if f <= 0+                    then stop (i + 1) given stopped+                    else do+                      lo <- minAt i+                      main <- readPrimArray mainArr i+                      if main - need * f / total < lo+                        then do+                          writePrimArray mainArr i lo+                          writePrimArray factorArr i 0+                          stop (i + 1) (given + main - lo) (stopped + 1)+                        else stop (i + 1) given stopped+        stop 0 0 0++-- | Sort @(keys, vals)@ of length @len@ in place by @keys@, ascending when+-- @ascending@ is 'True' and descending otherwise. Uses insertion sort for small+-- slices and heapsort above, allocating nothing.+sortPairsByKey :: Bool -> IOArr Float -> IOArr Int -> Int -> IO ()+sortPairsByKey ascending keys vals len+  | len <= 1 = pure ()+  | len <= 16 = insertLoop 1+  | otherwise = buildHeap ((len `quot` 2) - 1) >> extractLoop (len - 1)+  where+    {-# INLINE precedes #-}+    precedes :: Float -> Float -> Bool+    precedes a b = if ascending then a < b else a > b++    insertLoop !i = when (i < len) $ do+      k <- readPrimArray keys i+      v <- readPrimArray vals i+      let shift !j+            | j <= 0 = writePrimArray keys 0 k >> writePrimArray vals 0 v+            | otherwise = do+                kj <- readPrimArray keys (j - 1)+                if precedes k kj+                  then do+                    writePrimArray keys j kj+                    readPrimArray vals (j - 1) >>= writePrimArray vals j+                    shift (j - 1)+                  else writePrimArray keys j k >> writePrimArray vals j v+      shift i+      insertLoop (i + 1)++    -- Max-heap under 'precedes' puts the last-in-order element at the root so+    -- extracting to the tail leaves the array sorted.+    siftDown !root !end = do+      rk <- readPrimArray keys root+      rv <- readPrimArray vals root+      let go !cur = do+            let !l = cur * 2 + 1+            if l >= end+              then writePrimArray keys cur rk >> writePrimArray vals cur rv+              else do+                lk <- readPrimArray keys l+                let !r = l + 1+                (bestIdx, bestK) <-+                  if r < end+                    then do+                      rk' <- readPrimArray keys r+                      pure (if precedes lk rk' then (r, rk') else (l, lk))+                    else pure (l, lk)+                if precedes rk bestK+                  then do+                    writePrimArray keys cur bestK+                    readPrimArray vals bestIdx >>= writePrimArray vals cur+                    go bestIdx+                  else writePrimArray keys cur rk >> writePrimArray vals cur rv+      go root++    buildHeap !i = when (i >= 0) $ siftDown i len >> buildHeap (i - 1)++    extractLoop !end = when (end > 0) $ do+      k0 <- readPrimArray keys 0+      v0 <- readPrimArray vals 0+      ke <- readPrimArray keys end+      ve <- readPrimArray vals end+      writePrimArray keys 0 ke+      writePrimArray vals 0 ve+      writePrimArray keys end k0+      writePrimArray vals end v0+      siftDown 0 end+      extractLoop (end - 1)++-- | Lock every remaining shrinkable child whose headroom per unit of factor is+-- less than the shortfall per unit left once the tighter children before it+-- hit their floors. Runs in O(n log n) after 'waterFillAfter' sweeps using+-- unboxed scratch arrays.+waterFillShrink :: IOArr Float -> IOArr Float -> (Int -> IO Float) -> Float -> Int -> IO Float+waterFillShrink mainArr factorArr minAt need0 n+  | need0 <= 0 = pure need0+  | otherwise = do+      keys <- newPrimArray n+      idxs <- newPrimArray n+      slacks <- newPrimArray n+      floors <- newPrimArray n+      let collect !i !m !total+            | i >= n = pure (m, total)+            | otherwise = do+                f <- readPrimArray factorArr i+                if f <= 0+                  then collect (i + 1) m total+                  else do+                    lo <- minAt i+                    main <- readPrimArray mainArr i+                    let !slack = main - lo+                    writePrimArray keys m (slack / f)+                    writePrimArray idxs m i+                    writePrimArray slacks i slack+                    writePrimArray floors i lo+                    collect (i + 1) (m + 1) (total + f)+      (m, total0) <- collect 0 0 0+      sortPairsByKey True keys idxs m+      let stopFrom !j !remNeed !total+            | j >= m || remNeed <= 0 || total <= 0 = pure remNeed+            | otherwise = do+                i <- readPrimArray idxs j+                slack <- readPrimArray slacks i+                f <- readPrimArray factorArr i+                if slack * total < remNeed * f+                  then do+                    readPrimArray floors i >>= writePrimArray mainArr i+                    writePrimArray factorArr i 0+                    stopFrom (j + 1) (remNeed - slack) (total - f)+                  else pure remNeed+      stopFrom 0 need0 total0++{-# INLINE shrinkFactor #-}+shrinkFactor :: AxisSizing -> Float+shrinkFactor (AxisSizing tag val _ _) =+  case tag of+    SizingShrink -> max 0 val+    -- Grow also gives space back when the window is smaller than content.+    SizingGrow -> if val > 0 then val else 1+    -- Percent flexes like CSS: when siblings plus gaps overflow the axis,+    -- percent children give the overflow back so e.g. two 50% columns and a+    -- gap land exactly on the row width. Covers percent on either axis,+    -- should height percent ever be sized that way.+    SizingPercent -> 1+    -- Fit stays content-sized. A pinned header must not squash when a Grow+    -- sibling (page scroll) is taller than the window. 'distributeScratch'+    -- shrinks a fit scroll container along the axis it scrolls all the same.+    _ -> 0++-- One sweep: sum content of non-grow + already-locked children (factor 0) and+-- grow factors of the still-unlocked.+{-# INLINE scanGrow #-}+scanGrow :: IOArr Float -> IOArr Float -> Int -> Int -> Float -> Float -> IO (Float, Float)+scanGrow mainArr crossArr !i !end !occupied !gfSum+  | i >= end = pure (occupied, gfSum)+  | otherwise = do+      gf <- readPrimArray crossArr i+      if gf > 0+        then scanGrow mainArr crossArr (i + 1) end occupied (gfSum + gf)+        else do+          main <- readPrimArray mainArr i+          scanGrow mainArr crossArr (i + 1) end (occupied + main) gfSum++-- Pin every grow child whose content exceeds its would-be share by clearing+-- its factor; its content stays in mainArr.+lockGrow :: IOArr Float -> IOArr Float -> Float -> Float -> Int -> IO Int+lockGrow mainArr crossArr !free !gfSum n = foldUpTo n lock 0+  where+    lock acc i = do+      gf <- readPrimArray crossArr i+      need <- readPrimArray mainArr i+      if gf > 0 && need * gfSum > gf * free+        then (acc + 1) <$ writePrimArray crossArr i 0+        else pure acc++-- Each lock shrinks the share pool, possibly locking more children; the+-- locked set only grows, so this fixpoints within n sweeps, and a row of n+-- children could take n. Rows settle in a few; one still locking after+-- 'waterFillAfter' sweeps is settled by 'waterFillGrow', which the next sweep+-- confirms, so no row takes more than a sort and that many sweeps.+settleGrow :: IOArr Float -> IOArr Float -> Float -> Float -> Int -> Int -> IO (Float, Float)+settleGrow mainArr crossArr avail gapSum n !pass = do+  (occupied, gfSum) <- scanGrow mainArr crossArr 0 n 0 0+  let free = avail - gapSum - occupied+  locked <- lockGrow mainArr crossArr free gfSum n+  if locked == 0 || pass >= n+    then pure (free, gfSum)+    else do+      when (pass + 1 == waterFillAfter) $ waterFillGrow mainArr crossArr (avail - gapSum) n+      settleGrow mainArr crossArr avail gapSum n (pass + 1)++-- | 'settleGrow' for children of which some grow with a maximum along the+-- axis (@horizontal@ picks it), the scratch children in @idxArr@. A child+-- whose share passes its maximum stops there, -1 in @crossArr@, and the+-- rest share what it gave up; the children locked at their content size+-- grow again, since the shares rose. Each round stops one more child, so+-- there are at most as many rounds as children.+settleCapped ::+  NodeArenaArrays -> IOArr Int -> IOArr Float -> IOArr Float -> Bool -> Float -> Float -> Int -> IO (Float, Float)+settleCapped a idxArr mainArr crossArr horizontal avail gapSum n = go+  where+    sizingAt i = readPrimArray idxArr i >>= \ci -> readAxisSizing a ci horizontal+    go = do+      shares@(free, gfSum) <- settleGrow mainArr crossArr avail gapSum n 0+      let cap k i = do+            gf <- readPrimArray crossArr i+            if gf <= 0+              then pure k+              else do+                hi <- axMax <$> sizingAt i+                if free * gf / gfSum > hi + 1.0e-3+                  then (k + 1 :: Int) <$ (writePrimArray mainArr i hi >> writePrimArray crossArr i (-1))+                  else pure k+      stopped <- foldUpTo n cap 0+      if stopped == 0+        then pure shares+        else do+          forUpTo_ n $ \i -> do+            gf <- readPrimArray crossArr i+            when (gf == 0) $ do+              AxisSizing tag val _ _ <- sizingAt i+              when (tag == SizingGrow && val > 0) $ writePrimArray crossArr i val+          go++-- | Sweeps 'settleGrow' makes before it sorts. Rows with varied content and+-- weights settle in three or four, and below this the sweeps cost less than+-- the sort.+waterFillAfter :: Int+waterFillAfter = 8++-- Lock, in one go, every grow child that 'lockGrow' sweeps would lock one+-- after another. A child locks when its content per unit of grow factor is+-- more than the share per unit left once the children above it lock; the+-- share per unit only falls as children lock, so taking children by content+-- per unit, largest first, and stopping at the first that fits locks the+-- same set.+waterFillGrow :: IOArr Float -> IOArr Float -> Float -> Int -> IO ()+waterFillGrow mainArr crossArr room n = do+  keys <- newPrimArray n+  idxs <- newPrimArray n+  let collect !i !m !occupied !gfSum+        | i >= n = pure (m, occupied, gfSum)+        | otherwise = do+            gf <- readPrimArray crossArr i+            need <- readPrimArray mainArr i+            if gf > 0+              then do+                writePrimArray keys m (need / gf)+                writePrimArray idxs m i+                collect (i + 1) (m + 1) occupied (gfSum + gf)+              else collect (i + 1) m (occupied + need) gfSum+  (m, occupied, gfSum) <- collect 0 0 0 0+  sortPairsByKey False keys idxs m+  let lockFrom !j !free !g = when (j < m) $ do+        i <- readPrimArray idxs j+        need <- readPrimArray mainArr i+        gf <- readPrimArray crossArr i+        when (need * g > gf * free) $ do+          writePrimArray crossArr i 0+          lockFrom (j + 1) (free - need) (g - gf)+  lockFrom 0 (room - occupied) gfSum++-- | The size a node takes along an axis where @avail@ is offered, from its+-- sizing, its measured size @intrinsic@ and its limits.+{-# INLINE resolveSize #-}+resolveSize :: AxisSizing -> Float -> Float -> Float+resolveSize (AxisSizing tag val lo hi) intrinsic avail =+  clamp lo hi $ case tag of+    SizingFixed -> val+    SizingGrow -> avail+    SizingPercent -> avail+    _ -> min intrinsic avail++alignX :: AlignX -> Float -> Float -> Float -> Float+alignX ax cx cw iw = cx + (cw - iw) * alignXFraction ax++-- | 'AlignBaseline' places like 'AlignTop' here; 'positionRowFromParent'+-- places a row's baseline-aligned children.+alignY :: AlignY -> Float -> Float -> Float -> Float+alignY ay cy ch ih = cy + (ch - ih) * alignYFraction ay
+ lib/NanoUI/Internal/Layout/Solve/Measure.hs view
@@ -0,0 +1,1431 @@+-- | Measure pass, custom/text/container measurement, fit-height refit, and baselines.+module NanoUI.Internal.Layout.Solve.Measure+  ( SolveEnv (..)+  , Measurers (..)+  , solveEnv+  , TextMeasurer (..)+  , nodeMeasurer+  , textHeightAt+  , measurePass+  , runCustomMeasure+  , textWrapCap+  , findAncestorMaxW+  , adornedButtonGroup+  , windowBodyScroller+  , recomputeFitHeightAtWidth+  , loadChildrenScratch+  , flowChildSize+  , percentOr+  , isBaselineChild+  , childBaseline+  , scrollBarSlotOf+  , drawingHeightAt+  , measuredHeightAt+  , wrapLineCross+  , rowChildHeightAt+  , ContainerKind (..)+  , readContainerKind+  , readGridColumns+  ) where++import Control.Monad (foldM, forM_, guard, mfilter, unless, when)+import Data.IORef (IORef, modifyIORef', readIORef, writeIORef)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.Maybe (fromMaybe, isJust)+import Data.Primitive.PrimArray (copyMutablePrimArray, readPrimArray, writePrimArray)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word8, Word64)+import GHC.Float (castFloatToWord32)+import NanoUI.Internal.Font+import NanoUI.Internal.Layout.ScrollGeometry+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Arena.Types (newFlexScratch)+import NanoUI.Internal.Layout.Solve.Flex+import NanoUI.Internal.Style (AlignY (..), Flow (..), FontStyle (..), FontVariant (..), FontWeight (..), ItemsAlign (..), Padding (..), hasExplicitMin, resolveFontSize)+import NanoUI.Internal.Types (Rect (..), clamp, foldUpTo, newZeroedPrimArray, isBounded, isUnbounded, noLimit)+import NanoUI.Internal.WidgetText++-- | Resolve size, weight, slant, and variant to metrics plus logical-pixel+-- text measurement. Size zero requests the backend default.+type FontResolver = Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Text -> IO (Float, Float))++-- | Per-solve constants threaded through the measure and position passes.+data SolveEnv = SolveEnv+  { seArena :: !NodeArena+  , seArrays :: !NodeArenaArrays+  , seMs :: !Measurers+  , seCache :: !(Maybe LayoutCache)+  -- ^ A non-empty captured solve, taken under the current font metrics. A+  -- node it measured the same way gets its captured size back instead of+  -- measuring again ('restoreMeasured').+  , seMeasureLog :: !(Maybe (IORef (IntMap CustomMeasureRecord)))+  -- ^ Where 'measureCustomNode' records each custom measurement, for the+  -- layout cache: set by 'solveLayout' only, so floating placement records+  -- nothing.+  , seRecordPos :: !Bool+  -- ^ Set by 'solveLayout' only: what its position pass records and puts+  -- back ('positionNodeA').+  }++-- | How text and custom widgets are measured. The solve and the placement of+-- floating nodes after it measure with the same, so a label placed in a modal+-- wraps exactly as the solve measured it for the modal's size.+data Measurers = Measurers+  { msFm :: !FontMetrics+  , msMonoFm :: !FontMetrics+  , msFontSize :: !Float+  , msMeasure :: !(Text -> IO (Float, Float))+  , msResolveFont :: !FontResolver+  , msLookupMeasure :: !(WidgetId -> IO (Maybe CustomMeasureFn))+  , msWrap :: !TextWrapper+  }++-- | Wrap text in a font ('textNodeFontKey') with its line measure, as+-- 'wrapTextIO' does. The context's shares results across frames and with+-- the text spans ('NanoUI.Internal.Context.cachedWrapText').+type TextWrapper = Int -> (Text -> IO Float) -> Text -> Float -> IO WrapResult++solveEnv :: NodeArena -> Measurers -> Maybe LayoutCache -> IO SolveEnv+solveEnv na ms mCache = do+  a <- arenaArrays na+  pure (SolveEnv na a ms (mfilter ((> 0) . lcCount) mCache) Nothing False)++-- Keep font selection and single-line/wrapped measurement together so every+-- layout pass uses the same policy. Monospaced text uses its metrics directly;+-- proportional text uses the host's shaping-aware measurement callback.+data TextMeasurer = TextMeasurer+  { tmMetrics :: !FontMetrics+  , tmVariant :: !FontVariant+  , tmFontKey :: !Int+  , tmHostLine :: Text -> IO (Float, Float)+  }++-- | How node @idx@, of type @nt@ and style index @nodeSi@, measures its+-- text: in the font its style packs ('nodeFontBits'), else in its font size+-- in the default face, as+-- 'NanoUI.Internal.Frame.Node.resolveFontFor' draws them.+nodeMeasurer :: SolveEnv -> NodeIdx -> NodeType -> Word64 -> IO TextMeasurer+nodeMeasurer SolveEnv {seArena = na, seMs = ms} idx nt nodeSi = do+  let si = nodeFontBits nt nodeSi+  rawSize <- getNodeFontSize na idx+  let !size = resolveFontSize (msFontSize ms) rawSize+      variant = textNodeFontVariant si+      weight = textNodeFontWeight si+      style = textNodeFontStyle si+      tabular = textNodeFontTabular si+  (metrics0, measureLine0) <-+    if isDefaultNodeFont size weight style variant+      then pure (if variant == FontMono then msMonoFm ms else msFm ms, msMeasure ms)+      else msResolveFont ms size weight style variant+  let !metrics = if tabular then tabularFontMetrics metrics0 else metrics0+      measureLine = if tabular then measureTextIO metrics else measureLine0+  pure (TextMeasurer metrics variant (textNodeFontKey size si) measureLine)++-- Keep these operations as inline functions rather than allocating two+-- closures for every resolved node, including nodes that never wrap.+{-# INLINE measureFontLine #-}+measureFontLine :: TextMeasurer -> Text -> IO (Float, Float)+measureFontLine TextMeasurer {tmMetrics = metrics, tmVariant = variant, tmHostLine = hostLine} text+  | variant == FontMono = measureTextIO metrics text+  | otherwise = hostLine text++{-# INLINE measureFontWrapped #-}+measureFontWrapped :: SolveEnv -> TextMeasurer -> Text -> Float -> IO (Float, Float)+measureFontWrapped env TextMeasurer {tmMetrics = metrics, tmVariant = variant, tmFontKey = font, tmHostLine = hostLine} text width =+  wrapMeasure metrics width <$> msWrap (seMs env) font lineW text width+  where+    lineW+      | variant == FontMono = lineWidthIO metrics+      | otherwise = fmap fst . hostLine++-- | A measured text node: whether it wrapped, its content size, and the line+-- height of its font.+data TextBox = TextBox+  { tbWrapped :: !Bool+  , tbW :: !Float+  , tbH :: !Float+  , tbLineH :: !Float+  }++-- | Measure a text node's content for the width @outerW@. The text wraps at+-- @outerW@ minus its label inset ('tableStripeInset'), as paint wraps it,+-- when it has explicit newlines, or when @shouldWrap outerW lineW@ holds for+-- its single-line width.+measureTextNodeAt :: SolveEnv -> NodeIdx -> Text -> Float -> (Float -> Float -> Bool) -> IO TextBox+measureTextNodeAt env@SolveEnv {seArena = na, seArrays = a} idx txt outerW shouldWrap = do+  si <- getStyleIdx na idx+  measurer@TextMeasurer {tmMetrics = textFm} <- nodeMeasurer env idx NodeText si+  let wrapW = max 0 (outerW - 2 * tableStripeInset si)+      lineH = fmLineHeight textFm+      wrapped = do+        (tw, th) <- memoizeWidth na (naArrWrapMemo a) idx wrapW (measureFontWrapped env measurer txt wrapW)+        pure (TextBox True tw th lineH)+  if T.any (== '\n') txt+    then wrapped+    else do+      (tw0, th0) <- measureFontLine measurer txt+      if shouldWrap (max 0 outerW) tw0 then wrapped else pure (TextBox False tw0 th0 lineH)++-- | Height of text node @idx@ at width @w@, clamped to @hAx@. Text wraps at+-- newlines, and at @w@ when @allowed@ and its line overflows a positive @w@.+-- Text that does not wrap returns @fallback@, unless its height is fit and+-- it may wrap at a positive @w@, where paint wraps it ('textWrapCap'): the+-- measure may have wrapped it narrower, at an ancestor's cap. Empty text,+-- which measured one line tall, returns @fallback@.+{-# INLINE textHeightAt #-}+textHeightAt :: SolveEnv -> NodeIdx -> AxisSizing -> Float -> Bool -> Float -> IO Float+textHeightAt env !idx (AxisSizing hTag _ minH maxH) !w allowed !fallback = do+  txt <- getText (seArena env) idx+  if T.null txt+    then pure fallback+    else do+      si <- getStyleIdx (seArena env) idx+      let allow = allowed && not (textNodeSingleLine si)+      TextBox {tbWrapped, tbH, tbLineH} <-+        measureTextNodeAt env idx txt w (\wrapW lineW -> allow && wrapW + 0.5 < lineW && wrapW > 0)+      pure (if tbWrapped || (allow && hTag == SizingFit && w > 0) then clamp minH maxH (max tbLineH tbH) else fallback)++measurePass :: SolveEnv -> Int -> IO ()+measurePass env count = do+  -- Which nodes keep their height at any width ('markSteadyHeight'), before+  -- any is measured: a container's measure reads its own mark. Children+  -- follow their parent in the arena, so walking down from the last node+  -- reaches every child before its parent. A pass of its own: marking inside+  -- the measure loop below allocated a box per node.+  let steadyPass !i = when (i >= 0) (markSteadyHeight env i >> steadyPass (i - 1))+  steadyPass (count - 1)+  case seCache env of+    Nothing ->+      let go !idx = when (idx >= 0) (measureNode env idx >> recordMeasured env idx >> go (idx - 1))+       in go (count - 1)+    Just lc -> do+      -- Per node, 1 once some child came out a different size than the+      -- capture recorded for it, and 2 when a drawing with a custom measure+      -- is below it, so the node cannot take its captured size.+      moved <- newZeroedPrimArray count :: IO (IOArr Word8)+      let go !idx = when (idx >= 0) (measureCachedNode env lc moved idx >> go (idx - 1))+      go (count - 1)++-- | Measure node @idx@ in a solve with a layout cache, or put back its+-- captured size ('restoreMeasured'), and record for its parent whether it+-- came out its captured size. Children follow their parent in the arena,+-- so 'measurePass' walks down from the last node and measures every child+-- before its parent.+measureCachedNode :: SolveEnv -> LayoutCache -> IOArr Word8 -> NodeIdx -> IO ()+measureCachedNode env lc moved !idx = do+  let a = seArrays env+  hit <-+    if idx < lcCount lc+      then (==) <$> readPrimArray (naArrSubHash a) idx <*> readPrimArray (lcSub lc) idx+      else pure False+  restored <- restoreMeasured env lc moved hit idx+  unless restored (measureNode env idx)+  (w, h) <- recordMeasured env idx+  same <-+    if restored || idx >= lcCount lc+      then pure restored+      else do+        cw <- readPrimArray (lcMeasured lc) (idx * 2)+        ch <- readPrimArray (lcMeasured lc) (idx * 2 + 1)+        pure (cw == w && ch == h)+  -- 2 marks a node above a drawing with a custom measure: its measured+  -- height runs that measure at its children's widths+  -- ('recomputeFitHeightAtWidth'), which the cache does not record, so+  -- it measures again however its children came out.+  nt <- readTagEnum a idx TagNodeType+  aboveMeasure <-+    if nt == NodeDrawing+      then getWidgetId (seArena env) idx >>= fmap isJust . msLookupMeasure (seMs env)+      else (== 2) <$> readPrimArray moved idx+  p <- readTree a idx TreeParent+  when (p >= 0) $ do+    m <- readPrimArray moved p+    if aboveMeasure+      then writePrimArray moved p 2+      else when (not same && m == 0) (writePrimArray moved p 1)+  -- The captured solve placed the subtree as this one will when the+  -- node's key hit and it came out its captured size, as did every node+  -- below it, and it holds no drawing, whose custom measure may return a+  -- different size with nothing in the arena changed.+  when (seRecordPos env) $ do+    let spans = naArrSpans a+    end <- if hit && same && nt /= NodeDrawing then subtreeEnd a spans idx else pure (-1)+    writePrimArray spans idx end++-- | Put back the measured size the captured solve recorded for a node, when+-- that solve measured it the same way: its restore key+-- ('computeSubtreeHashes', over its own, its ancestors' and its descendants'+-- inputs) matches the capture's (@hit@), and no child came out a different+-- size.+-- 'False' when the node must be measured. Drawing nodes always measure: a+-- custom measure may read state outside the arena, and losing the hook+-- changes what the size means. Scroll containers always measure too, cheaply+-- from their children: the capture holds their content extent as the position+-- pass left it, not as measured.+{-# INLINE restoreMeasured #-}+restoreMeasured :: SolveEnv -> LayoutCache -> IOArr Word8 -> Bool -> NodeIdx -> IO Bool+restoreMeasured env lc moved hit idx+  | not hit = pure False+  | otherwise = do+      childMoved <- (/= 0) <$> readPrimArray moved idx+      nt <- readTagEnum (seArrays env) idx TagNodeType+      if childMoved || nt == NodeDrawing || isScrollNode nt+        then pure False+        else do+          w <- readPrimArray (lcMeasured lc) (idx * 2)+          h <- readPrimArray (lcMeasured lc) (idx * 2 + 1)+          setRect (seArena env) idx 0 0 w h+          pure True++-- | One past the last node of @idx@'s subtree when its children's subtrees,+-- whose ends @spans@ holds, follow it one after another, and -1 when one of+-- them has none or they do not.+subtreeEnd :: NodeArenaArrays -> IOArr Int -> NodeIdx -> IO Int+subtreeEnd a spans idx = do+  -- Children are linked last added first, so the first holds the end.+  fc <- readTree a idx TreeFirstChild+  end <- if fc < 0 then pure (idx + 1) else readPrimArray spans fc+  let go !c !next+        | c < 0 = pure (if next == idx + 1 then end else -1)+        | otherwise = do+            e <- readPrimArray spans c+            if e /= next then pure (-1) else readTree a c TreeNextSibling >>= \sib -> go sib c+  if end < 0 then pure (-1) else go fc end++-- | Record the node's measured size for the next capture, whether it was+-- just measured or restored, and return it.+{-# INLINE recordMeasured #-}+recordMeasured :: SolveEnv -> NodeIdx -> IO (Float, Float)+recordMeasured env idx = do+  Rect _ _ w h <- getNodeRect (seArena env) idx+  let ma = naArrMeasured (seArrays env)+  writePrimArray ma (idx * 2) w+  writePrimArray ma (idx * 2 + 1) h+  pure (w, h)++measureNode :: SolveEnv -> NodeIdx -> IO ()+measureNode env idx = measureContent env idx >> measureAspect (seArrays env) idx++-- | Apply a node's aspect ratio ('StyleAspect') after its content is+-- measured. A fit height becomes width / ratio, and a fit width beside a+-- fixed height becomes height * ratio, both within limits.+{-# INLINE measureAspect #-}+measureAspect :: NodeArenaArrays -> NodeIdx -> IO ()+measureAspect a idx = do+  ratio <- readStyle a idx StyleAspect+  when (ratio > 0) $ do+    wAx <- readAxisSizing a idx True+    hAx <- readAxisSizing a idx False+    case (axTag wAx, axTag hAx) of+      (_, SizingFit) -> readGeom a idx GeomW >>= \w -> writeGeom a idx GeomH (sizeWithin hAx (w / ratio))+      (SizingFit, SizingFixed) -> readGeom a idx GeomH >>= \h -> writeGeom a idx GeomW (sizeWithin wAx (h * ratio))+      _ -> pure ()++measureContent :: SolveEnv -> NodeIdx -> IO ()+measureContent env@SolveEnv {seArena = na} idx = do+  nt <- readTagEnum (seArrays env) idx TagNodeType+  -- Each is called once below, so it is inlined there.+  let container = do+        measureContainer env idx+        when (nt == NodeModal) $ setSolvedValue na idx 0+      widget = measureWidget env idx+  case nt of+    NodeText -> measureTextNode env idx+    -- Non-fixed spacers reserve the default 8px extent.+    NodeSpacer -> measureImage na idx (Just (8, 8))+    NodeSeparator -> measureSeparator na idx+    NodeScrollContainer -> measureScrollContainer env idx+    NodeImage -> getImageNode na idx >>= measureImage na idx . fmap (\n -> (inWidth n, inHeight n))+    NodeBox -> measureImage na idx Nothing+    NodeShader -> measureImage na idx Nothing+    NodeDrawing -> do+      wid <- getWidgetId na idx+      msLookupMeasure (seMs env) wid >>= maybe (measureImage na idx Nothing) (\fn -> measureCustomNode env fn idx)+    NodeContainer -> container+    NodePanel -> container+    NodeModal -> container+    NodeWindow -> container+    NodePopup -> container+    NodeButton -> widget+    NodeSlider -> widget+    NodeTextInput -> widget+    NodeTextArea -> widget+    NodeSelect -> widget+    NodeColorPicker -> widget++measureCustomNode :: SolveEnv -> CustomMeasureFn -> NodeIdx -> IO ()+measureCustomNode env@SolveEnv {seArena = na} measureFn idx = do+  wAx <- getWidthSizing na idx+  hAx <- getHeightSizing na idx+  let ((mw, mh), record) = customMeasure (msFm (seMs env)) measureFn wAx hAx+  forM_ (seMeasureLog env) $ \ref -> modifyIORef' ref (IM.insert idx record)+  setRect na idx 0 0 (sizeWithin wAx mw) (sizeWithin hAx mh)++-- | Run a node's custom measure again, as the solve ran it, and return the+-- record the layout cache keeps of the call. Layout-reuse validation compares+-- it with the solve's.+runCustomMeasure :: NodeArena -> FontMetrics -> CustomMeasureFn -> NodeIdx -> IO CustomMeasureRecord+runCustomMeasure na fm measureFn idx = do+  wAx <- getWidthSizing na idx+  hAx <- getHeightSizing na idx+  pure $! snd (customMeasure fm measureFn wAx hAx)++-- | Run a custom measure on the offered space ('offeredExtent'). Returns the+-- measured size and the call record, forced with the pair so the cache holds+-- words rather than the closure.+{-# INLINE customMeasure #-}+customMeasure ::+  FontMetrics -> CustomMeasureFn -> AxisSizing -> AxisSizing -> ((Float, Float), CustomMeasureRecord)+customMeasure fm measureFn wAx hAx =+  let aw = offeredExtent wAx+      ah = offeredExtent hAx+      (mw, mh) = measureFn fm (aw, ah)+      !aw' = castFloatToWord32 aw+      !ah' = castFloatToWord32 ah+      !mw' = castFloatToWord32 mw+      !mh' = castFloatToWord32 mh+   in ((mw, mh), (aw', ah', mw', mh'))++-- | The space a custom measure is offered along an axis: its fixed size, or+-- else its maximum when that is finite ('isBounded'), and 'noLimit' otherwise.+{-# INLINE offeredExtent #-}+offeredExtent :: AxisSizing -> Float+offeredExtent (AxisSizing tag val lo hi)+  | tag == SizingFixed = clamp lo hi val+  | otherwise = if isBounded hi then hi else noLimit++-- | The axis's fixed size or else @content@, within its limits.+{-# INLINE sizeWithin #-}+sizeWithin :: AxisSizing -> Float -> Float+sizeWithin (AxisSizing tag val lo hi) content = clamp lo hi (if tag == SizingFixed then val else content)++-- | A measured drawing's height at width @w@, within its fit height's+-- limits, or @fallback@ when its widget has no custom measure.+{-# INLINE drawingHeightAt #-}+drawingHeightAt :: SolveEnv -> NodeIdx -> Float -> AxisSizing -> Float -> IO Float+drawingHeightAt SolveEnv {seArena = na, seMs = ms} idx w hAx fallback = do+  wid <- getWidgetId na idx+  msLookupMeasure ms wid >>= \case+    Just measure -> pure (measuredHeightAt (msFm ms) measure w hAx)+    Nothing -> pure fallback++-- | The height a custom measure gives a drawing laid out at width @w@,+-- clamped to @hAx@: what the position pass sets ('drawingHeightAt').+{-# INLINE measuredHeightAt #-}+measuredHeightAt :: FontMetrics -> CustomMeasureFn -> Float -> AxisSizing -> Float+measuredHeightAt fm measure w hAx = clamp (axMin hAx) (axMax hAx) (snd (measure fm (w, offeredExtent hAx)))++-- | The width a text node that is not a row's child wraps at, from its+-- effective max width, width sizing and assigned width: 1e8 or more when+-- nothing caps it (@textNodeSpanEntry@ in the text-span collector). Text+-- whose width is not fit wraps at the width it was assigned, as the solve's+-- position pass wraps it; fit text wraps where it was measured.+textWrapCap :: Float -> SizingTag -> Float -> Float+textWrapCap effMaxW wTag w+  | wTag /= SizingFit && w > 0 = w+  | otherwise = max 0 effMaxW++-- | Find the nearest ancestor's fixed or finite maximum width, subtracting+-- accumulated horizontal padding. Returns 'noLimit' when none constrains the node.+findAncestorMaxW :: NodeArena -> NodeIdx -> IO Float+findAncestorMaxW na idx = go idx 0+  where+    go cur !padAccum = do+      p <- getParent na cur+      if p < 0+        then pure noLimit+        else do+          pad <- getPadding na p+          let padAccum' = padAccum + padL pad + padR pad+          AxisSizing pwTag pwVal pMinW pMaxW <- getWidthSizing na p+          if pwTag == SizingFixed+            then pure (max 0 (clamp pMinW pMaxW pwVal - padAccum'))+            else if isBounded pMaxW+              then pure (max 0 (pMaxW - padAccum'))+              else go p padAccum'++measureTextNode :: SolveEnv -> NodeIdx -> IO ()+measureTextNode env@SolveEnv {seArena = na} idx = do+  wAx@(AxisSizing wTag wVal minW maxW) <- getWidthSizing na idx+  hAx <- getHeightSizing na idx+  parentAssigns <- growParent na idx+  txt <- getText na idx+  si <- getStyleIdx na idx+  isRowChild <- parentIsRow na idx+  -- A fixed width wraps at itself within its limits, as placement does+  -- ('textWrapCap').+  effMaxW <-+    if wTag == SizingFixed+      then pure (clamp minW maxW wVal)+      else if isBounded maxW+        then pure maxW+        else findAncestorMaxW na idx+  let canWrap = not isRowChild && not (textNodeSingleLine si) && isBounded effMaxW+  TextBox {tbW = tw, tbH = th, tbLineH = lineH} <-+    measureTextNodeAt env idx txt effMaxW (\_ lineW -> canWrap && effMaxW + 0.5 < lineW)+  let reportedW = sizeWithin wAx (if wTag == SizingGrow && parentAssigns then 0 else tw)+  setRect na idx 0 0 reportedW (sizeWithin hAx (max lineH th))++-- | Whether a grow-width node's width is assigned from above rather than+-- reported: its parent grows, and the nearest ancestor that does not grow is+-- not a modal. A modal takes its width from what it holds, so a grow label+-- inside one still reports its natural width; otherwise the modal could never+-- widen for it and the label would wrap into more lines than the modal+-- measured. Windows keep their own width and truncate long lines instead.+growParent :: NodeArena -> NodeIdx -> IO Bool+growParent na = growParentOn na True False++-- | 'growParent' along the width with @horizontal@, else the height. When+-- @allowFixed@ is set, a direct fixed-size parent also counts as assigning the+-- size.+growParentOn :: NodeArena -> Bool -> Bool -> NodeIdx -> IO Bool+growParentOn na horizontal allowFixed idx = getParent na idx >>= go True+  where+    go isParent p+      | p < 0 = pure (not isParent)+      | otherwise = do+          pTag <- axTag <$> (if horizontal then getWidthSizing else getHeightSizing) na p+          if pTag == SizingGrow || pTag == SizingPercent+            then getParent na p >>= go False+            else if isParent+              then pure (allowFixed && pTag == SizingFixed)+              else (/= NodeModal) <$> getNodeType na p++-- | Whether a container of type @nt@ reports its minimum along an axis, with+-- @horizontal@ the width, in place of its content: it grows along the axis,+-- its minimum is explicit ('hasExplicitMin'), and its parent assigns its+-- size there ('growParentOn' or a fixed-size parent).+minAssignedOn :: NodeArena -> NodeType -> Bool -> NodeIdx -> AxisSizing -> IO Bool+minAssignedOn na nt horizontal idx (AxisSizing tag _ lo _)+  | tag == SizingGrow && hasExplicitMin lo && not (isFloatingNode nt) = growParentOn na horizontal True idx+  | otherwise = pure False++-- | Measure a node with no measurable content: an image, a box, a spacer,+-- or a drawing without its own measure. Unless fixed, it takes @natural@+-- (an image's own size, a spacer's default), else its minimum, else 32,+-- within its limits.+measureImage :: NodeArena -> NodeIdx -> Maybe (Float, Float) -> IO ()+measureImage na idx natural = do+  wAx <- getWidthSizing na idx+  hAx <- getHeightSizing na idx+  let orMin ax = if axMin ax > 0 then axMin ax else 32+      (nw, nh) = fromMaybe (orMin wAx, orMin hAx) natural+  setRect na idx 0 0 (sizeWithin wAx nw) (sizeWithin hAx nh)++measureSeparator :: NodeArena -> NodeIdx -> IO ()+measureSeparator na idx = do+  dir <- getDirection na idx+  setRect na idx 0 0 (if dir == DirRow then 1 else 20) (if dir == DirRow then 20 else 1)++-- | A label beside a box or marker: the label, @leading@ and the padding+-- @pad@ wide, and as tall as the label or the box, plus the padding.+{-# INLINE measureMarkedWidget #-}+measureMarkedWidget ::+  FontMetrics ->+  (Text -> IO (Float, Float)) ->+  Text ->+  Float ->+  (Float, Float) ->+  IO (Float, Float)+measureMarkedWidget fm measure body leading (padX, padY) = do+  (mw, mh) <- measure (if T.null body then " " else body)+  pure (mw + padX + leading, max mh (checkboxBoxSize fm) + padY)++-- | A widget's size from its content, measured in the font paint draws it+-- in ('nodeMeasurer').+measureWidget :: SolveEnv -> NodeIdx -> IO ()+measureWidget env@SolveEnv {seArena = na, seArrays = a, seMs = Measurers {msFm = baseFm}} idx = do+  nt <- readTagEnum a idx TagNodeType+  txt <- getText na idx+  si <- readStyleIdx a idx+  wAx <- readAxisSizing a idx True+  hAx <- readAxisSizing a idx False+  measurer@TextMeasurer {tmMetrics = fm} <- nodeMeasurer env idx nt si+  let measure = measureFontLine measurer+      measurePadded (padX, padY) = do+        (mw, mh) <- measure (if T.null txt then " " else txt)+        pure (mw + padX, mh + padY)+  -- The content with its padding and whatever sits beside the label.+  (rawW, rawH) <-+    case nt of+      NodeSlider -> pure (60, sliderHandleDiameter)+      NodeSelect -> do+        opts <- getOptions na idx+        let choices = if null opts then [""] else opts+            (padX, padY) = selectPadding fm+        (mw, mh) <-+          foldM+            (\(!mw, !mh) c -> (\(w, h) -> (max mw w, max mh h)) <$> measure (selectDisplayText txt c))+            (0, 0)+            choices+        pure (mw + padX + selectChevronReserve, mh + padY)+      -- Picker parts carry fixed layouts; the field grows to its square.+      NodeColorPicker -> pure (0, colorPickerSvH)+      NodeTextInput+        | hasFlag textInputFlagSelectable si ->+            measure (if T.null txt then " " else txt)+        -- Numeric field: a short editable box and its stepper.+        | hasFlag textInputFlagNumeric si ->+            pure (56 + numericStepperW, textInputFieldHeight fm)+        -- Caption-less search box: single row tall, icons counted in the+        -- width budget. Paint sizes the icons by the base font.+        | hasFlag textInputFlagSearch si -> do+            (lw, _) <- measure (if T.null txt then " " else txt)+            pure (max textInputMinWidth lw + searchInputReserveW baseFm, textInputFieldHeight fm)+        | otherwise -> do+            pw <- if T.null txt then pure 0 else fst <$> measure txt+            pure (max textInputMinWidth pw, textInputFieldHeight fm)+      -- A text area resolves its own font as it draws ('resolveTextAreaFont').+      NodeTextArea -> pure (textInputMinWidth, max 96 (textInputFieldHeight baseFm * 4))+      NodeButton -> case buttonKindOf si of+        ButtonChoice ->+          measureMarkedWidget fm measure txt (checkboxLeading fm) (0, 0)+        ButtonRow -> do+          let (depth, _, _) = treeDecodeStyle si+          measureMarkedWidget fm measure txt (treeRowLeading fm depth) (treeItemPadding fm)+        bkind ->+          measurePadded $ case bkind of+            ButtonTable -> (tableHeaderPadX, 0)+            ButtonTab -> (2 * tabHeaderPadX, snd (buttonPadding fm))+            -- Menu rows reserve the same gutter the text-field context+            -- menu paints (outer pad + item pad on each side of the+            -- label), so the generic popup panel sizes identically.+            ButtonMenu -> (2 * (menuOuterPad + menuItemPadX), snd (buttonPadding fm))+            _ -> buttonPadding fm+      -- 'measureContent' sends only widgets here, and decides per node+      -- type which ones; another widget is measured as a label with the+      -- widget padding.+      _ -> measurePadded (widgetPadding fm)+  -- A widget's children are its adornments ('measureAdorned').+  kids <- readTree a idx TreeFirstChild+  (w, h) <- if kids < 0 then pure (rawW, rawH) else measureAdorned env measurer idx nt si txt rawW rawH+  setRect na idx 0 0 (sizeWithin wAx w) (sizeWithin hAx h)++-- | The size of a button or text field with adornments ('adornRows'), from+-- its size without them, @rawW@ by @rawH@. A field widens by each row and a+-- gap. A button fits one group ('adornedButtonGroup'), padded as a label+-- except an icon alone, which the vertical padding squares.+measureAdorned :: SolveEnv -> TextMeasurer -> NodeIdx -> NodeType -> Word64 -> Text -> Float -> Float -> IO (Float, Float)+measureAdorned SolveEnv {seArena = na, seArrays = a} measurer@TextMeasurer {tmMetrics = fm} idx nt si txt rawW rawH = do+  gap <- readStyle a idx StyleGap+  rows@(AdornRows li lw ti tw rowH) <- adornRows na idx+  case nt of+    NodeTextInput ->+      let sides = fromIntegral (fromEnum (li >= 0) + fromEnum (ti >= 0))+       in pure (rawW + lw + tw + gap * sides, max rawH (rowH + rawH - fmLineHeight fm))+    -- A text field widens by its adornments; every other widget fits them+    -- in one group with its label.+    _ -> do+      (labelW, groupW) <- adornedButtonGroup measurer txt gap rows+      let kind = if nt == NodeButton then buttonKindOf si else ButtonPlain+          (padX, padY)+            | kind == ButtonTab = (2 * tabHeaderPadX, snd (buttonPadding fm))+            | otherwise = buttonPadding fm+          sidePad = if labelW > 0 || kind == ButtonContent then padX else padY+      pure (groupW + sidePad, max rawH (rowH + padY))++-- | A button's label width, in the font paint draws it in (0 without a+-- label), and the width of the group the label and its adornment rows make,+-- the node's gap apart.+adornedButtonGroup :: TextMeasurer -> Text -> Float -> AdornRows -> IO (Float, Float)+adornedButtonGroup measurer txt gap (AdornRows li lw ti tw _) = do+  labelW <- if T.null txt then pure 0 else fst <$> measureFontLine measurer txt+  let pieces = fromEnum (li >= 0) + fromEnum (labelW > 0) + fromEnum (ti >= 0)+  pure (labelW, lw + labelW + tw + gap * fromIntegral (max 0 (pieces - 1)))++-- | How a container lays out its flow children: in a grid, as layers, or+-- in lines along its direction ('TagDirection') that wrap or not. Grid+-- columns ('TreeGridCols' above 0, or 'StyleGridMinColW' above 0) take+-- precedence over the 'TagFlow'.+--+-- The constructors carry no fields, so choosing one allocates nothing even+-- where GHC passes it to a join point; a grid reads its columns with+-- 'readGridColumns'. The direction stays a separate case, so that each pass+-- calls its wrap or line layout from one site and GHC still inlines it.+data ContainerKind+  = KGrid+  | KLayered+  | KWrap+  | KLine++-- | Container @idx@'s 'ContainerKind'. The measure and position passes+-- branch on it, so a new layout mode is a constructor that+-- @-Wincomplete-patterns@ makes each of them handle.+{-# INLINE readContainerKind #-}+readContainerKind :: NodeArenaArrays -> NodeIdx -> IO ContainerKind+readContainerKind a idx = do+  gCols <- readTree a idx TreeGridCols+  minColW <- readStyle a idx StyleGridMinColW+  flow <- readTagEnum a idx TagFlow+  pure $+    if gCols > 0 || minColW > 0+      then KGrid+      else case flow of+        Layered -> KLayered+        Wrap -> KWrap+        Line -> KLine++-- | A grid container's column count ('TreeGridCols', 0 to pick it by width)+-- and minimum column width ('StyleGridMinColW').+{-# INLINE readGridColumns #-}+readGridColumns :: NodeArenaArrays -> NodeIdx -> IO (Int, Float)+readGridColumns a idx = (,) <$> readTree a idx TreeGridCols <*> readStyle a idx StyleGridMinColW++measureContainer :: SolveEnv -> NodeIdx -> IO ()+measureContainer env@SolveEnv {seArena = na, seArrays = a} idx = do+  (pad, gap, dir) <- containerFlow a idx+  -- Read here rather than in the grid branch: read there, they made the+  -- grow profile scene, which has no grid, allocate 0.005% more.+  (gCols, minColW) <- readGridColumns a idx+  kind <- readContainerKind a idx+  wAx@(AxisSizing wTag _ _ _) <- readAxisSizing a idx True+  hAx <- readAxisSizing a idx False+  nt <- readTagEnum a idx TagNodeType+  let chrome = isChromeColumn nt dir+      padX = padL pad + padR pad+      padY = padT pad + padB pad+      -- The room inside the fixed size, or else inside the maximum.+      inner (AxisSizing tag val lo hi) p = max 0 ((if tag == SizingFixed then clamp lo hi val else hi) - p)+      innerMaxW = inner wAx padX+      innerAvailH = inner hAx padY+  (contentW, contentH) <- case kind of+    KGrid -> measureGridScratch env idx wTag gCols minColW innerMaxW innerAvailH gap+    -- Layered children make a box as large as the largest on each axis.+    KLayered -> do+      let step (FlowAcc count maxW maxH) ci = do+            Rect _ _ w h <- getNodeRect na ci+            pure (FlowAcc (count + 1) (max maxW w) (max maxH h))+      FlowAcc _ layersW layersH <- foldFlowChildrenM na idx step (FlowAcc 0 0 0)+      pure (layersW, layersH)+    KWrap -> measureWrap env idx dir gap (if dir == DirRow then innerMaxW else innerAvailH)+    KLine+      | dir == DirColumn && chrome -> do+          n <- loadChildrenScratch na idx (flowChildSize env False innerMaxW innerAvailH)+          foldChromeColumnScratch na n gap+      | otherwise -> foldChildDimsFromParent env idx dir gap+  minAssignedW <- minAssignedOn na nt True idx wAx+  minAssignedH <- minAssignedOn na nt False idx hAx+  let h = sizeWithin hAx (if minAssignedH then 0 else contentH + padY)+  -- A window or modal that fits its width to its content leaves room for its+  -- body's scrollbar when the body will scroll, or the bar's gutter narrows+  -- the content below its measured width and clips its right edge.+  bodyGutter <-+    if chrome && wTag /= SizingFixed+      then floatingBodyGutter na idx (contentH + padY - h)+      else pure 0+  let measuredW = sizeWithin wAx (if minAssignedW then 0 else contentW + padX + bodyGutter)+  setRect na idx 0 0 measuredW h+  -- A parent lays a container out at the width it measured at without+  -- refitting its height ('flowChildSize', 'rowChildHeightAt'). Its children+  -- measured at widths of their own (an ancestor's cap, a grid cell unknown+  -- here, none for a filling label), so the measured height is the refit at+  -- the measured width, the height placement gives it there.+  steady <- readTagEnum a idx TagSteadyHeight+  when (axTag hAx == SizingFit && (nt == NodeContainer || nt == NodePanel) && not minAssignedH && not steady) $+    recomputeFitHeightAtWidth env idx measuredW >>= setRect na idx 0 0 measuredW++-- | Width the scrollbar of window or modal @idx@'s body takes when the+-- window is @overflow@ shorter than its content.+floatingBodyGutter :: NodeArena -> NodeIdx -> Float -> IO Float+floatingBodyGutter na idx overflow = do+  mBody <- windowBodyScroller na idx+  case mBody of+    Nothing -> pure 0+    Just ci -> do+      si <- getStyleIdx na ci+      dir <- getDirection na ci+      if isScrollStyle2D si || dir /= DirColumn+        then pure 0+        else do+          pad <- getPadding na ci+          Rect _ _ _ bodyH <- getNodeRect na ci+          contentH <- getNodeValue na ci+          let innerH = bodyH - padT pad - padB pad - max 0 overflow+          pure (scrollAxisGutter (scrollPolicyY (decodeScrollConfig si)) ScrollBarWindow (padR pad) contentH innerH)++-- | The scroll container holding window or modal @idx@'s body.+windowBodyScroller :: NodeArena -> NodeIdx -> IO (Maybe NodeIdx)+windowBodyScroller na idx =+  firstChildJustM na idx $ \ci -> do+    nt <- getNodeType na ci+    if nt /= NodeScrollContainer+      then pure Nothing+      else (\slot -> ci <$ guard (slot == ScrollBarWindow)) <$> scrollBarSlotOf na ci++measureScrollContainer :: SolveEnv -> NodeIdx -> IO ()+measureScrollContainer env@SolveEnv {seArena = na, seArrays = a} idx = do+  (pad, gap, dir) <- containerFlow a idx+  let padX = padL pad + padR pad+      padY = padT pad + padB pad+  si <- getStyleIdx na idx+  wAx@(AxisSizing wTag wVal wMin wMax) <- getWidthSizing na idx+  hAx@(AxisSizing hTag hVal hMin hMax) <- getHeightSizing na idx+  parent <- getParent na idx+  -- A modal's body scrolls like a window's: its bar sits just inside the+  -- panel's edge, out in the panel padding.+  isWin <-+    if parent < 0 then pure False else (`elem` [NodeWindow, NodeModal]) <$> getNodeType na parent+  inPanel <- hasPanelAncestor na parent+  let slot = classifyScrollBar isWin (wTag == SizingGrow && hTag == SizingGrow && not inPanel)+      cfg = decodeScrollConfig si+      vertical = not (isScrollStyle2D si) && dir == DirColumn+      fitsContent = wTag == SizingFit || wTag == SizingShrink+  writeTagEnum a idx TagScrollBarSlot slot+  -- A vertical scroller measures its children at the width it lays them out+  -- at, so what wraps there counts at its wrapped height. A column refits its+  -- children when it places them and grows to them; a scroller does not grow,+  -- so its measured height has to hold them already. The width is its own,+  -- or else the most its nearest bounded ancestor leaves it+  -- ('findAncestorMaxW'), and no more than its content when it fits its+  -- width to that. The bar's gutter comes off it when the content at its+  -- full width overflows the scroller's own height cap. A child with a+  -- percentage height keeps its measured height, since the scroller's height+  -- is not known yet.+  bound <-+    if not vertical+      then pure noLimit+      else if wTag == SizingFixed+        then pure (clamp wMin wMax wVal)+        else (\w -> min wMax (if wTag == SizingPercent then w * wVal / 100 else w)) <$> findAncestorMaxW na idx+  (contentW, contentH) <-+    if isUnbounded bound && not (vertical && fitsContent)+      then foldChildDimsFromParent env idx dir gap+      else do+        naturalW <- if fitsContent then fst <$> foldChildDimsFromParent env idx dir gap else pure noLimit+        let viewAt gutter = min naturalW (max 0 (bound - padX - gutter))+            stackAt viewW = do+              let step (FlowAcc count maxW sumH) ci = do+                    pct <- (== SizingPercent) . axTag <$> getHeightSizing na ci+                    (w, h) <-+                      if pct+                        then (\(Rect _ _ mw mh) -> (mw, mh)) <$> getNodeRect na ci+                        else flowChildSize env True viewW 0 ci+                    pure (FlowAcc (count + 1) (max maxW w) (sumH + h))+              FlowAcc count maxW sumH <- foldFlowChildrenM na idx step (FlowAcc 0 0 0)+              pure (maxW, sumH + gap * fromIntegral (max 0 (count - 1)))+        full@(_, fullH) <- stackAt (viewAt 0)+        let capH = (if hTag == SizingFixed then clamp hMin hMax hVal else hMax) - padY+            narrowed = viewAt (scrollAxisGutter (scrollPolicyY cfg) slot (padR pad) fullH capH)+        if narrowed /= viewAt 0 then stackAt narrowed else pure full+  -- A width fit to the content makes room for the bar when the content+  -- overflows the scroller's own height, fixed or capped. When a scroller's+  -- size along a scrollable axis is assigned from above with an explicit+  -- minimum ('minAssignedOn', like 'measureContainer'), report its padding+  -- floor within its limits so sibling grow panes share space instead of+  -- being pushed aside by the unclipped scroll content.+  minAssignedW <-+    if isScrollStyle2D si || dir == DirRow+      then minAssignedOn na NodeScrollContainer True idx wAx+      else pure False+  minAssignedH <-+    if isScrollStyle2D si || dir == DirColumn+      then minAssignedOn na NodeScrollContainer False idx hAx+      else pure False+  let h = sizeWithin hAx (if minAssignedH then padY else contentH + padY)+      fitGutterW+        | not vertical || wTag == SizingGrow || wTag == SizingFixed = 0+        | otherwise = scrollAxisGutter (scrollPolicyY cfg) slot (padR pad) contentH (h - padY)+      w = sizeWithin wAx (if minAssignedW then padX else contentW + padX + fitGutterW)+  if isScrollStyle2D si+    then setSolvedValue na idx contentH >> setScrollContentW na idx contentW+    else setSolvedValue na idx (if dir == DirColumn then contentH else contentW)+  setRect na idx 0 0 w h++foldChildDimsFromParent :: SolveEnv -> NodeIdx -> DirTag -> Float -> IO (Float, Float)+foldChildDimsFromParent env@SolveEnv {seArena = na} idx dir gap = do+  -- Along the axis the children's sizes add up, and across it the largest counts.+  FlowAcc count along across <- foldFlowChildrenM na idx step (FlowAcc 0 0 0)+  let gaps = gap * fromIntegral (max 0 (count - 1))+  case dir of+    DirColumn -> pure (across, along + gaps)+    DirRow -> do+      -- A row's baseline-aligned children stand on one line, so together they+      -- are as tall as the most room any takes above it plus the most any takes+      -- below. Skip the second pass when neither the row nor any child uses+      -- baseline alignment.+      let !a = seArrays env+      pItems <- readItemsAlign a idx+      hasBase <- if pItems == ItemsBaseline then pure True else hasBaselineChild a idx+      if not hasBase+        then pure (along + gaps, across)+        else do+          FlowAcc _ above below <- foldFlowChildrenM na idx (baselineStep pItems) (FlowAcc 0 0 0)+          pure (along + gaps, max across (above + below))+  where+    step (FlowAcc count along across) ci = do+      Rect _ _ w h <- getNodeRect na ci+      pure $ case dir of+        DirRow -> FlowAcc (count + 1) (along + w) (max across h)+        DirColumn -> FlowAcc (count + 1) (along + h) (max across w)+    baselineStep pItems (FlowAcc _ above below) ci = do+      Rect _ _ _ h <- getNodeRect na ci+      (above', below') <- accumulateBaseline env pItems (above, below) ci h+      pure (FlowAcc 0 above' below')++-- | Whether child @ci@ participates in row baseline alignment: its effective+-- vertical alignment is 'AlignBaseline' and it does not grow vertically.+{-# INLINE isBaselineChild #-}+isBaselineChild :: NodeArenaArrays -> ItemsAlign -> NodeIdx -> IO Bool+isBaselineChild a pItems ci = do+  ay <- effectiveAlignY a pItems ci+  if ay /= AlignBaseline then pure False else (/= SizingGrow) <$> readTagEnum a ci TagHSizing++-- | Fold a row child @(ci, h)@ into the @(maxAscent, maxDescent)@ baseline+-- envelope when it aligns to the baseline and does not grow vertically.+{-# INLINE accumulateBaseline #-}+accumulateBaseline :: SolveEnv -> ItemsAlign -> (Float, Float) -> NodeIdx -> Float -> IO (Float, Float)+accumulateBaseline env@SolveEnv {seArrays = a} pItems acc@(!above, !below) ci h = do+  ok <- isBaselineChild a pItems ci+  if not ok+    then pure acc+    else (\b -> (max above b, max below (h - b))) <$> childBaseline env ci h++-- | Content size of wrapping container @idx@ ('Wrap'), with lines along+-- @dir@ at most @bound@ long ('wrapExtent').+--+-- A row with no bound of its own (1e8 or more) wraps at its nearest bounded+-- ancestor's width, like text ('findAncestorMaxW'), or stays on one line if+-- there is none. A grow row whose width comes from its parent ('growParent')+-- reports only its widest child's width and one line's height, then wraps+-- at the width it gets: a column refits its height+-- ('recomputeFitHeightAtWidth'); elsewhere it grows to its lines after+-- placement ('adjustFitHeight').+measureWrap :: SolveEnv -> NodeIdx -> DirTag -> Float -> Float -> IO (Float, Float)+measureWrap env@SolveEnv {seArena = na} idx dir gap bound = do+  limit <-+    if dir == DirRow && isUnbounded bound+      then do+        pad <- getPadding na idx+        (\w -> max 0 (w - padL pad - padR pad)) <$> findAncestorMaxW na idx+      else pure bound+  kids <- sizedWrapKids na idx dir limit+  (along, across) <- wrapExtentWith env idx dir gap limit kids (wrapLineCross env dir)+  wTag <- axTag <$> getWidthSizing na idx+  assigned <-+    if dir == DirRow && isUnbounded limit && wTag == SizingGrow then growParent na idx else pure False+  let widest = foldl' (\m (_, (w, _)) -> max m w) 0 kids+  pure (if dir == DirRow then (if assigned then widest else along, across) else (across, along))++-- | Flow children of wrapping container @idx@ with percentage widths resolved+-- against @limit@ for wrapping rows, as placement resolves them ('positionWrap').+sizedWrapKids :: NodeArena -> NodeIdx -> DirTag -> Float -> IO [(NodeIdx, (Float, Float))]+sizedWrapKids na idx dir limit = mapM sized =<< flowChildrenInOrder na idx+  where+    sized ci = do+      Rect _ _ w h <- getNodeRect na ci+      w' <- if dir == DirRow then (\ax -> percentOr ax limit w) <$> getWidthSizing na ci else pure w+      pure (ci, (w', h))++-- | Extent of @kids@ broken into lines no longer than @limit@ ('wrapLines'):+-- the longest line's length, and the sum of the lines' cross sizes (measured+-- by @lineCross@) plus the line gaps.+{-# INLINE wrapExtentWith #-}+wrapExtentWith ::+  SolveEnv ->+  NodeIdx ->+  DirTag ->+  Float ->+  Float ->+  [(NodeIdx, (Float, Float))] ->+  (ItemsAlign -> [(NodeIdx, (Float, Float))] -> IO Float) ->+  IO (Float, Float)+wrapExtentWith env idx dir gap limit kids lineCross = do+  lineGap <- readStyle (seArrays env) idx StyleLineGap+  pItems <- readItemsAlign (seArrays env) idx+  let along (_, (w, h)) = if dir == DirRow then w else h+      lns = wrapLines limit gap along kids+      lineLength l = sum (map along l) + gap * fromIntegral (length l - 1)+  crosses <- mapM (lineCross pItems) lns+  pure (foldl' max 0 (map lineLength lns), sum crosses + lineGap * fromIntegral (max 0 (length lns - 1)))++-- | A wrap line's cross size: its largest child's. In a row it is at least+-- the tallest ascent plus the deepest descent among baseline-aligned+-- children, as in 'foldChildDimsFromParent'.+wrapLineCross :: SolveEnv -> DirTag -> ItemsAlign -> [(NodeIdx, (Float, Float))] -> IO Float+wrapLineCross env dir pItems line = do+  let across = foldl' (\m (_, (w, h)) -> max m (if dir == DirRow then h else w)) 0 line+  if dir /= DirRow+    then pure across+    else (\(above, below) -> max across (above + below)) <$> foldM (\acc (ci, (_, h)) -> accumulateBaseline env pItems acc ci h) (0, 0) line++-- | Content size of grid @idx@ with @gCols@ columns, or else as many+-- @minColW@ wide as fit in @innerMaxW@.+--+-- Without a bound, columns of @minColW@ come out one, and the grid reports+-- one column's width. When its width is assigned from above instead (a grow+-- grid whose parent grows, 'growParent', or a percentage), it reports one+-- row's height too, as a wrapping row does ('measureWrap'): the width it+-- gets decides its rows. A column refits its height at that width+-- ('recomputeFitHeightAtWidth'), and elsewhere it grows to its rows after+-- placement ('adjustFitHeight'). Every cell stacked would be the least+-- height its fit parents take ('positionNode'), a gap below a grid of+-- several columns.+measureGridScratch ::+  SolveEnv ->+  NodeIdx ->+  SizingTag ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  IO (Float, Float)+measureGridScratch env idx wTag gCols minColW innerMaxW innerAvailH gap = do+  let bounded = isBounded innerMaxW+      cols = gridColumnCount gCols minColW (if bounded then innerMaxW else 0) gap+      colW = gridColWidth innerMaxW cols gap+  n <- loadChildrenScratch (seArena env) idx (flowChildSize env bounded (if bounded then colW else innerMaxW) innerAvailH)+  if n <= 0+    then pure (0, 0)+    else do+      FlexScratch {fsW = wArr, fsH = hArr} <- readIORef (naScratch (seArena env))+      assigned <-+        if bounded || gCols > 0+          then pure False+          else if wTag == SizingGrow then growParent (seArena env) idx else pure (wTag == SizingPercent)+      let rowCols = if assigned then n else cols+          numRows = (n + rowCols - 1) `quot` rowCols+      totalH <- foldUpTo numRows (\t r -> (t +) <$> gridRowHeight hArr n rowCols r) 0+      let contentH = totalH + gap * fromIntegral (max 0 (numRows - 1))+      contentW <-+        if innerMaxW > 0 && isBounded innerMaxW+          then pure innerMaxW+          else if minColW > 0+            then pure (fromIntegral cols * minColW + gap * fromIntegral (max 0 (cols - 1)))+            else do+              maxChildW <- foldUpTo n (\m i -> max m <$> readPrimArray wArr i) 0+              pure (fromIntegral cols * maxChildW + gap * fromIntegral (max 0 (cols - 1)))+      pure (contentW, contentH)++-- | The height node @idx@ takes when @availW@ is offered to it: text and a+-- measured drawing can wrap taller when narrower, and so can a column that+-- holds them. Memoized per node and width for the frame.+recomputeFitHeightAtWidth :: SolveEnv -> NodeIdx -> Float -> IO Float+recomputeFitHeightAtWidth env@SolveEnv {seArrays = a} idx availW =+  readTagEnum a idx TagSteadyHeight >>= \case+    -- Its measured height, at any width ('markSteadyHeight').+    True -> readPrimArray (naArrMeasured a) (idx * 2 + 1)+    False -> recomputeUnsteady env idx availW++recomputeUnsteady :: SolveEnv -> NodeIdx -> Float -> IO Float+recomputeUnsteady env@SolveEnv {seArena = na, seArrays = a} idx availW =+  fmap snd . memoizeWidth na (naArrFitMemo a) idx availW . fmap ((,) 0) $ do+    nt <- getNodeType na idx+    AxisSizing wTag wVal minW maxW <- getWidthSizing na idx+    hAx@(AxisSizing hTag _ minH maxH) <- getHeightSizing na idx+    Rect _ _ oldW oldH <- getNodeRect na idx+    let -- The width a node measured @iw@ wide takes of @avail@, as a+        -- column places it ('columnChildX'): fixed, a percentage, all of it+        -- when it grows, or else its measured width, narrowed to @avail@.+        widthOf (AxisSizing tag val lo hi) iw avail = case tag of+          SizingPercent -> avail * val / 100+          SizingFixed -> clamp lo hi val+          SizingGrow -> avail+          _ -> min iw avail+        -- Every caller offers this node a percentage already resolved, as+        -- 'childH' below does, so only a fixed width replaces the offer.+        effW' = clamp minW maxW (if wTag == SizingFixed then wVal else availW)++    ratio <- if hTag == SizingFit then readStyle a idx StyleAspect else pure 0+    minAssignedH <-+      if nt == NodeContainer || nt == NodePanel then minAssignedOn na nt False idx hAx else pure False+    let -- A container's height at this width. Called from two alternatives+        -- below, both tail calls, so it compiles to a join point.+        refit+          | hTag == SizingFixed = pure oldH+          | otherwise = do+            (pad, gap, dir) <- containerFlow a idx+            kind <- readContainerKind a idx+            let innerW = max 0 (effW' - padL pad - padR pad)+                -- A child's height when @w@ is offered to it, kept to its max width.+                childH w ci = do+                  subAx <- getWidthSizing na ci+                  Rect _ _ iw _ <- getNodeRect na ci+                  let subW = widthOf subAx iw w+                  recomputeFitHeightAtWidth env ci (if isBounded (axMax subAx) then min subW (axMax subAx) else subW)+                padded h = pure (clamp minH maxH (h + padT pad + padB pad))+            case kind of+              -- A grid stacks rows, each as tall as its tallest cell at the+              -- column width, not every cell.+              KGrid -> do+                (gCols, minColW) <- readGridColumns a idx+                let cols = gridColumnCount gCols minColW innerW gap+                    colW = gridColWidth innerW cols gap+                    rows [] = []+                    rows hs = let (r, rest) = splitAt cols hs in r : rows rest+                hs <- mapM (childH colW) =<< flowChildrenInOrder na idx+                let rowHs = map (foldl' max 0) (rows hs)+                padded (if null rowHs then 0 else sum rowHs + gap * fromIntegral (length rowHs - 1))+              -- Layers are as tall as the tallest child at this width.+              KLayered -> padded . foldl' max 0 =<< mapM (childH innerW) =<< flowChildrenInOrder na idx+              -- A wrapping row is as tall as the lines this width breaks it+              -- into, with percentages resolved against the width. A+              -- wrapping column's height does not depend on its width.+              KWrap+                | dir == DirRow -> do+                    kids <- sizedWrapKids na idx DirRow innerW+                    -- A line is as thick as its measured children+                    -- ('wrapLineCross') or what they grow to at their shares+                    -- of it, as 'positionWrap' places it.+                    let lineCross pItems l = do+                          measured <- wrapLineCross env DirRow pItems l+                          maybe measured (max measured) <$> lineHeightAt env pItems l innerW gap+                    (_, across) <- wrapExtentWith env idx DirRow gap innerW kids lineCross+                    padded across+                | otherwise -> pure oldH+              KLine+                | dir == DirRow -> rowHeightAt env idx innerW gap >>= maybe (pure oldH) padded+                | otherwise -> do+                    let step (FlowAcc count contentH _) ci = do+                          subH <- childH innerW ci+                          pure (FlowAcc (count + 1) (contentH + subH) 0)+                    FlowAcc count contentH _ <- foldFlowChildrenM na idx step (FlowAcc 0 0 0)+                    padded (if count <= 0 then 0 else contentH + gap * fromIntegral (count - 1))+    case nt of+      -- A fit height with an aspect ratio is width / ratio.+      _ | ratio > 0 -> pure (clamp minH maxH (effW' / ratio))++      NodeText+        | hTag /= SizingFixed -> do+            isRowChild <- parentIsRow na idx+            textHeightAt env idx hAx effW' (wTag /= SizingFit && not isRowChild) oldH+        | otherwise -> pure oldH++      -- A measured drawing, like wrapped text, can be taller when narrower.+      -- At the width it measured at, it keeps its measured height, as+      -- 'positionNode' does: its measure was offered no width limit there.+      NodeDrawing+        | hTag == SizingFit && abs (effW' - oldW) > 1.0e-3 -> drawingHeightAt env idx effW' hAx oldH+        | otherwise -> pure oldH++      -- A container that reports its minimum height ('minAssignedOn') is as+      -- tall as it is given, whatever it holds.+      _ | minAssignedH -> pure oldH++      NodeContainer -> refit+      NodePanel -> refit+      NodeSpacer -> pure oldH+      NodeSeparator -> pure oldH+      NodeButton -> pure oldH+      NodeSlider -> pure oldH+      NodeTextInput -> pure oldH+      NodeTextArea -> pure oldH+      NodeScrollContainer -> pure oldH+      NodeSelect -> pure oldH+      NodeModal -> pure oldH+      NodeImage -> pure oldH+      NodeWindow -> pure oldH+      NodeBox -> pure oldH+      NodeColorPicker -> pure oldH+      NodePopup -> pure oldH+      NodeShader -> pure oldH++-- | The content height of row @idx@ laid out @innerW@ wide inside its+-- padding ('lineHeightAt'), or 'Nothing' when every child keeps its+-- measured width there.+rowHeightAt :: SolveEnv -> NodeIdx -> Float -> Float -> IO (Maybe Float)+rowHeightAt env@SolveEnv {seArena = na, seArrays = a} idx innerW gap = do+  anyFlex <- foldFlowChildrenM na idx (\acc ci -> if acc then pure True else flexesAlongRow env ci) False+  if not anyFlex+    then pure Nothing+    else do+      pItems <- readItemsAlign a idx+      kids <- mapM (\ci -> (ci,) <$> flowChildSize env False innerW noLimit ci) =<< flowChildrenInOrder na idx+      lineHeightAt env pItems kids innerW gap++-- | Whether a row's child can come out another width than it measured: it+-- grows, shrinks, takes a percentage or scrolls.+flexesAlongRow :: SolveEnv -> NodeIdx -> IO Bool+flexesAlongRow SolveEnv {seArrays = a} ci = do+  tag <- axTag <$> readAxisSizing a ci True+  nt <- readTagEnum a ci TagNodeType+  steady <- readTagEnum a ci TagSteadyHeight+  pure (not steady && ((tag /= SizingFit && tag /= SizingFixed) || nt == NodeScrollContainer))++-- | The height of a line of a row's children @kids@, each with its size+-- before the sharing, laid out @avail@ wide with @gap@ between them, or+-- 'Nothing' when every child keeps its measured width there. The line+-- shares the width out as 'positionRowFromParent' and 'positionWrap' do. A+-- child given another width than it measured at takes its height at that+-- width ('recomputeFitHeightAtWidth'), a fit container no less than it+-- measured, since 'placeRowLine' offers it that. Baseline-aligned children+-- stand on one line, as in 'foldChildDimsFromParent'.+--+-- The sharing runs in a scratch of its own: a parent can ask for this height+-- while it is filling the arena's scratch with its children's sizes.+lineHeightAt :: SolveEnv -> ItemsAlign -> [(NodeIdx, (Float, Float))] -> Float -> Float -> IO (Maybe Float)+lineHeightAt env@SolveEnv {seArena = na, seArrays = a} pItems kids avail gap = do+  anyFlex <- foldM (\acc (ci, _) -> if acc then pure True else flexesAlongRow env ci) False kids+  if not anyFlex+    then pure Nothing+    else do+      let n = length kids+      saved <- readIORef (naScratch na)+      scratch@FlexScratch {fsIdx = idxArr, fsW = wArr, fsH = hArr, fsOut = outArr} <- newFlexScratch (max 1 n)+      writeIORef (naScratch na) scratch+      forM_ (zip [0 ..] kids) $ \(i, (ci, (w, h))) ->+        writePrimArray idxArr i ci >> writePrimArray wArr i w >> writePrimArray hArr i h+      distributeScratch na n avail (gap * fromIntegral (max 0 (n - 1))) True+      shares <- mapM (\i -> (,) <$> readPrimArray idxArr i <*> readPrimArray outArr i) [0 .. n - 1]+      writeIORef (naScratch na) saved+      let heightAt (!changed, hs) (ci, share) =+            rowChildHeightAt env ci share >>= \case+              Just h -> pure (True, (ci, h) : hs)+              Nothing -> (\h -> (changed, (ci, h) : hs)) <$> readGeom a ci GeomH+      (changed, hs) <- foldM heightAt (False, []) shares+      if not changed+        then pure Nothing+        else do+          let across = foldl' (\m (_, h) -> max m h) 0 hs+          (above, below) <- foldM (\acc (ci, h) -> accumulateBaseline env pItems acc ci h) (0, 0) hs+          pure (Just (max across (above + below)))++-- | The height row child @ci@ comes out when its row gives it @share@ of+-- its width, or 'Nothing' when it keeps its measured height: it keeps its+-- measured width there, or its height is fixed, a percentage or grows. Its+-- height at its new width ('recomputeFitHeightAtWidth'), and for a fit+-- container no less than it measured, since 'placeRowLine' offers it that.+rowChildHeightAt :: SolveEnv -> NodeIdx -> Float -> IO (Maybe Float)+rowChildHeightAt env@SolveEnv {seArrays = a} ci share = readTagEnum a ci TagSteadyHeight >>= \case+  True -> pure Nothing+  False -> rowChildHeightAtUnsteady env ci share++rowChildHeightAtUnsteady :: SolveEnv -> NodeIdx -> Float -> IO (Maybe Float)+rowChildHeightAtUnsteady env@SolveEnv {seArrays = a} ci share = do+  wAx <- readAxisSizing a ci True+  hTag <- axTag <$> readAxisSizing a ci False+  iw <- readGeom a ci GeomW+  -- The width 'positionNode' gives a child offered its share.+  let w = resolveSize wAx iw share+  if abs (w - iw) <= 1.0e-3 || (hTag /= SizingFit && hTag /= SizingShrink)+    then pure Nothing+    else do+      nt <- readTagEnum a ci TagNodeType+      r <- recomputeFitHeightAtWidth env ci w+      if nt == NodeContainer || nt == NodePanel+        then Just . max r <$> readGeom a ci GeomH+        else pure (Just r)++-- | Record whether node @idx@ is as tall at every width it can be laid out+-- at ('TagSteadyHeight'), once its children are recorded. Then the refits+-- ('recomputeFitHeightAtWidth', 'rowChildHeightAt') take its measured height+-- instead of working it out again. A fixed or percentage height is steady,+-- as is a node with no content that wraps: text wraps unless it is empty,+-- has no newline and is fit or a row's child ('textHeightAt'); a drawing+-- with a custom measure, an aspect ratio, a wrapping container and a grid+-- that picks its column count by width can all change height with width;+-- and a container is steady when its flow children all are.+--+-- A child that is not steady leaves 2 in its parent's column, so a+-- container need not walk its children: 'measurePass' marks every child+-- before its parent. A floating child is laid out apart from the flow, so+-- it leaves no mark.+markSteadyHeight :: SolveEnv -> NodeIdx -> IO ()+markSteadyHeight env@SolveEnv {seArena = na, seArrays = a} idx = do+  hTag <- readTagEnum a idx TagHSizing+  nt <- readTagEnum a idx TagNodeType+  ratio <- readStyle a idx StyleAspect+  let container = do+        kind <- readContainerKind a idx+        childMark <- readTagEnum a idx TagSteadyHeight+        -- Wrapping lines and a grid that picks its column count by width+        -- can change height with width.+        byWidth <- case kind of+          KGrid -> (> 0) <$> readStyle a idx StyleGridMinColW+          KLayered -> pure False+          KWrap -> pure True+          KLine -> pure False+        pure (not byWidth && childMark /= (2 :: Int))+  steady <-+    if hTag == SizingFixed || hTag == SizingPercent+      then pure True+      else if ratio > 0+        then pure False+        else case nt of+          NodeText -> do+            txt <- getText na idx+            si <- getStyleIdx na idx+            wTag <- readTagEnum a idx TagWSizing+            rowChild <- parentIsRow na idx+            pure (T.null txt || (not (T.any (== '\n') txt) && (wTag == SizingFit || rowChild || textNodeSingleLine si)))+          NodeDrawing -> not . isJust <$> (msLookupMeasure (seMs env) =<< getWidgetId na idx)+          NodeContainer -> container+          NodePanel -> container+          NodeSpacer -> pure True+          NodeSeparator -> pure True+          NodeButton -> pure True+          NodeSlider -> pure True+          NodeTextInput -> pure True+          NodeTextArea -> pure True+          NodeScrollContainer -> pure True+          NodeSelect -> pure True+          NodeModal -> pure True+          NodeImage -> pure True+          NodeWindow -> pure True+          NodeBox -> pure True+          NodeColorPicker -> pure True+          NodePopup -> pure True+          NodeShader -> pure True+  writeTagEnum a idx TagSteadyHeight steady+  unless (steady || isFloatingNode nt) $ do+    p <- readTree a idx TreeParent+    when (p >= 0) $ writeTagEnum a p TagSteadyHeight (2 :: Int)++-- | Load a parent's flow children into the flex scratch in child order, with+-- each child's (width, height) from @sizeOf@. Returns the child count.+{-# INLINE loadChildrenScratch #-}+loadChildrenScratch :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Float, Float)) -> IO Int+loadChildrenScratch na parent sizeOf = do+  cc <- arenaArrays na >>= \a -> readTree a parent TreeChildCount+  FlexScratch {fsIdx = idxArr, fsW = wArr, fsH = hArr} <- ensureScratchCapacity na cc+  -- The sibling links run from the last child to the first, so the children+  -- fill the arrays from the end. Floating children leave room at the front,+  -- which the copies close.+  let write !i ci = do+        (w, h) <- sizeOf ci+        writePrimArray idxArr i ci+        writePrimArray wArr i w+        writePrimArray hArr i h+        pure (i - 1)+  lo <- (+ 1) <$> foldFlowChildrenM na parent write (cc - 1)+  when (lo > 0) $ do+    copyMutablePrimArray idxArr 0 idxArr lo (cc - lo)+    copyMutablePrimArray wArr 0 wArr lo (cc - lo)+    copyMutablePrimArray hArr 0 hArr lo (cc - lo)+  pure (cc - lo)++-- | Scratch size of a flow child: its measured box, with percent sizing+-- resolved against the parent's inner box. With @refit@, a fit-height child+-- that the parent narrows (grow or percent width, or wider than @availW@) is+-- re-measured at the assigned width.+flowChildSize :: SolveEnv -> Bool -> Float -> Float -> NodeIdx -> IO (Float, Float)+flowChildSize env refit availW availH ci = do+  let a = seArrays env+  w <- readGeom a ci GeomW+  h <- readGeom a ci GeomH+  wAx@(AxisSizing wTag _ _ _) <- readAxisSizing a ci True+  hAx@(AxisSizing hTag _ _ _) <- readAxisSizing a ci False+  let w' = percentOr wAx availW w+  h' <-+    if refit && hTag /= SizingFixed && hTag /= SizingPercent && (wTag == SizingGrow || wTag == SizingPercent || availW < w)+      then recomputeFitHeightAtWidth env ci (if wTag == SizingPercent then w' else availW)+      else pure (percentOr hAx availH h)+  pure (w', h')++-- | A percentage of @avail@ within the axis's limits, or else @size@.+-- Ignores unbounded extents (>= 1e8) so percentage children inside fit-sized+-- modals, windows, or unbounded grids keep their measured size.+{-# INLINE percentOr #-}+percentOr :: AxisSizing -> Float -> Float -> Float+percentOr (AxisSizing tag val lo hi) avail size =+  if tag == SizingPercent && isBounded avail then clamp lo hi (avail * val / 100) else size++-- | Distance from the top of node @ci@, laid out @h@ tall, to its first+-- baseline, as in CSS:+--+-- * text: its first line's, where the text-span collector puts it. One+--   line is centered in the box, and wrapped lines start at the top. Paint+--   wraps at explicit newlines, and outside a row where the line overflows+--   'textWrapCap'.+-- * a widget with a single-line label or text (a button, select, checkbox,+--   or single-line text input): the text's baseline, which paint centers in+--   the widget.+-- * a container: the baseline its baseline-aligned children share if it is a+--   row that has some, and otherwise its first child's, offset by where+--   that child's alignment places it in a row or among layers.+-- * anything else: its bottom edge.+childBaseline :: SolveEnv -> NodeIdx -> Float -> IO Float+childBaseline env@SolveEnv {seArena = na, seArrays = a} ci h = do+  nt <- getNodeType na ci+  si <- getStyleIdx na ci+  let -- Widget labels take the node's font size in the default face.+      label = do+        fm <- tmMetrics <$> nodeMeasurer env ci nt si+        pure (textBaseline fm h)+      container = do+        kids <- flowChildrenInOrder na ci+        case kids of+          [] -> pure h+          first : _ -> do+            (pad, _, dir) <- containerFlow a ci+            cItems <- readItemsAlign a ci+            let innerH = max 0 (h - padT pad - padB pad)+                heightOf k = rectH <$> getNodeRect na k+            let foldBase !acc k = do+                  ok <- isBaselineChild a cItems k+                  if not ok+                    then pure acc+                    else do+                      b <- heightOf k >>= childBaseline env k+                      pure (Just (maybe b (max b) acc))+            mBase <- if dir == DirRow then foldM foldBase Nothing kids else pure Nothing+            (padT pad +) <$> case mBase of+              Just b -> pure b+              Nothing -> do+                fh <- heightOf first+                flow <- getFlow na ci+                ay <-+                  if dir == DirRow+                    then effectiveAlignY a cItems first+                    else if flow == Layered then readAlignY a first else pure AlignTop+                (alignY ay 0 innerH fh +) <$> childBaseline env first fh+  case nt of+    NodeText -> do+      raw <- getText na ci+      if T.null raw+        then pure h+        else do+          measurer@TextMeasurer {tmMetrics = fm} <- nodeMeasurer env ci nt si+          rowChild <- parentIsRow na ci+          let newline = T.any (== '\n') raw+          wrapped <-+            if newline || rowChild || textNodeSingleLine si+              then pure newline+              else do+                AxisSizing wTag _ _ maxW <- getWidthSizing na ci+                Rect _ _ w _ <- getNodeRect na ci+                -- Only fit text wraps at the ancestor cap ('textWrapCap').+                effMaxW <- if isBounded maxW || (wTag /= SizingFit && w > 0) then pure maxW else findAncestorMaxW na ci+                let cap = textWrapCap effMaxW wTag w+                (tw, _) <- measureFontLine measurer raw+                pure (isBounded cap && cap + 0.5 < tw)+          pure (textBaseline fm (if wrapped then fmLineHeight fm else h))+    -- A close button's cross is no label.+    NodeButton+      | buttonKindOf si == ButtonClose -> pure h+      | otherwise -> label+    NodeSelect -> label+    NodeTextInput -> label+    NodeContainer -> container+    NodeScrollContainer -> container+    NodeModal -> container+    NodePanel -> container+    NodeWindow -> container+    NodePopup -> container+    NodeSpacer -> pure h+    NodeSeparator -> pure h+    NodeSlider -> pure h+    NodeTextArea -> pure h+    NodeImage -> pure h+    NodeBox -> pure h+    NodeColorPicker -> pure h+    NodeDrawing -> pure h+    NodeShader -> pure h+  where+    textBaseline fm boxH = centeredTextY fm 0 boxH (fmLineHeight fm) + fmAscent fm++-- | Where a scroll container's bar sits, as measurement stored it. Text+-- areas and other nodes read 'ScrollBarList'.+{-# INLINE scrollBarSlotOf #-}+scrollBarSlotOf :: NodeArena -> NodeIdx -> IO ScrollBarSlot+scrollBarSlotOf na idx = arenaArrays na >>= \a -> readTagEnum a idx TagScrollBarSlot++-- | Whether @p@ or an ancestor below the nearest floating node is a panel.+hasPanelAncestor :: NodeArena -> NodeIdx -> IO Bool+hasPanelAncestor na p =+  fmap (fromMaybe False) . walkAncestors na p $ \i -> do+    nt <- getNodeType na i+    pure (if nt == NodePanel then Just True else if isFloatingNode nt then Just False else Nothing)
+ lib/NanoUI/Internal/Layout/Solve/Position.hs view
@@ -0,0 +1,744 @@+-- | Position pass, container/scroll/grid/wrap placement, and floating panels.+module NanoUI.Internal.Layout.Solve.Position+  ( positionNodeA+  , placeFloatingNodes+  , computePopupPosition+  , scrollBarSlotOf+  ) where++import Control.Monad (foldM, foldM_, unless, when, zipWithM_)+import Data.IORef (IORef, readIORef, writeIORef)+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.Maybe (fromMaybe, isJust)+import Data.Primitive.PrimArray (copyMutablePrimArray, newPrimArray, readPrimArray, writePrimArray)+import NanoUI.Internal.Font+import NanoUI.Internal.Layout.ScrollGeometry+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Layout.Solve.Flex+import NanoUI.Internal.Layout.Solve.Measure+import NanoUI.Internal.Style (AlignX (..), AlignY (..), ItemsAlign (..), Justify (..), Padding (..), lineAlignFraction, windowMargin)+import NanoUI.Internal.Types (PopupAnchor (..), PopupPlacement (..), Rect (..), V2 (..), clamp, eqRectAt, foldUpTo, forUpTo_, writeRectAt)+import NanoUI.Internal.WidgetText++-- | Place a widget's adornment rows ('adornRows'), each centred on its+-- height: a field's at its content insets, a button's either side of its+-- label in its centred group ('adornedButtonGroup').+positionAdornments :: SolveEnv -> Int -> NodeIdx -> NodeType -> Rect -> IO ()+positionAdornments env@SolveEnv {seArena = na, seArrays = a} depth idx nt (Rect x y w h) = do+  rows@(AdornRows li lw ti tw _) <- adornRows na idx+  si <- getStyleIdx na idx+  measurer <- nodeMeasurer env idx nt si+  (x0, x1) <- case nt of+    NodeTextInput -> do+      let (ix, _) = widgetContentInset (tmMetrics measurer)+      pure (x + ix, x + w - ix)+    _ -> do+      gap <- readStyle a idx StyleGap+      txt <- getText na idx+      (_, groupW) <- adornedButtonGroup measurer txt gap rows+      let x0+            | nt == NodeButton && tabLabelAtStart si = x + tabHeaderPadX+            | otherwise = alignX AlignCenter x w groupW+      pure (x0, x0 + groupW)+  let place ci cx cw = when (ci >= 0) $ do+        ch <- readGeom a ci GeomH+        positionNodeA env (depth + 1) ci (Rect cx (y + (h - ch) / 2) cw ch)+  place li x0 lw+  place ti (x1 - tw) tw++-- | Place node @idx@ and its subtree in the rect offered it. In the solve's+-- position pass, record the rect, or put the subtree back from the cache+-- when the captured solve placed it as this one would ('reusePositions').+positionNodeA ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  Rect ->+  IO ()+positionNodeA env@SolveEnv {seArrays = a} !depth !idx rect@(Rect x y w h)+  | not (seRecordPos env) = positionNode env depth idx rect+  | otherwise = do+      let offered = naArrOffered a+          !o = idx * 4+      offeredBefore <- not . isNaN <$> readPrimArray offered o+      if offeredBefore+        -- A second offer reads what the first placed, so neither is put back.+        then writePrimArray offered (o + 2) (0 / 0) >> positionNode env depth idx rect+        else do+          reused <- maybe (pure False) (\lc -> reusePositions a lc idx rect) (seCache env)+          unless reused $ writeRectAt offered o x y w h >> positionNode env depth idx rect++-- | Put back what the captured solve's position pass left in @idx@'s subtree+-- (its unsnapped rects, the rects offered its nodes and its scroll extents),+-- when the measure pass found that solve placed the subtree as this one+-- would ('naArrSpans') and it offered the node @rect@ too. 'False' when not.+reusePositions :: NodeArenaArrays -> LayoutCache -> NodeIdx -> Rect -> IO Bool+reusePositions a lc idx (Rect x y w h) = do+  end <- readPrimArray (naArrSpans a) idx+  let prev = lcOffered lc+      !o = idx * 4+  same <- if end < 0 || end > lcCount lc then pure False else eqRectAt prev o x y w h+  when same $ do+    copyMutablePrimArray (naArrOffered a) o prev o ((end - idx) * 4)+    let copyNode !i = when (i < end) $ do+          copyMutablePrimArray (naArrGeom a) (i * geomStride) (lcUnsnapped lc) (i * 4) 4+          nt <- readTagEnum a i TagNodeType+          when (isScrollNode nt) (restoreScrollExtents a lc i)+          copyNode (i + 1)+    copyNode idx+  pure same++positionNode ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  Rect ->+  IO ()+positionNode env@SolveEnv {seArena = na, seArrays = a} !depth !idx (Rect x y availW availH) = do+  wAx <- readAxisSizing a idx True+  hAx@(AxisSizing hTag _ minH maxH) <- readAxisSizing a idx False+  intrinsicW <- readGeom a idx GeomW+  intrinsicH <- readGeom a idx GeomH+  nt <- readTagEnum a idx TagNodeType+  let !w = resolveSize wAx intrinsicW availW+      !resolvedH = resolveSize hAx intrinsicH availH+  ratio <- if hTag == SizingFit then readStyle a idx StyleAspect else pure 0+  h <- case nt of+    -- A fit height with an aspect ratio follows the assigned width.+    _ | ratio > 0 -> pure (clamp minH maxH (w / ratio))+    -- Text outside a row wraps at the assigned width, before its edges snap+    -- to the pixel grid, as its parent's refit wraps it+    -- ('recomputeFitHeightAtWidth'). Paint wraps it there too ('GeomLaidW').+    NodeText | hTag /= SizingFixed -> do+      isRowChild <- parentIsRow na idx+      if isRowChild then pure resolvedH else textHeightAt env idx hAx w (axTag wAx /= SizingFit) resolvedH+    -- A fit container laid out at another width than it measured at is as+    -- tall as its content at that width, as its parent's share assumed+    -- ('flowChildSize'). The measured height can be a line taller or shorter.+    _ | (nt == NodeContainer || nt == NodePanel) && hTag == SizingFit -> do+      steady <- readTagEnum a idx TagSteadyHeight+      content <-+        if steady || abs (w - intrinsicW) <= 1.0e-3+          then pure intrinsicH+          else recomputeFitHeightAtWidth env idx w+      pure (clamp minH maxH (max content availH))+    -- A measured drawing laid out at a new width recomputes its height.+    NodeDrawing | hTag == SizingFit && w /= intrinsicW -> drawingHeightAt env idx w hAx resolvedH+    _ -> pure resolvedH+  setRect na idx x y w h+  if isContainerNode nt+    then do+      (pad, gap, dir) <- containerFlow a idx+      (if isScrollNode nt then positionScrollChildren else positionChildren)+        env depth idx dir gap pad (Rect x y w h)+    else do+      kids <- readTree a idx TreeFirstChild+      when (kids >= 0) $ positionAdornments env depth idx nt (Rect x y w h)+  when (hTag == SizingFit && ratio <= 0 && isContainerNode nt && not (isScrollNode nt)) $+    adjustFitHeight na idx minH maxH x y w++adjustFitHeight :: NodeArena -> NodeIdx -> Float -> Float -> Float -> Float -> Float -> IO ()+adjustFitHeight na idx minH maxH x y w = do+  fc <- getFirstChild na idx+  when (fc >= 0) $ do+    pad <- getPadding na idx+    let step maxB ci = do+          Rect _ subY _ subH <- getNodeRect na ci+          pure (max maxB (subY + subH))+    maxB <- foldFlowChildrenM na idx step y+    let fitH = clamp minH maxH (maxB + padB pad - y)+    Rect _ _ _ curH <- getNodeRect na idx+    -- Children sit at raw positions, so only float error separates their+    -- bottom from the measured height; the epsilon keeps that from growing+    -- every nested content-sized level.+    when (fitH > curH + 1.0e-3) $+      setRect na idx x y w fitH++positionScrollChildren ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  DirTag ->+  Float ->+  Padding ->+  Rect ->+  IO ()+positionScrollChildren env@SolveEnv {seArena = na} depth idx dir gap pad (Rect px py pw ph) = do+  si <- getStyleIdx na idx+  contentSize <- getNodeValue na idx+  slot <- scrollBarSlotOf na idx+  let is2D = isScrollStyle2D si+      cfg = decodeScrollConfig si+  contentW <- if is2D then getScrollContentW na idx else pure 0+  let vp@(Rect cx cy viewW viewH) =+        scrollNodeViewport (ScrollNode slot cfg is2D dir pad contentSize contentW) px py pw ph+  -- cx/cy and the layout box are already inside the padding. For 2D scrollers+  -- keep measured content so shrinking to the clip does not wrap table columns.+  box <-+    if is2D+      then pure (Rect cx cy (max contentW viewW) (max contentSize viewH))+      else case dir of+        DirRow -> do+          wTag <- axTag <$> getWidthSizing na idx+          pure (Rect cx cy (if wTag == SizingGrow then max contentSize viewW else contentSize) viewH)+        DirColumn -> pure vp+  -- Children line up along the scroller's direction, as they measured, and a+  -- grid layout inside a scroller makes no grid.+  case dir of+    DirRow -> positionRowFromParent env depth idx gap box+    DirColumn -> positionColumn env depth idx gap False (if is2D then Nothing else Just contentSize) cx (rectW box) box+  positionLayered env depth idx False box+  fc <- getFirstChild na idx+  when (fc >= 0) $ do+    let step (FlowAcc count maxB maxR) ci = do+          Rect subX subY subW subH <- getNodeRect na ci+          pure (FlowAcc (count + 1) (max maxB (subY + subH)) (max maxR (subX + subW)))+    -- Pinned children count too, so the scroller reaches them.+    FlowAcc _ maxB maxR <- foldPlacedChildrenM na idx step (FlowAcc 0 cy cx)+    -- Content size is measured from the content origin (px+padL, py+padT) so+    -- it compares against the padded viewport (innerW/innerH) on the same+    -- scale. Measuring from the padding-box origin double-counts the leading+    -- padding and makes a child that exactly fills the viewport look+    -- padX/padY bigger, surfacing a phantom scrollbar on padded scrollers.+    -- The trailing padding is excluded here too (so it cannot+    -- surface a bar by itself); scrollAxisRange adds it back into the+    -- reachable range once an axis genuinely overflows, so scrolling to the+    -- end still reveals it.+    let actualContentH = maxB - py - padT pad+        actualContentW = maxR - px - padL pad+        raise get set v = get na idx >>= \old -> set na idx (max old v)+    if isScrollStyle2D si+      then do+        raise getNodeValue setSolvedValue actualContentH+        raise getScrollContentW setScrollContentW actualContentW+      else raise getNodeValue setSolvedValue $+        case dir of DirColumn -> actualContentH; DirRow -> actualContentW++-- | Left edge of column child @ci@ in a column of width @cw@ at @cx@, and the+-- width the column offers it: all of @cw@, or a percentage's share of it.+-- Grow children already take the full width; alignment is for content+-- narrower than the column, not for shifting a full-width box past it. A+-- child is aligned at its resolved width, so text measured wider than the+-- column wraps to it instead of being pushed past the edge.+{-# INLINE columnChildX #-}+columnChildX :: NodeArena -> ItemsAlign -> NodeIdx -> Float -> Float -> IO (Float, Float)+columnChildX na pItems ci cx cw = do+  wAx <- getWidthSizing na ci+  if axTag wAx == SizingGrow+    then pure (cx, cw)+    else do+      a <- arenaArrays na+      Rect _ _ iw _ <- getNodeRect na ci+      ax <- effectiveAlignX a pItems ci+      let !offer = percentOr wAx cw cw+          !x = alignX ax cx cw (resolveSize wAx iw offer)+      pure (x, offer)++positionChildren ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  DirTag ->+  Float ->+  Padding ->+  Rect ->+  IO ()+positionChildren env@SolveEnv {seArrays = a} depth idx dir gap pad (Rect px py pw ph) = do+  nt <- readTagEnum a idx TagNodeType+  kind <- readContainerKind a idx+  let chrome = isChromeColumn nt dir+      cbox = padContentClip px py pw ph pad+      layered = case kind of+        KLayered -> True+        _ -> False+  case kind of+    KGrid -> do+      (gCols, minColW) <- readGridColumns a idx+      positionGrid env depth idx gCols minColW gap cbox+    -- Layered children are placed with the pinned ones, below.+    KLayered -> pure ()+    KWrap -> positionWrap env depth idx dir gap cbox+    KLine -> case dir of+      DirRow -> positionRowFromParent env depth idx gap cbox+      DirColumn -> positionColumn env depth idx gap chrome Nothing px pw cbox+  positionLayered env depth idx layered cbox++childRowCrossSize :: NodeArena -> NodeIdx -> Float -> IO Float+childRowCrossSize na ci availCross = do+  hAx@(AxisSizing hTag _ minH _) <- getHeightSizing na ci+  Rect _ _ _ intrinsic <- getNodeRect na ci+  pure $+    if hTag == SizingFit || hTag == SizingShrink+      -- Fit/Shrink keep the measured box. Do not use the wrap-line+      -- or row slot as availH: that stretches every child when leftover+      -- leaks into scratch `fh`.+      then max minH intrinsic+      else resolveSize hAx intrinsic (percentOr hAx availCross availCross)++-- | Copy the first @n@ scratch child indices, and beside them the scratch+-- array @sizes@ picks, to the snapshot for nesting depth @depth@, and run+-- @act@ on the copies. Laying out a child reuses the scratch, so a container+-- walks its children from the snapshot.+{-# INLINE withSnapshot #-}+withSnapshot ::+  NodeArena -> Int -> Int -> (FlexScratch -> IOArr Float) ->+  (IOArr Int -> IOArr Float -> IO a) -> IO a+withSnapshot na depth n sizes act = do+  s <- readIORef (naScratch na)+  AxisSnapshot idxSnap sizeSnap <- ensureAxisSnapshot na depth n+  copyMutablePrimArray idxSnap 0 (fsIdx s) 0 n+  copyMutablePrimArray sizeSnap 0 (sizes s) 0 n+  act idxSnap sizeSnap++-- | Leading offset and inter-child gap for a single-line container distributing+-- leftover space according to 'Justify'. Fast-paths 'JustifyStart' without+-- summing child sizes.+{-# INLINE resolveJustify #-}+resolveJustify :: Justify -> Int -> Float -> Float -> Float -> IOArr Float -> IO (Float, Float)+resolveJustify j n avail gapSum baseGap outSnap+  | j == JustifyStart || n <= 0 = pure (0, baseGap)+  | otherwise = do+      used <- foldUpTo n (\t i -> (t +) <$> readPrimArray outSnap i) gapSum+      let !free = max 0 (avail - used)+      pure $ case j of+        JustifyStart -> (0, baseGap)+        JustifyCenter -> (free * 0.5, baseGap)+        JustifyEnd -> (free, baseGap)+        JustifyBetween ->+          if n > 1 then (0, baseGap + free / fromIntegral (n - 1)) else (0, baseGap)++positionRowFromParent ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  Float ->+  Rect ->+  IO ()+positionRowFromParent env@SolveEnv {seArena = na, seArrays = a} depth parent gap (Rect cx cy cw ch) = do+  pItems <- readItemsAlign a parent+  pJustify <- readTagEnum a parent TagJustify+  pHasBase <- if pItems == ItemsBaseline then pure True else hasBaselineChild a parent+  n <- loadChildrenScratch na parent (flowChildSize env False cw ch)+  let baseGaps = gap * fromIntegral (max 0 (n - 1))+  distributeScratch na n cw baseGaps True+  withSnapshot na depth n fsOut $ \idxSnap outSnap -> do+    (startOff, stepGap) <- resolveJustify pJustify n cw baseGaps gap outSnap+    placeRowLine env depth pItems pHasBase idxSnap outSnap n stepGap (cx + startOff) cy ch++-- | Place the first @k@ snapshot children left to right from @x0@, each as+-- wide as its @outSnap@ share, in a line @cross@ tall at @top@.+-- Baseline-aligned children share the lowest of their baselines, so the+-- child with the tallest ascent touches the top.+placeRowLine :: SolveEnv -> Int -> ItemsAlign -> Bool -> IOArr Int -> IOArr Float -> Int -> Float -> Float -> Float -> Float -> IO ()+placeRowLine env@SolveEnv {seArena = na, seArrays = a} !depth pItems !mayHaveBaseline idxSnap outSnap !k !gap !x0 !top !cross = do+  hasBaseline <- if mayHaveBaseline then anyBaseline 0 else pure False+  if not hasBaseline+    then goPlain 0 x0+    else do+      -- Compute each child's refit height and baseline once so pass 2 never+      -- repeats rowChildHeightAt or childBaseline.+      crossHs <- newPrimArray k+      baselines <- newPrimArray k+      let collect !acc !i = do+            ci <- readPrimArray idxSnap i+            fw <- readPrimArray outSnap i+            crossH <- childCrossH ci fw+            writePrimArray crossHs i crossH+            ok <- isBaselineChild a pItems ci+            if ok+              then do+                b <- childBaseline env ci crossH+                writePrimArray baselines i b+                pure (max acc b)+              else acc <$ writePrimArray baselines i (-1)+      base <- foldUpTo k collect 0+      let goBase !i !x = when (i < k) $ do+            ci <- readPrimArray idxSnap i+            fw <- readPrimArray outSnap i+            crossH <- readPrimArray crossHs i+            b <- readPrimArray baselines i+            fy <-+              if b >= 0+                then pure (clamp top (top + max 0 (cross - crossH)) (top + base - b))+                else (\ay -> alignY ay top cross crossH) <$> effectiveAlignY a pItems ci+            placeChild ci x fy fw crossH >>= goBase (i + 1)+      goBase 0 x0+  where+    anyBaseline !i+      | i >= k = pure False+      | otherwise = do+          ok <- readPrimArray idxSnap i >>= isBaselineChild a pItems+          if ok then pure True else anyBaseline (i + 1)+    -- A child is aligned at the height it is laid out at: its height at its+    -- share of the width when that is not the width it measured at.+    childCrossH ci fw = do+      crossH0 <- childRowCrossSize na ci cross+      steady <- readTagEnum a ci TagSteadyHeight+      if steady then pure crossH0 else fromMaybe crossH0 <$> rowChildHeightAt env ci fw+    -- The cursor stays in raw floats, never snapped: rounding it re-compounds+    -- error every child (1.667 -> 2.0 -> ...) so a shrink row overruns its+    -- fixed width. Each child's far edge is the next one's raw origin, so+    -- quantizeResultsA, which snaps edges, puts both on the same pixel.+    {-# INLINE placeChild #-}+    placeChild !ci !x !fy !fw !crossH = do+      positionNodeA env (depth + 1) ci (Rect x fy fw crossH)+      placedW <- readGeom a ci GeomW+      pure (x + min fw placedW + gap)+    goPlain !i !x = when (i < k) $ do+      ci <- readPrimArray idxSnap i+      fw <- readPrimArray outSnap i+      crossH <- childCrossH ci fw+      ay <- effectiveAlignY a pItems ci+      placeChild ci x (alignY ay top cross crossH) fw crossH >>= goPlain (i + 1)++positionGrid ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  Int ->+  Float ->+  Float ->+  Rect ->+  IO ()+positionGrid env@SolveEnv {seArena = na, seArrays = a} depth parent gCols minColW gap (Rect cx cy cw ch) = do+  let cols = gridColumnCount gCols minColW cw gap+      colW = gridColWidth cw cols gap+  pItems <- readItemsAlign a parent+  -- Refit at the column width before freezing row heights. The enclosing+  -- column's height query uses the same per-node, per-width memo.+  n <- loadChildrenScratch na parent (flowChildSize env True colW ch)+  when (n > 0) $ do+    let numRows = (n + cols - 1) `quot` cols+    -- Freeze child indices and their measured cross sizes before recursing.+    -- Children reuse the working scratch while this grid iterates rows and+    -- columns, so the live arrays would be clobbered by the first child.+    withSnapshot na depth n fsH $ \idxArr hArr -> do+      let goRows !r !curY = when (r < numRows) $ do+            rowH <- gridRowHeight hArr n cols r+            forUpTo_ (min cols (n - r * cols)) $ \j -> do+              ci <- readPrimArray idxArr (r * cols + j)+              wAx <- getWidthSizing na ci+              hAx <- getHeightSizing na ci+              Rect _ _ iw _ <- getNodeRect na ci+              fh <- readPrimArray hArr (r * cols + j)+              -- A cell is offered its own height, refit at the column width,+              -- where its alignment puts it, as a row places its children+              -- ('placeRowLine'). Offered the whole row there, a fit+              -- container would take all of it and overrun the row.+              let offerW = percentOr wAx colW colW+                  childW = resolveSize wAx iw offerW+                  childH =+                    if axTag hAx == SizingPercent+                      then percentOr hAx rowH rowH+                      else resolveSize hAx fh rowH+                  itemX = cx + fromIntegral j * (colW + gap)+              ax <- readAlignX a ci+              ay <- effectiveAlignY a pItems ci+              let fx = alignX ax itemX colW childW+                  fy = alignY ay curY rowH childH+              positionNodeA env (depth + 1) ci (Rect fx fy offerW childH)+            goRows (r + 1) (curY + rowH + gap)+      goRows 0 cy++-- | Lay out a wrapping container's flow children in lines along @dir@+-- within the content box ('wrapLines'), separated by the line gap.+-- Within a line, children share its spare or missing length as in a row or+-- column ('distributeScratch'), and sit across it by alignment or fill it+-- if they grow. A line with room left over shifts by the container's line+-- alignment ('TagLineAlign'). A line is as thick as its thickest child+-- ('wrapLineCross'), or whatever a placed child grew to.+positionWrap :: SolveEnv -> Int -> NodeIdx -> DirTag -> Float -> Rect -> IO ()+positionWrap env@SolveEnv {seArena = na, seArrays = a} depth parent dir gap (Rect cx cy cw ch) = do+  lineGap <- readStyle a parent StyleLineGap+  align <- lineAlignFraction <$> readTagEnum a parent TagLineAlign+  pItems <- readItemsAlign a parent+  pHasBase <- if pItems == ItemsBaseline then pure True else hasBaselineChild a parent+  let row = dir == DirRow+      limit = if row then cw else ch+      along (_, (w, h)) = if row then w else h+      gaps k = gap * fromIntegral (k - 1)+  kids <- mapM (\ci -> (ci,) <$> flowChildSize env False cw ch ci) =<< flowChildrenInOrder na parent+  let placeLine !lineAt line = do+        let k = length line+        FlexScratch {fsIdx = idxArr, fsW = wArr, fsH = hArr, fsOut = outArr} <- ensureScratchCapacity na k+        zipWithM_ (\j (ci, (w, h)) -> writePrimArray idxArr j ci >> writePrimArray wArr j w >> writePrimArray hArr j h) [0 ..] line+        distributeScratch na k limit (gaps k) row+        lineCross <- wrapLineCross env dir pItems line+        -- Shift the line by its alignment's share of the leftover room.+        shift <-+          if align <= 0+            then pure 0+            else (\used -> max 0 (limit - used) * align) <$> foldUpTo k (\t i -> (t +) <$> readPrimArray outArr i) (gaps k)+        withSnapshot na depth k fsOut $ \idxSnap outSnap ->+          if row+            then placeRowLine env depth pItems pHasBase idxSnap outSnap k gap (cx + shift) lineAt lineCross+            else placeColumnLine env depth pItems idxSnap outSnap k gap False Nothing 0 0 (Rect lineAt (cy + shift) lineCross ch)+        -- The next line starts past this one, or past any child that grew.+        let reach m (ci, _) = do+              Rect x y w h <- getNodeRect na ci+              pure (max m (if row then y + h else x + w))+        (+ lineGap) <$> foldM reach (lineAt + lineCross) line+  foldM_ placeLine (if row then cy else cx) (wrapLines limit gap along kids)++-- | Place the children of node @idx@ that draw over the rest, in its content+-- box: every child of a layered container (@allLayered@), plus pinned+-- children. Each sits where its alignment puts it; pinned ones then move by+-- their offsets, so an offset from the end edge anchors to that edge.+--+-- A grow child fills the box (from a pin's offset to its unaligned edge), a+-- percentage is of the box, and anything else keeps its measured size, capped+-- at the box width for layers. A fit height is recomputed at the new width.+positionLayered :: SolveEnv -> Int -> NodeIdx -> Bool -> Rect -> IO ()+positionLayered env@SolveEnv {seArena = na, seArrays = a} depth idx allLayered (Rect cx cy cw ch) = do+  pinnedBelow <- readTagEnum a idx TagPinnedBelow+  when (allLayered || pinnedBelow) $ forChildNodes_ na idx $ \ci -> do+    floating <- isFloatingNode <$> readTagEnum a ci TagNodeType+    pinned <- readTagEnum a ci TagPinned+    when ((allLayered || pinned) && not floating) $ do+      -- Only a pinned node has an offset.+      ox <- readStyle a ci StylePinX+      oy <- readStyle a ci StylePinY+      ax <- readAlignX a ci+      ay <- readAlignY a ci+      wAx <- readAxisSizing a ci True+      hAx@(AxisSizing hTag _ _ _) <- readAxisSizing a ci False+      iw <- readGeom a ci GeomW+      ih <- readGeom a ci GeomH+      let -- Room a grow child gets beside its offset: past it at the start,+          -- short of it at the end, inset on both sides when centred.+          room (AxisSizing tag val _ _) atStart atEnd box offset other = case tag of+            SizingGrow+              | atStart -> max 0 (box - offset)+              | atEnd -> max 0 (box + offset)+              | otherwise -> max 0 (box - 2 * abs offset)+            SizingPercent -> box * val / 100+            _ -> other+          w = resolveSize wAx iw (room wAx (ax == AlignStart) (ax == AlignEnd) cw ox (if pinned then iw else cw))+      fitH <-+        if (hTag == SizingFit || hTag == SizingShrink) && w /= iw+          then recomputeFitHeightAtWidth env ci w+          else pure ih+      let h = resolveSize hAx fitH (room hAx (ay /= AlignMiddle && ay /= AlignBottom) (ay == AlignBottom) ch oy fitH)+      positionNodeA env (depth + 1) ci (Rect (alignX ax cx cw w + ox) (alignY ay cy ch h + oy) w h)++-- | Place a column's flow children top to bottom in the box @cx cy cw ch@. A+-- scroll column shares out its content height (@scrollContent@) and gives a+-- scroll child no more than the part of the viewport below its top; any other+-- column shares out @ch@. In a window's or modal's column (@chrome@) a+-- separator spans the padding box (@px@, @pw@) and takes no gap before it.+positionColumn ::+  SolveEnv ->+  Int ->+  NodeIdx ->+  Float ->+  Bool ->+  Maybe Float ->+  Float ->+  Float ->+  Rect ->+  IO ()+positionColumn env@SolveEnv {seArena = na, seArrays = a} !depth !parent !gap chrome scrollContent !px !pw box@(Rect cx cy cw ch) = do+  pItems <- readItemsAlign a parent+  pJustify <- readTagEnum a parent TagJustify+  n <- loadChildrenScratch na parent (flowChildSize env True cw ch)+  -- The gaps come out of the height shared, as in a row, or grow children+  -- overflow the column by them.+  gapSum <-+    if chrome then columnGapSumScratch na n gap else pure (gap * fromIntegral (max 0 (n - 1)))+  distributeScratch na n (fromMaybe ch scrollContent) gapSum False+  withSnapshot na depth n fsOut $ \idxSnap outSnap -> do+    let effJustify = if isJust scrollContent then JustifyStart else pJustify+    (startOff, stepGap) <- resolveJustify effJustify n ch gapSum gap outSnap+    let box' = if startOff == 0 then box else Rect cx (cy + startOff) cw (max 0 (ch - startOff))+    placeColumnLine env depth pItems idxSnap outSnap n stepGap chrome scrollContent px pw box'++-- | Place the first @k@ snapshot children top to bottom in the box, each as+-- tall as its @outSnap@ share. Arguments after @gap@ are as for+-- 'positionColumn'.+placeColumnLine ::+  SolveEnv -> Int -> ItemsAlign -> IOArr Int -> IOArr Float -> Int -> Float ->+  Bool -> Maybe Float -> Float -> Float -> Rect -> IO ()+placeColumnLine env@SolveEnv {seArena = na} !depth pItems idxSnap outSnap !k !gap chrome scrollContent !px !pw (Rect cx cy cw ch) =+  go 0 cy+  where+    go !i !y = when (i < k) $ do+      ci <- readPrimArray idxSnap i+      fh <- readPrimArray outSnap i+      nt <- getNodeType na ci+      (fx, nodeW) <-+        if chrome && nt == NodeSeparator+          then pure (px, pw)+          else columnChildX na pItems ci cx cw+      let childH = case scrollContent of+            Just _ | isScrollNode nt -> min fh (max 0 (ch - (y - cy)))+            _ -> fh+      positionNodeA env (depth + 1) ci (Rect fx y nodeW childH)+      Rect _ _ _ placedH <- getNodeRect na ci+      gapAfter <-+        if i + 1 >= k+          then pure 0+          else readPrimArray idxSnap (i + 1) >>= \b -> pairColumnGap na chrome b gap+      go (i + 1) (y + placedH + gapAfter)++-- | Place the measured modals, windows and popups within a window @winW@+-- by @winH@ logical pixels, and lay out their children. A modal is centred,+-- leaving the standard window margin where space permits. A window takes its+-- saved position and size (@lookupPos@, @lookupSize@), by default its+-- measured size near the top-right corner. A popup goes where its registered+-- anchor, side and gap put it ('computePopupPosition'), by default at the+-- origin with automatic placement. A popup that @lookupRect@, given its id+-- and measured size, returns a rect for goes at that rect instead.+--+-- When @mPlaced@ is provided, a floating node whose target rect matches its+-- cached 'PlacedFloat' restores its cached subtree geometry instead of+-- re-running layout, and newly placed subtrees are recorded there. Nodes are+-- visited in arena order, so a nested floating node is placed or restored+-- after its enclosing floating node.+placeFloatingNodes ::+  NodeArena ->+  Measurers ->+  Float ->+  Float ->+  (WidgetId -> IO (Maybe (Float, Float))) ->+  (WidgetId -> IO (Maybe (Float, Float))) ->+  (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) ->+  (WidgetId -> Float -> Float -> IO (Maybe Rect)) ->+  Maybe (IORef (IntMap PlacedFloat)) ->+  IO ()+placeFloatingNodes na ms winW winH lookupPos lookupSize lookupAnchor lookupRect mPlaced = do+  env <- solveEnv na ms Nothing+  let place placed idx = do+        rect <- floatingRect idx+        case IM.lookup idx placed of+          Just p | pfRect p == rect -> placed <$ restorePlaced na idx p+          _ -> do+            positionFloating env idx rect+            maybe (IM.delete idx placed) (\p -> IM.insert idx p placed) <$> recordPlaced env idx rect+  case mPlaced of+    Nothing -> forClassNodes_ na FloatingNodes $ \idx -> positionFloating env idx =<< floatingRect idx+    Just placedRef -> writeIORef placedRef =<< foldClassNodesM na FloatingNodes place =<< readIORef placedRef+  where+    floatingRect idx = do+      nt <- getNodeType na idx+      wid <- getWidgetId na idx+      Rect _ _ iw ih <- getNodeRect na idx+      case nt of+        NodeModal -> do+          let w = min iw (max 0 (winW - 2 * windowMargin))+              h = min ih (max 0 (winH - 2 * windowMargin))+          pure (Rect (max 0 ((winW - w) / 2)) (max 0 ((winH - h) / 2)) w h)+        NodeWindow -> do+          (w0, h0) <- fromMaybe (min iw winW, min ih winH) <$> lookupSize wid+          mpos <- lookupPos wid+          windowRect na winW winH idx w0 h0 $ \w -> fromMaybe (winW - w - windowMargin, windowMargin) mpos+        _ ->+          lookupRect wid iw ih >>= \case+            Just r -> pure r+            Nothing -> do+              mcfg <- lookupAnchor wid+              let (anchor, placement, offset) = fromMaybe (AnchorPoint (V2 0 0), PlacementAuto, 4) mcfg+                  (x, y) = computePopupPosition winW winH windowMargin iw ih anchor placement offset+              pure (Rect x y iw ih)++-- | Lay out floating node @idx@ and its subtree at @rect@: a window at+-- exactly that rect, a modal or popup as the solve places a node offered it.+positionFloating :: SolveEnv -> NodeIdx -> Rect -> IO ()+positionFloating env@SolveEnv {seArena = na} idx rect@(Rect x y w h) = do+  nt <- getNodeType na idx+  if nt == NodeWindow+    then do+      setRect na idx x y w h+      (pad, gap, dir) <- containerFlow (seArrays env) idx+      positionChildren env 0 idx dir gap pad rect+    else positionNodeA env 0 idx rect++-- | Snapshot the placed subtree of floating node @idx@ at @rect@+-- ('snapshotPlaced'), or return 'Nothing' when its subtree is not a contiguous+-- index range or contains a drawing with a custom measure (whose height at+-- the placed width is not re-verified by the layout cache).+recordPlaced :: SolveEnv -> NodeIdx -> Rect -> IO (Maybe PlacedFloat)+recordPlaced SolveEnv {seArena = na, seMs = ms} idx rect =+  subtreeSpan na idx >>= \case+    Nothing -> pure Nothing+    Just n -> do+      let measured i = do+            nt <- getNodeType na i+            if nt == NodeDrawing then isJust <$> (msLookupMeasure ms =<< getWidgetId na i) else pure False+      anyMeasured <- foldUpTo n (\acc i -> if acc then pure True else measured (idx + i)) False+      if anyMeasured then pure Nothing else Just <$> snapshotPlaced na idx n rect++-- | Window @idx@'s rect at size @w0 h0@, clamped to its min and max size and+-- the screen, with its origin, given that size, clamped on screen. The+-- caller picks @w0 h0@: 'placeFloatingNodes' passes the saved size, or else+-- the measured size capped at the screen.+windowRect :: NodeArena -> Float -> Float -> NodeIdx -> Float -> Float -> (Float -> (Float, Float)) -> IO Rect+windowRect na winW winH idx w0 h0 originFor = do+  AxisSizing _ _ minW maxW <- getWidthSizing na idx+  AxisSizing _ _ minH maxH <- getHeightSizing na idx+  let w = clamp minW (min maxW winW) w0+      h = clamp minH (min maxH winH) h0+      (x0, y0) = originFor w+  pure (Rect (clamp 0 (max 0 (winW - w)) x0) (clamp 0 (max 0 (winH - h)) y0) w h)++-- | Horizontal placement for a widget-anchored popup. Aligns the popup's left+-- edge with the anchor even when the anchor sits inside the window margin (a+-- menu bar flush to the left, say); the margin is only there to keep the popup+-- clear of the right edge.+clampPopupX :: Float -> Float -> Float -> Float -> Float+clampPopupX margin winW iw x0+  | x0 < margin && x0 + iw <= winW = max 0 x0+  | otherwise = clamp margin (winW - iw - margin) x0++-- | Popup origin from window width/height, margin, popup width/height, anchor,+-- preferred placement, and gap. All coordinates use logical pixels.+-- Flips or clamps placement to the available window space.+computePopupPosition ::+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  PopupAnchor ->+  PopupPlacement ->+  Float ->+  (Float, Float)+computePopupPosition winW winH margin iw ih anchor placement offset =+  case anchor of+    AnchorPoint (V2 px py) ->+      -- On each axis the popup goes before or after the point, as beside an+      -- anchor span of no length, or at it, flipping to the other side if it+      -- would overflow and fits there. Either way it keeps within the margins.+      let onAxis p size lim isBefore isAfter+            | isBefore = before p 0 lim size+            | isAfter = after p 0 lim size+            | p + size > lim - margin && p - size - offset >= margin = p - size - offset+            | otherwise = p+       in ( clamp margin (winW - iw - margin) (onAxis px iw winW (placement == PlacementLeft) (placement == PlacementRight))+          , clampY (onAxis py ih winH (placement == PlacementAbove) (placement == PlacementBelow))+          )+    AnchorRect (Rect rx ry rw rh) ->+      let (rawX, rawY) = case placement of+            PlacementBelow -> (rx, after ry rh winH ih)+            PlacementAbove -> (rx, before ry rh winH ih)+            PlacementRight -> (after rx rw winW iw, ry)+            PlacementLeft -> (before rx rw winW iw, ry)+            PlacementAuto ->+              let spaceBelow = winH - margin - (ry + rh + offset)+                  spaceAbove = ry - offset - margin+               in (rx, if spaceBelow >= ih || spaceBelow >= spaceAbove then ry + rh + offset else ry - ih - offset)+            PlacementAtCursor -> (rx, ry + rh + offset)+       in (clampPopupX margin winW iw rawX, clampY rawY)+  where+    -- Keep the popup's top edge within the window margins.+    clampY y = clamp margin (winH - ih - margin) y+    -- A popup of @size@ after (or before) the anchor span @lo@..@lo + len@ on+    -- an axis of length @lim@, taking the other side when it would overflow+    -- and the other side fits.+    after lo len lim size+      | lo + len + offset + size > lim - margin && lo - size - offset >= margin = lo - size - offset+      | otherwise = lo + len + offset+    before lo len lim size+      | lo - size - offset < margin && lo + len + offset + size <= lim - margin = lo + len + offset+      | otherwise = lo - size - offset
+ lib/NanoUI/Internal/Metrics.hs view
@@ -0,0 +1,201 @@+-- | Shared UI layout constants and control geometry derived from 'FontMetrics'.+module NanoUI.Internal.Metrics+  ( tableCellInset+  , controlPadY+  , widgetContentInset+  , widgetPadding+  , buttonPadding+  , selectPadding+  , menuOuterPad+  , menuItemPadX+  , menuItemRowH+  , menuSepH+  , menuMinW+  , checkboxBoxSize+  , checkboxLeading+  , treeItemPadding+  , treeRowLeading+  , treeChevronRect+  , sliderHandleDiameter+  , sliderTrackBounds+  , sliderHitBounds+  , scrollBarWidth+  , scrollBarSideGap+  , scrollBarGeomFor+  , ScrollBarSlot (..)+  , classifyScrollBar+  , scrollBarGap+  , scrollBarGutter+  ) where++import NanoUI.Internal.Font.Types (FontMetrics (..))+import NanoUI.Internal.Types (Rect (..), clamp)++-- | Horizontal text inset of a table cell. Zebra and header fills use the full cell rect.+tableCellInset :: Float+tableCellInset = 6++-- | Shared total vertical padding for single-line controls (buttons, selects,+-- and text inputs), derived from line height so sibling controls match height+-- across proportional and monospace fonts.+{-# INLINE controlPadY #-}+controlPadY :: FontMetrics -> Float+controlPadY fm = max 6 (fromIntegral (round (fmLineHeight fm * 0.50) :: Int))++-- | Per-side horizontal and vertical content inset.+{-# INLINE widgetContentInset #-}+widgetContentInset :: FontMetrics -> (Float, Float)+widgetContentInset fm =+  (fmAdvance fm ' ' * 1.25, controlPadY fm / 2)++-- | Total horizontal and vertical content padding, twice 'widgetContentInset'.+{-# INLINE widgetPadding #-}+widgetPadding :: FontMetrics -> (Float, Float)+widgetPadding fm =+  let (cx, cy) = widgetContentInset fm+   in (2 * cx, 2 * cy)++-- | Total horizontal/vertical padding inside a button label box.+{-# INLINE buttonPadding #-}+buttonPadding :: FontMetrics -> (Float, Float)+buttonPadding fm = (fmAdvance fm ' ' * 2.0, controlPadY fm)++-- | Total horizontal/vertical padding inside a select button.+{-# INLINE selectPadding #-}+selectPadding :: FontMetrics -> (Float, Float)+selectPadding = buttonPadding++-- | Blank border between the menu panel edge and its rows.+menuOuterPad :: Float+menuOuterPad = 6++-- | Extra horizontal inset of a menu row's label past 'menuOuterPad'.+menuItemPadX :: Float+menuItemPadX = 10++-- | Fixed height of one menu row.+menuItemRowH :: Float+menuItemRowH = 28++-- | Height of a separator band inside a menu.+menuSepH :: Float+menuSepH = 9++-- | Floor for the menu panel width.+menuMinW :: Float+menuMinW = 148++-- | Side length of a checkbox's box, sized from its label's font.+{-# INLINE checkboxBoxSize #-}+checkboxBoxSize :: FontMetrics -> Float+checkboxBoxSize fm = clamp 18 22 (fmLineHeight fm * 1.15)++-- | Horizontal offset from a checkbox/radio node's left edge to its label.+{-# INLINE checkboxLeading #-}+checkboxLeading :: FontMetrics -> Float+checkboxLeading fm = checkboxBoxSize fm + 8++-- | Total tree-row x/y padding: zero horizontally and at least 8 logical pixels vertically.+{-# INLINE treeItemPadding #-}+treeItemPadding :: FontMetrics -> (Float, Float)+treeItemPadding fm = (0, max 8 (fromIntegral (round (fmLineHeight fm * 0.40) :: Int)))++-- | Per-depth horizontal indent for tree rows.+{-# INLINE treeIndentStep #-}+treeIndentStep :: FontMetrics -> Float+treeIndentStep fm = max 12 (fmLineHeight fm * 0.85)++-- | Width of the disclosure chevron slot beside a tree label.+{-# INLINE treeChevronLeading #-}+treeChevronLeading :: FontMetrics -> Float+treeChevronLeading fm = checkboxBoxSize fm + 6++-- | Leading width before a tree row's label at nesting depth @depth@.+{-# INLINE treeRowLeading #-}+treeRowLeading :: FontMetrics -> Int -> Float+treeRowLeading fm depth =+  treeIndentStep fm * fromIntegral (max 0 depth) + treeChevronLeading fm++-- | Bounding box of a tree row's disclosure chevron at @depth@.+{-# INLINE treeChevronRect #-}+treeChevronRect :: FontMetrics -> Float -> Float -> Float -> Int -> Rect+treeChevronRect fm x y h depth =+  let indent = treeIndentStep fm * fromIntegral (max 0 depth)+      lead = max 1 (treeChevronLeading fm)+   in Rect (x + indent) y lead h++-- | Visual height of a slider track.+sliderTrackHeight :: Float+sliderTrackHeight = 10++-- | Diameter of a slider thumb handle.+sliderHandleDiameter :: Float+sliderHandleDiameter = 18++-- | Half the difference between slider handle diameter and track height.+sliderHandleSlack :: Float+sliderHandleSlack = (sliderHandleDiameter - sliderTrackHeight) / 2++-- | A 10-pixel-high track centred vertically within x/y/width/height bounds.+{-# INLINE sliderTrackBounds #-}+sliderTrackBounds :: Float -> Float -> Float -> Float -> Rect+sliderTrackBounds x y w h =+  let trackY = y + max 0 ((h - sliderTrackHeight) / 2)+   in Rect x trackY (max 0 w) sliderTrackHeight++-- | The track grown by the handle's overhang: where a drag or a hover on the+-- handle counts. The painter and the cursor must agree on this.+{-# INLINE sliderHitBounds #-}+sliderHitBounds :: Float -> Float -> Float -> Float -> Rect+sliderHitBounds x y w h =+  let Rect tx ty tw th = sliderTrackBounds x y w h+   in Rect tx (ty - sliderHandleSlack) tw (th + 2 * sliderHandleSlack)++-- | Thickness of a list or page scrollbar.+scrollBarWidth :: Float+scrollBarWidth = 8++-- | Thickness of a window body's scrollbar.+scrollBarSlimWidth :: Float+scrollBarSlimWidth = 4++-- | Inset between scrollbar ends and container bounds.+scrollBarMargin :: Float+scrollBarMargin = 3++-- | The sliver between a page or window bar and the outer edge, and the+-- smallest gap on either side of a list bar.+scrollBarSideGap :: Float+scrollBarSideGap = 3++-- | Bar width and end margin for a slot.+scrollBarGeomFor :: ScrollBarSlot -> (Float, Float)+scrollBarGeomFor ScrollBarWindow = (scrollBarSlimWidth, 0)+scrollBarGeomFor _ = (scrollBarWidth, scrollBarMargin)++-- | The layout arena stores a scroller's slot as its 'Enum' value, and every+-- other node reads a zero there, so 'ScrollBarList' comes first.+data ScrollBarSlot = ScrollBarList | ScrollBarPage | ScrollBarWindow+  deriving (Eq, Ord, Show, Enum)++-- | Choose the 'ScrollBarSlot' for a scroller from window-body and page flags.+classifyScrollBar :: Bool -> Bool -> ScrollBarSlot+classifyScrollBar isWindowBody isPageGrow+  | isWindowBody = ScrollBarWindow+  | isPageGrow = ScrollBarPage+  | otherwise = ScrollBarList++-- | Gap between the content and a bar, given the padding @trailPad@ on the+-- bar's side.+scrollBarGap :: Float -> Float+scrollBarGap trailPad = max scrollBarSideGap trailPad++-- | Space an overflowing scroller takes from its content beside @trailPad@.+scrollBarGutter :: ScrollBarSlot -> Float -> Float+scrollBarGutter slot trailPad =+  let (barW, _) = scrollBarGeomFor slot+      gap = scrollBarGap trailPad+   in case slot of+        ScrollBarList -> barW + 2 * gap - trailPad+        ScrollBarPage -> barW + scrollBarSideGap + gap - trailPad+        ScrollBarWindow -> barW + scrollBarSideGap
+ lib/NanoUI/Internal/Monad.hs view
@@ -0,0 +1,109 @@+{-# OPTIONS_HADDOCK not-home #-}+++-- | Implementation of "NanoUI.Monad", plus running a view against a context,+-- reading and swapping the context, and id-frame plumbing. The definitions+-- live in "NanoUI.Internal.Monad.Core" (the monad, scopes, themes, fonts,+-- damage), "NanoUI.Internal.Monad.Focus" (focus, clipboard, Escape),+-- "NanoUI.Internal.Monad.Scroll" and "NanoUI.Internal.Monad.Explain"; this+-- module is their export list.+module NanoUI.Internal.Monad+  ( NanoUI (..)+  , NanoUIEs+  , Ui+  , runNanoUI+  , runUi+  , embedNanoUI+  , withRunInNanoUI+  , liftIO+  , withContext+  , withUiResource+  , withBuildScope+  , catchView+  , withKey+  , keyedTag+  , scope+  , withIdFrame+  , nextId+  , freshWidget+  , burstNextIds+  , currentId+  , askContext+  , askInput+  , askFrameInput+  , localInput+  , inertView+  , askDefaultLayout+  , withDefaultLayout+  , askHost+  , askBackendSession+  , uiFontMetrics+  , uiFontSize+  , resolveFontUi+  , lineWidthUi+  , truncateTextUi+  , truncateTextWithUi+  , uiTime+  , uiTheme+  , setTheme+  , followSystemTheme+  , systemAppearance+  , styled+  , themed+  , disabledWhen+  , uiMousePos+  , mousePressed+  , mouseReleased+  , mouseHeld+  , windowSize+  , windowWidth+  , windowHeight+  , lastRect+  , holdFocus+  , releaseFocus+  , focusedWidget+  , requestFocus+  , focusNext+  , focusPrevious+  , clearFocus+  , isFocused+  , getClipboard+  , setClipboard+  , requestFrame+  , takeEscape+  , explainLayout+  , explainingLayout+  , explainedNode+  , explainScope+  , withArenaRange+  , inArenaRange+  , getScrollTuning+  , setScrollTuning+  , getScrollMetrics+  , setScrollOffset+  , scrollTo+  , scrollBy+  , scrollPages+  , scrollToStart+  , scrollToEnd+  , scrollIntoView+  , scrollRectIntoView+  , setScrollStep+  , damageWidgetNow+  , damageKeyNow+  , damageRectNow+  , damageGroupNow+  , damageFullNow+  , whenM+  , unlessM+  , ifM+  , (<&&>)+  , mfilterM+  )+where++import Control.Monad.IO.Class (liftIO)+import NanoUI.Internal.Monad.Core+import NanoUI.Internal.Monad.Explain+import NanoUI.Internal.Monad.Focus+import NanoUI.Internal.Monad.Scroll
+ lib/NanoUI/Internal/Monad/Core.hs view
@@ -0,0 +1,619 @@+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}++-- | The view monad itself: the effect, running a view, the context, input,+-- id scopes, themes, fonts, and the damage requests backends make. The rest+-- of "NanoUI.Internal.Monad" builds on this.+module NanoUI.Internal.Monad.Core+  ( NanoUI (..)+  , NanoUIEs+  , Ui+  , runUi+  , runNanoUI+  , embedNanoUI+  , withRunInNanoUI+  , withContext+  , withUiResource+  , withBuildScope+  , catchView+  , currentId+  , nextId+  , freshWidget+  , burstNextIds+  , withIdFrame+  , scope+  , withKey+  , keyedTag+  , askContext+  , askDefaultLayout+  , withDefaultLayout+  , uiFontMetrics+  , uiFontSize+  , resolveFontUi+  , lineWidthUi+  , truncateTextUi+  , truncateTextWithUi+  , uiTime+  , uiTheme+  , styled+  , themed+  , disabledWhen+  , setTheme+  , followSystemTheme+  , systemAppearance+  , uiMousePos+  , mousePressed+  , mouseReleased+  , mouseHeld+  , askInput+  , askFrameInput+  , localInput+  , inertView+  , windowSize+  , windowWidth+  , windowHeight+  , askBackendSession+  , askHost+  , damageWidgetNow+  , damageKeyNow+  , damageRectNow+  , damageGroupNow+  , damageFullNow+  , whenM+  , unlessM+  , (<&&>)+  , ifM+  , mfilterM+  )+where++import Control.Exception (Exception, bracket)+import Control.Monad (unless, when, (<$!>))+import Control.Monad.Base (MonadBase)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)+import Control.Monad.Catch qualified as Catch (MonadCatch (catch))+import Control.Monad.Fix (MonadFix)+import Control.Monad.IO.Class (MonadIO (liftIO))+import Control.Monad.IO.Unlift (MonadUnliftIO)+import Control.Monad.Trans.Control (MonadBaseControl)+import Data.Bits ((.&.), (.|.))+import Data.Hashable (Hashable, hash)+import Data.Monoid (Ap (..))+import Data.Text (Text)+import Data.Word (Word64)+import Effectful (Dispatch (Static), DispatchOf, Eff, Effect, IOE, runEff, type (:>))+import Effectful.Dispatch.Static (SideEffects (WithSideEffects), StaticRep, evalStaticRep, getStaticRep, localStaticRep, unEff, unsafeEff, unsafeEff_)+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.BackendSession (BackendSession, SBackend)+import NanoUI.Internal.Context (askHostIO, Host, Context (ctxNodeArena, ctxContainerStack, ctxIdCursor, ctxFontMetrics, ctxFontSize), currentTheme, damageFull, damageKey, damagePeers, damageRect, damageWidget, pushThemeScope, scopeRawTheme, routedInput, backendSession, getSystemAppearance, setThemeInView)+import NanoUI.Internal.Context qualified as Ctx+import NanoUI.Internal.Context.Types (readContainerStack, writeContainerStack)+import NanoUI.Internal.Draw.Types (TextFont (..))+import NanoUI.Internal.Font (FontMetrics, lineWidthIO, truncateTextIO, truncateTextWithIO)+import NanoUI.Internal.Frame.Node (resolveTextFont)+import NanoUI.Internal.Id (scopeTag, IdContext, WidgetId)+import NanoUI.Internal.Id.Cursor (peekWidgetId, popIdScope, pushIdScope, pushKeyedIdScope, readIdCursor, readIdDepth, skipSiblingIds, takeWidgetId, writeIdCursor, writeIdDepth)+import NanoUI.Internal.Input (noButtons, stripInteractionInput, withoutPointer, Input (inputComposition, inputMousePos, inputWindowSize, inputButtonsHeld, inputKeysHeld), MouseButton, Pressable (heldIn, pressedIn, releasedIn))+import NanoUI.Internal.Layout.Arena (getArenaScope, setArenaScope)+import NanoUI.Internal.Style (Appearance, FontStyle, FontVariant, FontWeight, Layout, TextDecoration (DecorationNone), TextEllipsis, Theme, defaultLayout)+import NanoUI.Internal.Types (DamageBounds, Rect, Size (..), V2)+++-- | A view: widgets, layout, local state and IO. Backend runners execute it+-- as frames are needed; local-state changes can trigger a second pass within+-- a frame. Run IO in it with 'liftIO'; the action runs on every frame that+-- reaches it, so guard one-shot effects with a button or another event.+--+-- "NanoUI.Effectful" exports the constructor and functions for mixing views+-- with other @effectful@ effects in 'NanoUIEs'.+newtype NanoUI a = NanoUI {unNanoUI :: Eff NanoUIEs a}+  deriving newtype+    ( Functor+    , Applicative+    , Monad+    , MonadFix+    , MonadIO+    , MonadUnliftIO+    , MonadThrow+    , MonadCatch+    , MonadMask+    , MonadBase IO+    , MonadBaseControl IO+    )+  deriving (Semigroup, Monoid) via Ap NanoUI a++-- | The effect row a 'NanoUI' view runs in.+type NanoUIEs = '[Ui, IOE]++-- | Access to the current context, routed input, layout defaults, and widget ids.+data Ui :: Effect++type instance DispatchOf Ui = Static WithSideEffects++-- The input is held twice: as routed to the view being declared, which is+-- what widgets read, and as the frame received it ('askFrameInput'). Few+-- things read the second, so it is lazy: a 'disabledWhen' scope strips it+-- only if something inside asks.+data instance StaticRep Ui = UiRep+  { repContext :: !Context+  , repInput :: !Input+  , repFrame :: Input+  , repLayout :: !Layout+  }++-- | Interpret UI operations using a context and input. This runs the view only;+-- use a backend or @runFrame@ to reset arenas, solve layout, and paint.+{-# INLINE runUi #-}+runUi :: IOE :> es => Context -> Input -> Eff (Ui : es) a -> Eff es a+runUi ctx inp ui = do+  -- The page is layer 0; floating panels route their own bodies.+  page <- unsafeEff_ (routedInput ctx 0 inp)+  evalStaticRep (UiRep ctx page inp defaultLayout) ui++-- | Run a view against a context and input, without laying it out or+-- painting it.+{-# INLINE runNanoUI #-}+runNanoUI :: Context -> Input -> NanoUI a -> IO a+runNanoUI ctx inp = runEff . runUi ctx inp . unNanoUI++-- | Run a 'NanoUI' view as part of a view in any effect row with 'Ui', where+-- it declares its widgets as if written there: same context, input, layout+-- defaults and widget ids.+embedNanoUI :: Ui :> es => NanoUI a -> Eff es a+embedNanoUI view = withRunInNanoUI (\_ -> view)++-- | Run a 'NanoUI' view from any effect row with 'Ui', with a function that+-- runs that row's actions inside it: how a view written in a larger row+-- passes a body using its other effects to a container widget.+--+-- > counter :: (Ui :> es, State Int :> es) => Eff es ()+-- > counter = withRunInNanoUI $ \run -> row $ do+-- >   n <- run get+-- >   whenM (button "+") (run (put (n + 1)))+--+-- An action run this way sees the scope it is run in (layout defaults,+-- routed input, 'disabledWhen'), not the one 'withRunInNanoUI' was called+-- in. Call the function only on the thread running the view.+withRunInNanoUI :: forall es a. Ui :> es => ((forall r. Eff es r -> NanoUI r) -> NanoUI a) -> Eff es a+withRunInNanoUI k = unsafeEff $ \es -> do+  rep <- unEff (getStaticRep @Ui) es+  let run :: Eff es r -> NanoUI r+      run m = NanoUI $ do+        inner <- getStaticRep @Ui+        unsafeEff_ (unEff (localStaticRep (const inner) m) es)+  runEff (evalStaticRep rep (unNanoUI (k run)))++-- | Run an action on the view's 'Context'.+{-# INLINE withContext #-}+withContext :: (Context -> IO a) -> NanoUI a+withContext f = NanoUI (getStaticRep >>= \r -> unsafeEff_ (f $! repContext r))++-- | Acquire UI-thread state, run an action, and restore it even on exceptions.+-- Acquisition and release are masked, as in 'bracket'; the view inherits the+-- caller's masking state.+{-# INLINE withUiResource #-}+withUiResource :: IO a -> (a -> IO ()) -> NanoUI b -> NanoUI b+withUiResource acquire release (NanoUI action) =+  NanoUI (unsafeEff $ \es -> bracket acquire release (\_ -> unEff action es))++-- | Enter a view build scope (an id scope, a container, a paint scope), run+-- the action, and leave it. No exception handler is installed: an exception+-- that escapes the action leaves the scope entered for the rest of the pass,+-- which 'catchView' undoes for a view that recovers, and the next pass starts+-- from a clean build (@resetUiBuild@). Every row,+-- column, 'scope', 'withKey' row and 'styled' call goes through here, where a+-- handler would cost an allocation each.+{-# INLINE withBuildScope #-}+withBuildScope :: IO a -> (a -> IO ()) -> NanoUI b -> NanoUI b+withBuildScope acquire release m = do+  a <- liftIO acquire+  r <- m+  liftIO (release a)+  pure r++-- | Run part of a view, and run the handler after it if it throws. The view's+-- build state (open containers, the id scope, the paint scope) is put back+-- as it was before the part ran, so the handler and the rest of the view are+-- laid out where they are declared. What the part declared before it threw+-- stays in the frame:+--+-- > catchView (column (riskyPanel model)) $ \(e :: SomeException) ->+-- >   label ("Could not show the panel: " <> T.pack (displayException e))+--+-- Catching with 'Control.Monad.Catch.catch' or 'Control.Monad.Catch.try'+-- instead works, but leaves whatever containers the part had open around+-- the rest of the view until the next frame.+catchView :: Exception e => NanoUI a -> (e -> NanoUI a) -> NanoUI a+catchView m handler = do+  ctx <- askContext+  let na = ctxNodeArena ctx+      ic = ctxIdCursor ctx+  saved <- liftIO $ (,,,) <$> readContainerStack (ctxContainerStack ctx) <*> readIdCursor ic <*> readIdDepth ic <*> getArenaScope na+  m `Catch.catch` \e -> do+    liftIO $ case saved of+      (stack, ids, depth, sc) -> do+        writeContainerStack (ctxContainerStack ctx) stack+        writeIdCursor ic ids+        writeIdDepth ic depth+        setArenaScope na sc+    handler e++-- | The id 'nextId' would issue, without consuming it.+{-# INLINE currentId #-}+currentId :: NanoUI WidgetId+currentId = withContext (peekWidgetId . ctxIdCursor)++-- | Consume the next sibling id. Widgets share this sequence (positional+-- Vars count apart), so conditional widgets need their own 'scope'.+{-# INLINE nextId #-}+nextId :: NanoUI WidgetId+nextId = withContext (takeWidgetId . ctxIdCursor)++-- | The next sibling id ('nextId') and the view's 'Context', which a widget's body starts from.+{-# INLINE freshWidget #-}+freshWidget :: NanoUI (WidgetId, Context)+freshWidget = do+  wid <- nextId+  ctx <- askContext+  pure (wid, ctx)++-- | Reserve @n@ sibling ids without returning them. Non-positive counts do nothing.+{-# INLINE burstNextIds #-}+burstNextIds :: Int -> NanoUI ()+burstNextIds n+  | n <= 0 = pure ()+  | otherwise = withContext $ \ctx -> skipSiblingIds (ctxIdCursor ctx) n++-- | Run in the child context returned by @enter@, then restore its advanced+-- parent context, including when the action throws an exception.+{-# INLINE withIdFrame #-}+withIdFrame ::+  (IdContext -> (IdContext, IdContext)) -> NanoUI a -> NanoUI a+withIdFrame enter m = do+  ctx <- askContext+  withBuildScope+    ( do+        old <- readIdCursor (ctxIdCursor ctx)+        let+          !(!p, !c) = enter old+        writeIdCursor (ctxIdCursor ctx) c+        pure p+    )+    (writeIdCursor (ctxIdCursor ctx))+    m++-- | Give the action a child id sequence while consuming one parent id.+-- Put conditional content inside this scope to keep later siblings stable.+{-# INLINE scope #-}+scope :: NanoUI a -> NanoUI a+scope m = do+  ctx <- askContext+  let ic = ctxIdCursor ctx+  liftIO $ pushIdScope ic scopeTag+  r <- m+  liftIO $ popIdScope ic+  pure r++-- | Run the action under a key so its widgets keep their ids and state when+-- earlier siblings change. Keys must be unique among siblings in the same+-- scope; use a stable item key for a list that can be reordered. A keyed+-- scope takes no sibling position, so widgets declared after a keyed list+-- keep their ids as the list grows and shrinks.+--+-- The state kept under a key, by widgets such as a text field and by+-- 'NanoUI.Var.useVar', lasts as long as the context, also once the key is no+-- longer shown ('NanoUI.Var.useVar' says what to use for a growing feed).+{-# INLINE withKey #-}+withKey :: Hashable k => k -> NanoUI a -> NanoUI a+withKey k = keyedTag (fromIntegral (hash k))++-- | A keyed child scope using a precomputed 64-bit tag. Tags must be unique+-- among siblings; use 'withKey' to hash an application key.+{-# INLINE keyedTag #-}+keyedTag :: Word64 -> NanoUI a -> NanoUI a+keyedTag tag m = do+  ctx <- askContext+  let ic = ctxIdCursor ctx+  liftIO $ pushKeyedIdScope ic tag+  r <- m+  liftIO $ popIdScope ic+  pure r++-- | The mutable context for this view. It belongs to the current UI session.+{-# INLINE askContext #-}+askContext :: NanoUI Context+askContext = NanoUI (repContext <$!> getStaticRep)++-- | Layout defaults in the current 'withDefaultLayout' scope.+{-# INLINE askDefaultLayout #-}+askDefaultLayout :: NanoUI Layout+askDefaultLayout = NanoUI (repLayout <$!> getStaticRep)++-- | Modify layout defaults for the enclosed action, restoring them on exit.+{-# INLINE withDefaultLayout #-}+withDefaultLayout :: (Layout -> Layout) -> NanoUI a -> NanoUI a+withDefaultLayout f (NanoUI m) = NanoUI (localStaticRep (\r -> r {repLayout = f (repLayout r)}) m)++-- | The context's base font metrics, before per-widget font overrides.+{-# INLINE uiFontMetrics #-}+uiFontMetrics :: NanoUI FontMetrics+uiFontMetrics = fmap ctxFontMetrics askContext++-- | The backend's default font size, used when a layout sets none.+-- 'NanoUI.fontSizeScale' scales relative to this size unless an explicit+-- 'NanoUI.fontSize' was already set.+{-# INLINE uiFontSize #-}+uiFontSize :: NanoUI Float+uiFontSize = fmap ctxFontSize askContext++-- | Metrics for text at a size, weight, style and variant, resolved through+-- the backend's fonts: what a custom widget measures and places its text by+-- when it draws in a font other than the context's.+--+-- It resolves the font as a 'DrawTextStyled' op naming the same size,+-- weight, style and variant is painted, so text measured with these metrics+-- is drawn at the width it was measured at.+resolveFontUi :: Float -> FontWeight -> FontStyle -> FontVariant -> NanoUI FontMetrics+resolveFontUi size weight style variant =+  withContext (\ctx -> fst <$> resolveTextFont ctx (TextFont size variant weight style DecorationNone False))++-- | The advance of one line of text in these metrics, in logical pixels. Unlike+-- the pure 'NanoUI.lineWidth' it first loads the glyphs the text needs,+-- so it is right for metrics that have not drawn this text yet.+lineWidthUi :: FontMetrics -> Text -> NanoUI Float+lineWidthUi fm txt = liftIO (lineWidthIO fm txt)++-- | One line of text cut to fit @maxW@ logical pixels in these metrics,+-- ending in @...@ when it was cut; the text as it is when it fits. Too+-- narrow for the dots, it is cut without them. Buttons and selects cut+-- their labels this way themselves, and so does a single-line label with+-- 'fillW' or 'maxW' in a row.+--+-- > fm <- uiFontMetrics+-- > name <- truncateTextUi fm 120 (trackName t)+truncateTextUi :: FontMetrics -> Float -> Text -> NanoUI Text+truncateTextUi fm maxW txt = liftIO (truncateTextIO (lineWidthIO fm) maxW txt)++-- | Truncate one line of text to @maxW@ using an explicit 'TextEllipsis' mode.+truncateTextWithUi :: TextEllipsis -> FontMetrics -> Float -> Text -> NanoUI Text+truncateTextWithUi ell fm maxW txt = liftIO (truncateTextWithIO ell (lineWidthIO fm) maxW txt)++{-# INLINE uiTime #-}+-- | Monotonic seconds from an unspecified epoch. Subtract two readings to+-- measure elapsed time; this is not a wall-clock timestamp. Keep absolute+-- readings as 'Double' to retain precision during long sessions.+uiTime :: NanoUI Double+uiTime = liftIO getMonotonicTime++-- | The theme the view is drawn with where this is called: the context theme+-- as modified by the enclosing 'styled' and 'disabledWhen' scopes.+{-# INLINE uiTheme #-}+uiTheme :: NanoUI Theme+uiTheme = withContext currentTheme++-- | Draw a part of the view with a modified theme. Widgets declared inside+-- take their colours, borders and corner radii from it, and 'styled' scopes+-- nest, each modifying the theme of the scope around it:+--+-- > styled (buttonStyle (cornerRadius 8)) $ do+-- >   styled primary (button "Save")+-- >   button "Cancel"+--+-- The modifier runs once per scope per frame. The theme only affects how+-- widgets look, never their layout.+{-# INLINE styled #-}+styled :: (Theme -> Theme) -> NanoUI a -> NanoUI a+styled f = withPaintScope $ \ctx outer ->+  (.|. (outer .&. 2)) <$> (pushThemeScope ctx (outer .&. 1 /= 0) . f =<< scopeRawTheme ctx outer)++-- | Draw a part of the view with another theme, whatever the theme around it.+{-# INLINE themed #-}+themed :: Theme -> NanoUI a -> NanoUI a+themed theme = styled (const theme)++-- | Disable every widget declared inside when the condition holds. Disabled+-- widgets keep their place, state and layout, but take no pointer or+-- keyboard input, cannot be focused, and are drawn with 'disabledTheme'.+--+-- > disabledWhen (T.null name) $ whenM (button "Save") save+{-# INLINE disabledWhen #-}+disabledWhen :: Bool -> NanoUI a -> NanoUI a+disabledWhen False m = m+disabledWhen True m = disabledScope m++-- | Out-of-line active path for 'disabledWhen', so call sites only test the+-- flag inline.+{-# NOINLINE disabledScope #-}+disabledScope :: NanoUI a -> NanoUI a+disabledScope m =+  -- The view inside sees no presses, keys or wheel, so no widget's own input+  -- handling can fire; the frame's focus and click passes check the scope.+  localBothInputs (\i -> (stripInteractionInput i) {inputButtonsHeld = noButtons, inputKeysHeld = mempty})+    (withPaintScope enter m)+  where+    enter ctx outer+      | outer .&. 1 /= 0 = pure outer+      | otherwise = (.|. (outer .&. 2)) <$> (pushThemeScope ctx True =<< scopeRawTheme ctx outer)++{-# INLINE localBothInputs #-}+localBothInputs :: (Input -> Input) -> NanoUI a -> NanoUI a+localBothInputs f (NanoUI m) = NanoUI (localStaticRep (\r -> r {repInput = f (repInput r), repFrame = f (repFrame r)}) m)++-- Run @m@ with the arena scope @enter@ picks, then restore the scope around it+-- (also on exceptions).+{-# INLINE withPaintScope #-}+withPaintScope :: (Context -> Int -> IO Int) -> NanoUI a -> NanoUI a+withPaintScope enter m = do+  ctx <- askContext+  let+    na = ctxNodeArena ctx+  withBuildScope+    ( do+        old <- getArenaScope na+        setArenaScope na =<< enter ctx old+        pure old+    )+    (setArenaScope na)+    m++-- | Set the session's base theme, repainting if it changed. Use 'styled' for+-- a change limited to part of the view. Setting the same theme again is a+-- no-op, so a view can pick its theme every frame:+--+-- > setTheme . lightDark defaultLightTheme defaultTheme =<< systemAppearance+--+-- This replaces a theme set by 'followSystemTheme'.+{-# INLINE setTheme #-}+setTheme :: Theme -> NanoUI ()+setTheme th = withContext (`setThemeInView` th)++-- | Switch the session's theme automatically whenever the OS light/dark+-- preference changes. Calling 'setTheme' returns to a fixed theme.+{-# INLINE followSystemTheme #-}+followSystemTheme :: (Maybe Appearance -> Theme) -> NanoUI ()+followSystemTheme pick = withContext (`Ctx.followSystemTheme` pick)++-- | System light or dark preference, or 'Nothing' when the backend does not+-- report it (RGFW never does). A change repaints the whole window.+{-# INLINE systemAppearance #-}+systemAppearance :: NanoUI (Maybe Appearance)+systemAppearance = withContext getSystemAppearance++-- | Pointer position in the current layer's routed input (moved off-screen+-- when occluded by a layer or overlay in front).+{-# INLINE uiMousePos #-}+uiMousePos :: NanoUI V2+uiMousePos = fmap inputMousePos askInput++-- | Whether the button went down this frame with the pointer over the part of+-- the view being declared, on any widget. 'False' behind an open modal, under+-- a menu or panel drawn in front, and inside 'disabledWhen'. For a press on a+-- particular widget, use its 'NanoUI.respClickedWith' or 'NanoUI.respHeldWith'.+--+-- > whenM (mousePressed MouseBack) goBack+{-# INLINE mousePressed #-}+mousePressed :: MouseButton -> NanoUI Bool+mousePressed b = pressedIn b <$> askInput++-- | Like 'mousePressed', for a button that came up this frame.+{-# INLINE mouseReleased #-}+mouseReleased :: MouseButton -> NanoUI Bool+mouseReleased b = releasedIn b <$> askInput++-- | Like 'mousePressed', for a button that is down.+{-# INLINE mouseHeld #-}+mouseHeld :: MouseButton -> NanoUI Bool+mouseHeld b = heldIn b <$> askInput++-- | Input routed to the current layer. Covered layers receive no pointer;+-- disabled scopes also remove keyboard and other interaction events.+{-# INLINE askInput #-}+askInput :: NanoUI Input+askInput = NanoUI (repInput <$!> getStaticRep)++-- | Unrouted frame input, including the pointer regardless of which layer owns+-- it. Used for window-wide checks (such as outside-click dismissal or routing+-- input to floating panels). Widgets should read 'askInput' instead so they do+-- not react through overlays.+{-# INLINE askFrameInput #-}+askFrameInput :: NanoUI Input+askFrameInput = NanoUI (repFrame <$> getStaticRep)++-- | Run a part of the view with another routed input.+{-# INLINE localInput #-}+localInput :: Input -> NanoUI a -> NanoUI a+localInput inp (NanoUI m) = NanoUI (localStaticRep (\r -> r {repInput = inp}) m)++-- | Display-only content sees neither routed nor raw interaction input.+-- Its container flag independently excludes its widgets from focus and IME.+inertView :: NanoUI a -> NanoUI a+inertView =+  withPaintScope (\_ outer -> pure (outer .|. 2))+    . localBothInputs (\i -> (withoutPointer (stripInteractionInput i)) {inputKeysHeld = mempty, inputComposition = Nothing})++-- | The window's content size in logical pixels ('NanoUI.winSize' of+-- 'NanoUI.askWindow').+{-# INLINE windowSize #-}+windowSize :: NanoUI Size+windowSize = fmap inputWindowSize askInput++-- | Width component of 'windowSize', in logical pixels.+{-# INLINE windowWidth #-}+windowWidth :: NanoUI Float+windowWidth = fmap (sizeW . inputWindowSize) askInput++-- | Height component of 'windowSize', in logical pixels.+{-# INLINE windowHeight #-}+windowHeight :: NanoUI Float+windowHeight = fmap (sizeH . inputWindowSize) askInput++-- | The session value of the backend driving this view, if it is the+-- backend asked for ('NanoUI.Backend.withBackendSession'). For a+-- backend's own view-side operations.+{-# INLINE askBackendSession #-}+askBackendSession :: SBackend b -> NanoUI (Maybe (BackendSession b))+askBackendSession backend = withContext (backendSession backend)++-- | Read an explicit typed host slot. 'Nothing' means it is uninstalled.+{-# INLINE askHost #-}+askHost :: Host a -> NanoUI (Maybe a)+askHost = liftIO . askHostIO++-- | Request repaint bounds relative to a widget's rectangle.+{-# INLINE damageWidgetNow #-}+damageWidgetNow :: WidgetId -> DamageBounds -> NanoUI ()+damageWidgetNow wid bounds = withContext (\ctx -> damageWidget ctx wid bounds)++-- | 'damageWidgetNow' using the integer store key of a widget.+{-# INLINE damageKeyNow #-}+damageKeyNow :: Int -> DamageBounds -> NanoUI ()+damageKeyNow k bounds = withContext (\ctx -> damageKey ctx k bounds)++-- | Request repaint of a rectangle in logical window coordinates.+{-# INLINE damageRectNow #-}+damageRectNow :: Rect -> NanoUI ()+damageRectNow r = withContext (\ctx -> damageRect ctx r)++-- | Request repaint bounds for each widget in a group.+{-# INLINE damageGroupNow #-}+damageGroupNow :: [WidgetId] -> DamageBounds -> NanoUI ()+damageGroupNow wids bounds = withContext (\ctx -> damagePeers ctx wids bounds)++-- | Request repaint of the entire window, for changes without widget bounds.+{-# INLINE damageFullNow #-}+damageFullNow :: NanoUI ()+damageFullNow = withContext damageFull++-- | Monadic variant of 'when'. Runs the second action if the first returns 'True'.+--+-- Example:+--+-- > whenM (button "Save") saveDocument+{-# INLINE whenM #-}+whenM :: Monad m => m Bool -> m () -> m ()+whenM mb ma = mb >>= \b -> when b ma++-- | Monadic variant of 'unless'. Runs the second action if the first returns 'False'.+{-# INLINE unlessM #-}+unlessM :: Monad m => m Bool -> m () -> m ()+unlessM mb ma = mb >>= \b -> unless b ma++-- | '&&' over effectful tests: the second runs only when the first holds.+infixr 3 <&&>++{-# INLINE (<&&>) #-}+(<&&>) :: Monad m => m Bool -> m Bool -> m Bool+a <&&> b = a >>= \ok -> if ok then b else pure False++-- | Monadic conditional selection.+{-# INLINE ifM #-}+ifM :: Monad m => m Bool -> m a -> m a -> m a+ifM mb t f = mb >>= \b -> if b then t else f++-- | Effectful 'Control.Monad.mfilter' over 'Maybe', avoiding a list allocation.+{-# INLINE mfilterM #-}+mfilterM :: Monad m => (a -> m Bool) -> Maybe a -> m (Maybe a)+mfilterM _ Nothing = pure Nothing+mfilterM p (Just x) = p x >>= \ok -> pure (if ok then Just x else Nothing)+
+ lib/NanoUI/Internal/Monad/Explain.hs view
@@ -0,0 +1,78 @@++-- | The layout overlay and arena ranges, from inside a view.+module NanoUI.Internal.Monad.Explain+  ( explainLayout+  , explainingLayout+  , explainedNode+  , explainScope+  , withArenaRange+  , inArenaRange+  )+where++import Control.Monad.IO.Class (MonadIO (liftIO))+import Data.IORef (modifyIORef')+import NanoUI.Internal.Context (Context (ctxNodeArena, ctxExplain), ExplainState (esScopes), ExplainedNode, getExplainLayout, getExplainedNode, setExplainLayout)+import NanoUI.Internal.Layout.Arena (arenaCount)+import NanoUI.Internal.Monad.Core (NanoUI, withContext, askContext)++-- | Turn the layout overlay on or off. It outlines every layout node one pixel+-- inside its edge, coloured by depth and drawn in the node's layer, and tints+-- the node under the pointer with its content box outlined. It does not+-- affect layout or input. A change repaints the whole window; setting the+-- current value is a no-op, so a view can call this every frame:+--+-- > on <- explainingLayout+-- > (_, on') <- withValue on (checkbox "Outline layout nodes")+-- > explainLayout on'+--+-- Backend options can enable it at startup (@sdlExplainLayout@,+-- @optExplainLayout@); on your own context use 'setExplainLayout' from+-- "NanoUI.Backend".+explainLayout :: Bool -> NanoUI ()+explainLayout on = withContext (\ctx -> setExplainLayout ctx on)++-- | Whether the layout overlay is on ('explainLayout').+explainingLayout :: NanoUI Bool+explainingLayout = withContext getExplainLayout++-- | The node under the pointer while the layout overlay is on, as laid out+-- last frame: its kind, rect and padding. 'Nothing' when the overlay is off+-- or the pointer is over no node. A change requests a frame, so a debug panel+-- showing it keeps up with the pointer.+explainedNode :: NanoUI (Maybe ExplainedNode)+explainedNode = withContext getExplainedNode++-- | Limit the layout overlay ('explainLayout') to the nodes the body adds and+-- their descendants. With several scopes, all of them are shown; with none,+-- the whole view is. With the overlay off this just runs the body, so it can+-- stay in a view:+--+-- > explainScope (settingsPanel model)+explainScope :: NanoUI a -> NanoUI a+explainScope body = do+  ctx <- askContext+  on <- liftIO (getExplainLayout ctx)+  if not on+    then body+    else withArenaRange (\from below -> modifyIORef' (ctxExplain ctx) (\es -> es {esScopes = (from, below) : esScopes es})) body++-- | Run @body@, then pass @record@ the range of arena indices it added,+-- @from@ up to but not including @below@. The arena appends nodes in+-- declaration order and a subtree follows its root, so the range covers+-- exactly the nodes the body declared and their descendants.+withArenaRange :: (Int -> Int -> IO ()) -> NanoUI a -> NanoUI a+withArenaRange record body = do+  ctx <- askContext+  let count = liftIO (arenaCount (ctxNodeArena ctx))+  !from <- count+  a <- body+  !below <- count+  liftIO (record from below)+  pure a++-- | Whether arena index @idx@ is in a range 'withArenaRange' recorded.+{-# INLINE inArenaRange #-}+inArenaRange :: Int -> Int -> Int -> Bool+inArenaRange from below idx = from <= idx && idx < below+
+ lib/NanoUI/Internal/Monad/Focus.hs view
@@ -0,0 +1,166 @@++-- | Keyboard focus, the last laid-out rect, the clipboard, frame requests and+-- Escape, from inside a view.+module NanoUI.Internal.Monad.Focus+  ( lastRect+  , holdFocus+  , releaseFocus+  , focusedWidget+  , isFocused+  , requestFocus+  , focusNext+  , focusPrevious+  , clearFocus+  , askFocus+  , getClipboard+  , setClipboard+  , requestFrame+  , takeEscape+  )+where++import Control.Monad (when, unless)+import Data.IORef (writeIORef)+import Data.Text (Text)+import NanoUI.Internal.Context (intKey, Context (ctxClipboardSet, ctxFocusVisible, ctxFocusId, ctxFocusRequest, ctxClipboardGet), FocusRequest (..), getPrevRect, isDisabled, isInert, markDirty, recordLayoutRead, escapeReserved, markEscapeConsumed, markTabConsumed, pointerBlockedByModal, getFocusId)+import NanoUI.Internal.Id (hashWidgetId, WidgetId (..))+import NanoUI.Internal.Input (Key (KeyEscape), Pressable (pressedOnceIn))+import NanoUI.Internal.Monad.Core (NanoUI, withContext, askInput)+import NanoUI.Internal.Types (Rect)++-- | Where a widget was laid out last frame, or 'Nothing' before its first.+-- A widget that works out its own input -- a list that scrolls itself, a+-- text view hit-testing a click -- reads the rect it will be given from here,+-- since this frame's is solved only after the view has run:+--+-- > wid <- nextId+-- > rect <- fromMaybe (Rect 0 0 320 240) <$> lastRect wid+-- > ... work out this frame from rect and the input ...+-- > customWidgetWithId wid spec+--+-- When this frame's layout moves or resizes the widget, another frame+-- follows, so the view gets to read the new rect.+lastRect :: WidgetId -> NanoUI (Maybe Rect)+lastRect wid = withContext $ \ctx -> do+  r <- getPrevRect ctx wid+  recordLayoutRead ctx (intKey wid) ((/= r) <$> getPrevRect ctx wid)+  pure r++-- | Focus a widget immediately without showing the keyboard focus ring. Call+-- this each frame while a condition holds; no-op if already focused.+--+-- Consumes Tab for the current frame so focus does not advance and an editor+-- can use Tab to indent. A click elsewhere still moves focus away until the+-- next frame's call restores it.+--+-- Ignored when called outside an open 'NanoUI.modal'+-- or on a disabled or inert widget.+holdFocus :: WidgetId -> NanoUI ()+holdFocus wid = withContext $ \ctx -> do+  focus <- getFocusId ctx+  inert <- isInert ctx wid+  disabled <- isDisabled ctx wid+  blocked <- pointerBlockedByModal ctx+  unless (inert || disabled || blocked) $ do+    markTabConsumed ctx+    when (focus /= wid) $ do+      writeIORef (ctxFocusId ctx) wid+      writeIORef (ctxFocusVisible ctx) False++-- | Clear keyboard focus from @wid@ immediately if it is currently focused.+-- Unlike 'clearFocus' (which applies at the end of the frame and collapses+-- text selection and menus), this takes effect immediately for subsequent+-- widgets in the same pass and preserves text field selection and menu state.+releaseFocus :: WidgetId -> NanoUI ()+releaseFocus wid = withContext $ \ctx -> do+  focus <- getFocusId ctx+  when (focus == wid) (writeIORef (ctxFocusId ctx) (WidgetId 0))++-- | Currently focused widget ID, or @'WidgetId' 0@ for none.+focusedWidget :: NanoUI WidgetId+focusedWidget = withContext getFocusId++-- | Whether @wid@ currently has keyboard focus.+isFocused :: WidgetId -> NanoUI Bool+isFocused wid = (\focus -> hashWidgetId wid /= 0 && focus == wid) <$> focusedWidget++-- | Request moving keyboard focus to @wid@ at the end of the frame, as Tab+-- would. A text field resumes with its caret where it was (at the end if never+-- edited), the widget shows the focus ring, and Tab continues from it. The+-- previously focused field drops its selection and menu, an open dropdown+-- closes, and on the next frame the prior field observes focus loss (committing+-- a combo box or search field).+--+-- > resp <- searchInput' "Find" query+-- > findPressed <- shortcut (ctrl <> key 'f')+-- > when findPressed (requestFocus (respId resp))+--+-- The request is applied at the end of the frame, against that frame's+-- layout, so it can name a widget declared later, such as the next one via+-- 'currentId':+--+-- > whenM (shortcut (ctrl <> key 'l')) (requestFocus =<< currentId)+-- > textInput address+--+-- Focus moves on the next frame, which the request schedules, and the+-- scrollers around the widget scroll it into view, as for Tab. The last+-- request in a frame wins ('focusNext', 'focusPrevious' and 'clearFocus' are+-- requests too). The request is ignored for a widget Tab would not stop at+-- this frame: one that is disabled, behind an open+-- 'NanoUI.modal', or not declared this frame. A radio+-- group's response names its last option, which is not a Tab stop.+-- Requesting the widget that already has focus is a no-op, so a view can+-- request it every frame. @'WidgetId' 0@ means 'clearFocus'.+requestFocus :: WidgetId -> NanoUI ()+requestFocus wid = askFocus (if hashWidgetId wid == 0 then FocusNowhere else FocusOn wid)++-- | Move focus to the next Tab stop at the end of the frame ('requestFocus').+focusNext :: NanoUI ()+focusNext = askFocus FocusNext++-- | Move focus to the previous Tab stop at the end of the frame+-- ('requestFocus').+focusPrevious :: NanoUI ()+focusPrevious = askFocus FocusPrevious++-- | Drop focus at the end of the frame ('requestFocus'), as a click outside+-- any text field or select does. The focused field drops its selection and+-- menu. 'releaseFocus' instead acts at once on one widget.+clearFocus :: NanoUI ()+clearFocus = askFocus FocusNowhere++askFocus :: FocusRequest -> NanoUI ()+askFocus req = withContext (\ctx -> writeIORef (ctxFocusRequest ctx) (Just req))++-- | The clipboard's text, through whatever clipboard the backend installed.+-- 'Nothing' for an empty clipboard or none at all.+getClipboard :: NanoUI (Maybe Text)+getClipboard = withContext ctxClipboardGet++-- | Put text on the clipboard. 'False' when the backend could not.+setClipboard :: Text -> NanoUI Bool+setClipboard txt = withContext (\ctx -> ctxClipboardSet ctx txt)++-- | Schedule a full-window repaint on the next frame, for external state+-- changes not tracked by 'NanoUI.Var.Var'. Avoid calling unconditionally every+-- frame, as that prevents the event loop from sleeping; use+-- 'NanoUI.wakeAfter' for timed frames.+requestFrame :: NanoUI ()+requestFrame = withContext markDirty++-- | Consume an Escape press this frame and return 'True' if it was available.+-- Returns 'False' if Escape was not pressed, was already consumed earlier in+-- the frame, is reserved by an open text-field menu or dropdown (including a+-- focused combo box), or is blocked by an open modal.+takeEscape :: NanoUI Bool+takeEscape = do+  inp <- askInput+  if not (pressedOnceIn KeyEscape inp)+    then pure False+    else withContext $ \ctx -> do+      reserved <- escapeReserved ctx+      blocked <- pointerBlockedByModal ctx+      let ours = not reserved && not blocked+      when ours (markEscapeConsumed ctx)+      pure ours+
+ lib/NanoUI/Internal/Monad/Scroll.hs view
@@ -0,0 +1,92 @@+-- | Scroll queries, tuning, and commands from inside a view.+module NanoUI.Internal.Monad.Scroll+  ( getScrollTuning+  , setScrollTuning+  , getScrollMetrics+  , setScrollOffset+  , scrollTo+  , scrollBy+  , scrollPages+  , scrollToStart+  , scrollToEnd+  , scrollIntoView+  , scrollRectIntoView+  , setScrollStep+  )+where++import NanoUI.Internal.Context qualified as Ctx+import NanoUI.Internal.Context (ScrollAlign, ScrollBehavior, ScrollMetrics (scrollAxes), ScrollTuning)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Monad.Core (NanoUI, withContext)+import NanoUI.Internal.Types (Rect, V2)++-- | Read the session's global wheel-step and smooth-scroll tuning.+getScrollTuning :: NanoUI ScrollTuning+getScrollTuning = withContext Ctx.getScrollTuning++-- | Configure wheel-step distance and smooth-scroll duration for the session.+setScrollTuning :: ScrollTuning -> NanoUI ()+setScrollTuning tuning = withContext (`Ctx.setScrollTuning` tuning)++-- | The scroller's geometry from the previous layout (viewport, range, and+-- offset), or 'Nothing' before its first layout. The id comes from+-- 'NanoUI.scrollWith'', 'NanoUI.scroll2DWith'', or 'NanoUI.scrollConfigured'';+-- to query or command a scroller before it is declared, read its id with+-- 'NanoUI.currentId' first:+--+-- > sid <- currentId+-- > metrics <- getScrollMetrics sid+-- > (rows, _) <- scrollWith' (fillW . fillH) (visibleRows metrics)+--+-- If this frame's layout changes the metrics, a follow-up frame is scheduled.+getScrollMetrics :: WidgetId -> NanoUI (Maybe ScrollMetrics)+getScrollMetrics wid = withContext (`Ctx.getScrollMetrics` wid)++-- | Put a scroller at an offset in window axes, cancelling a glide; a 1D+-- scroller ignores the axis it does not scroll on, and a row scroller takes+-- its offset in x. Unlike 'scrollTo', the offset is not held to the range+-- the last layout found, so it can place content this frame is about to lay+-- out; the layout holds it to the content's real range.+setScrollOffset :: WidgetId -> V2 -> NanoUI ()+setScrollOffset wid off = withContext $ \ctx ->+  Ctx.readScrollMetrics ctx wid >>= \case+    Just m -> Ctx.setScrollOffsetIn ctx wid (scrollAxes m) off+    Nothing -> Ctx.setScrollOffsetPending ctx wid off++-- | Scroll to an offset, held to the scroller's range.+scrollTo :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()+scrollTo wid off behavior = withContext (\ctx -> Ctx.scrollTo ctx wid off behavior)++-- | Scroll by a delta in pixels.+scrollBy :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()+scrollBy wid delta behavior = withContext (\ctx -> Ctx.scrollBy ctx wid delta behavior)++-- | Scroll by whole viewports: @V2 0 0.5@ is half a page down.+scrollPages :: WidgetId -> V2 -> ScrollBehavior -> NanoUI ()+scrollPages wid pages behavior = withContext (\ctx -> Ctx.scrollPages ctx wid pages behavior)++-- | Scroll back to the top (and left).+scrollToStart :: WidgetId -> ScrollBehavior -> NanoUI ()+scrollToStart wid behavior = withContext (\ctx -> Ctx.scrollToStart ctx wid behavior)++-- | Scroll to the end of the content.+scrollToEnd :: WidgetId -> ScrollBehavior -> NanoUI ()+scrollToEnd wid behavior = withContext (\ctx -> Ctx.scrollToEnd ctx wid behavior)++-- | Scroll widget @target@ into the viewport of scroller @wid@ it lives in,+-- using last frame's layout. For virtualized lists that omit off-screen rows,+-- use 'scrollRectIntoView' with the row's content rectangle instead.+scrollIntoView :: WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> NanoUI ()+scrollIntoView wid target align behavior = withContext (\ctx -> Ctx.scrollIntoView ctx wid target align behavior)++-- | Scroll a rectangle of the content, in content coordinates, into view:+-- the row a keyboard selection moved to in a list that builds only the rows+-- it shows.+scrollRectIntoView :: WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> NanoUI ()+scrollRectIntoView wid r align behavior = withContext (\ctx -> Ctx.scrollRectIntoView ctx wid r align behavior)++-- | Give a scroller its own wheel step, in pixels per notch; @0@ restores the+-- session's default.+setScrollStep :: WidgetId -> Float -> NanoUI ()+setScrollStep wid px = withContext (\ctx -> Ctx.setScrollStep ctx wid px)
+ lib/NanoUI/Internal/NativeWindow.hs view
@@ -0,0 +1,502 @@+-- | The native window a view runs in: its opening settings+-- ('WindowSettings'), its state each frame ('askWindow'), the requests a view+-- makes of it (title, icon, size limits, mode, position, screenshots,+-- quitting), and the RGBA pixels used for icons and screenshots.+--+-- A backend opens the window from a 'WindowSettings', installs a+-- 'WindowHost' that carries out requests, and reports the window's state+-- once a frame. Without a host, as under a test context, requests do+-- nothing, 'requestScreenshot' answers 'Nothing', and 'askWindow' describes+-- a focused window the size of the frame's input.+module NanoUI.Internal.NativeWindow+  ( -- * Pixels+    RgbaPixels+  , rgbaPixels+  , rgbaWidth+  , rgbaHeight+  , rgbaBytes+  , Screenshot (..)++    -- * Settings+  , WindowSettings (..)+  , defaultWindowSettings+  , sizeLimitAt+  , WindowPosition (..)+  , WindowMode (..)++    -- * State+  , WindowState (..)+  , defaultWindowState+  , askWindow+  , WindowCapabilities (..)+  , noWindowCapabilities+  , allWindowCapabilities+  , askWindowCapabilities++    -- * From a view+  , setWindowTitle+  , setWindowIcon+  , setWindowMinSize+  , setWindowMaxSize+  , setWindowOpacity+  , setWindowMode+  , moveWindow+  , centerWindow+  , resizeWindow+  , minimizeWindow+  , maximizeWindow+  , restoreWindow+  , toggleMaximized+  , quit+  , requestScreenshot+  , askScreenshot+  , useScreenshot++    -- * Backends+  , WindowHost (..)+  , defaultWindowHost+  , installWindowHost+  , closeWindowHost+  , closeWindowSlot+  , reportWindowState+  , answerScreenshots+  , answerScreenshotsAfter+  , requestWindowClose+  , clearWindowClose+  , quitRequested+  ) where++import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException, finally, mask, throwIO, try)+import Control.Monad (join, unless, when)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.Foldable (traverse_)+import Data.IORef (atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import NanoUI.Internal.Context (Context (ctxNativeWindow), markDirty, wakeAction)+import NanoUI.Internal.Host (Host, askHostIO, clearHost, setHost)+import NanoUI.Internal.NativeWindow.Types+import NanoUI.Internal.Monad (NanoUI, windowSize, withContext)+import NanoUI.Internal.Tasks (Task, useTask)+import NanoUI.Internal.Types (Size (..))++-- | Pixels @width@ by @height@, or 'Nothing' when either is not positive or+-- the byte count is not @4 * width * height@. To draw them, register them+-- with @registerImageRgba iid (rgbaWidth p) (rgbaHeight p) (rgbaBytes p)@.+rgbaPixels :: Int -> Int -> ByteString -> Maybe RgbaPixels+rgbaPixels w h bytes+  | w > 0 && h > 0 && toInteger (BS.length bytes) == toInteger w * toInteger h * 4 = Just (RgbaPixels w h bytes)+  | otherwise = Nothing++-- | A resizable, opaque 1280x800 window titled @"nano-ui"@, placed by the+-- desktop, with no size limits and the desktop's icon. Closing it ends the+-- session.+defaultWindowSettings :: WindowSettings+defaultWindowSettings =+  WindowSettings+    { wsTitle = "nano-ui"+    , wsSize = Size 1280 800+    , wsPosition = WindowPositionDefault+    , wsMinSize = Nothing+    , wsMaxSize = Nothing+    , wsIcon = Nothing+    , wsResizable = True+    , wsMode = Windowed+    , wsTransparent = False+    , wsOpacity = 1+    , wsExitOnCloseRequest = True+    }++-- | A size limit in layout units ('wsMinSize', 'wsMaxSize') in whole native+-- units at @scale@ per layout unit, plus @outset@ on each axis, such as a+-- desktop frame the native limit includes. A missing limit, or an axis of+-- zero or less, NaN or infinity, is 0 on that axis: no limit. A limit stops+-- at the largest 32-bit size, which is what hosts take.+sizeLimitAt :: Float -> (Int, Int) -> Maybe Size -> (Int, Int)+sizeLimitAt scale (outW, outH) limit+  | not (scale > 0) || isInfinite scale = (0, 0)+  | otherwise = (axis w outW, axis h outH)+  where+    Size w h = fromMaybe (Size 0 0) limit+    axis v outset = if not (v > 0) || isInfinite v then 0 else min 0x7FFFFFFF (round (min 3.0e9 (v * scale)) + outset)++-- | The state without a window, as under a test context: focused, scale 1,+-- unknown position, no special mode. 'askWindow' fills in the frame's size.+defaultWindowState :: WindowState+defaultWindowState =+  WindowState+    { winSize = Size 0 0+    , winScale = 1+    , winPosition = Nothing+    , winFocused = True+    , winMaximized = False+    , winMinimized = False+    , winFullscreen = False+    , winCloseRequested = False+    }++-- | The window as the backend reported it at the start of this frame, plus+-- whether it was asked to close. Its 'winSize' is 'NanoUI.windowSize'. Once+-- a view reads it, a change (in focus, say) triggers a frame; a view that+-- never reads it pays nothing.+askWindow :: NanoUI WindowState+askWindow = do+  size <- windowSize+  withContext $ \ctx ->+    askHostIO (ctxNativeWindow ctx) >>= \case+      Nothing -> pure defaultWindowState {winSize = size}+      Just nw -> do+        writeIORef (nwStateRead nw) True+        (\st -> st {winSize = size}) <$> readIORef (nwState nw)++-- | What a host supports, for a view to check before offering a control+-- ('WindowCapabilities'). Nothing without a window, as under a test context.+askWindowCapabilities :: NanoUI WindowCapabilities+askWindowCapabilities =+  withContext $ \ctx ->+    maybe noWindowCapabilities (hostCapabilities . nwHost) <$> askHostIO (ctxNativeWindow ctx)++-- | Supports no request.+noWindowCapabilities :: WindowCapabilities+noWindowCapabilities = WindowCapabilities False False False False False False False False False++-- | Supports every request.+allWindowCapabilities :: WindowCapabilities+allWindowCapabilities = WindowCapabilities True True True True True True True True True++-- | No-op host with 'noWindowCapabilities'. Backends override the operations+-- they support and set 'hostCapabilities' to match.+defaultWindowHost :: WindowHost+defaultWindowHost =+  WindowHost+    { hostCapabilities = noWindowCapabilities+    , hostSetTitle = \_ -> pure ()+    , hostSetIcon = \_ -> pure ()+    , hostSetMinSize = \_ -> pure ()+    , hostSetMaxSize = \_ -> pure ()+    , hostSetOpacity = \_ -> pure ()+    , hostSetMode = \_ -> pure ()+    , hostMove = \_ _ -> pure ()+    , hostCenter = pure ()+    , hostResize = \_ -> pure ()+    , hostMinimize = pure ()+    , hostMaximize = pure ()+    , hostRestore = pure ()+    }++-- | Install the host for the context's window. The backend has already+-- opened the window from @settings@ with its title, size, mode,+-- resizability and transparency; this applies the size limits, icon,+-- opacity and position through the host, in that order. Call it once before+-- the first frame. A later call replaces the host and answers the old one's+-- pending screenshots with 'Nothing'.+installWindowHost :: Context -> WindowSettings -> WindowHost -> IO ()+installWindowHost ctx settings host = do+  closeWindowHost ctx+  nw <-+    NativeWindow host+      <$> newIORef settings {wsMinSize = Nothing, wsMaxSize = Nothing, wsIcon = Nothing, wsOpacity = 1}+      <*> newIORef defaultWindowState+      <*> newIORef False+      <*> newIORef False+      <*> newIORef (Just [])+  setHost (ctxNativeWindow ctx) nw+  setMinSize nw (wsMinSize settings)+  setMaxSize nw (wsMaxSize settings)+  traverse_ (setIcon nw) (wsIcon settings)+  setOpacity nw (wsOpacity settings)+  case wsPosition settings of+    WindowPositionDefault -> pure ()+    WindowPositionCentered -> hostCenter host+    WindowPositionAt x y -> hostMove host x y++-- | End native-window access before releasing the platform window. Pending+-- screenshots receive Nothing, including actions obtained before closing but+-- invoked afterwards. Idempotent; call even if the opening frame failed.+-- Every queued callback is attempted before a callback exception propagates.+closeWindowHost :: Context -> IO ()+closeWindowHost = closeWindowSlot . ctxNativeWindow++-- | 'closeWindowHost' on the context's 'ctxNativeWindow', for a caller that+-- keeps the slot rather than the context.+closeWindowSlot :: Host NativeWindow -> IO ()+closeWindowSlot slot = mask $ \_ -> do+  old <- askHostIO slot+  clearHost slot+  traverse_ (\nw -> do+    waiting <- atomicModifyIORef' (nwShots nw) (Nothing,)+    completeScreenshots Nothing (reverse (fromMaybe [] waiting))) old++-- | Report the window's state once a frame, before the view runs. The+-- 'winSize' and 'winCloseRequested' passed in are ignored; they come from+-- the frame input and the session loop. A change other than a position-only+-- move triggers a frame if a view reads the state.+reportWindowState :: Context -> WindowState -> IO ()+reportWindowState ctx st =+  withHost ctx $ \nw -> do+    old <- readIORef (nwState nw)+    let new = st {winCloseRequested = winCloseRequested old}+    unless (new == old) $ do+      writeIORef (nwState nw) new+      read' <- readIORef (nwStateRead nw)+      -- The view may paint the state (a colour on focus) where no diff sees+      -- it, so the frame repaints whole. A position-only move updates the+      -- stored coordinates without forcing a repaint.+      when (read' && new {winPosition = winPosition old} /= old) (markDirty ctx)++-- | For the session loop when the window is asked to close. Returns 'True'+-- when the session should end ('wsExitOnCloseRequest' set, or no host).+-- Otherwise sets 'winCloseRequested' and requests a frame; call+-- 'clearWindowClose' after that frame runs.+requestWindowClose :: Context -> IO Bool+requestWindowClose ctx =+  askHostIO (ctxNativeWindow ctx) >>= \case+    Nothing -> pure True+    Just nw -> do+      exits <- wsExitOnCloseRequest <$> readIORef (nwSettings nw)+      unless exits $ do+        modifyIORef' (nwState nw) (\s -> s {winCloseRequested = True})+        markDirty ctx+      pure exits++-- | Clear 'winCloseRequested' after the frame that saw it.+clearWindowClose :: Context -> IO ()+clearWindowClose ctx = withHost ctx $ \nw -> modifyIORef' (nwState nw) (\s -> s {winCloseRequested = False})++-- | Whether a view called 'quit'. The session loop checks after each+-- frame.+quitRequested :: Context -> IO Bool+quitRequested ctx = maybe (pure False) (readIORef . nwQuit) =<< askHostIO (ctxNativeWindow ctx)++withHost :: Context -> (NativeWindow -> IO ()) -> IO ()+withHost ctx act = askHostIO (ctxNativeWindow ctx) >>= traverse_ act++withNativeWindow :: (NativeWindow -> IO ()) -> NanoUI ()+withNativeWindow act = withContext (`withHost` act)++hostAction :: (WindowHost -> IO ()) -> NanoUI ()+hostAction f = withNativeWindow (f . nwHost)++-- | Apply a setting through the host only when it differs from the current+-- one.+setting :: Eq a => (WindowSettings -> a) -> (a -> WindowSettings -> WindowSettings) -> (WindowHost -> a -> IO ()) -> NativeWindow -> a -> IO ()+setting get put apply nw v = do+  s <- readIORef (nwSettings nw)+  unless (get s == v) $ do+    apply (nwHost nw) v+    modifyIORef' (nwSettings nw) (put v)++-- | Set one size limit. On an axis where the minimum would pass the maximum,+-- the limit being set wins and the other moves to it, and goes to the host+-- first, so the host never sees a crossed pair: most desktops reject one+-- (SDL keeps the old limit) and a Wayland compositor disconnects the client.+setMinSize, setMaxSize :: NativeWindow -> Maybe Size -> IO ()+setMinSize nw v = do+  other <- wsMaxSize <$> readIORef (nwSettings nw)+  putMaxSize nw (yieldLimit (>) v other)+  putMinSize nw v+setMaxSize nw v = do+  other <- wsMinSize <$> readIORef (nwSettings nw)+  putMinSize nw (yieldLimit (<) v other)+  putMaxSize nw v++putMinSize, putMaxSize :: NativeWindow -> Maybe Size -> IO ()+putMinSize = setting wsMinSize (\v s -> s {wsMinSize = v}) hostSetMinSize+putMaxSize = setting wsMaxSize (\v s -> s {wsMaxSize = v}) hostSetMaxSize++-- | @other@ with each axis that @crosses@ the limit @new@ sets moved to+-- @new@'s. An axis of zero or less, or a missing limit, crosses nothing.+yieldLimit :: (Float -> Float -> Bool) -> Maybe Size -> Maybe Size -> Maybe Size+yieldLimit crosses (Just (Size nw nh)) (Just (Size ow oh)) = Just (Size (axis nw ow) (axis nh oh))+  where+    axis n o = if n > 0 && o > 0 && crosses n o then n else o+yieldLimit _ _ other = other++setIcon :: NativeWindow -> RgbaPixels -> IO ()+setIcon nw = setting wsIcon (\v s -> s {wsIcon = v}) (traverse_ . hostSetIcon) nw . Just++setOpacity :: NativeWindow -> Float -> IO ()+setOpacity nw v+  | isNaN v || isInfinite v = pure ()+  | otherwise = setting wsOpacity (\x s -> s {wsOpacity = x}) hostSetOpacity nw (max 0 (min 1 v))++-- | Set the window title ('wsTitle').+--+-- This and the setters below do nothing when the value matches the last one+-- set, so calling them every frame costs only a comparison.+setWindowTitle :: Text -> NanoUI ()+setWindowTitle t = withNativeWindow (\nw -> setting wsTitle (\v s -> s {wsTitle = v}) hostSetTitle nw t)++-- | Set the window icon ('wsIcon').+setWindowIcon :: RgbaPixels -> NanoUI ()+setWindowIcon icon = withNativeWindow (`setIcon` icon)++-- | Set the smallest size, in layout units, the user can resize the window+-- to, or remove the limit with 'Nothing'. A zero axis is unlimited. The size+-- is converted at the UI scale when the limit is set, and not again if the+-- scale changes later. Where it passes the maximum size, the maximum is+-- raised to it; 'setWindowMaxSize' likewise lowers a minimum above it.+setWindowMinSize :: Maybe Size -> NanoUI ()+setWindowMinSize s = withNativeWindow (`setMinSize` s)++-- | Set the largest size the user can resize the window to, as for+-- 'setWindowMinSize'.+setWindowMaxSize :: Maybe Size -> NanoUI ()+setWindowMaxSize s = withNativeWindow (`setMaxSize` s)++-- | Set the opacity of the whole window, decorations included, from 0+-- (invisible) to 1 (opaque), clamped, where the backend and desktop support+-- it ('wsOpacity'). For a see-through background use 'wsTransparent'.+setWindowOpacity :: Float -> NanoUI ()+setWindowOpacity o = withNativeWindow (`setOpacity` o)++-- | Make the window windowed, fullscreen or hidden ('wsMode'). The desktop+-- can change the mode too (with its own fullscreen control, say), which+-- 'winFullscreen' in 'askWindow' then shows; asking again for the mode last+-- set still does nothing.+--+-- > fullscreen <- useVar False+-- > whenM (shortcut (key (KeyF 11))) (modifyVar fullscreen not)+-- > full <- readVar fullscreen+-- > setWindowMode (if full then Fullscreen else Windowed)+setWindowMode :: WindowMode -> NanoUI ()+setWindowMode m = withNativeWindow (\nw -> setting wsMode (\v s -> s {wsMode = v}) hostSetMode nw m)++-- | Move the window's top-left corner to a desktop point: window coordinates+-- on SDL, pixels on RGFW.+--+-- This and the commands below act on every call, because the user can also+-- move, resize, maximize and restore the window. Call them from an event,+-- not every frame. Some desktops ignore placement (Wayland does), and a+-- maximized or fullscreen window stays put.+moveWindow :: Int -> Int -> NanoUI ()+moveWindow x y = hostAction (\h -> hostMove h x y)++-- | Center the window on its display.+centerWindow :: NanoUI ()+centerWindow = hostAction hostCenter++-- | Resize the view to a size in layout units, excluding the desktop's+-- decorations.+resizeWindow :: Size -> NanoUI ()+resizeWindow s = hostAction (`hostResize` s)++-- | Minimize the window to the taskbar.+minimizeWindow :: NanoUI ()+minimizeWindow = hostAction hostMinimize++-- | Maximize the window, leaving the desktop's panels visible.+maximizeWindow :: NanoUI ()+maximizeWindow = hostAction hostMaximize++-- | Return a maximized or minimized window to its previous size.+restoreWindow :: NanoUI ()+restoreWindow = hostAction hostRestore++-- | Maximize the window, or restore it if it is maximized. Reads+-- 'winMaximized', since the desktop can maximize the window itself (on a+-- title bar double-click, say).+toggleMaximized :: NanoUI ()+toggleMaximized = withNativeWindow $ \nw -> do+  maxed <- winMaximized <$> readIORef (nwState nw)+  (if maxed then hostRestore else hostMaximize) (nwHost nw)++-- | End the session after this frame is drawn; the backend's runner closes+-- the window and returns. With 'wsExitOnCloseRequest' off, this is how the+-- window closes.+quit :: NanoUI ()+quit = withNativeWindow (\nw -> writeIORef (nwQuit nw) True)++-- | Request a screenshot of the frame this view is building. The action runs+-- on the UI thread after that frame is presented and before the next one+-- starts. It gets 'Nothing' when the backend cannot capture, immediately if+-- there is no window.+--+-- Each call is answered once. Request from an event such as a click, not+-- every frame, or the view never stops redrawing and capturing. Keep the+-- action short (an 'IORef' write, a 'Control.Concurrent.forkIO' of the+-- encoding), since the next frame waits on it. A frame follows each answer,+-- so the view can show the result. 'useScreenshot' returns the screenshot to+-- the view directly.+requestScreenshot :: (Maybe Screenshot -> IO ()) -> NanoUI ()+requestScreenshot answer = withContext $ \ctx -> askHostIO (ctxNativeWindow ctx) >>= maybe (answer Nothing) (`queueScreenshot` answer)++-- | Queue an answer for 'answerScreenshots'.+queueScreenshot :: NativeWindow -> (Maybe Screenshot -> IO ()) -> IO ()+queueScreenshot nw answer = do+  accepted <- atomicModifyIORef' (nwShots nw) $ \case+    Nothing -> (Nothing, False)+    Just waiting -> (Just (answer : waiting), True)+  unless accepted (answer Nothing)++-- | An action for another thread, such as a 'NanoUI.useTaskStatus' job. It+-- wakes the loop, waits for the next frame to be presented, and returns a+-- screenshot of it, as 'requestScreenshot' does. Without a window it returns+-- 'Nothing' at once, also after that window is closed or replaced. On the UI+-- thread it deadlocks while the window is open.+--+-- > shoot <- askScreenshot+-- > saved <- useTaskStatus task shots (shoot >>= traverse_ (savePng "shot.png"))+askScreenshot :: NanoUI (IO (Maybe Screenshot))+askScreenshot = withContext $ \ctx -> do+  let !wake = wakeAction ctx+  maybe (pure Nothing) (shoot wake) <$> askHostIO (ctxNativeWindow ctx)+  where+    shoot :: IO () -> NativeWindow -> IO (Maybe Screenshot)+    shoot wake nw = do+      box <- newEmptyMVar+      queueScreenshot nw (putMVar box)+      wake+      takeMVar box++-- | A screenshot per key. The first frame with a new key requests one, which+-- arrives a frame or two later; until then it returns the previous key's+-- screenshot, as 'useTask' does. Allocate @task <- newTask@ during setup;+-- change the key to take another screenshot. This consumes no widget id.+--+-- > shotsVar <- useVar (0 :: Int)+-- > whenM (button "Screenshot") (modifyVar shotsVar (+ 1))+-- > shots <- readVar shotsVar+-- > shot <- if shots == 0 then pure Nothing else useScreenshot task shots+useScreenshot :: Eq k => Task k (Maybe Screenshot) -> k -> NanoUI (Maybe Screenshot)+useScreenshot owner k = join <$> (useTask owner k =<< askScreenshot)++-- | Answer every screenshot request since the last call, in request order,+-- with one run of @capture@, which does not run when none are pending. A+-- backend calls this once a frame is presented, and not while it has no+-- frame to capture. The scale is the last one given to 'reportWindowState'.+--+-- Answers are view code that usually changes what a view reads, outside+-- anything the damage pass diffs, so answering any requests a frame that+-- repaints whole.+answerScreenshots :: Context -> IO (Maybe RgbaPixels) -> IO ()+answerScreenshots ctx capture = answerScreenshotsAfter ctx capture (pure ())++-- | Capture only if requests are pending, run the presentation action, then+-- deliver the answers. For a backbuffer that must be read before presentation.+-- Capture or presentation failure answers the batch with Nothing before+-- propagating the exception. A throwing callback cannot strand later answers.+answerScreenshotsAfter :: Context -> IO (Maybe RgbaPixels) -> IO () -> IO ()+answerScreenshotsAfter ctx capture present = mask $ \restore -> do+  host <- askHostIO (ctxNativeWindow ctx)+  waiting <- maybe (pure [])+    (\nw -> atomicModifyIORef' (nwShots nw) (\pending -> (fmap (const []) pending, reverse (fromMaybe [] pending)))) host+  if null waiting then restore present else do+    outcome <- try @SomeException $ restore $ do+      scale <- maybe (pure 1) (fmap winScale . readIORef . nwState) host+      shot <- fmap (`Screenshot` scale) <$> capture+      present+      pure shot+    delivered <- try @SomeException $+      completeScreenshots (either (const Nothing) id outcome) waiting+        `finally` markDirty ctx+    either throwIO (const (either throwIO pure delivered)) outcome++completeScreenshots :: Maybe Screenshot -> [Maybe Screenshot -> IO ()] -> IO ()+completeScreenshots shot answers = mask $ \restore -> do+  results <- mapM (try @SomeException . restore . ($ shot)) answers+  case [e | Left e <- results] of+    e : _ -> throwIO e+    [] -> pure ()
+ lib/NanoUI/Internal/NativeWindow/Types.hs view
@@ -0,0 +1,159 @@+-- | Window values and backend callbacks, independent of the UI context.+module NanoUI.Internal.NativeWindow.Types+  ( RgbaPixels (..)+  , Screenshot (..)+  , WindowSettings (..)+  , WindowPosition (..)+  , WindowMode (..)+  , WindowState (..)+  , WindowHost (..)+  , WindowCapabilities (..)+  , NativeWindow (..)+  )+where++import Data.ByteString (ByteString)+import Data.IORef (IORef)+import Data.Text (Text)+import NanoUI.Internal.Types (Size)++-- | RGBA8, top-to-bottom tightly packed rows with straight alpha. Construct+-- through 'NanoUI.rgbaPixels' to check the byte count.+data RgbaPixels = RgbaPixels+  { rgbaWidth :: !Int+  -- ^ Width in pixels.+  , rgbaHeight :: !Int+  -- ^ Height in pixels.+  , rgbaBytes :: !ByteString+  -- ^ Exactly four bytes per pixel.+  }+  deriving Eq++instance Show RgbaPixels where+  showsPrec d (RgbaPixels w h _) =+    showParen+      (d > 10)+      (showString "RgbaPixels " . shows w . showString "x" . shows h)++-- | Presented pixels and pixels per logical layout unit.+data Screenshot = Screenshot+  { screenshotPixels :: !RgbaPixels+  , screenshotScale :: !Float+  }+  deriving (Eq, Show)++-- | Backend-independent initial window settings. Sizes are in layout units.+data WindowSettings = WindowSettings+  { wsTitle :: !Text+  -- ^ Title bar/taskbar text, initially "nano-ui".+  , wsSize :: !Size+  -- ^ Initial logical view size, normally 1280 by 800.+  , wsPosition :: !WindowPosition+  , wsMinSize :: !(Maybe Size)+  -- ^ Nothing or a zero axis means no limit.+  , wsMaxSize :: !(Maybe Size)+  , wsIcon :: !(Maybe RgbaPixels)+  , wsResizable :: !Bool+  , wsMode :: !WindowMode+  , wsTransparent :: !Bool+  -- ^ Desktop transparency where the page background is translucent; set it+  -- with 'NanoUI.pageColor' (an unset page is 'NanoUI.themeWindow'). SDL supports it with a+  -- compositor; RGFW windows are opaque.+  , wsOpacity :: !Float+  -- ^ Whole-window opacity, including decorations, from 0 to 1 (SDL only).+  , wsExitOnCloseRequest :: !Bool+  -- ^ True ends the session on a platform close request. False exposes+  -- 'winCloseRequested' so the view can confirm unsaved work before quitting.+  }+  deriving (Eq, Show)++-- | Where a new window opens.+data WindowPosition+  = -- | Desktop placement (centred by RGFW).+    WindowPositionDefault+  | -- | The centre of the desktop.+    WindowPositionCentered+  | -- | Top-left corner in desktop coordinates.+    WindowPositionAt !Int !Int+  deriving (Eq, Show)++-- | Display state of a window: an ordinary window, a fullscreen window, or a+-- window that is not shown.+data WindowMode = Windowed | Fullscreen | Hidden+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | The window as reported at frame start.+data WindowState = WindowState+  { winSize :: !Size+  -- ^ View size in logical layout units.+  , winScale :: !Float+  -- ^ Physical pixels per layout unit.+  , winPosition :: !(Maybe (Int, Int))+  -- ^ Desktop coordinates, when available (not reported on Wayland).+  , winFocused :: !Bool+  , winMaximized :: !Bool+  , winMinimized :: !Bool+  , winFullscreen :: !Bool+  , winCloseRequested :: !Bool+  -- ^ A one-frame request when automatic close handling is disabled.+  }+  deriving (Eq, Show)++-- | Backend operations invoked on the UI thread. Sizes are in layout units;+-- zero axes or absent size limits mean unlimited. Build from defaultWindowHost.+data WindowHost = WindowHost+  { hostCapabilities :: !WindowCapabilities+  -- ^ The requests this host carries out; the rest do nothing.+  , hostSetTitle :: Text -> IO ()+  , hostSetIcon :: RgbaPixels -> IO ()+  , hostSetMinSize :: Maybe Size -> IO ()+  , hostSetMaxSize :: Maybe Size -> IO ()+  , hostSetOpacity :: Float -> IO ()+  , hostSetMode :: WindowMode -> IO ()+  , hostMove :: Int -> Int -> IO ()+  , hostCenter :: IO ()+  , hostResize :: Size -> IO ()+  , hostMinimize :: IO ()+  , hostMaximize :: IO ()+  , hostRestore :: IO ()+  }++-- | Which window requests a backend carries out on this platform. A request+-- it does not support does nothing, and the window's state+-- ('NanoUI.askWindow') stays as it was, so check before offering a control+-- for it. Even a supported request can be refused or adjusted by the desktop;+-- the reported state says what happened.+data WindowCapabilities = WindowCapabilities+  { wcTitle :: !Bool+  -- ^ 'NanoUI.setWindowTitle'.+  , wcIcon :: !Bool+  -- ^ 'NanoUI.setWindowIcon'.+  , wcSizeLimits :: !Bool+  -- ^ 'NanoUI.setWindowMinSize' and 'NanoUI.setWindowMaxSize'.+  , wcOpacity :: !Bool+  -- ^ 'NanoUI.setWindowOpacity'.+  , wcMode :: !Bool+  -- ^ 'NanoUI.setWindowMode'.+  , wcMove :: !Bool+  -- ^ 'NanoUI.moveWindow' and 'NanoUI.centerWindow'. Not on Wayland,+  -- where only the compositor places windows.+  , wcResize :: !Bool+  -- ^ 'NanoUI.resizeWindow'.+  , wcMinimize :: !Bool+  -- ^ 'NanoUI.minimizeWindow'.+  , wcMaximize :: !Bool+  -- ^ 'NanoUI.maximizeWindow', 'NanoUI.restoreWindow' and+  -- 'NanoUI.toggleMaximized'.+  }+  deriving (Eq, Show)++-- | Concrete session-owned host, last settings/state, and pending callbacks.+data NativeWindow = NativeWindow+  { nwHost :: !WindowHost+  , nwSettings :: !(IORef WindowSettings)+  , nwState :: !(IORef WindowState)+  , nwStateRead :: !(IORef Bool)+  , nwQuit :: !(IORef Bool)+  , nwShots :: !(IORef (Maybe [Maybe Screenshot -> IO ()]))+  -- ^ Nothing closes the queue atomically, including captured thread actions.+  }
+ lib/NanoUI/Internal/Path.hs view
@@ -0,0 +1,1733 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Paths, affine transforms, and the geometry that turns them into draw ops:+-- curve flattening, SVG arc conversion, nesting rings into polygons with+-- holes, triangulation for 'FillPolygon', dashes, miters and gradients.+-- Shared by the canvas ("NanoUI.Path", "NanoUI.Widgets.Custom"), the SVG+-- rasterizer ("NanoUI.Svg") and nano-ui-diagrams.+module NanoUI.Internal.Path+  ( -- * Paths+    Path (..)+  , Segment (..)+  , moveTo+  , lineTo+  , quadTo+  , cubicTo+  , arc+  , ellipticalArc+  , arcTo+  , close+    -- * Shapes+  , rect+  , roundedRect+  , roundedRectCorners+  , circle+  , ellipse+  , polygon+  , polyline+    -- * Transforms+  , Transform (..)+  , applyTransform+  , translate+  , rotate+  , rotateAround+  , scale+  , affine+  , transformPoint+  , invert+  , transformFinite+  , averageStretch+    -- * Strokes, fills and paints+  , Stroke (..)+  , stroke+  , LineCap (..)+  , LineJoin (..)+  , miterOffset+  , FillRule (..)+  , fillsWinding+  , ringBox+  , Paint (..)+  , Shade (..)+    -- * Rings+  , Rings (..)+  , ringCount+  , shoelace+  , buildRings+  , cleanRings+    -- * Flattening+  , curveTolerance+  , flattenPath+  , idealArcSteps+    -- * Draw ops+  , fillPathOps+  , strokePathOps+  , transformOp+  ) where++import Control.Monad (forM_, unless, when)+import Control.Monad.ST (ST, runST)+import Data.Fixed (mod')+import Data.List (minimumBy, sort, sortBy, sortOn, unsnoc)+import Data.List.NonEmpty qualified as NE+import Data.Ord (comparing)+import Data.Primitive.PrimArray+  ( PrimArray+  , emptyPrimArray+  , generatePrimArray+  , indexPrimArray+  , newPrimArray+  , primArrayFromList+  , primArrayFromListN+  , readPrimArray+  , runPrimArray+  , setPrimArray+  , shrinkMutablePrimArray+  , sizeofPrimArray+  , thawPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Primitive.SmallArray (indexSmallArray, newSmallArray, readSmallArray, runSmallArray, smallArrayFromListN, writeSmallArray)+import Data.Word (Word32)+import NanoUI.Internal.Draw.Types (DrawOp (..), LineCap (..), LineJoin (..), Shade (..), defaultTextFont, quadPolygon)+import NanoUI.Internal.Types (Color (..), Rect (..), V2 (..), bucketOffsets, colorA, colorB, colorG, colorR, finite, lerpColor, newZeroedPrimArray)++--------------------------------------------------------------------------------+-- Paths+--------------------------------------------------------------------------------++-- | A sequence of subpaths made of lines, curves and arcs, in the drawing's+-- coordinates. Paths concatenate with '<>'.+newtype Path = Path [Segment]+  deriving (Eq, Show)+  deriving newtype (Semigroup, Monoid)++-- | One step of a 'Path'. A line, curve or 'SegArcTo' with no open subpath+-- starts one at the current point (where the last subpath closed, or the+-- origin).+data Segment+  = SegMove {-# UNPACK #-} !Float {-# UNPACK #-} !Float+  -- ^ Start a subpath at a point.+  | SegLine {-# UNPACK #-} !Float {-# UNPACK #-} !Float+  -- ^ A straight line to a point.+  | SegQuad+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  -- ^ A quadratic Bezier: control point, end.+  | SegCubic+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  -- ^ A cubic Bezier: two control points, end.+  | SegArc+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  -- ^ An elliptical arc in centre form: centre, radii, rotation, start angle+  -- and sweep, in radians. With a subpath open, a line joins the arc's+  -- start; otherwise the arc starts a new subpath.+  | SegArcTo+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      !Bool+      !Bool+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  -- ^ An SVG arc to a point: radii, rotation in radians, large-arc and sweep+  -- flags, end.+  | SegClose+  -- ^ Close the subpath back to where it started.+  deriving (Eq, Show)++-- | Start a subpath at a point.+moveTo :: V2 -> Path+moveTo (V2 x y) = Path [SegMove x y]++-- | A straight line to a point.+lineTo :: V2 -> Path+lineTo (V2 x y) = Path [SegLine x y]++-- | A quadratic Bezier curve: control point, then end point.+quadTo :: V2 -> V2 -> Path+quadTo (V2 qx qy) (V2 x y) = Path [SegQuad qx qy x y]++-- | A cubic Bezier curve: two control points, then end point.+cubicTo :: V2 -> V2 -> V2 -> Path+cubicTo (V2 x1 y1) (V2 x2 y2) (V2 x y) = Path [SegCubic x1 y1 x2 y2 x y]++-- | A circular arc: centre, radius, start angle and sweep. With a subpath+-- open, a line joins the current point to the arc's start; otherwise the arc+-- starts a new subpath. A sweep of a full turn or more draws the whole+-- circle, and a negative sweep goes anticlockwise. A negative radius is+-- treated as its absolute value.+--+-- > P.moveTo c <> P.arc c r 0 (pi / 3) <> P.close  -- a pie slice+arc :: V2 -> Float -> Float -> Float -> Path+arc c r = ellipticalArc c (V2 r r) 0++-- | An elliptical arc: centre, x and y radii, the ellipse's rotation, start+-- angle and sweep. The angles are measured before the ellipse is stretched+-- and rotated. Joins the current subpath like 'arc'.+ellipticalArc :: V2 -> V2 -> Float -> Float -> Float -> Path+ellipticalArc (V2 cx cy) (V2 rx ry) rot start sweep = Path [SegArc cx cy rx ry rot start sweep]++-- | An arc to a point, like SVG's @A@ command: x and y radii, the ellipse's+-- rotation, whether to take the larger of the two possible arcs, whether to+-- go clockwise on screen, and the end point. Radii too small to reach the+-- end are scaled up; a zero radius draws a straight line. This is not HTML+-- canvas's @arcTo@, which rounds the corner between two lines; draw that+-- with 'arc' around the corner's centre.+arcTo :: V2 -> Float -> Bool -> Bool -> V2 -> Path+arcTo (V2 rx ry) rot large clockwise (V2 x y) = Path [SegArcTo rx ry rot large clockwise x y]++-- | Close the subpath with a line back to its start. A stroke joins a+-- closed subpath's ends instead of capping them.+close :: Path+close = Path [SegClose]++--------------------------------------------------------------------------------+-- Shapes+--------------------------------------------------------------------------------++-- | A rectangle's outline, clockwise on screen from its top left corner.+rect :: Rect -> Path+rect (Rect x y w h) =+  Path [SegMove x y, SegLine (x + w) y, SegLine (x + w) (y + h), SegLine x (y + h), SegClose]++-- | A rectangle with rounded corners, the radius clamped to half the shorter+-- side. Runs clockwise on screen from the end of the top left corner.+roundedRect :: Rect -> Float -> Path+roundedRect box radius = roundedRectCorners box radius radius radius radius++-- | A rectangle with a radius per corner, in CSS @border-radius@ order: top+-- left, top right, bottom right, bottom left. If two corners on a side would+-- overlap, all radii shrink by the same factor, as in CSS. A negative radius+-- gives a square corner. A rectangle with a negative width or height is+-- the one it spans, with the radii on its corners as seen on screen.+roundedRectCorners :: Rect -> Float -> Float -> Float -> Float -> Path+roundedRectCorners box@(Rect x0 y0 w h) tl0 tr0 br0 bl0+  | tl <= 0 && tr <= 0 && br <= 0 && bl <= 0 = rect box+  | otherwise =+      Path+        [ SegMove (x + tl) y+        , corner (x + aw - tr) (y + tr) tr (-pi / 2)+        , corner (x + aw - br) (y + ah - br) br 0+        , corner (x + bl) (y + ah - bl) bl (pi / 2)+        , corner (x + tl) (y + tl) tl pi+        , SegClose+        ]+  where+    -- Capped, so an infinite radius shrinks to fit like a huge one, not to NaN.+    positive r = if r > 0 then min r 1e30 else 0+    x = min x0 (x0 + w)+    y = min y0 (y0 + h)+    aw = abs w+    ah = abs h+    -- The factor that fits a side's two radii within its length.+    fitSide side a b = let both = positive a + positive b in if both > side then side / both else 1+    shrink = min (min (fitSide aw tl0 tr0) (fitSide ah tr0 br0)) (min (fitSide aw br0 bl0) (fitSide ah bl0 tl0))+    fit r = positive r * shrink+    tl = fit tl0+    tr = fit tr0+    br = fit br0+    bl = fit bl0+    -- A quarter arc about the corner's centre, or a line for a square corner.+    corner cx cy r a0+      | r > 0 = SegArc cx cy r r 0 a0 (pi / 2)+      | otherwise = SegLine cx cy++-- | A circle: its centre and radius.+circle :: V2 -> Float -> Path+circle c r = ellipse c (V2 r r)++-- | An axis-aligned ellipse: centre and x and y radii. For a rotated one use+-- 'ellipticalArc' or a transform.+ellipse :: V2 -> V2 -> Path+ellipse (V2 cx cy) (V2 rx ry) = Path [SegMove (cx + abs rx) cy, SegArc cx cy rx ry 0 0 (2 * pi), SegClose]++-- | A closed polygon through the points.+polygon :: [V2] -> Path+polygon pts = polyline pts <> if null pts then mempty else close++-- | An open line through the points.+polyline :: [V2] -> Path+polyline [] = mempty+polyline (V2 x y : rest) = Path (SegMove x y : [SegLine px py | V2 px py <- rest])++--------------------------------------------------------------------------------+-- Strokes, fills and paints+--------------------------------------------------------------------------------++-- | Stroke settings. Start from 'stroke' and change the rest with a record+-- update:+--+-- > (P.stroke 3) {P.strokeCap = P.RoundCap, P.strokeDash = [6, 4]}+data Stroke = StrokeStyle+  { strokeWidth :: !Float+  -- ^ Line width. A transform scales it along with the path.+  , strokeCap :: !LineCap+  -- ^ Cap for the ends of open subpaths and of every dash (default+  -- 'ButtCap'). A subpath of zero length, such as a move and a line to the+  -- same point, is a dot with 'RoundCap' or 'SquareCap'.+  , strokeJoin :: !LineJoin+  -- ^ Corner join (default 'MiterJoin').+  , strokeMiterLimit :: !Float+  -- ^ Longest allowed miter, as a multiple of the width; longer corners are+  -- beveled (default 4, like SVG's @stroke-miterlimit@).+  , strokeDash :: ![Float]+  -- ^ Alternating dash and gap lengths, repeated along each subpath. An odd+  -- count is repeated twice (default @[]@, solid). A zero-length dash with+  -- round or square caps draws a dot. Negative or all-zero lengths draw a+  -- solid line, as does a pattern that would cut a subpath into more than+  -- 4096 dashes. A transform scales the lengths along with the width.+  , strokeDashOffset :: !Float+  -- ^ Distance into the dash pattern at which each subpath starts+  -- (default 0).+  }+  deriving (Eq, Show)++-- | A solid stroke of the given width, with butt caps and miter joins.+stroke :: Float -> Stroke+stroke w = StrokeStyle w ButtCap MiterJoin 4 [] 0++-- | The miter at a corner between edges with unit normals @(ax, ay)@ and+-- @(bx, by)@: moving the corner by this offset moves both edges out by one.+-- Its length is the miter length relative to the line width. 'Nothing' past+-- @limit@, where the corner is beveled. Used by canvas strokes and the SVG+-- rasterizer.+{-# INLINE miterOffset #-}+miterOffset :: Float -> Float -> Float -> Float -> Float -> Maybe (Float, Float)+miterOffset limit ax ay bx by+  | not (d2 * limit * limit >= 1) = Nothing+  | otherwise = Just (mx / d2, my / d2)+  where+    mx = (ax + bx) / 2+    my = (ay + by) / 2+    d2 = mx * mx + my * my++-- | Which points a fill covers, based on the path's winding number around+-- them (+1 for each turn one way, -1 for the other).+data FillRule+  = NonZero+  -- ^ Points with a nonzero winding number. A subpath inside another is+  -- filled too, unless it runs the opposite way, which cuts it out.+  | EvenOdd+  -- ^ Points with an odd winding number. A subpath inside another is cut+  -- out, and one inside that is filled again.+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | Whether a point with winding number @w@ is inside the fill. Used by+-- canvas fills and the SVG rasterizer.+{-# INLINE fillsWinding #-}+fillsWinding :: FillRule -> Int -> Bool+fillsWinding NonZero w = w /= 0+fillsWinding EvenOdd w = odd w++-- | The paint for a fill or stroke.+data Paint+  = Solid !Color+  -- ^ One colour.+  | Linear !V2 !V2 ![(Float, Color)]+  -- ^ A linear gradient from its first point (offset 0) to its second+  -- (offset 1), with colour stops at offsets. Beyond the first and last+  -- stops it keeps their colours. Offsets are clamped to 0..1, and an+  -- offset below the previous one is raised to it, so two stops at the same+  -- offset give a hard edge. The gradient is in drawing coordinates, so+  -- transforms rotate and scale it. A stroke uses the colour at its centre+  -- line across its whole width.+  deriving (Eq, Show)++--------------------------------------------------------------------------------+-- Transforms+--------------------------------------------------------------------------------++-- | An affine transform, laid out like SVG's @matrix(a b c d e f)@: @(x, y)@+-- maps to @(a x + c y + e, b x + d y + f)@. @s <> t@ applies @t@ first, like+-- function composition; 'mempty' is the identity.+data Transform+  = Transform+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+      {-# UNPACK #-} !Float+  deriving (Eq, Show)++instance Semigroup Transform where+  Transform a b c d e f <> Transform a' b' c' d' e' f' =+    Transform+      (a * a' + c * b')+      (b * a' + d * b')+      (a * c' + c * d')+      (b * c' + d * d')+      (a * e' + c * f' + e)+      (b * e' + d * f' + f)++instance Monoid Transform where+  mempty = Transform 1 0 0 1 0 0++-- | Map a point through a transform.+{-# INLINE applyTransform #-}+applyTransform :: Transform -> Float -> Float -> (Float, Float)+applyTransform (Transform a b c d e f) x y = (a * x + c * y + e, b * x + d * y + f)++-- | Move by an offset.+translate :: Float -> Float -> Transform+translate dx dy = Transform 1 0 0 1 dx dy++-- | Rotate about the origin. A positive angle turns clockwise on screen.+rotate :: Float -> Transform+rotate a =+  let s = sin a+      c = cos a+   in Transform c s (negate s) c 0 0++-- | Rotate about a point.+rotateAround :: V2 -> Float -> Transform+rotateAround (V2 x y) a = translate x y <> rotate a <> translate (negate x) (negate y)++-- | Scale about the origin by separate x and y factors. A negative factor+-- flips that axis.+scale :: Float -> Float -> Transform+scale sx sy = Transform sx 0 0 sy 0 0++-- | A transform from its matrix entries, in SVG @matrix(a b c d e f)@+-- order: @(x, y)@ maps to @(a x + c y + e, b x + d y + f)@.+affine :: Float -> Float -> Float -> Float -> Float -> Float -> Transform+affine = Transform++-- | Apply a transform to a point.+transformPoint :: Transform -> V2 -> V2+transformPoint t (V2 x y) = let (x', y') = applyTransform t x y in V2 x' y'++-- | The inverse transform, e.g. to map a pointer position back into a+-- drawing's coordinates. 'Nothing' if the transform collapses the plane to+-- a line or point, or has a NaN or infinite entry.+invert :: Transform -> Maybe Transform+invert (Transform a b c d e f)+  | det == 0 || not (transformFinite inv) = Nothing+  | otherwise = Just inv+  where+    det = a * d - b * c+    inv = Transform (d / det) (negate b / det) (negate c / det) (a / det) ((c * f - d * e) / det) ((b * e - a * f) / det)++-- | No entry is NaN or infinite.+transformFinite :: Transform -> Bool+transformFinite (Transform a b c d e f) = all finite [a, b, c, d, e, f]++-- | The most the transform lengthens any vector: the larger singular value+-- of its linear part.+maxStretch :: Transform -> Float+maxStretch (Transform a b c d _ _) =+  let s = a * a + b * b + c * c + d * d+      det = a * d - b * c+   in sqrt ((s + sqrt (max 0 (s * s - 4 * det * det))) / 2)++-- | The square root of the transform's area scale. For a uniform scale this+-- is the scale factor; in general, the geometric mean of the singular values.+averageStretch :: Transform -> Float+averageStretch (Transform a b c d _ _) = sqrt (abs (a * d - b * c))++--------------------------------------------------------------------------------+-- Rings+--------------------------------------------------------------------------------++-- | Rings of points in flat arrays: interleaved x/y coordinates, start+-- offsets (ring @i@ is points @starts[i]@ up to @starts[i + 1]@), and one+-- builder-assigned tag per ring.+data Rings = Rings !(PrimArray Float) !(PrimArray Int) !(PrimArray Int)++-- | The number of rings.+ringCount :: Rings -> Int+ringCount (Rings _ starts _) = sizeofPrimArray starts - 1++-- | Build 'Rings' from a walk that calls @point x y@ per point and @end tag@+-- after each ring. The walk runs twice (once to size the arrays, once to+-- fill them), so both runs must emit the same points.+{-# INLINE buildRings #-}+buildRings :: (forall s. (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()) -> Rings+buildRings walk = runST $ do+  counts <- newZeroedPrimArray 2+  let bump k = readPrimArray counts k >>= writePrimArray counts k . (+ 1)+  walk (\_ _ -> bump 0) (\_ -> bump 1)+  nPoints <- readPrimArray counts 0+  nRings <- readPrimArray counts 1+  points <- newPrimArray (2 * nPoints)+  starts <- newPrimArray (nRings + 1)+  tags <- newPrimArray nRings+  writePrimArray starts 0 0+  setPrimArray counts 0 2 0+  walk+    ( \x y -> do+        k <- readPrimArray counts 0+        writePrimArray points (2 * k) x+        writePrimArray points (2 * k + 1) y+        writePrimArray counts 0 (k + 1)+    )+    ( \tag -> do+        r <- readPrimArray counts 1+        readPrimArray counts 0 >>= writePrimArray starts (r + 1)+        writePrimArray tags r tag+        writePrimArray counts 1 (r + 1)+    )+  Rings <$> unsafeFreezePrimArray points <*> unsafeFreezePrimArray starts <*> unsafeFreezePrimArray tags++--------------------------------------------------------------------------------+-- Flattening+--------------------------------------------------------------------------------++-- | Flattening tolerance in logical pixels for a display with @s@ device+-- pixels per logical pixel: a quarter of a device pixel.+curveTolerance :: Float -> Float+curveTolerance s+  | s > 0 && s < 1 / 0 = 0.25 / s+  | otherwise = 0.25++-- | Flatten a path through a transform into rings, tagging a ring 1 if+-- 'SegClose' ended it. Curves are subdivided until they are within @tol@ of+-- their chords after transforming, so scaled-up curves get more points. An+-- arc gets @steps r sweep@ chords, where @r@ is its larger transformed+-- radius (the canvas passes a count that keeps chords within @tol@ of the+-- arc). Segments with a NaN or infinite+-- coordinate are skipped; a transform with one yields no rings.+flattenPath :: Float -> (Float -> Float -> Int) -> Transform -> Path -> Rings+flattenPath tol steps t (Path segs)+  | transformFinite t = buildRings (pathWalk tol steps t segs)+  | otherwise = buildRings (\_ _ -> pure ())++{-# INLINE pathWalk #-}+pathWalk :: Float -> (Float -> Float -> Int) -> Transform -> [Segment] -> (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()+pathWalk tol steps t segs0 point end = go segs0 False 0 0 0 0+  where+    emit x y = let (x', y') = applyTransform t x y in point x' y'+    finish open closed = when open (end (if closed then 1 else 0))+    -- A drawing segment with no subpath open starts one at the current point.+    begin open cx cy = unless open (emit cx cy)+    stretch = maxStretch t+    -- An elliptical arc's points after its start. The last is exactly+    -- @(x1, y1)@, so a full turn closes on its start.+    arcPoints ax ay rx ry rot a0 sweep x1 y1 = do+      let n = steps (stretch * max (abs rx) (abs ry)) sweep+      forM_ [1 .. n - 1] $ \i ->+        uncurry emit (ellipsePoint ax ay rx ry rot (a0 + sweep * fromIntegral i / fromIntegral n))+      emit x1 y1+    cubic x0 y0 x1 y1 x2 y2 x3 y3 = do+      let (tx0, ty0) = applyTransform t x0 y0+          (tx1, ty1) = applyTransform t x1 y1+          (tx2, ty2) = applyTransform t x2 y2+          (tx3, ty3) = applyTransform t x3 y3+      cubicPoints tol point tx0 ty0 tx1 ty1 tx2 ty2 tx3 ty3+    go [] open _ _ _ _ = finish open False+    go (seg : rest) open cx cy sx sy+      | not (segmentFinite seg) = go rest open cx cy sx sy+      | otherwise = case seg of+          SegMove x y -> finish open False >> emit x y >> go rest True x y x y+          SegLine x y -> begin open cx cy >> emit x y >> go rest True x y sx sy+          SegQuad qx qy x y -> do+            begin open cx cy+            -- The quadratic as a cubic: each control point is two thirds of+            -- the way from an end to the quadratic's control point.+            cubic cx cy (cx + 2 / 3 * (qx - cx)) (cy + 2 / 3 * (qy - cy)) (x + 2 / 3 * (qx - x)) (y + 2 / 3 * (qy - y)) x y+            go rest True x y sx sy+          SegCubic x1 y1 x2 y2 x y -> do+            begin open cx cy+            cubic cx cy x1 y1 x2 y2 x y+            go rest True x y sx sy+          SegArc ax ay rx ry rot a0 sweep0 -> do+            -- A sweep past a whole turn draws the whole ellipse once.+            let sweep = max (-2 * pi) (min (2 * pi) sweep0)+                (x0, y0) = ellipsePoint ax ay rx ry rot a0+                (x1, y1)+                  | abs sweep >= 2 * pi = (x0, y0)+                  | otherwise = ellipsePoint ax ay rx ry rot (a0 + sweep)+            -- A line to the arc's start, or the first point of a new subpath.+            emit x0 y0+            arcPoints ax ay rx ry rot a0 sweep x1 y1+            if open then go rest True x1 y1 sx sy else go rest True x1 y1 x0 y0+          SegArcTo rx ry rot large sweepFlag x y -> do+            begin open cx cy+            case arcCentre cx cy rx ry rot large sweepFlag x y of+              Nothing -> emit x y+              Just (ax, ay, arx, ary, a0, sweep) -> arcPoints ax ay arx ary rot a0 sweep x y+            go rest True x y sx sy+          SegClose -> finish open True >> go rest False sx sy sx sy++-- | No coordinate of the segment is NaN or infinite.+segmentFinite :: Segment -> Bool+segmentFinite seg = case seg of+  SegMove x y -> finite x && finite y+  SegLine x y -> finite x && finite y+  SegQuad a b x y -> all finite [a, b, x, y]+  SegCubic a b c d x y -> all finite [a, b, c, d, x, y]+  SegArc a b c d e f g -> all finite [a, b, c, d, e, f, g]+  SegArcTo a b c _ _ x y -> all finite [a, b, c, x, y]+  SegClose -> True++-- | The point at angle @a@ on an ellipse with the given centre, radii+-- (negative ones taken as absolute) and rotation.+{-# INLINE ellipsePoint #-}+ellipsePoint :: Float -> Float -> Float -> Float -> Float -> Float -> (Float, Float)+ellipsePoint cx cy rx ry rot a =+  let ex = abs rx * cos a+      ey = abs ry * sin a+      cr = cos rot+      sr = sin rot+   in (cx + cr * ex - sr * ey, cy + sr * ex + cr * ey)++-- | The number of chords for @sweep@ radians of an ellipse with larger+-- transformed radius @r@, so each chord stays within @tol@ of the curve. At+-- least one per quarter turn, at most 'maxArcSteps'.+arcSteps :: Float -> Float -> Float -> Int+arcSteps tol r sweep+  | not (abs sweep <= 4 * pi) = maxArcSteps+  | r > tol && ideal < fromIntegral maxArcSteps = max quarters (ceiling ideal)+  | r > tol = maxArcSteps+  | otherwise = quarters+  where+    quarters = max 1 (ceiling (abs sweep / (pi / 2)))+    ideal = idealArcSteps tol r sweep++-- | The unrounded number of equal chords that keep @sweep@ radians of a+-- circle of radius @r@ within @tol@ of it, for @r > tol@. Grows without+-- bound as @tol / r@ shrinks, so bound it before rounding to an 'Int'.+--+-- A chord of angle @da@ strays @r (1 - cos (da / 2)) = 2 r sin (da / 4) ^ 2@+-- from the circle. Solved in the sine form because @1 - tol / r@ rounds to 1+-- for huge radii, which would give a nearly straight arc as many chords as+-- the caller allows.+{-# INLINE idealArcSteps #-}+idealArcSteps :: Float -> Float -> Float -> Float+idealArcSteps tol r sweep = abs sweep / (4 * asin (sqrt (tol / (2 * r))))++-- | The most chords one arc is split into.+maxArcSteps :: Int+maxArcSteps = 1024++-- | Emit the points after the start of a cubic Bezier from @(x0, y0)@ via+-- @(x1, y1)@ and @(x2, y2)@ to @(x3, y3)@. Splits in halves until each+-- piece's control points keep it within @tol@ of its chord, at most ten+-- levels deep.+{-# INLINE cubicPoints #-}+cubicPoints :: Monad m => Float -> (Float -> Float -> m ()) -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> m ()+cubicPoints tol point = go (0 :: Int)+  where+    go depth x0 y0 x1 y1 x2 y2 x3 y3+      | depth >= 10 || flat = point x3 y3+      | otherwise = do+          let mx01 = (x0 + x1) / 2+              my01 = (y0 + y1) / 2+              mx12 = (x1 + x2) / 2+              my12 = (y1 + y2) / 2+              mx23 = (x2 + x3) / 2+              my23 = (y2 + y3) / 2+              mx012 = (mx01 + mx12) / 2+              my012 = (my01 + my12) / 2+              mx123 = (mx12 + mx23) / 2+              my123 = (my12 + my23) / 2+              mx = (mx012 + mx123) / 2+              my = (my012 + my123) / 2+          go (depth + 1) x0 y0 mx01 my01 mx012 my012 mx my+          go (depth + 1) mx my mx123 my123 mx23 my23 x3 y3+      where+        ux = 3 * x1 - 2 * x0 - x3+        uy = 3 * y1 - 2 * y0 - y3+        vx = 3 * x2 - 2 * x3 - x0+        vy = 3 * y2 - 2 * y3 - y0+        flat = max (ux * ux) (vx * vx) + max (uy * uy) (vy * vy) <= 16 * tol * tol++-- | Convert an SVG arc from @(x1, y1)@ to @(x2, y2)@ (radii @rx0@ and @ry0@,+-- rotation @phi@) to centre form, per the SVG specification: centre, radii+-- (scaled up if too small to reach), start angle and sweep. 'Nothing' when a+-- radius is zero or the ends coincide (SVG draws a line or nothing), or when+-- extreme radii make the centre NaN or infinite. Callers draw 'Nothing' as a+-- straight line, which a huge-radius arc nearly is.+arcCentre :: Float -> Float -> Float -> Float -> Float -> Bool -> Bool -> Float -> Float -> Maybe (Float, Float, Float, Float, Float, Float)+arcCentre x1 y1 rx0 ry0 phi large sweep x2 y2+  | rx0 == 0 || ry0 == 0 || (x1 == x2 && y1 == y2) = Nothing+  | not (all finite [cx, cy, rx, ry, theta1, dtheta]) = Nothing+  | otherwise = Just (cx, cy, rx, ry, theta1, dtheta)+  where+    cosP = cos phi+    sinP = sin phi+    dx = (x1 - x2) / 2+    dy = (y1 - y2) / 2+    x1' = cosP * dx + sinP * dy+    y1' = negate sinP * dx + cosP * dy+    lambda = (x1' * x1') / (rx0 * rx0) + (y1' * y1') / (ry0 * ry0)+    grow = if lambda > 1 then sqrt lambda else 1+    rx = abs rx0 * grow+    ry = abs ry0 * grow+    -- The specification's (rx² ry² - rx² y1'² - ry² x1'²) / (rx² y1'² ++    -- ry² x1'²), divided through by rx² ry² so large radii don't overflow.+    reach = (x1' / rx) * (x1' / rx) + (y1' / ry) * (y1' / ry)+    coef = (if large == sweep then -1 else 1) * sqrt (max 0 (1 / reach - 1))+    cx' = coef * rx * y1' / ry+    cy' = coef * negate (ry * x1' / rx)+    cx = cosP * cx' - sinP * cy' + (x1 + x2) / 2+    cy = sinP * cx' + cosP * cy' + (y1 + y2) / 2+    angle ux uy vx vy = atan2 (ux * vy - uy * vx) (ux * vx + uy * vy)+    theta1 = angle 1 0 ((x1' - cx') / rx) ((y1' - cy') / ry)+    dtheta0 = angle ((x1' - cx') / rx) ((y1' - cy') / ry) ((negate x1' - cx') / rx) ((negate y1' - cy') / ry)+    dtheta+      | not sweep && dtheta0 > 0 = dtheta0 - 2 * pi+      | sweep && dtheta0 < 0 = dtheta0 + 2 * pi+      | otherwise = dtheta0++--------------------------------------------------------------------------------+-- Triangulation+--------------------------------------------------------------------------------++-- | Triangle index triples covering a simple polygon given as x/y pairs+-- (either winding, first point not repeated). Convex polygons are fanned+-- from the first point; others are ear clipped. Fewer than three points give+-- no triangles. Holes and self-intersections are unsupported and may leave+-- gaps.+triangulate :: PrimArray Float -> PrimArray Int+triangulate vs+  | n < 3 = emptyPrimArray+  | convexRing vs = generatePrimArray (3 * (n - 2)) fan+  | otherwise = earClip vs (generatePrimArray n id)+  where+    n = sizeofPrimArray vs `div` 2+    fan k = case k `mod` 3 of+      0 -> 0+      1 -> k `div` 3 + 1+      _ -> k `div` 3 + 2++-- | Triangle index triples covering a polygon with holes. @vs@ holds every+-- ring's points back to back; @rings@ holds each ring's start plus the end+-- of the last. The first ring is the outline; the rest are holes inside it+-- that touch neither it nor each other. A lone outline may wind either way.+-- With holes, the outline must have a positive 'ringArea' and the holes a+-- negative one, as 'fillPathOps' produces. Each hole is bridged to a visible+-- outline point (as in Eberly's \"Triangulation by Ear Clipping\" and+-- mapbox's earcut), and the merged ring is ear clipped.+triangulateRings :: PrimArray Float -> PrimArray Int -> PrimArray Int+triangulateRings vs rings+  | sizeofPrimArray rings <= 2 = triangulate vs+  | otherwise = earClip vs (primArrayFromList (bridgeHoles vs (ringAt 0) (map ringAt [1 .. sizeofPrimArray rings - 2])))+  where+    ringAt r = [indexPrimArray rings r .. indexPrimArray rings (r + 1) - 1]++-- | The outline's point indices with each hole spliced in, leftmost hole+-- first. A splice runs from the outline point bridged to the hole's leftmost+-- point, around the hole, and back along the bridge. A hole with no visible+-- outline point is dropped.+bridgeHoles :: PrimArray Float -> [Int] -> [[Int]] -> [Int]+bridgeHoles vs outline holes = foldl' join outline (map snd (sortOn fst (map leftmostFirst (filter (not . null) holes))))+  where+    at = pointAt vs+    -- The hole rotated to start at its leftmost point, keyed by that point.+    leftmostFirst h =+      let (p, m) = minimum [(at i, k) | (k, i) <- zip [0 :: Int ..] h]+       in (p, drop m h ++ take m h)+    join ring h@(hi : _) = case bridgeFrom ring (at hi) of+      Nothing -> ring+      Just k ->+        let (before, after) = splitAt (k + 1) ring+         in before ++ h ++ [hi, ring !! k] ++ after+    join ring [] = ring+    -- The ring position to bridge @(hx, hy)@ to. A ray cast left hits the+    -- nearest edge, and the bridge goes to that edge's left end, unless+    -- ring points inside the triangle it forms with the ray block the view;+    -- then it goes to the one at the smallest angle to the ray.+    bridgeFrom ring (hx, hy) =+      let n = length ring+          ix = primArrayFromListN n ring+          node k = indexPrimArray ix (k `mod` n)+          pt k = at (node k)+          hits =+            [ (x, k')+            | k <- [0 .. n - 1]+            , let (ax, ay) = pt k+                  (bx, by) = pt (k + 1)+            , hy <= ay && hy >= by && by /= ay+            , let x = ax + (hy - ay) * (bx - ax) / (by - ay)+            , x <= hx+            , let k' = if ax < bx then k else (k + 1) `mod` n+            ]+       in case hits of+            [] -> Nothing+            _ ->+              let (qx, m) = maximum hits+                  (mx, my) = pt m+                  -- The bridge from the hole point to ring point @k@ enters+                  -- the ring's interior at that corner.+                  locallyInside k =+                    let a = pt k+                        prev = pt (k - 1)+                        next = pt (k + 1)+                        h = (hx, hy)+                     in if turn prev a next < 0+                          then turn a h next >= 0 && turn a prev h >= 0+                          else turn a h prev < 0 || turn a next h < 0+                  better (tanBest, kBest) k =+                    let (px, py) = pt k+                        t = abs (hy - py) / (hx - px)+                     in if hx >= px && px >= mx && hx /= px && pointInTri (px, py) (hx, hy) (qx, hy) (mx, my) && locallyInside k+                          && (t < tanBest || (t == tanBest && px > fst (pt kBest)))+                          then (t, k)+                          else (tanBest, kBest)+               in if qx == hx then Just m else Just (snd (foldl' better (1 / 0, m) [0 .. n - 1]))++-- | Twice a triangle's signed area, with earcut's sign: negative at a convex+-- corner of a ring with positive 'signedArea'. The negated 'cross' of its+-- edges, which 'isConvex' tests.+turn :: (Float, Float) -> (Float, Float) -> (Float, Float) -> Float+turn p q r = negate (cross (diff p q) (diff q r))++-- | Whether the ring is convex: every corner turns the same way (straight+-- ones aside) and it winds once. Winding once is checked by the x and y+-- directions each reversing at most twice, which a doubly wound star fails.+convexRing :: PrimArray Float -> Bool+convexRing vs = go 0 0 0 0 0 0+  where+    n = sizeofPrimArray vs `div` 2+    go :: Int -> Int -> Int -> Int -> Int -> Int -> Bool+    go !i !turn' !xs !ys !lastX !lastY+      | i >= n = True+      | otherwise =+          -- Strict coordinates: lazily bound point tuples cost a thunk and+          -- boxes per point. 'triangulate' calls this with n >= 3, so one+          -- subtraction wraps an index.+          let !i1 = if i + 1 >= n then i + 1 - n else i + 1+              !i2 = if i1 + 1 >= n then i1 + 1 - n else i1 + 1+              !x0 = indexPrimArray vs (2 * i)+              !y0 = indexPrimArray vs (2 * i + 1)+              !x1 = indexPrimArray vs (2 * i1)+              !y1 = indexPrimArray vs (2 * i1 + 1)+              !x2 = indexPrimArray vs (2 * i2)+              !y2 = indexPrimArray vs (2 * i2 + 1)+              !c = (x1 - x0) * (y2 - y1) - (x2 - x1) * (y1 - y0)+              !turn'' = if c > 0 then 1 else if c < 0 then -1 else turn'+              !sx = signum' (x1 - x0)+              !sy = signum' (y1 - y0)+              !xs' = if sx /= 0 && lastX /= 0 && sx /= lastX then xs + 1 else xs+              !ys' = if sy /= 0 && lastY /= 0 && sy /= lastY then ys + 1 else ys+           in if turn' /= 0 && turn'' /= turn' || xs' > 2 || ys' > 2+                then False+                else go (i + 1) turn'' xs' ys' (if sx /= 0 then sx else lastX) (if sy /= 0 then sy else lastY)+    signum' v = if v > 0 then 1 else if v < 0 then -1 else 0 :: Int++{-# INLINE pointAt #-}+pointAt :: PrimArray Float -> Int -> (Float, Float)+pointAt vs i =+  let !x = indexPrimArray vs (2 * i)+      !y = indexPrimArray vs (2 * i + 1)+   in (x, y)++-- | The shoelace area of the points of @vs@ listed by @ix@, in order.+-- Positive for a ring clockwise on screen.+signedArea :: PrimArray Float -> PrimArray Int -> Float+signedArea vs ix = shoelace (sizeofPrimArray ix) (pointAt vs . indexPrimArray ix)++-- | 'signedArea' of a ring's points in their own order.+ringArea :: PrimArray Float -> Float+ringArea vs = shoelace (sizeofPrimArray vs `div` 2) (pointAt vs)++-- | The shoelace area of @n@ points, point @k@ being @at k@. Positive for a+-- ring clockwise on screen; the polygon emitter uses the sign for winding.+{-# INLINE shoelace #-}+shoelace :: Int -> (Int -> (Float, Float)) -> Float+shoelace n at = go 0 0+  where+    go !k !acc+      | k >= n = acc / 2+      | otherwise = go (k + 1) (acc + cross (at k) (at (if k + 1 >= n then 0 else k + 1)))++cross :: (Float, Float) -> (Float, Float) -> Float+cross (x0, y0) (x1, y1) = x0 * y1 - x1 * y0++diff :: (Float, Float) -> (Float, Float) -> (Float, Float)+diff (x0, y0) (x1, y1) = (x1 - x0, y1 - y0)++isConvex :: Bool -> (Float, Float) -> (Float, Float) -> (Float, Float) -> Bool+isConvex ccw a b c =+  let ab = diff a b+      bc = diff b c+   in if ccw then cross ab bc >= 0 else cross ab bc <= 0++pointInTri :: (Float, Float) -> (Float, Float) -> (Float, Float) -> (Float, Float) -> Bool+pointInTri p a b c =+  let sign (p1, p2, p3) = cross (diff p1 p3) (diff p2 p3)+      d1 = sign (p, a, b)+      d2 = sign (p, b, c)+      d3 = sign (p, c, a)+   in not ((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0))++-- | Triangle index triples into @vs@ covering the ring listed by @ix@. A+-- hole bridge lists its end points twice, so a point on an ear's corner does+-- not block the ear.+--+-- After an ear is cut the scan goes on from its next corner, and the points+-- that could block an ear are looked up in a grid of the remaining points,+-- so a typical ring costs about linear time rather than a full pass of+-- every point per ear.+earClip :: PrimArray Float -> PrimArray Int -> PrimArray Int+earClip vs ix = runPrimArray $ do+  let !ccw = signedArea vs ix >= 0+  -- Remove an ear by relinking its neighbours instead of copying the+  -- remaining points at every step.+  prevs <- newPrimArray n+  nexts <- newPrimArray n+  forM_ [0 .. n - 1] $ \i -> do+    writePrimArray prevs i (if i == 0 then n - 1 else i - 1)+    writePrimArray nexts i (if i + 1 == n then 0 else i + 1)+  -- The remaining points by cell: cell @c@ holds the first @lens c@ entries+  -- of its span of @members@, and @slots@ says where each point is.+  members <- thawPrimArray (gridItems grid) 0 n+  lens <- newPrimArray cellCount+  forM_ [0 .. cellCount - 1] $ \c -> writePrimArray lens c (start (c + 1) - start c)+  slots <- newPrimArray n+  forM_ [0 .. n - 1] $ \k -> readPrimArray members k >>= \i -> writePrimArray slots i k+  out <- newPrimArray (3 * max 0 (n - 2))+  let remove i = do+        let !c = cellOf (at i)+        len <- readPrimArray lens c+        slot <- readPrimArray slots i+        moved <- readPrimArray members (start c + len - 1)+        writePrimArray members slot moved+        writePrimArray slots moved slot+        writePrimArray lens c (len - 1)+      -- Whether a remaining point lies in the ear @p i q@. One on a corner+      -- (the other end of a hole bridge) does not block it. The loops only+      -- tail call each other, so they compile to jumps, not closures.+      blocked p i q a@(ax, ay) b@(bx, by) c@(cx, cy) = cell r0 c0+        where+          !c0 = gridCol grid (min ax (min bx cx))+          !c1 = gridCol grid (max ax (max bx cx))+          !r0 = gridRow grid (min ay (min by cy))+          !r1 = gridRow grid (max ay (max by cy))+          cell !r !col+            | r > r1 = pure False+            | col > c1 = cell (r + 1) c0+            | otherwise = do+                let !k = r * gridCols grid + col+                len <- readPrimArray lens k+                scan r col (start k) (start k + len)+          scan !r !col !k !end+            | k >= end = cell r (col + 1)+            | otherwise = do+                j <- readPrimArray members k+                let !pj = at j+                if j /= p && j /= i && j /= q && pointInTri pj a b c && pj /= a && pj /= b && pj /= c+                  then pure True+                  else scan r col (k + 1) end+      emit !m p i q = do+        writePrimArray out m (indexPrimArray ix p)+        writePrimArray out (m + 1) (indexPrimArray ix i)+        writePrimArray out (m + 2) (indexPrimArray ix q)+        pure (m + 3)+      convex !_ 0 = pure True+      convex !i !left = do+        p <- readPrimArray prevs i+        q <- readPrimArray nexts i+        if isConvex ccw (at p) (at i) (at q) then convex q (left - 1) else pure False+      fan !m !origin !i !left+        | left <= 0 = pure m+        | otherwise = do+            q <- readPrimArray nexts i+            m' <- emit m origin i q+            fan m' origin q (left - 1)+      go !m !count !i !tries+        | count < 3 = pure m+        | count == 3 = do+            p <- readPrimArray prevs i+            q <- readPrimArray nexts i+            emit m p i q+        | tries >= count = do+            -- A whole pass found no ear: fan a convex remainder, else stop.+            isConvexRing <- convex i count+            if isConvexRing then readPrimArray nexts i >>= \q -> fan m i q (count - 2) else pure m+        | otherwise = do+            p <- readPrimArray prevs i+            q <- readPrimArray nexts i+            let !a = at p+                !b = at i+                !c = at q+            ear <- if isConvex ccw a b c then not <$> blocked p i q a b c else pure False+            if ear+              then do+                writePrimArray nexts p q+                writePrimArray prevs q p+                remove i+                m' <- emit m p i q+                go m' (count - 1) q 0+              else go m count q (tries + 1)+  m <- go 0 n 0 0+  shrinkMutablePrimArray out m+  pure out+  where+    n = sizeofPrimArray ix+    at k = pointAt vs (indexPrimArray ix k)+    -- About four points per cell. A point that is not finite could block+    -- any ear, so then every point shares one cell.+    (x0, y0, x1, y1) = ringBox vs+    cells = if all (finite . indexPrimArray vs) [0 .. sizeofPrimArray vs - 1] then n `div` 4 else 1+    grid = gridOf cells x0 y0 x1 y1 n (\k -> let (x, y) = at k in (x, y, x, y))+    cellCount = gridCols grid * gridRows grid+    start = indexPrimArray (gridStarts grid)+    cellOf (x, y) = gridRow grid y * gridCols grid + gridCol grid x++--------------------------------------------------------------------------------+-- Grids+--------------------------------------------------------------------------------++-- | Items bucketed by a uniform grid of about square cells over a box. Cell+-- @c@, counted along rows, lists the items whose boxes overlap it, in item+-- order: 'gridItems' from @'gridStarts' c@ up to @'gridStarts' (c + 1)@.+data Grid = Grid+  { gridCols :: !Int+  , gridRows :: !Int+  , gridX :: !Float+  , gridY :: !Float+  , gridScaleX :: !Float+  -- ^ Columns per unit of x (0 with one column).+  , gridScaleY :: !Float+  , gridStarts :: !(PrimArray Int)+  , gridItems :: !(PrimArray Int)+  }++-- | The column of the cells holding an x coordinate, clamped to the grid.+{-# INLINE gridCol #-}+gridCol :: Grid -> Float -> Int+gridCol g = cellAlong (gridCols g) (gridX g) (gridScaleX g)++-- | The row of the cells holding a y coordinate, clamped to the grid.+{-# INLINE gridRow #-}+gridRow :: Grid -> Float -> Int+gridRow g = cellAlong (gridRows g) (gridY g) (gridScaleY g)++-- | The cell along one axis holding a coordinate, clamped to @0 .. cells - 1@.+-- Monotonic, so the cells a box's corners fall in bound the cells of every+-- point in the box.+{-# INLINE cellAlong #-}+cellAlong :: Int -> Float -> Float -> Float -> Int+cellAlong cells origin perUnit v = max 0 (min (cells - 1) (truncate ((v - origin) * perUnit)))++-- | A grid of about @cells@ cells over the box from @(x0, y0)@ to @(x1, y1)@,+-- holding items @0 .. count - 1@; item @k@ covers @boxOf k@. A box that is+-- not finite gets one cell, and a side under 1e-20 a single row or column.+{-# INLINE gridOf #-}+gridOf :: Int -> Float -> Float -> Float -> Float -> Int -> (Int -> (Float, Float, Float, Float)) -> Grid+gridOf cells x0 y0 x1 y1 count boxOf = runST $ do+  -- Explicit loops: list ranges here are shared across iterations rather+  -- than fused, and cost a cell per step.+  let forCells f = item 0+        where+          item !k+            | k >= count = pure ()+            | otherwise = do+                let (bx0, by0, bx1, by1) = boxOf k+                    !c0 = cellAlong cols x0 sx bx0+                    !c1 = cellAlong cols x0 sx bx1+                    !r1 = cellAlong rows y0 sy by1+                    cell !r !c+                      | r > r1 = item (k + 1)+                      | c > c1 = cell (r + 1) c0+                      | otherwise = f k (r * cols + c) >> cell r (c + 1)+                cell (cellAlong rows y0 sy by0) c0+  (starts, fill) <- bucketOffsets total (\emit -> forCells (\_ c -> emit c))+  size <- readPrimArray starts total+  items <- newPrimArray size+  forCells $ \k c -> do+    slot <- readPrimArray fill c+    writePrimArray items slot k+    writePrimArray fill c (slot + 1)+  Grid cols rows x0 y0 sx sy <$> unsafeFreezePrimArray starts <*> unsafeFreezePrimArray items+  where+    w = x1 - x0+    h = y1 - y0+    target = max 1 cells+    usable s = s > 1e-20 && finite s+    (cols, rows)+      | not (finite w && finite h) = (1, 1)+      | usable w && usable h =+          let side = sqrt w * sqrt h / sqrt (fromIntegral target)+           in (fit (w / side), fit (h / side))+      | otherwise = (if usable w then target else 1, if usable h then target else 1)+    fit v = max 1 (ceiling (min (fromIntegral target) v))+    total = cols * rows+    sx = if cols > 1 then fromIntegral cols / w else 0+    sy = if rows > 1 then fromIntegral rows / h else 0++-- | A ring's bounding box: its least and greatest x and y.+ringBox :: PrimArray Float -> (Float, Float, Float, Float)+ringBox r = go 0 (1 / 0) (1 / 0) (-1 / 0) (-1 / 0)+  where+    go !k !x0 !y0 !x1 !y1+      | k + 1 >= sizeofPrimArray r = (x0, y0, x1, y1)+      | otherwise =+          let !x = indexPrimArray r k+              !y = indexPrimArray r (k + 1)+           in go (k + 2) (min x0 x) (min y0 y) (max x1 x) (max y1 y)++--------------------------------------------------------------------------------+-- Draw ops+--------------------------------------------------------------------------------++-- | Each ring's points with near-duplicates dropped, and whether it was+-- closed. Rings with a NaN or infinite coordinate are skipped. A point+-- within 1e-4 px of the previous one is a duplicate; with @closing@, or for+-- a closed ring, so is a last point on the first. A lone move, one point+-- that is not closed, is left out: it draws nothing, even with caps.+cleanRings :: Bool -> Rings -> [(PrimArray Float, Bool)]+cleanRings closing rings@(Rings pts starts tags) =+  [ (kept, closed)+  | r <- [0 .. ringCount rings - 1]+  , let from = indexPrimArray starts r+        to = indexPrimArray starts (r + 1)+        closed = indexPrimArray tags r /= 0+  , closed || to - from > 1+  , all (\k -> finite (indexPrimArray pts k)) [2 * from .. 2 * to - 1]+  , let kept = dedupe (closing || closed) from to+  ]+  where+    near ax ay bx by = let dx = ax - bx; dy = ay - by in dx * dx + dy * dy < 1e-8+    dedupe wrap from to = runPrimArray $ do+      out <- newPrimArray (2 * (to - from))+      let copy !k !m+            | k >= to = pure m+            | otherwise = do+                let x = indexPrimArray pts (2 * k)+                    y = indexPrimArray pts (2 * k + 1)+                repeated <-+                  if m == 0+                    then pure False+                    else near x y <$> readPrimArray out (2 * m - 2) <*> readPrimArray out (2 * m - 1)+                if repeated+                  then copy (k + 1) m+                  else do+                    writePrimArray out (2 * m) x+                    writePrimArray out (2 * m + 1) y+                    copy (k + 1) (m + 1)+      m <- copy from 0+      m' <-+        if wrap && m > 1+          then do+            onFirst <- near <$> readPrimArray out 0 <*> readPrimArray out 1 <*> readPrimArray out (2 * m - 2) <*> readPrimArray out (2 * m - 1)+            pure (if onFirst then m - 1 else m)+          else pure m+      shrinkMutablePrimArray out (2 * m')+      pure out++-- | Draw ops that fill a path, flattened through @t@ within @tol@: one+-- 'FillPolygon' per outline (open subpaths are filled as closed), with the+-- holes the fill rule makes cut out. A subpath is a hole when the rule+-- leaves it unfilled. Crossing subpaths fill independently, and a+-- self-intersecting one may fill only partly.+fillPathOps :: Float -> Transform -> FillRule -> Path -> Paint -> [DrawOp]+fillPathOps tol t rule path paint = concatMap polygonOp (fillComponents rule rings)+  where+    rings =+      [ pts+      | (pts, _) <- cleanRings True (flattenPath tol (arcSteps tol) t path)+      , abs (ringArea pts) > 1e-6+      ]+    polygonOp (outline, holes) = case devicePaint t paint of+      DeviceSolid col ->+        let pts = concatPoints (outline : holes)+            starts = ringStarts (outline : holes)+            tris = triangulateRings pts starts+         in [FillPolygon pts starts tris (Flat col) | nonEmpty tris]+      DeviceRamp ramp ->+        -- Split ring edges and triangles at every stop, so each piece's+        -- colour interpolates linearly between its corners.+        let rs = map (\r -> splitEdges (rampAt ramp) (rampSplits ramp) True r) (outline : holes)+            outlinePts = concatPoints rs+            starts = ringStarts rs+            (pts, tris) = splitTriangles (rampAt ramp) (rampSplits ramp) outlinePts (triangulateRings outlinePts starts)+         in [FillPolygon pts starts tris (Shaded (rampShades ramp pts)) | nonEmpty tris]+    nonEmpty a = sizeofPrimArray a > 0++-- | Draw ops that stroke a path, flattened through @t@ within @tol@: one+-- 'StrokePolyline' per subpath or per dash. Width and dash lengths scale by+-- the square root of the transform's area scale.+strokePathOps :: Float -> Transform -> Stroke -> Path -> Paint -> [DrawOp]+strokePathOps tol t st path paint+  | not (width > 0) = []+  | otherwise = concatMap ring (cleanRings False (flattenPath tol (arcSteps tol) t path))+  where+    k = averageStretch t+    width = strokeWidth st * k+    shade = devicePaint t paint+    ring (pts, closed)+      -- A subpath of zero length is a dot for round and square caps, a+      -- square one aligned with the x axis, as in SVG.+      | n == 1 = [line False (strokeCap st) (dot pts) | strokeCap st /= ButtCap]+      | n < 2 = []+      | not (null (strokeDash st))+      , Just pieces <- dashes (strokeCap st /= ButtCap) (map (* k) (strokeDash st)) (strokeDashOffset st * k) closed pts =+          map (line False (strokeCap st)) pieces+      -- A closed subpath of two points is a line that turns back on itself+      -- at each end: a round join rounds the ends, and a miter (past any+      -- limit) or bevel at a half turn is flat.+      | closed && n == 2 = [line False (if strokeJoin st == RoundJoin then RoundCap else ButtCap) pts]+      | otherwise = [line closed (strokeCap st) pts]+      where+        n = sizeofPrimArray pts `div` 2+    -- The point and another a hair along the transformed x axis, so its+    -- caps have a direction.+    dot pts =+      let x = indexPrimArray pts 0+          y = indexPrimArray pts 1+          Transform a b _ _ _ _ = t+          len = sqrt (a * a + b * b)+          (ux, uy) = if len > 0 && finite len then (a / len, b / len) else (1, 0)+       in primArrayFromListN 4 [x, y, x + 1e-3 * ux, y + 1e-3 * uy]+    line closed cap pts = case shade of+      DeviceSolid col -> StrokePolyline pts width closed cap (strokeJoin st) (strokeMiterLimit st) (Flat col)+      DeviceRamp ramp ->+        let pts' = splitEdges (rampAt ramp) (rampSplits ramp) closed pts+         in StrokePolyline pts' width closed cap (strokeJoin st) (strokeMiterLimit st) (Shaded (rampShades ramp pts'))++-- | All rings' points, back to back.+concatPoints :: [PrimArray Float] -> PrimArray Float+concatPoints [r] = r+concatPoints rs = mconcat rs++-- | Where each ring starts in 'concatPoints', and where the last ends.+ringStarts :: [PrimArray Float] -> PrimArray Int+ringStarts [r] = primArrayFromListN 2 [0, sizeofPrimArray r `div` 2]+ringStarts rs = primArrayFromList (scanl (+) 0 [sizeofPrimArray r `div` 2 | r <- rs])++-- | Group rings into outlines with their holes under the fill rule. Where+-- there are holes, the outline gets a positive 'ringArea' and the holes a+-- negative one. A ring is inside another when all its points are. Crossing+-- a ring inward changes the winding number by one, with the sign of the+-- ring's orientation, and the rule decides which regions fill. A filled+-- ring with no filled parent is an outline. An unfilled ring directly inside+-- it, or inside filled rings within it, is one of its holes. Crossing rings+-- are not nested, so each fills on its own. Copies of one loop, in either+-- direction, nest in turn like rings a hair apart, and an outline whose+-- hole is its own copy encloses nothing, so it draws nothing.+--+-- A ring's parent is the smallest larger ring holding all its points. The+-- rings whose boxes hold its box are found through a grid of the boxes and+-- tried smallest first, so mostly only the parent is tested point by point.+fillComponents :: FillRule -> [PrimArray Float] -> [(PrimArray Float, [PrimArray Float])]+fillComponents _ [r] = [(r, [])]+fillComponents rule rs =+  [ (orient True i, map (orient False) hs)+  | i <- ids+  , outline i+  , let hs = holesOf i+  , not (any (sameLoop (ring i) . ring) hs)+  ]+  where+    count = length rs+    ids = [0 .. count - 1]+    rings = smallArrayFromListN count rs+    ring = indexSmallArray rings+    areas = primArrayFromListN count (map ringArea rs)+    areaOf i = indexPrimArray areas i+    -- No area is NaN: 'fillPathOps' keeps only rings whose area is over 1e-6.+    size i = abs (areaOf i)+    boxes = smallArrayFromListN count (map ringBox rs)+    boxOf = indexSmallArray boxes+    -- Ring ids smallest first (the sort is stable, so equal sizes stay in id+    -- order), and a grid of their boxes in that order, so each cell lists its+    -- rings smallest first.+    bySize = primArrayFromListN count (sortBy (comparing size) ids)+    -- Each ring's place in 'bySize'.+    rank = indexPrimArray $ runPrimArray $ do+      out <- newPrimArray count+      forM_ [0 .. count - 1] $ \k -> writePrimArray out (indexPrimArray bySize k) k+      pure out+    grid =+      let (x0, y0, x1, y1) = foldl' union (1 / 0, 1 / 0, -1 / 0, -1 / 0) boxes+          union (!a, !b, !c, !d) (bx0, by0, bx1, by1) = (min a bx0, min b by0, max c bx1, max d by1)+       in gridOf count x0 y0 x1 y1 count (boxOf . indexPrimArray bySize)+    -- The smallest ring enclosing ring @i@. A box holding @i@'s box holds+    -- its corner, so the corner's cell lists every candidate. A copy of+    -- @i@'s loop later in 'bySize' encloses it too, so copies chain and the+    -- rings inside them find the first copy.+    parents = generatePrimArray count parentOf+    parentOf i = candidate (indexPrimArray (gridStarts grid) cell)+      where+        box@(bx0, by0, _, _) = boxOf i+        cell = gridRow grid by0 * gridCols grid + gridCol grid bx0+        end = indexPrimArray (gridStarts grid) (cell + 1)+        candidate !k+          | k >= end = -1+          | size j > size i && boxInside box (boxOf j) && encloses (ring j) (ring i) = j+          | rank j > rank i && sameLoop (ring j) (ring i) = j+          | otherwise = candidate (k + 1)+          where+            j = indexPrimArray bySize (indexPrimArray (gridItems grid) k)+    parent i = let p = indexPrimArray parents i in if p < 0 then Nothing else Just p+    -- The winding number just inside ring @i@: its parent's plus or minus+    -- one. Boxed and lazy so each ring can read its parent's.+    windings = smallArrayFromListN count (map windingOf ids)+    windingOf i = maybe 0 (indexSmallArray windings) (parent i) + (if areaOf i > 0 then 1 else -1) :: Int+    filled i = fillsWinding rule (indexSmallArray windings i)+    outline i = filled i && maybe True (not . filled) (parent i)+    -- Each ring's children in id order, gathered in one pass.+    children = indexSmallArray $ runSmallArray $ do+      kids <- newSmallArray count []+      forM_ [count - 1, count - 2 .. 0] $ \j -> do+        let p = indexPrimArray parents j+        when (p >= 0) (readSmallArray kids p >>= writeSmallArray kids p . (j :))+      pure kids+    holesOf i = concat [if filled c then holesOf c else [c] | c <- children i]+    orient positive i+      | (areaOf i >= 0) == positive = ring i+      | otherwise = reversePoints (ring i)+    boxInside (ax0, ay0, ax1, ay1) (bx0, by0, bx1, by1) = ax0 >= bx0 && ay0 >= by0 && ax1 <= bx1 && ay1 <= by1++-- | Whether every point of ring @q@ is inside ring @r@, by ray crossing+-- parity. A point on @r@'s outline may count either way: on a rect's left or+-- top edge it is inside, on its right or bottom edge outside.+encloses :: PrimArray Float -> PrimArray Float -> Bool+encloses r q = every 0+  where+    every !k+      | k + 1 >= sizeofPrimArray q = True+      | otherwise = inside (indexPrimArray q k) (indexPrimArray q (k + 1)) && every (k + 2)+    m = sizeofPrimArray r `div` 2+    inside px py = walk 0 False+      where+        walk !k !odd'+          | k >= m = odd'+          | otherwise =+              let !k' = if k + 1 >= m then 0 else k + 1+                  !ax = indexPrimArray r (2 * k)+                  !ay = indexPrimArray r (2 * k + 1)+                  !bx = indexPrimArray r (2 * k')+                  !by = indexPrimArray r (2 * k' + 1)+                  crosses = (ay > py) /= (by > py) && px < ax + (py - ay) * (bx - ax) / (by - ay)+               in walk (k + 1) (if crosses then not odd' else odd')++-- | Whether two rings list the same points around the same loop, from any+-- start and in either direction.+sameLoop :: PrimArray Float -> PrimArray Float -> Bool+sameLoop r q = sizeofPrimArray r == sizeofPrimArray q && m > 0 && any from [s | s <- [0 .. m - 1], pointAt r s == pointAt q 0]+  where+    m = sizeofPrimArray r `div` 2+    from s = all (\k -> pointAt r ((s + k) `mod` m) == pointAt q k) [1 .. m - 1] || all (\k -> pointAt r ((s - k) `mod` m) == pointAt q k) [1 .. m - 1]++-- | A ring's points in reverse order.+reversePoints :: PrimArray Float -> PrimArray Float+reversePoints r =+  let m = sizeofPrimArray r `div` 2+   in generatePrimArray (2 * m) (\i -> indexPrimArray r (2 * (m - 1 - i `div` 2) + i `mod` 2))++--------------------------------------------------------------------------------+-- Gradients+--------------------------------------------------------------------------------++-- | A paint in device coordinates.+data DevicePaint+  = DeviceSolid !Color+  | DeviceRamp !Ramp++-- | A linear gradient in device coordinates: its value at @(x, y)@ is+-- @gx x + gy y + g0@. Stop offsets are non-decreasing within 0..1.+data Ramp = Ramp !Float !Float !Float ![(Float, Color)]++-- | Map a paint from drawing coordinates to device coordinates. A+-- gradient's device value at a point is its value at the inverse-transformed+-- point, which is still linear in the point.+devicePaint :: Transform -> Paint -> DevicePaint+devicePaint _ (Solid c) = DeviceSolid c+devicePaint t@(Transform a b c d _ _) (Linear (V2 x0 y0) (V2 x1 y1) stops0) = case stops of+  [] -> DeviceSolid (Color 0)+  [(_, col)] -> DeviceSolid col+  _+    | len2 > 0 && det /= 0 && all finite [gx, gy, g0] -> DeviceRamp (Ramp gx gy g0 stops)+    | otherwise -> DeviceSolid (snd (last stops))+  where+    stops = rising 0 stops0+    rising lo ((o, col) : rest) = let o' = max lo (min 1 o) in (o', col) : rising o' rest+    rising _ [] = []+    dx = x1 - x0+    dy = y1 - y0+    len2 = dx * dx + dy * dy+    det = a * d - b * c+    -- The gradient's direction over its length squared, through the+    -- inverse transpose of the transform's linear part.+    gx = (d * dx - b * dy) / det / len2+    gy = (a * dy - c * dx) / det / len2+    (px, py) = applyTransform t x0 y0+    g0 = negate (gx * px + gy * py)++-- | A gradient's value at a point.+{-# INLINE rampAt #-}+rampAt :: Ramp -> Float -> Float -> Float+rampAt (Ramp gx gy g0 _) x y = gx * x + gy * y + g0++-- | The gradient values where the colour changes slope: its distinct stop+-- offsets, ascending. A hard edge (stops at one offset in different+-- colours) splits half a pixel either side of it instead, so the pieces+-- beside it keep their own colours and only the pixel across it blends.+rampSplits :: Ramp -> [Float]+rampSplits (Ramp gx gy _ stops) = nubAsc (sort (concatMap around (nubAsc (map fst stops))))+  where+    half = 0.5 * sqrt (gx * gx + gy * gy)+    around v = case [c | (o, c) <- stops, o == v] of+      c0 : rest | any (/= c0) rest -> [v - half, v + half]+      _ -> [v]+    nubAsc = map NE.head . NE.group++-- | The gradient's colour at each point.+rampShades :: Ramp -> PrimArray Float -> PrimArray Word32+rampShades ramp@(Ramp _ _ _ stops) pts =+  generatePrimArray (sizeofPrimArray pts `div` 2) $ \i ->+    let (x, y) = pointAt pts i+        Color w = rampColor stops (rampAt ramp x y)+     in w++-- | The colour at a gradient value, given stops in non-decreasing order.+rampColor :: [(Float, Color)] -> Float -> Color+rampColor stops v = case stops of+  (o0, c0) : _ | v <= o0 -> c0+  _ -> go stops+  where+    go ((o0, c0) : rest@((o1, c1) : _))+      | v < o1 = lerpColor c0 c1 ((v - o0) / (o1 - o0))+      | otherwise = go rest+    go [(_, c)] = c+    go [] = Color 0++-- | A polyline's points with a point inserted wherever an edge crosses a+-- value in @vs@ of @g@, in order along the edge. With @closed@, the closing+-- edge is split too.+splitEdges :: (Float -> Float -> Float) -> [Float] -> Bool -> PrimArray Float -> PrimArray Float+splitEdges g vs closed pts = primArrayFromList (concat [x : y : cuts i | i <- [0 .. m - 1], let (x, y) = pointAt pts i])+  where+    m = sizeofPrimArray pts `div` 2+    cuts i+      | i == m - 1 && not closed = []+      | otherwise =+          let (ax, ay) = pointAt pts i+              (bx, by) = pointAt pts ((i + 1) `mod` m)+              ga = g ax ay+              gb = g bx by+              us = sort [(v - ga) / (gb - ga) | v <- vs, min ga gb < v, v < max ga gb]+           in concat [[ax + u * (bx - ax), ay + u * (by - ay)] | u <- us]++-- | Cut triangles along the lines where @g@ equals each value in @vs@+-- (ascending), so no piece straddles one. Returns the points with the new+-- corners appended, and the pieces' index triples. A cut point is computed+-- from its edge's lower-indexed end, so both triangles sharing the edge put+-- it in exactly the same place.+splitTriangles :: (Float -> Float -> Float) -> [Float] -> PrimArray Float -> PrimArray Int -> (PrimArray Float, PrimArray Int)+splitTriangles g vs pts tris = (pts <> primArrayFromList [c | (x, y) <- reverse added, c <- [x, y]], primArrayFromList (reverse out))+  where+    n0 = sizeofPrimArray pts `div` 2+    corner i = let (x, y) = pointAt pts i in (i, x, y, g x y)+    (_, added, out) = foldl' triangle (n0, [], []) [(indexPrimArray tris (3 * t), indexPrimArray tris (3 * t + 1), indexPrimArray tris (3 * t + 2)) | t <- [0 .. sizeofPrimArray tris `div` 3 - 1]]+    triangle acc (i, j, k) =+      let poly = map corner [i, j, k]+          gs = [v | (_, _, _, v) <- poly]+          cutsHere = [v | v <- vs, minimum gs < v, v < maximum gs]+          (acc', rest) = foldl' cut (acc, poly) cutsHere+       in fanOut acc' rest+    -- Fan out the part below the value; the part above goes to the next cut.+    cut ((next, adds, tris'), poly) v =+      let edges = zip poly (drop 1 poly ++ take 1 poly)+          step (nx, ads, lower, upper) (p@(_, _, _, gp), q@(_, _, _, gq))+            | (gp < v && v < gq) || (gq < v && v < gp) =+                let (a, b) = if first p q then (p, q) else (q, p)+                    (_, ax, ay, ga) = a+                    (_, bx, by, gb) = b+                    u = (v - ga) / (gb - ga)+                    cx = ax + u * (bx - ax)+                    cy = ay + u * (by - ay)+                    c = (nx, cx, cy, v)+                 in (nx + 1, (cx, cy) : ads, c : keepBelow p lower, c : keepAbove p upper)+            | otherwise = (nx, ads, keepBelow p lower, keepAbove p upper)+          keepBelow p@(_, _, _, gp) acc = if gp <= v then p : acc else acc+          keepAbove p@(_, _, _, gp) acc = if gp >= v then p : acc else acc+          (next', adds', belowR, aboveR) = foldl' step (next, adds, [], []) edges+          -- The crossing goes after its edge's first end.+          below = reverse belowR+          above = reverse aboveR+          (next'', adds'', tris'') = fanOut (next', adds', tris') below+       in ((next'', adds'', tris''), above)+    first (i, _, _, _) (j, _, _, _) = i <= j+    fanOut acc@(nx, ads, ts) poly = case poly of+      (a, _, _, _) : rest@(_ : _ : _) -> (nx, ads, foldl' (\acc' ((b, _, _, _), (c, _, _, _)) -> c : b : a : acc') ts (zip rest (drop 1 rest)))+      _ -> acc++--------------------------------------------------------------------------------+-- Dashes+--------------------------------------------------------------------------------++-- | Split a polyline into dashes for a pattern and start offset. Each dash+-- is an open polyline. With @dots@, a zero-length dash gets a hair of length+-- so its caps have a direction; without, it is left out, as butt caps draw+-- nothing there. On a closed polyline, a dash through the start point is one+-- dash: the last one runs on into the first. 'Nothing' means draw solid: an+-- empty pattern, one with a negative or infinite length or all zeros, a+-- non-finite offset, or more than 'maxDashes' dashes.+--+-- NOINLINE: inlined, its bindings are allocated for every stroke, dashed or+-- not.+{-# NOINLINE dashes #-}+dashes :: Bool -> [Float] -> Float -> Bool -> PrimArray Float -> Maybe [PrimArray Float]+dashes dots pattern0 offset closed pts+  | null pattern0 || any (\v -> not (v >= 0) || isInfinite v) pattern0 || not (period > 0) || isInfinite period = Nothing+  | not (finite offset) || fromIntegral (length pattern `div` 2) * (total / period + 1) > (fromIntegral maxDashes :: Float) = Nothing+  | otherwise = case path of+      p0 : rest -> Just [primArrayFromList (concat [[x, y] | (x, y) <- d]) | d <- seam (filter (not . null) (walk k0 left0 [p0 | even k0] (0, 0) p0 rest))]+      [] -> Nothing+  where+    pattern = if odd (length pattern0) then pattern0 ++ pattern0 else pattern0+    plen = length pattern+    entries = primArrayFromListN plen pattern+    entry k = indexPrimArray entries (k `mod` plen)+    period = sum pattern+    widest = maximum pattern+    m = sizeofPrimArray pts `div` 2+    path = [pointAt pts i | i <- [0 .. m - 1]] ++ [pointAt pts 0 | closed]+    total = sum (zipWith dist path (drop 1 path))+    dist (ax, ay) (bx, by) = sqrt ((bx - ax) * (bx - ax) + (by - ay) * (by - ay))+    -- The pattern entry the line starts in and how much of it remains. A+    -- zero-length dash at the very start is kept as a dot. The offset is+    -- taken modulo the period in double precision, and kept within it, so+    -- a large offset cannot start past the entry it lands in.+    (k0, left0) =+      let o = realToFrac (realToFrac offset `mod'` (realToFrac period :: Double)) :: Float+       in skip 0 (if o >= 0 && o < period then o else 0)+    skip k o+      | k < 2 * plen && o >= entry k && (entry k > 0 || o > 0) = skip (k + 1) (o - entry k)+      | otherwise = (k, entry k - o)+    -- In entry @k@ with @left@ remaining, at point @p@ heading along @dir@.+    -- Inside a dash, @cur@ holds its points so far, reversed.+    walk :: Int -> Float -> [(Float, Float)] -> (Float, Float) -> (Float, Float) -> [(Float, Float)] -> [[(Float, Float)]]+    walk k left cur dir p qs = case qs of+      []+        | even k -> [dash dir cur | not (null cur)]+        -- A gap ending exactly at the line's end, followed by a zero-length+        -- dash: a dot at the end.+        | left <= 0 && entry (k + 1) == 0 -> [dash dir [p]]+        | otherwise -> []+      q : rest+        | len <= left -> walk k (left - len) (if even k then q : cur else cur) dir' q rest+        -- Not even the longest entry moves off @p@ at this precision, so+        -- the pattern would repeat here forever: the rest of the segment is+        -- solid.+        | mid == p && along (widest / len) == p ->+            if even k then walk k len cur dir' p qs else walk (k + 1) len [p] dir' p qs+        | even k -> dash dir' (mid : cur) : walk (k + 1) (entry (k + 1)) [] dir' mid qs+        | otherwise -> walk (k + 1) (entry (k + 1)) [mid] dir' mid qs+        where+          len = dist p q+          along u = (fst p + u * (fst q - fst p), snd p + u * (snd q - snd p))+          mid = along (left / len)+          dir' = if len > 0 then ((fst q - fst p) / len, (snd q - snd p) / len) else dir+    -- A dash's points in order without repeats. A lone point gets a second+    -- one a hair further along the line, or with no @dots@ is dropped.+    dash (dx, dy) ds = case dropRepeats (reverse ds) of+      [(x, y)]+        | dots -> [(x, y), (x + 1e-3 * dx, y + 1e-3 * dy)]+        | otherwise -> []+      kept -> kept+    -- On a closed polyline, a last dash ending at the start runs on into a+    -- first dash beginning there, rather than meeting it cap to cap.+    seam ds = case ds of+      first@(start : _) : more+        | closed+        , Just (middle, final) <- unsnoc more+        , Just (_, end) <- unsnoc final+        , dist start end < 1e-4 ->+            middle ++ [final ++ drop 1 first]+      _ -> ds+    dropRepeats (a : b : rest)+      | dist a b < 1e-4 = dropRepeats (a : rest)+      | otherwise = a : dropRepeats (b : rest)+    dropRepeats xs = xs++-- | The most dashes per subpath; past that it is drawn solid.+maxDashes :: Int+maxDashes = 4096++--------------------------------------------------------------------------------+-- Ops under a transform+--------------------------------------------------------------------------------++-- | An op drawn under transform @t@, flattening within @tol@ where needed.+--+-- Rects keep their op under transforms that keep sides axis-aligned (scale,+-- flip, quarter turn). Rounded rects also need a uniform scale, and circles+-- a transform that keeps them round. Otherwise they become polygons. Lines,+-- polygons and triangles transform their points, with widths scaled by the+-- square root of the transform's area scale.+--+-- A quad gradient under an axis-aligned transform fills the transformed+-- rect, each corner taking the colour of the nearest transformed corner,+-- when that keeps the diagonal it splits along or its colours blend the+-- same over either diagonal. Otherwise it becomes a polygon with per-corner+-- colours, triangulated as the untransformed quad is.+--+-- An unrotated image stays a rect under a transform without rotation or+-- skew, flipping its UVs for a flip or a negative size. Otherwise it is+-- rotated: its centre moves and it scales and turns with the transform. Text+-- moves its anchor and scales its font as widths scale; glyphs are not+-- rotated. A clip+-- becomes the bounding box of its transformed rect.+--+-- A transform with a NaN or infinite entry draws nothing, as does an empty+-- rounded rect, quad gradient or circle.+transformOp :: Float -> Transform -> DrawOp -> [DrawOp]+transformOp tol t@(Transform a b c d _ _) op+  | not (transformFinite t) = []+  | otherwise = case op of+      FillRect r col+        | keepsRects -> [FillRect (box r) col]+        | otherwise -> fillPathOps tol t NonZero (rect r) (Solid col)+      FillRoundedRect r rad col+        | empty r -> []+        | keepsRects && uniform -> [FillRoundedRect (box r) (rad * k) col]+        | otherwise -> fillPathOps tol t NonZero (roundedRect r rad) (Solid col)+      FillTriangle x0 y0 x1 y1 x2 y2 col ->+        let (x0', y0') = applyTransform t x0 y0+            (x1', y1') = applyTransform t x1 y1+            (x2', y2') = applyTransform t x2 y2+         in [FillTriangle x0' y0' x1' y1' x2' y2' col]+      FillCircle cx cy rad col+        | not (rad > 0) -> []+        | conformal -> let (cx', cy') = applyTransform t cx cy in [FillCircle cx' cy' (rad * k) col]+        | otherwise -> fillPathOps tol t NonZero (ellipse (V2 cx cy) (V2 rad rad)) (Solid col)+      Stroke x0 y0 x1 y1 w col -> line Stroke x0 y0 x1 y1 w col+      StrokeRoundedRect r rad w col+        | empty r -> []+        | keepsRects && uniform -> [StrokeRoundedRect (box r) (rad * k) (w * k) col]+        | otherwise ->+            -- The border lies inside the rect, so its centre line is the+            -- rect inset by half the width.+            let Rect x y rw rh = r+                bw = min w (min rw rh / 2)+             in strokePathOps tol t (stroke bw) (roundedRect (Rect (x + bw / 2) (y + bw / 2) (rw - bw) (rh - bw)) (rad - bw / 2)) (Solid col)+      StrokeCircle cx cy rad w col+        | not (rad > 0) -> []+        | conformal -> let (cx', cy') = applyTransform t cx cy in [StrokeCircle cx' cy' (rad * k) (w * k) col]+        | otherwise ->+            let bw = min w rad+             in strokePathOps tol t (stroke bw) (ellipse (V2 cx cy) (V2 (rad - bw / 2) (rad - bw / 2))) (Solid col)+      StrokeLineAA x0 y0 x1 y1 w col -> line StrokeLineAA x0 y0 x1 y1 w col+      FillPolygon pts rings tris sh -> [FillPolygon (points pts) rings tris sh]+      StrokePolyline pts w closed cap join limit sh -> [StrokePolyline (points pts) (w * k) closed cap join limit sh]+      FillQuadGradient r tl tr br bl+        | empty r -> []+        -- A quad blends over two triangles split from its top left to its+        -- bottom right. When the old top left lands on another corner that+        -- diagonal changes, which changes the blend unless the corner+        -- colours lie on a plane.+        | keepsRects && (even (fst (nearest (bx, by))) || planar) ->+            [ FillQuadGradient+                (Rect bx by bw bh)+                (snd (nearest (bx, by)))+                (snd (nearest (bx + bw, by)))+                (snd (nearest (bx + bw, by + bh)))+                (snd (nearest (bx, by + bh)))+            ]+        | otherwise ->+            -- The transformed corners, with the same order and two+            -- triangles the untransformed quad uses.+            let quad = primArrayFromList (concat [[x, y] | (x, y) <- cs])+             in [ quadPolygon quad (Shaded (primArrayFromListN 4 [w | Color w <- [tl, tr, br, bl]]))+                | abs (a * d - b * c) > 0+                ]+        where+          cs = corners r+          Rect bx by bw bh = box r+          -- The index and colour of the old corner, clockwise from top left,+          -- nearest a point.+          tagged = zip cs (zip [0 :: Int ..] [tl, tr, br, bl])+          nearest (px, py) =+            snd $ minimumBy (comparing (\((qx, qy), _) -> (qx - px) * (qx - px) + (qy - py) * (qy - py))) tagged+          planar = all sameDiag [colorR, colorG, colorB, colorA]+          sameDiag ch =+            fromIntegral (ch tl) + fromIntegral (ch br) == (fromIntegral (ch tr) + fromIntegral (ch bl) :: Int)+      DrawImage r angle tex u0 v0 u1 v1 col+        | angle == 0 && levelAxes ->+            -- The box runs left to right and top to bottom, so a flip, or a+            -- negative width or height (drawn mirrored), flips the UVs.+            let Rect _ _ rw rh = r+                (u0', u1') = if (a < 0) /= (rw < 0) then (u1, u0) else (u0, u1)+                (v0', v1') = if (d < 0) /= (rh < 0) then (v1, v0) else (v0, v1)+             in [DrawImage (box r) 0 tex u0' v0' u1' v1' col]+        | otherwise -> [turnedImage r angle tex u0 v0 u1 v1 col]+      DrawText x y ax ay txt col+        | scaled -> [DrawTextAligned x' y' ax ay k defaultTextFont txt col]+        | otherwise -> [DrawText x' y' ax ay txt col]+        where+          (x', y') = applyTransform t x y+      DrawTextStyled x y font txt col+        | scaled -> [DrawTextAligned x' y' 0 1 k font txt col]+        | otherwise -> [DrawTextStyled x' y' font txt col]+        where+          (x', y') = applyTransform t x y+      DrawTextAligned x y ax ay s font txt col ->+        let (x', y') = applyTransform t x y in [DrawTextAligned x' y' ax ay (if scaled then s * k else s) font txt col]+      PushClip r -> [PushClip (box r)]+      PopClip -> [PopClip]+  where+    k = averageStretch t+    -- Ignore scale within rounding error (as from a rotation), so text+    -- keeps its font.+    scaled = abs (k - 1) > 1e-3+    -- A zero-size rect, for which the rounded rect ops draw nothing.+    empty (Rect _ _ w h) = not (w > 0 && h > 0)+    -- Zero but for rounding: a half turn's sine is not quite 0.+    rounding = 1e-6 * maximum (map abs [a, b, c, d])+    small v = abs v <= rounding+    -- No rotation or skew.+    levelAxes = small b && small c+    keepsRects = levelAxes || (small a && small d)+    uniform = small (abs a + abs b - abs c - abs d)+    -- Rotation and a uniform scale, perhaps with a flip.+    conformal = (a == d && b == negate c) || (a == negate d && b == c)+    line mk x0 y0 x1 y1 w col =+      let (x0', y0') = applyTransform t x0 y0+          (x1', y1') = applyTransform t x1 y1+       in [mk x0' y0' x1' y1' (w * k) col]+    points pts = runPrimArray $ do+      let !n = sizeofPrimArray pts+      out <- newPrimArray n+      let go !i = when (i + 1 < n) $ do+            let (x, y) = applyTransform t (indexPrimArray pts i) (indexPrimArray pts (i + 1))+            writePrimArray out i x+            writePrimArray out (i + 1) y+            go (i + 2)+      go 0+      pure out+    -- The rect's transformed corners, clockwise from the top left.+    corners (Rect x y w h) = [applyTransform t px py | (px, py) <- [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]]+    -- The bounding box of the rect's transformed corners.+    box r =+      let cs = corners r+          xs = map fst cs+          ys = map snd cs+       in Rect (minimum xs) (minimum ys) (maximum xs - minimum xs) (maximum ys - minimum ys)+    -- An image rotated by @angle@ about its centre, under the transform.+    -- The centre is transformed, each side scales by how much the transform+    -- stretches the rotated image's axis along it, and the rotation follows+    -- the image's x axis, flipping v when the transform flips. Exact for+    -- rotations, uniform scales and flips; under a skew the image stays a+    -- rect rather than a parallelogram.+    turnedImage (Rect x y w h) angle tex u0 v0 u1 v1 col =+      let (cx, cy) = applyTransform t (x + w / 2) (y + h / 2)+          cs = cos angle+          sn = sin angle+          exX = a * cs + c * sn+          exY = b * cs + d * sn+          eyX = c * cs - a * sn+          eyY = d * cs - b * sn+          w' = w * sqrt (exX * exX + exY * exY)+          h' = h * sqrt (eyX * eyX + eyY * eyY)+          (v0', v1') = if a * d - b * c < 0 then (v1, v0) else (v0, v1)+       in DrawImage (Rect (cx - w' / 2) (cy - h' / 2) w' h') (atan2 exY exX) tex u0 v0' u1 v1' col
+ lib/NanoUI/Internal/Resource.hs view
@@ -0,0 +1,51 @@+-- | Typed resource ownership and a payload-free session cleanup registry.+module NanoUI.Internal.Resource+  ( Resource (..)+  , newResource+  , Held (..)+  , newHeld+  , Holding (..)+  )+where++import Data.IORef (IORef, newIORef)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.Primitive.PrimVar (PrimVar, newPrimVar)+import Data.Unique (hashUnique, newUnique)+import GHC.Exts (RealWorld)++-- | A typed owner allocated once per component in a session. The registry+-- retains only its cleanup action; its key and value never leave this cell.+data Resource k a = Resource !Int !(IORef (Maybe (k, a, Holding)))++instance Eq (Resource k a) where+  Resource a _ == Resource b _ = a == b++newResource :: IO (Resource k a)+newResource = Resource <$> (hashUnique <$> newUnique) <*> newIORef Nothing++-- | Release starts cleanup and returns an action waiting for completion.+data Holding = Holding+  { holdingRelease :: !(IO (IO ()))+  , holdingSeen :: !(PrimVar RealWorld Int)+  }++-- | Session registry and frame stamps. Built-in callback-only leases use a+-- widget-to-resource-id index; arbitrary values live in typed owners instead.+data Held = Held+  { heldEntries :: !(IORef (IntMap Holding))+  , heldWidgets :: !(IORef (IntMap Int))+  , heldFrame :: !(PrimVar RealWorld Int)+  , heldStamped :: !(PrimVar RealWorld Int)+  , heldCount :: !(PrimVar RealWorld Int)+  }++newHeld :: IO Held+newHeld =+  Held+    <$> newIORef IM.empty+    <*> newIORef IM.empty+    <*> newPrimVar 0+    <*> newPrimVar 0+    <*> newPrimVar 0
+ lib/NanoUI/Internal/RichText/Types.hs view
@@ -0,0 +1,187 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Paragraph values and typed layout cache, independent of view execution.+module NanoUI.Internal.RichText.Types+  ( InlineStyle (..)+  , Inline (..)+  , inlineText+  , Run (..)+  , TokenKind (..)+  , Token (..)+  , Line (..)+  , InteractivePiece (..)+  , Paragraph (..)+  , Inputs (..)+  , RichSelection (..)+  , Measured (..)+  , ParagraphCache (..)+  , Paragraphs (..)+  )+where++import Data.IORef (IORef)+import Data.IntMap.Strict (IntMap)+import Data.Primitive.SmallArray (SmallArray)+import Data.String (IsString (..))+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Draw.Types (TextFont)+import NanoUI.Internal.Font (FontMetrics)+import NanoUI.Internal.Style (Layout, Theme)+import NanoUI.Internal.Types (Color)+import NanoUI.Widgets.TextBuffer (Cursor, TextBuffer)++-- | How an 'Inline' piece modifies the paragraph's base layout. Common presets+-- carry no function or 'Layout' copy so steady-frame cache checks allocate+-- nothing.+data InlineStyle+  = InlinePlain+  | InlineBold+  | InlineItalic+  | InlineMono+  | InlineCustom !(Layout -> Layout)++-- | Text with a layout-style modifier, optional link target, background,+-- and hover tooltip.+data Inline = Inline !Text !InlineStyle !(Maybe Text) !(Maybe Color) !(Maybe Text)++instance IsString Inline where+  fromString = inlineText . T.pack++-- | Plain text in the paragraph's style. A string literal is the same piece+-- ('IsString').+inlineText :: Text -> Inline+inlineText txt = Inline txt InlinePlain Nothing Nothing Nothing++-- | The style of one 'Inline' piece, resolved once when the paragraph is+-- measured.+data Run = Run+  { runFont :: !TextFont+  , runColor :: !Color+  , runLineHeight :: !Float+  -- ^ Line height of 'runFont'.+  , runAscent :: !Float+  -- ^ Distance from the top of a line box to the baseline of 'runFont'.+  , runTarget :: !(Maybe Text)+  -- ^ Link target, if the piece is a link.+  , runBackground :: !(Maybe Color)+  -- ^ Fill drawn behind the piece's text, if any.+  , runTooltip :: !(Maybe Text)+  -- ^ Optional tooltip shown when hovering the piece.+  }++-- | How a 'Token' wraps. 'Word' and 'Space' come from pieces that break at+-- spaces, 'Break' is a newline, and 'Glyph' and 'GlyphSpace' are single+-- characters from pieces that break anywhere.+data TokenKind+  = -- | A run of non-space characters, kept on one line.+    Word+  | -- | A run of spaces or tabs.+    Space+  | -- | A newline; it has zero width and ends the line.+    Break+  | -- | One character cluster of a break-anywhere piece.+    Glyph+  | -- | A space or tab inside a break-anywhere piece.+    GlyphSpace+  deriving Eq++-- | A unit of line breaking: a slice of one piece's text with its measured+-- width.+data Token = Token+  { tokenText :: !Text+  , tokenRun :: !Int+  -- ^ Index of the token's 'Run' in 'paraRuns'.+  , tokenKind :: !TokenKind+  , tokenWidth :: !Float+  , tokenStart :: {-# UNPACK #-} !Int+  -- ^ Character offset of the token in the paragraph's plain text.+  , tokenMetrics :: !FontMetrics+  -- ^ Font metrics prepared for the token's text.+  }++-- | One wrapped line of a paragraph, placed by its tokens.+data Line = Line+  { lineStart :: {-# UNPACK #-} !Int+  -- ^ Character offset of the line's first character in the paragraph text.+  , lineTop :: !Float+  -- ^ Offset of the line box from the top of the paragraph.+  , lineHeight :: !Float+  , lineAscent :: !Float+  , lineWidth :: !Float+  , lineTokens :: ![(Float, Token)]+  -- ^ Tokens with their x offset from the line's left edge.+  }++-- | Interactive span (link or tooltipped run) relative to the paragraph's+-- top-left corner, cached alongside 'paraLines' when the width settles.+data InteractivePiece = InteractivePiece+  { ipRun :: {-# UNPACK #-} !Int+  , ipX :: {-# UNPACK #-} !Float+  , ipY :: {-# UNPACK #-} !Float+  , ipW :: {-# UNPACK #-} !Float+  , ipH :: {-# UNPACK #-} !Float+  }++-- | Disposable text/measurement data. Selection belongs to the widget store,+-- so changing presentation or evicting this cache cannot clear it.+data Paragraph = Paragraph+  { paraKey :: !Int+  , paraInputs :: !(IORef Inputs)+  , paraRuns :: !(SmallArray Run)+  , paraTokens :: ![Token]+  , paraEmptyLine :: !(Float, Float)+  , paraNatural :: (Float, Float)+  , paraWidth :: !Float+  , paraLines :: [Line]+  , paraInteractive :: ![InteractivePiece]+  -- ^ Link and tooltip spans in paragraph-local coordinates for 'paraLines'.+  , paraTooltipRuns :: ![(Int, Text)]+  -- ^ Runs carrying a hover tooltip, precomputed once per paragraph.+  , paraHasInteractive :: !Bool+  -- ^ Whether any run is a link or has a hover tooltip.+  , paraHasGlyphs :: !Bool+  -- ^ Whether any piece uses 'BreakAnywhere' (has 'Glyph' or 'GlyphSpace' tokens).+  , paraMeasured :: !(IORef Measured)+  , paraText :: !Text+  , paraBuffer :: TextBuffer+  -- ^ Built lazily, at most once per paragraph, when a text command needs it.+  }++-- | What a 'Paragraph' was built from: the pieces, the base 'Layout', the+-- 'Theme', the font metric generation, and whether it is selectable. The+-- paragraph is reused while a new frame's inputs match these.+data Inputs = Inputs [Inline] !Layout !Theme !Int !Bool++-- | The selection in a selectable paragraph, kept in the widget store.+data RichSelection = RichSelection+  { selectionText :: !Text+  -- ^ The paragraph text the offsets below index.+  , selectionAnchor :: !Cursor+  -- ^ Where the selection started.+  , selectionCursor :: !Cursor+  -- ^ The moving end of the selection.+  , selectionDragging :: !Bool+  -- ^ A mouse drag that began in the paragraph is in progress.+  , selectionMoved :: !Bool+  -- ^ The pointer has moved since the drag began.+  , selectionStart :: !Int+  -- ^ Lower end of the selection, as a character offset.+  , selectionEnd :: !Int+  -- ^ Upper end of the selection, as a character offset.+  }+  deriving Eq++-- | The last extent measured for a paragraph. @Measured width w h@ holds the+-- extent @(w, h)@ computed when offered @width@.+data Measured+  = -- | Nothing measured yet.+    Unmeasured+  | Measured !Float !Float !Float++-- | Entry count, eviction threshold, and paragraphs by widget key.+data ParagraphCache = ParagraphCache !Int !Int !(IntMap Paragraph)++-- | The 'ParagraphCache' in a mutable reference; it is the value held in the+-- context's paragraph 'NanoUI.Internal.Host.Host' slot.+newtype Paragraphs = Paragraphs (IORef ParagraphCache)
+ lib/NanoUI/Internal/SIMD.hs view
@@ -0,0 +1,169 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Vertex and index writers for the draw buffers. They write with scalar+-- stores, which measured no slower than packed 128-bit ones.+module NanoUI.Internal.SIMD+  ( pokeVertexSIMD+  , pokeQuadSIMD+  , pokeQuadGradientSIMD+  , pokeQuadIndices+  , concentricOffsetsSIMD+  , pokeQuadCornersSIMD+  ) where++import Foreign.Ptr (Ptr)+import Foreign.Storable (pokeByteOff)+import Data.Word (Word32, Word8)++-- | Writes one 32-byte Vertex (8 floats: position, colour, uv) into memory.+{-# INLINE pokeVertexSIMD #-}+pokeVertexSIMD ::+  Ptr Word8 ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  IO ()+pokeVertexSIMD vp off px py r g b a u v = do+  pokeByteOff vp off px+  pokeByteOff vp (off + 4) py+  pokeByteOff vp (off + 8) r+  pokeByteOff vp (off + 12) g+  pokeByteOff vp (off + 16) b+  pokeByteOff vp (off + 20) a+  pokeByteOff vp (off + 24) u+  pokeByteOff vp (off + 28) v++-- | Quad Poking: writes 4 vertices (128 bytes total) and 6 indices (24 bytes total).+{-# INLINE pokeQuadSIMD #-}+pokeQuadSIMD ::+  Ptr Word8 ->+  Int ->+  Ptr Word8 ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Word32 ->+  IO ()+pokeQuadSIMD vertices vOffset indices iOffset x y w h =+  let x1 = x + w+      y1 = y + h+   in pokeQuadCornersSIMD vertices vOffset indices iOffset x y x1 y x1 y1 x y1++-- | Quad with arbitrary corners, for non-axis-aligned quads: 4 vertices and+-- 6 indices. The corners map to the texture's top-left, top-right,+-- bottom-right and bottom-left, in that order.+{-# INLINE pokeQuadCornersSIMD #-}+pokeQuadCornersSIMD ::+  Ptr Word8 ->+  Int ->+  Ptr Word8 ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Word32 ->+  IO ()+pokeQuadCornersSIMD vertices vOffset indices iOffset x0 y0 x1 y1 x2 y2 x3 y3 u0 v0 u1 v1 r g b a baseIdx = do+  pokeVertexSIMD vertices vOffset x0 y0 r g b a u0 v0+  pokeVertexSIMD vertices (vOffset + 32) x1 y1 r g b a u1 v0+  pokeVertexSIMD vertices (vOffset + 64) x2 y2 r g b a u1 v1+  pokeVertexSIMD vertices (vOffset + 96) x3 y3 r g b a u0 v1+  pokeQuadIndices indices iOffset baseIdx (baseIdx + 1) (baseIdx + 2) (baseIdx + 3)++-- | Writes the six indices of quad @a b c d@ (corners in order) as the two+-- triangles @a b c@ and @a c d@, with scalar stores.+{-# INLINE pokeQuadIndices #-}+pokeQuadIndices :: Ptr Word8 -> Int -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()+pokeQuadIndices ip off a b c d = do+  pokeByteOff ip off a+  pokeByteOff ip (off + 4) b+  pokeByteOff ip (off + 8) c+  pokeByteOff ip (off + 12) a+  pokeByteOff ip (off + 16) c+  pokeByteOff ip (off + 20) d++-- | Quad with 4 distinct corner colors (top-left, top-right, bottom-right, bottom-left)+{-# INLINE pokeQuadGradientSIMD #-}+pokeQuadGradientSIMD ::+  Ptr Word8 ->+  Int ->+  Ptr Word8 ->+  Int ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  (Float, Float, Float, Float) ->+  (Float, Float, Float, Float) ->+  (Float, Float, Float, Float) ->+  (Float, Float, Float, Float) ->+  Word32 ->+  IO ()+pokeQuadGradientSIMD+  vertices vOffset indices iOffset x y w h u v+  (r0, g0, b0, a0) (r1, g1, b1, a1)+  (r2, g2, b2, a2) (r3, g3, b3, a3) baseIdx = do+  let x1 = x + w+      y1 = y + h+  pokeVertexSIMD vertices vOffset x y r0 g0 b0 a0 u v+  pokeVertexSIMD vertices (vOffset + 32) x1 y r1 g1 b1 a1 u v+  pokeVertexSIMD vertices (vOffset + 64) x1 y1 r2 g2 b2 a2 u v+  pokeVertexSIMD vertices (vOffset + 96) x y1 r3 g3 b3 a3 u v+  pokeQuadIndices indices iOffset baseIdx (baseIdx + 1) (baseIdx + 2) (baseIdx + 3)++-- | Evaluates 4 concentric arc positions:+-- xs = cx + radii * ct+-- ys = cy + radii * st+--+-- Scalar on purpose: GHC 9.14.1 miscompiles the broadcast/pack/unpack FloatX4#+-- version at -O2 once it is inlined into a loop (liberate-case computed the y+-- lane from cx), corrupting anti-aliased border vertices. The results are+-- bit-identical to the vector version, which also multiplied and added separately.+{-# INLINE concentricOffsetsSIMD #-}+concentricOffsetsSIMD ::+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  Float ->+  ((Float, Float), (Float, Float), (Float, Float), (Float, Float))+concentricOffsetsSIMD cx cy ct st r0 r1 r2 r3 =+  ( (cx + r0 * ct, cy + r0 * st)+  , (cx + r1 * ct, cy + r1 * st)+  , (cx + r2 * ct, cy + r2 * st)+  , (cx + r3 * ct, cy + r3 * st)+  )
+ lib/NanoUI/Internal/Sensor/Types.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE StrictData #-}++-- | Visibility values and typed sensor storage, independent of frame execution.+module NanoUI.Internal.Sensor.Types+  ( Visibility (..)+  , VisibilityEvent (..)+  , SensorConfig (..)+  , Sensors (..)+  , SensorState (..)+  , Cell (..)+  , CellState (..)+  , Watch (..)+  , Seen (..)+  , ClipMemo (..)+  , MemoEntry (..)+  )+where++import Data.IORef (IORef)+import Data.IntMap.Strict (IntMap)+import Data.Primitive.Array (MutableArray)+import GHC.Exts (RealWorld)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Style (Layout)+import NanoUI.Internal.Types (Rect)++-- | Visibility at the last completed layout. Movement alone emits no event.+data Visibility = Visibility+  { visVisible :: !Bool+  -- ^ Overlaps the window and ancestor clips, including the anticipation+  -- margin, for at least sensorDelay. Empty extents count as lines or points.+  , visEvent :: !(Maybe VisibilityEvent)+  -- ^ Consumed by the first view pass that reads it.+  , visRect :: !Rect+  -- ^ Visible portion without anticipation margin; empty off screen.+  , visBounds :: !Rect+  -- ^ Whole widget bounds; empty when no node exists.+  }+  deriving (Eq, Show)++-- | A change of 'visVisible', reported once in 'visEvent'.+data VisibilityEvent = BecameVisible | BecameHidden+  deriving (Eq, Show)++-- | Options for 'NanoUI.sensorConfigured' and 'NanoUI.useVisibility'.+data SensorConfig = SensorConfig+  { sensorAnticipate :: Float+  -- ^ Grow the window and clips by this many logical pixels; negatives act as 0.+  , sensorDelay :: Double+  -- ^ Seconds continuously visible before entering; leaving is immediate.+  , sensorLayout :: Layout -> Layout+  -- ^ Container layout modifier, ignored by useVisibility.+  }++data Sensors = Sensors (IORef SensorState) (IORef ClipMemo)++-- | Pass, watched cells and count, and all retained cells with their count.+data SensorState = SensorState Int [Cell] Int (IntMap Cell) Int++data Cell = Cell Int (IORef CellState)++data CellState = CellState Int Watch Seen++data Watch = Watch WidgetId SensorConfig++data Seen = Seen Visibility Double+  deriving (Eq)++-- | Reused ancestor-clip array, invalidated by a per-layout stamp.+data ClipMemo = ClipMemo Int (MutableArray RealWorld MemoEntry)++data MemoEntry = NoClips | Clips Int Float (Maybe Rect, Maybe Rect)
+ lib/NanoUI/Internal/Shader.hs view
@@ -0,0 +1,299 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Core shader descriptors, capability flags, and packed per-frame call+-- payloads. Shaders are pure, immutable, content-hashed values: views never+-- hold a backend handle, and backends compile and cache GPU programs lazily+-- on first draw.+module NanoUI.Internal.Shader+  ( ShaderKind (..)+  , IsNodeEffect (..)+  , ShaderCapabilities (..)+  , noShaderCapabilities+  , ShaderProgram (..)+  , emptyShaderProgram+  , hashShaderProgram+  , CpuFragCtx (..)+  , CpuShaderEval+  , ShaderPass (..)+  , Shader (..)+  , contramapShader+  , fixUniform+  , rawShader+  , rawLayerShader+  , ShaderConfig (..)+  , defaultShaderConfig+  , PackedShaderPass (..)+  , packShaderPass+  , ShaderNodeEntry (..)+  , ShaderEffectEntry (..)+  ) where++import Data.Bits (xor)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.Dynamic (Dynamic)+import Data.Primitive.ByteArray (ByteArray, MutableByteArray)+import Data.Proxy (Proxy (..))+import Data.Text (Text)+import Data.Text.Encoding qualified as TE+import Data.Word (Word64, Word8)+import GHC.Exts (RealWorld)+import NanoUI.Internal.Style (LayoutModifier)+import NanoUI.Internal.Types (Color, V2 (..), colorTransparent, colorWhite)+import NanoUI.Internal.Uniforms+  ( UniformField (..)+  , Uniforms (..)+  , hashUniformBytes+  , packZeroedBytes+  , uniformLayout+  , uniformSize+  )++-- | Role a fragment shader plays in the node tree.+data ShaderKind+  = -- | Leaf surface fill over a node's rectangle; requires no offscreen target.+    Surface+  | -- | Pure pixel-color transform over a subtree; composes and fuses into one pass.+    ColorEffect+  | -- | Coordinate warp over a subtree; fuses with other distortions and color effects.+    DistortionEffect+  | -- | General neighborhood-sampling post-process over an offscreen subtree target.+    LayerEffect+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | Constraint selecting shader kinds valid for wrapping a node subtree+-- ('NanoUI.withShader').+class IsNodeEffect (k :: ShaderKind) where+  -- | Witness the effect kind at runtime.+  nodeEffectKind :: Proxy k -> ShaderKind++instance IsNodeEffect 'ColorEffect where+  nodeEffectKind _ = ColorEffect++instance IsNodeEffect 'DistortionEffect where+  nodeEffectKind _ = DistortionEffect++instance IsNodeEffect 'LayerEffect where+  nodeEffectKind _ = LayerEffect++-- | Which shader features the active backend supports.+data ShaderCapabilities = ShaderCapabilities+  { capSurfaceShaders :: !Bool+  -- ^ Backend can run Tier 1 leaf surface shaders.+  , capNodeEffects :: !Bool+  -- ^ Backend can run Tier 2 offscreen subtree effects.+  }+  deriving (Eq, Show)++-- | Capabilities for headless, SVG, or non-GPU backends.+noShaderCapabilities :: ShaderCapabilities+noShaderCapabilities = ShaderCapabilities False False++-- | Compiled backend shader payloads for one fragment pass. Fields are lazy+-- so each backend only evaluates the target format it needs.+data ShaderProgram = ShaderProgram+  { spGlsl150 :: Maybe Text+  -- ^ OpenGL 3.2 core fragment shader (@nano-ui-rgfw@).+  , spGlslEs300 :: Maybe Text+  -- ^ WebGL2 fragment shader (@nano-ui-sdl-web@).+  , spSpirv :: Maybe ByteString+  -- ^ SPIR-V 1.0 fragment binary (@nano-ui-sdl@ Vulkan via SDL 3.4 GPU).+  , spMsl :: Maybe Text+  -- ^ Metal Shading Language fragment source (@nano-ui-sdl@ Metal).+  , spNeedsTex :: !Bool+  -- ^ Whether the fragment shader samples the input texture (@uInput@).+  , spUniformLayout :: ![UniformField]+  -- ^ Flattened std140 fields of the user uniform block (after the 48-byte+  -- system header).+  , spUniformBytes :: !Int+  -- ^ Padded user uniform byte count (multiple of 16; 0 for @()@).+  }++-- | Program with no backend artifacts and no user uniforms.+emptyShaderProgram :: ShaderProgram+emptyShaderProgram =+  ShaderProgram+    { spGlsl150 = Nothing+    , spGlslEs300 = Nothing+    , spSpirv = Nothing+    , spMsl = Nothing+    , spNeedsTex = False+    , spUniformLayout = []+    , spUniformBytes = 0+    }++-- | Stable 64-bit FNV-1a content hash identifying a compiled 'ShaderProgram'+-- across frames for backend program caching and paint-hash tracking.+hashShaderProgram :: ShaderProgram -> Word64+hashShaderProgram sp =+  let h0 = 0xcbf29ce484222325 :: Word64+      h1 = mixByte h0 (if spNeedsTex sp then 1 else 0)+      h2 = mixInt h1 (spUniformBytes sp)+      h3 = maybe h2 (mixBytes h2 . TE.encodeUtf8) (spGlsl150 sp)+      h4 = maybe h3 (mixBytes h3 . TE.encodeUtf8) (spGlslEs300 sp)+      h5 = maybe h4 (mixBytes h4) (spSpirv sp)+      h6 = maybe h5 (mixBytes h5 . TE.encodeUtf8) (spMsl sp)+   in if h6 == 0 then 1 else h6+  where+    mixByte :: Word64 -> Word8 -> Word64+    mixByte !h !b = (h `xor` fromIntegral b) * 0x100000001b3+    mixInt :: Word64 -> Int -> Word64+    mixInt !h !n = (h `xor` fromIntegral n) * 0x100000001b3+    mixBytes !h bs = BS.foldl' mixByte (mixInt h (BS.length bs)) bs++-- | Fragment evaluation context passed to a CPU fallback evaluator.+data CpuFragCtx = CpuFragCtx+  { cfcUv :: !V2+  -- ^ Normalized coordinates in @[0, 1] x [0, 1]@.+  , cfcPos :: !V2+  -- ^ Local logical pixel coordinates.+  , cfcSize :: !V2+  -- ^ Node width and height in logical pixels.+  , cfcScale :: !Float+  -- ^ Physical pixels per logical layout unit.+  , cfcColor :: !Color+  -- ^ Vertex tint color.+  , cfcCornerRadius :: !Float+  -- ^ Logical corner radius.+  }+  deriving (Eq, Show)++-- | Pure CPU fragment evaluator: given fragment context and an input texture+-- sampler (in local logical pixel coordinates), returns the output color.+type CpuShaderEval = CpuFragCtx -> (V2 -> Color) -> Color++-- | One GPU fragment pass parameterized by uniform record @u@.+data ShaderPass u = ShaderPass+  { spHash :: {-# UNPACK #-} !Word64+  , spProgram :: !ShaderProgram+  , spUniformSize :: {-# UNPACK #-} !Int+  , spPack :: !(u -> MutableByteArray RealWorld -> Int -> IO ())+  }++-- | Pure, phantom-typed fragment shader descriptor.+--+-- @k@ fixes whether the shader paints a leaf 'Surface' or wraps a subtree+-- ('ColorEffect', 'DistortionEffect', 'LayerEffect'). @u@ is the Haskell+-- uniform record packed into std140 bytes each frame.+data Shader (k :: ShaderKind) u = Shader+  { shaderHash :: {-# UNPACK #-} !Word64+  , shaderPasses :: ![ShaderPass u]+  -- ^ GPU passes executed in order (one for most shaders; two or more for+  -- separable multi-pass filters such as Gaussian blur).+  , shaderMargin :: !(u -> V2)+  -- ^ Maximum sample offset in logical pixels in X and Y, used to size+  -- offscreen targets and expand partial-damage bounds.+  , shaderCpuEval :: !(Maybe (u -> CpuShaderEval))+  -- ^ Optional CPU evaluator for headless differential testing and SVG export.+  , shaderSvgOpacity :: !(Maybe (u -> Float))+  -- ^ Optional native opacity extractor so @nano-ui-svg@ can emit @<g opacity>@.+  , shaderFusion :: !(Maybe Dynamic)+  -- ^ Optional monomorphic EDSL fusion body attached by @nano-ui-shader@ so+  -- compatible effects fuse into a single GPU pass.+  }++-- | Adapt a shader to accept a larger or different uniform record @u2@.+contramapShader :: (u2 -> u1) -> Shader k u1 -> Shader k u2+contramapShader f s =+  s+    { shaderPasses = [p {spPack = \u -> spPack p (f u)} | p <- shaderPasses s]+    , shaderMargin = shaderMargin s . f+    , shaderCpuEval = fmap (. f) (shaderCpuEval s)+    , shaderSvgOpacity = fmap (. f) (shaderSvgOpacity s)+    , shaderFusion = Nothing+    }++-- | Specialize a shader with a constant uniform value.+fixUniform :: u -> Shader k u -> Shader k ()+fixUniform u = contramapShader (const u)++-- | Build a shader from hand-written backend sources while keeping typed+-- 'Uniforms' packing and automatic paint-hash damage tracking.+rawShader :: forall k u. Uniforms u => ShaderProgram -> Shader k u+rawShader prog0 =+  let !layout = uniformLayout (Proxy :: Proxy u)+      !sz = uniformSize (Proxy :: Proxy u)+      prog = prog0 {spUniformLayout = layout, spUniformBytes = sz}+      !h = hashShaderProgram prog+      pass =+        ShaderPass+          { spHash = h+          , spProgram = prog+          , spUniformSize = sz+          , spPack = \u mba base -> do+              _ <- pokeUniformAt u mba base 0+              pure ()+          }+   in Shader+        { shaderHash = h+        , shaderPasses = [pass]+        , shaderMargin = const (V2 0 0)+        , shaderCpuEval = Nothing+        , shaderSvgOpacity = Nothing+        , shaderFusion = Nothing+        }++-- | Build a 'LayerEffect' shader from hand-written backend sources with an+-- explicit maximum sample offset in logical pixels.+rawLayerShader :: forall u. Uniforms u => (u -> V2) -> ShaderProgram -> Shader 'LayerEffect u+rawLayerShader margin prog = (rawShader prog {spNeedsTex = True}) {shaderMargin = margin}++-- | Configuration for a leaf 'Surface' shader node ('NanoUI.shaderConfigured').+data ShaderConfig = ShaderConfig+  { scLayout :: !LayoutModifier+  -- ^ Layout modifier applied to 'NanoUI.defaultLayout'.+  , scCornerRadius :: !Float+  -- ^ Corner radius in logical pixels, forwarded in @uMeta.y@ and used for+  -- fallback rounded-rect rendering.+  , scFallback :: !Color+  -- ^ Solid fill drawn when the active backend does not support shaders (or+  -- during SVG export when CPU rasterization is off).+  , scTint :: !Color+  -- ^ Vertex tint color passed as @vColor@ (default opaque white).+  }++-- | Default leaf shader config: unconstrained layout, square corners,+-- transparent fallback, white tint.+defaultShaderConfig :: ShaderConfig+defaultShaderConfig =+  ShaderConfig+    { scLayout = id+    , scCornerRadius = 0+    , scFallback = colorTransparent+    , scTint = colorWhite+    }++-- | Existential-free packed pass payload captured during view construction.+data PackedShaderPass = PackedShaderPass+  { pspHash :: {-# UNPACK #-} !Word64+  , pspProgram :: !ShaderProgram+  , pspUniforms :: !ByteArray+  , pspUniformHash :: {-# UNPACK #-} !Word64+  }++-- | Pack a 'ShaderPass' with its frame uniform value @u@ into zero-padded+-- std140 bytes and compute its content hash.+packShaderPass :: ShaderPass u -> u -> IO PackedShaderPass+packShaderPass pass u = do+  ba <- packZeroedBytes (spUniformSize pass) (\mba -> spPack pass u mba 0)+  pure (PackedShaderPass (spHash pass) (spProgram pass) ba (hashUniformBytes ba))++-- | Registration attached to a 'NanoUI.Internal.Layout.Arena.NodeShader' in 'NanoUI.Internal.Context.Types.NodeCustom'.+data ShaderNodeEntry = ShaderNodeEntry+  { snePass :: !PackedShaderPass+  , sneCornerRadius :: {-# UNPACK #-} !Float+  , sneFallback :: {-# UNPACK #-} !Color+  , sneTint :: {-# UNPACK #-} !Color+  }++-- | Registration attached to a shaded 'NanoUI.Internal.Layout.Arena.NodeContainer' in+-- 'NanoUI.Internal.Context.Types.NodeCustom'.+data ShaderEffectEntry = ShaderEffectEntry+  { seePasses :: ![PackedShaderPass]+  , seeMargin :: !V2+  , seeSvgOpacity :: !(Maybe Float)+  }
+ lib/NanoUI/Internal/Shortcut.hs view
@@ -0,0 +1,154 @@+-- | Key chords: a key plus the exact modifiers held with it. Build them with+-- '<>' (@ctrl <> shift <> key \'s\'@), parse them from xmonad EZConfig-style+-- text (@C-S-s@), and label them for menus (@Ctrl+Shift+S@).+module NanoUI.Internal.Shortcut+  ( Shortcut (..)+  , ToKey (..)+  , key+  , ctrl+  , shift+  , alt+  , super+  , cmdOrCtrl+  , parseShortcut+  , shortcutLabel+  , keyLabel+  , shortcutIn+  ) where++import Control.Applicative ((<|>))+import Data.Char (toLower, toUpper)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Input+import Text.ParserCombinators.ReadP (choice, eof, get, many, readP_to_S, string, (+++))++-- | A key pressed while exactly these modifiers are held, so+-- @ctrl <> key \'s\'@ does not match Ctrl+Shift+S. '<>' unions the modifiers+-- and keeps the right-hand key if it has one. A chord with no key, such as+-- @ctrl <> shift@, never matches.+data Shortcut = Shortcut+  { shortcutKey :: !(Maybe Key)+  , shortcutModifiers :: !Modifiers+  }+  deriving (Eq, Ord, Show)++instance Semigroup Shortcut where+  Shortcut k m <> Shortcut k' m' = Shortcut (k' <|> k) (m <> m')++instance Monoid Shortcut where+  mempty = Shortcut Nothing mempty++-- | A 'Key', or a 'Char' naming the key that types it without Shift+-- ('KeyChar'). Letters may be either case.+class ToKey a where+  toKey :: a -> Key++instance ToKey Key where+  toKey = id++instance ToKey Char where+  -- Backends report the space bar as 'KeySpace', never as a character.+  toKey ' ' = KeySpace+  toKey c = KeyChar (toLower c)++-- | The key of a chord: @key \'s\'@, @key KeyEnter@, @key (KeyF 5)@. Name a+-- symbol by its unshifted key: on a US layout Ctrl++ is+-- @ctrl <> shift <> key \'=\'@, while @ctrl <> key \'+\'@ is keypad plus.+key :: ToKey k => k -> Shortcut+key k = Shortcut (Just (toKey k)) mempty++-- | Ctrl held.+ctrl :: Shortcut+ctrl = modifier noModifiers {modCtrl = True}++-- | Shift held.+shift :: Shortcut+shift = modifier noModifiers {modShift = True}++-- | Alt (Option) held.+alt :: Shortcut+alt = modifier noModifiers {modAlt = True}++-- | Super (Command, the Windows key) held.+super :: Shortcut+super = modifier noModifiers {modSuper = True}++-- | Command held on macOS, Ctrl elsewhere ('modPrimary'), so+-- @cmdOrCtrl <> key \'s\'@ works on both.+cmdOrCtrl :: Shortcut+cmdOrCtrl = modifier primaryModifiers++modifier :: Modifiers -> Shortcut+modifier = Shortcut Nothing++-- | Parse a chord from text, such as a settings file: modifier prefixes,+-- then a key. In code, prefer '<>' (@cmdOrCtrl <> shift <> key \'p\'@), which+-- cannot be misspelled.+--+-- * Modifiers: @C-@ Ctrl, @S-@ Shift, @A-@ Alt (Option), @s-@ Super+--   (Command, the Windows key), @M-@ Command on macOS and Ctrl elsewhere+--   ('modPrimary').+-- * Key: one character, as typed without Shift ('KeyChar'; letters in+--   either case), or a named key in angle brackets: @<F1>@ to @<F24>@, or a+--   'Key' constructor without its @Key@ prefix, such as @<Enter>@,+--   @<Escape>@, @<PageDown>@ or @<Space>@.+--+-- > C-s   M-S-p   A-<Enter>   <F5>   C--   C-S-=+--+-- Name a symbol by its unshifted key: on a US layout Ctrl++ is @C-S-=@,+-- while @C-+@ is keypad plus. Returns 'Left' for text that is not a chord.+parseShortcut :: Text -> Either Text Shortcut+parseShortcut txt =+  case [s | (s, "") <- readP_to_S chord (T.unpack txt)] of+    s : _ -> Right s+    [] -> Left ("not a chord: " <> txt)+  where+    chord = do+      mods <- many (choice [m <$ string [prefix, '-'] | (prefix, m) <- modifierPrefixes])+      k <- choice [named <$ string ('<' : name ++ ">") | (name, named) <- keyNames] +++ (toKey <$> get)+      eof+      pure (mconcat mods <> key k)++modifierPrefixes :: [(Char, Shortcut)]+modifierPrefixes = [('C', ctrl), ('S', shift), ('A', alt), ('s', super), ('M', cmdOrCtrl)]++-- | Keys written in angle brackets, by their 'keyLabel'.+keyNames :: [(String, Key)]+keyNames =+  [ (T.unpack (keyLabel k), k)+  | k <-+      [ KeyBackspace, KeyDelete, KeyEnter, KeyEscape, KeyTab, KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd+      , KeyPageUp, KeyPageDown, KeyInsert, KeySpace, KeyPrintScreen, KeyPause, KeyCapsLock, KeyNumLock+      , KeyScrollLock, KeyMenu+      ]+        ++ map KeyF [1 .. 24]+  ]++-- | The chord as a menu label: modifiers in the order Ctrl, Alt, Shift,+-- Super (Option and Cmd on macOS), then the key ('keyLabel'), joined by @+@.+shortcutLabel :: Shortcut -> Text+shortcutLabel (Shortcut k mods) =+  T.intercalate "+" ([name | (True, name) <- held] ++ maybe [] (pure . keyLabel) k)+  where+    held =+      [ (modCtrl mods, "Ctrl")+      , (modAlt mods, if onMac then "Option" else "Alt")+      , (modShift mods, "Shift")+      , (modSuper mods, if onMac then "Cmd" else "Super")+      ]++-- | A key's name: letters upper-cased, other characters as is, named keys+-- by constructor without the @Key@ prefix.+keyLabel :: Key -> Text+keyLabel = \case+  KeyChar c -> T.singleton (toUpper c)+  KeyF n -> "F" <> T.pack (show n)+  k -> T.pack (drop 3 (show k))++-- | Whether the input presses the chord: its key was pressed this frame with+-- exactly its modifiers held. Ignores focus, modals and other shortcuts that+-- claimed the key; views use 'NanoUI.shortcut' instead.+shortcutIn :: Shortcut -> Input -> Bool+shortcutIn (Shortcut k mods) inp =+  inputModifiers inp == mods && any (`pressedIn` inp) k
+ lib/NanoUI/Internal/Store.hs view
@@ -0,0 +1,601 @@+{-# LANGUAGE CPP #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | The widget store: per-widget state in maps by value type, keyed by widget+-- id and 'Slot'.+module NanoUI.Internal.Store+  ( WidgetStore (..)+  , emptyWidgetStore+  , Field+  , fieldInt+  , fieldFloat+  , fieldDouble+  , fieldPoint+  , fieldText+  , fieldIntSet+  , fieldBuffer+  , fieldDocument+  , fieldTextDocument+  , fieldHistory+  , fieldEditorMode+  , fieldLineWidths+  , fieldGrid+  , fieldTableState+  , fieldCombo+  , fieldRichSelection+  , fieldQuiet+  , overField+  , lookupSlot+  , findSlot+  , insertSlot+  , deleteSlot+  , flagSlot+  , SlotWrites (..)+  , slotWrite+  , slotWriteOr+  , slotKey+  , Slot (..)+  , SlotSpec (..)+  , slotSpec+  , ownSlotSpec+  , encodedSpec+  , floatBitsSpec+  , specKey+  , lookupSpec+  , findSpec+  , memberSpec+  , insertSpec+  , deleteSpec+  , specWrite+  , specWriteOr+  , fieldSelection+  , fieldSelectionWrite+  , setFieldSelection+  , collapseFieldSelection+  , boolInt+  , intBool+  , anySelectOpen+  , isSelectOpen+  , setSelectOpen+  , closeSelects+  , ptrEq+  , eqByPtr+  , sameFloat+  , sameDouble+  , diffKeys+  , slotChangedKeys+  )+where++import Data.IntMap.Strict (IntMap)+import Data.IntSet (IntSet)+import Data.Text (Text)+import Data.Word (Word64)+import GHC.Float (castFloatToWord32, castWord32ToFloat)+import qualified Data.IntMap.Internal as IMI+import qualified Data.IntMap.Strict as IM+#if MIN_VERSION_containers(0,8,0)+import qualified Data.IntSet.Internal.IntTreeCommons as ITC+#endif+import qualified Data.Text as T+import NanoUI.Internal.Id (mix64)+import NanoUI.Internal.Equality (eqByPtr, ptrEq, sameDouble, sameFloat)+import NanoUI.Internal.Store.Types (ComboState, GridState, LineWidths, TableState, TextHistory, sameComboVisual)+import NanoUI.Internal.RichText.Types (RichSelection)+import NanoUI.Internal.TextEditor.Types (EditorMode)+import NanoUI.Internal.Types (V2)+import NanoUI.Internal.Widgets.TextDocument (TextDocument)+import NanoUI.Widgets.TextBuffer (TextBuffer)++-- | Keys whose values differ between two maps, a key that left or joined+-- included. Exploits structural sharing via 'ptrEq' at every internal 'Bin'+-- node so single-key store updates diff in O(log n) without building an+-- intermediate map.+diffKeysBy :: (a -> a -> Bool) -> IntMap a -> IntMap a -> [Int]+diffKeysBy eq !old !new = go old new []+  where+    allKeys IMI.Nil acc = acc+    allKeys (IMI.Tip k _) acc = k : acc+#if MIN_VERSION_containers(0,8,0)+    allKeys (IMI.Bin _ l r) acc = allKeys l (allKeys r acc)+#else+    allKeys (IMI.Bin _ _ l r) acc = allKeys l (allKeys r acc)+#endif++    go !t1 !t2 acc+      | ptrEq t1 t2 = acc+      | otherwise = case (t1, t2) of+          (IMI.Nil, _) -> allKeys t2 acc+          (_, IMI.Nil) -> allKeys t1 acc+          (IMI.Tip k1 v1, IMI.Tip k2 v2)+            | k1 == k2 -> if eq v1 v2 then acc else k1 : acc+            | k1 < k2 -> k1 : k2 : acc+            | otherwise -> k2 : k1 : acc+          (IMI.Tip k1 v1, IMI.Bin {}) -> diffTip True k1 v1 t2 acc+          (IMI.Bin {}, IMI.Tip k2 v2) -> diffTip False k2 v2 t1 acc+#if MIN_VERSION_containers(0,8,0)+          (IMI.Bin p1 l1 r1, IMI.Bin p2 l2 r2) -> case ITC.treeTreeBranch p1 p2 of+            ITC.ABL -> go l1 t2 (allKeys r1 acc)+            ITC.ABR -> allKeys l1 (go r1 t2 acc)+            ITC.BAL -> go t1 l2 (allKeys r2 acc)+            ITC.BAR -> allKeys l2 (go t1 r2 acc)+            ITC.EQL -> go l1 l2 (go r1 r2 acc)+            ITC.NOM -> allKeys t1 (allKeys t2 acc)+#else+          (IMI.Bin p1 m1 l1 r1, IMI.Bin p2 m2 l2 r2)+            | IMI.shorter m1 m2 -> merge1 p1 m1 l1 r1 p2 t2 acc+            | IMI.shorter m2 m1 -> merge2 p2 m2 l2 r2 p1 t1 acc+            | p1 == p2 -> go l1 l2 (go r1 r2 acc)+            | otherwise -> allKeys t1 (allKeys t2 acc)++    merge1 p1 m1 l1 r1 p2 t2 acc+      | IMI.nomatch p2 p1 m1 = allKeys (IMI.Bin p1 m1 l1 r1) (allKeys t2 acc)+      | IMI.zero p2 m1 = go l1 t2 (allKeys r1 acc)+      | otherwise = allKeys l1 (go r1 t2 acc)++    merge2 p2 m2 l2 r2 p1 t1 acc+      | IMI.nomatch p1 p2 m2 = allKeys t1 (allKeys (IMI.Bin p2 m2 l2 r2) acc)+      | IMI.zero p1 m2 = go t1 l2 (allKeys r2 acc)+      | otherwise = allKeys l2 (go t1 r2 acc)+#endif++    diffTip !fromOld !k !v !t acc = case t of+      IMI.Nil -> k : acc+      IMI.Tip k' v'+        | k == k' ->+            let same = if fromOld then eq v v' else eq v' v+             in if same then acc else k : acc+        | otherwise -> k : k' : acc+#if MIN_VERSION_containers(0,8,0)+      IMI.Bin p l r+        | ITC.nomatch k p -> k : allKeys t acc+        | ITC.left k p -> diffTip fromOld k v l (allKeys r acc)+        | otherwise -> allKeys l (diffTip fromOld k v r acc)+#else+      IMI.Bin p m l r+        | IMI.nomatch k p m -> k : allKeys t acc+        | IMI.zero k m -> diffTip fromOld k v l (allKeys r acc)+        | otherwise -> allKeys l (diffTip fromOld k v r acc)+#endif++-- | 'diffKeysBy' with '==' behind a pointer check: an entry a map update left+-- alone keeps its object, so it compares without touching its value.+diffKeys :: Eq a => IntMap a -> IntMap a -> [Int]+diffKeys = diffKeysBy eqByPtr++-- | The keys whose values changed between two stores in every slot map but+-- the scroll offsets ('storeFloat', 'storePoint') and the 'storeQuiet'+-- bookkeeping. Lazy: a caller that only asks whether anything changed stops+-- at the first changed key.+slotChangedKeys :: WidgetStore -> WidgetStore -> [Int]+slotChangedKeys !old !new+  | ptrEq old new = []+  | otherwise =+      diffKeys (storeInt old) (storeInt new)+        ++ diffKeys (storeDouble old) (storeDouble new)+        ++ diffKeys (storeText old) (storeText new)+        ++ diffKeys (storeIntSet old) (storeIntSet new)+        ++ diffKeysBy ptrEq (storeBuffer old) (storeBuffer new)+        ++ diffKeysBy ptrEq (storeDocument old) (storeDocument new)+        ++ diffKeysBy ptrEq (storeTextDocument old) (storeTextDocument new)+        ++ diffKeysBy ptrEq (storeHistory old) (storeHistory new)+        ++ diffKeys (storeEditorMode old) (storeEditorMode new)+        ++ diffKeysBy ptrEq (storeLineWidths old) (storeLineWidths new)+        ++ diffKeys (storeGrid old) (storeGrid new)+        ++ diffKeys (storeTableState old) (storeTableState new)+        ++ diffKeysBy sameComboVisual (storeCombo old) (storeCombo new)+        ++ diffKeys (storeRichSelection old) (storeRichSelection new)++-- | Widget state for every widget, in maps by value type. Same-type fields+-- that share a widget key use 'slotKey'.+data WidgetStore = WidgetStore+  { storeOpenSelect :: {-# UNPACK #-} !Int+  , storeInt :: !(IntMap Int)+  , storeFloat :: !(IntMap Float)+  , storeDouble :: !(IntMap Double)+  , storePoint :: !(IntMap V2)+  , storeText :: !(IntMap Text)+  , storeIntSet :: !(IntMap IntSet)+  , storeBuffer :: !(IntMap TextBuffer)+  , storeDocument :: !(IntMap TextDocument)+  , storeTextDocument :: !(IntMap (Text, TextDocument))+  , storeHistory :: !(IntMap TextHistory)+  , storeEditorMode :: !(IntMap EditorMode)+  , storeLineWidths :: !(IntMap LineWidths)+  , storeGrid :: !(IntMap GridState)+  , storeTableState :: !(IntMap TableState)+  , storeCombo :: !(IntMap ComboState)+  , storeRichSelection :: !(IntMap RichSelection)+  , storeQuiet :: !(IntMap Int)+  -- ^ Interaction bookkeeping that repaints nothing by itself, such as+  -- whether a drag hook's press is still held. Writes to it neither damage+  -- nor wake the loop: the visible effects of the interaction go through the+  -- widget's own slots.+  }++-- | One of the store's maps: how to read it, and how to put a new one back.+-- The slot functions inline at the field they are given, so+-- @insertSlot fieldInt k v@ compiles to the record update it stands for, and+-- a composition of them builds the store once.+data Field a = Field (WidgetStore -> IntMap a) (IntMap a -> WidgetStore -> WidgetStore)++-- | Integer slots, including boolean flags and selection indices.+fieldInt :: Field Int+fieldInt = Field storeInt (\m st -> st {storeInt = m})++-- | Single-precision numeric slots.+fieldFloat :: Field Float+fieldFloat = Field storeFloat (\m st -> st {storeFloat = m})++-- | Double-precision slots, including monotonic timestamps.+fieldDouble :: Field Double+fieldDouble = Field storeDouble (\m st -> st {storeDouble = m})++-- | 2D vector slots for positions, sizes, or offsets.+fieldPoint :: Field V2+fieldPoint = Field storePoint (\m st -> st {storePoint = m})++-- | Text-value slots.+fieldText :: Field Text+fieldText = Field storeText (\m st -> st {storeText = m})++-- | Integer-set slots, such as expanded tree-node indices.+fieldIntSet :: Field IntSet+fieldIntSet = Field storeIntSet (\m st -> st {storeIntSet = m})++-- | A text area's 'TextBuffer', by widget key.+fieldBuffer :: Field TextBuffer+fieldBuffer = Field storeBuffer (\m st -> st {storeBuffer = m})++-- | The 'TextDocument' last passed to or returned from a text area.+fieldDocument :: Field TextDocument+fieldDocument = Field storeDocument (\m st -> st {storeDocument = m})++-- | The text last passed to or returned from a text area over 'Text', with+-- its document.+fieldTextDocument :: Field (Text, TextDocument)+fieldTextDocument = Field storeTextDocument (\m st -> st {storeTextDocument = m})++-- | A text area's undo and redo history.+fieldHistory :: Field TextHistory+fieldHistory = Field storeHistory (\m st -> st {storeHistory = m})++-- | A text editor's modal editing mode.+fieldEditorMode :: Field EditorMode+fieldEditorMode = Field storeEditorMode (\m st -> st {storeEditorMode = m})++-- | A text area's measured line widths.+fieldLineWidths :: Field LineWidths+fieldLineWidths = Field storeLineWidths (\m st -> st {storeLineWidths = m})++-- | A grid's state.+fieldGrid :: Field GridState+fieldGrid = Field storeGrid (\m st -> st {storeGrid = m})++-- | A table's column order, dragged widths, hidden set, and active resize.+fieldTableState :: Field TableState+fieldTableState = Field storeTableState (\m st -> st {storeTableState = m})++-- | A combo box's state between frames.+fieldCombo :: Field ComboState+fieldCombo = Field storeCombo (\m st -> st {storeCombo = m})++-- | A selectable paragraph's selection, kept apart from its measurement cache.+fieldRichSelection :: Field RichSelection+fieldRichSelection = Field storeRichSelection (\m st -> st {storeRichSelection = m})++-- | Integer bookkeeping slots that repaint nothing by themselves+-- ('storeQuiet'). The store diff that drives damage skips them.+fieldQuiet :: Field Int+fieldQuiet = Field storeQuiet (\m st -> st {storeQuiet = m})++-- | Read the map selected by a field descriptor.+{-# INLINE fieldMap #-}+fieldMap :: Field a -> WidgetStore -> IntMap a+fieldMap (Field get _) = get++-- | Pure update of one selected map; publish the resulting store through the context.+{-# INLINE overField #-}+overField :: Field a -> (IntMap a -> IntMap a) -> WidgetStore -> WidgetStore+overField (Field get set) f st = set (f (get st)) st++-- | Read a key from a typed map, returning 'Nothing' when absent.+{-# INLINE lookupSlot #-}+lookupSlot :: Field a -> Int -> WidgetStore -> Maybe a+lookupSlot field k = IM.lookup k . fieldMap field++-- | The slot's value, or @def@ while it has none.+{-# INLINE findSlot #-}+findSlot :: Field a -> a -> Int -> WidgetStore -> a+findSlot field def k = IM.findWithDefault def k . fieldMap field++-- | Pure insert or replacement. Does not itself notify a context or schedule a frame.+{-# INLINE insertSlot #-}+insertSlot :: Field a -> Int -> a -> WidgetStore -> WidgetStore+insertSlot field k v = overField field (IM.insert k v)++-- | Pure removal of a key; an absent key leaves the map unchanged.+{-# INLINE deleteSlot #-}+deleteSlot :: Field a -> Int -> WidgetStore -> WidgetStore+deleteSlot field k = overField field (IM.delete k)++-- | An int slot read as a flag: set while it holds anything but 0.+{-# INLINE flagSlot #-}+flagSlot :: Int -> WidgetStore -> Bool+flagSlot k = intBool . findSlot fieldInt 0 k++-- | Slot writes that know whether they would change the store. Combine them+-- with '<>' and run them with 'NanoUI.Internal.Context.writeSlots', which leaves the+-- store alone when every slot already holds its value.+data SlotWrites = SlotWrites (WidgetStore -> Bool) (WidgetStore -> WidgetStore)++instance Semigroup SlotWrites where+  {-# INLINE (<>) #-}+  SlotWrites same f <> SlotWrites same' g = SlotWrites (\st -> same st && same' st) (f . g)++instance Monoid SlotWrites where+  {-# INLINE mempty #-}+  mempty = SlotWrites (const True) id++-- | Describe a write with an equality check. In @a <> b@, @a@ wins if both+-- writes target the same field and key.+{-# INLINE slotWrite #-}+slotWrite :: Eq a => Field a -> Int -> a -> SlotWrites+slotWrite field k v = SlotWrites (\st -> lookupSlot field k st == Just v) (insertSlot field k v)++-- | 'slotWrite' whose change check treats an absent slot as @def@. A batch+-- with no other changes can leave that slot empty; a batch that does write+-- may materialise the default value too.+{-# INLINE slotWriteOr #-}+slotWriteOr :: Eq a => Field a -> a -> Int -> a -> SlotWrites+slotWriteOr field def k v = SlotWrites (\st -> findSlot field def k st == v) (insertSlot field k v)++-- | Where one value of a widget's state lives: the key it is stored under,+-- as a function of the widget's key, the 'Field' map that holds it, and how+-- the value is kept there (decode, encode). A spec names the map and the+-- stored encoding once, so a reader and a writer of the same state cannot+-- disagree on either. "NanoUI.Internal.Store.Slots" lists the built-in+-- ones.+--+-- The functions over a spec inline at a constant one: @insertSpec+-- (slotSpec SlotCursor fieldInt) k v@ compiles to @insertSlot fieldInt+-- (slotKey SlotCursor k) v@ (checked by the @nano-ui-inspection@ suite).+data SlotSpec a = forall s. SlotSpec (Int -> Int) (Field s) (s -> a) (a -> s)++-- | Slot @s@ of a widget in map @field@, stored as it is.+{-# INLINE slotSpec #-}+slotSpec :: Slot -> Field a -> SlotSpec a+slotSpec s field = SlotSpec (slotKey s) field id id++-- | The widget's own key in map @field@, stored as it is.+{-# INLINE ownSlotSpec #-}+ownSlotSpec :: Field a -> SlotSpec a+ownSlotSpec field = SlotSpec id field id id++-- | A spec whose values are stored as @spec@'s, through @dec@ and @enc@.+-- @dec . enc@ must be 'id'.+{-# INLINE encodedSpec #-}+encodedSpec :: (s -> a) -> (a -> s) -> SlotSpec s -> SlotSpec a+encodedSpec dec enc (SlotSpec key field d e) = SlotSpec key field (dec . d) (e . enc)++-- | A 'Float' kept as its 32 bits in an 'Int' slot, such as one in+-- 'fieldQuiet'.+{-# INLINE floatBitsSpec #-}+floatBitsSpec :: SlotSpec Int -> SlotSpec Float+floatBitsSpec = encodedSpec (castWord32ToFloat . fromIntegral) (fromIntegral . castFloatToWord32)++-- | The store key of a widget key's value.+{-# INLINE specKey #-}+specKey :: SlotSpec a -> Int -> Int+specKey (SlotSpec key _ _ _) = key++-- | 'lookupSlot' through a spec.+{-# INLINE lookupSpec #-}+lookupSpec :: SlotSpec a -> Int -> WidgetStore -> Maybe a+lookupSpec (SlotSpec key field dec _) k st = dec <$> lookupSlot field (key k) st++-- | 'findSlot' through a spec: the value, or @def@ while there is none.+{-# INLINE findSpec #-}+findSpec :: SlotSpec a -> a -> Int -> WidgetStore -> a+findSpec (SlotSpec key field dec enc) def k st = dec (findSlot field (enc def) (key k) st)++-- | Whether a key exists in the spec's map, regardless of its value.+{-# INLINE memberSpec #-}+memberSpec :: SlotSpec a -> Int -> WidgetStore -> Bool+memberSpec (SlotSpec key field _ _) k = IM.member (key k) . fieldMap field++-- | 'insertSlot' through a spec.+{-# INLINE insertSpec #-}+insertSpec :: SlotSpec a -> Int -> a -> WidgetStore -> WidgetStore+insertSpec (SlotSpec key field _ enc) k v = insertSlot field (key k) (enc v)++-- | 'deleteSlot' through a spec.+{-# INLINE deleteSpec #-}+deleteSpec :: SlotSpec a -> Int -> WidgetStore -> WidgetStore+deleteSpec (SlotSpec key field _ _) k = deleteSlot field (key k)++-- | 'slotWrite' through a spec.+{-# INLINE specWrite #-}+specWrite :: Eq a => SlotSpec a -> Int -> a -> SlotWrites+specWrite spec k v = SlotWrites (\st -> lookupSpec spec k st == Just v) (insertSpec spec k v)++-- | 'slotWriteOr' through a spec.+{-# INLINE specWriteOr #-}+specWriteOr :: Eq a => SlotSpec a -> a -> Int -> a -> SlotWrites+specWriteOr spec def k v = SlotWrites (\st -> findSpec spec def k st == v) (insertSpec spec k v)++-- | Empty maps and no open select.+emptyWidgetStore :: WidgetStore+emptyWidgetStore =+  WidgetStore+    { storeOpenSelect = 0+    , storeInt = IM.empty+    , storeFloat = IM.empty+    , storeDouble = IM.empty+    , storePoint = IM.empty+    , storeText = IM.empty+    , storeIntSet = IM.empty+    , storeBuffer = IM.empty+    , storeDocument = IM.empty+    , storeTextDocument = IM.empty+    , storeHistory = IM.empty+    , storeEditorMode = IM.empty+    , storeLineWidths = IM.empty+    , storeGrid = IM.empty+    , storeTableState = IM.empty+    , storeCombo = IM.empty+    , storeRichSelection = IM.empty+    , storeQuiet = IM.empty+    }++-- | Derive a key for a named sub-slot, separating values such as cursor and+-- anchor that share one widget and one typed map. Uses a non-cryptographic hash.+{-# INLINE slotKey #-}+slotKey :: Slot -> Int -> Int+slotKey s k = fromIntegral (mix64 (fromIntegral k) (slotTag s))++-- | Single-line field @key@'s @(anchor, cursor)@ over @text@, the one+-- reading of its slots: an unstored cursor is at the end and an unstored+-- anchor on the cursor, both clamped to the text.+fieldSelection :: WidgetStore -> Int -> Text -> (Int, Int)+fieldSelection store key text =+  let len = T.length text+      cursor = min len (findSlot fieldInt len (slotKey SlotCursor key) store)+      anchor = min len (findSlot fieldInt cursor (slotKey SlotAnchor key) store)+   in (anchor, cursor)++-- | Store field @key@'s selection over @text@, a change only when it differs+-- from what 'fieldSelection' reads.+fieldSelectionWrite :: Int -> Text -> Int -> Int -> SlotWrites+fieldSelectionWrite key text anchor cursor =+  SlotWrites+    (\st -> fieldSelection st key text == (anchor, cursor))+    (setFieldSelection key anchor cursor)++-- | Store field @key@'s anchor and cursor.+setFieldSelection :: Int -> Int -> Int -> WidgetStore -> WidgetStore+setFieldSelection key anchor cursor =+  insertSlot fieldInt (slotKey SlotAnchor key) anchor . insertSlot fieldInt (slotKey SlotCursor key) cursor++-- | Collapse field @key@'s selection onto its cursor ('fieldSelection').+collapseFieldSelection :: Int -> WidgetStore -> WidgetStore+collapseFieldSelection key = deleteSlot fieldInt (slotKey SlotAnchor key)++-- | Every built-in slot. The map each slot's values live in, and how they+-- are stored there, is in its 'SlotSpec' in "NanoUI.Internal.Store.Slots";+-- read and write a slot through that spec.+data Slot+  = SlotCursor+  | SlotAnchor+  | SlotDrag+  | SlotDragW+  | SlotDrop+  | SlotDropPos+  | SlotWinSize+  | SlotMenuOpen+  | SlotMenuPos+  | SlotScrollCross+  | SlotScrollLinkX+  | SlotScrollLinkY+  | SlotScrollStep+  | SlotScrollAxes+  | SlotScrollRange+  | SlotScrollContent+  | -- | An offset in window axes set before the scroller's first layout+    -- (storePoint), placed on the axes it owns once it has one.+    SlotScrollPending+  | SlotTextAreaScroll+  | SlotTextAreaViewport+  | SlotTextAreaAnchorRow+  | SlotTextAreaAnchorCol+  | -- | The text area's 'NanoUI.Widgets.TextBuffer.TextBuffer' (in 'storeBuffer'):+    -- its lines, which are its current document, its caret, and which lines+    -- changed since they were measured. Loads and paint read it. The document+    -- last passed or returned is under 'SlotSeen', in 'storeDocument'.+    SlotTextAreaBuffer+  | -- | For a text area over 'Text' (in 'storeTextDocument'): the text last passed or+    -- returned and the document it is the text of, so a frame that edits+    -- nothing neither splits nor joins the text.+    SlotTextAreaText+  | -- | Set (value 1) to signal that a text field's or text area's text changed+    -- through a path that does not flow through @Input@ (e.g. a context-menu+    -- cut/paste). The widget reads and clears this on its next frame, so the+    -- caller still gets a @respChanged@ pulse for edits that carry no keys or+    -- chars.+    SlotTextAreaChanged+  | -- | A text field's undo history with the text it was recorded against, in+    -- 'storeHistory'.+    SlotTextHistory+  | -- | How the text field with this id edits (its editor mode, in+    -- 'storeEditorMode'). Commands sent to the id between frames read it.+    SlotTextMode+  | -- | A text area's measured line widths and content extent, in 'storeLineWidths',+    -- kept in step with its lines so an edit remeasures only the lines it+    -- changed.+    SlotTextAreaWidths+  | -- | A text area's row height as it was last painted (storeFloat), for+    -- commands run between frames to keep the caret in view with.+    SlotTextAreaLineH+  | -- | Set (value 1, in 'storeQuiet') when a text area's editor state is+    -- saved: its next paint, which has the font, scrolls the caret into view+    -- across and clears it. The saved state already keeps the caret in view+    -- vertically, and its slots repaint the area.+    SlotTextAreaReveal+  | SlotTextInputScroll++  | -- | Search-field debounce bookkeeping, on the text widget id: the last+    -- committed query (storeText) and the monotonic time of the last edit+    -- (storeDouble).+    SlotSearchCommitted+  | SlotSearchAge+  | -- | The value a controlled widget last returned to its caller.+    SlotSeen+  | -- | A colour picker's opening colour.+    SlotColorBase+  | -- | The stepper arrow a numeric field's press holds: 1 up, -1 down.+    SlotNumericHeld+  | -- | When a numeric field's held stepper arrow next repeats, in monotonic+    -- seconds.+    SlotNumericRepeat+  | -- | When a tooltip opens, in monotonic microseconds ('storeQuiet', keyed+    -- by tooltip id); absent while its target is not hovered. Key 0 holds+    -- when any tooltip was last open, for the grace period.+    SlotTooltipShow+  deriving (Enum)++-- | Tag for a built-in slot: the constructor index mixed with a salt, so tags+-- are well spread.+{-# INLINE slotTag #-}+slotTag :: Slot -> Word64+slotTag s = mix64 0x534C4F5454414753 (fromIntegral (fromEnum s))++-- | Encode 'False' as 0 and 'True' as 1.+boolInt :: Bool -> Int+boolInt b = if b then 1 else 0++-- | Decode zero as 'False' and any nonzero integer as 'True'.+intBool :: Int -> Bool+intBool n = n /= 0++-- | Whether any select owns the single open-dropdown slot.+{-# INLINE anySelectOpen #-}+anySelectOpen :: WidgetStore -> Bool+anySelectOpen st = storeOpenSelect st /= 0++-- | Whether this nonzero widget key owns the open-dropdown slot.+{-# INLINE isSelectOpen #-}+isSelectOpen :: WidgetStore -> Int -> Bool+isSelectOpen st k = k /= 0 && storeOpenSelect st == k++-- | Open a select, replacing the current owner, or close it if it owns the slot.+{-# INLINE setSelectOpen #-}+setSelectOpen :: WidgetStore -> Int -> Bool -> WidgetStore+setSelectOpen st k True = st {storeOpenSelect = k}+setSelectOpen st k False+  | isSelectOpen st k = closeSelects st+  | otherwise = st++-- | Clear the open-dropdown owner.+{-# INLINE closeSelects #-}+closeSelects :: WidgetStore -> WidgetStore+closeSelects st = st {storeOpenSelect = 0}
+ lib/NanoUI/Internal/Store/Slots.hs view
@@ -0,0 +1,268 @@+-- | The built-in widget state: for each value, the 'Slot' it is keyed by,+-- the 'NanoUI.Internal.Store.Field' map that holds it, and how it is stored+-- there, as one 'SlotSpec'. A widget reads and writes a value through its+-- spec ('findSpec', 'insertSpec', 'specWrite'), so the map and the encoding+-- are written down once.+--+-- One 'Slot' can key values in several maps: 'SlotDrag' keys the press a+-- drag started under ('slotDragPress', in 'fieldQuiet'), the item being+-- dragged ('slotDragItem', in 'fieldInt') and the last pointer position+-- ('slotDragPoint', in 'fieldPoint'). The maps are separate, so these do not+-- collide.+module NanoUI.Internal.Store.Slots+  ( -- * Text fields+    slotTextInputScroll+  , slotTextChanged+  , slotTextHistory+  , slotTextMode+  , slotSearchCommitted+  , slotSearchAge+  , slotSeen+    -- * Text areas+  , slotTextAreaScroll+  , slotTextAreaViewport+  , slotTextAreaAnchorRow+  , slotTextAreaAnchorCol+  , slotTextAreaBuffer+  , slotTextAreaText+  , slotTextAreaWidths+  , slotTextAreaLineH+  , slotTextAreaReveal+    -- * Drags and drops+  , slotDragPress+  , slotDragItem+  , slotDragPoint+  , slotDragStartPos+  , slotDrop+  , slotDropPos+    -- * Windows, menus and tooltips+  , slotWinSize+  , slotMenuOpen+  , slotMenuPos+  , slotTooltipShow+    -- * Scrolling+  , slotScrollCross+  , slotScrollLinkX+  , slotScrollLinkY+  , slotScrollStep+  , slotScrollAxes+  , slotScrollRange+  , slotScrollContent+  , slotScrollPending+    -- * Other widgets+  , slotColorBase+  , slotNumericHeld+  , slotNumericRepeat+  , setFlagSpec+  )+where++import Data.Text (Text)+import NanoUI.Internal.Store+import NanoUI.Internal.Store.Types (LineWidths, TextHistory)+import NanoUI.Internal.TextEditor.Types (EditorMode)+import NanoUI.Internal.Types (V2)+import NanoUI.Internal.Widgets.TextDocument (TextDocument)+import NanoUI.Widgets.TextBuffer (TextBuffer)++-- | An int slot read as a flag: set while it holds anything but 0, as+-- 'flagSlot' reads it, and written as 1 or 0.+{-# INLINE flagSpec #-}+flagSpec :: SlotSpec Int -> SlotSpec Bool+flagSpec = encodedSpec intBool boolInt++-- | Raise a flag, or remove its slot, as 'setFlagSlot' does.+{-# INLINE setFlagSpec #-}+setFlagSpec :: SlotSpec Bool -> Int -> Bool -> WidgetStore -> WidgetStore+setFlagSpec spec k on = if on then insertSpec spec k True else deleteSpec spec k++-- Text fields ----------------------------------------------------------------++-- | A single-line field's horizontal text scroll.+{-# INLINE slotTextInputScroll #-}+slotTextInputScroll :: SlotSpec Float+slotTextInputScroll = slotSpec SlotTextInputScroll fieldFloat++-- | Present (value 1) when a text field's or text area's text changed by a+-- path that carries no input, such as a context-menu paste+-- ('SlotTextAreaChanged').+{-# INLINE slotTextChanged #-}+slotTextChanged :: SlotSpec Int+slotTextChanged = slotSpec SlotTextAreaChanged fieldInt++-- | A text field's or text area's undo history.+{-# INLINE slotTextHistory #-}+slotTextHistory :: SlotSpec TextHistory+slotTextHistory = slotSpec SlotTextHistory fieldHistory++-- | How a text field edits, for commands sent between frames.+{-# INLINE slotTextMode #-}+slotTextMode :: SlotSpec EditorMode+slotTextMode = slotSpec SlotTextMode fieldEditorMode++-- | A search field's last committed query.+{-# INLINE slotSearchCommitted #-}+slotSearchCommitted :: SlotSpec Text+slotSearchCommitted = slotSpec SlotSearchCommitted fieldText++-- | The monotonic time of a search field's last edit, in seconds.+{-# INLINE slotSearchAge #-}+slotSearchAge :: SlotSpec Double+slotSearchAge = slotSpec SlotSearchAge fieldDouble++-- | The value a controlled widget last returned, in the map its value+-- lives in.+{-# INLINE slotSeen #-}+slotSeen :: Field a -> SlotSpec a+slotSeen = slotSpec SlotSeen++-- Text areas -----------------------------------------------------------------++{-# INLINE slotTextAreaScroll #-}+slotTextAreaScroll :: SlotSpec V2+slotTextAreaScroll = slotSpec SlotTextAreaScroll fieldPoint++{-# INLINE slotTextAreaViewport #-}+slotTextAreaViewport :: SlotSpec V2+slotTextAreaViewport = slotSpec SlotTextAreaViewport fieldPoint++{-# INLINE slotTextAreaAnchorRow #-}+slotTextAreaAnchorRow :: SlotSpec Int+slotTextAreaAnchorRow = slotSpec SlotTextAreaAnchorRow fieldInt++{-# INLINE slotTextAreaAnchorCol #-}+slotTextAreaAnchorCol :: SlotSpec Int+slotTextAreaAnchorCol = slotSpec SlotTextAreaAnchorCol fieldInt++{-# INLINE slotTextAreaBuffer #-}+slotTextAreaBuffer :: SlotSpec TextBuffer+slotTextAreaBuffer = slotSpec SlotTextAreaBuffer fieldBuffer++{-# INLINE slotTextAreaText #-}+slotTextAreaText :: SlotSpec (Text, TextDocument)+slotTextAreaText = slotSpec SlotTextAreaText fieldTextDocument++{-# INLINE slotTextAreaWidths #-}+slotTextAreaWidths :: SlotSpec LineWidths+slotTextAreaWidths = slotSpec SlotTextAreaWidths fieldLineWidths++{-# INLINE slotTextAreaLineH #-}+slotTextAreaLineH :: SlotSpec Float+slotTextAreaLineH = slotSpec SlotTextAreaLineH fieldFloat++-- | Present (value 1) while a text area's next paint should bring its caret+-- into view across. Bookkeeping, so it repaints nothing.+{-# INLINE slotTextAreaReveal #-}+slotTextAreaReveal :: SlotSpec Int+slotTextAreaReveal = slotSpec SlotTextAreaReveal fieldQuiet++-- Drags and drops ------------------------------------------------------------++-- | The press ('NanoUI.Internal.Context.leftPress') a drag started under, 0+-- for none. Bookkeeping, so it repaints nothing.+{-# INLINE slotDragPress #-}+slotDragPress :: SlotSpec Int+slotDragPress = slotSpec SlotDrag fieldQuiet++-- | The item a drag holds: a reordered item, or a table's resized column+-- (stored plus one, see the table).+{-# INLINE slotDragItem #-}+slotDragItem :: SlotSpec Int+slotDragItem = slotSpec SlotDrag fieldInt++-- | A drag's last pointer position.+{-# INLINE slotDragPoint #-}+slotDragPoint :: SlotSpec V2+slotDragPoint = slotSpec SlotDrag fieldPoint++-- | Where a reorder's press went down.+{-# INLINE slotDragStartPos #-}+slotDragStartPos :: SlotSpec V2+slotDragStartPos = slotSpec SlotDragW fieldPoint++-- | Whether a reorder has moved past its threshold, or a file drop is under+-- way.+{-# INLINE slotDrop #-}+slotDrop :: SlotSpec Bool+slotDrop = flagSpec (slotSpec SlotDrop fieldInt)++-- | Where a file drop last reported the pointer.+{-# INLINE slotDropPos #-}+slotDropPos :: SlotSpec V2+slotDropPos = slotSpec SlotDropPos fieldPoint++-- Windows, menus and tooltips ------------------------------------------------++{-# INLINE slotWinSize #-}+slotWinSize :: SlotSpec V2+slotWinSize = slotSpec SlotWinSize fieldPoint++{-# INLINE slotMenuOpen #-}+slotMenuOpen :: SlotSpec Bool+slotMenuOpen = flagSpec (slotSpec SlotMenuOpen fieldInt)++{-# INLINE slotMenuPos #-}+slotMenuPos :: SlotSpec V2+slotMenuPos = slotSpec SlotMenuPos fieldPoint++-- | When a tooltip opens, in monotonic microseconds, 0 while its target is+-- not hovered. Key 0 holds when any tooltip was last open. Bookkeeping, so+-- it repaints nothing.+{-# INLINE slotTooltipShow #-}+slotTooltipShow :: SlotSpec Int+slotTooltipShow = slotSpec SlotTooltipShow fieldQuiet++-- Scrolling ------------------------------------------------------------------++-- | A 2D scroller's offset on the axis its own key does not hold.+{-# INLINE slotScrollCross #-}+slotScrollCross :: SlotSpec Float+slotScrollCross = slotSpec SlotScrollCross fieldFloat++{-# INLINE slotScrollLinkX #-}+slotScrollLinkX :: SlotSpec Int+slotScrollLinkX = slotSpec SlotScrollLinkX fieldInt++{-# INLINE slotScrollLinkY #-}+slotScrollLinkY :: SlotSpec Int+slotScrollLinkY = slotSpec SlotScrollLinkY fieldInt++{-# INLINE slotScrollStep #-}+slotScrollStep :: SlotSpec Float+slotScrollStep = slotSpec SlotScrollStep fieldFloat++{-# INLINE slotScrollAxes #-}+slotScrollAxes :: SlotSpec Int+slotScrollAxes = slotSpec SlotScrollAxes fieldInt++{-# INLINE slotScrollRange #-}+slotScrollRange :: SlotSpec V2+slotScrollRange = slotSpec SlotScrollRange fieldPoint++-- | How far a scrolling tab strip's headers can scroll, from its last+-- layout.+{-# INLINE slotScrollContent #-}+slotScrollContent :: SlotSpec Float+slotScrollContent = slotSpec SlotScrollContent fieldFloat++-- | An offset in window axes set before the scroller's first layout.+{-# INLINE slotScrollPending #-}+slotScrollPending :: SlotSpec V2+slotScrollPending = slotSpec SlotScrollPending fieldPoint++-- Other widgets --------------------------------------------------------------++-- | A colour picker's opening colour, packed.+{-# INLINE slotColorBase #-}+slotColorBase :: SlotSpec Int+slotColorBase = slotSpec SlotColorBase fieldInt++-- | The stepper arrow a numeric field's press holds: 1 up, -1 down.+{-# INLINE slotNumericHeld #-}+slotNumericHeld :: SlotSpec Int+slotNumericHeld = slotSpec SlotNumericHeld fieldInt++-- | When a numeric field's held arrow next repeats, in monotonic seconds.+{-# INLINE slotNumericRepeat #-}+slotNumericRepeat :: SlotSpec Double+slotNumericRepeat = slotSpec SlotNumericRepeat fieldDouble
+ lib/NanoUI/Internal/Store/Types.hs view
@@ -0,0 +1,116 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Concrete compound values retained by the widget store. These types depend+-- only on pure models, so the store does not depend on widget implementations.+module NanoUI.Internal.Store.Types+  ( ComboState (..)+  , sameComboVisual+  , TableState (..)+  , GridState (..)+  , Gesture (..)+  , LineWidths (..)+  , TextHistory (..)+  ) where++import Data.IntSet (IntSet)+import Data.Sequence (Seq)+import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Equality (eqByPtr, ptrEq)+import NanoUI.Internal.GridNode (GridNode)+import NanoUI.Internal.TextEditor.Types (EditHistory)+import NanoUI.Internal.Types (V2)++-- | A combo's state between frames.+data ComboState = ComboState+  { csHighlight :: !Int+  -- ^ Highlighted row of the filtered list; -1 for none.+  , csWindow :: !Int+  -- ^ First visible row.+  , csScrollX :: !Float+  -- ^ How far the rows are scrolled left, in pixels, when the widest+  -- overflows the dropdown.+  , csContentW :: !Float+  -- ^ Widest matching row, measured while focused.+  , csDrag :: !Int+  -- ^ Scrollbar thumb drag: 0 none, 1 vertical, 2 horizontal.+  , csDragOff :: !Float+  -- ^ Pointer offset into the dragged thumb.+  , csWheelRem :: !Float+  -- ^ Rows the wheel moved short of a whole row, carried to the next+  -- frame, so a trackpad's small steps add up.+  , csCommitted :: !Text+  -- ^ Last committed value.+  , csLive :: !Text+  -- ^ Field text the combo last produced.+  , csFocused :: !Bool+  -- ^ The field held focus; the frame that finds it lost commits.+  , csNavPointer :: !(Maybe V2)+  -- ^ Pointer position when Up/Down last moved the highlight, cleared once+  -- the pointer moves or the wheel scrolls. Suppresses hover-highlighting+  -- while the pointer is stationary during keyboard navigation.+  }+  deriving (Eq, Show)++-- | Whether two combo states show the same dropdown and field state. Ignores+-- 'csWheelRem' and 'csNavPointer', which are quiet bookkeeping.+sameComboVisual :: ComboState -> ComboState -> Bool+sameComboVisual a b =+  ptrEq a b+    || ( csHighlight a == csHighlight b+           && csWindow a == csWindow b+           && csScrollX a == csScrollX b+           && csContentW a == csContentW b+           && csDrag a == csDrag b+           && csDragOff a == csDragOff b+           && eqByPtr (csCommitted a) (csCommitted b)+           && eqByPtr (csLive a) (csLive b)+           && csFocused a == csFocused b+       )++-- | A table's state between frames, persisted under the table's key.+data TableState = TableState+  { tsOrder :: ![Int]+  -- ^ Every source column in display order, hidden ones included.+  , tsWidths :: ![Float]+  -- ^ The width each source column was dragged to, 0 for none.+  , tsHidden :: !IntSet+  , tsResizeCol :: !Int+  -- ^ The column a header-edge drag resizes, or -1.+  , tsResizeX :: !Float+  -- ^ The pointer's x when that resize started.+  , tsResizeW :: !Float+  -- ^ The column's width when that resize started.+  }+  deriving (Eq)++-- | A grid's state between frames, under its widget id.+data GridState = GridState+  { gsTree :: !(Maybe GridNode)+  -- ^ Nothing is an empty workspace, including after the last pane closes.+  , gsSeed :: !Word64+  -- ^ Monotonic split/pane id, including across closure of the last pane.+  , gsFocus :: !Word64+  , gsMax :: !Word64+  , gsSpan :: !(Maybe (Float, Float))+  -- ^ Last fitted size, used to reflow pinned panes.+  , gsGesture :: !Gesture+  }+  deriving (Eq, Show)++-- | A press's gesture, retained until release.+data Gesture+  = NoGesture+  | -- | Split id, original ratio, and original pointer coordinate.+    Resize !Word64 !Float !Float+  | -- | Pane id, press position, crossed-threshold flag, and title.+    Drag !Word64 !V2 !Bool !Text+  deriving (Eq, Show)++-- | Font ('NanoUI.Internal.WidgetText.textNodeFontKey') and metric+-- generation, measured widths, widest line and width, and content height.+-- Incremental updates remeasure only edited lines.+data LineWidths = LineWidths !Int !Int !(Seq Float) !Int !Float !Float++-- | A history slot changes kind when a widget id changes editor kind.+data TextHistory = FieldHistory !Text !EditHistory | AreaHistory !EditHistory
+ lib/NanoUI/Internal/Style.hs view
@@ -0,0 +1,14 @@+-- | Layout options, text styling, and theme palettes. Re-export facade over+-- "NanoUI.Internal.Style.Layout", "NanoUI.Internal.Style.Theme", and+-- "NanoUI.Internal.Style.Presets".+module NanoUI.Internal.Style+  ( module NanoUI.Internal.Style.Layout+  , module NanoUI.Internal.Style.Theme+  , module NanoUI.Internal.Style.Presets+  , fadeAlpha+  ) where++import NanoUI.Internal.Style.Layout+import NanoUI.Internal.Style.Presets+import NanoUI.Internal.Style.Theme+import NanoUI.Internal.Types (fadeAlpha)
+ lib/NanoUI/Internal/Style/Layout.hs view
@@ -0,0 +1,1042 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE StrictData #-}++-- | Layout options, flow modes, alignment, typography attributes, and layout+-- modifiers. Modifiers compose with @(.)@, with the leftmost modifier winning+-- when both set the same field.+module NanoUI.Internal.Style.Layout+  ( Sizing (..)+  , Direction (..)+  , direction+  , Flow (..)+  , AlignX (..)+  , AlignY (..)+  , ItemsAlign (ItemsStart, ItemsCenter, ItemsEnd, ItemsBaseline, ItemsStretch)+  , itemsAlign+  , itemsStart+  , itemsCenter+  , itemsEnd+  , itemsBaseline+  , itemsStretch+  , Justify (JustifyStart, JustifyCenter, JustifyEnd, JustifyBetween)+  , justify+  , justifyStart+  , justifyCenter+  , justifyEnd+  , justifyBetween+  , alignXFraction+  , alignYFraction+  , Padding (..)+  , Layout (..)+  , defaultLayout+  , inheritFont+  , Tone (..)+  , windowPad+  , windowMargin+  , padAll+  , padXY+  , padTop+  , padBottom+  , padLeft+  , padRight+  , padLRTB+  , gap+  , fitW+  , fitH+  , fillW+  , fillH+  , growW+  , growH+  , grow+  , minW+  , maxW+  , fixedW+  , minH+  , hasExplicitMin+  , maxH+  , fixedH+  , fixedWH+  , alignMiddle+  , alignEnd+  , tight+  , percent+  , percentH+  , gridMinColW+  , fixedAspectW+  , fixedAspectH+  , aspect+  , gridCols+  , FontVariant (..)+  , FontWeight (..)+  , FontStyle (..)+  , TextDecoration (..)+  , LayoutModifier+  , fontRegular+  , fontHeading+  , fontMuted+  , fontMono+  , fontDanger+  , fontTone+  , fontSize+  , fontSizeScale+  , resolveFontSize+  , fontColor+  , fontWeight+  , fontBold+  , fontLight+  , fontMedium+  , fontSemiBold+  , fontExtraBold+  , fontBlack+  , fontStyle+  , fontItalic+  , fontOblique+  , textDecoration+  , fontUnderline+  , addUnderline+  , fontStrike+  , fontTabular+  , fontProportional+  , singleLine+  , alignStart+  , alignCenter+  , alignTop+  , alignBottom+  , alignBaseline+  , wrap+  , layered+  , lineGap+  , lineAlign+  , LineAlign (LinesStart, LinesCenter, LinesEnd)+  , lineAlignFraction+  , pinAt+  , PointerMode (PointerAuto, PointerBlock, PointerPass)+  , pointer+  , TextBreak (BreakWords, BreakAnywhere)+  , textBreak+  , breakAnywhere+  , TextEllipsis (EllipsisEnd, EllipsisMiddle, EllipsisStart)+  , textEllipsis+  , ellipsisEnd+  , ellipsisMiddle+  , ellipsisStart+  ) where++import Data.Bits ((.|.))+import Data.Proxy (Proxy (..))+import Data.Word (Word8)+import GHC.Enum (boundedEnumFrom, boundedEnumFromThen, predError, succError, toEnumError)+import GHC.TypeLits (KnownNat, Nat, natVal)+import NanoUI.Internal.Equality (ptrEq)+import NanoUI.Internal.Types (Color (..), V2 (..), noLimit)++-- | Size along one axis. Fixed sizes use logical pixels; grow/shrink values+-- are relative weights, and percentages use 100 for the full available size.+data Sizing+  = Fixed Float+  | Fit+  | Grow Float+  | Shrink Float+  | Percent Float+  deriving (Eq, Show)++-- | Main axis for laying out a container's children: left to right, or top+-- to bottom. 'Flow' decides whether they stay in one line, wrap, or layer.+data Direction = Row | Column+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | How a container places its children ('layoutFlow'). Scroll containers+-- and grids ignore it; put a wrapping or layered column inside them instead.+data Flow+  = -- | A single row or column along the 'Direction'. The default.+    Line+  | -- | Starts a new line where the next child would overflow the main axis+    -- ('wrap').+    Wrap+  | -- | Every child covers the content box, placed by its own alignment and+    -- drawn over earlier siblings ('layered'). 'Direction' is ignored.+    Layered+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Horizontal alignment: left, center, or right.+data AlignX = AlignStart | AlignCenter | AlignEnd+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | 'AlignBaseline' lines a row's text children up on their first baseline, and+-- sits any other child on it by its bottom edge. Outside a row it is+-- 'AlignTop'.+data AlignY = AlignTop | AlignMiddle | AlignBottom | AlignBaseline+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Where 'AlignX' puts content across the room left over: 0 at the left, 0.5+-- centered, 1 at the right.+{-# INLINE alignXFraction #-}+alignXFraction :: AlignX -> Float+alignXFraction AlignStart = 0+alignXFraction AlignCenter = 0.5+alignXFraction AlignEnd = 1++-- | Where 'AlignY' puts content down the room left over: 0 at the top, 0.5+-- centered, 1 at the bottom. 'AlignBaseline' counts as 'AlignTop': only a row+-- has a baseline to share, and it places those children itself.+{-# INLINE alignYFraction #-}+alignYFraction :: AlignY -> Float+alignYFraction AlignMiddle = 0.5+alignYFraction AlignBottom = 1+alignYFraction _ = 0++-- | Insets in logical pixels, ordered left, right, top, bottom.+data Padding = Padding+  { padL :: {-# UNPACK #-} !Float+  , padR :: {-# UNPACK #-} !Float+  , padT :: {-# UNPACK #-} !Float+  , padB :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | Floating window padding.+windowPad :: Padding+windowPad = Padding 10 10 0 10++-- | Screen inset in logical pixels for floating window/modal size and placement.+windowMargin :: Float+windowMargin = 14++-- | Semantic font choice. The backend selects a face.+data FontVariant+  = FontRegular+  | FontMono+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | A semantic theme color ('NanoUI.toneColor') for text+-- ('fontTone') and buttons.+data Tone+  = Accent+  | Muted+  | Success+  | Warning+  | Danger+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Requested font weight. Available faces and synthetic weights depend on the backend.+data FontWeight+  = WeightNormal+  | WeightBold+  | WeightLight+  | WeightMedium+  | WeightSemiBold+  | WeightExtraBold+  | WeightBlack+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Upright, italic, or oblique text. Backend support determines the rendered face.+data FontStyle+  = FontStyleNormal+  | FontStyleItalic+  | FontStyleOblique+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Underline and strikethrough flags for text painting.+data TextDecoration+  = DecorationNone+  | DecorationUnderline+  | DecorationStrikethrough+  | DecorationUnderlineStrike+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | A layout update. Compose with @(.)@; the leftmost update wins when two+-- modifiers set the same field.+type LayoutModifier = Layout -> Layout++-- | Layout and text options for a node. Lengths use logical pixels. Font size+-- 0 selects the backend default, positive values set an explicit logical size,+-- and negative values encode a scale factor relative to the backend default+-- ('fontSizeScale'); 'Nothing' for font color uses the theme.+data Layout = Layout+  { layoutDirection :: !Direction+  , layoutWidth :: !Sizing+  , layoutHeight :: !Sizing+  , layoutPadding :: {-# UNPACK #-} !Padding+  , layoutGap :: {-# UNPACK #-} !Float+  , layoutPointer :: {-# UNPACK #-} !PointerMode+  -- ^ Placed next to 'layoutGap' so both share one word.+  , layoutLineAlign :: {-# UNPACK #-} !LineAlign+  -- ^ Also in the 'layoutGap' word.+  , layoutTextBreak :: {-# UNPACK #-} !TextBreak+  -- ^ Where rich text may wrap ('textBreak'). Also in the 'layoutGap' word.+  , layoutEllipsis :: {-# UNPACK #-} !TextEllipsis+  -- ^ Where truncated single-line text places its ellipsis. Completes the 'layoutGap' word.+  , layoutAlignX :: !AlignX+  , layoutAlignY :: !AlignY+  , layoutItemsAlign :: {-# UNPACK #-} !ItemsAlign+  -- ^ Cross-axis alignment applied to children without an explicit alignment ('itemsAlign').+  , layoutJustify :: {-# UNPACK #-} !Justify+  -- ^ Main-axis distribution of leftover space on single-line containers ('justify').+  , layoutAlignExplicit :: {-# UNPACK #-} !Word8+  -- ^ Bit 0: 'layoutAlignX' set explicitly; bit 1: 'layoutAlignY' set explicitly.+  , layoutMinW :: {-# UNPACK #-} !Float+  , layoutMinH :: {-# UNPACK #-} !Float+  , layoutMaxW :: {-# UNPACK #-} !Float+  , layoutMaxH :: {-# UNPACK #-} !Float+  , layoutFontVariant :: !FontVariant+  , layoutGridCols :: {-# UNPACK #-} !Int+  , layoutGridMinColW :: {-# UNPACK #-} !Float+  , layoutFontSize :: {-# UNPACK #-} !Float+  , layoutLineGap :: {-# UNPACK #-} !Float+  , layoutAspect :: {-# UNPACK #-} !Float+  , layoutFontColor :: !(Maybe Color)+  , layoutFontTone :: !(Maybe Tone)+  -- ^ Text color tone, overridden by 'layoutFontColor' ('fontTone').+  , layoutFontWeight :: !FontWeight+  , layoutFontStyle :: !FontStyle+  , layoutTextDecoration :: !TextDecoration+  , layoutFontTabular :: !Bool+  -- ^ Uniform-width ASCII digits ('fontTabular').+  , layoutSingleLine :: !Bool+  -- ^ Keep text on one line and truncate instead of wrapping ('singleLine').+  , layoutFlow :: !Flow+  , layoutPin :: !(Maybe V2)+  }+  deriving (Eq, Show)++-- | Fit-sized column with 3-pixel padding, an 8-pixel gap, top-left alignment,+-- and the regular font.+defaultLayout :: Layout+defaultLayout =+  Layout+    { layoutDirection = Column+    , layoutWidth = Fit+    , layoutHeight = Fit+    , layoutPadding = Padding 3 3 3 3+    , layoutGap = 8+    , layoutAlignX = AlignStart+    , layoutAlignY = AlignTop+    , layoutItemsAlign = ItemsStart+    , layoutJustify = JustifyStart+    , layoutAlignExplicit = 0+    , layoutMinW = 0+    , layoutMinH = 0+    , layoutMaxW = noLimit+    , layoutMaxH = noLimit+    , layoutFontVariant = FontRegular+    , layoutGridCols = 0+    , layoutGridMinColW = 0+    , layoutFontSize = 0+    , layoutFontColor = Nothing+    , layoutFontTone = Nothing+    , layoutFontWeight = WeightNormal+    , layoutFontStyle = FontStyleNormal+    , layoutTextDecoration = DecorationNone+    , layoutFontTabular = False+    , layoutSingleLine = False+    , layoutFlow = Line+    , layoutLineGap = -1+    , layoutLineAlign = LinesStart+    , layoutTextBreak = BreakWords+    , layoutEllipsis = EllipsisEnd+    , layoutAspect = 0+    , layoutPin = Nothing+    , layoutPointer = PointerAuto+    }++-- | Copy typography attributes from @src@ onto @dst@, keeping @dst@'s box+-- geometry (sizing, padding, gap, alignment, flow). Keeps the common+-- pointer-equal fast path tiny for inlining and avoids copying @dst@ when+-- typography already matches.+{-# INLINE inheritFont #-}+inheritFont :: Layout -> Layout -> Layout+inheritFont src dst+  | ptrEq src dst = dst+  | otherwise = inheritFontSlow src dst++{-# NOINLINE inheritFontSlow #-}+inheritFontSlow :: Layout -> Layout -> Layout+inheritFontSlow src dst+  | layoutFontVariant src == layoutFontVariant dst+      && layoutFontSize src == layoutFontSize dst+      && layoutFontColor src == layoutFontColor dst+      && layoutFontTone src == layoutFontTone dst+      && layoutFontWeight src == layoutFontWeight dst+      && layoutFontStyle src == layoutFontStyle dst+      && layoutTextDecoration src == layoutTextDecoration dst+      && layoutFontTabular src == layoutFontTabular dst+      && layoutEllipsis src == layoutEllipsis dst+      && layoutSingleLine src == layoutSingleLine dst =+      dst+  | otherwise =+      dst+        { layoutFontVariant = layoutFontVariant src+        , layoutFontSize = layoutFontSize src+        , layoutFontColor = layoutFontColor src+        , layoutFontTone = layoutFontTone src+        , layoutFontWeight = layoutFontWeight src+        , layoutFontStyle = layoutFontStyle src+        , layoutTextDecoration = layoutTextDecoration src+        , layoutFontTabular = layoutFontTabular src+        , layoutEllipsis = layoutEllipsis src+        , layoutSingleLine = layoutSingleLine src+        }++-- | Set all four padding edges in logical pixels.+{-# INLINE padAll #-}+padAll :: Float -> Layout -> Layout+padAll n l = l {layoutPadding = Padding n n n n}++-- | Set horizontal and vertical padding, in that order, in logical pixels.+{-# INLINE padXY #-}+padXY :: Float -> Float -> Layout -> Layout+padXY x y l = l {layoutPadding = Padding x x y y}++-- | Set the top padding in logical pixels, keeping the other three edges.+{-# INLINE padTop #-}+padTop :: Float -> Layout -> Layout+padTop n l = l {layoutPadding = (layoutPadding l) {padT = n}}++-- | Set the bottom padding in logical pixels, keeping the other three edges.+{-# INLINE padBottom #-}+padBottom :: Float -> Layout -> Layout+padBottom n l = l {layoutPadding = (layoutPadding l) {padB = n}}++-- | Set the left padding in logical pixels, keeping the other three edges.+{-# INLINE padLeft #-}+padLeft :: Float -> Layout -> Layout+padLeft n l = l {layoutPadding = (layoutPadding l) {padL = n}}++-- | Set the right padding in logical pixels, keeping the other three edges.+{-# INLINE padRight #-}+padRight :: Float -> Layout -> Layout+padRight n l = l {layoutPadding = (layoutPadding l) {padR = n}}++-- | Set left, right, top and bottom padding, in that order, in logical pixels.+{-# INLINE padLRTB #-}+padLRTB :: Float -> Float -> Float -> Float -> Layout -> Layout+padLRTB left right top bottom l = l {layoutPadding = Padding left right top bottom}++-- | Set the main layout direction ('Row' or 'Column'). Useful with containers+-- whose direction is configurable, such as 'NanoUI.buttonGroupWith' or+-- 'NanoUI.scrollWith'.+{-# INLINE direction #-}+direction :: Direction -> Layout -> Layout+direction d l = l {layoutDirection = d}++-- | Set the space between children in logical pixels.+{-# INLINE gap #-}+gap :: Float -> Layout -> Layout+gap n l = l {layoutGap = n}++-- | Size width to content ('Fit'), overriding an inherited 'fillW' or 'fixedW'.+{-# INLINE fitW #-}+fitW :: Layout -> Layout+fitW l = l {layoutWidth = Fit}++-- | Size height to content ('Fit'), overriding an inherited 'fillH' or 'fixedH'.+{-# INLINE fitH #-}+fitH :: Layout -> Layout+fitH l = l {layoutHeight = Fit}++-- | Share available horizontal space with grow weight 1.+{-# INLINE fillW #-}+fillW :: Layout -> Layout+fillW l = l {layoutWidth = Grow 1}++-- | Share available vertical space with grow weight 1.+{-# INLINE fillH #-}+fillH :: Layout -> Layout+fillH l = l {layoutHeight = Grow 1}++-- | Share available horizontal space with an explicit grow weight.+{-# INLINE growW #-}+growW :: Float -> Layout -> Layout+growW w l = l {layoutWidth = Grow (max 0 w)}++-- | Share available vertical space with an explicit grow weight.+{-# INLINE growH #-}+growH :: Float -> Layout -> Layout+growH h l = l {layoutHeight = Grow (max 0 h)}++-- | Apply 'fillW' and 'fillH'.+{-# INLINE grow #-}+grow :: Layout -> Layout+grow = fillW . fillH++-- | Set the minimum width in logical pixels without changing the sizing mode.+{-# INLINE minW #-}+minW :: Float -> Layout -> Layout+minW n l = l {layoutMinW = explicitMin n}++-- | Set the maximum width in logical pixels without changing the sizing mode.+{-# INLINE maxW #-}+maxW :: Float -> Layout -> Layout+maxW n l = l {layoutMaxW = n}++-- | Fix width and both width limits to the given logical-pixel value.+{-# INLINE fixedW #-}+fixedW :: Float -> Layout -> Layout+fixedW n l = l {layoutWidth = Fixed n, layoutMinW = n, layoutMaxW = n}++-- | Set the minimum height in logical pixels without changing the sizing mode.+{-# INLINE minH #-}+minH :: Float -> Layout -> Layout+minH n l = l {layoutMinH = explicitMin n}++explicitMin :: Float -> Float+explicitMin n = if n == 0 then -0.0 else n++-- | Whether a minimum was set on purpose ('explicitMin').+{-# INLINE hasExplicitMin #-}+hasExplicitMin :: Float -> Bool+hasExplicitMin m = m > 0 || isNegativeZero m++-- | Set the maximum height in logical pixels without changing the sizing mode.+{-# INLINE maxH #-}+maxH :: Float -> Layout -> Layout+maxH n l = l {layoutMaxH = n}++-- | Request a fixed height in logical pixels, retaining existing height limits.+{-# INLINE fixedH #-}+fixedH :: Float -> Layout -> Layout+fixedH n l = l {layoutHeight = Fixed n}++-- | Fix width and height in logical pixels: @fixedW w . fixedH h@.+{-# INLINE fixedWH #-}+fixedWH :: Float -> Float -> Layout -> Layout+fixedWH w h = fixedW w . fixedH h++-- | Center vertically in the available space.+{-# INLINE alignMiddle #-}+alignMiddle :: Layout -> Layout+alignMiddle l = l {layoutAlignY = AlignMiddle, layoutAlignExplicit = layoutAlignExplicit l .|. 2}++-- | Align to the right edge of the available space.+{-# INLINE alignEnd #-}+alignEnd :: Layout -> Layout+alignEnd l = l {layoutAlignX = AlignEnd, layoutAlignExplicit = layoutAlignExplicit l .|. 1}++-- | Remove all padding, retaining the gap between children.+{-# INLINE tight #-}+tight :: Layout -> Layout+tight l = l {layoutPadding = Padding 0 0 0 0}++-- | Set width as a percentage of the parent's available width: 100 means all.+{-# INLINE percent #-}+percent :: Float -> Layout -> Layout+percent p l = l {layoutWidth = Percent p}++-- | Set height as a percentage of the parent's available height: 100 means all.+{-# INLINE percentH #-}+percentH :: Float -> Layout -> Layout+percentH p l = l {layoutHeight = Percent p}++-- | Set the minimum column width for an adaptive grid, in logical pixels.+{-# INLINE gridMinColW #-}+gridMinColW :: Float -> Layout -> Layout+gridMinColW w l = l {layoutGridMinColW = max 0 w}++-- | Fixed width and width/height ratio; the height is derived. A ratio that+-- is not positive and finite gives a square, as 'aspect' ignores one.+fixedAspectW :: Float -> Float -> Layout -> Layout+fixedAspectW w ratio = fixedWH w (w / validRatio ratio)++-- | Fixed height and width/height ratio; the width is derived. A ratio that+-- is not positive and finite gives a square.+fixedAspectH :: Float -> Float -> Layout -> Layout+fixedAspectH h ratio = fixedWH (h * validRatio ratio) h++-- | The ratio when it is positive and finite, otherwise 1.+validRatio :: Float -> Float+validRatio r = if r > 0 && not (isInfinite r) then r else 1++-- | Keep width / height at @ratio@.+aspect :: Float -> Layout -> Layout+aspect ratio l = l {layoutAspect = if ratio > 0 && not (isInfinite ratio) then ratio else 0}++-- | Set the grid column count, clamping negative counts to zero.+{-# INLINE gridCols #-}+gridCols :: Int -> Layout -> Layout+gridCols n l = l {layoutGridCols = max 0 n}++-- | Select the regular font variant.+{-# INLINE fontRegular #-}+fontRegular :: Layout -> Layout+fontRegular l = l {layoutFontVariant = FontRegular}++-- | Text set with medium weight for headings.+{-# INLINE fontHeading #-}+fontHeading :: Layout -> Layout+fontHeading = fontMedium++-- | Text in the theme's muted color: 'fontTone' 'Muted'.+{-# INLINE fontMuted #-}+fontMuted :: Layout -> Layout+fontMuted = fontTone Muted++-- | Select the backend's monospace font variant.+{-# INLINE fontMono #-}+fontMono :: Layout -> Layout+fontMono l = l {layoutFontVariant = FontMono}++-- | Text in the theme's danger color: 'fontTone' 'Danger'.+{-# INLINE fontDanger #-}+fontDanger :: Layout -> Layout+fontDanger = fontTone Danger++-- | Color text with a tone. 'fontColor' takes precedence.+{-# INLINE fontTone #-}+fontTone :: Tone -> Layout -> Layout+fontTone t l = l {layoutFontTone = Just t}++-- | Set logical font size. Non-positive values select the backend default.+{-# INLINE fontSize #-}+fontSize :: Float -> Layout -> Layout+fontSize sz l = l {layoutFontSize = max 0 sz}++-- | Scale the node's font size by @s@. When an explicit size is already set,+-- multiplies that size; otherwise stores a scale factor resolved against the+-- active base font size ('NanoUI.uiFontSize'). Non-positive factors reset to+-- the default size.+fontSizeScale :: Float -> Layout -> Layout+fontSizeScale s l+  | s <= 0 = l {layoutFontSize = 0}+  | cur /= 0 = l {layoutFontSize = cur * s}+  | otherwise = l {layoutFontSize = negate s}+  where+    cur = layoutFontSize l++-- | Resolve a stored 'layoutFontSize' against the host's base logical font+-- size @baseSize@. Positive values are explicit sizes, negative values encode+-- a scale factor ('fontSizeScale'), and zero requests the default (returned as+-- @0@). A scale factor of 1 also returns @0@ so callers stay on the default+-- font fast path.+{-# INLINE resolveFontSize #-}+resolveFontSize :: Float -> Float -> Float+resolveFontSize baseSize stored+  | stored > 0 = stored+  | stored < 0 =+      let !s = negate stored+       in if abs (s - 1) <= 1.0e-5 then 0 else max 1 (baseSize * s)+  | otherwise = 0++-- | Override the theme's text color for this node.+{-# INLINE fontColor #-}+fontColor :: Color -> Layout -> Layout+fontColor col l = l {layoutFontColor = Just col}++-- | Set the requested font weight independently of its semantic variant.+{-# INLINE fontWeight #-}+fontWeight :: FontWeight -> Layout -> Layout+fontWeight w l = l {layoutFontWeight = w}++-- | Request 'WeightBold'.+{-# INLINE fontBold #-}+fontBold :: Layout -> Layout+fontBold = fontWeight WeightBold++-- | Request 'WeightLight'.+{-# INLINE fontLight #-}+fontLight :: Layout -> Layout+fontLight = fontWeight WeightLight++-- | Request 'WeightMedium'.+{-# INLINE fontMedium #-}+fontMedium :: Layout -> Layout+fontMedium = fontWeight WeightMedium++-- | Request 'WeightSemiBold'.+{-# INLINE fontSemiBold #-}+fontSemiBold :: Layout -> Layout+fontSemiBold = fontWeight WeightSemiBold++-- | Request 'WeightExtraBold'.+{-# INLINE fontExtraBold #-}+fontExtraBold :: Layout -> Layout+fontExtraBold = fontWeight WeightExtraBold++-- | Request 'WeightBlack', the heaviest weight.+{-# INLINE fontBlack #-}+fontBlack :: Layout -> Layout+fontBlack = fontWeight WeightBlack++-- | Set upright, italic, or oblique text without changing its weight.+{-# INLINE fontStyle #-}+fontStyle :: FontStyle -> Layout -> Layout+fontStyle s l = l {layoutFontStyle = s}++-- | Request 'FontStyleItalic'.+{-# INLINE fontItalic #-}+fontItalic :: Layout -> Layout+fontItalic = fontStyle FontStyleItalic++-- | Request 'FontStyleOblique'.+{-# INLINE fontOblique #-}+fontOblique :: Layout -> Layout+fontOblique = fontStyle FontStyleOblique++-- | Replace the node's underline and strikethrough settings.+{-# INLINE textDecoration #-}+textDecoration :: TextDecoration -> Layout -> Layout+textDecoration d l = l {layoutTextDecoration = d}++-- | Add an underline while preserving any strikethrough.+{-# INLINE fontUnderline #-}+fontUnderline :: Layout -> Layout+fontUnderline l = l {layoutTextDecoration = addUnderline (layoutTextDecoration l)}++-- | The decoration with an underline added, keeping any strikethrough.+{-# INLINE addUnderline #-}+addUnderline :: TextDecoration -> TextDecoration+addUnderline d = toEnum (fromEnum d .|. 1)++-- | Add a strikethrough while preserving any underline.+{-# INLINE fontStrike #-}+fontStrike :: Layout -> Layout+fontStrike l =+  l {layoutTextDecoration = toEnum (fromEnum (layoutTextDecoration l) .|. 2)}++-- | Align to the left edge of the available space.+{-# INLINE alignStart #-}+alignStart :: Layout -> Layout+alignStart l = l {layoutAlignX = AlignStart, layoutAlignExplicit = layoutAlignExplicit l .|. 1}++-- | Center horizontally in the available space.+{-# INLINE alignCenter #-}+alignCenter :: Layout -> Layout+alignCenter l = l {layoutAlignX = AlignCenter, layoutAlignExplicit = layoutAlignExplicit l .|. 1}++-- | Align to the top edge of the available space.+{-# INLINE alignTop #-}+alignTop :: Layout -> Layout+alignTop l = l {layoutAlignY = AlignTop, layoutAlignExplicit = layoutAlignExplicit l .|. 2}++-- | Align to the bottom edge of the available space.+{-# INLINE alignBottom #-}+alignBottom :: Layout -> Layout+alignBottom l = l {layoutAlignY = AlignBottom, layoutAlignExplicit = layoutAlignExplicit l .|. 2}++-- | Sit on the row's shared text baseline.+{-# INLINE alignBaseline #-}+alignBaseline :: Layout -> Layout+alignBaseline l = l {layoutAlignY = AlignBaseline, layoutAlignExplicit = layoutAlignExplicit l .|. 2}++-- | Cross-axis alignment a container applies to children that do not set their+-- own alignment along that axis ('itemsAlign').+newtype ItemsAlign = ItemsAlign Word8+  deriving newtype (Eq, Ord)+  deriving (Bounded, Enum) via BoundedByte 4++-- | Top of a row or grid row, left of a column. The default.+pattern ItemsStart :: ItemsAlign+pattern ItemsStart = ItemsAlign 0++-- | Centered across the container: vertically in a row or grid row,+-- horizontally in a column.+pattern ItemsCenter :: ItemsAlign+pattern ItemsCenter = ItemsAlign 1++-- | Bottom of a row or grid row, right of a column.+pattern ItemsEnd :: ItemsAlign+pattern ItemsEnd = ItemsAlign 2++-- | Shared text baseline across a row. Outside a row, behaves like+-- 'ItemsStart'.+pattern ItemsBaseline :: ItemsAlign+pattern ItemsBaseline = ItemsAlign 3++-- | Stretch fit-sized children across the container's cross axis (width in a+-- column, height in a row or grid row) unless a child sets its own cross-axis+-- alignment or explicit sizing.+pattern ItemsStretch :: ItemsAlign+pattern ItemsStretch = ItemsAlign 4++{-# COMPLETE ItemsStart, ItemsCenter, ItemsEnd, ItemsBaseline, ItemsStretch #-}++instance Show ItemsAlign where+  show ItemsStart = "ItemsStart"+  show ItemsCenter = "ItemsCenter"+  show ItemsEnd = "ItemsEnd"+  show ItemsBaseline = "ItemsBaseline"+  show ItemsStretch = "ItemsStretch"++-- | Set cross-axis alignment for direct children that leave their own+-- cross-axis alignment unset.+{-# INLINE itemsAlign #-}+itemsAlign :: ItemsAlign -> Layout -> Layout+itemsAlign a l = l {layoutItemsAlign = a}++-- | Align children to the start of the cross axis: top of a row, left of a column.+{-# INLINE itemsStart #-}+itemsStart :: Layout -> Layout+itemsStart = itemsAlign ItemsStart++-- | Center children across the container: vertically in a row or grid row,+-- horizontally in a column.+{-# INLINE itemsCenter #-}+itemsCenter :: Layout -> Layout+itemsCenter = itemsAlign ItemsCenter++-- | Align children to the end of the cross axis: bottom of a row or grid row,+-- right of a column.+{-# INLINE itemsEnd #-}+itemsEnd :: Layout -> Layout+itemsEnd = itemsAlign ItemsEnd++-- | Align row children on their shared text baseline. Outside a row, behaves+-- like 'itemsStart'.+{-# INLINE itemsBaseline #-}+itemsBaseline :: Layout -> Layout+itemsBaseline = itemsAlign ItemsBaseline++-- | Stretch fit-sized children across the container's cross axis unless a child+-- sets its own cross-axis alignment.+{-# INLINE itemsStretch #-}+itemsStretch :: Layout -> Layout+itemsStretch = itemsAlign ItemsStretch++-- | How a single-line row or column distributes leftover main-axis space when+-- no child grows to fill it ('justify').+newtype Justify = Justify Word8+  deriving newtype (Eq, Ord)+  deriving (Bounded, Enum) via BoundedByte 3++-- | Pack children at the start of the main axis. The default.+pattern JustifyStart :: Justify+pattern JustifyStart = Justify 0++-- | Center children along the main axis.+pattern JustifyCenter :: Justify+pattern JustifyCenter = Justify 1++-- | Pack children at the end of the main axis.+pattern JustifyEnd :: Justify+pattern JustifyEnd = Justify 2++-- | Distribute leftover space evenly between adjacent children, keeping the+-- first and last flush with the container's inner edges.+pattern JustifyBetween :: Justify+pattern JustifyBetween = Justify 3++{-# COMPLETE JustifyStart, JustifyCenter, JustifyEnd, JustifyBetween #-}++instance Show Justify where+  show JustifyStart = "JustifyStart"+  show JustifyCenter = "JustifyCenter"+  show JustifyEnd = "JustifyEnd"+  show JustifyBetween = "JustifyBetween"++-- | Set main-axis distribution of leftover space on a single-line container.+{-# INLINE justify #-}+justify :: Justify -> Layout -> Layout+justify j l = l {layoutJustify = j}++-- | Pack children at the start of the main axis.+{-# INLINE justifyStart #-}+justifyStart :: Layout -> Layout+justifyStart = justify JustifyStart++-- | Center children along the main axis.+{-# INLINE justifyCenter #-}+justifyCenter :: Layout -> Layout+justifyCenter = justify JustifyCenter++-- | Pack children at the end of the main axis.+{-# INLINE justifyEnd #-}+justifyEnd :: Layout -> Layout+justifyEnd = justify JustifyEnd++-- | Distribute leftover main-axis space evenly between children.+{-# INLINE justifyBetween #-}+justifyBetween :: Layout -> Layout+justifyBetween = justify JustifyBetween++-- | Start a new line when the next child would overflow the main axis ('Wrap').+{-# INLINE wrap #-}+wrap :: Layout -> Layout+wrap l = l {layoutFlow = Wrap}++-- | Stack children in the content box instead of a line ('Layered').+{-# INLINE layered #-}+layered :: Layout -> Layout+layered l = l {layoutFlow = Layered}++-- | Space between a wrapping container's lines, in logical pixels.+{-# INLINE lineGap #-}+lineGap :: Float -> Layout -> Layout+lineGap n l = l {layoutLineGap = max 0 n}++-- | Position of a wrapping container's short lines along the main axis.+{-# INLINE lineAlign #-}+lineAlign :: LineAlign -> Layout -> Layout+lineAlign a l = l {layoutLineAlign = a}++-- | Shared 'Bounded' and 'Enum' implementation for 'Word8'-backed enum+-- newtypes with values @[0 .. n]@.+newtype BoundedByte (n :: Nat) = BoundedByte Word8+  deriving newtype (Eq, Ord)++instance KnownNat n => Bounded (BoundedByte n) where+  minBound = BoundedByte 0+  maxBound = BoundedByte (fromIntegral (natVal (Proxy @n)))++instance KnownNat n => Enum (BoundedByte n) where+  fromEnum (BoundedByte x) = fromIntegral x+  toEnum i+    | i >= 0 && i <= hi = BoundedByte (fromIntegral i)+    | otherwise = toEnumError "BoundedByte" i (0 :: Int, hi)+    where+      hi = fromIntegral (natVal (Proxy @n))+  succ a = if a >= maxBound then succError "BoundedByte" else toEnum (fromEnum a + 1)+  pred a = if a <= minBound then predError "BoundedByte" else toEnum (fromEnum a - 1)+  enumFrom = boundedEnumFrom+  enumFromThen = boundedEnumFromThen++-- | Line position for 'lineAlign': 'LinesStart', 'LinesCenter' or 'LinesEnd'.+newtype LineAlign = LineAlign Word8+  deriving newtype (Eq, Ord)+  deriving (Bounded, Enum) via BoundedByte 2++-- | Left of a row, top of a column.+pattern LinesStart :: LineAlign+pattern LinesStart = LineAlign 0++-- | Centered on the main axis.+pattern LinesCenter :: LineAlign+pattern LinesCenter = LineAlign 1++-- | Right of a row, bottom of a column.+pattern LinesEnd :: LineAlign+pattern LinesEnd = LineAlign 2++{-# COMPLETE LinesStart, LinesCenter, LinesEnd #-}++instance Show LineAlign where+  show LinesStart = "LinesStart"+  show LinesCenter = "LinesCenter"+  show LinesEnd = "LinesEnd"++-- | Fraction of a line's free space placed before it: 0, 0.5 or 1.+lineAlignFraction :: LineAlign -> Float+lineAlignFraction (LineAlign n) = min 1 (fromIntegral n / 2)++-- | Take the node out of its parent's flow and draw it over its siblings in+-- the parent's content box.+pinAt :: Float -> Float -> Layout -> Layout+pinAt x y l = l {layoutPin = Just (V2 x y)}++-- | Pointer handling where a node overlaps others, through layers or 'pinAt'.+newtype PointerMode = PointerMode Word8+  deriving newtype (Eq, Ord)+  deriving (Bounded, Enum) via BoundedByte 2++-- | Controls take the pointer from what they cover; passive containers pass it through.+pattern PointerAuto :: PointerMode+pattern PointerAuto = PointerMode 0++-- | The node's box blocks presses, wheel and hover from reaching anything beneath.+pattern PointerBlock :: PointerMode+pattern PointerBlock = PointerMode 1++-- | The node and its descendants ignore the pointer entirely.+pattern PointerPass :: PointerMode+pattern PointerPass = PointerMode 2++{-# COMPLETE PointerAuto, PointerBlock, PointerPass #-}++instance Show PointerMode where+  show PointerAuto = "PointerAuto"+  show PointerBlock = "PointerBlock"+  show PointerPass = "PointerPass"++-- | Set how the node handles the pointer where it overlaps others.+pointer :: PointerMode -> Layout -> Layout+pointer m l = l {layoutPointer = m}++-- | Where rich text may wrap a line: 'BreakWords' or 'BreakAnywhere'.+newtype TextBreak = TextBreak Word8+  deriving newtype (Eq, Ord)+  deriving (Bounded, Enum) via BoundedByte 1++-- | Wrap at spaces and newlines.+pattern BreakWords :: TextBreak+pattern BreakWords = TextBreak 0++-- | Wrap between any two characters.+pattern BreakAnywhere :: TextBreak+pattern BreakAnywhere = TextBreak 1++{-# COMPLETE BreakWords, BreakAnywhere #-}++instance Show TextBreak where+  show b = if b == BreakWords then "BreakWords" else "BreakAnywhere"++-- | Set where rich text may wrap its lines.+textBreak :: TextBreak -> Layout -> Layout+textBreak b l = l {layoutTextBreak = b}++-- | Wrap rich text between any two characters, as for code.+breakAnywhere :: Layout -> Layout+breakAnywhere = textBreak BreakAnywhere++-- | Render ASCII digits (@0@ to @9@) with uniform tabular advance widths so live+-- counters and aligned numeric columns never jitter horizontally, even in a+-- proportional UI font.+{-# INLINE fontTabular #-}+fontTabular :: Layout -> Layout+fontTabular l = l {layoutFontTabular = True}++-- | Use proportional digit advances, overriding an inherited 'fontTabular'.+{-# INLINE fontProportional #-}+fontProportional :: Layout -> Layout+fontProportional l = l {layoutFontTabular = False}++-- | Keep a text node on one line, truncating with an ellipsis when constrained+-- instead of wrapping in a column.+{-# INLINE singleLine #-}+singleLine :: Layout -> Layout+singleLine l = l {layoutSingleLine = True}++-- | Where single-line text places its ellipsis (@...@) when truncated to fit.+newtype TextEllipsis = TextEllipsis Word8+  deriving newtype (Eq, Ord)+  deriving (Bounded, Enum) via BoundedByte 2++-- | Truncate at the trailing end (@"ghc-internal:GHC..."@). The default.+pattern EllipsisEnd :: TextEllipsis+pattern EllipsisEnd = TextEllipsis 0++-- | Truncate in the middle (@"ghc-internal:...Natural.add"@), preserving both+-- package/path prefix and identifier/file suffix.+pattern EllipsisMiddle :: TextEllipsis+pattern EllipsisMiddle = TextEllipsis 1++-- | Truncate at the leading start (@"...Bignum.Natural.add"@).+pattern EllipsisStart :: TextEllipsis+pattern EllipsisStart = TextEllipsis 2++{-# COMPLETE EllipsisEnd, EllipsisMiddle, EllipsisStart #-}++instance Show TextEllipsis where+  show EllipsisEnd = "EllipsisEnd"+  show EllipsisMiddle = "EllipsisMiddle"+  show EllipsisStart = "EllipsisStart"++-- | Set where truncated single-line text places its ellipsis. Also enables+-- 'singleLine' so the ellipsis applies in columns as well as rows.+{-# INLINE textEllipsis #-}+textEllipsis :: TextEllipsis -> Layout -> Layout+textEllipsis e l = l {layoutEllipsis = e, layoutSingleLine = True}++-- | Truncate single-line text at the trailing end.+{-# INLINE ellipsisEnd #-}+ellipsisEnd :: Layout -> Layout+ellipsisEnd = textEllipsis EllipsisEnd++-- | Truncate single-line text in the middle, keeping prefix and suffix visible.+{-# INLINE ellipsisMiddle #-}+ellipsisMiddle :: Layout -> Layout+ellipsisMiddle = textEllipsis EllipsisMiddle++-- | Truncate single-line text at the leading start, keeping the suffix visible.+{-# INLINE ellipsisStart #-}+ellipsisStart :: Layout -> Layout+ellipsisStart = textEllipsis EllipsisStart
+ lib/NanoUI/Internal/Style/Presets.hs view
@@ -0,0 +1,398 @@+{-# LANGUAGE StrictData #-}++-- | Built-in theme presets and Base16 palette conversion.+module NanoUI.Internal.Style.Presets+  ( defaultTheme+  , defaultLightTheme+  , defaultThemeFor+  , tomorrowNightMinDarkTheme+  , tomorrowMinLightTheme+  , tomorrowMidnightMinDarkTheme+  , Base16 (..)+  , themeFromBase16+  , themeFromBase16Dark+  , themeFromBase16Light+  , base16TomorrowNight+  , base16TomorrowLight+  ) where++import NanoUI.Internal.Style.Theme+  ( Appearance+  , Style+  , Theme (..)+  , accentColor+  , buildThemePreset+  , flatStyle+  , lightDark+  , readableTone+  , withReadableTones+  )+import NanoUI.Internal.Types (Color, colorLuminance, colorRGBA, fadeAlpha, lerpColor)++-- | 'defaultLightTheme' for a light appearance, 'defaultTheme' otherwise.+defaultThemeFor :: Maybe Appearance -> Theme+defaultThemeFor = lightDark defaultLightTheme defaultTheme++-- | Neutral charcoal surfaces, warm text, and a blue selection accent.+defaultTheme :: Theme+defaultTheme =+  withReadableTones $+  let panelSurface =+        flatStyle+          (colorRGBA 34 34 38 255)+          (colorRGBA 236 234 230 255)+          (colorRGBA 54 54 62 255)+          (colorRGBA 34 34 38 255)+          (colorRGBA 30 30 34 255)+      greenCol = colorRGBA 104 168 124 255+      redCol = colorRGBA 252 165 165 255+   in Theme+        { themeWindow = colorRGBA 24 24 27 255+        , themePage = Nothing+        , themePanel = panelSurface+        , themeFloatingWindow = panelSurface+        , themePopup = panelSurface+        , themeButton =+            flatStyle+              (colorRGBA 52 52 58 255)+              (colorRGBA 248 247 245 255)+              (colorRGBA 74 76 84 255)+              (colorRGBA 68 70 78 255)+              (colorRGBA 42 42 48 255)+        , themeInput =+            flatStyle+              (colorRGBA 18 18 21 255)+              (colorRGBA 236 234 230 255)+              (colorRGBA 70 72 80 255)+              (colorRGBA 24 24 28 255)+              (colorRGBA 14 14 17 255)+        , themeSeparator = colorRGBA 62 64 72 255+        , themeAccent = colorRGBA 88 156 246 255+        , themeMuted = colorRGBA 176 172 164 255+        , themeRed = redCol+        , themeOrange = colorRGBA 216 140 72 255+        , themeYellow = colorRGBA 212 176 88 255+        , themeGreen = greenCol+        , themePurple = colorRGBA 176 140 220 255+        , themeSuccess = greenCol+        , themeWarning = colorRGBA 242 180 76 255+        , themeDanger = redCol+        , themeOverlayDim = colorRGBA 8 8 10 176+        , themeOnAccent = colorRGBA 255 255 255 255+        , themeSelection = fadeAlpha (colorRGBA 88 156 246 255) 115+        , themeFocusRing = colorRGBA 88 156 246 255+        , themeLink = colorRGBA 124 178 250 255+        , themeShadow = colorRGBA 0 0 0 72+        , themeDisabledFade = 0.55+        }++-- | Light counterpart of 'defaultTheme', for use with @followSystemTheme@.+defaultLightTheme :: Theme+defaultLightTheme =+  buildThemePreset+    defaultTheme+    ( flatStyle+        (colorRGBA 252 252 251 255)+        (colorRGBA 36 36 40 255)+        (colorRGBA 220 220 216 255)+        (colorRGBA 252 252 251 255)+        (colorRGBA 240 240 238 255)+    )+    $ \t ->+      t+        { themeWindow = colorRGBA 244 244 242 255+        , themeButton =+            flatStyle+              (colorRGBA 234 234 231 255)+              (colorRGBA 24 24 27 255)+              (colorRGBA 196 196 192 255)+              (colorRGBA 222 222 218 255)+              (colorRGBA 210 210 206 255)+        , themeInput =+            flatStyle+              (colorRGBA 255 255 255 255)+              (colorRGBA 36 36 40 255)+              (colorRGBA 190 190 186 255)+              (colorRGBA 250 250 249 255)+              (colorRGBA 255 255 255 255)+        , themeSeparator = colorRGBA 214 214 210 255+        , themeAccent = colorRGBA 37 99 235 255+        , themeMuted = colorRGBA 108 105 100 255+        , themeRed = colorRGBA 190 40 40 255+        , themeOrange = colorRGBA 184 82 14 255+        , themeYellow = colorRGBA 150 104 0 255+        , themeGreen = colorRGBA 30 128 70 255+        , themePurple = colorRGBA 128 70 190 255+        , themeWarning = colorRGBA 150 90 0 255+        , themeOverlayDim = colorRGBA 20 20 24 90+        , themeSelection = fadeAlpha (colorRGBA 37 99 235 255) 80+        , themeFocusRing = colorRGBA 37 99 235 255+        , themeLink = colorRGBA 29 78 216 255+        , themeShadow = colorRGBA 0 0 0 40+        }++-- | Ported from "Tomorrow Night Min" in https://github.com/biaqat/tomorrow-min-theme-zed+tomorrowNightMinDarkTheme :: Theme+tomorrowNightMinDarkTheme =+  buildThemePreset+    (accentColor accentCol defaultTheme)+    ( flatStyle+        (colorRGBA 30 31 33 255)+        (colorRGBA 234 234 234 255)+        edgeCol+        (colorRGBA 52 54 62 255)+        (colorRGBA 26 27 29 255)+    )+    $ \t ->+      t+        { themeWindow = windowCol+        , themeButton =+            flatStyle+              (colorRGBA 44 46 51 255)+              (colorRGBA 245 245 245 255)+              edgeCol+              (colorRGBA 69 74 83 255)+              (colorRGBA 28 29 32 255)+        , themeInput =+            flatStyle+              (colorRGBA 23 24 26 255)+              (colorRGBA 234 234 234 255)+              edgeCol+              (colorRGBA 29 30 33 255)+              (colorRGBA 19 20 22 255)+        , themeSeparator = colorRGBA 55 59 65 255+        , themeMuted = colorRGBA 150 152 150 255+        , themeRed = colorRGBA 204 102 102 255+        , themeOrange = colorRGBA 222 147 95 255+        , themeYellow = colorRGBA 240 198 116 255+        , themeGreen = colorRGBA 181 189 104 255+        , themePurple = colorRGBA 178 148 187 255+        , themeWarning = colorRGBA 240 198 116 255+        , themeOverlayDim = colorRGBA 0 0 0 160+        , themeLink = accentCol+        }+  where+    windowCol = colorRGBA 23 24 26 255+    edgeCol = colorRGBA 77 80 87 255+    accentCol = colorRGBA 103 150 230 255++-- | Ported from "Tomorrow Min" in https://github.com/biaqat/tomorrow-min-theme-zed+tomorrowMinLightTheme :: Theme+tomorrowMinLightTheme =+  buildThemePreset+    (accentColor (colorRGBA 82 134 188 255) defaultLightTheme)+    ( flatStyle+        (colorRGBA 242 242 242 255)+        (colorRGBA 55 59 65 255)+        (colorRGBA 222 222 222 255)+        (colorRGBA 231 231 231 255)+        (colorRGBA 219 219 219 255)+    )+    $ \t ->+      t+        { themeWindow = colorRGBA 255 255 255 255+        , themeButton =+            flatStyle+              (colorRGBA 232 232 232 255)+              (colorRGBA 55 59 65 255)+              (colorRGBA 214 214 214 255)+              (colorRGBA 214 214 214 255)+              (colorRGBA 196 196 196 255)+        , themeInput =+            flatStyle+              (colorRGBA 255 255 255 255)+              (colorRGBA 55 59 65 255)+              (colorRGBA 210 210 210 255)+              (colorRGBA 243 243 243 255)+              (colorRGBA 255 255 255 255)+        , themeSeparator = colorRGBA 222 222 222 255+        , themeMuted = colorRGBA 140 140 140 255+        , themeRed = colorRGBA 197 78 82 255+        , themeOrange = colorRGBA 231 140 69 255+        , themeYellow = colorRGBA 231 197 71 255+        , themeGreen = colorRGBA 113 140 0 255+        , themePurple = colorRGBA 137 91 144 255+        , themeWarning = colorRGBA 150 94 0 255+        , themeOverlayDim = colorRGBA 0 0 0 100+        , themeSelection = fadeAlpha (colorRGBA 82 134 188 255) 80+        , themeLink = colorRGBA 66 113 174 255+        , themeShadow = colorRGBA 0 0 0 36+        }++-- | Ported from "Tomorrow at Midnight Min" in https://github.com/biaqat/tomorrow-min-theme-zed+tomorrowMidnightMinDarkTheme :: Theme+tomorrowMidnightMinDarkTheme =+  buildThemePreset+    (accentColor accentCol defaultTheme)+    ( flatStyle+        (colorRGBA 16 17 20 255)+        (colorRGBA 238 238 238 255)+        edgeCol+        (colorRGBA 46 48 56 255)+        (colorRGBA 12 13 15 255)+    )+    $ \t ->+      t+        { themeWindow = colorRGBA 0 0 0 255+        , themeButton =+            flatStyle+              (colorRGBA 26 27 34 255)+              (colorRGBA 238 238 238 255)+              edgeCol+              (colorRGBA 54 58 72 255)+              (colorRGBA 56 60 81 255)+        , themeInput =+            flatStyle+              (colorRGBA 13 14 18 255)+              (colorRGBA 238 238 238 255)+              edgeCol+              (colorRGBA 21 22 28 255)+              (colorRGBA 8 9 11 255)+        , themeSeparator = edgeCol+        , themeMuted = colorRGBA 128 132 150 255+        , themeRed = colorRGBA 213 78 83 255+        , themeOrange = colorRGBA 231 140 69 255+        , themeYellow = colorRGBA 231 197 71 255+        , themeGreen = colorRGBA 185 202 74 255+        , themePurple = colorRGBA 195 151 216 255+        , themeWarning = colorRGBA 231 197 71 255+        , themeOverlayDim = colorRGBA 0 0 0 160+        , themeLink = accentCol+        , themeShadow = colorRGBA 0 0 0 96+        }+  where+    edgeCol = colorRGBA 48 52 70 255+    accentCol = colorRGBA 140 182 226 255++-- | Standard Base16 palette containing 16 styling tones and syntax colours.+data Base16 = Base16+  { base00 :: {-# UNPACK #-} !Color -- ^ Default Background+  , base01 :: {-# UNPACK #-} !Color -- ^ Lighter Background+  , base02 :: {-# UNPACK #-} !Color -- ^ Selection Background+  , base03 :: {-# UNPACK #-} !Color -- ^ Comments, Invisibles, Borders+  , base04 :: {-# UNPACK #-} !Color -- ^ Dark Foreground+  , base05 :: {-# UNPACK #-} !Color -- ^ Default Foreground+  , base06 :: {-# UNPACK #-} !Color -- ^ Light Foreground+  , base07 :: {-# UNPACK #-} !Color -- ^ Light Background / Highest contrast foreground+  , base08 :: {-# UNPACK #-} !Color -- ^ Red+  , base09 :: {-# UNPACK #-} !Color -- ^ Orange+  , base0A :: {-# UNPACK #-} !Color -- ^ Yellow+  , base0B :: {-# UNPACK #-} !Color -- ^ Green+  , base0C :: {-# UNPACK #-} !Color -- ^ Cyan+  , base0D :: {-# UNPACK #-} !Color -- ^ Blue / Primary Accent+  , base0E :: {-# UNPACK #-} !Color -- ^ Purple / Magenta+  , base0F :: {-# UNPACK #-} !Color -- ^ Brown / Deprecated+  }+  deriving (Eq, Show)++-- | Calculate a 'Theme' from a 'Base16' colorscheme, choosing dark or light+-- styling from background vs foreground luminance.+themeFromBase16 :: Base16 -> Theme+themeFromBase16 b+  | isDark = themeFromBase16Dark b+  | otherwise = themeFromBase16Light b+  where+    isDark = colorLuminance (base00 b) < colorLuminance (base05 b)++-- | Calculate a dark 'Theme' from a 'Base16' colorscheme.+themeFromBase16Dark :: Base16 -> Theme+themeFromBase16Dark = themeFromBase16Mode True++-- | Calculate a light 'Theme' from a 'Base16' colorscheme.+themeFromBase16Light :: Base16 -> Theme+themeFromBase16Light = themeFromBase16Mode False++themeFromBase16Mode :: Bool -> Base16 -> Theme+themeFromBase16Mode dark b =+  let pick :: a -> a -> a+      pick night day = if dark then night else day+      edgeCol = pick (lerpColor (base02 b) (base03 b) 0.35) (base02 b)+      panelBg =+        pick (lerpColor (base01 b) (base02 b) 0.3) (lerpColor (base00 b) (base01 b) 0.5)+      panelSurface :: Style+      panelSurface =+        flatStyle+          panelBg+          (base05 b)+          edgeCol+          (pick (lerpColor panelBg (base02 b) 0.5) (lerpColor panelBg (base00 b) 0.4))+          (lerpColor panelBg (pick (base00 b) (base02 b)) 0.4)+      readable = readableTone (base00 b)+   in buildThemePreset (accentColor (base0D b) (pick defaultTheme defaultLightTheme)) panelSurface $ \t ->+        t+          { themeWindow = base00 b+          , themeButton =+              flatStyle+                (pick (base02 b) (base01 b))+                (pick (base07 b) (base05 b))+                edgeCol+                (pick (lerpColor (base02 b) (base03 b) 0.4) (base02 b))+                (pick (base01 b) (lerpColor (base02 b) (base03 b) 0.35))+          , themeInput =+              flatStyle+                (base00 b)+                (base05 b)+                edgeCol+                (pick (base01 b) (lerpColor (base00 b) (base01 b) 0.3))+                (pick (base00 b) (lerpColor (base00 b) (base01 b) 0.6))+          , themeSeparator = edgeCol+          , themeMuted = base03 b+          , themeRed = base08 b+          , themeOrange = base09 b+          , themeYellow = base0A b+          , themeGreen = base0B b+          , themePurple = base0E b+          , themeWarning = readable (pick (base0A b) (base09 b))+          , themeOverlayDim = colorRGBA 0 0 0 (pick 160 100)+          , themeOnAccent =+              if colorLuminance (base0D b) > 0.6+                then pick (base00 b) (base07 b)+                else colorRGBA 255 255 255 255+          , themeSelection = fadeAlpha (base0D b) (pick 115 80)+          , themeLink = base0D b+          , themeShadow = colorRGBA 0 0 0 (pick 72 36)+          }++-- | Tomorrow Night Base16 reference palette.+base16TomorrowNight :: Base16+base16TomorrowNight =+  Base16+    { base00 = colorRGBA 29 31 33 255+    , base01 = colorRGBA 40 42 46 255+    , base02 = colorRGBA 55 59 65 255+    , base03 = colorRGBA 150 152 150 255+    , base04 = colorRGBA 180 183 180 255+    , base05 = colorRGBA 197 200 198 255+    , base06 = colorRGBA 224 224 224 255+    , base07 = colorRGBA 255 255 255 255+    , base08 = colorRGBA 213 78 83 255+    , base09 = colorRGBA 231 140 69 255+    , base0A = colorRGBA 231 197 71 255+    , base0B = colorRGBA 185 202 74 255+    , base0C = colorRGBA 112 192 186 255+    , base0D = colorRGBA 103 150 230 255+    , base0E = colorRGBA 195 151 216 255+    , base0F = colorRGBA 163 104 90 255+    }++-- | Tomorrow Light Base16 reference palette.+base16TomorrowLight :: Base16+base16TomorrowLight =+  Base16+    { base00 = colorRGBA 255 255 255 255+    , base01 = colorRGBA 242 242 242 255+    , base02 = colorRGBA 222 222 222 255+    , base03 = colorRGBA 140 140 140 255+    , base04 = colorRGBA 150 152 150 255+    , base05 = colorRGBA 55 59 65 255+    , base06 = colorRGBA 40 42 46 255+    , base07 = colorRGBA 29 31 33 255+    , base08 = colorRGBA 197 78 82 255+    , base09 = colorRGBA 231 140 69 255+    , base0A = colorRGBA 231 197 71 255+    , base0B = colorRGBA 113 140 0 255+    , base0C = colorRGBA 62 153 159 255+    , base0D = colorRGBA 82 134 188 255+    , base0E = colorRGBA 137 91 144 255+    , base0F = colorRGBA 163 104 90 255+    }
+ lib/NanoUI/Internal/Style/Theme.hs view
@@ -0,0 +1,454 @@+{-# LANGUAGE StrictData #-}++-- | Surface styles, theme definitions, readability helpers, and style/theme+-- modifiers.+module NanoUI.Internal.Style.Theme+  ( Style (..)+  , Side (..)+  , styleHasSide+  , fieldIconColor+  , Theme (..)+  , Appearance (..)+  , lightDark+  , themeAppearance+  , readableTone+  , toneColor+  , textToneColor+  , flatStyle+  , withReadableTones+  , buildThemePreset+  , background+  , foreground+  , borderColor+  , borderWidth+  , borderSides+  , borderLeft+  , borderRight+  , borderTop+  , borderBottom+  , cornerRadius+  , hoverBackground+  , pressBackground+  , fillColor+  , buttonStyle+  , inputStyle+  , panelStyle+  , windowStyle+  , popupStyle+  , everyStyle+  , accentColor+  , textColor+  , mutedColor+  , linkColor+  , selectionColor+  , windowColor+  , pageBackground+  , pageColor+  , panelPage+  , rounded+  , tinted+  , tone+  , primary+  , destructive+  , success+  , warning+  , subtle+  , readableOn+  , disabledTheme+  , themeSeries+  , scrollBarTrackColor+  , scrollBarThumbColor+  , scrollBarThumbHoverColor+  ) where++import Data.Bits (setBit, testBit)+import Data.List (find)+import Data.Maybe (fromMaybe)+import Data.Word (Word8)+import NanoUI.Internal.Style.Layout (Tone (..))+import NanoUI.Internal.Types (Color (..), clamp, colorA, colorB, colorG, colorLuminance, colorR, colorRGBA, colorTransparent, contrastRatio, fadeAlpha, lerpColor)++-- | Surface colours and border geometry. Border width and corner radius use+-- logical pixels and affect painting, not layout size.+data Style = Style+  { styleBg :: {-# UNPACK #-} !Color+  , styleFg :: {-# UNPACK #-} !Color+  , styleBorder :: {-# UNPACK #-} !Color+  , styleBorderWidth :: {-# UNPACK #-} !Float+  , styleCornerRadius :: {-# UNPACK #-} !Float+  , styleHoverBg :: {-# UNPACK #-} !Color+  , styleActiveBg :: {-# UNPACK #-} !Color+  , styleBorderSides :: {-# UNPACK #-} !Word8+  -- ^ The sides the border is drawn on, one bit per 'Side' in its order.+  }+  deriving (Eq, Show)++-- | A side of a rectangle, for 'borderSides'.+data Side = SideLeft | SideRight | SideTop | SideBottom+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Whether the style's border is drawn on this side.+{-# INLINE styleHasSide #-}+styleHasSide :: Side -> Style -> Bool+styleHasSide side s = testBit (styleBorderSides s) (fromEnum side)++-- | Colours and surface styles used to paint a view.+data Theme = Theme+  { themeWindow :: {-# UNPACK #-} !Color+  , themePage :: !(Maybe Color)+  , themePanel :: !Style+  , themeFloatingWindow :: !Style+  , themePopup :: !Style+  , themeButton :: !Style+  , themeInput :: !Style+  , themeSeparator :: {-# UNPACK #-} !Color+  , themeAccent :: {-# UNPACK #-} !Color+  , themeMuted :: {-# UNPACK #-} !Color+  , themeRed :: {-# UNPACK #-} !Color+  , themeOrange :: {-# UNPACK #-} !Color+  , themeYellow :: {-# UNPACK #-} !Color+  , themeGreen :: {-# UNPACK #-} !Color+  , themePurple :: {-# UNPACK #-} !Color+  , themeSuccess :: {-# UNPACK #-} !Color+  , themeWarning :: {-# UNPACK #-} !Color+  , themeDanger :: {-# UNPACK #-} !Color+  , themeOverlayDim :: {-# UNPACK #-} !Color+  , themeOnAccent :: {-# UNPACK #-} !Color+  , themeSelection :: {-# UNPACK #-} !Color+  , themeFocusRing :: {-# UNPACK #-} !Color+  , themeLink :: {-# UNPACK #-} !Color+  , themeShadow :: {-# UNPACK #-} !Color+  , themeDisabledFade :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | The system's light or dark preference.+data Appearance+  = AppearanceLight+  | AppearanceDark+  deriving (Eq, Show, Enum, Bounded, Ord)++-- | Pick the light theme for 'AppearanceLight', otherwise the dark one.+lightDark :: Theme -> Theme -> Maybe Appearance -> Theme+lightDark light _ (Just AppearanceLight) = light+lightDark _ dark _ = dark++-- | Classify a theme by its page background: dark if white text reads better on+-- it than black.+themeAppearance :: Theme -> Appearance+themeAppearance t = if darkColor (pageBackground t) then AppearanceDark else AppearanceLight++-- | Whether white reads better on a colour than black.+darkColor :: Color -> Bool+darkColor c = colorLuminance c < 0.179++-- | Blend a colour toward white (dark window) or black (light window) in 5%+-- steps until it reaches 4.5:1 contrast with the window.+readableTone :: Color -> Color -> Color+readableTone window c0 =+  fromMaybe (lerpColor c0 toward 0.95) $+    find (\c -> contrastRatio c window >= 4.5) [lerpColor c0 toward (fromIntegral i * 0.05) | i <- [0 .. 18 :: Int]]+  where+    toward = if darkColor window then colorRGBA 255 255 255 255 else colorRGBA 0 0 0 255++-- | A tone's colour in a theme.+toneColor :: Theme -> Tone -> Color+toneColor t = \case+  Accent -> themeAccent t+  Muted -> themeMuted t+  Success -> themeSuccess t+  Warning -> themeWarning t+  Danger -> themeDanger t++-- | Text color when no explicit color is set.+textToneColor :: Theme -> Maybe Tone -> Color+textToneColor theme = maybe (styleFg (themePanel theme)) (toneColor theme)++-- | Set the background, shifting hover/press shades proportionally.+background :: Color -> Style -> Style+background c s =+  s {styleBg = c, styleHoverBg = follow styleHoverBg, styleActiveBg = follow styleActiveBg}+  where+    old = styleBg s+    follow shade+      | shade s == old = c+      | colorA old == 0 = shade (fillColor c s)+      | otherwise = shiftColor old (shade s) c++shiftColor :: Color -> Color -> Color -> Color+shiftColor from to c =+  let ch f = fromIntegral (clamp 0 255 (fromIntegral (f c) + fromIntegral (f to) - fromIntegral (f from) :: Int))+   in colorRGBA (ch colorR) (ch colorG) (ch colorB) (colorA c)++-- | Set a surface's text and foreground colour.+foreground :: Color -> Style -> Style+foreground c s = s {styleFg = c}++-- | Set the border colour without changing its width.+borderColor :: Color -> Style -> Style+borderColor c s = s {styleBorder = c}++-- | Set border width in logical pixels, clamped to zero or greater.+borderWidth :: Float -> Style -> Style+borderWidth w s = s {styleBorderWidth = max 0 w}++-- | Draw the border on these sides only.+borderSides :: [Side] -> Style -> Style+borderSides sides s = s {styleBorderSides = foldl' (\m side -> setBit m (fromEnum side)) 0 sides}++borderSide :: Side -> Float -> Color -> Style -> Style+borderSide side w c s = s {styleBorder = c, styleBorderWidth = max 0 w, styleBorderSides = setBit 0 (fromEnum side)}++-- | A border of width @w@ and colour @c@ on one side only.+borderLeft, borderRight, borderTop, borderBottom :: Float -> Color -> Style -> Style+borderLeft = borderSide SideLeft+borderRight = borderSide SideRight+borderTop = borderSide SideTop+borderBottom = borderSide SideBottom++-- | Set corner radius in logical pixels, clamped to zero or greater.+cornerRadius :: Float -> Style -> Style+cornerRadius r s = s {styleCornerRadius = max 0 r}++-- | Set the background used while the pointer hovers over a control.+hoverBackground :: Color -> Style -> Style+hoverBackground c s = s {styleHoverBg = c}++-- | Set the background used while a control is active.+pressBackground :: Color -> Style -> Style+pressBackground c s = s {styleActiveBg = c}++-- | A background with hover and press shades derived from it.+fillColor :: Color -> Style -> Style+fillColor c s =+  s+    { styleBg = c+    , styleHoverBg = lerpColor c (styleFg s) 0.12+    , styleActiveBg = lerpColor c (colorRGBA 0 0 0 (colorA c)) 0.18+    }++-- | The colour of icons and adornments inside a field of this style.+fieldIconColor :: Style -> Color+fieldIconColor s = lerpColor (styleFg s) (styleBg s) 0.45++-- | Modify the theme's button surface.+buttonStyle :: (Style -> Style) -> Theme -> Theme+buttonStyle f t = t {themeButton = f (themeButton t)}++-- | Modify the theme's input surface.+inputStyle :: (Style -> Style) -> Theme -> Theme+inputStyle f t = t {themeInput = f (themeInput t)}++-- | Modify the theme's panel surface.+panelStyle :: (Style -> Style) -> Theme -> Theme+panelStyle f t = t {themePanel = f (themePanel t)}++-- | Modify the theme's floating-window surface.+windowStyle :: (Style -> Style) -> Theme -> Theme+windowStyle f t = t {themeFloatingWindow = f (themeFloatingWindow t)}++-- | Modify the theme's popup surface.+popupStyle :: (Style -> Style) -> Theme -> Theme+popupStyle f t = t {themePopup = f (themePopup t)}++-- | Modify button, input, panel, floating-window and popup surfaces together.+everyStyle :: (Style -> Style) -> Theme -> Theme+everyStyle f t =+  t+    { themeButton = f (themeButton t)+    , themeInput = f (themeInput t)+    , themePanel = f (themePanel t)+    , themeFloatingWindow = f (themeFloatingWindow t)+    , themePopup = f (themePopup t)+    }++-- | Set the accent and focus-ring colours, recolouring selection while keeping its alpha.+accentColor :: Color -> Theme -> Theme+accentColor c t = t {themeAccent = c, themeFocusRing = c, themeSelection = fadeAlpha c (colorA (themeSelection t))}++-- | The foreground of every surface.+textColor :: Color -> Theme -> Theme+textColor c = everyStyle (foreground c)++-- | Set the colour for secondary text.+mutedColor :: Color -> Theme -> Theme+mutedColor c t = t {themeMuted = c}++-- | Set the colour for rich-text hyperlinks.+linkColor :: Color -> Theme -> Theme+linkColor c t = t {themeLink = c}++-- | Set the selected-text highlight, including its alpha.+selectionColor :: Color -> Theme -> Theme+selectionColor c t = t {themeSelection = c}++-- | The window background, and the page's unless 'NanoUI.pageColor' sets another.+windowColor :: Color -> Theme -> Theme+windowColor c t = t {themeWindow = c}++-- | The colour a page is painted on.+pageBackground :: Theme -> Color+pageBackground t = fromMaybe (themeWindow t) (themePage t)++-- | Set the page surface colour painted under the view.+pageColor :: Color -> Theme -> Theme+pageColor c t = t {themePage = Just c}++-- | A page painted on the panel surface.+panelPage :: Theme -> Theme+panelPage t = pageColor (styleBg (themePanel t)) t++-- | The corner radius of every surface.+rounded :: Float -> Theme -> Theme+rounded r = everyStyle (cornerRadius r)++-- | Buttons filled with a colour picked from the theme, with a readable label.+tinted :: (Theme -> Color) -> Theme -> Theme+tinted pick t =+  let c = pick t+      label = readableOn t c+   in buttonStyle+        ( \s ->+            s+              { styleBg = c+              , styleFg = label+              , styleBorder = c+              , styleHoverBg = lerpColor c label 0.14+              , styleActiveBg = lerpColor c (themeWindow t) 0.22+              }+        )+        t++-- | Fill buttons with a tone's colour and pick a readable label colour.+tone :: Tone -> Theme -> Theme+tone t = tinted (`toneColor` t)++-- | Buttons in the accent colour: 'tone' 'Accent'.+primary :: Theme -> Theme+primary = tone Accent++-- | Buttons in the danger colour: 'tone' 'Danger'.+destructive :: Theme -> Theme+destructive = tone Danger++-- | Buttons in the success colour: 'tone' 'Success'.+success :: Theme -> Theme+success = tone Success++-- | Buttons in the warning colour: 'tone' 'Warning'.+warning :: Theme -> Theme+warning = tone Warning++-- | Buttons without a fill or border until hovered.+subtle :: Theme -> Theme+subtle =+  buttonStyle $ \s ->+    s+      { styleBg = colorTransparent+      , styleBorder = colorTransparent+      , styleBorderWidth = 0+      , styleHoverBg = fadeAlpha (styleFg s) 30+      , styleActiveBg = fadeAlpha (styleFg s) 48+      }++-- | Whichever of the theme's text colours reads best on @c@.+readableOn :: Theme -> Color -> Color+readableOn t c =+  let !c0 = themeOnAccent t+      !c1 = styleFg (themePanel t)+      !c2 = themeWindow t+      !r0 = contrastRatio c0 c+      !r1 = contrastRatio c1 c+      !r2 = contrastRatio c2 c+   in if r0 >= r1 && r0 >= r2 then c0 else if r1 >= r2 then c1 else c2++-- | The theme disabled widgets are drawn with.+disabledTheme :: Theme -> Theme+disabledTheme t =+  let f = themeDisabledFade t+      page = pageBackground t+      fade c+        | colorA c == 0 = c+        | otherwise = fadeAlpha (lerpColor c page f) (colorA c)+      fadeStyle s =+        let bg = fade (styleBg s)+         in s {styleBg = bg, styleFg = fade (styleFg s), styleBorder = fade (styleBorder s), styleHoverBg = bg, styleActiveBg = bg}+   in (everyStyle fadeStyle t)+        { themeSeparator = fade (themeSeparator t)+        , themeAccent = fade (themeAccent t)+        , themeMuted = fade (themeMuted t)+        , themeRed = fade (themeRed t)+        , themeOrange = fade (themeOrange t)+        , themeYellow = fade (themeYellow t)+        , themeGreen = fade (themeGreen t)+        , themePurple = fade (themePurple t)+        , themeSuccess = fade (themeSuccess t)+        , themeWarning = fade (themeWarning t)+        , themeDanger = fade (themeDanger t)+        , themeOnAccent = fade (themeOnAccent t)+        , themeFocusRing = fade (themeFocusRing t)+        , themeLink = fade (themeLink t)+        }++-- | Flat widget style: bg/fg/border plus hover and active fills with border width 1 and radius 2.+flatStyle :: Color -> Color -> Color -> Color -> Color -> Style+flatStyle bg fg border hoverBg activeBg =+  Style+    { styleBg = bg+    , styleFg = fg+    , styleBorder = border+    , styleBorderWidth = 1+    , styleCornerRadius = 2+    , styleHoverBg = hoverBg+    , styleActiveBg = activeBg+    , styleBorderSides = 15+    }++-- | Set 'themeSuccess' and 'themeDanger' from the theme's green and red,+-- toned to read on its page ('readableTone').+withReadableTones :: Theme -> Theme+withReadableTones t =+  t+    { themeSuccess = readableTone (pageBackground t) (themeGreen t)+    , themeDanger = readableTone (pageBackground t) (themeRed t)+    }++-- | Shared preset builder: installs @panelSurface@ on panel, floating window,+-- and popup slots, derives readable success/danger tones, and applies overrides.+buildThemePreset :: Theme -> Style -> (Theme -> Theme) -> Theme+buildThemePreset base panelSurface refine =+  withReadableTones $+    refine+      base+        { themePanel = panelSurface+        , themeFloatingWindow = panelSurface+        , themePopup = panelSurface+        }++-- | Series palette in order: red, orange, yellow, green, accent, purple.+themeSeries :: Theme -> [Color]+themeSeries t =+  [ themeRed t+  , themeOrange t+  , themeYellow t+  , themeGreen t+  , themeAccent t+  , themePurple t+  ]++-- | Scrollbar track colour mixed from background and separator.+scrollBarTrackColor :: Style -> Theme -> Color+scrollBarTrackColor base theme =+  lerpColor (styleBg base) (themeSeparator theme) 0.28++-- | Scrollbar thumb colour mixed from separator and foreground, with alpha 130.+scrollBarThumbColor :: Style -> Theme -> Color+scrollBarThumbColor base theme =+  let solid = lerpColor (themeSeparator theme) (styleFg base) 0.58+   in fadeAlpha solid 130++-- | Scrollbar thumb colour under hover/drag, with alpha 180.+scrollBarThumbHoverColor :: Style -> Theme -> Color+scrollBarThumbHoverColor base theme =+  let solid = lerpColor (themeSeparator theme) (styleFg base) 0.72+   in fadeAlpha solid 180
+ lib/NanoUI/Internal/StyleBits.hs view
@@ -0,0 +1,450 @@+-- | The bit layout of a node's style index+-- ('NanoUI.Internal.Layout.Arena.getStyleIdx'): one 'Int' whose bits mean+-- different things per 'NanoUI.Internal.Layout.Arena.NodeType'. Every field+-- is a 'BitField' constant here, and every encoder and decoder reads its+-- shift and width from one of them. 'styleLayouts' lists the fields each+-- node type packs together; the @style-bits-spec@ suite checks that none of+-- them overlap and that each fits in 64 bits.+--+-- This module imports only @base@, so that suite compiles it on its own.+--+-- @+-- bits    field             node types+-- ------  ----------------  ----------------------------------------------+-- 0-3     textFace          text font: NodeText, NodeTextInput,+-- 4-7     stripe            NodeTextArea, and a button's or select's+-- 8-11    textWeight        labelFont (moved up 32 bits)+-- 12-13   textSlant+-- 14-15   textDecoration+-- 16      textTabular+-- 18-20   textTone          tone plus one, 0 for none+-- 21-22   textEllipsis      0 end, 1 middle, 2 start+-- 26      inputSearch       NodeTextInput flags+-- 28      inputSelectable+-- 29      inputPassword+-- 30      inputNumeric+-- 0-23    buttonVisual      NodeButton: the bits below the type flags+-- 0-1     buttonVariant     close button (1 trailing, 2 tab), choice (1 radio)+-- 0-1     tabStyle          tab header ('buttonKind' = ButtonTab)+-- 2-3     tabOrient+-- 0-7     treeDepth         tree row ('buttonKind' = ButtonRow)+-- 8       treeHasKids+-- 9       treeExpanded+-- 10      treeOdd+-- 16-17   headerSortMark    table header ('buttonKind' = ButtonTable)+-- 20-22   buttonTone        plain toggle button: tone plus one+-- 24-27   buttonKind        ButtonKind enum (0 plain .. 8 row)+-- 32-63   labelFont         NodeButton, NodeSelect: a text font packing+-- 0       containerInert    NodeContainer+-- 1       containerClip+-- 2       containerShaderEffect+-- 3       containerButtonGroup+-- 8-9     chromePart        tab strip chrome+-- 10-11   chromeStyle+-- 12-13   chromeOrient+-- 4-7     stripe            NodePanel: a table cell's row stripe+-- 0-2     scrollPolicyX     NodeScrollContainer+-- 3-5     scrollPolicyY+-- 6       scrollMarker      always set+-- 7       scrollBare+-- 8       scrollFocusable+-- 0-1     pickerPart        NodeColorPicker+-- @+--+-- A @NodeBox@ keeps its fill color's 32-bit word and a @NodeImage@ its look+-- in the whole index; the other node types keep nothing there.+module NanoUI.Internal.StyleBits+  ( BitField (..)+  , fieldEnd+  , fieldMask+  , getField+  , packField+  , placeField+  , testField+  , decodeStyleEnum+  -- * Text font+  , textFace+  , stripe+  , textWeight+  , textSlant+  , textDecoration+  , textTabular+  , textTone+  , textEllipsis+  , textSingleLine+  , textFontFields+  , textFontKeyMask+  -- * Text field flags+  , inputSearch+  , inputSelectable+  , inputPassword+  , inputNumeric+  -- * Button+  , buttonVisual+  , buttonTone+  , buttonKind+  , tabStyle+  , tabOrient+  , treeDepth+  , treeHasKids+  , treeExpanded+  , treeOdd+  , headerSortMark+  , labelFont+  -- * Container+  , containerInert+  , containerClip+  , containerShaderEffect+  , containerButtonGroup+  , chromePart+  , chromeStyle+  , chromeOrient+  -- * Scroll container+  , scrollPolicyX+  , scrollPolicyY+  , scrollMarker+  , scrollBare+  , scrollFocusable+  -- * Color picker+  , pickerPart+  -- * Layouts+  , styleLayouts+  ) where++import Data.Bits ((.&.), (.|.), shiftL, shiftR)+import Data.Word (Word64)++-- | @bfWidth@ bits of a 64-bit style index starting at bit @bfShift@. The+-- fields below are INLINE constants, so 'getField' and 'packField' on one of+-- them compile to the shift and mask literals they replace.+data BitField = BitField+  { bfShift :: !Int+  , bfWidth :: !Int+  }+  deriving (Eq, Show)++-- | The bit after a field's last one.+{-# INLINE fieldEnd #-}+fieldEnd :: BitField -> Int+fieldEnd f = bfShift f + bfWidth f++{-# INLINE lowMask #-}+lowMask :: BitField -> Word64+lowMask f = (1 `shiftL` bfWidth f) - 1++-- | A field's bits in place.+{-# INLINE fieldMask #-}+fieldMask :: BitField -> Word64+fieldMask f = lowMask f `shiftL` bfShift f++-- | The value a 64-bit style index holds in a field.+{-# INLINE getField #-}+getField :: BitField -> Word64 -> Int+getField f si = fromIntegral ((si `shiftR` bfShift f) .&. lowMask f)++-- | @v@ cut to the field's width and moved into place.+{-# INLINE packField #-}+packField :: BitField -> Int -> Word64+packField f v = (fromIntegral v .&. lowMask f) `shiftL` bfShift f++-- | @v@ moved into place, for a value already known to fit the field.+{-# INLINE placeField #-}+placeField :: BitField -> Int -> Word64+placeField f v = fromIntegral v `shiftL` bfShift f++-- | Whether any bit of the field is set.+{-# INLINE testField #-}+testField :: BitField -> Word64 -> Bool+testField f si = si .&. fieldMask f /= 0++-- | The enum packed in field @f@ of the style bits, or @fallback@ when the+-- field holds no constructor.+{-# INLINE decodeStyleEnum #-}+decodeStyleEnum :: forall a. (Bounded a, Enum a) => BitField -> a -> Word64 -> a+decodeStyleEnum f fallback si =+  let v = getField f si+   in if v >= fromEnum (minBound :: a) && v <= fromEnum (maxBound :: a) then toEnum v else fallback++-- Text font ----------------------------------------------------------------++-- | The face of the layout's 'NanoUI.Internal.Style.FontVariant'.+{-# INLINE textFace #-}+textFace :: BitField+textFace = BitField 0 4++-- | A row stripe code (0 none, 1 even row, 2 odd row), on a text node or on+-- a table cell's panel.+{-# INLINE stripe #-}+stripe :: BitField+stripe = BitField 4 4++-- | Font weight ('NanoUI.Internal.Style.FontWeight').+{-# INLINE textWeight #-}+textWeight :: BitField+textWeight = BitField 8 4++-- | Font slant ('NanoUI.Internal.Style.FontStyle').+{-# INLINE textSlant #-}+textSlant :: BitField+textSlant = BitField 12 2++-- | Text decoration ('NanoUI.Internal.Style.TextDecoration').+{-# INLINE textDecoration #-}+textDecoration :: BitField+textDecoration = BitField 14 2++-- | Whether a text node uses tabular lining figures ('NanoUI.fontTabular').+{-# INLINE textTabular #-}+textTabular :: BitField+textTabular = BitField 16 1++-- | The 'NanoUI.Internal.Style.Tone' plus one, or 0 for none.+{-# INLINE textTone #-}+textTone :: BitField+textTone = BitField 18 3++-- | Where truncated single-line text places its ellipsis (0 end, 1 middle, 2 start).+{-# INLINE textEllipsis #-}+textEllipsis :: BitField+textEllipsis = BitField 21 2++-- | Whether a text node stays on one line and truncates instead of wrapping in a column.+{-# INLINE textSingleLine #-}+textSingleLine :: BitField+textSingleLine = BitField 23 1++-- | Every field of a text font packing, which 'labelFont' must hold.+textFontFields :: [(String, BitField)]+textFontFields =+  [ ("textFace", textFace)+  , ("stripe", stripe)+  , ("textWeight", textWeight)+  , ("textSlant", textSlant)+  , ("textDecoration", textDecoration)+  , ("textTabular", textTabular)+  , ("textTone", textTone)+  , ("textEllipsis", textEllipsis)+  , ("textSingleLine", textSingleLine)+  ]++-- | The fields that pick the font a text node is measured in: face, weight,+-- slant and tabular figures.+{-# INLINE textFontKeyMask #-}+textFontKeyMask :: Word64+textFontKeyMask = fieldMask textFace .|. fieldMask textWeight .|. fieldMask textSlant .|. fieldMask textTabular++-- Text field flags ---------------------------------------------------------++-- | Search input with leading icon and clear button ('NanoUI.searchInput').+{-# INLINE inputSearch #-}+inputSearch :: BitField+inputSearch = BitField 26 1++-- | Read-only selectable text node ('NanoUI.selectableText').+{-# INLINE inputSelectable #-}+inputSelectable :: BitField+inputSelectable = BitField 28 1++-- | Masked password input ('NanoUI.ticPassword').+{-# INLINE inputPassword #-}+inputPassword :: BitField+inputPassword = BitField 29 1++-- | Numeric input with steppers ('NanoUI.numericInput').+{-# INLINE inputNumeric #-}+inputNumeric :: BitField+inputNumeric = BitField 30 1++-- Button -------------------------------------------------------------------++-- | A button's own bits below its type flags. Each kind reads them its own+-- way ('buttonVariant', 'tabStyle', 'treeDepth', 'headerSortMark',+-- 'buttonTone').+{-# INLINE buttonVisual #-}+buttonVisual :: BitField+buttonVisual = BitField 0 24++-- | The variant of a close button (1 trailing, 2 tab header) or a choice (1+-- radio).+{-# INLINE buttonVariant #-}+buttonVariant :: BitField+buttonVariant = BitField 0 2++-- | The 'NanoUI.Internal.Style.Tone' plus one that a plain toggle button fills with, or 0 for the+-- accent.+{-# INLINE buttonTone #-}+buttonTone :: BitField+buttonTone = BitField 20 3++-- | The 'NanoUI.Internal.WidgetText.ButtonKind' enum packed in bits 24-27+-- (0 plain .. 8 tree row).+{-# INLINE buttonKind #-}+buttonKind :: BitField+buttonKind = BitField 24 4++-- | A tab header's tab style (0-3).+{-# INLINE tabStyle #-}+tabStyle :: BitField+tabStyle = BitField 0 2++-- | A tab header's strip orientation (0-3); 2 and up are vertical strips.+{-# INLINE tabOrient #-}+tabOrient :: BitField+tabOrient = BitField 2 2++-- | Indentation depth (0-255) of a tree row.+{-# INLINE treeDepth #-}+treeDepth :: BitField+treeDepth = BitField 0 8++-- | Whether a tree row has child rows.+{-# INLINE treeHasKids #-}+treeHasKids :: BitField+treeHasKids = BitField 8 1++-- | Whether a tree row's branch is currently expanded.+{-# INLINE treeExpanded #-}+treeExpanded :: BitField+treeExpanded = BitField 9 1++-- | Alternating-row stripe bit for a tree row.+{-# INLINE treeOdd #-}+treeOdd :: BitField+treeOdd = BitField 10 1++-- | A table header's sort mark: 0 none, 1 ascending, 2 descending.+{-# INLINE headerSortMark #-}+headerSortMark :: BitField+headerSortMark = BitField 16 2++-- | A button's or select's label font, packed as a text node packs one.+{-# INLINE labelFont #-}+labelFont :: BitField+labelFont = BitField 32 32++-- Container ----------------------------------------------------------------++-- | Inert container whose subtree ignores pointer and focus interaction.+{-# INLINE containerInert #-}+containerInert :: BitField+containerInert = BitField 0 1++-- | Container clips its children to its own laid-out rectangle.+{-# INLINE containerClip #-}+containerClip :: BitField+containerClip = BitField 1 1++-- | Container wraps its children in a Tier 2 shader effect ('NanoUI.withShader').+{-# INLINE containerShaderEffect #-}+containerShaderEffect :: BitField+containerShaderEffect = BitField 2 1++-- | Container joins adjacent buttons with outer-only rounding and shared+-- internal borders ('NanoUI.buttonGroup').+{-# INLINE containerButtonGroup #-}+containerButtonGroup :: BitField+containerButtonGroup = BitField 3 1++-- | The 'NanoUI.Internal.WidgetText.TabChrome' a tab strip's container+-- paints.+{-# INLINE chromePart #-}+chromePart :: BitField+chromePart = BitField 8 2++-- | Tab strip visual style (0-3) stored on a tab chrome container.+{-# INLINE chromeStyle #-}+chromeStyle :: BitField+chromeStyle = BitField 10 2++-- | Tab strip orientation (0-3) stored on a tab chrome container.+{-# INLINE chromeOrient #-}+chromeOrient :: BitField+chromeOrient = BitField 12 2++-- Scroll container ---------------------------------------------------------++-- | Horizontal 'NanoUI.ScrollPolicy' enum code (0-4).+{-# INLINE scrollPolicyX #-}+scrollPolicyX :: BitField+scrollPolicyX = BitField 0 3++-- | Vertical 'NanoUI.ScrollPolicy' enum code (0-4).+{-# INLINE scrollPolicyY #-}+scrollPolicyY :: BitField+scrollPolicyY = BitField 3 3++-- | Always set, so that no scroll node's style index is 0.+{-# INLINE scrollMarker #-}+scrollMarker :: BitField+scrollMarker = BitField 6 1++-- | Omit the scroll container's background well and border ('NanoUI.scrollBare').+{-# INLINE scrollBare #-}+scrollBare :: BitField+scrollBare = BitField 7 1++-- | Scroll container takes keyboard focus as a Tab stop and on click+-- ('NanoUI.scrollFocusable').+{-# INLINE scrollFocusable #-}+scrollFocusable :: BitField+scrollFocusable = BitField 8 1++-- Color picker -------------------------------------------------------------++-- | The 'NanoUI.Internal.Widgets.ColorPicker.ColorPickerPart' a node paints.+{-# INLINE pickerPart #-}+pickerPart :: BitField+pickerPart = BitField 0 2++-- Layouts ------------------------------------------------------------------++-- | The fields each node type packs into one style index, by name. A button+-- appears once per kind, since each kind reads 'buttonVisual' its own way.+styleLayouts :: [(String, [(String, BitField)])]+styleLayouts =+  [ ("NodeText", textFontFields)+  , ("NodeTextArea", textFontFields)+  , ( "NodeTextInput"+    , textFontFields+        <> [ ("inputSearch", inputSearch)+           , ("inputSelectable", inputSelectable)+           , ("inputPassword", inputPassword)+           , ("inputNumeric", inputNumeric)+           ]+    )+  , ("NodeButton plain", button [("buttonTone", buttonTone)])+  , ("NodeButton close or choice", button [("buttonVariant", buttonVariant)])+  , ("NodeButton tab", button [("tabStyle", tabStyle), ("tabOrient", tabOrient)])+  , ( "NodeButton tree row"+    , button+        [ ("treeDepth", treeDepth)+        , ("treeHasKids", treeHasKids)+        , ("treeExpanded", treeExpanded)+        , ("treeOdd", treeOdd)+        ]+    )+  , ("NodeButton table header", button [("headerSortMark", headerSortMark)])+  , ("NodeSelect", [("labelFont", labelFont)])+  , ( "NodeContainer"+    , [ ("containerInert", containerInert)+      , ("containerClip", containerClip)+      , ("containerShaderEffect", containerShaderEffect)+      , ("containerButtonGroup", containerButtonGroup)+      , ("chromePart", chromePart)+      , ("chromeStyle", chromeStyle)+      , ("chromeOrient", chromeOrient)+      ]+    )+  , ("NodePanel", [("stripe", stripe)])+  , ( "NodeScrollContainer"+    , [ ("scrollPolicyX", scrollPolicyX)+      , ("scrollPolicyY", scrollPolicyY)+      , ("scrollMarker", scrollMarker)+      , ("scrollBare", scrollBare)+      , ("scrollFocusable", scrollFocusable)+      ]+    )+  , ("NodeColorPicker", [("pickerPart", pickerPart)])+  ]+  where+    button own = own <> [("buttonKind", buttonKind), ("labelFont", labelFont)]
+ lib/NanoUI/Internal/Tasks.hs view
@@ -0,0 +1,325 @@+-- | Background work. 'useTaskStatus' and 'useTask' run an action on a worker+-- thread and return its outcome. 'useStream' runs a producer that updates+-- state the view reads. 'askWake' lets any other thread rerun the view.+--+-- Worker threads never touch the context's stores. A job writes into its own+-- 'IORef' and wakes the loop ('wakeFromThread'); the view reads the ref on its+-- next call to the hook. A job belongs to its typed handle and lives while+-- the view keeps calling the hook ('useHeld'). 'sweepHeld' ends the rest.+module NanoUI.Internal.Tasks+  ( TaskStatus (..)+  , Task+  , newTask+  , Stream+  , newStream+  , useTaskStatus+  , useTask+  , useStream+  , askWake+  , useHeld+  , holdAction+  , sweepHeld+  , cancelTasks+  , cancelTasksOf+  )+where++import Control.Concurrent (forkIO, forkIOWithUnmask, killThread, newEmptyMVar, newMVar, putMVar, readMVar, withMVar)+import Control.Exception (AsyncException (ThreadKilled), SomeException, catch, evaluate, finally, fromException, mask, mask_, throwIO, try)+import Control.Monad (filterM, forM_, unless, void, when)+import Data.IORef (IORef, atomicWriteIORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.Primitive.PrimVar (modifyPrimVar, newPrimVar, readPrimVar, writePrimVar)+import Data.Unique (hashUnique, newUnique)+import GHC.Conc (labelThread)+import NanoUI.Internal.Context (Context (ctxWakeLoop, ctxHeld), intKey, wakeAction)+import NanoUI.Internal.Resource (Resource (..), newResource, Held (..), Holding (..))+import NanoUI.Internal.Monad (NanoUI, askContext, freshWidget, liftIO, withContext)+import System.Timeout (timeout)++-- | Hold a resource for key @k@ in its typed owner. While the key is+-- unchanged the cached value is returned. Otherwise the old resource is+-- released and @acquire@ builds a new one, receiving the old value.+-- A second view pass in the same frame reuses the first pass's+-- value. Resources are released when a frame skips the hook ('sweepHeld') and+-- when the session ends ('cancelTasks'). Holds job threads and+-- 'NanoUI.useImageRgba' images.+useHeld :: Eq k => Resource k a -> k -> (Context -> Maybe a -> IO (a, IO ())) -> NanoUI a+useHeld owner k acquire = useHeldBy owner k (\ctx old -> fmap (pure () <$) <$> acquire ctx old)++-- | 'useHeld' whose release returns an action that waits for it to finish.+{-# INLINE useHeldBy #-}+useHeldBy :: Eq k => Resource k a -> k -> (Context -> Maybe a -> IO (a, IO (IO ()))) -> NanoUI a+useHeldBy (Resource key cell) k acquire =+  withContext $ \ctx -> do+    let registry = ctxHeld ctx+        ref = heldEntries registry+        stampedVar = heldStamped registry+        countVar = heldCount registry+    entry <- readIORef cell+    frame <- readPrimVar (heldFrame registry)+    case entry of+      Just (k0, v, holding) | k0 == k -> do+        touch registry frame holding+        pure v+      _ -> mask $ \restore -> do+        -- The replaced entry leaves the map, and the counts, before its+        -- release, so an @acquire@ that throws leaves nothing released+        -- behind for a later frame to release again. Guard membership in case+        -- a Resource was reused across contexts.+        forM_ entry $ \(_, _, old) -> do+          wasHere <- IM.member key <$> readIORef ref+          when wasHere $ do+            modifyIORef' ref (IM.delete key)+            modifyPrimVar countVar (subtract 1)+            s <- readPrimVar (holdingSeen old)+            when (s == frame) $ modifyPrimVar stampedVar (subtract 1)+          void (holdingRelease old `catch` \(_ :: SomeException) -> pure (pure ()))+        (v, release) <- restore (acquire ctx ((\(_, v, _) -> v) <$> entry))+        holding <- registerHolding registry frame key (writeIORef cell Nothing >> release)+        writeIORef cell (Just (k, v, holding))+        pure v++registerHolding :: Held -> Int -> Int -> IO (IO ()) -> IO Holding+registerHolding registry frame key release = do+  seen <- newPrimVar frame+  let holding = Holding release seen+  modifyIORef' (heldEntries registry) (IM.insert key holding)+  modifyPrimVar (heldStamped registry) (+ 1)+  modifyPrimVar (heldCount registry) (+ 1)+  pure holding++touch :: Held -> Int -> Holding -> IO ()+touch registry frame holding = do+  seen <- readPrimVar (holdingSeen holding)+  unless (seen == frame) $ do+    writePrimVar (holdingSeen holding) frame+    modifyPrimVar (heldStamped registry) (+ 1)++-- | Lease a callback-only built-in resource at a widget id. There is no+-- payload to recover: sweeping only runs its cleanup action.+holdAction :: IO () -> NanoUI ()+holdAction release = do+  (wid, ctx) <- freshWidget+  liftIO $ do+    let registry = ctxHeld ctx+        widget = intKey wid+    frame <- readPrimVar (heldFrame registry)+    widgets <- readIORef (heldWidgets registry)+    entries <- readIORef (heldEntries registry)+    case IM.lookup widget widgets >>= (`IM.lookup` entries) of+      Just holding -> touch registry frame holding+      Nothing -> do+        key <- hashUnique <$> newUnique+        modifyIORef' (heldWidgets registry) (IM.insert widget key)+        void $ registerHolding registry frame key $+          pure () <$ (modifyIORef' (heldWidgets registry) (IM.delete widget) >> release)++-- | State of a 'useTaskStatus' job. The 'Maybe' is the latest result from an+-- earlier key, so the view can keep showing it instead of flickering.+data TaskStatus a+  = -- | The job is running.+    TaskRunning (Maybe a)+  | -- | The job returned this.+    TaskDone a+  | -- | The job threw this.+    TaskFailed SomeException (Maybe a)+  deriving (Show, Functor)++-- | A job's status and latest result, stored together so neither read+-- allocates.+data Outcome a = Outcome !(TaskStatus a) !(Maybe a)++-- | Allocate one typed task owner per component/session. Key and result types+-- are fixed by the handle. Skipping its hook releases its running job.+newtype Task k a = Task (Resource k (IORef (Outcome a)))++-- | A new task owner. Allocate it once during setup, outside the view, and+-- give each 'useTask' or 'useTaskStatus' call site its own.+newTask :: IO (Task k a)+newTask = Task <$> newResource++-- | A typed stream owner, allocated before the per-frame view.+newtype Stream k s = Stream (Resource k (IORef s))++-- | A new stream owner. Allocate it once during setup, outside the view, and+-- give each 'useStream' call site its own.+newStream :: IO (Stream k s)+newStream = Stream <$> newResource++-- | 'useHeldBy' for a job. @start@ builds the result box (given the old+-- box) and the action to fork, given the job's wake. Once the job is+-- released the wake does nothing: no view reads the box, so a wake from a+-- job that has not unwound yet, or from a thread it started, would only+-- repaint.+{-# INLINE useJob #-}+useJob :: Eq k => Resource k a -> k -> (IO () -> Maybe a -> IO (a, IO ())) -> NanoUI a+useJob owner k start = useHeldBy owner k $ \ctx old -> do+  live <- newIORef True+  let !wake = wakeAction ctx+  (box, run) <- start (readIORef live >>= \l -> when l wake) old+  done <- newEmptyMVar+  -- Masked until the handler is in place, so a job killed before it first+  -- runs still reports that it has ended.+  tid <- mask_ (forkIOWithUnmask (\unmask -> unmask run `finally` putMVar done ()))+  labelThread tid "nano-ui task"+  -- Kill from a separate thread: 'killThread' blocks until the job receives+  -- the exception, which masking or a foreign call can delay. Only the+  -- session's end waits for the job to end ('cancelTasks').+  pure (box, writeIORef live False >> (readMVar done <$ forkIO (killThread tid)))++-- | Run an action on a worker thread and report its status: running, done,+-- or failed with the exception it threw.+--+-- The job runs once per key. Calling with a new key kills the running job+-- and starts another. To rerun with the same input, pair it with a counter+-- that a Retry button bumps:+--+-- > attemptVar <- useVar (0 :: Int)+-- > attempt <- readVar attemptVar+-- > status <- useTaskStatus task (path, attempt) (T.readFile path)+-- > case status of+-- >   TaskRunning _ -> label "Loading..."+-- >   TaskDone contents -> label contents+-- >   TaskFailed e _ -> do+-- >     danger (T.pack (displayException e))+-- >     whenM (button "Retry") (modifyVar attemptVar (+ 1))+--+-- The loop sleeps while the job runs and wakes once when it ends; that frame+-- repaints the whole window. Allocate @task <- newTask@ once during setup.+-- This consumes no widget id. A frame that skips the handle kills its job;+-- call it above a tab or branch that should not end it:+--+-- > when shown (void (useTask task path (T.readFile path)))+--+-- Kills are asynchronous and sent from another thread, so the frame does not+-- wait. An old job may run briefly alongside its replacement, until it next+-- allocates or returns from a foreign call. Use 'Control.Exception.bracket'+-- in jobs that write files or hold resources. Jobs still running when the+-- session ends are killed, and the session waits up to a second for them to+-- finish unwinding.+--+-- The result is forced to weak head normal form on the worker thread; force+-- deeper structure inside the action, or the view will pay for it.+-- Exceptions from the action or from forcing the result become 'TaskFailed',+-- asynchronous ones such as a stack overflow included; only the hook's own+-- kill ends the job without one. Build with @-threaded@ so jobs run while the+-- loop sleeps.+useTaskStatus :: Eq k => Task k a -> k -> IO a -> NanoUI (TaskStatus a)+useTaskStatus owner k run = (\(Outcome status _) -> status) <$> useOutcome owner k run++-- | Like 'useTaskStatus', but returns only the latest result: the current+-- job's once it returns, otherwise the previous key's, or 'Nothing'. A failed+-- job keeps the previous result.+--+-- > path <- readVar =<< useVar "notes.txt"+-- > contents <- useTask task path (T.readFile (T.unpack path))+-- > label (fromMaybe "Loading..." contents)+useTask :: Eq k => Task k a -> k -> IO a -> NanoUI (Maybe a)+useTask owner k run = (\(Outcome _ latest) -> latest) <$> useOutcome owner k run++-- | The job's outcome as of this frame. A new key's job starts as running,+-- carrying the replaced job's latest result.+useOutcome :: Eq k => Task k a -> k -> IO a -> NanoUI (Outcome a)+useOutcome (Task owner) k run = do+  box <- useJob owner k $ \wake old -> do+    prev <- maybe (pure Nothing) (fmap (\(Outcome _ latest) -> latest) . readIORef) old+    box <- newIORef (Outcome (TaskRunning prev) prev)+    let finish = (>> wake) . atomicWriteIORef box+    pure+      ( box+      , try (run >>= evaluate) >>= \case+          Right a -> finish (Outcome (TaskDone a) (Just a))+          Left e+            | Just ThreadKilled <- fromException e -> throwIO e+            | otherwise -> finish (Outcome (TaskFailed e prev) prev)+      )+  liftIO (readIORef box)++-- | Run a producer on a worker thread that updates state the view reads, such+-- as sensor readings, download progress, or a streamed chat reply. The+-- producer gets @update@, which applies a function to the state atomically,+-- forces the result to weak head normal form on the producer's thread, and+-- wakes the loop. Each call returns the current state, starting from+-- @initial@.+--+-- Allocate @stream <- newStream@ during setup, then read it in the view:+--+-- > sensorView stream = do+-- >   reading <- useStream stream () Nothing $ \update -> forever $ do+-- >     r <- readSensor+-- >     update (const (Just r))+-- >   label (maybe "--" (T.pack . show) reading)+--+-- Many updates between frames cost one frame. To keep every value, fold it+-- in: @update (x :)@. Keys and lifetime work as in 'useTaskStatus': a new key+-- kills the producer and restarts from @initial@, and a frame that skips the+-- hook kills it. A producer that returns leaves the state as it last set it.+-- An uncaught exception ends the producer like any 'forkIO' thread; catch it+-- inside to show it in the state. An update whose function throws leaves the+-- state as it was and throws to its caller.+useStream :: Eq k => Stream k s -> k -> s -> (((s -> s) -> IO ()) -> IO ()) -> NanoUI s+useStream (Stream owner) k initial produce = do+  box <- useJob owner k $ \wake _ -> do+    box <- newIORef initial+    -- The new state is forced before it is published, so a function that+    -- throws leaves nothing in the box for the view to raise. Updates from+    -- threads the producer starts take turns.+    lock <- newMVar ()+    let update f = withMVar lock (\_ -> readIORef box >>= evaluate . f >>= atomicWriteIORef box) >> wake+    pure (box, produce update)+  liftIO (readIORef box)++-- | An action any thread can call to rerun the view after changing something+-- it reads. The woken frame repaints the whole window, since nothing says+-- which widgets changed. Wakes before that frame runs merge into it, so a+-- thread faster than the display costs one frame per display frame.+--+-- 'useStream' is built on this. Use it directly for a thread the view does+-- not own: publish each value where the view reads it, then wake.+askWake :: NanoUI (IO ())+askWake = wakeAction <$> askContext++-- | End-of-frame sweep: release resources whose hook did not run this frame.+-- Two view passes in one frame count as one. When every hook ran, it touches+-- no entry.+sweepHeld :: Context -> IO ()+sweepHeld ctx = sweep (ctxHeld ctx)+  where+    sweep (Held ref _ frameVar stampedVar countVar) = do+      frame <- readPrimVar frameVar+      stamped <- readPrimVar stampedVar+      count <- readPrimVar countVar+      writePrimVar frameVar (frame + 1)+      writePrimVar stampedVar 0+      unless (stamped == count) $ do+        held <- readIORef ref+        gone <- filterM (\(_, Holding _ seen) -> (/= frame) <$> readPrimVar seen) (IM.toAscList held)+        writeIORef ref $! IM.withoutKeys held (IS.fromDistinctAscList (map fst gone))+        writePrimVar countVar (count - length gone)+        mapM_ (\(_, h) -> void (holdingRelease h) `catch` \(_ :: SomeException) -> pure ()) gone++-- | Kill every job on the context and release images held by+-- 'NanoUI.useImageRgba', at session end. 'NanoUI.Runner.runSessionLoop' calls+-- this when its loop returns; hosts that run frames themselves should too.+-- It removes the wake action ('NanoUI.Backend.setWakeLoop'), so nothing wakes+-- a loop that is gone, and waits up to a second for the killed jobs to finish+-- unwinding, so their 'Control.Exception.bracket' and+-- 'Control.Exception.finally' cleanups run before the session's resources go.+cancelTasks :: Context -> IO ()+cancelTasks ctx = cancelTasksOf (ctxWakeLoop ctx) (ctxHeld ctx)++-- | 'cancelTasks' on the context's 'ctxWakeLoop' and 'ctxHeld', for a caller+-- that keeps those rather than the context.+cancelTasksOf :: IORef (Maybe (IO Bool)) -> Held -> IO ()+cancelTasksOf wake (Held ref widgets _ stampedVar countVar) = do+  writeIORef wake Nothing+  held <- readIORef ref+  writeIORef ref IM.empty+  writeIORef widgets IM.empty+  writePrimVar stampedVar 0+  writePrimVar countVar 0+  -- Every kill is sent before the wait, so the jobs unwind together.+  waits <- mapM (\h -> holdingRelease h `catch` \(_ :: SomeException) -> pure (pure ())) held+  void (timeout 1000000 (mapM_ (\wait -> wait `catch` \(_ :: SomeException) -> pure ()) waits))
+ lib/NanoUI/Internal/TextCluster.hs view
@@ -0,0 +1,94 @@+-- | User-perceived characters, closely enough for caret motion and wrapping,+-- told apart without Unicode's segmentation tables.+module NanoUI.Internal.TextCluster+  ( clusterLength+  , clusterBounds+  , prevClusterStart+  ) where++import Data.Char (isMark)+import Data.Text (Text)+import Data.Text qualified as T++attaches :: Char -> Bool+attaches c =+  isMark c+    || (c >= '\x1F3FB' && c <= '\x1F3FF')+    || (c >= '\xE0020' && c <= '\xE007F')++isRegional :: Char -> Bool+isRegional c = c >= '\x1F1E6' && c <= '\x1F1FF'++-- | How many characters the user-perceived character @t@ starts with spans,+-- 0 for empty text: a character keeps the combining marks (variation+-- selectors among them), emoji modifiers and tag characters after it, a+-- zero-width joiner joins the next character on, and regional indicators+-- pair into flags. A newline is its own cluster: nothing joins or attaches+-- to it.+clusterLength :: Text -> Int+clusterLength t = case T.uncons t of+  Nothing -> 0+  Just ('\n', _) -> 1+  Just (c, rest) -> 1 + extend (isRegional c) rest+  where+    -- Characters after the first that stay in its cluster.+    extend regional s = case T.uncons s of+      Just (c, rest)+        | c == '\x200D' -> case T.uncons rest of+            Just (n, rest') | n /= '\n' -> 2 + extend False rest'+            _ -> 1+        | attaches c -> 1 + extend False rest+        | regional && isRegional c -> 1 + extend False rest+      _ -> 0++-- | The user-perceived character boundaries around character @k@ of @t@:+-- the last at or before it and the first at or after it. Both are @k@ where+-- a character starts, and both the length of @t@ past its end.+clusterBounds :: Text -> Int -> (Int, Int)+clusterBounds t k = go 0 t+  where+    go !i s+      | i >= k || n == 0 = (i, i)+      | i + n > k = (i, i + n)+      | otherwise = go (i + n) (T.drop n s)+      where+        n = clusterLength s++-- | Start index of the cluster immediately preceding character offset @k@+-- (for @k > 0@), equal to @fst (clusterBounds t (k - 1))@ while only walking+-- back to the nearest guaranteed cluster boundary.+prevClusterStart :: Text -> Int -> Int+prevClusterStart t !k+  | k <= 1 = 0+  | otherwise =+      let (prefix, suffix) = T.splitAt k t+          -- 'T.null suffix' holds only at or past end-of-line; checking length+          -- there keeps out-of-bounds offsets consistent with 'clusterBounds'.+          !len = if T.null suffix then T.length prefix else k+       in if k > len+            then len+            else case T.unsnoc prefix of+              Nothing -> 0+              Just (rest, c)+                | not (attaches c || c == '\x200D' || isRegional c)+                , not (endsWithZWJ rest) -> k - 1+                | otherwise ->+                    let !target = k - 1+                        !back = rewind 0 prefix+                        !syncPos = k - back+                        run !i s =+                          let n = clusterLength s+                           in if n == 0 || i + n > target+                                then i+                                else run (i + n) (T.drop n s)+                     in run syncPos (T.takeEnd back prefix)+  where+    endsWithZWJ s = case T.unsnoc s of+      Just (_, '\x200D') -> True+      _ -> False+    rewind !back s = case T.unsnoc s of+      Nothing -> back+      Just (rest, c)+        | c == '\n' -> back + 1+        | attaches c || c == '\x200D' || isRegional c || endsWithZWJ rest -> rewind (back + 1) rest+        | otherwise -> back + 1
+ lib/NanoUI/Internal/TextEditor/Types.hs view
@@ -0,0 +1,53 @@+-- | Pure editor types, shared by editing operations and typed widget storage.+module NanoUI.Internal.TextEditor.Types+  ( EditorMode (..)+  , EditKind (..)+  , StoredEdit (..)+  , EditGroup (..)+  , EditHistory (..)+  )+where++import Data.Text.Short qualified as TS+import NanoUI.Widgets.TextBuffer (Cursor)++-- | Editing and clipboard permissions for a text field.+data EditorMode = EditorMode+  { modeMultiLine :: !Bool+  , modeEditable :: !Bool+  -- ^ Off for selectable labels: only motion, selection and copy apply.+  , modeCopyable :: !Bool+  -- ^ Off for passwords: nothing reaches the clipboard.+  }+  deriving (Eq, Show)++-- | Classification of an edit group for coalescing consecutive edits.+data EditKind = EditTyping | EditDeleting | EditOther+  deriving (Eq, Show)++-- | Compact copied text avoids retaining slices of large documents in history.+data StoredEdit = StoredEdit !Cursor !TS.ShortText !TS.ShortText+  deriving (Eq, Show)++-- | Edits undone and redone as one step.+data EditGroup = EditGroup+  { groupKind :: !EditKind+  , groupEdits :: ![StoredEdit]+  -- ^ Newest first.+  , groupBefore :: !(Cursor, Cursor)+  -- ^ Anchor and cursor before the first edit.+  , groupAfter :: !(Cursor, Cursor)+  -- ^ Anchor and cursor after the last edit.+  }+  deriving (Eq, Show)++-- | Undo and redo groups, newest first, with consecutive-edit grouping state.+data EditHistory = EditHistory+  { historyUndo :: ![EditGroup]+  , historyRedo :: ![EditGroup]+  , historyDepth :: !Int+  -- ^ Length of 'historyUndo'.+  , historyOpen :: !Bool+  -- ^ Whether the next edit may join the newest group.+  }+  deriving (Eq, Show)
+ lib/NanoUI/Internal/Types.hs view
@@ -0,0 +1,604 @@+-- | Geometry in logical pixels, packed RGBA colours, and repaint bounds.+-- Window coordinates start at the top-left, with x rightward and y downward.+module NanoUI.Internal.Types+  ( V2 (..)+  , Rect (..)+  , Size (..)+  , Color (..)+  , colorRGBA+  , colorRGB+  , colorHex+  , colorHexA+  , withAlpha+  , fadeAlpha+  , colorWhite+  , colorBlack+  , colorTransparent+  , colorToWord32+  , colorR+  , colorG+  , colorB+  , colorA+  , unpackColorF+  , rgbToHsv+  , hsvToRgb+  , clamp+  , clamp01+  , noLimit+  , isBounded+  , isUnbounded+  , finite+  , onGrid+  , gridSpan+  , roundHalfUp+  , lerpColor+  , colorLuminance+  , contrastRatio+  , ImageId (..)+  , rectContains+  , rectNonEmpty+  , rectUnion+  , rectIntersect+  , rectFullyInside+  , rectInflate+  , rectArea+  , Damage (..)+  , DamageBounds (..)+  , defaultDamageSlop+  , sliderDamageSlop+  , haloDamageSlop+  , resolveDamageRect+  , damageIsEmpty+  , v2Add+  , v2Sub+  , PopupAnchor (..)+  , PopupPlacement (..)+  , spanEffectiveClip+  , shiftClip+  , readRectAt+  , writeRectAt+  , eqRectAt+  , foldUpTo+  , forUpTo_+  , newZeroedPrimArray+  , bucketOffsets+  ) where++import Control.Monad.Primitive (PrimMonad, PrimState)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.Hashable (Hashable)+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , PrimArray+  , copyMutablePrimArray+  , indexPrimArray+  , newPrimArray+  , primArrayFromList+  , readPrimArray+  , setPrimArray+  , writePrimArray+  )+import Data.Primitive.Types (Prim)+import Data.Word (Word8, Word32)+import GHC.Exts (RealWorld)+import GHC.Generics (Generic)++-- | A two-component point, offset, or vector; units depend on its use.+data V2 = V2+  { v2X :: {-# UNPACK #-} !Float+  , v2Y :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show, Generic)++-- | Width and height in logical pixels.+data Size = Size+  { sizeW :: {-# UNPACK #-} !Float+  , sizeH :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | Top-left origin, width, and height in logical pixels. Hit tests include+-- the left and top edges and exclude the right and bottom edges.+data Rect = Rect+  { rectX :: {-# UNPACK #-} !Float+  , rectY :: {-# UNPACK #-} !Float+  , rectW :: {-# UNPACK #-} !Float+  , rectH :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show)++-- | An image registered in a context's atlas. It is not a native texture handle.+newtype ImageId = ImageId+  { unImageId :: Int+  }+  deriving (Eq, Ord, Show)++-- | Straight-alpha colour packed as @0xRRGGBBAA@, with 8 bits per channel.+newtype Color = Color Word32+  deriving (Eq, Show, Num, Hashable)++-- | Pack red, green, blue, and alpha channels; alpha 0 is transparent, 255 opaque.+{-# INLINE colorRGBA #-}+colorRGBA :: Word8 -> Word8 -> Word8 -> Word8 -> Color+colorRGBA r g b a =+  Color $+    (fromIntegral r `shiftL` 24)+      .|. (fromIntegral g `shiftL` 16)+      .|. (fromIntegral b `shiftL` 8)+      .|. fromIntegral a++-- | An opaque colour from red, green and blue channels.+{-# INLINE colorRGB #-}+colorRGB :: Word8 -> Word8 -> Word8 -> Color+colorRGB r g b = colorRGBA r g b 255++-- | An opaque colour from a 24-bit @0xRRGGBB@ hex literal (for example,+-- @colorHex 0x2a7fff@).+{-# INLINE colorHex #-}+colorHex :: Word32 -> Color+colorHex rgb = Color (((rgb .&. 0xFFFFFF) `shiftL` 8) .|. 0xFF)++-- | A straight-alpha colour from a 32-bit @0xRRGGBBAA@ hex literal (for+-- example, @colorHexA 0x2a7fff80@).+{-# INLINE colorHexA #-}+colorHexA :: Word32 -> Color+colorHexA = Color++-- | The colour with its alpha set to @a@, from 0 (transparent) to 1+-- (opaque); values outside that range are clamped.+--+-- > withAlpha (themeAccent theme) 0.25+{-# INLINE withAlpha #-}+withAlpha :: Color -> Float -> Color+withAlpha c a = fadeAlpha c (round (255 * clamp01 a))++-- | Replaces the alpha channel of a color.+fadeAlpha :: Color -> Word8 -> Color+fadeAlpha (Color w) a = Color ((w .&. 0xFFFFFF00) .|. fromIntegral a)++-- | Opaque white, black, and fully transparent black.+colorWhite, colorBlack, colorTransparent :: Color+colorWhite = Color 0xFFFFFFFF+colorBlack = Color 0x000000FF+colorTransparent = Color 0++-- | The packed @0xRRGGBBAA@ representation.+{-# INLINE colorToWord32 #-}+colorToWord32 :: Color -> Word32+colorToWord32 (Color w) = w++-- | Red channel, in the range 0-255.+{-# INLINE colorR #-}+colorR :: Color -> Word8+colorR (Color w) = fromIntegral ((w `shiftR` 24) .&. 0xFF)++-- | Green channel, in the range 0-255.+{-# INLINE colorG #-}+colorG :: Color -> Word8+colorG (Color w) = fromIntegral ((w `shiftR` 16) .&. 0xFF)++-- | Blue channel, in the range 0-255.+{-# INLINE colorB #-}+colorB :: Color -> Word8+colorB (Color w) = fromIntegral ((w `shiftR` 8) .&. 0xFF)++-- | Alpha channel, from 0 (transparent) to 255 (opaque).+{-# INLINE colorA #-}+colorA :: Color -> Word8+colorA (Color w) = fromIntegral (w .&. 0xFF)++-- | Unpack a packed 'Color' into normalized @[0, 1]@ RGBA floats.+{-# INLINE unpackColorF #-}+unpackColorF :: Color -> (Float, Float, Float, Float)+unpackColorF (Color w) =+  let !inv = 1.0 / 255.0+   in ( fromIntegral ((w `shiftR` 24) .&. 0xFF) * inv+      , fromIntegral ((w `shiftR` 16) .&. 0xFF) * inv+      , fromIntegral ((w `shiftR` 8) .&. 0xFF) * inv+      , fromIntegral (w .&. 0xFF) * inv+      )++-- | Restrict a value to inclusive lower and upper bounds, which must be ordered.+{-# INLINE clamp #-}+clamp :: Ord a => a -> a -> a -> a+clamp lo hi x = max lo (min hi x)++-- | The size limit that means none: the default maximum width and height,+-- and the space a measure is offered along an unbounded axis.+noLimit :: Float+noLimit = 1e9++-- | Whether a size limit constrains anything. Limits of 1e8 or more, such as+-- 'noLimit', mean no limit, so a sum or a padding added to 'noLimit' still+-- reads as unbounded.+{-# INLINE isBounded #-}+isBounded :: Float -> Bool+isBounded v = v < 1e8++-- | @not . 'isBounded'@.+{-# INLINE isUnbounded #-}+isUnbounded :: Float -> Bool+isUnbounded v = v >= 1e8++-- | Restrict a value to the inclusive range 0-1.+{-# INLINE clamp01 #-}+clamp01 :: Float -> Float+clamp01 x = clamp 0 1 x++-- | Neither NaN nor infinite.+{-# INLINE finite #-}+finite :: Float -> Bool+finite v = not (isNaN v || isInfinite v)++-- | Round a logical coordinate onto the device-pixel grid implied by draw+-- scale @s@ (device px = logical * s). Every layer that positions pixels --+-- the layout solve, text pens, scroll offsets, paint and glyph rasterization --+-- must route its coordinates through this single function (backends through+-- 'roundHalfUp'), so geometry can never dephase from text. An identity when+-- @s <= 0@ (no scaling).+{-# INLINE onGrid #-}+onGrid :: Float -> Float -> Float+onGrid s v+  | s > 0 = fromIntegral (roundHalfUp (v * s)) / s+  | otherwise = v++-- | Size between two edges once both are snapped with 'onGrid'. Counted in+-- device pixels and scaled once, so an edge pair a whole number of device+-- pixels apart gives that size exactly; subtracting two 'onGrid' results+-- can land a float step off it. An identity on @b - a@ when @s <= 0@.+{-# INLINE gridSpan #-}+gridSpan :: Float -> Float -> Float -> Float+gridSpan s a b+  | s > 0 = fromIntegral (roundHalfUp (b * s) - roundHalfUp (a * s)) / s+  | otherwise = b - a++-- | Round to the nearest integer, ties up: the device-pixel rounding shared by+-- 'onGrid' and the backends. Not ties-to-even (@round@): at a fractional scale+-- (125%: a 20px row is 25 device px) a column of rows can all sit on half+-- pixels, and ties-to-even would alternate them down and up, leaving uneven+-- gaps. Compares the exact fractional part rather than @floor (r + 0.5)@,+-- whose addition itself rounds: it lifts the float just below 0.5 to 1 and+-- odd integers past 2^23 up by one.+{-# INLINE roundHalfUp #-}+roundHalfUp :: Float -> Int+roundHalfUp r =+  let f = floor r+   in if r - fromIntegral f >= 0.5 then f + 1 else f++-- | Hue in degrees (0-360), saturation and value in 0-1. Alpha is ignored;+-- grey colours have hue 0.+rgbToHsv :: Color -> (Float, Float, Float)+rgbToHsv c =+  let r = fromIntegral (colorR c) / 255+      g = fromIntegral (colorG c) / 255+      b = fromIntegral (colorB c) / 255+      maxC = max r (max g b)+      minC = min r (min g b)+      delta = maxC - minC+      v = maxC+      s = if maxC <= 0 then 0 else delta / maxC+      h+        | delta <= 0 = 0+        | maxC == r =+            let t = (g - b) / delta+             in if t < 0 then 60 * (t + 6) else 60 * t+        | maxC == g = 60 * (((b - r) / delta) + 2)+        | otherwise = 60 * (((r - g) / delta) + 4)+   in (h, s, v)++-- | Convert hue in degrees and saturation/value in 0-1 to an opaque colour.+-- Hue wraps every 360 degrees; output channels are clamped.+hsvToRgb :: Float -> Float -> Float -> Color+hsvToRgb h s v =+  let hi = floor (h / 60) :: Int+      f = h / 60 - fromIntegral hi+      p = v * (1 - s)+      q = v * (1 - f * s)+      t = v * (1 - (1 - f) * s)+      (r, g, b) =+        case hi `mod` 6 of+          0 -> (v, t, p)+          1 -> (q, v, p)+          2 -> (p, v, t)+          3 -> (p, q, v)+          4 -> (t, p, v)+          _ -> (v, p, q)+      toCh x = round (clamp01 x * 255) :: Word8+   in colorRGBA (toCh r) (toCh g) (toCh b) 255++-- | WCAG 2 relative-luminance contrast. 4.5 is AA for normal text.+--+-- Alpha is ignored, so both colours must be opaque. Passing a translucent+-- colour such as 'NanoUI.themeOverlayDim' gives a meaningless ratio;+-- composite it over its backdrop first.+contrastRatio :: Color -> Color -> Double+contrastRatio a b =+  let hi = max (colorLuminance a) (colorLuminance b)+      lo = min (colorLuminance a) (colorLuminance b)+   in (hi + 0.05) / (lo + 0.05)++-- | Relative luminance after sRGB linearisation, in 0-1. Ignores alpha.+colorLuminance :: Color -> Double+colorLuminance c =+  0.2126 * srgb (colorR c) + 0.7152 * srgb (colorG c) + 0.0722 * srgb (colorB c)++-- | Interpolate all four packed channels. The factor is clamped to 0-1;+-- interpolation is in sRGB channel space, not linear light.+lerpColor :: Color -> Color -> Float -> Color+lerpColor (Color a) (Color b) t =+  let u = clamp01 t+      ch shift =+        round $+          fromIntegral ((a `shiftR` shift) .&. 0xFF) * (1 - u)+            + fromIntegral ((b `shiftR` shift) .&. 0xFF) * u+   in Color+        ( (ch 24 `shiftL` 24)+            .|. (ch 16 `shiftL` 16)+            .|. (ch 8 `shiftL` 8)+            .|. ch 0+        )++-- | Precomputed sRGB-to-linear lookup table for all 256 8-bit channel values.+{-# NOINLINE srgbLut #-}+srgbLut :: PrimArray Double+srgbLut = primArrayFromList [linearize i | i <- [0 .. 255 :: Int]]+  where+    linearize ch =+      let x = fromIntegral ch / 255+       in if x <= 0.04045 then x / 12.92 else ((x + 0.055) / 1.055) ** 2.4++{-# INLINE srgb #-}+srgb :: Word8 -> Double+srgb ch = indexPrimArray srgbLut (fromIntegral ch)++-- | Test a point against half-open rectangle bounds. An empty or+-- negative-size rectangle contains no point.+{-# INLINE rectContains #-}+rectContains :: Rect -> V2 -> Bool+rectContains (Rect x y w h) (V2 px py) =+  px >= x && px < x + w && py >= y && py < y + h++-- | Whether both width and height are strictly positive.+{-# INLINE rectNonEmpty #-}+rectNonEmpty :: Rect -> Bool+rectNonEmpty r = rectW r > 0 && rectH r > 0++-- | Smallest bounding rectangle containing both inputs. Empty inputs are+-- still included by their coordinates; filter them first if they mean no area.+{-# INLINE rectUnion #-}+rectUnion :: Rect -> Rect -> Rect+rectUnion (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) =+  let x = min x1 x2+      y = min y1 y2+      xEnd = max (x1 + w1) (x2 + w2)+      yEnd = max (y1 + h1) (y2 + h2)+   in Rect x y (xEnd - x) (yEnd - y)++-- | Shared positive-area rectangle, or 'Nothing' for disjoint or touching edges.+{-# INLINE rectIntersect #-}+rectIntersect :: Rect -> Rect -> Maybe Rect+rectIntersect (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) =+  let x = max x1 x2+      y = max y1 y2+      xEnd = min (x1 + w1) (x2 + w2)+      yEnd = min (y1 + h1) (y2 + h2)+      w = xEnd - x+      h = yEnd - y+   in if w > 0 && h > 0 then Just (Rect x y w h) else Nothing++-- | Whether the first rectangle has positive size and lies inside the second.+{-# INLINE rectFullyInside #-}+rectFullyInside :: Rect -> Rect -> Bool+rectFullyInside (Rect ix iy iw ih) (Rect ox oy ow oh) =+  iw > 0+    && ih > 0+    && ix >= ox+    && iy >= oy+    && ix + iw <= ox + ow+    && iy + ih <= oy + oh++-- | Extend every edge by the margin. A negative margin shrinks the rectangle.+{-# INLINE rectInflate #-}+rectInflate :: Float -> Rect -> Rect+rectInflate pad (Rect x y w h) =+  Rect (x - pad) (y - pad) (w + pad * 2) (h + pad * 2)++-- | Width times height. Requires non-negative dimensions for a geometric area.+{-# INLINE rectArea #-}+rectArea :: Rect -> Float+rectArea (Rect _ _ w h) = w * h++-- | Region to repaint: the whole window or a clip in logical window coordinates.+-- An empty 'NanoUI.Backend.DamageClip' means no repaint is needed.+data Damage+  = DamageFull+  | DamageClip !Rect+  deriving (Eq, Show)++-- | Whether damage is a clip with non-positive width or height.+{-# INLINE damageIsEmpty #-}+damageIsEmpty :: Damage -> Bool+damageIsEmpty dmg =+  case dmg of+    DamageFull -> False+    DamageClip r -> rectW r <= 0 || rectH r <= 0++-- | Invalidation bounding strategy for a widget and its interaction events.+data DamageBounds+  = DamageSelf                              -- ^ Exact layout bounding box Rect+  | DamageInflated {-# UNPACK #-} !Float    -- ^ Layout bounding box inflated by margin (focus rings, shadows, text slop)+  | DamageExact !Rect                       -- ^ Explicit rectangle in window space+  | DamageCustom (Rect -> Rect)             -- ^ Custom transformation on layout bounding box+  | DamageUnion !DamageBounds !DamageBounds -- ^ Combined invalidation bounds+  | DamageNone                              -- ^ No invalidation bounds++instance Show DamageBounds where+  show DamageSelf = "DamageSelf"+  show (DamageInflated f) = "DamageInflated " ++ show f+  show (DamageExact r) = "DamageExact " ++ show r+  show (DamageCustom _) = "DamageCustom <fn>"+  show (DamageUnion a b) = "DamageUnion (" ++ show a ++ ") (" ++ show b ++ ")"+  show DamageNone = "DamageNone"++-- | Functions cannot be compared, so a 'DamageCustom' equals nothing, not+-- even itself.+instance Eq DamageBounds where+  DamageSelf == DamageSelf = True+  DamageInflated a == DamageInflated b = a == b+  DamageExact a == DamageExact b = a == b+  DamageUnion a1 b1 == DamageUnion a2 b2 = a1 == a2 && b1 == b2+  DamageNone == DamageNone = True+  _ == _ = False++-- | Standard damage slop for text overhang, focus rings, and border anti-aliasing.+defaultDamageSlop :: Float+defaultDamageSlop = 4.0++-- | Damage slop for slider handles that extend past track bounds.+sliderDamageSlop :: Float+sliderDamageSlop = 8.0++-- | Damage slop for window resize halos and shadows.+haloDamageSlop :: Float+haloDamageSlop = 12.0++-- | Resolve damage bounds against a given layout rect.+resolveDamageRect :: DamageBounds -> Rect -> Rect+resolveDamageRect bounds r =+  case bounds of+    DamageSelf -> r+    DamageInflated pad -> rectInflate pad r+    DamageExact exactR -> exactR+    DamageCustom f -> f r+    DamageUnion a b ->+      -- An empty side (DamageNone, or an unlaid-out rect) contributes+      -- nothing; a plain rect union would stretch the damage to the origin.+      let ra = resolveDamageRect a r+          rb = resolveDamageRect b r+       in if not (rectNonEmpty ra)+            then rb+            else if not (rectNonEmpty rb) then ra else rectUnion ra rb+    DamageNone -> Rect 0 0 0 0++-- | Add corresponding components, for example a point and an offset.+{-# INLINE v2Add #-}+v2Add :: V2 -> V2 -> V2+v2Add (V2 x1 y1) (V2 x2 y2) = V2 (x1 + x2) (y1 + y2)++-- | Subtract corresponding components, for example the offset between points.+{-# INLINE v2Sub #-}+v2Sub :: V2 -> V2 -> V2+v2Sub (V2 x1 y1) (V2 x2 y2) = V2 (x1 - x2) (y1 - y2)++-- | Point or rectangle a popup is placed relative to, in logical window coordinates.+data PopupAnchor+  = AnchorPoint !V2+  | AnchorRect !Rect+  deriving (Eq, Show)++-- | Preferred side of a popup anchor. Placement also accounts for available+-- window space; 'PlacementAuto' lets the positioner choose a side.+data PopupPlacement+  = PlacementBelow+  | PlacementAbove+  | PlacementRight+  | PlacementLeft+  | PlacementAtCursor+  -- ^ For a tooltip ('NanoUI.tooltipPlacement'): just below the pointer,+  -- following it. For a popup or context menu: top-left corner at the+  -- anchor point, so a menu opens where it was clicked and stays there.+  | PlacementAuto+  deriving (Eq, Show, Ord)++-- | Strict left fold over @0 .. n - 1@.+{-# INLINE foldUpTo #-}+foldUpTo :: Int -> (a -> Int -> IO a) -> a -> IO a+foldUpTo n f = go 0+  where+    go !i !acc+      | i >= n = pure acc+      | otherwise = f acc i >>= go (i + 1)++-- | Run @f@ on @0 .. n - 1@ in order, without allocating a range list.+{-# INLINE forUpTo_ #-}+forUpTo_ :: Int -> (Int -> IO ()) -> IO ()+forUpTo_ n f = foldUpTo n (\() i -> f i) ()++-- | A primitive array of @n@ zeroes.+{-# INLINE newZeroedPrimArray #-}+newZeroedPrimArray :: (PrimMonad m, Prim a, Num a) => Int -> m (MutablePrimArray (PrimState m) a)+newZeroedPrimArray n = do+  arr <- newPrimArray n+  arr <$ setPrimArray arr 0 n 0++-- | Intersect a clip rectangle (where 'isUnbounded' width or height means open)+-- with an optional damage rectangle: 'Nothing' when culled, @Just Nothing@ when+-- open, and @Just (Just r)@ for a concrete clip.+{-# INLINE spanEffectiveClip #-}+spanEffectiveClip :: Maybe Rect -> Rect -> Maybe (Maybe Rect)+spanEffectiveClip mDamage r@(Rect _ _ cw ch) =+  let !open = isUnbounded cw || isUnbounded ch+   in case (mDamage, open) of+        (Nothing, True) -> Just Nothing+        (Nothing, False) -> Just (Just r)+        (Just dmg, True) -> Just (Just dmg)+        (Just dmg, False) -> Just <$> rectIntersect dmg r++-- | Translate an optional clip rectangle into local target space by subtracting @(ox, oy)@.+{-# INLINE shiftClip #-}+shiftClip :: Float -> Float -> Maybe Rect -> Maybe Rect+shiftClip ox oy mClip+  | ox == 0 && oy == 0 = mClip+  | otherwise = (\(Rect x y w h) -> Rect (x - ox) (y - oy) w h) <$> mClip++-- | Read four contiguous floats @(x, y, w, h)@ starting at @off@ as a 'Rect'.+{-# INLINE readRectAt #-}+readRectAt :: MutablePrimArray RealWorld Float -> Int -> IO Rect+readRectAt arr !off =+  Rect+    <$> readPrimArray arr off+    <*> readPrimArray arr (off + 1)+    <*> readPrimArray arr (off + 2)+    <*> readPrimArray arr (off + 3)++-- | Write four contiguous floats @(x, y, w, h)@ starting at @off@.+{-# INLINE writeRectAt #-}+writeRectAt :: MutablePrimArray RealWorld Float -> Int -> Float -> Float -> Float -> Float -> IO ()+writeRectAt arr !off x y w h = do+  writePrimArray arr off x+  writePrimArray arr (off + 1) y+  writePrimArray arr (off + 2) w+  writePrimArray arr (off + 3) h++-- | Compare four contiguous floats at @off@ against @(x, y, w, h)@.+{-# INLINE eqRectAt #-}+eqRectAt :: MutablePrimArray RealWorld Float -> Int -> Float -> Float -> Float -> Float -> IO Bool+eqRectAt arr !off x y w h = do+  x0 <- readPrimArray arr off+  y0 <- readPrimArray arr (off + 1)+  w0 <- readPrimArray arr (off + 2)+  h0 <- readPrimArray arr (off + 3)+  pure (x0 == x && y0 == y && w0 == w && h0 == h)++-- | Count items across @buckets@ buckets via @forItems@, returning cumulative+-- bucket @starts@ (length @buckets + 1@) and a mutable write @cursor@ copy of+-- @starts[0 .. buckets - 1]@.+{-# INLINE bucketOffsets #-}+bucketOffsets ::+  PrimMonad m =>+  Int ->+  ((Int -> m ()) -> m ()) ->+  m (MutablePrimArray (PrimState m) Int, MutablePrimArray (PrimState m) Int)+bucketOffsets buckets forItems = do+  starts <- newZeroedPrimArray (buckets + 1)+  forItems $ \b -> readPrimArray starts (b + 1) >>= writePrimArray starts (b + 1) . (+ 1)+  let prefix !b+        | b > buckets = pure ()+        | otherwise = do+            before <- readPrimArray starts (b - 1)+            readPrimArray starts b >>= writePrimArray starts b . (+ before)+            prefix (b + 1)+  prefix 1+  cursor <- newPrimArray buckets+  copyMutablePrimArray cursor 0 starts 0 buckets+  pure (starts, cursor)
+ lib/NanoUI/Internal/Uniforms.hs view
@@ -0,0 +1,360 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DefaultSignatures #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE TypeOperators #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | GPU uniform types and std140 byte-layout packing via 'GHC.Generics'.+--+-- A uniform record is defined once in Haskell and drives host-side byte+-- packing, paint-hash invalidation, and GPU uniform-block declarations across+-- GLSL 150, GLSL ES 300, SPIR-V, and MSL. Every packed block is zero-padded+-- to a 16-byte multiple so identical values always produce identical bytes+-- and hashes.+module NanoUI.Internal.Uniforms+  ( V3 (..)+  , V4 (..)+  , GpuType (..)+  , gpuTypeSize+  , alignUp+  , UniformField (..)+  , Uniforms (..)+  , GUniforms (..)+  , uniformLayout+  , uniformSize+  , packUniformBytes+  , packZeroedBytes+  , hashUniformBytes+  , sysUniformBytes+  , pokeSysUniforms+  ) where++import Control.Monad (when)+import Data.Bits (shiftR, xor)+import Data.Int (Int32)+import Data.Kind (Type)+import Data.Primitive.ByteArray+  ( ByteArray+  , MutableByteArray+  , fillByteArray+  , indexByteArray+  , newByteArray+  , sizeofByteArray+  , unsafeFreezeByteArray+  , writeByteArray+  )+import Data.Proxy (Proxy (..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word32, Word64)+import GHC.Exts (RealWorld)+import GHC.Float (castFloatToWord32)+import GHC.Generics+  ( (:*:) (..)+  , C1+  , D1+  , Generic (..)+  , K1 (..)+  , M1 (..)+  , S1+  , Selector (..)+  , U1 (..)+  )+import NanoUI.Internal.Types (Color (..), Rect (..), Size (..), V2 (..), unpackColorF)++-- | A three-component float vector for GPU uniforms and shader math.+data V3 = V3+  { v3X :: {-# UNPACK #-} !Float+  , v3Y :: {-# UNPACK #-} !Float+  , v3Z :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show, Generic)++-- | A four-component float vector for GPU uniforms and shader math.+data V4 = V4+  { v4X :: {-# UNPACK #-} !Float+  , v4Y :: {-# UNPACK #-} !Float+  , v4Z :: {-# UNPACK #-} !Float+  , v4W :: {-# UNPACK #-} !Float+  }+  deriving (Eq, Show, Generic)++-- | Primitive GPU field types supported inside std140 uniform blocks.+data GpuType+  = GFloat+  | GInt32+  | GUInt32+  | GBool+  | GVec2+  | GVec3+  | GVec4+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | Std140 byte size for a primitive GPU type.+{-# INLINE gpuTypeSize #-}+gpuTypeSize :: GpuType -> Int+gpuTypeSize gt = case gt of+  GFloat -> 4+  GInt32 -> 4+  GUInt32 -> 4+  GBool -> 4+  GVec2 -> 8+  GVec3 -> 12+  GVec4 -> 16++-- | Round @off@ upward to the next multiple of @align@ (a power of two).+{-# INLINE alignUp #-}+alignUp :: Int -> Int -> Int+alignUp align off =+  let !rem' = off `rem` align+   in if rem' == 0 then off else off + (align - rem')++-- | One flattened field of a std140 uniform block.+data UniformField = UniformField+  { ufName :: !Text+  , ufType :: !GpuType+  , ufOffset :: {-# UNPACK #-} !Int+  }+  deriving (Eq, Show)++-- | Write one 32-bit word at a 4-byte-aligned byte offset.+{-# INLINE writeWord32At #-}+writeWord32At :: MutableByteArray RealWorld -> Int -> Word32 -> IO ()+writeWord32At mba byteOff w = writeByteArray mba (byteOff `shiftR` 2) w++-- | Write one 32-bit float at a 4-byte-aligned byte offset.+{-# INLINE writeFloatAt #-}+writeFloatAt :: MutableByteArray RealWorld -> Int -> Float -> IO ()+writeFloatAt mba byteOff f = writeWord32At mba byteOff (castFloatToWord32 f)++-- | Join a prefix and a field name without leading underscores.+joinFieldName :: Text -> Text -> Text+joinFieldName pfx name+  | T.null pfx = name+  | T.null name = pfx+  | otherwise = pfx <> "_" <> name++-- | Types that can be packed into a GPU std140 uniform block.+--+-- Product records derive 'Uniforms' automatically via 'Generic':+--+-- > data GlowParams = GlowParams+-- >   { glowColor  :: Color+-- >   , glowRadius :: Float+-- >   }+-- >   deriving (Generic, Eq)+-- >   deriving anyclass (Uniforms)+class Eq u => Uniforms u where+  -- | Flatten @u@ into std140 fields starting at byte offset @off@, returning+  -- the next byte offset and the fields in declaration order.+  uniformFieldsAt :: Proxy u -> Text -> Int -> (Int, [UniformField])+  default uniformFieldsAt ::+    GUniforms (Rep u) =>+    Proxy u -> Text -> Int -> (Int, [UniformField])+  uniformFieldsAt _ = gUniformFieldsAt (Proxy :: Proxy (Rep u))++  -- | Pack @u@ into @mba@ at byte offset @base + off@ (with @base@ 16-byte+  -- aligned), returning the next byte offset relative to @base@.+  pokeUniformAt :: u -> MutableByteArray RealWorld -> Int -> Int -> IO Int+  default pokeUniformAt ::+    (Generic u, GUniforms (Rep u)) =>+    u -> MutableByteArray RealWorld -> Int -> Int -> IO Int+  pokeUniformAt u mba base off = gPokeUniformAt (from u) mba base off++-- | Generic derivation helper for product records.+class GUniforms (f :: Type -> Type) where+  gUniformFieldsAt :: Proxy f -> Text -> Int -> (Int, [UniformField])+  gPokeUniformAt :: f p -> MutableByteArray RealWorld -> Int -> Int -> IO Int++instance GUniforms U1 where+  gUniformFieldsAt _ _ off = (off, [])+  gPokeUniformAt U1 _ _ off = pure off++instance GUniforms f => GUniforms (D1 d f) where+  gUniformFieldsAt _ = gUniformFieldsAt (Proxy :: Proxy f)+  gPokeUniformAt (M1 x) = gPokeUniformAt x++instance GUniforms f => GUniforms (C1 c f) where+  gUniformFieldsAt _ = gUniformFieldsAt (Proxy :: Proxy f)+  gPokeUniformAt (M1 x) = gPokeUniformAt x++instance (Selector s, GUniforms f) => GUniforms (S1 s f) where+  gUniformFieldsAt _ pfx off =+    let sname = T.pack (selName (undefined :: S1 s f ()))+     in gUniformFieldsAt (Proxy :: Proxy f) (joinFieldName pfx sname) off+  gPokeUniformAt (M1 x) = gPokeUniformAt x++instance (GUniforms f, GUniforms g) => GUniforms (f :*: g) where+  gUniformFieldsAt _ pfx off =+    let (off1, fs1) = gUniformFieldsAt (Proxy :: Proxy f) pfx off+        (off2, fs2) = gUniformFieldsAt (Proxy :: Proxy g) pfx off1+     in (off2, fs1 <> fs2)+  gPokeUniformAt (x :*: y) mba base off = do+    off1 <- gPokeUniformAt x mba base off+    gPokeUniformAt y mba base off1++instance Uniforms a => GUniforms (K1 i a) where+  gUniformFieldsAt _ = uniformFieldsAt (Proxy :: Proxy a)+  gPokeUniformAt (K1 x) = pokeUniformAt x++instance Uniforms () where+  uniformFieldsAt _ _ off = (off, [])+  pokeUniformAt () _ _ off = pure off++{-# INLINE primField #-}+primField :: Int -> Int -> GpuType -> Text -> Int -> (Int, [UniformField])+primField align sz gt name off = let !o = alignUp align off in (o + sz, [UniformField name gt o])++{-# INLINE pokeWordUniform #-}+pokeWordUniform :: Word32 -> MutableByteArray RealWorld -> Int -> Int -> IO Int+pokeWordUniform w mba base off = let !o = alignUp 4 off in (o + 4) <$ writeWord32At mba (base + o) w++{-# INLINE pokeVec2 #-}+pokeVec2 :: Float -> Float -> MutableByteArray RealWorld -> Int -> Int -> IO Int+pokeVec2 x y mba base off = do+  let !o = alignUp 8 off+  writeFloatAt mba (base + o) x+  writeFloatAt mba (base + o + 4) y+  pure (o + 8)++{-# INLINE pokeVec4 #-}+pokeVec4 :: Float -> Float -> Float -> Float -> MutableByteArray RealWorld -> Int -> Int -> IO Int+pokeVec4 x y z w mba base off = do+  let !o = alignUp 16 off+  writeFloatAt mba (base + o) x+  writeFloatAt mba (base + o + 4) y+  writeFloatAt mba (base + o + 8) z+  writeFloatAt mba (base + o + 12) w+  pure (o + 16)++instance Uniforms Float where+  uniformFieldsAt _ = primField 4 4 GFloat+  pokeUniformAt f = pokeWordUniform (castFloatToWord32 f)++instance Uniforms Int32 where+  uniformFieldsAt _ = primField 4 4 GInt32+  pokeUniformAt n = pokeWordUniform (fromIntegral n)++instance Uniforms Word32 where+  uniformFieldsAt _ = primField 4 4 GUInt32+  pokeUniformAt = pokeWordUniform++instance Uniforms Bool where+  uniformFieldsAt _ = primField 4 4 GBool+  pokeUniformAt b = pokeWordUniform (if b then 1 else 0)++instance Uniforms V2 where+  uniformFieldsAt _ = primField 8 8 GVec2+  pokeUniformAt (V2 x y) = pokeVec2 x y++instance Uniforms V3 where+  uniformFieldsAt _ = primField 16 12 GVec3+  pokeUniformAt (V3 x y z) mba base off = do+    let !o = alignUp 16 off+    writeFloatAt mba (base + o) x+    writeFloatAt mba (base + o + 4) y+    writeFloatAt mba (base + o + 8) z+    pure (o + 12)++instance Uniforms V4 where+  uniformFieldsAt _ = primField 16 16 GVec4+  pokeUniformAt (V4 x y z w) = pokeVec4 x y z w++instance Uniforms Color where+  uniformFieldsAt _ = primField 16 16 GVec4+  pokeUniformAt col = let !(r, g, b, a) = unpackColorF col in pokeVec4 r g b a++instance Uniforms Rect where+  uniformFieldsAt _ = primField 16 16 GVec4+  pokeUniformAt (Rect x y w h) = pokeVec4 x y w h++instance Uniforms Size where+  uniformFieldsAt _ = primField 8 8 GVec2+  pokeUniformAt (Size w h) = pokeVec2 w h++instance (Uniforms a, Uniforms b) => Uniforms (a, b) where+  uniformFieldsAt _ pfx off =+    let (off1, fs1) = uniformFieldsAt (Proxy :: Proxy a) (joinFieldName pfx "a") off+        (off2, fs2) = uniformFieldsAt (Proxy :: Proxy b) (joinFieldName pfx "b") off1+     in (off2, fs1 <> fs2)+  pokeUniformAt (a, b) mba base off = do+    off1 <- pokeUniformAt a mba base off+    pokeUniformAt b mba base off1++instance (Uniforms a, Uniforms b, Uniforms c) => Uniforms (a, b, c) where+  uniformFieldsAt _ pfx off =+    let (off1, fs1) = uniformFieldsAt (Proxy :: Proxy a) (joinFieldName pfx "a") off+        (off2, fs2) = uniformFieldsAt (Proxy :: Proxy b) (joinFieldName pfx "b") off1+        (off3, fs3) = uniformFieldsAt (Proxy :: Proxy c) (joinFieldName pfx "c") off2+     in (off3, fs1 <> fs2 <> fs3)+  pokeUniformAt (a, b, c) mba base off = do+    off1 <- pokeUniformAt a mba base off+    off2 <- pokeUniformAt b mba base off1+    pokeUniformAt c mba base off2++-- | Flattened std140 field descriptors for uniform type @u@.+uniformLayout :: Uniforms u => Proxy u -> [UniformField]+uniformLayout p = snd (uniformFieldsAt p "" 0)++-- | Padded std140 byte size for uniform type @u@ (always a multiple of 16;+-- @0@ for @()@).+uniformSize :: Uniforms u => Proxy u -> Int+uniformSize p =+  let !raw = fst (uniformFieldsAt p "" 0)+   in if raw == 0 then 0 else alignUp 16 raw++-- | Allocate a zero-filled @sz@-byte buffer, run @fill@ when @sz > 0@, and freeze it.+{-# INLINE packZeroedBytes #-}+packZeroedBytes :: Int -> (MutableByteArray RealWorld -> IO a) -> IO ByteArray+packZeroedBytes !sz fill = do+  mba <- newByteArray sz+  when (sz > 0) (fillByteArray mba 0 sz 0 >> fill mba >> pure ())+  unsafeFreezeByteArray mba++-- | Pack @u@ into a zero-padded immutable std140 'ByteArray'.+packUniformBytes :: forall u. Uniforms u => u -> IO ByteArray+packUniformBytes u = packZeroedBytes (uniformSize (Proxy :: Proxy u)) (\mba -> pokeUniformAt u mba 0 0)++-- | Deterministic 64-bit FNV-1a hash over the 32-bit words of a packed+-- uniform 'ByteArray'. Because 'packUniformBytes' zeroes padding bytes,+-- equal uniform values produce identical hashes.+hashUniformBytes :: ByteArray -> Word64+hashUniformBytes ba = go 0 0xcbf29ce484222325+  where+    !wordsN = sizeofByteArray ba `shiftR` 2+    go !i !h+      | i >= wordsN = h+      | otherwise =+          let !w = indexByteArray ba i :: Word32+              !h' = (h `xor` fromIntegral w) * 0x100000001b3+           in go (i + 1) h'++-- | Size in bytes of the system uniform header prepended to every shader+-- uniform block: three @vec4@ values (@uRect@, @uUvRect@, @uMeta@).+sysUniformBytes :: Int+sysUniformBytes = 48++-- | Write the 48-byte system uniform header at byte offset @off@ (which must+-- be 4-byte aligned):+--+-- * bytes 0..15: @uRect@ (@nodeX, nodeY, nodeW, nodeH@) in logical pixels+-- * bytes 16..31: @uUvRect@ (@u0, v0, uSpan, vSpan@) in source target UVs+-- * bytes 32..47: @uMeta@ (@dpiScale, cornerRadius, targetW, targetH@)+pokeSysUniforms ::+  Rect ->+  Rect ->+  Float ->+  Float ->+  Float ->+  Float ->+  MutableByteArray RealWorld ->+  Int ->+  IO ()+pokeSysUniforms (Rect rx ry rw rh) (Rect u0 v0 us vs) scale radius tw th mba off = do+  _ <- pokeVec4 rx ry rw rh mba off 0+  _ <- pokeVec4 u0 v0 us vs mba (off + 16) 0+  _ <- pokeVec4 scale radius tw th mba (off + 32) 0+  pure ()
+ lib/NanoUI/Internal/Var.hs view
@@ -0,0 +1,355 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Reading and mutating 'Var's from the view, and tracking dependencies for+-- reruns and damage.+--+-- Within a pass, a tracked read ('readVar') stamps the part of the cell it+-- reads as observed and seen, and a widget bound to the 'Var' ('bindVar')+-- stamps its part as observed. Parts are record fields and list elements,+-- two levels deep ('lensSig'). A mutation that changes a part observed+-- earlier in the same pass is a backwards write: an earlier widget already+-- rendered the old value. In the first pass that reruns the view; in the+-- second it schedules a follow-up frame. What a change shows is damaged+-- like any other view output: the nodes whose text, value or style it+-- changed repaint ('NanoUI.Internal.Damage').+module NanoUI.Internal.Var+  ( newVar+  , useVar+  , useEnumVar+  , readVar+  , readCell+  , peekVar+  , writeVar+  , modifyVar+  , readVarIO+  , writeVarIO+  , modifyVarIO+  , withValue+  , Binding (..)+  , bindVar+  , bindVarBy+  , bindVarOn+  , requestRerun+  , beginVarPass+  , takeVarRerun+  , endVarFrame+  , lastFramePasses+  )+where++import Control.Monad (unless, when)+import Data.Bits (complement, (.&.))+import Data.IORef (atomicModifyIORef', readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.Primitive.PrimArray (readPrimArray, writePrimArray)+import Data.Proxy (Proxy (..))+import Data.Typeable (Typeable, typeRep)+import Data.Word (Word64)+import NanoUI.Internal.Context (Context (..), markDirty)+import NanoUI.Internal.Equality (eqByPtr, ptrEq)+import NanoUI.Internal.Id.Cursor (takeVarKey)+import NanoUI.Internal.Monad (NanoUI, askContext, liftIO, withContext)+import NanoUI.Internal.Var.Cell+import NanoUI.Internal.Var.Types++flagRerun :: Word64+flagRerun = 1++{-# INLINE frameSlot #-}+frameSlot :: Context -> Int -> IO Word64+frameSlot ctx = readPrimArray (ctxVarFrame ctx)++{-# INLINE setFlag #-}+setFlag :: Context -> Word64 -> IO ()+setFlag ctx = orWord (ctxVarFrame ctx) flagSlot++-- | Allocate a new mutable 'Var'. Create it once outside the view and pass it+-- in; calling 'newVar' inside the view would allocate a fresh 'Var' every+-- frame.+newVar :: a -> IO (Var a)+newVar a = (\c -> VarRef c Here) <$> newCell a++-- | Mutable 'Var' persisted at the current call-site slot, initialized to+-- @initial@ on first reach. Positional 'Var' slots are indexed separately from+-- widgets, so conditional widgets do not shift them; wrap a conditional+-- 'useVar' in 'NanoUI.scope'. Reinitializes to @initial@ if the slot+-- previously held a different type.+--+-- A slot lasts as long as the context, so hidden content keeps its state:+-- each 'NanoUI.withKey' key a 'useVar' ever ran under keeps one. For rows of+-- a collection whose keys keep coming, such as a feed, hold their state in a+-- 'NanoUI.Var.VarMap' and drop it with 'NanoUI.Var.retainVars'.+{-# INLINE useVar #-}+useVar :: VarSlot a => a -> NanoUI (Var a)+useVar = slotVar slotMatch slotWrap++-- | 'useVar' for an enumeration, stored by its 'Enum' index. An out-of-range+-- index decodes as @initial@, and a slot that held another enumeration+-- starts over.+useEnumVar :: forall a. (Bounded a, Enum a, Typeable a) => a -> NanoUI (Var a)+useEnumVar initial = do+  let ty = typeRep (Proxy @a)+  v <- slotVar (\case SEnum t v | t == ty -> Just v; _ -> Nothing) (SEnum ty) (fromEnum initial)+  let decode i+        | i >= fromEnum (minBound :: a) && i <= fromEnum (maxBound :: a) = toEnum i+        | otherwise = initial+  pure (zoomVar decode (\a _ -> fromEnum a) v)++-- | Look up or initialize the 'Var' at the next positional slot.+{-# INLINE slotVar #-}+slotVar :: (SlotVar -> Maybe (Var b)) -> (Var b -> SlotVar) -> b -> NanoUI (Var b)+slotVar match wrap initial = withContext $ \ctx -> do+  key <- takeVarKey (ctxIdCursor ctx)+  slots <- readIORef (ctxVarSlots ctx)+  case IM.lookup key slots >>= match of+    Just v -> pure v+    Nothing -> do+      v <- newVar initial+      writeIORef (ctxVarSlots ctx) $! IM.insert key (wrap v) slots+      pure v++-- | Read the current value and record the read for this pass: a later mutation+-- in the same pass triggers a rerun so this read observes the updated value.+-- Reading a 'Var' after the widgets that mutate it avoids a rerun.+readVar :: Var a -> NanoUI a+readVar (VarRef cell l) = readCell (lensSig l) cell l+readVar (VarConst a) = pure a++-- | 'readVar' of a cell through a path, recording the read as one of the+-- part @sig@ of the cell. A part already read whole in this pass records+-- nothing new.+readCell :: Sig -> Cell s -> Lens s a -> NanoUI a+readCell !sig cell@(Cell ref _) l = withContext $ \ctx -> do+  unless (isInert cell) $ do+    p <- frameSlot ctx passSlot+    when (p /= 0) $ do+      again <- seenWhole cell p sig+      unless again $ do+        addToSet cell obsSet p sig+        addToSet cell seenSet p sig+  peekLens l =<< readIORef ref++-- | Read the current value without recording a dependency. Use for+-- frame-to-frame state comparisons where a second pass in the same frame would+-- otherwise see the already-updated value. Do not use for rendering; use+-- 'readVar' instead.+peekVar :: Var a -> NanoUI a+peekVar v = liftIO (readVarIO v)++-- | Mutate the 'Var' in place to a new value. No-op if equal to the current value.+writeVar :: Eq a => Var a -> a -> NanoUI ()+writeVar v a = modifyVar v (const a)++-- | Mutate the 'Var' in place with a function. No-op if the result equals the+-- current value.+modifyVar :: Eq a => Var a -> (a -> a) -> NanoUI ()+modifyVar (VarConst _) _ = pure ()+modifyVar (VarRef cell l) f = withContext $ \ctx -> do+  touched <- modifyRoot cell l f eqByPtr+  mapM_ (noteWrite ctx cell) touched++-- | Read from any thread without recording a dependency.+readVarIO :: Var a -> IO a+readVarIO (VarConst a) = pure a+readVarIO (VarRef (Cell ref _) l) = peekLens l =<< readIORef ref++-- | Mutate a 'Var' from any thread or setup code. Does not wake the event+-- loop; call the action from 'NanoUI.askWake' after background mutations.+writeVarIO :: Eq a => Var a -> a -> IO ()+writeVarIO v a = modifyVarIO v (const a)++-- | 'modifyVar' from any thread.+modifyVarIO :: Eq a => Var a -> (a -> a) -> IO ()+modifyVarIO (VarConst _) _ = pure ()+modifyVarIO (VarRef cell l) f = mapM_ (const countChange) =<< modifyRoot cell l f eqByPtr++-- | Run @body@ with a temporary 'Var' initialized to @a@ and return the final+-- value. Used to adapt a widget that takes a 'Var' to external state;+-- mutations to this temporary 'Var' do not trigger reruns or damage.+withValue :: a -> (Var a -> NanoUI r) -> NanoUI (r, a)+withValue a body = do+  cell@(Cell ref _) <- liftIO (newInertCell a)+  r <- body (VarRef cell Here)+  a' <- liftIO (readIORef ref)+  pure (r, a')++-- | Atomically modify the part of a cell focused by a lens. Returns the+-- modified part signature ('overLensSig') if the value changed, or 'Nothing'+-- for unchanged or inert cells, and for an element whose key has left its+-- list, which the write leaves alone.+{-# INLINE modifyRoot #-}+modifyRoot :: Cell s -> Lens s a -> (a -> a) -> (a -> a -> Bool) -> IO (Maybe Sig)+modifyRoot cell@(Cell ref _) l f eq+  | isInert cell = do+      (root', touched) <- step <$> readIORef ref+      Nothing <$ mapM_ (\_ -> writeIORef ref root') touched+  | otherwise = atomicModifyIORef' ref step+  where+    step root = case previewLens l root of+      Just old+        | new <- f old+        , not (eq new old) ->+            case overLensSig l (const new) root of (!root', sig) -> (root', Just sig)+      _ -> (root, Nothing)++-- | A write outside a pass: count it, and ask for a frame to show it.+noteOutsidePass :: Context -> IO ()+noteOutsidePass ctx = countChange >> markDirty ctx++-- | Record a changing write to the part @sig@ made by view code.+noteWrite :: Context -> Cell s -> Sig -> IO ()+noteWrite ctx cell sig = do+  p <- frameSlot ctx passSlot+  if p == 0+    then noteOutsidePass ctx+    else noteInPass ctx =<< setHits cell obsSet p sig++-- | Record a write in a pass, rerunning when @observed@: something observed+-- the part earlier in the pass.+noteInPass :: Context -> Bool -> IO ()+noteInPass ctx observed = do+  when observed (backwards ctx)+  countChange++-- | A part observed earlier in this pass was mutated: rerun in pass 1, or+-- schedule a follow-up frame in pass 2.+backwards :: Context -> IO ()+backwards ctx = do+  passNo <- frameSlot ctx passNoSlot+  if passNo <= 1+    then setFlag ctx flagRerun+    else markDirty ctx++-- | How a widget bound to a Var draws it.+data Binding+  = -- | The widget draws the value it returns in the same pass.+    RenderFinal+  | -- | The widget draws the value it was given, so a change it makes needs+    -- the view run again to show.+    Conservative+  deriving (Eq, Show)++-- | 'bindVarBy' comparing with '=='.+{-# INLINE bindVar #-}+bindVar :: Eq a => Binding -> Var a -> (a -> NanoUI (r, a)) -> NanoUI r+bindVar = bindVarBy eqByPtr++-- | Bind a value-in, value-out widget to a 'Var': pass the current value and+-- write back the returned value. Edits to a 'constVar' are ignored. Direct+-- mutations to the same part during the widget's execution take precedence+-- over the widget's returned value, while mutations to sibling fields are+-- preserved.+{-# INLINE bindVarBy #-}+bindVarBy :: (a -> a -> Bool) -> Binding -> Var a -> (a -> NanoUI (r, a)) -> NanoUI r+bindVarBy eq mode = bindWith eq mode fst snd++-- | 'bindVar' for a widget whose result carries its value, read with+-- @value@.+{-# INLINE bindVarOn #-}+bindVarOn :: Eq a => Binding -> (r -> a) -> Var a -> (a -> NanoUI r) -> NanoUI r+bindVarOn mode value = bindWith eqByPtr mode id value++{-# INLINE bindWith #-}+bindWith :: (a -> a -> Bool) -> Binding -> (x -> r) -> (x -> a) -> Var a -> (a -> NanoUI x) -> NanoUI r+bindWith _ _ result _ (VarConst a) widget = result <$> widget a+bindWith eq mode result value (VarRef cell@(Cell ref _) l) widget = do+  ctx <- askContext+  let !sig = lensSig l+  (root0, a0, before) <- liftIO $ do+    root0 <- readIORef ref+    a0 <- peekLens l root0+    before <- observeBinding ctx cell sig+    pure (root0, a0, before)+  x <- widget a0+  let a1 = value x+  unless (eq a1 a0) $+    liftIO (commitBoundWrite ctx cell l eq mode sig root0 a0 a1 before)+  pure (result x)++-- | Write back a bound widget's changed value if the cell's part was not+-- concurrently overwritten during the widget's execution. Kept out of line so+-- unchanged bindings never allocate a write-back closure.+{-# NOINLINE commitBoundWrite #-}+commitBoundWrite :: Context -> Cell s -> Lens s a -> (a -> a -> Bool) -> Binding -> Sig -> s -> a -> a -> Bool -> IO ()+commitBoundWrite ctx cell@(Cell ref _) l eq mode !sig root0 a0 a1 !before = do+  root1 <- readIORef ref+  -- While the root is the one the widget was given, the part it shows is+  -- still a0. A write elsewhere in the cell (a sibling field, from a tab's+  -- body say) leaves that part alone, so only a write to the part itself+  -- wins over the widget's edit.+  untouched <- if ptrEq root1 root0 then pure True else eq a0 <$> peekLens l root1+  when untouched $+    mapM_ (noteBound ctx cell mode sig before) =<< modifyRoot cell l (const a1) eq++-- | Stamp the part @sig@ of a bound cell observed, returning whether+-- something observed it earlier in this pass.+observeBinding :: Context -> Cell s -> Sig -> IO Bool+observeBinding ctx cell !sig+  | isInert cell = pure False+  | otherwise = do+      p <- frameSlot ctx passSlot+      if p == 0+        then pure False+        else do+          hit <- setHits cell obsSet p sig+          addToSet cell obsSet p sig+          pure hit++-- | Record a bound widget's changing write to the part @wsig@. Its own node+-- shows the value, so only an earlier observer needs the view rerun. A+-- write that rekeyed a list element touched more than the widget observed+-- ('overLensSig'), so it is checked again.+noteBound :: Context -> Cell s -> Binding -> Sig -> Bool -> Sig -> IO ()+noteBound ctx cell mode sig before wsig = do+  p <- frameSlot ctx passSlot+  if p == 0+    then noteOutsidePass ctx+    else do+      observed <-+        if wsig == sig+          then do+            -- A tracked read inside the widget (a tab's body reading the+            -- tab Var) saw the value before this write, so it counts like+            -- one before the widget. The binding's own observation is in+            -- the obs set, so only the seen set can tell.+            (before ||) <$> setHits cell seenSet p sig+          else setHits cell obsSet p wsig+      noteInPass ctx (observed || mode == Conservative)++-- | Request a same-frame pass rerun, or a follow-up frame if already in the+-- second pass.+requestRerun :: Context -> IO ()+requestRerun ctx = do+  p <- frameSlot ctx passSlot+  if p == 0 then markDirty ctx else backwards ctx++-- | Start view pass @n@ of a frame. The first pass drops any requests left+-- by a frame an exception cut short. No handler is installed per frame,+-- since one costs an allocation every frame.+beginVarPass :: Context -> Int -> IO ()+beginVarPass ctx n = do+  t <- nextTick+  let arr = ctxVarFrame ctx+  writePrimArray arr passSlot t+  writePrimArray arr passNoSlot (fromIntegral n)+  when (n == 1) (writePrimArray arr flagSlot 0)++-- | Consume and return whether a pass rerun was requested.+takeVarRerun :: Context -> IO Bool+takeVarRerun ctx = do+  fs <- frameSlot ctx flagSlot+  writePrimArray (ctxVarFrame ctx) flagSlot (fs .&. complement flagRerun)+  pure (fs .&. flagRerun /= 0)++-- | Finish the frame's passes: record how many ran, and leave the pass, so+-- writes until the next frame count as outside one.+endVarFrame :: Context -> IO ()+endVarFrame ctx = do+  let arr = ctxVarFrame ctx+  writePrimArray arr lastPassesSlot =<< frameSlot ctx passNoSlot+  writePrimArray arr passSlot 0+  writePrimArray arr flagSlot 0++-- | How many view passes the last frame ran.+lastFramePasses :: Context -> IO Int+lastFramePasses ctx = fromIntegral <$> frameSlot ctx lastPassesSlot
+ lib/NanoUI/Internal/Var/Cell.hs view
@@ -0,0 +1,205 @@+{-# OPTIONS_HADDOCK not-home #-}+++-- | Mutable cell backing a 'NanoUI.Var.Var' and its per-pass read/mutation+-- bitmasks. Timestamps come from a single process-wide monotonic counter so+-- cells shared across sessions keep distinct pass stamps.+module NanoUI.Internal.Var.Cell+  ( Cell (..)+  , newCell+  , newInertCell+  , isInert+  , Sig (..)+  , allBits+  , obsSet+  , seenSet+  , setHits+  , seenWhole+  , addToSet+  , orWord+  , nextTick+  , countChange+  , varChangeCount+  , newStamps+  , passSlot+  , passNoSlot+  , flagSlot+  , lastPassesSlot+  , frameSlots+  )+where++import Control.Monad (when)+import Control.Monad.Primitive (RealWorld)+import Data.Bits (complement, (.&.), (.|.))+import Data.IORef (IORef, newIORef)+import Data.Primitive.ByteArray (MutableByteArray (..), newByteArray, writeByteArray)+import Data.Primitive.PrimArray (MutablePrimArray, readPrimArray, sameMutablePrimArray, setPrimArray, writePrimArray)+import Data.Word (Word64)+import GHC.Exts (Int (..), atomicReadIntArray#, fetchAddIntArray#, (+#))+import GHC.IO (IO (..))+import System.IO.Unsafe (unsafePerformIO)+import NanoUI.Internal.Types (newZeroedPrimArray)++-- | Mutable state, and its 'obsSet' and 'seenSet' in a UI-thread stamp+-- array.+data Cell s = Cell+  {-# UNPACK #-} !(IORef s)+  {-# UNPACK #-} !(MutablePrimArray RealWorld Word64)++-- | Two-level bit signature of the portion of a cell addressed by a lens path:+-- the first-level record field or list key bitmask, the second-level bitmask+-- ('allBits' when the path stops at one level), and whether the path is still+-- open, so that a further step can narrow it.+-- An opaque step such as 'NanoUI.Var.zoomVar' covers all bits beneath its+-- prefix and marks the signature closed so further steps leave it unchanged.+--+-- Because hashes map multiple fields or keys into 64 bits, bitmask intersection+-- is conservative: non-overlapping paths may collide, while overlapping paths+-- always intersect.+data Sig = Sig {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64 !Bool+  deriving (Eq)++-- | A second-level mask with every bit set, meaning the path stops at the+-- first level ('Sig').+allBits :: Word64+allBits = complement 0++-- | Whether @sig@ overlaps a set of paths, given as the first-level bits of+-- those that stop at the first level (@whole@), and the first- and+-- second-level bits of those that go on (@firsts@, @seconds@).+{-# INLINE sigHits #-}+sigHits :: Word64 -> Word64 -> Word64 -> Sig -> Bool+sigHits whole firsts seconds (Sig a b _)+  | b == allBits = (whole .|. firsts) .&. a /= 0+  | otherwise = whole .&. a /= 0 || (firsts .&. a /= 0 && seconds .&. b /= 0)++-- | Where each set starts: a tick, then the @whole@, @firsts@ and+-- @seconds@ bits ('sigHits').+obsSet, seenSet, stampWords :: Int+obsSet = 0+seenSet = 4+stampWords = 8++-- | Slots of a context's frame record ('NanoUI.Internal.Context.ctxVarFrame'):+-- the current pass's tick (0 outside a pass), the pass number, request+-- flags, and the last frame's pass count.+passSlot, passNoSlot, flagSlot, lastPassesSlot, frameSlots :: Int+passSlot = 0+passNoSlot = 1+flagSlot = 2+lastPassesSlot = 3+frameSlots = 4++-- | A zeroed array of @n@ stamp words.+newStamps :: Int -> IO (MutablePrimArray RealWorld Word64)+newStamps = newZeroedPrimArray++-- | A cell holding @s@, with its own zeroed stamps.+newCell :: s -> IO (Cell s)+newCell s = Cell <$> newIORef s <*> newStamps stampWords++-- | Stamps shared by every inert cell and never written: an inert cell+-- ('NanoUI.Var.withValue') takes part in no rerun, damage or wake.+{-# NOINLINE inertStamps #-}+inertStamps :: MutablePrimArray RealWorld Word64+inertStamps = unsafePerformIO (newStamps stampWords)++-- | A cell holding @s@ that uses 'inertStamps', so it records no+-- observation.+newInertCell :: s -> IO (Cell s)+newInertCell s = do+  ref <- newIORef s+  pure (Cell ref inertStamps)++-- | Whether the cell was made by 'newInertCell'.+{-# INLINE isInert #-}+isInert :: Cell s -> Bool+isInert (Cell _ stamps) = sameMutablePrimArray stamps inertStamps++{-# INLINE readStamp #-}+readStamp :: Cell s -> Int -> IO Word64+readStamp (Cell _ stamps) = readPrimArray stamps++{-# INLINE writeStamp #-}+writeStamp :: Cell s -> Int -> Word64 -> IO ()+writeStamp (Cell _ stamps) = writePrimArray stamps++-- | Whether the set at @set@, stamped with tick @t@, holds a path that+-- overlaps @sig@. A set stamped with another tick is empty.+{-# INLINE setHits #-}+setHits :: Cell s -> Int -> Word64 -> Sig -> IO Bool+setHits cell set t sig = do+  t0 <- readStamp cell set+  if t0 /= t then pure False else bitsHit cell (set + 1) sig++bitsHit :: Cell s -> Int -> Sig -> IO Bool+bitsHit cell at sig =+  sigHits <$> readStamp cell at <*> readStamp cell (at + 1) <*> readStamp cell (at + 2) <*> pure sig++-- | Whether 'seenSet' for pass @p@ already covers all first-level bits of a+-- single-level @sig@, so a repeat read records nothing new.+{-# INLINE seenWhole #-}+seenWhole :: Cell s -> Word64 -> Sig -> IO Bool+seenWhole cell p (Sig a b _)+  | b /= allBits = pure False+  | otherwise = do+      t0 <- readStamp cell seenSet+      if t0 /= p then pure False else (\w -> w .&. a == a) <$> readStamp cell (seenSet + 1)++-- | Add the path to the set at @set@ under tick @t@, emptying it first if it+-- holds another tick's paths.+{-# INLINE addToSet #-}+addToSet :: Cell s -> Int -> Word64 -> Sig -> IO ()+addToSet cell set t sig = do+  t0 <- readStamp cell set+  when (t0 /= t) (writeStamp cell set t)+  addBits cell (set + 1) (t0 /= t) sig++-- | Add a path's bits to the three bit slots from @at@, clearing them first+-- when @fresh@.+addBits :: Cell s -> Int -> Bool -> Sig -> IO ()+addBits (Cell _ stamps) at fresh (Sig a b _) = do+  when fresh (setPrimArray stamps at 3 0)+  if b == allBits+    then orWord stamps at a+    else orWord stamps (at + 1) a >> orWord stamps (at + 2) b++-- | Set bits in one word of a prim array, writing only when that changes it.+{-# INLINE orWord #-}+orWord :: MutablePrimArray RealWorld Word64 -> Int -> Word64 -> IO ()+orWord arr i x = do+  old <- readPrimArray arr i+  when (old .|. x /= old) (writePrimArray arr i (old .|. x))++-- | Process-wide monotonic tick counter, then the count of changes any cell+-- has had ('varChangeCount'), each in a machine word.+{-# NOINLINE tickClock #-}+tickClock :: MutableByteArray RealWorld+tickClock = unsafePerformIO $ do+  arr <- newByteArray 16+  writeByteArray arr 0 (1 :: Int)+  writeByteArray arr 1 (0 :: Int)+  pure arr++-- | How many changes any cell has had, process-wide. A window that ran its+-- view when this was lower may show a value since changed, which is how a+-- backend with several windows knows to run the others' views again.+varChangeCount :: IO Word64+varChangeCount = case tickClock of+  MutableByteArray arr -> IO $ \s -> case atomicReadIntArray# arr 1# s of+    (# s', n #) -> (# s', fromIntegral (I# n) #)++-- | Count a change to a cell ('varChangeCount').+{-# INLINE countChange #-}+countChange :: IO ()+countChange = case tickClock of+  MutableByteArray arr -> IO $ \s -> case fetchAddIntArray# arr 1# 1# s of+    (# s', _ #) -> (# s', () #)++-- | Atomically increment and return the next tick without boxing an 'IORef'.+{-# INLINE nextTick #-}+nextTick :: IO Word64+nextTick = case tickClock of+  MutableByteArray arr -> IO $ \s -> case fetchAddIntArray# arr 0# 1# s of+    (# s', old #) -> (# s', fromIntegral (I# (old +# 1#)) #)
+ lib/NanoUI/Internal/Var/Generic.hs view
@@ -0,0 +1,95 @@+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Reading and replacing one record field through "GHC.Generics", for the+-- @v.field@ focus on a 'NanoUI.Var.Var'. The path to the field is found at+-- compile time, so with optimisation a focus compiles to a plain selector+-- and record update.+module NanoUI.Internal.Var.Generic+  ( Side (..)+  , FieldPath+  , GFocus (..)+  , PathIx (..)+  )+where++import Data.Kind (Type)+import GHC.Generics+import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError)++-- | Which half of a product the field is in.+data Side = SL | SR++-- | The path to field @x@ in the representation of record @s@.+type family FieldPath (x :: Symbol) s (rep :: Type -> Type) :: [Side] where+  FieldPath x s (D1 _ (C1 _ f)) = Found x s (Search x f)+  FieldPath x s (D1 _ _) =+    TypeError+      ( 'Text "Cannot focus a Var on field ‘" ':<>: 'Text x ':<>: 'Text "’ of " ':<>: 'ShowType s ':<>: 'Text ":"+          ':$$: 'Text "only a type with exactly one constructor can be focused by field."+      )++type family Search (x :: Symbol) (f :: Type -> Type) :: Maybe [Side] where+  Search x (S1 ('MetaSel ('Just x) _ _ _) _) = 'Just '[]+  Search x (S1 _ _) = 'Nothing+  Search x (l :*: r) = Pick (Search x l) (Search x r)+  Search x U1 = 'Nothing++type family Pick (l :: Maybe [Side]) (r :: Maybe [Side]) :: Maybe [Side] where+  Pick ('Just p) _ = 'Just ('SL ': p)+  Pick 'Nothing ('Just p) = 'Just ('SR ': p)+  Pick 'Nothing 'Nothing = 'Nothing++type family Found (x :: Symbol) s (m :: Maybe [Side]) :: [Side] where+  Found _ _ ('Just p) = p+  Found x s 'Nothing =+    TypeError ('Text "Cannot focus a Var on field ‘" ':<>: 'Text x ':<>: 'Text "’: " ':<>: 'ShowType s ':<>: 'Text " has no such field.")++-- | Get and set the field at path @p@ of a representation.+class GFocus (p :: [Side]) (f :: Type -> Type) a | p f -> a where+  gget :: f x -> a+  gset :: a -> f x -> f x++instance GFocus '[] (M1 S m (K1 i a)) a where+  {-# INLINE gget #-}+  gget (M1 (K1 a)) = a+  {-# INLINE gset #-}+  gset a _ = M1 (K1 a)++instance GFocus p f a => GFocus p (M1 D m (M1 C c f)) a where+  {-# INLINE gget #-}+  gget (M1 (M1 f)) = gget @p f+  {-# INLINE gset #-}+  gset a (M1 (M1 f)) = M1 (M1 (gset @p a f))++instance GFocus p l a => GFocus ('SL ': p) (l :*: r) a where+  {-# INLINE gget #-}+  gget (l :*: _) = gget @p l+  {-# INLINE gset #-}+  gset a (l :*: r) = gset @p a l :*: r++instance GFocus p r a => GFocus ('SR ': p) (l :*: r) a where+  {-# INLINE gget #-}+  gget (_ :*: r) = gget @p r+  {-# INLINE gset #-}+  gset a (l :*: r) = l :*: gset @p a r++-- | A number for a path, unique among the fields of one record: the path's+-- sides read as binary digits after a leading one.+class PathIx (p :: [Side]) where+  pathIx :: Int -> Int++instance PathIx '[] where+  {-# INLINE pathIx #-}+  pathIx acc = acc++instance PathIx p => PathIx ('SL ': p) where+  {-# INLINE pathIx #-}+  pathIx acc = pathIx @p (2 * acc)++instance PathIx p => PathIx ('SR ': p) where+  {-# INLINE pathIx #-}+  pathIx acc = pathIx @p (2 * acc + 1)
+ lib/NanoUI/Internal/Var/List.hs view
@@ -0,0 +1,58 @@+-- | A Var for each element of a list held in a Var, found by key.+module NanoUI.Internal.Var.List+  ( forEachVar+  , withElemVars+  )+where++import Data.Foldable (for_)+import Data.Hashable (Hashable, hash)+import NanoUI.Internal.Monad (NanoUI, keyedTag, liftIO)+import NanoUI.Internal.Var (readCell, readVar)+import NanoUI.Internal.Var.Types (Lens (..), Var (..), newElemCtx, stepBit, structSig)++-- | Run @body@ for each element of the list under 'withKey' of its key,+-- passing a 'Var' focused on that element. Each element 'Var' is addressed by+-- key rather than index: reordering the list preserves each element's target,+-- and mutating an element whose key was removed is a no-op. Keys must be+-- unique.+--+-- The outer pass records only the list's keys and order, so mutating a single+-- element in place does not invalidate sibling rows. Rows are told apart by+-- one of 63 bits of their key's hash, though: past about 63 rows, or for keys+-- that share a bit (such as 'Int' keys 64 apart), a row's edit also counts as+-- one to the earlier rows that share its bit. That reruns the view, and+-- repaints it whole when those rows 'readVar' the field it edits.+--+-- As under 'NanoUI.withKey', what a row keeps with 'NanoUI.Var.useVar' or in+-- its widgets stays after its key leaves the list.+--+-- > forEachVar todoId app.todos $ \todo -> checkbox "" todo.done+forEachVar :: Hashable k => (a -> k) -> Var [a] -> (Var a -> NanoUI ()) -> NanoUI ()+forEachVar key v body = do+  (xs, at) <- elemVars True key v+  -- One hash per key serves both the row's id, as 'withKey' would make it,+  -- and its Var.+  for_ xs $ \x -> let !k = key x; !h = hash k in keyedTag (fromIntegral h) (body (at k h x))++-- | Read the full list and pass @body@ both the elements and a key-addressed+-- 'Var' constructor. Use when filtering, reordering, or inspecting adjacent+-- elements; wrap each rendered row in 'withKey' manually.+--+-- Because @body@ receives the element values directly, this records a read of+-- every element in the list.+withElemVars :: Hashable k => (a -> k) -> Var [a] -> ([a] -> (a -> Var a) -> NanoUI r) -> NanoUI r+withElemVars key v body = do+  (xs, at) <- elemVars False key v+  body xs (\x -> let k = key x in at k (hash k) x)++-- | Read the list and build an element 'Var' constructor from a key, its hash,+-- and its initial value. When @keysOnly@ is 'True', only the list's structure+-- (keys and order) is recorded as read.+elemVars :: Hashable k => Bool -> (a -> k) -> Var [a] -> NanoUI ([a], k -> Int -> a -> Var a)+elemVars keysOnly key v = case v of+  VarConst xs -> pure (xs, \_ _ x -> VarConst x)+  VarRef cell l -> do+    xs <- if keysOnly then readCell (structSig l) cell l else readVar v+    ec <- liftIO (newElemCtx l key xs)+    pure (xs, \k h x -> VarRef cell (Elem (stepBit h) ec k x))
+ lib/NanoUI/Internal/Var/Map.hs view
@@ -0,0 +1,57 @@+-- | Keyed table of mutable 'Var's for dynamic children, allocated on first+-- lookup and removed explicitly by the application.+module NanoUI.Internal.Var.Map+  ( VarMap+  , newVarMap+  , varAt+  , dropVar+  , retainVars+  )+where++import Control.Monad (when)+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as HM+import Data.Hashable (Hashable)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)+import NanoUI.Internal.Context (damageFull)+import NanoUI.Internal.Monad (NanoUI, liftIO, withContext)+import NanoUI.Internal.Var (newVar, requestRerun)+import NanoUI.Internal.Var.Types (Var)++-- | Map from keys to mutable 'Var's. Unlike positional 'Var's, entries persist+-- across frames until explicitly removed with 'dropVar' or 'retainVars'.+newtype VarMap k a = VarMap (IORef (HashMap k (Var a)))++-- | An empty map.+newVarMap :: IO (VarMap k a)+newVarMap = VarMap <$> newIORef HM.empty++-- | Look up the 'Var' for @k@, allocating it with @initial@ if absent.+varAt :: Hashable k => VarMap k a -> k -> a -> NanoUI (Var a)+varAt (VarMap ref) k initial = liftIO $ do+  m <- readIORef ref+  case HM.lookup k m of+    Just v -> pure v+    Nothing -> do+      v <- newVar initial+      writeIORef ref $! HM.insert k v m+      pure v++-- | Remove the 'Var' at @k@ so a subsequent 'varAt' allocates a fresh one, and+-- schedule a full rerun and repaint.+dropVar :: Hashable k => VarMap k a -> k -> NanoUI ()+dropVar (VarMap ref) k = forgetWhere ref (HM.member k) (HM.delete k)++-- | Retain only entries whose keys satisfy the predicate. Dropping anything+-- schedules a rerun and a full repaint, as 'dropVar' does; a call that drops+-- nothing does neither.+retainVars :: (k -> Bool) -> VarMap k a -> NanoUI ()+retainVars keep (VarMap ref) = forgetWhere ref (any (not . keep) . HM.keys) (HM.filterWithKey (\k _ -> keep k))++forgetWhere :: IORef (HashMap k v) -> (HashMap k v -> Bool) -> (HashMap k v -> HashMap k v) -> NanoUI ()+forgetWhere ref changes f = withContext $ \ctx -> do+  dropped <- atomicModifyIORef' ref (\m -> if changes m then (f m, True) else (m, False))+  -- A newly allocated replacement Var has no prior mutation stamp, so force a+  -- rerun and full damage when any entry is removed.+  when dropped (damageFull ctx >> requestRerun ctx)
+ lib/NanoUI/Internal/Var/Types.hs view
@@ -0,0 +1,257 @@+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | The 'Var' handle: a constant, or a cell plus a path into its value, with+-- the paths' reads and writes, the list-element index, and the positional+-- slot types. The view's reads and writes, and what they cost, live in+-- "NanoUI.Internal.Var".+module NanoUI.Internal.Var.Types+  ( Var (..)+  , constVar+  , Lens (..)+  , ElemCtx (..)+  , viewLens+  , previewLens+  , overLensSig+  , peekLens+  , zoomVar+  , zoomVarL+  , fieldLens+  , newElemCtx+  , stepBit+  , lensSig+  , structSig+  , VarSlot (..)+  , SlotVar (..)+  )+where++import Data.Bits (bit, (.&.))+import Data.Functor.Const (Const (..))+import Data.Functor.Identity (Identity (..))+import Data.HashMap.Strict qualified as HM+import Data.Hashable (Hashable)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.List (find)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Typeable (TypeRep)+import Data.Word (Word64)+import GHC.Generics (Generic (..))+import GHC.Records (HasField (..))+import GHC.TypeLits (Symbol)+import NanoUI.Internal.Derived (SortCol)+import NanoUI.Internal.Equality (ptrEq)+import NanoUI.Internal.Var.Cell (Cell, Sig (..), allBits)+import NanoUI.Internal.Var.Generic (FieldPath, GFocus (..), PathIx (..))++-- | Mutable state handle (a cell and lens path) or read-only constant passed+-- to widgets.+--+-- * 'NanoUI.Var.newVar' and 'NanoUI.Var.useVar' create mutable 'Var's that+--   widgets mutate in place.+-- * @'constVar' x@ is a read-only constant; widget edits to it are discarded.+--+-- @v.field@ focuses a 'Var' on one field of its record, for any single-constructor+-- record with a 'Generic' instance.+data Var a where+  VarConst :: a -> Var a+  VarRef :: {-# UNPACK #-} !(Cell s) -> !(Lens s a) -> Var a++-- | Read-only 'Var' with constant value @x@; widget edits to it are ignored.+-- Use with primed widget variants to handle updates manually from the response:+--+-- > allDone <- all todoDone <$> readVar todos+-- > r <- checkbox' "All done" (constVar allDone)+-- > when (respChanged r) (modifyVar todos (map (\t -> t {todoDone = not allDone})))+constVar :: a -> Var a+constVar = VarConst++-- | The path from a cell's value to the part a Var shows. Each step after+-- 'Here' carries its bit for 'lensSig': a record field's or a list key's,+-- or 0 for a step to an unknown part.+data Lens s a where+  Here :: Lens a a+  Field :: {-# UNPACK #-} !Word64 -> !(Lens s b) -> (b -> a) -> (a -> b -> b) -> Lens s a+  Elem :: {-# UNPACK #-} !Word64 -> !(ElemCtx s k a) -> !k -> a -> Lens s a++-- | One list's elements, found by key: the list as it was when the elements+-- were handed out, and an index of the current list built on first need.+data ElemCtx s k a where+  ElemCtx :: Hashable k => !(Lens s [a]) -> (a -> k) -> [a] -> !(IORef (Maybe ([a], HM.HashMap k a))) -> ElemCtx s k a++-- | An 'ElemCtx' for the list at the lens, keying elements with @key@, with+-- an empty key index.+newElemCtx :: Hashable k => Lens s [a] -> (a -> k) -> [a] -> IO (ElemCtx s k a)+newElemCtx l key xs = ElemCtx l key xs <$> newIORef Nothing++-- | The part of @s@ a lens shows. An element whose key has left the list+-- shows the value it had when it was handed out.+viewLens :: Lens s a -> s -> a+viewLens Here s = s+viewLens (Field _ l g _) s = g (viewLens l s)+viewLens (Elem _ (ElemCtx l key _ _) k snap) s =+  fromMaybe snap (find ((== k) . key) (viewLens l s))++-- | The part of @s@ a lens shows, or 'Nothing' when its path goes through an+-- element whose key has left the list, which a write cannot reach.+previewLens :: Lens s a -> s -> Maybe a+previewLens Here s = Just s+previewLens (Field _ l g _) s = g <$> previewLens l s+previewLens (Elem _ (ElemCtx l key _ _) k _) s = find ((== k) . key) =<< previewLens l s++-- | Update the part of @s@ focused by the lens, returning the updated root and+-- the modified part signature ('lensSig'): the lens's own part or, when the+-- update changed a list element's key, the outermost affected list (including+-- keys and order). Updating an element whose key is no longer in the list is a+-- no-op. Keys are unique, so only the elements before the modified one are+-- copied.+overLensSig :: Lens s a -> (a -> a) -> s -> (s, Sig)+overLensSig l f s = case overPath l (\a -> (f a, Nothing)) s of+  (s', rekeyed) -> (s', fromMaybe (lensSig l) rekeyed)++-- | 'overLensSig' over a change that may itself report a rekeyed list.+overPath :: Lens s a -> (a -> (a, Maybe Sig)) -> s -> (s, Maybe Sig)+overPath Here f s = f s+overPath (Field _ l g set) f s = overPath l (\b -> case f (g b) of (!a, w) -> (set a b, w)) s+overPath (Elem _ (ElemCtx l key _ _) k _) f s = overPath l update s+  where+    update xs = case break ((== k) . key) xs of+      (before, x : after) -> case f x of+        (!y, w) -> (before ++ y : after, if key y == k then w else Just (lensSig l))+      (_, []) -> (xs, Nothing)++-- | 'viewLens', using an element's index instead of a linear search: the+-- snapshot when the list is the one handed out, else an index of the+-- current list, built once per list. Parts are returned evaluated, so the+-- list compares by pointer with the one handed out.+peekLens :: Lens s a -> s -> IO a+peekLens Here s = pure s+peekLens (Field _ l g _) s = do+  b <- peekLens l s+  pure $! g b+peekLens (Elem _ (ElemCtx l key xs0 cache) k snap) s = do+  !xs <- peekLens l s+  if ptrEq xs xs0+    then pure snap+    else do+      cached <- readIORef cache+      index <- case cached of+        Just (ys, ix) | ptrEq ys xs -> pure ix+        _ -> do+          -- The first of equal keys wins, as in 'viewLens'.+          let !ix = HM.fromListWith (\_ old -> old) [(key x, x) | x <- xs]+          writeIORef cache (Just (xs, ix))+          pure ix+      pure (HM.findWithDefault snap k index)++-- | The part of the cell a path touches: its first two steps narrow it,+-- and a step to an unknown part closes it.+lensSig :: Lens s a -> Sig+lensSig Here = Sig allBits allBits True+lensSig (Field step l _ _) = narrow step (lensSig l)+lensSig (Elem step (ElemCtx l _ _ _) _ _) = narrow step (lensSig l)++narrow :: Word64 -> Sig -> Sig+narrow step (Sig a b open)+  | step == 0 || not open = Sig a b False+  | a == allBits = Sig step allBits True+  | otherwise = Sig a step False++-- | The part of the cell that holds a list's keys and order, apart from+-- what its elements hold, for a reader that only lays out one row per key.+-- It takes a bit no field or key takes, at the list's level.+structSig :: Lens s [a] -> Sig+structSig l = case lensSig l of+  Sig a _ True+    | a == allBits -> Sig structBit allBits False+    | otherwise -> Sig a structBit False+  sig -> sig++-- | The bit only 'structSig' takes.+structBit :: Word64+structBit = bit 63++-- | A field's or key's bit, from a number such as a key's hash: any bit but+-- 'structBit'.+{-# INLINE stepBit #-}+stepBit :: Int -> Word64+stepBit n = let i = n .&. 63 in bit (if i == 63 then 62 else i)++-- | Focus a Var on part of its value, given how to read the part and how to+-- replace it. Writes through the result change that part of the whole.+--+-- > draft <- zoomVar fst (\a (_, b) -> (a, b)) pair+--+-- Where @v.field@ is known to touch one field, the part this shows is+-- unknown, so a write through it counts as a write to all of @v@ when+-- deciding what it costs.+{-# INLINE zoomVar #-}+zoomVar :: (s -> a) -> (a -> s -> s) -> Var s -> Var a+zoomVar = zoomStep 0++-- | 'zoomVar' with the step's bit for 'lensSig'.+{-# INLINE zoomStep #-}+zoomStep :: Word64 -> (s -> a) -> (a -> s -> s) -> Var s -> Var a+zoomStep _ g _ (VarConst s) = VarConst (g s)+zoomStep step g set (VarRef cell l) = VarRef cell (Field step l g set)++-- | 'zoomVar' from a van Laarhoven lens, such as one from @lens@ or+-- @microlens@.+{-# INLINE zoomVarL #-}+zoomVarL :: (forall f. Functor f => (a -> f a) -> s -> f s) -> Var s -> Var a+zoomVarL l = zoomVar (getConst . l Const) (\a -> runIdentity . l (\_ -> Identity a))++instance (Generic s, GFocus (FieldPath x s (Rep s)) (Rep s) a, PathIx (FieldPath x s (Rep s))) => HasField (x :: Symbol) (Var s) (Var a) where+  {-# INLINE getField #-}+  getField = uncurry (zoomStep (stepBit (pathIx @(FieldPath x s (Rep s)) 1))) (fieldLens @x)++-- | How to read field @x@ of @s@ and how to replace it, found through+-- "GHC.Generics"; with optimisation, a selector and a record update.+{-# INLINE fieldLens #-}+fieldLens :: forall x s a. (Generic s, GFocus (FieldPath x s (Rep s)) (Rep s) a) => (s -> a, a -> s -> s)+fieldLens = (gget @(FieldPath x s (Rep s)) . from, \a -> to . gset @(FieldPath x s (Rep s)) a . from)++-- | A positional Var as the slot table keeps it, tagged with its type so a+-- slot that changes type starts over instead of being misread.+data SlotVar+  = SInt !(Var Int)+  | SDouble !(Var Double)+  | SFloat !(Var Float)+  | SBool !(Var Bool)+  | SText !(Var Text)+  | -- | An enumeration's index, with the enumeration's type.+    SEnum !TypeRep !(Var Int)+  | SSort !(Var SortCol)++-- | Types a positional 'NanoUI.Var.useVar' can hold. For an enumeration,+-- use 'NanoUI.Var.useEnumVar'; for any other type, 'NanoUI.Var.newVar'.+class VarSlot a where+  slotWrap :: Var a -> SlotVar+  slotMatch :: SlotVar -> Maybe (Var a)++instance VarSlot Int where+  slotWrap = SInt+  slotMatch = \case SInt v -> Just v; _ -> Nothing++instance VarSlot Double where+  slotWrap = SDouble+  slotMatch = \case SDouble v -> Just v; _ -> Nothing++instance VarSlot Float where+  slotWrap = SFloat+  slotMatch = \case SFloat v -> Just v; _ -> Nothing++instance VarSlot Bool where+  slotWrap = SBool+  slotMatch = \case SBool v -> Just v; _ -> Nothing++instance VarSlot Text where+  slotWrap = SText+  slotMatch = \case SText v -> Just v; _ -> Nothing++instance VarSlot SortCol where+  slotWrap = SSort+  slotMatch = \case SSort v -> Just v; _ -> Nothing
+ lib/NanoUI/Internal/WidgetText.hs view
@@ -0,0 +1,593 @@+-- | Widget labels, numeric/color formatting, and packed node-style encodings+-- shared by construction, layout, and painting.+module NanoUI.Internal.WidgetText+  ( treeEncodeStyle+  , treeDecodeStyle+  , treeDecodeStripe+  , textInputFieldText+  , textInputMinWidth+  , textInputFieldHeight+  , textInputFlagSearch+  , textInputFlagSelectable+  , textInputFlagPassword+  , textInputFlagNumeric+  , numericStepperW+  , numericTextClip+  , numericStepperRects+  , comboTextClip+  , searchInputReserveW+  , searchInputTextClip+  , textClipBetween+  , searchInputIconRects+  , selectDisplayText+  , selectChevronReserve+  , selectChevronCenterX+  , colorPickerGap+  , colorPickerSvH+  , colorToHex+  , colorToHexA+  , colorFromHex+  , colorPickerParseHex+  , buttonFlagClose+  , buttonCloseTrailing+  , buttonCloseTab+  , buttonFlagTable+  , buttonFlagMenu+  , buttonFlagMenuBar+  , buttonFlagContent+  , buttonFlagChoice+  , buttonFlagRow+  , ButtonKind (..)+  , buttonKindOf+  , containerFlagInert+  , containerFlagClip+  , containerFlagShaderEffect+  , containerFlagButtonGroup+  , hasFlag+  , tableSortLane+  , tableHeaderPadX+  , tableStripeColor+  , rowStripe+  , stripeBits+  , panelSurface+  , tableStripeInset+  , stripeColor+  , packTextNodeStyle+  , textNodeFontKey+  , textNodeFontVariant+  , textNodeFontTone+  , textNodeFontWeight+  , textNodeFontStyle+  , textNodeTextDecoration+  , textNodeFontTabular+  , textNodeEllipsis+  , textNodeSingleLine+  , tableSortMarkOf+  , buttonVisualStyle+  , labelFontStyle+  , labelColor+  , buttonToneStyle+  , buttonToneOf+  , tabEncodeStyle+  , tabDecodeStyle+  , tabLabelAtStart+  , tabHeaderPadX+  , TabChrome (..)+  , tabChromeEncode+  , tabChromeDecode+  ) where++import Data.Bits ((.&.), (.|.), finiteBitSize, shiftL, shiftR, xor)+import Data.Char (digitToInt, isHexDigit)+import Data.Maybe (fromMaybe)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, smallArrayFromList)+import Data.Text (Text)+import Data.Word (Word8, Word64)+import GHC.Float (castFloatToWord32)+import Numeric (showHex)+import NanoUI.Internal.Font (FontMetrics (..), controlPadY, fmLineHeight, tableCellInset, widgetContentInset)+import NanoUI.Internal.Layout.Arena (labelFontShift)+import NanoUI.Internal.StyleBits (BitField (..), decodeStyleEnum)+import qualified NanoUI.Internal.StyleBits as SB+import NanoUI.Internal.Style (FontStyle (..), FontVariant (..), FontWeight (..), Layout (..), Style (..), TextDecoration (..), TextEllipsis (..), Theme (..), Tone (..), toneColor)+import NanoUI.Internal.Types (Color (..), Rect (..), clamp, colorA, colorB, colorG, colorR, colorRGBA, lerpColor)+import qualified Data.Text as T++-- | A tree row's button style: 'buttonFlagRow', its depth+-- ('SB.treeDepth'), and whether it has children ('SB.treeHasKids'), is+-- expanded ('SB.treeExpanded') and is an odd row ('SB.treeOdd').+treeEncodeStyle :: Int -> Bool -> Bool -> Bool -> Word64+treeEncodeStyle depth hasKids expanded isOdd =+  buttonFlagRow+    .|. (if isOdd then SB.fieldMask SB.treeOdd else 0)+    .|. (if expanded then SB.fieldMask SB.treeExpanded else 0)+    .|. (if hasKids then SB.fieldMask SB.treeHasKids else 0)+    .|. SB.packField SB.treeDepth depth++-- | A tree row's depth, and whether it has children and is expanded.+treeDecodeStyle :: Word64 -> (Int, Bool, Bool)+treeDecodeStyle s = (SB.getField SB.treeDepth s, SB.testField SB.treeHasKids s, SB.testField SB.treeExpanded s)++-- | A tree row's stripe code for 'stripeColor', from its odd-row bit.+treeDecodeStripe :: Word64 -> Int+treeDecodeStripe s = if SB.testField SB.treeOdd s then 2 else 1++textInputMinWidth :: Float+textInputMinWidth = 160++textInputFieldHeight :: FontMetrics -> Float+textInputFieldHeight fm = fmLineHeight fm + controlPadY fm++-- | Search-field icon geometry. Returns+-- (icon diameter, outer pad, left chrome lead, right chrome tail). The lead/tail+-- are the horizontal space the magnifier / clear buttons reserve either side of+-- the editable text.+searchInputChrome :: FontMetrics -> (Float, Float, Float, Float)+searchInputChrome fm =+  let (ix, _) = widgetContentInset fm+      s = clamp 12 15 (fmLineHeight fm * 0.8)+      pad = fmAdvance fm ' ' * 0.6+   in (s, ix, ix + s + pad, pad + s + ix)++-- | Total horizontal chrome a caption-less search box reserves for its icons.+searchInputReserveW :: FontMetrics -> Float+searchInputReserveW fm =+  let (_, _, lead, tailw) = searchInputChrome fm+   in lead + tailw++-- | Region a caption-less search field's editable text may occupy. Excludes the+-- magnifier on the left and the clear slot on the right.+searchInputTextClip :: FontMetrics -> Float -> Float -> Float -> Float -> Rect+searchInputTextClip fm x y w h =+  let (_, _, lead, tailw) = searchInputChrome fm+   in textClipBetween fm lead tailw x y w h++-- | A field's text region: inside the vertical content inset, between @lead@+-- from the left edge and @trail@ from the right.+textClipBetween :: FontMetrics -> Float -> Float -> Float -> Float -> Float -> Float -> Rect+textClipBetween fm lead trail x y w h =+  let (_, iy) = widgetContentInset fm+   in Rect (x + lead) (y + iy) (max 0 (w - lead - trail)) (max 0 (h - 2 * iy))++-- | Square slots (magnifier left, clear right) the search icons are drawn in.+searchInputIconRects :: FontMetrics -> Float -> Float -> Float -> Float -> (Rect, Rect)+searchInputIconRects fm x y w h =+  let (s, ix, _, _) = searchInputChrome fm+      cy = y + h / 2+      mag = Rect (x + ix) (cy - s / 2) s s+      clear = Rect (x + w - ix - s) (cy - s / 2) s s+   in (mag, clear)++textInputFieldText :: Text -> Text -> Bool -> Text+textInputFieldText ph value focused+  | T.null value && not focused = ph+  | otherwise = value++-- | Marks a @NodeTextInput@ as a caption-less search field ('SB.inputSearch').+{-# INLINE textInputFlagSearch #-}+textInputFlagSearch :: Word64+textInputFlagSearch = SB.fieldMask SB.inputSearch++-- | Marks a @NodeTextInput@ as a selectable text label: read-only, caption-less,+-- chrome-less, sized to its text content, with mouse drag-to-select and copy.+{-# INLINE textInputFlagSelectable #-}+textInputFlagSelectable :: Word64+textInputFlagSelectable = SB.fieldMask SB.inputSelectable++-- | Marks a @NodeTextInput@ as a password field: its value is displayed masked+-- and is never copied or cut to the clipboard.+{-# INLINE textInputFlagPassword #-}+textInputFlagPassword :: Word64+textInputFlagPassword = SB.fieldMask SB.inputPassword++-- | Marks a @NodeTextInput@ as a numeric field: a caption-less box whose text+-- stops short of an up / down stepper at its right edge.+{-# INLINE textInputFlagNumeric #-}+textInputFlagNumeric :: Word64+textInputFlagNumeric = SB.fieldMask SB.inputNumeric++-- | Width of a numeric field's stepper column.+numericStepperW :: Float+numericStepperW = 18++-- | Region a numeric field's text may occupy: inside the content inset, left+-- of the stepper.+numericTextClip :: FontMetrics -> Float -> Float -> Float -> Float -> Rect+numericTextClip fm x y w h =+  let (ix, _) = widgetContentInset fm+   in textClipBetween fm ix (ix + numericStepperW) x y w h++-- | The up and down halves of a numeric field's stepper.+numericStepperRects :: Float -> Float -> Float -> Float -> (Rect, Rect)+numericStepperRects x y w h =+  let sx = x + w - numericStepperW+      half = h / 2+   in (Rect sx y numericStepperW half, Rect sx (y + half) numericStepperW (h - half))++-- | Region a combo box's editable text may occupy: from the left content inset+-- to the select chevron reserve on the right.+comboTextClip :: FontMetrics -> Float -> Float -> Float -> Float -> Rect+comboTextClip fm x y w h =+  let (ix, _) = widgetContentInset fm+   in textClipBetween fm ix selectChevronReserve x y w h++selectDisplayText :: Text -> Text -> Text+selectDisplayText lbl opt+  | T.null lbl = opt+  | otherwise = lbl <> ": " <> opt++-- Space reserved on the right of a select for the chevron.+selectChevronReserve :: Float+selectChevronReserve = 16++selectChevronCenterX :: Float -> Float -> Float+selectChevronCenterX x w = x + w - selectChevronReserve / 2++colorPickerGap :: Float+colorPickerGap = 4++-- | Height of a color picker's field row; the field grows to a square this tall.+colorPickerSvH :: Float+colorPickerSvH = 250++-- | Lowercase @#rrggbb@ text. Discards alpha; use 'colorToHexA' to retain it.+colorToHex :: Color -> Text+colorToHex c =+  "#" <> hexByte (colorR c) <> hexByte (colorG c) <> hexByte (colorB c)++-- | Lowercase @#rrggbbaa@: 'colorToHex' with the alpha byte.+colorToHexA :: Color -> Text+colorToHexA c = colorToHex c <> hexByte (colorA c)++hexByte :: Word8 -> Text+hexByte n = indexSmallArray hexBytes (fromIntegral n)++-- Each byte's two-character representation is allocated once, shared by+-- color-picker labels instead of formatting fresh Strings every frame.+hexBytes :: SmallArray Text+hexBytes =+  smallArrayFromList+    [T.justifyRight 2 '0' (T.pack (showHex n "")) | n <- [0 .. 255 :: Int]]++-- | Parse a hex color, accepting an optional leading @#@ and either 6 or 8+-- digits. The fourth component is 'Nothing' for the six-digit form.+colorPickerParseHex :: Text -> Maybe (Word8, Word8, Word8, Maybe Word8)+colorPickerParseHex txt+  | (n == 6 || n == 8) && T.all isHexDigit bare =+      Just (byte 0, byte 2, byte 4, if n == 8 then Just (byte 6) else Nothing)+  | otherwise = Nothing+  where+    bare = T.dropWhile (== '#') (T.strip txt)+    n = T.length bare+    byte i = fromIntegral (digitToInt (T.index bare i) * 16 + digitToInt (T.index bare (i + 1)))++-- | Parse six or eight hex digits as RGB or RGBA. Strips surrounding whitespace+-- and leading @#@ characters; invalid digits/length return 'Nothing'. RGB is opaque.+colorFromHex :: Text -> Maybe Color+colorFromHex txt = do+  (r, g, b, ma) <- colorPickerParseHex txt+  pure (colorRGBA r g b (fromMaybe 255 ma))++-- | A text node's style index: the layout's font face, weight, slant and+-- decoration, a row stripe code (see 'stripeColor'), and the tone (the+-- 'Tone' plus one, or 0 for none). "NanoUI.Internal.StyleBits" places each+-- field. A color-only variant packs as the regular face plus its tone, so+-- it is measured in the base font.+{-# INLINE packTextNodeStyle #-}+packTextNodeStyle :: Layout -> Int -> Word64+packTextNodeStyle l stripe =+  stripeBits stripe+    .|. SB.packField SB.textFace (fromEnum (layoutFontVariant l))+    .|. SB.packField SB.textWeight (fromEnum (layoutFontWeight l))+    .|. SB.packField SB.textSlant (fromEnum (layoutFontStyle l))+    .|. SB.packField SB.textDecoration (fromEnum (layoutTextDecoration l))+    .|. (if layoutFontTabular l then SB.fieldMask SB.textTabular else 0)+    .|. SB.placeField SB.textTone (maybe 0 ((+ 1) . fromEnum) (layoutFontTone l))+    .|. SB.packField SB.textEllipsis (fromEnum (layoutEllipsis l))+    .|. (if layoutSingleLine l then SB.fieldMask SB.textSingleLine else 0)++-- | The tone in a field that holds a 'Tone' plus one, 'Nothing' for 0.+{-# INLINE decodeToneField #-}+decodeToneField :: BitField -> Word64 -> Maybe Tone+decodeToneField f si = case SB.getField f si of+  0 -> Nothing+  v -> Just (decodeStyleEnum (BitField 0 (bfWidth f)) Danger (fromIntegral (v - 1)))++-- | The font a text node of font size @size@ and style index @si@ is measured+-- in, as one key: the size and the variant, weight and slant bits of the+-- style index.+textNodeFontKey :: Float -> Word64 -> Int+textNodeFontKey size si =+  let w = castFloatToWord32 size+      bits = fromIntegral (si .&. SB.textFontKeyMask)+   in if finiteBitSize (0 :: Int) > 32+        then fromIntegral w `shiftL` 18 .|. bits+        else fromIntegral (w `xor` (w `shiftR` 16)) `shiftL` 17 .|. bits++-- | The font variant packed in a text node's style index.+{-# INLINE textNodeFontVariant #-}+textNodeFontVariant :: Word64 -> FontVariant+textNodeFontVariant = decodeStyleEnum SB.textFace FontRegular++-- | The tone packed in a text node's style index, if any.+{-# INLINE textNodeFontTone #-}+textNodeFontTone :: Word64 -> Maybe Tone+textNodeFontTone = decodeToneField SB.textTone++-- | Decode weight bits, falling back to normal for an invalid enum value.+{-# INLINE textNodeFontWeight #-}+textNodeFontWeight :: Word64 -> FontWeight+textNodeFontWeight = decodeStyleEnum SB.textWeight WeightNormal++-- | Decode slant bits, falling back to upright for an invalid enum value.+{-# INLINE textNodeFontStyle #-}+textNodeFontStyle :: Word64 -> FontStyle+textNodeFontStyle = decodeStyleEnum SB.textSlant FontStyleNormal++-- | Decode the underline/strikethrough bits of a text node's style code.+{-# INLINE textNodeTextDecoration #-}+textNodeTextDecoration :: Word64 -> TextDecoration+textNodeTextDecoration = decodeStyleEnum SB.textDecoration DecorationNone++-- | Whether a text node's style requests uniform tabular digit advances.+{-# INLINE textNodeFontTabular #-}+textNodeFontTabular :: Word64 -> Bool+textNodeFontTabular = SB.testField SB.textTabular++-- | Decode where a truncated single-line text node places its ellipsis.+{-# INLINE textNodeEllipsis #-}+textNodeEllipsis :: Word64 -> TextEllipsis+textNodeEllipsis = decodeStyleEnum SB.textEllipsis EllipsisEnd++-- | Whether a text node stays on one line and truncates instead of wrapping.+{-# INLINE textNodeSingleLine #-}+textNodeSingleLine :: Word64 -> Bool+textNodeSingleLine = SB.testField SB.textSingleLine++-- | Row fill for stripe code 1 (even rows) or 2 (odd rows); 0 is unstriped.+{-# INLINE stripeColor #-}+stripeColor :: Theme -> Int -> Maybe Color+stripeColor theme s = case s of+  1 -> Just (lerpColor (styleBg (themePanel theme)) (themeWindow theme) 0.26)+  2 -> Just (lerpColor (styleBg (themePanel theme)) (styleBg (themeButton theme)) 0.55)+  _ -> Nothing++-- | The stripe code of table row @ri@.+{-# INLINE rowStripe #-}+rowStripe :: Int -> Int+rowStripe ri = if even ri then 1 else 2++-- | A stripe code in its style-index bits, as 'tableStripeColor' decodes it.+{-# INLINE stripeBits #-}+stripeBits :: Int -> Word64+stripeBits = SB.placeField SB.stripe++-- | Row fill decoded from a text node's or a panel's style index.+tableStripeColor :: Theme -> Word64 -> Maybe Color+tableStripeColor theme si = stripeColor theme (SB.getField SB.stripe si)++-- | The surface of a panel with style index @si@: the theme's panel, or, for+-- a table's widget cell, its row fill ('tableStripeColor') with no border or+-- rounding.+{-# INLINE panelSurface #-}+panelSurface :: Theme -> Word64 -> Style+panelSurface theme si = case tableStripeColor theme si of+  Just bg -> (themePanel theme) {styleBg = bg, styleBorderWidth = 0, styleCornerRadius = 0}+  Nothing -> themePanel theme++-- | How far the lines of a text node with style index @si@ keep from each+-- side: a table cell's inset when it has a row fill ('tableStripeColor').+{-# INLINE tableStripeInset #-}+tableStripeInset :: Word64 -> Float+tableStripeInset si = case SB.getField SB.stripe si of+  1 -> tableCellInset+  2 -> tableCellInset+  _ -> 0++-- | The lane every table header keeps beside its label for the sort mark,+-- on the side the label does not align to: the right of a left-aligned+-- label, the left of a right-aligned one. Reserved whether or not the column+-- is sorted, so the mark never changes the column's width or covers the+-- label.+tableSortLane :: Float+tableSortLane = 14++-- | A table header's horizontal padding: the cell inset on both sides and+-- the sort mark's lane.+tableHeaderPadX :: Float+tableHeaderPadX = 2 * tableCellInset + tableSortLane++-- | The sort direction a table header's style packs ('SB.headerSortMark'):+-- 0 none, 1 ascending, 2 descending.+{-# INLINE tableSortMarkOf #-}+tableSortMarkOf :: Word64 -> Int+tableSortMarkOf = SB.getField SB.headerSortMark++-- Button kind lives in bits 24-27 as a 4-bit enum ("NanoUI.Internal.StyleBits")+-- so visual style and tab index stay in the low bits.+{-# INLINE packButtonKind #-}+packButtonKind :: ButtonKind -> Word64+packButtonKind = SB.packField SB.buttonKind . fromEnum++{-# INLINE buttonFlagClose #-}+buttonFlagClose :: Word64+buttonFlagClose = packButtonKind ButtonClose++-- | Visual style of a title-bar close button: its cross sits against the+-- box's right edge, so it lines up with the panel padding the way the title+-- does on the left.+buttonCloseTrailing :: Word64+buttonCloseTrailing = 1++-- | Visual style of a tab header's close button: its cross in the header's+-- label colour ('NanoUI.Internal.Style.fontColor'), dimmed at rest, on a+-- round fill while hovered.+buttonCloseTab :: Word64+buttonCloseTab = 2++{-# INLINE buttonFlagTab #-}+buttonFlagTab :: Word64+buttonFlagTab = packButtonKind ButtonTab++{-# INLINE buttonFlagTable #-}+buttonFlagTable :: Word64+buttonFlagTable = packButtonKind ButtonTable++-- Flat menu row / menu-bar entry: transparent at rest, hover highlight, and an+-- accent marker on hover. Rendered by 'menuItemVisualStyle'.+{-# INLINE buttonFlagMenu #-}+buttonFlagMenu :: Word64+buttonFlagMenu = packButtonKind ButtonMenu++-- Flat menu-bar title: same flat/hover/open fill as a menu row, but centered+-- text and no hover accent marker (that marker belongs to drop-down rows).+{-# INLINE buttonFlagMenuBar #-}+buttonFlagMenuBar :: Word64+buttonFlagMenuBar = packButtonKind ButtonMenuBar++-- | A button whose content is a view of its own ('NanoUI.buttonContent'),+-- padded as a labelled button is.+{-# INLINE buttonFlagContent #-}+buttonFlagContent :: Word64+buttonFlagContent = packButtonKind ButtonContent++-- | A checkbox, or with visual style 1 a radio option: no fill, border or+-- padding, its box or ring before its label, checked while its value is over+-- a half.+{-# INLINE buttonFlagChoice #-}+buttonFlagChoice :: Word64+buttonFlagChoice = packButtonKind ButtonChoice++-- | A tree row: square and borderless, its stripe's fill, or the accent's+-- tint while its value is over a half. Its style packs the rest+-- ('treeEncodeStyle').+{-# INLINE buttonFlagRow #-}+buttonFlagRow :: Word64+buttonFlagRow = packButtonKind ButtonRow++-- | Mutually exclusive visual role of a 'NodeButton' decoded from its packed+-- 'SB.buttonKind' field.+data ButtonKind+  = ButtonPlain+  | ButtonClose+  | ButtonTab+  | ButtonTable+  | ButtonMenu+  | ButtonMenuBar+  | ButtonContent+  | ButtonChoice+  | ButtonRow+  deriving (Eq, Show, Enum, Bounded)++-- | Decode a button's visual role from its packed 'SB.buttonKind' field.+{-# INLINE buttonKindOf #-}+buttonKindOf :: Word64 -> ButtonKind+buttonKindOf = decodeStyleEnum SB.buttonKind ButtonPlain++-- | Marks a @NodeContainer@ whose widgets are for display: the pointer passes+-- through them to the widget they are drawn in+-- ('NanoUI.Internal.Frame.Hit.innermostHit').+{-# INLINE containerFlagInert #-}+containerFlagInert :: Word64+containerFlagInert = SB.fieldMask SB.containerInert++-- | Marks a @NodeContainer@ that clips its children to its rect, for paint,+-- text spans and the pointer, as a panel does.+{-# INLINE containerFlagClip #-}+containerFlagClip :: Word64+containerFlagClip = SB.fieldMask SB.containerClip++-- | Marks a @NodeContainer@ that wraps its children in a Tier 2 shader effect.+{-# INLINE containerFlagShaderEffect #-}+containerFlagShaderEffect :: Word64+containerFlagShaderEffect = SB.fieldMask SB.containerShaderEffect++-- | Marks a @NodeContainer@ that joins adjacent buttons ('NanoUI.buttonGroup').+{-# INLINE containerFlagButtonGroup #-}+containerFlagButtonGroup :: Word64+containerFlagButtonGroup = SB.fieldMask SB.containerButtonGroup++-- | Whether the packed style index @si@ carries @flag@.+{-# INLINE hasFlag #-}+hasFlag :: Word64 -> Word64 -> Bool+hasFlag flag si = si .&. flag /= 0++-- | A button's own style bits ('SB.buttonVisual'): those below the type+-- flags, leaving out the label font above them ('labelFontStyle').+{-# INLINE buttonVisualStyle #-}+buttonVisualStyle :: Word64 -> Word64+buttonVisualStyle si = si .&. SB.fieldMask SB.buttonVisual++-- | The color of a widget label in font bits @font@ ('nodeFontBits') on a+-- surface of @style@: the layout's 'NanoUI.Internal.Style.fontColor', else+-- its tone's, else the surface's text color.+{-# INLINE labelColor #-}+labelColor :: Theme -> Style -> Word64 -> Maybe Color -> Color+labelColor theme style font = fromMaybe (maybe (styleFg style) (toneColor theme) (textNodeFontTone font))++-- | A button's or select's label font from its layout: the text-node packing+-- ('packTextNodeStyle') moved up to 'labelFontShift', for 'nodeFontBits' to+-- read back.+{-# INLINE labelFontStyle #-}+labelFontStyle :: Layout -> Word64+labelFontStyle l = packTextNodeStyle l 0 `shiftL` labelFontShift++-- | A plain button's packed style carrying the 'Tone' it fills with while+-- its value is on ('SB.buttonTone', a toggle button's).+{-# INLINE buttonToneStyle #-}+buttonToneStyle :: Tone -> Word64+buttonToneStyle t = SB.placeField SB.buttonTone (fromEnum t + 1)++-- | The tone 'buttonToneStyle' packed, 'Nothing' for the accent.+{-# INLINE buttonToneOf #-}+buttonToneOf :: Word64 -> Maybe Tone+buttonToneOf = decodeToneField SB.buttonTone++-- | A tab header's packed button style: the strip's tab style (0-3,+-- 'SB.tabStyle'), its orientation (0-3, 'SB.tabOrient'), and+-- 'buttonFlagTab'.+{-# INLINE tabEncodeStyle #-}+tabEncodeStyle :: Int -> Int -> Word64+tabEncodeStyle style orient = SB.packField SB.tabStyle style .|. SB.packField SB.tabOrient orient .|. buttonFlagTab++-- | The tab style and orientation of a tab header's packed style.+{-# INLINE tabDecodeStyle #-}+tabDecodeStyle :: Word64 -> (Int, Int)+tabDecodeStyle si = (SB.getField SB.tabStyle si, SB.getField SB.tabOrient si)++-- | Space either side of a tab header's label and adornments.+tabHeaderPadX :: Float+tabHeaderPadX = 12++-- | Whether a button's label and adornments start at its left padding+-- ('tabHeaderPadX') rather than sit centered: a header of a vertical tab+-- strip.+{-# INLINE tabLabelAtStart #-}+tabLabelAtStart :: Word64 -> Bool+tabLabelAtStart si = buttonKindOf si == ButtonTab && snd (tabDecodeStyle si) >= 2++-- | What a tab strip's container paints under its children.+data TabChrome+  = TabChromeNone+  | TabChromeRule+  -- ^ A one-pixel rule along the side facing the body.+  | TabChromeTrack+  -- ^ A rounded track behind segmented headers.+  | TabChromeBody+  -- ^ A contained body's fill, and its border on the three sides away from+  -- the headers.+  deriving (Eq, Show, Enum, Bounded)++-- | A @NodeContainer@'s style for 'TabChrome' @part@ of a strip with tab+-- style @style@ and orientation @orient@ ('SB.chromePart', 'SB.chromeStyle',+-- 'SB.chromeOrient'), clear of 'containerFlagInert'.+{-# INLINE tabChromeEncode #-}+tabChromeEncode :: TabChrome -> Int -> Int -> Word64+tabChromeEncode part style orient =+  SB.placeField SB.chromePart (fromEnum part) .|. SB.packField SB.chromeStyle style .|. SB.packField SB.chromeOrient orient++-- | The chrome part, tab style and orientation a container's style packs.+{-# INLINE tabChromeDecode #-}+tabChromeDecode :: Word64 -> (TabChrome, Int, Int)+tabChromeDecode si =+  (decodeStyleEnum SB.chromePart TabChromeNone si, SB.getField SB.chromeStyle si, SB.getField SB.chromeOrient si)
+ lib/NanoUI/Internal/Widgets/Adornment.hs view
@@ -0,0 +1,187 @@+-- | Icons, short texts and small views drawn inside a widget beside its own+-- text: before or after a text field's value, or beside a button's label.+--+-- An adornment is a value that describes what to draw. The widget adds each+-- side's adornments as one row inside its own node, so they lay out, paint,+-- and damage inside the widget's box. A press on an icon, a text or a view+-- is a press on the widget; a control takes its own presses.+module NanoUI.Internal.Widgets.Adornment+  ( Adornment (..)+  , Adornments (..)+  , leading+  , trailing+  , icon+  , iconSized+  , affix+  , view+  , control+  , adornWidget+  , adornButton+  , adornmentRow+  )+where++import Control.Monad (forM)+import Data.IORef (readIORef)+import Data.Maybe (catMaybes)+import Data.Text (Text)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Font (FontMetrics (..))+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input (inputMousePos)+import NanoUI.Internal.Layout.Arena (arenaCount, lookupNodeByWidgetId)+import NanoUI.Internal.Monad (NanoUI, askContext, askInput, ifM, resolveFontUi, liftIO, uiTheme, withDefaultLayout)+import NanoUI.Internal.Style+import NanoUI.Internal.Types (Color, V2)+import NanoUI.Internal.Widgets.Behavior (keyActivated)+import NanoUI.Internal.Widgets.Display (svgIconWith')+import NanoUI.Internal.Widgets.Layout (labelEx, row')+import NanoUI.Internal.Widgets.Node+import NanoUI.Svg (Svg)++-- | An item drawn beside a widget's text in the widget's adornment colour.+data Adornment+  = AdornIcon !(Maybe Float) !Svg+  -- ^ An SVG icon, this many logical pixels square, or with 'Nothing' about+  -- as tall as a line of the widget's text. A one-colour icon takes the+  -- adornment colour, as 'NanoUI.svgIcon' takes the text colour.+  | AdornText !Text+  -- ^ A short text in the widget's font, such as a unit or a prefix.+  | AdornView (NanoUI ())+  -- ^ Any view, such as a 'NanoUI.spinner'. It runs inside the widget each+  -- frame, with the adornment colour as its default text colour. It is for+  -- display: a press on it is a press on the widget.+  | AdornControl (NanoUI ())+  -- ^ An interactive child view, such as a field's clear button. Pointer+  -- events inside it are handled by the child widgets rather than the+  -- enclosing widget (which does not report the press, take focus, or move+  -- its caret).++-- | A view shows as @AdornView \<view\>@.+instance Show Adornment where+  showsPrec d a = showParen (d > 10) $ case a of+    AdornIcon size doc -> showString "AdornIcon " . showsPrec 11 size . showChar ' ' . showsPrec 11 doc+    AdornText txt -> showString "AdornText " . showsPrec 11 txt+    AdornView _ -> showString "AdornView <view>"+    AdornControl _ -> showString "AdornControl <view>"++-- | What a widget draws before its text and after it. Adornments combine+-- side by side, each side in the order given:+--+-- > leading (icon mail) <> trailing (affix "@example.com")+data Adornments = Adornments+  { adornLeading :: ![Adornment]+  , adornTrailing :: ![Adornment]+  }+  deriving (Show)++instance Semigroup Adornments where+  Adornments l1 t1 <> Adornments l2 t2 = Adornments (l1 <> l2) (t1 <> t2)++instance Monoid Adornments where+  mempty = Adornments [] []++-- | Draw an adornment before the widget's text.+leading :: Adornment -> Adornments+leading a = Adornments [a] []++-- | Draw an adornment after the widget's text.+trailing :: Adornment -> Adornments+trailing a = Adornments [] [a]++-- | An SVG icon about as tall as a line of the widget's text.+icon :: Svg -> Adornment+icon = AdornIcon Nothing++-- | An SVG icon @size@ logical pixels square.+iconSized :: Float -> Svg -> Adornment+iconSized size = AdornIcon (Just size)++-- | A short text, such as @"kg"@ after a weight or @"https://"@ before an+-- address.+affix :: Text -> Adornment+affix = AdornText++-- | Any view, for display, such as a spinner while a field's value is+-- checked. A press on it is a press on the widget.+--+-- > trailing (view (void (spinnerWith' id 14)))+view :: NanoUI () -> Adornment+view = AdornView++-- | An interactive adornment whose widgets handle their own pointer events,+-- such as a button that toggles password visibility:+--+-- > trailing (control (whenM (buttonWith tight "Show") (setShown (not shown))))+control :: NanoUI () -> Adornment+control = AdornControl++-- | Add adornments to widget @wid@ using layout @lay@ and colour @colorOf@.+-- Returns 'True' when an 'AdornControl' captures the pointer ('holdsPointer'),+-- suppressing the enclosing widget's pointer handling.+{-# INLINE adornWidget #-}+adornWidget :: WidgetId -> Layout -> (Theme -> Color) -> Adornments -> NanoUI Bool+adornWidget _ _ _ (Adornments [] []) = pure False+adornWidget wid lay colorOf adorns = addAdornments wid lay colorOf adorns++-- | Add adornments to a button, suppressing pointer clicks on the outer button+-- (while keeping keyboard activation) when an 'AdornControl' captures the+-- pointer.+{-# INLINE adornButton #-}+adornButton :: Response -> Layout -> (Theme -> Color) -> Adornments -> NanoUI Response+adornButton resp lay colorOf adorns = do+  taken <- adornWidget (respId resp) lay colorOf adorns+  if taken then (`setClicked` inertResponse resp) <$> keyActivated (respId resp) else pure resp++-- | 'adornWidget' with something to draw: one row a side, the leading row+-- aligned to the start and the trailing one to the end ('adornRows').+{-# NOINLINE addAdornments #-}+addAdornments :: WidgetId -> Layout -> (Theme -> Color) -> Adornments -> NanoUI Bool+addAdornments wid lay colorOf (Adornments ls ts) = do+  ctx <- askContext+  let na = ctxNodeArena ctx+  inp <- askInput+  color <- colorOf <$> uiTheme+  let copyFontSize l = l {layoutFontSize = layoutFontSize lay}+      add = \case+        AdornIcon size doc -> do+          s <- case size of+            Just n -> pure (max 0 n)+            Nothing -> do+              fm <- resolveFontUi (layoutFontSize lay) WeightNormal FontStyleNormal FontRegular+              pure (fromIntegral (round (fmLineHeight fm * 0.9) :: Int))+          Nothing <$ svgIconWith' (fixedWH s s . fontColor color) doc+        AdornText txt -> Nothing <$ labelEx (tight . copyFontSize . fontColor color $ defaultLayout) txt+        AdornView v -> Nothing <$ adornmentRow lay color v+        AdornControl v -> do+          from <- liftIO (arenaCount na)+          withDefaultLayout (copyFontSize . fontColor color) v+          to <- liftIO (arenaCount na)+          pure (Just (from, to))+      side align pieces+        | null pieces = pure []+        | otherwise = row' (align (adornmentRowLayout lay)) (catMaybes <$> forM pieces add)+  mRanges <- withWidgetChildren wid ((<>) <$> side alignStart ls <*> side alignEnd ts)+  case mRanges of+    Just ranges@(_ : _) -> liftIO (holdsPointer ctx wid (inputMousePos inp) ranges)+    _ -> pure False++-- | An inert row inside a widget with layout @lay@, its labels in the+-- widget's font and colour @color@.+adornmentRow :: Layout -> Color -> NanoUI a -> NanoUI a+adornmentRow lay color =+  inertContainer (adornmentRowLayout lay) . withDefaultLayout ((\l -> l {layoutFontSize = layoutFontSize lay}) . fontColor color)++adornmentRowLayout :: Layout -> Layout+adornmentRowLayout lay = tight . gap (layoutGap lay) . alignMiddle . itemsCenter $ defaultLayout {layoutDirection = Row}++-- | Whether an 'AdornControl' in one of the node ranges captures the pointer+-- (either active or hovered over an enabled widget node). When @wid@ itself+-- is active, it retains the pointer.+holdsPointer :: Context -> WidgetId -> V2 -> [(Int, Int)] -> IO Bool+holdsPointer ctx wid mouse ranges = do+  active <- readIORef (ctxActiveId ctx)+  pressedControl <- maybe False (\i -> any (\(from, to) -> i >= from && i < to) ranges) <$> lookupNodeByWidgetId (ctxNodeArena ctx) active+  if pressedControl || active == wid+    then pure pressedControl+    else foldr (\(from, to) rest -> ifM (anyControlHitInRange ctx mouse from to) (pure True) rest) (pure False) ranges
+ lib/NanoUI/Internal/Widgets/Animate.hs view
@@ -0,0 +1,106 @@+-- | View-level tween and spring hooks, continuous animation, and timed frame requests.+module NanoUI.Internal.Widgets.Animate+  ( Transition (..)+  , animate+  , animateTo+  , animateToA+  , pulse+  , keepAnimating+  , wakeAfter+  )+where++import Control.Monad (when)+import Data.Maybe (isNothing)+import NanoUI.Internal.Animatable (Animatable (..))+import NanoUI.Internal.Context+import NanoUI.Internal.Monad (NanoUI, nextId, scope, uiTime, withContext, withKey)+import NanoUI.Internal.Widgets.Node (HasResponse, respId)++-- | How an animated value moves.+data Transition+  = -- | Eased tween: duration and start delay, in seconds.+    Tween !Ease !Float !Float+  | -- | Damped spring; retargets from its current position and velocity.+    Spring !SpringParams+  deriving (Eq, Show)++-- | Animate from @from@ to @to@. It starts over from @from@ once it has+-- finished (a tween completes, a spring settles) or its tween changes, so+-- calling it every frame cycles. A frame that leaves it out stops it.+animate :: Transition -> Float -> Float -> NanoUI Float+animate transition from to = do+  wid <- nextId+  withContext $ \ctx -> do+    case transition of+      Tween ease dur delay -> startAnimationEaseDelay ctx wid from to dur ease delay+      Spring params -> do+        running <- lookupAnimation ctx wid+        when (isNothing running) (setAnimationValue ctx wid from)+        startSpring ctx wid params to+    getViewAnimationValue ctx wid++-- | Animate from the current value toward @target@. An unchanged target keeps+-- the running animation; a new one retargets from wherever the value is. A+-- frame that leaves it out stops it where it is.+animateTo :: Transition -> Float -> NanoUI Float+animateTo transition target = do+  wid <- nextId+  withContext $ \ctx -> do+    case transition of+      Tween ease dur delay -> do+        cur <- getAnimationValue ctx wid+        manim <- lookupAnimation ctx wid+        case manim of+          -- Still running: its key is not attached to a widget node, so request+          -- a full-frame repaint just as 'startAnimationEaseDelay' does.+          Just a | easeSameSpec a ease dur delay target -> repaintIfOrphan ctx (intKey wid)+          Nothing | approxEq cur target -> pure ()+          _ -> startAnimationEaseDelay ctx wid cur target dur ease delay+      Spring params -> startSpring ctx wid params target+    getViewAnimationValue ctx wid++-- | 'animateTo' for every component of a composite value. Component keys are+-- local to the value, not its parent widget.+animateToA :: Animatable a => Transition -> a -> NanoUI a+animateToA transition =+  scope . traverseChannels (\index value -> withKey index (animateTo transition value))++-- | A smoothly oscillating value in @[0,1]@ driven by the real-time clock, with+-- the given period in seconds (e.g. @pulse 6@ sweeps once every six seconds).+-- The time is captured in 'Double' (see 'NanoUI.uiTime'), so the sweep+-- stays sub-frame smooth even on long-running processes. Unlike 'animate', it+-- asks for no frames: pair it with 'keepAnimating' for continuous motion, or+-- 'wakeAfter' for stepped updates, or it changes only when something else+-- draws a frame.+pulse :: Float -> NanoUI Float+pulse periodSec = do+  t <- uiTime+  let+    period = max 0.001 (realToFrac periodSec :: Double)+  pure (realToFrac (0.5 + 0.5 * sin (2 * pi * t / period)) :: Float)++-- | Keep a widget animating for as long as this is called, so the frame loop+-- does not idle. Widgets driven by the wall clock ('pulse', or drawing from+-- 'NanoUI.uiTime') rather than by a frame-counted animation would+-- otherwise stop repainting once other animations settle. Call it every+-- frame the widget is shown: the loop goes back to sleep on the first frame+-- that leaves it out.+--+-- > bar <- progressBarWith' id 12 =<< pulse 6+-- > keepAnimating bar+keepAnimating :: HasResponse r => r -> NanoUI ()+keepAnimating resp = withContext (\ctx -> keepAnimationAlive ctx (respId resp))++-- | Ask for another frame after this many seconds, even if no input arrives.+-- The loop sleeps until then. Call it on every frame that still needs the+-- later one, as a clock label would to tick once a second:+--+-- > clock = do+-- >   label =<< currentTimeText+-- >   wakeAfter 1+--+-- Use it instead of 'keepAnimating' when a view changes on a schedule and not+-- continuously: 'keepAnimating' runs a frame for every display refresh.+wakeAfter :: Double -> NanoUI ()+wakeAfter sec = withContext (\ctx -> requestWakeAfter ctx sec)
+ lib/NanoUI/Internal/Widgets/Behavior.hs view
@@ -0,0 +1,488 @@+-- | Interaction hooks shared by widgets: 1D drags, drag reordering, arrow-key+-- navigation, click-outside and Escape dismissal, and the keyboard focus+-- check. Their state lives in the widget store.+module NanoUI.Internal.Widgets.Behavior+  ( DragAxis (..)+  , useDrag1D+  , leftPress+  , dragPressLive+  , recordDragPress+  , holdActiveWhile+  , Reorder (..)+  , useReorder+  , useKeyNav+  , keyboardFocused+  , useInputMethod+  , keyActivated+  , focusedKeyPressed+  , focusedKeyPressedOnce+  , KeyNav (..)+  , navStep+  , ListNav (..)+  , ListNavScroll (..)+  , useListNav+  , useListNavWith+  , useDismissable+  , pastDragThreshold+  )+where++import Control.Monad (forM_, when, (>=>))+import Data.Bits (shiftL, (.|.))+import Data.IORef (readIORef, writeIORef)+import Data.IntSet qualified as IS+import Data.List (find, minimumBy)+import Data.Map.Strict qualified as M+import Data.Ord (comparing)+import Data.Maybe (isJust)+import GHC.Float (castFloatToWord32)+import NanoUI.Internal.Context+import NanoUI.Internal.Frame.Hit (findNodeByWidgetId, nodeInSubtree, nodeInteractionHit)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (getParent, getWidgetId, lookupNodeByKey)+import NanoUI.Internal.Monad (NanoUI, (<&&>), askContext, askFrameInput, askInput, focusedWidget, freshWidget, liftIO, withContext)+import NanoUI.Internal.Store (deleteSpec, findSpec, insertSpec, lookupSpec)+import NanoUI.Internal.Store.Slots (setFlagSpec, slotDragItem, slotDragPress, slotDragStartPos, slotDrop)+import NanoUI.Internal.Types (Rect (..), V2 (..), clamp, clamp01, rectContains, v2X, v2Y)+import NanoUI.Internal.Widgets.Node (Response, respPressed, respRect)+import NanoUI.Internal.Widgets.SplitPane (rectDistSq)++-- | Pointer slop in pixels before a held press counts as a drag.+dragThresholdPx :: Float+dragThresholdPx = 8++-- | Whether the pointer has moved past 'dragThresholdPx' from the press origin.+{-# INLINE pastDragThreshold #-}+pastDragThreshold :: V2 -> V2 -> Bool+pastDragThreshold (V2 sx sy) (V2 mx my) =+  let dx = mx - sx+      dy = my - sy+   in dx * dx + dy * dy > dragThresholdPx * dragThresholdPx++-- | The axis a drag or an insertion index measures along.+data DragAxis = DragAxisX | DragAxisY+  deriving (Eq, Show)++-- | Clamped 1D drag on a track of widget @owner@. Maps pointer position on+-- @track@ into [lo, hi]. The drag starts with a press on the track and lasts+-- until the button comes up. A button held from elsewhere and moved onto the+-- track drags nothing, nor does a press where another widget covers the+-- owner ('trackCovered'). Returns the value, whether the drag is held, and+-- whether it was held before this frame.+useDrag1D ::+  DragAxis ->+  WidgetId ->+  Float ->+  Float ->+  Float ->+  Rect ->+  NanoUI (Float, Bool, Bool)+useDrag1D axis owner lo hi current track = do+  (wid, ctx) <- freshWidget+  inp <- askInput+  let !key = intKey wid+  -- The drag keeps the point of the press that started it in a quiet slot+  -- (0 for none), and lasts only under that press: one released while this+  -- hook did not run does not come back with a later press.+  store <- liftIO (getStore ctx)+  let !held = findSpec slotDragPress 0 key store+      !leftHeld = heldIn MouseLeft inp+      !leftPressed = pressedIn MouseLeft inp+  if not leftHeld && not leftPressed && held == 0+    then pure (current, False, False)+    else do+      active0 <- liftIO (dragPressLive ctx key store)+      -- Hit-test against the clipped node so a track scrolled out of its+      -- viewport does not respond at its stale rect.+      started <-+        if not leftPressed+          then pure False+          else liftIO $ do+            let mousePos = inputMousePos inp+            onT <- findNodeByWidgetId ctx owner >>= maybe (pure (rectContains track mousePos)) (\i -> nodeInteractionHit ctx i track mousePos)+            if not onT then pure False else not <$> trackCovered ctx owner mousePos+      let !active = leftHeld && (active0 || started)+      when (if active then not active0 else held /= 0) . liftIO $+        if active+          then recordDragPress ctx key+          else modifyStore ctx (deleteSpec slotDragPress key)+      if active+        then do+          let (origin, trackLen, mouse) = case axis of+                DragAxisX -> (rectX track, rectW track, v2X (inputMousePos inp))+                DragAxisY -> (rectY track, rectH track, v2Y (inputMousePos inp))+              !frac = if trackLen <= 0 then 0 else clamp01 ((mouse - origin) / trackLen)+          pure (lo + frac * (hi - lo), True, active0)+        else pure (current, False, active0)++-- | The left button's press point as one nonzero Int, exact in both+-- coordinates; 0 while it is up. A drag that keeps the one it started under+-- lasts only under that press.+leftPress :: Context -> IO Int+leftPress ctx = maybe 0 (\PressPoint {ppPos = V2 x y} -> (fromIntegral (castFloatToWord32 x) `shiftL` 32 .|. fromIntegral (castFloatToWord32 y)) + 1) . M.lookup MouseLeft <$> readIORef (ctxPressPos ctx)++-- | Whether the left-button press recorded under @key@ ('slotDragPress') is+-- still the currently held press.+dragPressLive :: Context -> Int -> WidgetStore -> IO Bool+dragPressLive ctx key store =+  let held = findSpec slotDragPress 0 key store+   in if held == 0 then pure False else (== held) <$> leftPress ctx++-- | Store the current left-button press token under @key@ ('slotDragPress').+recordDragPress :: Context -> Int -> IO ()+recordDragPress ctx key = leftPress ctx >>= modifyStore ctx . insertSpec slotDragPress key++-- | Whether a press at @mouse@ on a track of widget @owner@ is covered+-- ('pointerCovered'). A track wider than its owner (a color picker's bar)+-- takes presses beside the owner too, where the pointer reaches what holds+-- the owner rather than the owner itself: there only a node that is none of+-- the owner's ancestors covers it.+trackCovered :: Context -> WidgetId -> V2 -> IO Bool+trackCovered ctx owner mouse = do+  covered <- pointerCovered ctx owner+  inOwner <- maybe False (`rectContains` mouse) <$> getPrevRect ctx owner+  if not covered || inOwner+    then pure covered+    else do+      reach <- readIORef (ctxPointerReach ctx)+      ancestors <- maybe (pure IS.empty) (getParent na >=> idsUp IS.empty) =<< findNodeByWidgetId ctx owner+      pure (maybe False (not . (`IS.isSubsetOf` ancestors)) reach)+  where+    na = ctxNodeArena ctx+    idsUp !acc i+      | i < 0 = pure acc+      | otherwise = do+          wid <- getWidgetId na i+          getParent na i >>= idsUp (if hashWidgetId wid == 0 then acc else IS.insert (intKey wid) acc)++-- | Hold the active id for @wid@ while its drag lasts and let it go after, so+-- the widget paints and takes the cursor as pressed wherever the pointer goes.+-- On the release frame the id stays until the frame lets it go after the+-- view, so a container around the widget does not take the release as its+-- click.+holdActiveWhile :: WidgetId -> Bool -> NanoUI ()+holdActiveWhile wid dragging = do+  inp <- askInput+  withContext $ \ctx -> do+    active <- readIORef (ctxActiveId ctx)+    when (dragging /= (active == wid) && (dragging || not (releasedIn MouseLeft inp))) $+      writeIORef (ctxActiveId ctx) (if dragging then wid else WidgetId 0)++-- | Where a drag-and-drop reorder stands after this frame ('useReorder').+data Reorder = Reorder+  { reorderOrder :: ![Int]+    -- ^ The order after this frame: the one passed in, with the dragged+    -- item moved on the frame it is dropped.+  , reorderPreview :: ![Int]+    -- ^ The order a drop would leave now, the one passed in while nothing+    -- is being dragged. Draw from it to show the items making room.+  , reorderDragging :: !(Maybe Int)+    -- ^ The item held, from the press on it until the button comes up.+  , reorderMoved :: !Bool+    -- ^ The pointer has gone past the drag threshold since the press, so+    -- the press is a drag and not a click. Still set on the release frame,+    -- so a click on the item there can be ignored.+  }+  deriving (Eq, Show)++-- | Drag-and-drop reorder of a list of item ids. Pass the order and each+-- item's response from this view pass, in the order drawn: the+-- order passed, or 'reorderPreview' for a live preview. A press on an item+-- starts a drag; once the pointer passes the drag threshold the item takes+-- the place of the item nearest the pointer, so the list can wrap over+-- several rows. Store 'reorderOrder'; releasing outside every item drops+-- at the nearest one too.+--+-- Make @orderVar <- newVar [0 .. 4]@ during component setup.+--+-- > order <- readVar orderVar+-- > drawn <- forM order $ \i -> (i,) <$> chip i+-- > r <- useReorder order drawn+-- > writeVar orderVar (reorderOrder r)+--+-- Only an owned press starts the drag; clipping, covering controls and+-- disabled scopes are respected. Geometry comes from the response's last layout.+useReorder :: [Int] -> [(Int, Response)] -> NanoUI Reorder+useReorder order responses = do+  (wid, ctx) <- freshWidget+  inp <- askInput+  let key = intKey wid+      mouse = inputMousePos inp+      press = pressedIn MouseLeft inp+      hit = fst <$> find (respPressed . snd) responses+      items = [(i, respRect r) | (i, r) <- responses]+  store <- liftIO (getStore ctx)+  -- The drag keeps the press that started it ('leftPress') and lasts only+  -- under it: one released while this hook did not run does not come back.+  let stored = lookupSpec slotDragItem key store+  token <- if press || isJust stored then liftIO (leftPress ctx) else pure 0+  let dragging+        | press = hit+        | token == findSpec slotDragPress 0 key store = stored+        | otherwise = Nothing+      startPos = if press then mouse else findSpec slotDragStartPos mouse key store+      moved =+        isJust dragging+          && not press+          && (findSpec slotDrop False key store || pastDragThreshold startPos mouse)+      target = if null items then Nothing else Just (fst (minimumBy (comparing ((`rectDistSq` mouse) . snd . snd)) (zip [0 :: Int ..] items)))+      preview = case (target, dragging) of+        (Just t, Just d) | moved, d `elem` order ->+          let (before, after) = splitAt t (filter (/= d) order)+           in before ++ d : after+        _ -> order+      released = releasedIn MouseLeft inp+      ended = released || not (heldIn MouseLeft inp)+      next = if ended then Nothing else dragging+  when (next /= stored || (press && isJust dragging) || moved /= findSpec slotDrop False key store) $+    liftIO . modifyStore ctx $+      case next of+        Nothing -> deleteSpec slotDragItem key . deleteSpec slotDragPress key . deleteSpec slotDragStartPos key . setFlagSpec slotDrop key False+        Just d -> insertSpec slotDragItem key d . insertSpec slotDragPress key token . insertSpec slotDragStartPos key startPos . setFlagSpec slotDrop key moved+  pure+    Reorder+      { reorderOrder = if released && moved then preview else order+      , reorderPreview = if ended then order else preview+      , reorderDragging = next+      , reorderMoved = moved+      }++-- | The navigation keys pressed this frame ('useKeyNav'). The arrows count+-- key auto-repeats; Enter and Space only the initial press.+data KeyNav = KeyNav+  { knUp :: !Bool+  , knDown :: !Bool+  , knLeft :: !Bool+  , knRight :: !Bool+  , knEnter :: !Bool+  , knSpace :: !Bool+  }+  deriving (Eq, Show)++-- | Focus alone does not grant keyboard input. A retained focus ID must still+-- respect disabled state and the modal currently being declared. Unfocused+-- controls avoid the store and modal checks entirely.+{-# INLINE keyboardFocused #-}+keyboardFocused :: WidgetId -> NanoUI Bool+keyboardFocused wid+  | hashWidgetId wid == 0 = pure False+  | otherwise = do+      focus <- focusedWidget+      if focus /= wid+        then pure False+        else do+          ctx <- askContext+          liftIO $ do+            dis <- isDisabled ctx wid+            if dis+              then pure False+              else do+                ine <- isInert ctx wid+                if ine+                  then pure False+                  else not <$> pointerBlockedByModal ctx++-- | Request input method (IME) text for widget @wid@, like iced's+-- @request_input_method@. Call it every frame the widget accepts text,+-- passing its caret in window coordinates and the input purpose; text fields+-- do this themselves.+--+-- While the IME is composing, this returns the 'Composition' for the widget+-- to draw at its caret, and the frame drops the IME's keys. Committed text+-- arrives as 'inputChars'. The backend places the candidate window at the+-- caret and enables text input only while some widget requests it, so a+-- custom widget reading 'inputChars' (a terminal, say) must call this.+-- Returns 'Nothing' and requests nothing when the widget is unfocused,+-- disabled or behind a modal.+--+-- > wid <- nextId+-- > Rect x y _ _ <- fromMaybe (Rect 0 0 0 0) <$> lastRect wid+-- > preedit <- useInputMethod wid InputNormal (Rect (x + caretX) y 1 lineH)+-- > customWidgetWithId wid spec {widgetFocusable = True, widgetKeys = KeysAll}+useInputMethod :: WidgetId -> InputPurpose -> Rect -> NanoUI (Maybe Composition)+useInputMethod wid purpose caret = do+  focused <- keyboardFocused wid+  if not focused+    then pure Nothing+    else withContext $ \ctx -> do+      requestInputMethod ctx wid (Just caret) purpose+      fieldComposition ctx wid++-- | Run @act@ with the current input when @wid@ holds keyboard focus, keys+-- arrived this frame, and only Shift (if any modifier) is held; otherwise+-- return @fallback@.+whenKeyNavFocused :: WidgetId -> a -> (Input -> NanoUI a) -> NanoUI a+whenKeyNavFocused wid fallback act = do+  inp <- askInput+  if hashWidgetId wid == 0 || inputKeysNull (inputKeys inp) || not (shiftAtMost (inputModifiers inp))+    then pure fallback+    else do+      eligible <- keyboardFocused wid+      if not eligible then pure fallback else act inp++-- | Arrow / Enter / Space while @wid@ is focused and eligible for input,+-- bare or with Shift only ('shiftAtMost'); other modifiers leave them to+-- shortcuts. Arrows repeat with key auto-repeat; Enter and Space count only+-- on the initial press.+useKeyNav :: WidgetId -> NanoUI KeyNav+useKeyNav wid =+  whenKeyNavFocused wid (KeyNav False False False False False False) $ \inp ->+    pure KeyNav+      { knUp = pressedIn KeyUp inp+      , knDown = pressedIn KeyDown inp+      , knLeft = pressedIn KeyLeft inp+      , knRight = pressedIn KeyRight inp+      , knEnter = pressedOnceIn KeyEnter inp+      , knSpace = pressedOnceIn KeySpace inp+      }++-- | Directional step from arrow keys: @1@ for Right or Up, @-1@ for Left or Down.+{-# INLINE navStep #-}+navStep :: KeyNav -> Int+navStep nav = fromEnum (knRight nav || knUp nav) - fromEnum (knLeft nav || knDown nav)++-- | Result of one frame of keyboard list navigation ('useListNav').+data ListNav = ListNav+  { lnIndex :: !(Maybe Int)+  -- ^ Selected zero-based row index after applying this frame's keys, or+  -- 'Nothing' when the list is empty or nothing is selected.+  , lnChanged :: !Bool+  -- ^ 'True' on the frame the selection moved via keyboard navigation.+  , lnActivated :: !Bool+  -- ^ 'True' when Enter or Space was pressed while the list held focus and+  -- had a selection ('Just' index).+  }+  deriving (Eq, Show)++-- | How 'useListNavWith' scrolls a newly selected row into view.+data ListNavScroll+  = NavNoScroll+  -- ^ Do not scroll automatically; caller handles scrolling.+  | NavUniformRow !Float+  -- ^ Uniform row step in logical pixels (row height plus gap).+  | NavRowRect !(Int -> Rect)+  -- ^ Content-space rectangle for row @i@ (variable-height rows or lists with+  -- a header above row 0).++-- | Keyboard list navigation for a scrolled list of @count@ uniform-height+-- rows (@rowStep@ logical pixels per row, including gap). While @scrollId@+-- holds keyboard focus (see 'NanoUI.scrollFocusable'), handles Up, Down,+-- PageUp, PageDown, Home, End, Enter, and Space, and scrolls the newly+-- selected row into view when @rowStep > 0@. Pass @0@ or use 'useListNavWith'+-- with 'NavNoScroll' to scroll manually.+--+-- Call before 'NanoUI.scrollConfigured' using 'NanoUI.currentId' so the new+-- selection highlights on the same frame:+--+-- > sid <- currentId+-- > sel <- readVar selVar+-- > nav <- useListNav sid (length items) sel 28+-- > when (lnChanged nav) (writeVar selVar (lnIndex nav))+-- > scrollConfigured defaultScrollConfig {scrollFocusable = True} (fixedWH 240 180) $ ...+useListNav :: WidgetId -> Int -> Maybe Int -> Float -> NanoUI ListNav+useListNav scrollId count current rowStep =+  useListNavWith scrollId count current (if rowStep > 0 then NavUniformRow rowStep else NavNoScroll)++-- | Like 'useListNav', with an explicit 'ListNavScroll' strategy for+-- variable-height rows, headers above row 0, or manual scrolling.+useListNavWith :: WidgetId -> Int -> Maybe Int -> ListNavScroll -> NanoUI ListNav+useListNavWith scrollId count current scrollMode+  | count <= 0 = pure (ListNav Nothing False False)+  | otherwise =+      let cur = clamp 0 (count - 1) <$> current+       in whenKeyNavFocused scrollId (ListNav cur False False) $ \inp -> do+              let home = pressedOnceIn KeyHome inp+                  end = pressedOnceIn KeyEnd inp+                  pgUp = pressedIn KeyPageUp inp+                  pgDown = pressedIn KeyPageDown inp+                  up = pressedIn KeyUp inp+                  down = pressedIn KeyDown inp+                  act = pressedOnceIn KeyEnter inp || pressedOnceIn KeySpace inp+                  mRowRect = case scrollMode of+                    NavNoScroll -> Nothing+                    NavUniformRow step | step > 0 -> Just (\i -> Rect 0 (fromIntegral i * step) 1 step)+                    NavUniformRow _ -> Nothing+                    NavRowRect f -> Just f+              pageStep <-+                if pgUp || pgDown+                  then withContext $ \ctx -> do+                    mm <- readScrollMetrics ctx scrollId+                    let viewH = maybe 0 (rectH . scrollViewport) mm+                        stepH = case scrollMode of+                          NavUniformRow s | s > 0 -> s+                          NavRowRect f -> max 1 (rectH (f (maybe 0 id cur)))+                          _ -> 0+                    pure (if viewH > 0 && stepH > 0 then max 1 (floor (viewH / stepH)) else 10)+                  else pure 10+              let stepBy d def = Just (maybe def (\i -> clamp 0 (count - 1) (i + d)) cur)+                  next+                    | home = Just 0+                    | end = Just (count - 1)+                    | pgUp = stepBy (-pageStep) (count - 1)+                    | pgDown = stepBy pageStep 0+                    | up = stepBy (-1) (count - 1)+                    | down = stepBy 1 0+                    | otherwise = cur+                  changed = next /= cur+              when changed $+                forM_ ((,) <$> mRowRect <*> next) $ \(rectOf, idx) ->+                  withContext (\ctx -> scrollRectIntoView ctx scrollId (rectOf idx) ScrollNearest ScrollInstant)+              pure (ListNav next changed (act && isJust next))++-- | Whether @key@ was pressed this frame, auto-repeats included, while+-- @wid@ holds the keyboard: focused, enabled and not behind a modal. For a+-- custom widget reading the keys it claims ('NanoUI.Widgets.Custom.widgetKeys'),+-- which 'NanoUI.keyPressed' leaves out:+--+-- > (resp, ()) <- customWidget spec {widgetFocusable = True}+-- > whenM (focusedKeyPressed (respId resp) KeyDelete) clearCell+focusedKeyPressed :: WidgetId -> Key -> NanoUI Bool+focusedKeyPressed wid k = keyboardFocused wid <&&> (pressedIn k <$> askInput)++-- | 'focusedKeyPressed' without auto-repeats, so holding the key acts once.+focusedKeyPressedOnce :: WidgetId -> Key -> NanoUI Bool+focusedKeyPressedOnce wid k = keyboardFocused wid <&&> (pressedOnceIn k <$> askInput)++-- | True when Enter or Space was pressed while @wid@ holds focus. Buttons,+-- checkboxes, and toggle switches treat this as a click.+{-# INLINE keyActivated #-}+keyActivated :: WidgetId -> NanoUI Bool+keyActivated wid = do+  nav <- useKeyNav wid+  pure (knEnter nav || knSpace nav)++-- | Escape and click-outside-rect dismiss. Consumes Escape when it fires. A+-- press anywhere else dismisses, whoever it belongs to, so this watches the+-- frame's input rather than the pointer routed here. A press on @opener@+-- does not: the widget that opened the panel toggles it on its own click,+-- which would otherwise reopen what the press just closed. Nor does a press+-- on an open dropdown or text-edit menu, which may lie outside the panel it+-- belongs to, or an Escape that closes one or a focused combo box's list, or+-- that something declared earlier (a popup inside this one) already took+-- ('escapeReserved'). Nor does a press on a+-- floating panel inside @owner@'s (a context menu or popup declared in its+-- body), which may lie past the panel's edge.+useDismissable :: WidgetId -> Rect -> Rect -> NanoUI Bool+useDismissable owner panel opener = do+  inp <- askFrameInput+  withContext $ \ctx -> do+    route <- getsInteraction ctx isPointerRoute+    reserved <- escapeReserved ctx+    let onMenu = case route of+          RouteLayer _ -> False+          _ -> True+        esc = pressedOnceIn KeyEscape inp && not reserved+        pressed = anyButtonPressed inp && not onMenu+        at = inputMousePos inp+        outside = pressed && not (rectContains panel at || rectContains opener at)+    when esc (markEscapeConsumed ctx)+    inChild <- case route of+      RouteLayer k | outside && k /= 0 && k /= intKey owner -> do+        ownerNode <- findNodeByWidgetId ctx owner+        layerNode <- lookupNodeByKey (ctxNodeArena ctx) k+        case (layerNode, ownerNode) of+          (Just l, Just o) -> nodeInSubtree ctx l o+          _ -> pure False+      _ -> pure False+    pure (esc || (outside && not inChild))
+ lib/NanoUI/Internal/Widgets/Button.hs view
@@ -0,0 +1,191 @@+-- | Push buttons.+module NanoUI.Internal.Widgets.Button+  ( button+  , button'+  , buttonWith+  , buttonWith'+  , ButtonConfig (..)+  , defaultButtonConfig+  , buttonConfigured+  , buttonConfigured'+  , iconButton+  , iconButton'+  , buttonContent+  , buttonContent'+  , buttonContentWith+  , buttonContentWith'+  , buttonContentStyled+  , buttonGroup+  , buttonGroupWith+  )+where++import Control.Monad (void, when)+import Data.Bits ((.|.))+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (NodeType (..), addNodeFromLayout, flowChildEnds, foldFlowChildrenM, mixNodePaintHash, setStyleIdx)+import NanoUI.Internal.Monad (NanoUI, askDefaultLayout, uiTheme, withContext)+import NanoUI.Internal.Style (Direction (..), Layout (..), LayoutModifier, Style (..), Theme (..), defaultLayout, gap, tight)+import NanoUI.Internal.Types (Color)+import NanoUI.Internal.WidgetText (ButtonKind (..), buttonFlagContent, buttonKindOf, containerFlagButtonGroup)+import NanoUI.Internal.Widgets.Adornment (Adornments, adornButton, adornmentRow, icon, leading)+import NanoUI.Internal.Widgets.Combinators (buttonStyledEx, widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response, currentParent, respClicked, respId, withContainerNode, withWidgetChildren)+import NanoUI.Svg (Svg)++-- | Button with a text label. 'True' on the frame it is clicked, by pointer+-- or by Enter or Space while focused.+--+-- > whenM (button "Save") saveDocument+button :: Text -> NanoUI Bool+button txt = do+  lay <- widgetBaseLayout defaultLayout id+  respClicked <$> buttonStyledEx True txt 0 lay 0++-- | 'button' returning its 'Response', for tooltips, anchored popups, or+-- hover state.+--+-- > help <- button' "Help"+-- > tooltip help "Open the manual"+-- > when (respClicked help) openManual+button' :: Text -> NanoUI Response+button' txt = do+  lay <- widgetBaseLayout defaultLayout id+  buttonStyledEx True txt 0 lay 0++-- | 'button' with a layout modifier.+--+-- > whenM (buttonWith (fixedW 120) "Submit") submitForm+buttonWith :: (Layout -> Layout) -> Text -> NanoUI Bool+buttonWith f txt = do+  lay <- widgetBaseLayout defaultLayout f+  respClicked <$> buttonStyledEx True txt 0 lay 0++-- | 'buttonWith' returning the full response; activation is in @respClicked@.+buttonWith' :: (Layout -> Layout) -> Text -> NanoUI Response+buttonWith' f txt = do+  lay <- widgetBaseLayout defaultLayout f+  buttonStyledEx True txt 0 lay 0++-- | A button's layout modifier, and the adornments ("NanoUI.Adornment") it draws+-- beside its label. The label and its adornments sit together in the middle+-- of the button, the layout's gap apart.+data ButtonConfig = ButtonConfig+  { bcLayout :: !LayoutModifier+  , bcAdornments :: !Adornments+  }++-- | The default layout and no adornments: a plain 'button'.+defaultButtonConfig :: ButtonConfig+defaultButtonConfig = ButtonConfig {bcLayout = id, bcAdornments = mempty}++-- | 'button' with its own layout or adornments, drawn in the label's color.+--+-- > whenM (buttonConfigured defaultButtonConfig {bcAdornments = A.trailing (A.icon chevron)} "Next") next+{-# INLINE buttonConfigured #-}+buttonConfigured :: ButtonConfig -> Text -> NanoUI Bool+buttonConfigured cfg txt = respClicked <$> buttonConfigured' cfg txt++-- | 'buttonConfigured' returning its 'Response'.+buttonConfigured' :: ButtonConfig -> Text -> NanoUI Response+buttonConfigured' (ButtonConfig f adorns) txt = do+  lay <- widgetBaseLayout defaultLayout f+  resp <- buttonStyledEx True txt 0 lay 0+  adornButton resp lay (labelColor lay) adorns++labelColor :: Layout -> Theme -> Color+labelColor lay theme = fromMaybe (styleFg (themeButton theme)) (layoutFontColor lay)++-- | A button with an icon before its label, or with an empty label an icon+-- alone in a square button.+--+-- > whenM (iconButton saveIcon "Save") saveDocument+-- > whenM (iconButton gearIcon "") openSettings+{-# INLINE iconButton #-}+iconButton :: Svg -> Text -> NanoUI Bool+iconButton doc txt = respClicked <$> iconButton' doc txt++-- | 'iconButton' returning its 'Response', for a tooltip on an icon alone.+{-# INLINE iconButton' #-}+iconButton' :: Svg -> Text -> NanoUI Response+iconButton' doc = buttonConfigured' defaultButtonConfig {bcAdornments = leading (icon doc)}++-- | A button whose content is any view, as iced's buttons are: laid out in a+-- row, the layout's gap apart, and centered as a label is, with a label's+-- padding around it. Labels in it take the button's text color. The content+-- is for display, so a press anywhere on the button is the button's.+--+-- > whenM (buttonContent (svgIcon 16 saveIcon >> label "Save")) saveDocument+{-# INLINE buttonContent #-}+buttonContent :: NanoUI () -> NanoUI Bool+buttonContent = buttonContentWith id++-- | 'buttonContent' returning its 'Response'.+{-# INLINE buttonContent' #-}+buttonContent' :: NanoUI () -> NanoUI Response+buttonContent' = buttonContentWith' id++-- | 'buttonContent' with a layout modifier.+--+-- > whenM (buttonContentWith (gap 4 . fixedW 160) (spinner >> label "Saving")) cancel+{-# INLINE buttonContentWith #-}+buttonContentWith :: (Layout -> Layout) -> NanoUI () -> NanoUI Bool+buttonContentWith f content = respClicked <$> buttonContentWith' f content++-- | 'buttonContentWith' returning its 'Response'.+buttonContentWith' :: (Layout -> Layout) -> NanoUI () -> NanoUI Response+buttonContentWith' f content = do+  lay <- widgetBaseLayout defaultLayout f+  buttonContentStyled 0 0 lay content++-- | A content button with style index @styleIx@ and the extra button+-- @flags@, as a table's header passes them.+buttonContentStyled :: Float -> Word64 -> Layout -> NanoUI () -> NanoUI Response+buttonContentStyled styleIx flags lay content = do+  let kindFlags = if buttonKindOf flags == ButtonPlain then flags .|. buttonFlagContent else flags+  resp <- buttonStyledEx True "" styleIx lay kindFlags+  theme <- uiTheme+  -- The content is the button's one child, which lays out and paints as an+  -- adornment beside an empty label does.+  _ <- withWidgetChildren (respId resp) (adornmentRow lay (labelColor lay theme) content)+  pure resp++-- | A row of adjacent buttons sharing internal 1-pixel borders with outer-only+-- corner rounding. Works with plain buttons, icon buttons, toggle buttons,+-- content buttons, and selects.+--+-- > buttonGroup $ do+-- >   whenM (button "Left") alignL+-- >   whenM (button "Center") alignC+-- >   whenM (button "Right") alignR+{-# INLINE buttonGroup #-}+buttonGroup :: NanoUI a -> NanoUI a+buttonGroup = buttonGroupWith id++-- | 'buttonGroup' with a layout modifier. Defaults to a tight row with zero+-- gap; override 'layoutDirection' to @Column@ for a vertical connected group.+buttonGroupWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a+buttonGroupWith f child = do+  base <- askDefaultLayout+  let lay = f (tight . gap 0 $ base {layoutDirection = Row})+  idx <- withContext $ \ctx -> do+    parent <- currentParent ctx+    idx <- addNodeFromLayout (ctxNodeArena ctx) NodeContainer parent lay+    idx <$ setStyleIdx (ctxNodeArena ctx) idx containerFlagButtonGroup+  res <- withContainerNode True idx child+  -- Mix each direct flow child's 2-bit (isFirst, isLast) cap mask into its+  -- paint hash so adding or removing a sibling repaints the neighbor's corner+  -- rounding and internal seam on partial-damage frames, while ignoring open+  -- dropdowns or tooltips attached to the container.+  withContext $ \ctx -> do+    let na = ctxNodeArena ctx+    (firstC, lastC) <- flowChildEnds na idx+    when (firstC >= 0) $+      void $+        foldFlowChildrenM na idx (\() ci -> do+          let !mask = (if ci == firstC then 1 else 0) .|. (if ci == lastC then 2 else 0 :: Word64)+          mixNodePaintHash na ci (0x424700 .|. mask)) ()+  pure res
+ lib/NanoUI/Internal/Widgets/Caption.hs view
@@ -0,0 +1,216 @@+-- | Client-side decorations for a frameless window: caption buttons,+-- window border, and title-bar drag regions. Window actions are handled by+-- the backend ('NanoUI.Sdl.Internal.Chrome.windowCaption' in @nano-ui-sdl@).+-- Glyphs are rendered as pixel-aligned geometry rather than font glyphs.+module NanoUI.Internal.Widgets.Caption+  ( -- * Buttons+    CaptionGlyph (..)+  , CaptionAction (..)+  , CaptionConfig (..)+  , defaultCaptionConfig+  , captionButton+  , captionButtons+  , captionButtonsConfigured++    -- * The window's border+  , WindowFrame (..)+  , defaultWindowFrame+  , windowFrame++    -- * Geometry+  , captionBarHeight+  , dragSpans+  ) where++import Control.Monad (when)+import Data.List (sortOn)+import Data.Maybe (fromMaybe)+import NanoUI.Internal.Context (Context (..), scopeRawTheme)+import NanoUI.Internal.Layout.Arena (getArenaScope)+import NanoUI.Internal.Monad (NanoUI, styled, themed, withContext)+import NanoUI.Internal.Style+import NanoUI.Internal.Types (Color, Rect (..), V2 (..), lerpColor, rectUnion)+import NanoUI.Path qualified as P+import NanoUI.Widgets.Custom+import NanoUI.Internal.Widgets.Layout (panelWith)+import NanoUI.Internal.Widgets.Node (Response, respClicked, respRect)++-- | Caption button kind and glyph.+data CaptionGlyph+  = GlyphMinimize+  | GlyphMaximize+  | GlyphRestore+  -- ^ Shown on the middle button while the window is maximized.+  | GlyphClose+  deriving (Eq, Show)++-- | Window action triggered by the caption buttons this frame.+data CaptionAction+  = CaptionMinimize+  | CaptionToggleMaximize+  -- ^ Maximize a window that is restored, restore one that is maximized.+  | CaptionClose+  deriving (Eq, Show)++-- | Dimensions and styling for caption buttons.+data CaptionConfig = CaptionConfig+  { capButtonW :: !Float+  -- ^ One button's width.+  , capButtonH :: !Float+  -- ^ One button's height, which is usually the title bar's.+  , capGlyphSize :: !Float+  -- ^ The side of the square a glyph is drawn in, centred in the button.+  , capCloseColor :: !(Maybe Color)+  -- ^ The close button's hover colour; the theme's red when unset.+  , capCornerRadius :: !Float+  -- ^ Rounding of the close button's top-right corner, which is also the+  -- window's corner.+  }+  deriving (Eq, Show)++-- | 44 by 'captionBarHeight' buttons, a ten-pixel glyph, and an 8-pixel+-- corner matching the desktop's window rounding.+defaultCaptionConfig :: CaptionConfig+defaultCaptionConfig =+  CaptionConfig+    { capButtonW = 44+    , capButtonH = captionBarHeight+    , capGlyphSize = 10+    , capCloseColor = Nothing+    , capCornerRadius = 8+    }++-- | A title bar tall enough that a few pixels along its top can resize the+-- window without the rest becoming hard to aim at.+captionBarHeight :: Float+captionBarHeight = 30++-- | One caption button. Highlights on hover or press: 'GlyphClose' in red+-- (rounded at the top right by 'capCornerRadius'), the others a step up from+-- the window background colour.+captionButton :: CaptionConfig -> CaptionGlyph -> NanoUI Response+captionButton cfg glyph = do+  (resp, _) <-+    customWidget+      defaultCustomWidgetSpec+        { widgetLayout = tight . fixedWH (capButtonW cfg) (capButtonH cfg)+        , widgetDraw = \cdc rect -> runCanvasFor cdc $ do+            let theme = cdcTheme cdc+                lit = cdcHovered cdc || cdcPressed cdc+                fg = styleFg (themePanel theme)+            when lit $+              if glyph == GlyphClose+                then cornerRect (capCornerRadius cfg) rect (fromMaybe (themeRed theme) (capCloseColor cfg))+                else drawRect rect (lerpColor (themeWindow theme) fg 0.18)+            drawGlyph glyph (glyphBox (capGlyphSize cfg) rect) (if lit then fg else themeMuted theme)+        }+  pure resp++cornerRect :: Float -> Rect -> Color -> CanvasM ()+cornerRect radius r col+  | radius <= 0 = drawRect r col+  | otherwise = drawPath (P.roundedRectCorners r 0 radius 0 0) col++-- | The three caption buttons in a row: returns the triggered action and the+-- combined button rectangle to exclude from title-bar dragging. Pass whether+-- the window is maximized to select the middle button's glyph.+captionButtons :: Bool -> NanoUI (Maybe CaptionAction, Rect)+captionButtons = captionButtonsConfigured defaultCaptionConfig++-- | 'captionButtons' with custom 'CaptionConfig'.+captionButtonsConfigured :: CaptionConfig -> Bool -> NanoUI (Maybe CaptionAction, Rect)+captionButtonsConfigured cfg maximized = do+  mini <- captionButton cfg GlyphMinimize+  mid <- captionButton cfg (if maximized then GlyphRestore else GlyphMaximize)+  close <- captionButton cfg GlyphClose+  let action+        | respClicked mini = Just CaptionMinimize+        | respClicked mid = Just CaptionToggleMaximize+        | respClicked close = Just CaptionClose+        | otherwise = Nothing+  pure (action, rectUnion (respRect mini) (respRect close))++--------------------------------------------------------------------------------+-- The window's border+--------------------------------------------------------------------------------++-- | Border style for a frameless window.+data WindowFrame = WindowFrame+  { frameWidth :: !Float+  -- ^ The line's thickness, and the view's inset. Zero draws no border.+  , frameRadius :: !Float+  -- ^ Corner rounding, which should match the desktop's for the window.+  , frameColor :: !Color+  }+  deriving (Eq, Show)++-- | A one-pixel border rounded by eight.+defaultWindowFrame :: Color -> WindowFrame+defaultWindowFrame col = WindowFrame {frameWidth = 1, frameRadius = 8, frameColor = col}++-- | Draw a border around the whole window, with the view inside it. A width+-- of zero (for a maximized window) draws none but keeps the container, so+-- the widgets inside keep their ids. The border style stays on the frame's+-- own panel; the view inside uses the surrounding theme.+windowFrame :: WindowFrame -> NanoUI a -> NanoUI a+windowFrame frame body = do+  outer <- withContext $ \ctx -> scopeRawTheme ctx =<< getArenaScope (ctxNodeArena ctx)+  styled+    ( panelStyle+        ( background (themeWindow outer)+            . borderColor (frameColor frame)+            . borderWidth (frameWidth frame)+            . cornerRadius (frameRadius frame)+        )+    )+    $ panelWith (grow . gap 0 . padAll (frameWidth frame) . tight) (themed outer body)++--------------------------------------------------------------------------------+-- Geometry+--------------------------------------------------------------------------------++-- | The parts of a title bar row that drag the window: the row minus the+-- rectangles that take their own clicks, cut horizontally only. Pass the+-- result to the backend as the drag region (@setWindowChrome@ in+-- @nano-ui-sdl@).+dragSpans :: Rect -> [Rect] -> [Rect]+dragSpans (Rect rx ry rw rh) taken =+  filter (\r -> rectW r > 0) (go rx (sortOn rectX (filter overlaps taken)))+  where+    right = rx + rw+    overlaps (Rect tx ty tw th) =+      tw > 0 && th > 0 && tx < right && tx + tw > rx && ty < ry + rh && ty + th > ry+    go x [] = [Rect x ry (right - x) rh]+    go x (Rect tx _ tw _ : rest) =+      Rect x ry (min right tx - x) rh : go (max x (tx + tw)) rest++--------------------------------------------------------------------------------+-- The glyphs+--------------------------------------------------------------------------------++-- | The square a glyph is drawn in, centred on whole pixels.+glyphBox :: Float -> Rect -> Rect+glyphBox s (Rect x y w h) = Rect (whole (x + (w - s) / 2)) (whole (y + (h - s) / 2)) s s++whole :: Float -> Float+whole v = fromIntegral (round v :: Int)++drawGlyph :: CaptionGlyph -> Rect -> Color -> CanvasM ()+drawGlyph glyph box@(Rect x y w h) col = case glyph of+  GlyphMinimize -> drawRect (Rect x (y + whole (h / 2)) w 1) col+  GlyphMaximize -> strokeBox box col+  -- Two overlapping squares; the back one shows only its top and right edges.+  GlyphRestore -> do+    drawRect (Rect (x + 2) y (w - 2) 1) col+    drawRect (Rect (x + w - 1) y 1 (h - 2)) col+    strokeBox (Rect x (y + 2) (w - 2) (h - 2)) col+  GlyphClose -> do+    drawStrokeAA (V2 (x + 0.5) (y + 0.5)) (V2 (x + w - 0.5) (y + h - 0.5)) 1.2 col+    drawStrokeAA (V2 (x + w - 0.5) (y + 0.5)) (V2 (x + 0.5) (y + h - 0.5)) 1.2 col++strokeBox :: Rect -> Color -> CanvasM ()+strokeBox (Rect x y w h) col = do+  drawRect (Rect x y w 1) col+  drawRect (Rect x (y + h - 1) w 1) col+  drawRect (Rect x (y + 1) 1 (h - 2)) col+  drawRect (Rect (x + w - 1) (y + 1) 1 (h - 2)) col
+ lib/NanoUI/Internal/Widgets/Checkbox.hs view
@@ -0,0 +1,68 @@+-- | Boolean buttons: a checkbox, a button in the choice look+-- ('buttonFlagChoice'), and a toggle button, filled while it is on.+module NanoUI.Internal.Widgets.Checkbox+  ( checkbox+  , checkbox'+  , checkboxWith+  , checkboxWith'+  , toggleButton+  , toggleButton'+  , toggleButtonWith+  , toggleButtonWith'+  ) where++import Data.Functor (void)+import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Monad (NanoUI)+import NanoUI.Internal.Style (Layout, Tone, defaultLayout)+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.WidgetText (buttonFlagChoice, buttonToneStyle)+import NanoUI.Internal.Widgets.Combinators (choiceToggleWidget, widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response)++{-# INLINE toggleWith' #-}+toggleWith' :: Word64 -> (Layout -> Layout) -> Text -> Var Bool -> NanoUI Response+toggleWith' flag f txt v = do+  lay <- widgetBaseLayout defaultLayout f+  bindVar RenderFinal v (choiceToggleWidget txt lay flag)++-- | Checkbox with a caption bound to mutable state ('Var'): a click or+-- Space/Enter toggles the value in place.+--+-- > checkbox "Dark mode" settings.darkMode+checkbox :: Text -> Var Bool -> NanoUI ()+checkbox txt v = void (toggleWith' buttonFlagChoice id txt v)++-- | 'checkbox' returning its 'Response'.+checkbox' :: Text -> Var Bool -> NanoUI Response+checkbox' txt v = toggleWith' buttonFlagChoice id txt v++-- | 'checkbox' with a layout modifier: @checkboxWith alignMiddle@ centers it in+-- a row taller than itself, and @checkboxWith fillW@ gives it the row.+checkboxWith :: (Layout -> Layout) -> Text -> Var Bool -> NanoUI ()+checkboxWith f txt v = void (toggleWith' buttonFlagChoice f txt v)++-- | 'checkboxWith' returning its 'Response'.+checkboxWith' :: (Layout -> Layout) -> Text -> Var Bool -> NanoUI Response+checkboxWith' f txt v = toggleWith' buttonFlagChoice f txt v++-- | Toggle button bound to mutable state ('Var'): filled in the tone's color+-- while on, a plain button while off. A click or Space/Enter toggles it in place.+--+-- > toggleButton Warning "M" muted+toggleButton :: Tone -> Text -> Var Bool -> NanoUI ()+toggleButton t txt v = void (toggleWith' (buttonToneStyle t) id txt v)++-- | 'toggleButton' returning its 'Response'.+toggleButton' :: Tone -> Text -> Var Bool -> NanoUI Response+toggleButton' t txt v = toggleWith' (buttonToneStyle t) id txt v++-- | 'toggleButton' with a layout modifier: @toggleButtonWith (fixedWH 32 30)@.+toggleButtonWith :: (Layout -> Layout) -> Tone -> Text -> Var Bool -> NanoUI ()+toggleButtonWith f t txt v = void (toggleWith' (buttonToneStyle t) f txt v)++-- | 'toggleButtonWith' returning its 'Response'.+toggleButtonWith' :: (Layout -> Layout) -> Tone -> Text -> Var Bool -> NanoUI Response+toggleButtonWith' f t txt v = toggleWith' (buttonToneStyle t) f txt v
+ lib/NanoUI/Internal/Widgets/ColorPicker.hs view
@@ -0,0 +1,510 @@+-- | Colour picker. The saturation / value field, the hue bar, the alpha bar and+-- the Current / New preview are separate 'NodeColorPicker' nodes in one row,+-- so each bar is its own focus stop with its own keyboard control.+module NanoUI.Internal.Widgets.ColorPicker+  ( ColorPickerPart (..)+  , colorPickerPartOf+  , widgetStoreColor+  , widgetStoreBaseColor+  , colorPickerSvSquare+  , colorPickerPartRect+  , colorPickerPreviewGeom+  , drawColorPickerPart+  , colorPicker+  , colorPicker'+  , colorPickerRGBA+  , colorPickerRGBA'+  )+where++import Control.Monad (forM_, guard, void, when)+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.Word (Word8, Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Draw+import NanoUI.Internal.Font+import NanoUI.Internal.Id (WidgetId (..), mix64, mkWidgetId)+import NanoUI.Internal.Input (Input (..), Key (..), Pressable (..), inputModifiers, modShift, shiftAtMost)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (NanoUI, askContext, askInput, freshWidget, nextId, liftIO, withKey)+import NanoUI.Internal.Store (fieldFloat, fieldInt, fieldPoint, findSlot, insertSlot, insertSpec, lookupSlot, lookupSpec, specKey, specWriteOr)+import NanoUI.Internal.Store.Slots (slotColorBase, slotSeen)+import NanoUI.Internal.Style+import NanoUI.Internal.Types+import NanoUI.Internal.WidgetText+import qualified NanoUI.Internal.StyleBits as SB+import NanoUI.Internal.Widgets.Behavior+import NanoUI.Internal.Widgets.Node+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.NumericInput (NumericInputConfig (..), defaultNumericInputConfig, numericInputCore)+import NanoUI.Widgets.TextEditor (singleLineMode)+import NanoUI.Internal.Widgets.TextInput (editTextField)++colorPickerDefaultColor :: Color+colorPickerDefaultColor = colorRGBA 128 128 128 255++colorPickerBarW :: Float+colorPickerBarW = 14++-- | The piece of a colour picker a 'NodeColorPicker' node paints, kept in the+-- low bits of its style.+data ColorPickerPart = PickerSv | PickerHue | PickerAlpha | PickerPreview+  deriving (Eq, Show, Enum, Bounded)++{-# INLINE colorPickerPartOf #-}+colorPickerPartOf :: Word64 -> ColorPickerPart+colorPickerPartOf si = toEnum (SB.getField SB.pickerPart si)++-- | The id of the container holding a picker's parts, derived from the+-- field's id. The picker's state is keyed on it: every part reads that state+-- at paint time, and a write to the container's key damages the container's+-- rect, which covers them all. Readers take the field's id (the picker's+-- response id) and map it here.+pickerStateId :: WidgetId -> WidgetId+pickerStateId (WidgetId w) = mkWidgetId (mix64 w 0x434F4C5243414E56)++pickerKey :: WidgetId -> Int+pickerKey = intKey . pickerStateId++packColor :: Color -> Int+packColor = fromIntegral . colorToWord32++storeColorAt :: WidgetStore -> Int -> Color -> Color+storeColorAt store key fallback =+  Color (fromIntegral (findSlot fieldInt (packColor fallback) key store))++-- | Picker's current stored colour, or the supplied fallback if absent.+widgetStoreColor :: WidgetStore -> WidgetId -> Color -> Color+widgetStoreColor store wid fallback = storeColorAt store (pickerKey wid) fallback++-- | Picker's comparison colour, falling back to its current colour and then+-- the caller's default.+widgetStoreBaseColor :: WidgetStore -> WidgetId -> Color -> Color+widgetStoreBaseColor store wid fallback =+  storeColorAt+    store+    (specKey slotColorBase (pickerKey wid))+    (widgetStoreColor store wid fallback)++-- | The picker's hue, saturation and value. RGB cannot tell hue 0 from 360,+-- and black collapses S, so the hue and S/V the user last set are kept: the+-- hue slider stays at the end it was put at, and the marker does not jitter.+widgetStoreHsv :: WidgetStore -> WidgetId -> Color -> (Float, Float, Float)+widgetStoreHsv store wid fallback =+  let+    (h0, s0, v0) = rgbToHsv (widgetStoreColor store wid fallback)+    V2 s v = findSlot fieldPoint (V2 s0 v0) (pickerKey wid) store+   in+    (findSlot fieldFloat h0 (pickerKey wid) store, s, v)++-- | Store the live colour with the hue and S/V it was set through.+putColorState :: Int -> Color -> (Float, Float, Float) -> WidgetStore -> WidgetStore+putColorState key col (h, s, v) =+  insertSlot fieldInt key (packColor col)+    . insertSlot fieldFloat key h+    . insertSlot fieldPoint key (V2 s v)++-- | The square the saturation / value field fills, centered in its node.+colorPickerSvSquare :: Rect -> Rect+colorPickerSvSquare (Rect x y w h) =+  let s = max 0 (min w h)+   in Rect (x + (w - s) / 2) (y + (h - s) / 2) s s++-- | The field node of the picker a part belongs to: the part's sibling that+-- paints the saturation / value square. Its widget id names the picker.+pickerSvNode :: NodeArena -> NodeIdx -> IO NodeIdx+pickerSvNode na idx = do+  parent <- getParent na idx+  if parent < 0+    then pure idx+    else fmap (fromMaybe idx) . firstChildJustM na parent $ \ci -> do+      nt <- getNodeType na ci+      si <- getStyleIdx na ci+      pure (ci <$ guard (nt == NodeColorPicker && colorPickerPartOf si == PickerSv))++-- | Resolve the owning picker's widget id, the part kind, and the rectangle+-- the part draws in (the SV square, or the part's column cut to the SV+-- square's vertical band).+pickerPartOwnerAndRect :: NodeArena -> NodeIdx -> Rect -> IO (WidgetId, ColorPickerPart, Rect)+pickerPartOwnerAndRect na idx rect@(Rect x _ w _) = do+  part <- colorPickerPartOf <$> getStyleIdx na idx+  if part == PickerSv+    then (,part,colorPickerSvSquare rect) <$> getWidgetId na idx+    else do+      svIdx <- pickerSvNode na idx+      owner <- getWidgetId na svIdx+      Rect sx sy0 sw sh <- getNodeRect na svIdx+      let Rect _ sy _ side = colorPickerSvSquare (Rect sx sy0 sw sh)+      pure (owner, part, Rect x sy w side)++-- | Where the part at @idx@ (laid out at @rect@) draws: the field's square, or+-- the part's column cut to the square's height so the bars and the preview+-- line up with the field.+colorPickerPartRect :: NodeArena -> NodeIdx -> Rect -> IO Rect+colorPickerPartRect na idx rect = (\(_, _, r) -> r) <$> pickerPartOwnerAndRect na idx rect++-- | The preview column's rows, stacked and centered in its band: the Current+-- label's top, its swatch, the New label's top, and its swatch.+colorPickerPreviewGeom :: FontMetrics -> Rect -> (Float, Rect, Float, Rect)+colorPickerPreviewGeom fm (Rect x y w h) =+  let+    labelH = fmLineHeight fm+    swatchW = min 80 w+    swatchH = clamp 0 30 ((h - labelH * 2 - colorPickerGap) / 2)+    stackH = labelH + swatchH + colorPickerGap + labelH + swatchH+    top = y + max 0 ((h - stackH) / 2)+    currentY = top + labelH+    newLabelY = currentY + swatchH + colorPickerGap+   in+    (top, Rect x currentY swatchW swatchH, newLabelY, Rect x (newLabelY + labelH) swatchW swatchH)++drawChecker :: DrawArena -> Rect -> IO ()+drawChecker da (Rect x y w h) = goRows 0+  where+    s = 6 :: Float+    cols = ceiling (max 0 w / s) :: Int+    rows = ceiling (max 0 h / s) :: Int+    -- Nested range folds retain a shared column list under -O2. Explicit+    -- counters keep both loops numeric, without allocating that list.+    goRows !ry = when (ry < rows) $ do+      goCols ry 0+      goRows (ry + 1)+    goCols !ry !cx = when (cx < cols) $ do+      let+        col =+          if even (ry + cx) then colorRGBA 190 190 190 255 else colorRGBA 140 140 140 255+        rx = x + fromIntegral cx * s+        ry' = y + fromIntegral ry * s+        cw = clamp 0 s (x + w - rx)+        ch = clamp 0 s (y + h - ry')+      pushRect da (Rect rx ry' cw ch) col+      goCols ry (cx + 1)++-- | Paint one part of a picker from its state in the store.+drawColorPickerPart :: NodeArena -> NodeIdx -> FontMetrics -> DrawArena -> WidgetStore -> Style -> Rect -> IO ()+drawColorPickerPart na idx fm da store style rect = do+  (owner, part, area@(Rect x y w h)) <- pickerPartOwnerAndRect na idx rect+  let+    newCol = widgetStoreColor store owner colorPickerDefaultColor+    (hue, sat, val) = widgetStoreHsv store owner colorPickerDefaultColor+    border = styleBorder style+    white = colorRGBA 255 255 255 255+    handleCol = colorRGBA 0 0 0 180+    pushVGrad r topC botC = pushQuadGradient da r topC topC botC botC+    -- A bar's outline and its handle, @frac@ of the way down.+    barHandle frac = do+      let handle = Rect (x - 3) (y + frac * h - 2) (w + 6) 4+      pushRoundedStroke da area 3 1 border+      pushRoundedRect da handle 2 white+      pushRoundedStroke da handle 2 1 handleCol+  case part of+    PickerSv -> do+      let hueCol = hsvToRgb hue 1 1+          dot = Rect (x + sat * w - 3) (y + (1 - val) * h - 3) 6 6+      -- Horizontal: white to hue. Vertical overlay: fade to black (alpha over).+      pushQuadGradient da area white hueCol hueCol white+      pushVGrad area (colorRGBA 0 0 0 0) (colorRGBA 0 0 0 255)+      pushRoundedStroke da area 4 1 border+      pushRoundedRect da dot 3 white+      pushRoundedStroke da dot 3 1 handleCol+    PickerHue -> do+      -- Vertical rainbow: each of six stop bands fades into the next.+      let cellH = h / 6+          stop i = hsvToRgb (60 * fromIntegral i) 1 1+      forM_ [0 .. 5 :: Int] $ \i ->+        pushVGrad (Rect x (y + fromIntegral i * cellH) w cellH) (stop i) (stop (i + 1))+      barHandle (hue / 360)+    PickerAlpha -> do+      drawChecker da area+      pushVGrad area (fadeAlpha newCol 0) (fadeAlpha newCol 255)+      barHandle (fromIntegral (colorA newCol) / 255)+    PickerPreview -> do+      let (_, current, _, new) = colorPickerPreviewGeom fm area+          swatch r col = do+            drawChecker da r+            pushRect da r col+            pushRoundedStroke da r 0 1 border+      swatch current (widgetStoreBaseColor store owner colorPickerDefaultColor)+      swatch new newCol++colorPickerLayout :: Direction -> Layout+colorPickerLayout dir = tight . fillW . gap colorPickerGap $ defaultLayout {layoutDirection = dir}++-- The field grows up to a square as tall as the row.+colorPickerSvLayout :: Layout+colorPickerSvLayout =+  tight . fillW . fixedH colorPickerSvH . minW 60 . maxW colorPickerSvH $ defaultLayout++-- A row of channel fields. Children are groups sized by 'percent' so the+-- R/G/B(/A) and H/S/V rows share the same column widths.+colorPickerRowLayout :: Layout+colorPickerRowLayout = itemsCenter (colorPickerLayout Row)++-- One channel field: an inline label plus its bare box, taking @pct@ of the row.+colorPickerFieldGroupLayout :: Float -> Layout+colorPickerFieldGroupLayout pct = percent pct colorPickerRowLayout++colorPickerFieldLayout :: Layout+colorPickerFieldLayout = tight . fillW . minW 40 $ defaultLayout++-- | RGB colour picker bound to mutable state ('Var'): a saturation/value+-- field, a hue bar, and RGB, HSV and hex fields. Edits mutate the 'Var' in+-- place. Without an alpha bar, any edit makes the colour opaque; use+-- 'colorPickerRGBA' to keep its alpha.+--+-- The field and each bar take keyboard focus in turn. On the field the arrow+-- keys move the marker (left and right for saturation, up and down for+-- value); on a bar they move its handle, and Home and End jump to its ends.+-- Shift takes steps ten times larger.+{-# INLINE colorPicker #-}+colorPicker :: Var Color -> NanoUI ()+colorPicker v = void (colorPicker' v)++-- | 'colorPicker' returning its 'Response'.+{-# INLINE colorPicker' #-}+colorPicker' :: Var Color -> NanoUI Response+colorPicker' v = bindVar RenderFinal v (colorPickerWith False)++-- | 'colorPicker' with an alpha bar and an A / @#RRGGBBAA@ field.+{-# INLINE colorPickerRGBA #-}+colorPickerRGBA :: Var Color -> NanoUI ()+colorPickerRGBA v = void (colorPickerRGBA' v)++-- | 'colorPickerRGBA' returning its 'Response'.+{-# INLINE colorPickerRGBA' #-}+colorPickerRGBA' :: Var Color -> NanoUI Response+colorPickerRGBA' v = bindVar RenderFinal v (colorPickerWith True)++-- | The byte fields: label, the channel read, and the channel write.+rgbChannels, rgbaChannels :: [(Text, Color -> Word8, Word8 -> Color -> Color)]+rgbChannels =+  [ ("R", colorR, \v c -> colorRGBA v (colorG c) (colorB c) (colorA c))+  , ("G", colorG, \v c -> colorRGBA (colorR c) v (colorB c) (colorA c))+  , ("B", colorB, \v c -> colorRGBA (colorR c) (colorG c) v (colorA c))+  ]+rgbaChannels = rgbChannels ++ [("A", colorA, flip fadeAlpha)]++-- | The HSV fields: label, the largest value, the shown value, and the+-- (hue, s, v) a typed value makes.+hsvChannels :: [(Text, Int, (Float, Float, Float) -> Int, Int -> (Float, Float, Float) -> (Float, Float, Float))]+hsvChannels =+  [ ("H", 360, \(h, _, _) -> round h, \n (_, s, v) -> (fromIntegral n, s, v))+  , ("S", 100, \(_, s, _) -> round (s * 100), \n (h, _, v) -> (h, fraction n, v))+  , ("V", 100, \(_, _, v) -> round (v * 100), \n (h, s, _) -> (h, s, fraction n))+  ]+  where+    fraction n = fromIntegral n / 100++colorPickerWith ::+  Bool -> Color -> NanoUI (Response, Color)+colorPickerWith showAlpha value = do+  (wid, ctx) <- freshWidget+  hueWid <- nextId+  alphaWid <- nextId+  previewWid <- nextId+  let+    key = pickerKey wid+    pct = 100 / (if showAlpha then 4 else 3)+    readColor = (\st -> widgetStoreColor st wid value) <$> liftIO (getStore ctx)+    writePicker col hsv = liftIO (modifyStore ctx (putColorState key col hsv))+    writeColor col = writePicker col (rgbToHsv col)+    -- Without the alpha bar the colour stays opaque.+    alphaOf c = if showAlpha then colorA c else 255+    part pid p lay = (,) pid <$> addWidgetStyled pid NodeColorPicker "" 0 lay (fromIntegral (fromEnum p))+    column w = fixedW w colorPickerSvLayout+  liftIO $ do+    adoptColorPickerValue ctx wid value+    mapM_ (registerFocusable ctx) (wid : hueWid : [alphaWid | showAlpha])+  (start, final, svResp) <- container NodeContainer (colorPickerLayout Column) $ do+    (sv, hue, alphaPart) <-+      container NodeContainer (colorPickerLayout Row) $ do+        tagContainer (pickerStateId wid)+        sv <- part wid PickerSv colorPickerSvLayout+        hue <- part hueWid PickerHue (column colorPickerBarW)+        alphaPart <-+          if showAlpha+            then Just <$> part alphaWid PickerAlpha (column colorPickerBarW)+            else pure Nothing+        void (part previewWid PickerPreview (column 112))+        pure (sv, hue, alphaPart)+    start <- colorPickerCanvas sv hue alphaPart value+    -- Only the focused field edits, so each row's fields share one store read.+    rgb <- readColor+    _ <- container NodeContainer colorPickerRowLayout $+      forM_ (if showAlpha then rgbaChannels else rgbChannels) $ \(lbl, get, set) -> do+        let shown = fromIntegral (get rgb)+        n <- channelField pct lbl 255 shown+        when (n /= shown) $ do+          let c' = set (fromIntegral n) (fadeAlpha rgb (alphaOf rgb))+          if lbl == "A"+            then do+              st <- liftIO (getStore ctx)+              writePicker c' (widgetStoreHsv st wid value)+            else writeColor c'+    hsvStore <- liftIO (getStore ctx)+    let+      hsv = widgetStoreHsv hsvStore wid value+      alpha = alphaOf (widgetStoreColor hsvStore wid value)+    _ <- container NodeContainer colorPickerRowLayout $ do+      forM_ hsvChannels $ \(lbl, hi, shown, edit) -> do+        let cur = shown hsv+        n <- channelField pct lbl hi cur+        when (n /= cur) $ do+          let hsv'@(h, s, v) = edit n hsv+          writePicker (fadeAlpha (hsvToRgb h s v) alpha) hsv'+      when showAlpha $+        void (container NodeContainer (colorPickerFieldGroupLayout pct) (pure ()))+    hex <- readColor+    let hexText = if showAlpha then colorToHexA hex else colorToHex hex+    hexWid <- nextId+    (_, thex, fhex, _) <- editTextField hexWid singleLineMode hexText (Just hexText)+    _ <-+      container NodeContainer (colorPickerFieldGroupLayout 100) $+        addWidgetStyled hexWid NodeTextInput "" 0 colorPickerFieldLayout 0+    when (fhex && thex /= hexText) $+      forM_ (colorPickerParseHex thex) $ \(r, g, b, ma) ->+        writeColor (colorRGBA r g b (if showAlpha then fromMaybe (colorA hex) ma else 255))+    final <- readColor+    -- A field edit commits the "current" swatch at once, as a key step does.+    when (final /= rgb) $ liftIO (commitColorPickerCurrent ctx wid final)+    pure (start, final, snd sv)+  liftIO $ recordSlot fieldInt ctx key (packColor final)+  pure (setChanged (final /= start) svResp, final)++-- | The field and the bars, each its part's id and response: pointer drags,+-- then arrow keys on whichever part holds focus, then committing the+-- "current" swatch when a drag ends or a key moved the colour. Returns the+-- colour the frame started with.+colorPickerCanvas ::+  (WidgetId, Response) ->+  (WidgetId, Response) ->+  Maybe (WidgetId, Response) ->+  Color ->+  NanoUI Color+colorPickerCanvas (wid, svResp) (hueWid, hueResp) alphaPart initial = do+  ctx <- askContext+  inp <- askInput+  store0 <- liftIO (getStore ctx)+  let+    current0 = widgetStoreColor store0 wid initial+    (h0, s0, v0) = widgetStoreHsv store0 wid initial+    -- A press starts the drag of the part it lands on: the parts' hit rects+    -- share no point, the bars' slack being narrower than the gaps.+    svSquare = colorPickerSvSquare (respRect svResp)+    -- A bar's column cut to the field's height, and wider than the painted+    -- bar so the handle is easy to grab.+    barHit resp =+      Rect (rectX (respRect resp) - 2) (rectY svSquare) (rectW (respRect resp) + 4) (rectH svSquare)+  (s, sA, sHeld) <- withKey ("s" :: Text) (useDrag1D DragAxisX wid 0 1 s0 svSquare)+  (v, vA, vHeld) <- withKey ("v" :: Text) (useDrag1D DragAxisY wid 1 0 v0 svSquare)+  (h, hA, hHeld) <- withKey ("hue" :: Text) (useDrag1D DragAxisY hueWid 0 360 h0 (barHit hueResp))+  (a, aA, aHeld) <-+    withKey ("alpha" :: Text) $+      useDrag1D DragAxisY (maybe wid fst alphaPart) 0 255 (fromIntegral (colorA current0)) (maybe (Rect 0 0 0 0) (barHit . snd) alphaPart)+  let+    dragging = sA || vA || hA || aA+    alpha = fromIntegral (clamp 0 255 (round a :: Int))+    dragged+      | aA && not (sA || vA || hA) = fadeAlpha current0 alpha+      | otherwise = fadeAlpha (hsvToRgb h s v) (if isJust alphaPart then alpha else 255)+  holdActiveWhile wid dragging+  when (dragging && (dragged /= current0 || h /= h0 || s /= s0 || v /= v0)) $+    liftIO $ modifyStore ctx (putColorState (pickerKey wid) dragged (h, s, v))+  svFocus <- keyboardFocused wid+  hueFocus <- keyboardFocused hueWid+  alphaFocus <- maybe (pure False) (keyboardFocused . fst) alphaPart+  keyMoved <-+    if svFocus || hueFocus || alphaFocus+      then liftIO (applyColorPickerKeys ctx wid initial inp (isJust alphaPart) svFocus hueFocus)+      else pure False+  let releasedDrag = (sHeld || vHeld || hHeld || aHeld) && not dragging+  when (releasedDrag || keyMoved) $+    liftIO $ do+      st <- getStore ctx+      commitColorPickerCurrent ctx wid (widgetStoreColor st wid initial)+  pure current0++channelLabelLayout :: Layout+channelLabelLayout = tight (alignMiddle defaultLayout)++channelNumericLayout :: Layout+channelNumericLayout = minW 60 colorPickerFieldLayout++channelConfig100, channelConfig255, channelConfig360 :: NumericInputConfig+channelConfig100 = defaultNumericInputConfig {nicMin = 0, nicMax = 100, nicLayout = const channelNumericLayout}+channelConfig255 = defaultNumericInputConfig {nicMin = 0, nicMax = 255, nicLayout = const channelNumericLayout}+channelConfig360 = defaultNumericInputConfig {nicMin = 0, nicMax = 360, nicLayout = const channelNumericLayout}++-- | One channel field: an inline label and a numeric box over @0..hi@ that+-- shows @value@ while unfocused. Returns the value after this frame's edits.+channelField :: Float -> Text -> Int -> Int -> NanoUI Int+channelField pct label hi value =+  container NodeContainer (colorPickerFieldGroupLayout pct) $ do+    labelWid <- nextId+    void (addWidget labelWid NodeText label 0 channelLabelLayout)+    -- Room for three digits beside the stepper.+    let !cfg = case hi of+          255 -> channelConfig255+          100 -> channelConfig100+          360 -> channelConfig360+          _ -> defaultNumericInputConfig {nicMin = 0, nicMax = fromIntegral hi, nicLayout = const channelNumericLayout}+    round . snd <$> numericInputCore cfg (fromIntegral value)++-- | Adopt the caller's colour as 'adoptSlot' does. A new+-- colour also resets the hue, S/V, and the "current" swatch.+adoptColorPickerValue :: Context -> WidgetId -> Color -> IO ()+adoptColorPickerValue ctx wid value = do+  store0 <- getStore ctx+  let+    key = pickerKey wid+    packed = packColor value+    seen = insertSpec (slotSeen fieldInt) key packed store0+  when (lookupSpec (slotSeen fieldInt) key store0 /= Just packed) $+    setStore ctx $+      if lookupSlot fieldInt key store0 == Just packed+        then seen+        else putColorState key value (rgbToHsv value) (insertSpec slotColorBase key packed seen)++commitColorPickerCurrent :: Context -> WidgetId -> Color -> IO ()+commitColorPickerCurrent ctx wid col =+  let packed = packColor col+   in writeSlots ctx (specWriteOr slotColorBase packed (pickerKey wid) packed)++-- | Arrow, Home and End keys on the focused part: the field when @svFocus@,+-- the hue bar when @hueFocus@, otherwise the alpha bar. Arrows move a part+-- the way it is drawn: the marker right for more saturation and up for more+-- value, a bar's handle down (or right) towards its bottom end. Without an+-- alpha bar (@hasAlpha@), the colour comes out opaque. Returns whether the+-- colour moved.+applyColorPickerKeys :: Context -> WidgetId -> Color -> Input -> Bool -> Bool -> Bool -> IO Bool+applyColorPickerKeys ctx wid fallback inp hasAlpha svFocus hueFocus = do+  store <- getStore ctx+  let+    -- Arrows with Ctrl, Alt or Super are left to shortcuts.+    down k = shiftAtMost (inputModifiers inp) && pressedIn k inp+    step = if modShift (inputModifiers inp) then 10 else 1+    along neg pos = (if down pos then 1 else 0) - (if down neg then 1 else 0) :: Float+    dx = along KeyLeft KeyRight+    dy = along KeyUp KeyDown+    current = widgetStoreColor store wid fallback+    alpha = if hasAlpha then colorA current else 255+    hsv@(h, s, v) = widgetStoreHsv store wid fallback+    bar lo hi cur+      | down KeyHome = lo+      | down KeyEnd = hi+      | otherwise = clamp lo hi (cur + (dx + dy) * step)+    (col', hsv')+      | svFocus =+          let sat = clamp01 (s + dx * step / 100)+              val = clamp01 (v - dy * step / 100)+           in (fadeAlpha (hsvToRgb h sat val) alpha, (h, sat, val))+      | hueFocus =+          let hue = bar 0 360 h+           in (fadeAlpha (hsvToRgb hue s v) alpha, (hue, s, v))+      | otherwise = (fadeAlpha current (round (bar 0 255 (fromIntegral (colorA current)))), hsv)+    moved = col' /= current || hsv' /= hsv+  when moved $+    setStore ctx (putColorState (pickerKey wid) col' hsv' store)+  pure moved
+ lib/NanoUI/Internal/Widgets/Combinators.hs view
@@ -0,0 +1,136 @@+-- | Button, selection and cache helpers shared by the widget modules.+module NanoUI.Internal.Widgets.Combinators+  ( widgetBaseLayout+  , buttonStyledEx+  , choiceToggleWidget+  , bindEnumPicker+  , nonEmptyOpts+  , finishToggle+  , finishInput+  , readDerived+  , writeDerived+  )+where++import Control.Monad (when)+import Data.Foldable (toList)+import Data.IORef (modifyIORef', readIORef)+import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Derived (DerivedField, insertDerived, lookupDerived)+import NanoUI.Internal.Equality (sameEnum)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askDefaultLayout, freshWidget, liftIO)+import NanoUI.Internal.Store (Field, boolInt, fieldInt)+import NanoUI.Internal.Style (Layout (..), inheritFont)+import NanoUI.Internal.Var (Binding (..), bindVarBy)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Behavior (keyActivated)+import NanoUI.Internal.Widgets.Node++-- | Apply @f@ over @base@ after inheriting the ambient default layout's font.+{-# INLINE widgetBaseLayout #-}+widgetBaseLayout :: Layout -> (Layout -> Layout) -> NanoUI Layout+widgetBaseLayout base f = do+  dl <- askDefaultLayout+  pure (f (inheritFont dl base))++-- | A button, given whether it is enabled, its value, and a style index for+-- active, sort, badge, or close chrome: the shared activation path for+-- ordinary buttons, menu items, and header chrome. An enabled button is+-- focusable and activatable with Enter or Space while focused.+-- Disabled controls keep their identity and geometry but cannot take focus or+-- activate, including through a click queued before they became disabled.+{-# INLINE buttonStyledEx #-}+buttonStyledEx :: Bool -> Text -> Float -> Layout -> Word64 -> NanoUI Response+buttonStyledEx enabled txt value layout styleIdx = do+  (wid, ctx) <- freshWidget+  disabled <- liftIO (isDisabled ctx wid)+  let active = enabled && not disabled+  when active $ liftIO (registerFocusable ctx wid)+  resp <- addWidgetStyled wid NodeButton txt value layout styleIdx+  if active+    then do+      keyClick <- keyActivated wid+      pure (if keyClick then setClicked True resp else resp)+    else pure (inertResponse resp)++-- | Controlled toggle widget: registers focus, adopts the boolean model value,+-- lays out and styles the node, resolves toggle clicks and keyboard activation,+-- and updates the node's visual value when toggled.+{-# INLINE choiceToggleWidget #-}+choiceToggleWidget :: Text -> Layout -> Word64 -> Bool -> NanoUI (Response, Bool)+choiceToggleWidget txt lay flag on = do+  (wid, ctx) <- freshWidget+  liftIO $ registerFocusable ctx wid+  current <- liftIO (intBool <$> adoptSlot fieldInt ctx wid (boolInt on))+  resp <- addWidgetStyled wid NodeButton txt (if current then 1 else 0) lay flag+  result@(_, value) <- finishToggle ctx wid current resp+  when (value /= current) . liftIO $ setWidgetValue ctx wid (if value then 1 else 0)+  pure result++-- | Finish a boolean control after its node has registered focus eligibility.+-- Keyboard activation changes the value without inventing a pointer click.+{-# INLINE finishToggle #-}+finishToggle ::+  Context -> WidgetId -> Bool -> Response -> NanoUI (Response, Bool)+finishToggle ctx wid current resp = do+  keyClick <- keyActivated wid+  let+    clicked = respClicked resp || keyClick+    value = current /= clicked+  liftIO $ do+    writeStoreBool ctx wid value+    recordSlot fieldInt ctx (intKey wid) (boolInt value)+  pure (setChanged clicked resp, value)++-- | Publish an input's result and record it for controlled adoption. The+-- caller chooses the comparison value: live state or the supplied model value.+{-# INLINE finishInput #-}+finishInput ::+  Eq a =>+  Field a+  -> Context+  -> WidgetId+  -> a+  -> Response+  -> a+  -> NanoUI (Response, a)+finishInput field ctx wid original resp value = do+  liftIO $ do+    writeSlot field ctx wid (intKey wid) value+    recordSlot field ctx (intKey wid) value+  pure (setChanged (value /= original) resp, value)++-- | The value widget @key@ cached in 'ctxDerivedCache', if present.+readDerived :: DerivedField a -> Context -> Int -> IO (Maybe a)+readDerived field ctx key = lookupDerived field key <$> readIORef (ctxDerivedCache ctx)++-- | Cache a value derived by widget @key@. Entries of widgets no longer+-- built are never removed one by one, so a full cache is cleared instead,+-- when a new key would grow it; replacing a key's entry never clears it.+writeDerived :: DerivedField a -> Context -> Int -> a -> IO ()+writeDerived field ctx key value = modifyIORef' (ctxDerivedCache ctx) (insertDerived field key value)++-- | Non-empty option list, defaulting an empty foldable to a single blank option.+nonEmptyOpts :: Foldable f => f Text -> [Text]+nonEmptyOpts xs = case toList xs of+  [] -> [""]+  ys -> ys++-- | Bind a 'Var' over every value of a bounded enum to an index-based picker.+-- Indices are offset by @fromEnum minBound@, so enums that do not start at 0+-- map accurately.+{-# INLINE bindEnumPicker #-}+bindEnumPicker ::+  forall a.+  (Bounded a, Enum a) =>+  ([Text] -> Int -> NanoUI (Response, Int)) -> (a -> Text) -> Var a -> NanoUI Response+bindEnumPicker pick encode v =+  bindVarBy sameEnum RenderFinal v $ \val ->+    fmap (toEnum . (+ lower)) <$> pick opts (fromEnum val - lower)+  where+    lower = fromEnum (minBound :: a)+    opts = map encode [minBound .. maxBound]
+ lib/NanoUI/Internal/Widgets/Cursor.hs view
@@ -0,0 +1,36 @@+-- | The pointer shape over part of a view. The frame resolves it after layout+-- ("NanoUI.Internal.Frame.Cursor"), against the nodes the scope declared.+module NanoUI.Internal.Widgets.Cursor+  ( withCursorShape+  ) where++import Control.Monad (when)+import Data.IORef (modifyIORef')+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Input (UiCursorKind)+import NanoUI.Internal.Monad (NanoUI, askContext, withArenaRange)++-- | Show @shape@ while the pointer is over the widgets and containers declared+-- inside. Gaps in the enclosing container keep their own cursor.+--+-- Widgets with their own cursor keep it: a button still shows the hand and a+-- text field the I-beam. A custom widget whose+-- 'NanoUI.Widgets.Custom.widgetCursor' returns 'NanoUI.UiCursorDefault' shows the+-- scope's shape. Disabled widgets have no cursor of their own, so they show+-- the scope's shape too. The innermost scope wins, so a nested+-- @withCursorShape UiCursorDefault@ restores the arrow, and 'NanoUI.UiCursorHidden'+-- hides the pointer.+--+-- > withCursorShape UiCursorCrosshair (drawing (fixedWH 320 200) plot)+-- > withCursorShape UiCursorNotAllowed (disabledWhen locked (button "Delete"))+--+-- The scope takes no widget id and adds no layout node, so wrapping a view in+-- it changes neither ids nor layout. Windows and popups declared inside also+-- get the shape. Only the pointer position matters: a drag that leaves the+-- scope's widgets loses the shape.+withCursorShape :: UiCursorKind -> NanoUI a -> NanoUI a+withCursorShape !shape body = do+  ctx <- askContext+  withArenaRange+    (\start end -> when (end > start) $ modifyIORef' (ctxCursorRegions ctx) ((start, end, shape) :))+    body
+ lib/NanoUI/Internal/Widgets/Custom.hs view
@@ -0,0 +1,40 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | 'CustomDrawContext' construction for custom widgets ("NanoUI.Widgets.Custom")+-- and the paint, damage and cursor passes.+module NanoUI.Internal.Widgets.Custom+  ( mkCustomDrawContext+  , customDrawContext+  ) where++import Data.IORef (readIORef)+import NanoUI.Internal.Context (Context (..), CustomDrawContext (..), getFocusId, getHotId, isDisabled, widgetTheme)+import NanoUI.Internal.Font (FontMetrics)+import NanoUI.Internal.Id (WidgetId)++-- | Build a 'CustomDrawContext' for @wid@, resolving hover, press and focus+-- state from the 'Context'.+mkCustomDrawContext ::Context -> FontMetrics -> WidgetId -> IO CustomDrawContext+mkCustomDrawContext ctx fm wid = do+  hot <- getHotId ctx+  active <- readIORef (ctxActiveId ctx)+  customDrawContext ctx fm wid (hot == wid) (active == wid)++-- | Draw context for @wid@ with the given hover and press state; a disabled+-- widget is never hovered or pressed.+customDrawContext :: Context -> FontMetrics -> WidgetId -> Bool -> Bool -> IO CustomDrawContext+customDrawContext ctx fm wid hovered pressed = do+  disabled <- isDisabled ctx wid+  focused <- (== wid) <$> getFocusId ctx+  active <- readIORef (ctxActiveId ctx)+  theme <- widgetTheme ctx wid+  pure+    CustomDrawContext+      { cdcHovered = hovered && not disabled+      , cdcPressed = pressed && not disabled+      , cdcFocused = focused+      , cdcActive = active == wid+      , cdcDisabled = disabled+      , cdcTheme = theme+      , cdcFont = fm+      }
+ lib/NanoUI/Internal/Widgets/Disclosure.hs view
@@ -0,0 +1,115 @@+-- | Selectable list rows and collapsible disclosure sections built on core+-- containers and canvas primitives.+module NanoUI.Internal.Widgets.Disclosure+  ( selectableRow+  , selectableRow'+  , selectableRowWith+  , selectableRowWith'+  , collapsing+  , collapsingWith+  ) where++import Control.Monad (when)+import Data.Text (Text)+import NanoUI.Internal.Context (registerHoverZone)+import NanoUI.Internal.Input (UiCursorKind (..))+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askContext, askDefaultLayout, askInput, liftIO, nextId, scope, styled, themed, uiTheme)+import NanoUI.Internal.Style+import NanoUI.Internal.Style qualified as Style+import NanoUI.Internal.Types (Rect (..), V2 (..), colorTransparent, lerpColor, rectNonEmpty)+import NanoUI.Internal.Var (readVar, writeVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Cursor (withCursorShape)+import NanoUI.Internal.Widgets.Layout (columnWith, labelWith)+import NanoUI.Internal.Widgets.Node (Response, container, resolveInteraction, respClicked, respHovered, respPressed, respRect, tagContainer)+import NanoUI.Path qualified as P+import NanoUI.Widgets.Custom (CanvasConfig (..), CustomDrawContext (..), canvasConfigured, contentKey, defaultCanvasConfig, drawContext, drawPath)++-- | A full-width clickable row that highlights on hover and when @selected@.+-- Returns 'True' on click (presses on interactive children inside the row+-- belong to those children).+{-# INLINE selectableRow #-}+selectableRow :: Bool -> NanoUI () -> NanoUI Bool+selectableRow selected = selectableRowWith selected id++-- | 'selectableRow' returning both the body's result and the row's 'Response'.+{-# INLINE selectableRow' #-}+selectableRow' :: Bool -> NanoUI a -> NanoUI (a, Response)+selectableRow' selected = selectableRowWith' selected id++-- | 'selectableRow' with a layout modifier applied over the default horizontal+-- row layout (@fillW . direction Row . padXY 8 5 . gap 8 . itemsCenter@).+{-# INLINE selectableRowWith #-}+selectableRowWith :: Bool -> LayoutModifier -> NanoUI () -> NanoUI Bool+selectableRowWith selected f body = respClicked . snd <$> selectableRowWith' selected f body++-- | 'selectableRowWith' returning both the body's result and the row's 'Response'.+selectableRowWith' :: Bool -> LayoutModifier -> NanoUI a -> NanoUI (a, Response)+selectableRowWith' selected f body = do+  wid <- nextId+  ctx <- askContext+  inp <- askInput+  base <- askDefaultLayout+  outerTheme <- uiTheme+  resp <- liftIO (resolveInteraction ctx inp (-1) wid)+  when (rectNonEmpty (respRect resp)) $+    liftIO (registerHoverZone ctx False (respRect resp))+  let lay = f (itemsCenter (gap 8 (padXY 8 5 (fillW (direction Row base)))))+      rowTheme t =+        let panelBg = Style.styleBg (Style.themePanel t)+            panelFg = Style.styleFg (Style.themePanel t)+            rad = Style.styleCornerRadius (Style.themeButton t)+            bg+              | selected && respHovered resp = lerpColor (Style.themeAccent t) panelBg 0.72+              | selected = lerpColor (Style.themeAccent t) panelBg 0.80+              | respPressed resp = lerpColor panelFg panelBg 0.86+              | respHovered resp = lerpColor panelFg panelBg 0.92+              | otherwise = colorTransparent+         in panelStyle (Style.background bg . Style.borderWidth 0 . Style.cornerRadius rad) t+  a <- withCursorShape UiCursorPointer $+    styled rowTheme $+      container NodePanel lay (tagContainer wid >> themed outerTheme body)+  pure (a, resp)++-- | A titled section whose body expands and collapses when its header is+-- clicked, backed by a 'Var Bool'. The body runs inside 'scope' so toggling+-- it never shifts sibling widget ids.+{-# INLINE collapsing #-}+collapsing :: Text -> Var Bool -> NanoUI () -> NanoUI ()+collapsing = collapsingWith id++-- | 'collapsing' with a layout modifier on the outer section column.+collapsingWith :: LayoutModifier -> Text -> Var Bool -> NanoUI () -> NanoUI ()+collapsingWith f title openVar body = do+  open <- readVar openVar+  columnWith (f . tight . gap 4 . fillW) $ do+    clicked <- selectableRowWith False (padXY 6 4 . gap 6 . itemsCenter) $ do+      _ <- canvasConfigured (chevronCfg open) $ \(Rect x y w h) -> do+        cdc <- drawContext+        let col = Style.themeMuted (cdcTheme cdc)+            cx = x + w * 0.5+            cy = y + h * 0.5+            r = min w h * 0.28+            pts+              | open =+                  [ V2 (cx - r) (cy - r * 0.65)+                  , V2 (cx + r) (cy - r * 0.65)+                  , V2 cx (cy + r * 0.85)+                  ]+              | otherwise =+                  [ V2 (cx - r * 0.65) (cy - r)+                  , V2 (cx + r * 0.85) cy+                  , V2 (cx - r * 0.65) (cy + r)+                  ]+        drawPath (P.polygon pts) col+      labelWith fontSemiBold title+    when clicked (writeVar openVar (not open))+    scope $ when open $+      columnWith (tight . padLeft 16 . gap 4 . fillW) body+  where+    chevronCfg isOpen =+      defaultCanvasConfig+        { canvasLayout = fixedWH 12 12 . pointer PointerPass+        , canvasContent = contentKey [if isOpen then 1 else 0]+        }
+ lib/NanoUI/Internal/Widgets/Display.hs view
@@ -0,0 +1,277 @@+-- | Display helpers: styled labels, key/value rows, cards, toolbars, images+-- and colour boxes.+module NanoUI.Internal.Widgets.Display+  ( heading+  , muted+  , mono+  , danger+  , bold+  , italic+  , underline+  , kv+  , kvMono+  , kvBlock+  , card+  , toolbar+  , image+  , image'+  , freshImageId+  , registerImageRgba+  , releaseImageRgba+  , svgIcon+  , svgIconWith+  , svgIconWith'+  , svgIconConfigured+  , svgIconConfigured'+  , loadSvg+  , box+  )+where++import Control.Exception (IOException, try)+import Control.Monad (filterM, void)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.IORef (readIORef, writeIORef)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Primitive.PrimVar (newPrimVar, readPrimVar, writePrimVar)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Atlas qualified as Atlas+import NanoUI.Internal.Context (Context (..), frameNumber, registerImage, releaseImage)+import NanoUI.Internal.Draw (getDrawSnapScale)+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askDefaultLayout, nextId, uiTheme, withContext)+import NanoUI.Svg (Svg, parseSvg, rasterizeSvgIn, svgKey, svgMonochrome, svgSize)+import NanoUI.Internal.Style+import NanoUI.Internal.Image (ContentFit (..), ImageLook (..), fitRect, imageLook, turnedRect)+import NanoUI.Internal.Types (Color (..), ImageId (..), Rect (..), colorRGBA, colorToWord32)+import NanoUI.Internal.Widgets.Layout (panelWith, row', rowWith)+import NanoUI.Internal.Widgets.Image (ImageConfig (..), defaultImageConfig, imageConfigured', imageNode)+import NanoUI.Internal.Widgets.Node (Response, addWidgetStyled, addWidgetVoid)++{-# INLINE styledLabel #-}+styledLabel :: (Layout -> Layout) -> Text -> NanoUI ()+styledLabel f txt = do+  base <- askDefaultLayout+  wid <- nextId+  addWidgetVoid wid NodeText txt 0 (f base)++-- | Medium-weight label without padding ('fontHeading'). Uses the current+-- font size.+heading :: Text -> NanoUI ()+heading txt = styledLabel (tight . fontHeading) txt++-- | Label in the theme's muted color.+muted :: Text -> NanoUI ()+muted txt = styledLabel fontMuted txt++-- | Label using the backend's monospace font variant.+mono :: Text -> NanoUI ()+mono txt = styledLabel fontMono txt++-- | Label in the theme's danger color.+danger :: Text -> NanoUI ()+danger txt = styledLabel fontDanger txt++-- | Label requesting bold weight.+bold :: Text -> NanoUI ()+bold txt = styledLabel fontBold txt++-- | Label requesting italic styling.+italic :: Text -> NanoUI ()+italic txt = styledLabel fontItalic txt++-- | Label with an underline.+underline :: Text -> NanoUI ()+underline txt = styledLabel fontUnderline txt++-- | Key/value row: a muted key on the left, the value right-aligned. Trailing+-- whitespace in the value is dropped.+kv :: Text -> Text -> NanoUI ()+kv k v = kvRow fontMuted id k v++-- | Key/value row with a monospace value.+kvMono :: Text -> Text -> NanoUI ()+kvMono k v = kvRow id fontMono k v++{-# INLINE kvRow #-}+kvRow :: (Layout -> Layout) -> (Layout -> Layout) -> Text -> Text -> NanoUI ()+kvRow keyF valF k v =+  row' (tight . gap 12 . itemsCenter . fillW $ defaultLayout) $ do+    widK <- nextId+    addWidgetVoid widK NodeText k 0 (keyF . tight . minW 88 $ defaultLayout)+    widV <- nextId+    addWidgetVoid widV NodeText (T.stripEnd v) 0 (tight . fillW . alignEnd . valF $ defaultLayout)++-- | Key/value pairs as one monospace block with the keys padded to a column.+kvBlock :: Foldable f => f (Text, Text) -> NanoUI ()+kvBlock rows =+  let maxK = foldl' (\acc (k, _) -> max acc (T.length k)) 0 rows+      padK k = T.justifyLeft maxK ' ' k+   in do+        wid <- nextId+        addWidgetVoid+          wid+          NodeText+          (T.concat (foldr (\(k, v) rest -> padK k : "  " : v : "\n" : rest) [] rows))+          0+          (tight . gap 0 . fontMono $ defaultLayout)++-- | Full-width panel with a 300-pixel minimum width, 12x10 padding, and 8-pixel gap.+card :: NanoUI a -> NanoUI a+card = panelWith (minW 300 . padXY 12 10 . gap 8 . fillW)++-- | Full-width row with no padding, an 8-pixel gap, and vertical centring of children.+toolbar :: NanoUI a -> NanoUI a+toolbar = rowWith (tight . gap 8 . itemsCenter . fillW)++-- | An image registered with the host, stretched to the rect the layout+-- modifier gives it; an unsized axis is 32 pixels. 'NanoUI.imageConfigured'+-- instead uses the image's own size and can fit, align, crop, fade and+-- rotate it.+image :: (Layout -> Layout) -> ImageId -> NanoUI ()+image f iid = void (image' f iid)++-- | 'image' with its 'Response', for example to 'NanoUI.keepAnimating' an+-- image whose id changes over time.+image' :: (Layout -> Layout) -> ImageId -> NanoUI Response+image' f iid = nextId >>= \wid -> imageNode wid Nothing (f defaultLayout) iid++-- | An image id that no registered image uses and no earlier call returned.+-- Take one for each image registered while the app runs.+freshImageId :: NanoUI ImageId+freshImageId = withContext (\ctx -> Atlas.freshImageId (ctxImageAtlas ctx))++-- | Register an RGBA image (4 bytes a pixel, rows top to bottom) under an id+-- while the app runs, for 'image' to draw. Returns 'False' when the size or+-- pixels are invalid, an image of another size already has the id, or the+-- atlas is full. An image of the same size is replaced.+registerImageRgba :: ImageId -> Int -> Int -> ByteString -> NanoUI Bool+registerImageRgba iid w h pixels = withContext (\ctx -> registerImage ctx iid w h pixels)++-- | Remove an image 'registerImageRgba' registered and free its atlas space+-- for later images. Anything still drawing the id shows the placeholder for+-- an unknown image.+releaseImageRgba :: ImageId -> NanoUI ()+releaseImageRgba iid = withContext (\ctx -> releaseImage ctx iid)++-- | Read and parse an SVG file.+loadSvg :: FilePath -> IO (Either String Svg)+loadSvg path =+  either (\(err :: IOException) -> Left (show err)) parseSvg <$> try (BS.readFile path)++-- | An SVG icon @size@ logical pixels square, drawn in the text colour where+-- it is used: a one-colour document (every paint @currentColor@ or+-- unspecified) takes the colour as a tint, and a multicoloured one paints+-- its @currentColor@ with it.+{-# INLINE svgIcon #-}+svgIcon :: Float -> Svg -> NanoUI ()+svgIcon size = svgIconWith (fixedWH size size)++-- | An SVG document sized by the layout modifier: a fixed width and height,+-- or else the document's own size. A 'NanoUI.fontColor' in the modifier+-- replaces the text colour.+{-# INLINE svgIconWith #-}+svgIconWith :: (Layout -> Layout) -> Svg -> NanoUI ()+svgIconWith f doc = void (svgIconWith' f doc)++-- | The document is rasterized once per pixel size and colour, at the+-- display's scale, and kept in the image atlas while frames draw it at that+-- size and colour; the first frame that does not frees its space.+-- A rect of another shape than the document's letterboxes it, centred, as+-- SVG's default @xMidYMid meet@ does.+svgIconWith' :: (Layout -> Layout) -> Svg -> NanoUI Response+svgIconWith' f = svgIconConfigured' defaultImageConfig {icLayout = f, icFit = FitContain}++-- | An SVG document drawn like 'NanoUI.imageConfigured' draws an image:+-- faded, rotated, fitted and aligned in its rect. The rect is sized as in+-- 'svgIconWith': a fixed width and height from 'icLayout', or else the+-- document's own size. Fit and alignment place the document's own shape+-- ('svgSize'), so 'FitCover' crops real content and 'FitFill' stretches it;+-- use 'FitContain' for the letterboxing 'svgIconWith' does. The document is+-- rasterized at the fitted size, so it stays sharp. 'icCrop' is in raster+-- pixels.+--+-- > svgIconConfigured defaultImageConfig {icLayout = fixedWH 24 24, icRotation = RotateFloating turn} spinnerIcon+svgIconConfigured :: ImageConfig -> Svg -> NanoUI ()+svgIconConfigured cfg doc = void (svgIconConfigured' cfg doc)++-- | 'svgIconConfigured' with its 'Response'.+svgIconConfigured' :: ImageConfig -> Svg -> NanoUI Response+svgIconConfigured' cfg doc = do+  theme <- uiTheme+  let lay0 = icLayout cfg defaultLayout+      (docW, docH) = svgSize doc+      fixedOr sizing dflt = case sizing of+        Fixed n -> n+        _ -> dflt+      w = fixedOr (layoutWidth lay0) docW+      h = fixedOr (layoutHeight lay0) docH+      color = fromMaybe (styleFg (themePanel theme)) (layoutFontColor lay0)+      oneColour = svgMonochrome doc+      white = colorRGBA 255 255 255 255+      lay = lay0 {layoutWidth = Fixed w, layoutHeight = Fixed h, layoutFontColor = Just (if oneColour then color else white)}+      -- The raster is the rect before any solid rotation, stretched over it+      -- when drawn; the document is fitted inside the raster instead.+      Rect _ _ bw bh = turnedRect FitFill AlignCenter AlignMiddle (lookRotation (imageLook cfg white)) (w, h) (Rect 0 0 w h)+      Rect cx cy cw ch = fitRect (icFit cfg) (icAlignX cfg) (icAlignY cfg) (docW, docH) (Rect 0 0 bw bh)+  iid <- withContext $ \ctx -> do+    scale <- getDrawSnapScale (ctxDrawArena ctx)+    let pw = max 1 (ceiling (bw * max 1 scale))+        ph = max 1 (ceiling (bh * max 1 scale))+        -- A zero-sized rect draws nothing, so its content is empty rather+        -- than infinite.+        per px b = if b > 0 then fromIntegral px / b else 0+        -- The content rect in eighths of a raster pixel: sizes a hair apart+        -- share a raster, and the key compares whole numbers.+        eighths v = round (v * 8) :: Int+        content@(qx, qy, qw, qh) = (eighths (cx * per pw bw), eighths (cy * per ph bh), eighths (cw * per pw bw), eighths (ch * per ph bh))+        -- A one-colour raster is white and tinted when drawn, so every colour+        -- shares it.+        rasterColor = if oneColour then white else color+        key = (svgKey doc, pw, ph, colorToWord32 rasterColor, content)+    let cache = ctxSvgRasters ctx+        atlas = ctxImageAtlas ctx+    frame <- frameNumber ctx+    known <- Map.lookup key <$> readIORef cache+    retry <- case known of+      -- A raster the atlas had no room for is made again once an image has+      -- left the atlas.+      Just (ImageId 0, freed, _) -> (/= freed) <$> Atlas.atlasReleases atlas+      _ -> pure False+    case known of+      Just (iid, _, drawn) | not retry -> iid <$ writePrimVar drawn frame+      _ -> do+        -- Rasters no frame drew since the one before give their room to this+        -- one: nothing on screen shows them, so their release needs no+        -- repaint. Until then, an icon hidden and shown again keeps its own.+        rasters <- readIORef cache+        stale <- filterM (\(_, (_, _, drawn)) -> (< frame - 1) <$> readPrimVar drawn) (Map.toList rasters)+        mapM_ (\(_, (old, _, _)) -> Atlas.releaseImage atlas old) stale+        iid <- Atlas.freshImageId atlas+        let placed = Rect (fromIntegral qx / 8) (fromIntegral qy / 8) (fromIntegral qw / 8) (fromIntegral qh / 8)+        ok <- registerImage ctx iid pw ph (rasterizeSvgIn pw ph placed rasterColor doc)+        -- A raster the atlas has no room for is kept too, as id 0, so it is+        -- not made again on every pass while drawn.+        let shown = if ok then iid else ImageId 0+        freed <- Atlas.atlasReleases atlas+        drawn <- newPrimVar frame+        writeIORef cache $! Map.insert key (shown, freed, drawn) (foldr (Map.delete . fst) rasters stale)+        pure shown+  imageConfigured' cfg {icLayout = const lay, icFit = FitFill, icAlignX = AlignCenter, icAlignY = AlignMiddle} iid++-- | A solid rectangle sized by the layout modifier.+box :: (Layout -> Layout) -> Color -> NanoUI ()+box f col = do+  wid <- nextId+  void+    ( addWidgetStyled+        wid+        NodeBox+        T.empty+        0+        (f defaultLayout)+        (fromIntegral (colorToWord32 col))+    )
+ lib/NanoUI/Internal/Widgets/Drawing.hs view
@@ -0,0 +1,68 @@+-- | Layout nodes painted by cached vector operations. Use content versions+-- whenever the builder's output can change without a size change.+module NanoUI.Internal.Widgets.Drawing+  ( DrawOp (..)+  , DrawingBuild+  , drawing+  , drawingVersioned+  , drawingCached+  )+where++import Data.Text qualified as T+import Data.Primitive.SmallArray (SmallArray)+import NanoUI.Internal.Context (cachedWidgetLayout, registerDrawing)+import NanoUI.Internal.Draw (DrawOp (..), DrawingBuild)+import NanoUI.Internal.Layout.Arena (NodeType (NodeDrawing))+import NanoUI.Internal.Monad (NanoUI, freshWidget, nextId, liftIO, withContext)+import NanoUI.Internal.Style (Layout, defaultLayout)+import NanoUI.Internal.Types (Rect)+import NanoUI.Internal.Widgets.Node (Response, addWidget)++-- | Vector ops for a laid-out widget. Paint caches ops while width and height+-- stay the same, then translates when the widget moves. Unversioned: the cache+-- drops while the widget animates because the builder has no content key, and+-- a builder that draws something else at the same size neither rebuilds nor+-- repaints. Use 'drawingVersioned' for output that changes, or+-- 'NanoUI.Widgets.Custom.customWidget' without a key to have every frame+-- rebuild and compare.+{-# INLINE drawing #-}+drawing :: (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> NanoUI Response+drawing = drawingVersioned 0++-- | Like 'drawing', but the tessellated op cache is keyed by an explicit+-- content version. Change the version whenever the builder output changes+-- (a model pointer, dirty counter, or content hash): that rebuilds the ops and+-- repaints the widget. Frames with the same version replay cached ops without+-- rebuilding, even while the widget animates. Version 0 means unversioned, as+-- in 'drawing'.+drawingVersioned :: Int -> (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> NanoUI Response+drawingVersioned version f build = do+  wid <- nextId+  resp <- addWidget wid NodeDrawing T.empty 0 (f defaultLayout)+  resp <$ withContext (\ctx -> registerDrawing ctx wid version build)++-- | Like 'drawingVersioned', but the layout itself comes from @compute@, which+-- only reruns when the envelope, line height, content key, or modifier result+-- change.+--+-- > drawingCached w h lineH content f compute build+--+-- @w@ and @h@ are the envelope, the drawing's natural size; @lineH@ is the+-- line height its text is measured with; @content@ is the content version, as+-- in 'drawingVersioned' (0 is unversioned); and @f@ is the layout modifier,+-- whose result on 'defaultLayout' is compared but not used.+drawingCached ::+  Double ->+  Double ->+  Float ->+  Int ->+  (Layout -> Layout) ->+  IO Layout ->+  DrawingBuild ->+  NanoUI Response+drawingCached dw dh lh content f compute build = do+  (wid, ctx) <- freshWidget+  layout <- liftIO (cachedWidgetLayout ctx wid dw dh lh content (f defaultLayout) compute)+  resp <- addWidget wid NodeDrawing T.empty 0 layout+  resp <$ liftIO (registerDrawing ctx wid content build)
+ lib/NanoUI/Internal/Widgets/Drop.hs view
@@ -0,0 +1,184 @@+{-# LANGUAGE StrictData #-}++-- | Local pointer drags and operating-system drag and drop.+--+-- 'useDrop' turns the frame's 'NanoUI.Internal.Input.DropEvent's into a 'DropTarget'+-- for one rectangle. 'dropZone' wraps a panel and does the same for its rect.+--+-- > (_, _, target) <- dropZone fillW (label "Drop files here")+-- > when (dropReceived target) (mapM_ openFile (dropFiles target))+module NanoUI.Internal.Widgets.Drop+  ( DropTarget (..)+  , useDrop+  , dropZone+  , Drag (..)+  , DragPhase (..)+  , DragHandle+  , newDrag+  , useDrag+  , insertionIndex+  ) where++import Control.Applicative ((<|>))+import Control.Monad (when)+import Data.List (find)+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import NanoUI.Internal.Context+import NanoUI.Internal.Input+import NanoUI.Internal.Monad (NanoUI, askInput, freshWidget, liftIO, takeEscape, withContext)+import NanoUI.Internal.Store (deleteSpec, findSpec, insertSpec, lookupSpec)+import NanoUI.Internal.Store.Slots (setFlagSpec, slotDrop, slotDropPos)+import NanoUI.Internal.Style (Layout)+import NanoUI.Internal.Types (Rect (..), V2 (..), rectContains, rectIntersect)+import NanoUI.Internal.Widgets.Layout (panelWith')+import NanoUI.Internal.Widgets.Node (Response, respId, respRect, respPressed)+import NanoUI.Internal.Widgets.Behavior (DragAxis (..), pastDragThreshold)++-- | A thresholded pointer gesture. Terminal phases last one frame.+data DragPhase = DragStarted | Dragging | DragReleased | DragCancelled+  deriving (Eq, Show)++-- | Application-owned payload and window coordinates. Map the payload to+-- adapt one gesture to another target without restarting its lifecycle.+data Drag a = Drag+  { dragPayload :: !a+  , dragAt :: !V2+  -- ^ Where the pointer is.+  , dragFrom :: !V2+  -- ^ Where the press was.+  , dragPhase :: !DragPhase+  }+  deriving (Eq, Show, Functor)++data DragState a = DragState !a !V2 !Bool+  deriving (Eq)++-- | Component-owned gesture state, allocated once before rendering. Use on+-- the UI thread in one session; each independent gesture needs its own handle.+newtype DragHandle a = DragHandle (IORef (Maybe (DragState a)))++-- | A handle for 'useDrag'. Allocate it once during setup, outside the view:+-- a handle made every frame never tracks a drag.+newDrag :: IO (DragHandle a)+newDrag = DragHandle <$> newIORef Nothing++-- | Track a drag across uniquely keyed responses. Call with the same handle+-- every frame, including for an empty collection. Only owned presses start;+-- payload identity survives reordering. Below the threshold, returns Nothing.+-- Escape, lost hold or source removal cancels; only DragReleased may commit.+useDrag :: Eq a => DragHandle a -> [(a, Response)] -> NanoUI (Maybe (Drag a))+useDrag (DragHandle ref) sources = do+  inp <- askInput+  let pos = inputMousePos inp+  old <- liftIO (readIORef ref)+  let armed = if pressedIn MouseLeft inp+        then (\(a, _) -> DragState a pos False) <$> find (respPressed . snd) sources+        else old+  escaped <- if isJust armed then takeEscape else pure False+  let step (DragState a origin hot) =+        let cancelled = escaped || all ((/= a) . fst) sources+              || (not (heldIn MouseLeft inp) && not (releasedIn MouseLeft inp))+            moved = hot || pastDragThreshold origin pos+            released = releasedIn MouseLeft inp+            phase | cancelled = DragCancelled+                  | released = DragReleased+                  | not hot = DragStarted+                  | otherwise = Dragging+            emitted = if hot || (moved && not cancelled) then Just (Drag a pos origin phase) else Nothing+            retained = if cancelled || released then Nothing else Just (DragState a origin moved)+         in (retained, emitted)+      (next, result) = maybe (Nothing, Nothing) step armed+  when (next /= old) $ withContext $ \ctx -> do+    writeIORef ref next+    -- Only repaint when a drag actually became active or ended; arming and+    -- releasing on a plain click below threshold needs no full-window damage.+    when (isJust result || maybe False (\(DragState _ _ h) -> h) old) $ do+      damageFull ctx+      markDirty ctx+  pure result++-- | Insertion slot in an ordered row or column, bounded by its visible+-- viewport. Pass remaining items (omit the source for a same-list move).+-- Empty targets accept slot zero. Rectangles may extend beyond the viewport+-- when scrolled; their centers still determine the original list index.+insertionIndex :: DragAxis -> Rect -> [Rect] -> V2 -> Maybe Int+insertionIndex axis bounds items pos@(V2 x y)+  | not (rectContains bounds pos) = Nothing+  | otherwise = Just (length (takeWhile before items))+  where+    before (Rect rx ry rw rh) = case axis of+      DragAxisX -> x > rx + rw / 2+      DragAxisY -> y > ry + rh / 2++-- | Per-frame drop state for a single rectangular drop target.+data DropTarget = DropTarget+  { dropHovered :: !Bool+    -- ^ A drag is currently positioned over the target rect.+  , dropReceived :: !Bool+    -- ^ One or more payloads landed on the target this frame.+  , dropFiles :: ![Text]+    -- ^ File paths dropped on the target this frame.+  , dropTexts :: ![Text]+    -- ^ Text snippets dropped on the target this frame.+  , dropPosition :: !(Maybe V2)+    -- ^ Last known drop position in window coordinates, if any.+  }+  deriving (Eq, Show)++-- | The drop state for a rectangle from this frame's drop events. Hover+-- persists while the OS drag is still; payloads are reported on the frame+-- they arrive. A payload lands at the last 'DropPosition', not its own+-- coordinates, which SDL reports as (0,0) when it has none. Only the layer+-- on top where the drag is sees it there: a target behind a modal, or under+-- a floating window, sees it off the window.+useDrop :: Rect -> NanoUI DropTarget+useDrop bounds = do+  (wid, ctx) <- freshWidget+  inp <- askInput+  let key = intKey wid+  store <- liftIO (getStore ctx)+  let active0 = findSpec slotDrop False key store+      lastPos0 = lookupSpec slotDropPos key store+      -- A drag is active from 'DropBegin' until 'DropComplete'. A payload+      -- uses the position current at its point in the sequence.+      step (active, pos, fs, ts) ev = case dropEventType ev of+        DropBegin -> (True, pos, fs, ts)+        DropPosition -> (active, dropEventPos ev <|> pos, fs, ts)+        DropComplete -> (False, pos, fs, ts)+        DropFile | posInside bounds pos -> (active, pos, dropEventData ev : fs, ts)+        DropText | posInside bounds pos -> (active, pos, fs, dropEventData ev : ts)+        _ -> (active, pos, fs, ts)+      (active1, lastPos1, filesRev, textsRev) =+        foldl' step (active0, lastPos0, [], []) (inputDrops inp)+      files = reverse filesRev+      texts = reverse textsRev+      hovered = active1 && posInside bounds lastPos1+      -- The payloads and 'DropComplete' arrive in one frame, which still+      -- reports where they landed; only an active drag keeps the position.+      stored1 = if active1 then lastPos1 else Nothing+  when (active1 /= active0 || stored1 /= lastPos0) $+    liftIO . modifyStore ctx $+      setFlagSpec slotDrop key active1+        . maybe (deleteSpec slotDropPos key) (insertSpec slotDropPos key) stored1+  pure+    DropTarget+      { dropHovered = hovered+      , dropReceived = not (null files) || not (null texts)+      , dropFiles = files+      , dropTexts = texts+      , dropPosition = lastPos1+      }++posInside :: Rect -> Maybe V2 -> Bool+posInside bounds = maybe False (rectContains bounds)++-- | A panel that is also a drop target. Returns the body's result, the+-- panel's 'Response', and the 'DropTarget' for its rect.+dropZone :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response, DropTarget)+dropZone f child = do+  (a, resp) <- panelWith' f child+  mClip <- withContext (`getPrevClipRect` respId resp)+  let dropBounds = maybe (respRect resp) (fromMaybe (Rect 0 0 0 0) . rectIntersect (respRect resp)) mClip+  (a, resp,) <$> useDrop dropBounds
+ lib/NanoUI/Internal/Widgets/Image.hs view
@@ -0,0 +1,107 @@+-- | Images with fit, alignment, crop, zoom, opacity and rotation+-- ('imageConfigured'), the underlying image node ('imageNode'), and images+-- registered for as long as a view shows them ('useImageRgba').+module NanoUI.Internal.Widgets.Image+  ( ContentFit (..)+  , Rotation (..)+  , rotationAngle+  , ImageConfig (..)+  , defaultImageConfig+  , fitRect+  , imageNode+  , imageConfigured+  , imageConfigured'+  , useImageRgba+  , ImageHandle+  , newImageHandle+  )+where++import Control.Monad (void)+import Data.ByteString (ByteString)+import Data.Maybe (fromMaybe, isJust)+import Data.Text qualified as T+import NanoUI.Internal.Atlas qualified as Atlas+import NanoUI.Internal.Context (Context (..), lookupImageSize, registerImage, releaseImage)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Image+import NanoUI.Internal.Layout.Arena (ImageNode (..), NodeType (NodeImage), setImageId, setImageNode)+import NanoUI.Internal.Monad (NanoUI, freshWidget, liftIO)+import NanoUI.Internal.Style (Layout (..), Sizing (..), aspect, defaultLayout)+import NanoUI.Internal.Tasks (useHeld)+import NanoUI.Internal.Resource (Resource, newResource)+import NanoUI.Internal.Types (ImageId (..), colorRGBA)+import NanoUI.Internal.Widgets.Node (Response, addWidgetNode)++-- | An image node for image @iid@ under widget @wid@. Paint finds the image+-- by the node's image id ('setImageId'), and damage spots a switched image+-- by it. With an 'ImageNode', paint fits, fades and rotates the image+-- ('withLookDraw') and an unsized axis takes the image's size; without one the+-- image is stretched, as with 'NanoUI.image'. Like a label, it passes the+-- pointer to a control it is drawn over; its response still reports hover+-- and clicks.+imageNode :: WidgetId -> Maybe ImageNode -> Layout -> ImageId -> NanoUI Response+imageNode wid node lay (ImageId tid) =+  addWidgetNode wid NodeImage T.empty 0 lay $ \arena idx -> do+    setImageId arena idx (max 0 tid)+    mapM_ (setImageNode arena idx) node++-- | A registered image drawn with a fit, alignment, crop, zoom, opacity and+-- rotation:+--+-- > imageConfigured defaultImageConfig {icLayout = fixedWH 160 90, icFit = FitCover} photo+-- > imageConfigured defaultImageConfig {icLayout = fillW} photo   -- column width, photo's aspect ratio+imageConfigured :: ImageConfig -> ImageId -> NanoUI ()+imageConfigured cfg iid = void (imageConfigured' cfg iid)++-- | 'imageConfigured' returning its 'Response'. An unregistered image+-- behaves like 'NanoUI.image': 32 pixels on an unsized axis, painted in the+-- theme accent.+imageConfigured' :: ImageConfig -> ImageId -> NanoUI Response+imageConfigured' cfg iid = do+  (wid, ctx) <- freshWidget+  natural <- liftIO (lookupImageSize ctx iid)+  let !lay0 = icLayout cfg defaultLayout+      !look = imageLook cfg (fromMaybe (colorRGBA 255 255 255 255) (layoutFontColor lay0))+      fixed = \case Fixed _ -> True; _ -> False+  -- Both axes fixed with a default look: a plain stretched image, which+  -- paint and damage handle on a faster path.+  if fixed (layoutWidth lay0) && fixed (layoutHeight lay0) && plainLook look+    then imageNode wid Nothing lay0 iid+    else do+      let !(w, h) = maybe (32, 32) (lookSize look) natural+          -- A registered image keeps its aspect ratio on an unsized axis.+          lay+            | isJust natural && (layoutWidth lay0 == Fit || layoutHeight lay0 == Fit) && layoutAspect lay0 <= 0 = aspect (w / h) lay0+            | otherwise = lay0+      imageNode wid (Just $! ImageNode look w h) lay iid++-- | Typed ownership of one image registration, allocated during setup.+newtype ImageHandle k = ImageHandle (Resource k (Maybe ImageId))+  deriving newtype (Eq)++-- | A handle holding no image yet. Allocate one per image during setup.+newImageHandle :: IO (ImageHandle k)+newImageHandle = ImageHandle <$> newResource++-- | Register an RGBA image (4 bytes per pixel, rows top to bottom), @w@ by+-- @h@ pixels, on the first frame this is called with a key, and return its+-- id on every frame while the key stays the same:+--+-- > thumb <- useImageRgba owner path w h pixels+-- > mapM_ (image (fixedWH 96 96)) thumb+--+-- Allocate @owner <- newImageHandle@ during setup.+--+-- The image lives as long as the view keeps calling the hook, like a+-- 'NanoUI.useTask' job. A new key registers the new image and releases the+-- old one; a frame that skips the call releases the image and frees its+-- atlas space. Ids are never reused, so a stale id draws the placeholder+-- 'NanoUI.image' shows for an unknown id. Returns 'Nothing' if the size or+-- pixels are invalid or the atlas is full, until the key changes. It consumes+-- no widget id. Call with the same handle on every frame that shows the image.+useImageRgba :: Eq k => ImageHandle k -> k -> Int -> Int -> ByteString -> NanoUI (Maybe ImageId)+useImageRgba (ImageHandle owner) k w h pixels = useHeld owner k $ \ctx _ -> do+  iid <- Atlas.freshImageId (ctxImageAtlas ctx)+  ok <- registerImage ctx iid w h pixels+  pure (if ok then (Just iid, releaseImage ctx iid) else (Nothing, pure ()))
+ lib/NanoUI/Internal/Widgets/Layout.hs view
@@ -0,0 +1,471 @@+-- | Rows, columns, grids, panels, labels, and scrollers built during the view pass.+module NanoUI.Internal.Widgets.Layout+  ( withDefaultWith+  , panel+  , panelWith+  , panelWith'+  , panel'+  , callout+  , calloutWith+  , calloutWith'+  , calloutTone+  , calloutToneWith+  , calloutToneWith'+  , row+  , rowWith+  , rowWith'+  , row'+  , column+  , columnWith+  , columnWith'+  , column'+  , layers+  , layersWith+  , layersWith'+  , clipBox+  , label+  , label'+  , labelWith+  , labelWith'+  , labelEx+  , separator+  , spacer+  , spacerW+  , spacerH+  , flex+  , ScrollPolicy (..)+  , ScrollConfig (..)+  , defaultScrollConfig+  , scroll2DConfig+  , scroll+  , scrollWith+  , scrollWith'+  , scroll2D+  , scroll2DWith+  , scroll2DWith'+  , scrollConfigured+  , scrollConfigured'+  , scrollAreaIdConfigured+  , grid+  , gridWith+  , gridWith'+  , responsive+  , responsiveRowCol+  , withContainerQuery+  , withContainerSize+  , withContainerWidth+  , responsiveIn+  , responsiveRowColIn+  , center+  )+where++import Control.Monad (when)+import Data.Text (Text)+import NanoUI.Internal.Context (Context (..), getPrevRect, intKey, recordLayoutRead, registerFocusable)+import NanoUI.Internal.Layout.ScrollGeometry+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (NanoUI, askContext, askDefaultLayout, askInput, currentId, liftIO, nextId, styled, uiTheme, windowSize, windowWidth, withContext)+import NanoUI.Internal.Style+import NanoUI.Internal.Style qualified as Style+import NanoUI.Internal.Types (Color (..), Rect (..), Size (..), lerpColor)+import NanoUI.Internal.Widgets.Node++{-# INLINE withDefaultWith #-}+withDefaultWith :: (Layout -> Layout) -> (Layout -> NanoUI a -> NanoUI r) -> NanoUI a -> NanoUI r+withDefaultWith f c child = do+  base <- askDefaultLayout+  c (f base) child++-- | Container with the theme's panel background and border. Returns its body's result.+{-# INLINE panel #-}+panel :: NanoUI a -> NanoUI a+panel = panelWith id++-- | 'panel' with modified layout defaults.+{-# INLINE panelWith #-}+panelWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a+panelWith = (`withDefaultWith` panel')++-- | 'panel' with an explicit 'Layout' record.+{-# INLINE panel' #-}+panel' :: Layout -> NanoUI a -> NanoUI a+panel' = container NodePanel++-- | 'panelWith' returning its 'Response', as 'rowWith'' does. It takes an+-- id, like a widget.+panelWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+panelWith' f = withDefaultWith f (containerResponse NodePanel)++-- | Full-width panel tinted by a color, with a matching border. See 'calloutWith'.+callout :: Color -> NanoUI a -> NanoUI a+callout borderCol = calloutWith borderCol id++calloutTheme :: Color -> Theme -> Theme+calloutTheme col t =+  panelStyle (Style.background (lerpColor col (Style.styleBg (Style.themePanel t)) 0.88) . Style.borderColor col) t++-- | A panel tinted with @col@: a border in it and a faint wash of it over the+-- panel color. The tint applies to the callout's own panel and to panels+-- nested in it.+calloutWith :: Color -> (Layout -> Layout) -> NanoUI a -> NanoUI a+calloutWith col f = styled (calloutTheme col) . panelWith (f . padXY 10 6 . gap 8 . fillW)++-- | 'calloutWith' returning its 'Response', as 'rowWith'' does.+calloutWith' :: Color -> (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+calloutWith' col f = styled (calloutTheme col) . panelWith' (f . padXY 10 6 . gap 8 . fillW)++-- | Full-width callout panel tinted by a semantic theme 'Tone' (for example,+-- @calloutTone Warning@ or @calloutTone Danger@).+calloutTone :: Tone -> NanoUI a -> NanoUI a+calloutTone t = calloutToneWith t id++-- | 'calloutTone' with a layout modifier.+calloutToneWith :: Tone -> (Layout -> Layout) -> NanoUI a -> NanoUI a+calloutToneWith t f body = do+  col <- flip toneColor t <$> uiTheme+  calloutWith col f body++-- | 'calloutToneWith' returning its 'Response'.+calloutToneWith' :: Tone -> (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+calloutToneWith' t f body = do+  col <- flip toneColor t <$> uiTheme+  calloutWith' col f body++-- | Lay out children left to right, using current defaults and a child id scope.+{-# INLINE row #-}+row :: NanoUI a -> NanoUI a+row = rowWith id++-- | 'row' with modified layout defaults; direction remains horizontal.+{-# INLINE rowWith #-}+rowWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a+rowWith = (`withDefaultWith` row')++-- | 'rowWith' returning its 'Response', whose 'respRect' is where the row+-- was laid out last frame. A row that runs out of room can drop controls by+-- comparing it with the widths they need:+--+-- > (_, bar) <- rowWith' fillW $ do+-- >   label title+-- >   flex+-- >   when (rectW (respRect bar) >= 300) controls+--+-- Unlike 'rowWith', it takes an id, like a widget.+rowWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+rowWith' f = withDefaultWith (\l -> (f l) {layoutDirection = Row}) (containerResponse NodeContainer)++-- | 'columnWith' returning its 'Response', as 'rowWith''.+columnWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+columnWith' f = withDefaultWith (\l -> (f l) {layoutDirection = Column}) (containerResponse NodeContainer)++-- | 'row' with an explicit 'Layout' record; direction remains horizontal.+{-# INLINE row' #-}+row' :: Layout -> NanoUI a -> NanoUI a+row' layout = container NodeContainer (layout {layoutDirection = Row})++-- | Lay out children top to bottom, using current defaults and a child id scope.+{-# INLINE column #-}+column :: NanoUI a -> NanoUI a+column = columnWith id++-- | 'column' with modified layout defaults; direction remains vertical.+{-# INLINE columnWith #-}+columnWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a+columnWith = (`withDefaultWith` column')++-- | 'column' with an explicit 'Layout' record; direction remains vertical.+{-# INLINE column' #-}+column' :: Layout -> NanoUI a -> NanoUI a+column' layout = container NodeContainer (layout {layoutDirection = Column})++-- | Stack children in the same box, later ones on top, such as a badge on+-- an icon or a caption over an image. The box is as large as its largest+-- child, and each child is placed by its alignment: @alignEnd . alignTop@+-- for a corner badge, @alignCenter . alignMiddle@ to center it. A growing+-- child ('fillW', 'grow') fills the box on that axis. The pointer goes to+-- the child on top: where one widget covers another, hover, presses and+-- focus go to the top one, and the one underneath shows no hover or tooltip+-- there.+--+-- This is a container with the 'layered' flow, which panels and cards can+-- also use. To cover a container without affecting its size, pin the+-- overlay instead ('pinAt').+{-# INLINE layers #-}+layers :: NanoUI a -> NanoUI a+layers = layersWith id++-- | 'layers' with modified layout defaults; the flow remains layered.+{-# INLINE layersWith #-}+layersWith :: (Layout -> Layout) -> NanoUI a -> NanoUI a+layersWith = (`withDefaultWith` (container NodeContainer . layered))++-- | 'layersWith' returning its 'Response', as 'rowWith'' does.+layersWith' :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+layersWith' f = withDefaultWith (layered . f) (containerResponse NodeContainer)++-- | A plain container that clips its children to its bounds without painting+-- a panel background or border.+{-# INLINE clipBox #-}+clipBox :: LayoutModifier -> NanoUI a -> NanoUI a+clipBox f = withDefaultWith (f . tight) clipContainer++-- | Place children in a grid with at least one column. The count is clamped to 1.+{-# INLINE grid #-}+grid :: Int -> NanoUI a -> NanoUI a+grid n = gridWith n id++-- | 'grid' with a layout modifier for spacing, sizing, and alignment.+{-# INLINE gridWith #-}+gridWith :: Int -> (Layout -> Layout) -> NanoUI a -> NanoUI a+gridWith n f =+  withDefaultWith f $ \layout -> container NodeContainer layout {layoutGridCols = max 1 n}++-- | 'gridWith' returning its 'Response', as 'rowWith'' does.+gridWith' :: Int -> (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+gridWith' n f =+  withDefaultWith f $ \layout -> containerResponse NodeContainer layout {layoutGridCols = max 1 n}++-- | Choose between two container builders based on window width.+{-# INLINE responsive #-}+responsive :: Float -> (NanoUI a -> NanoUI a) -> (NanoUI a -> NanoUI a) -> NanoUI a -> NanoUI a+responsive breakpoint wideContainer narrowContainer child = do+  w <- windowWidth+  if w >= breakpoint then wideContainer child else narrowContainer child++-- | A row while the window is at least @breakpoint@ wide, a column below it.+{-# INLINE responsiveRowCol #-}+responsiveRowCol :: Float -> (Layout -> Layout) -> NanoUI a -> NanoUI a+responsiveRowCol breakpoint f = responsive breakpoint (rowWith f) (columnWith f)++-- | Shared container-size measurement scaffold. Runs @body@ with the derived+-- value @q@ computed from the container's inner content size (or window size+-- minus padding on its first frame), requesting a follow-up frame only when+-- @changed@ reports a meaningful transition.+containerQuery ::+  LayoutModifier ->+  (Size -> q) ->+  (q -> q -> Bool) ->+  (q -> Layout -> Layout) ->+  (q -> NanoUI a) ->+  NanoUI a+containerQuery f project changed adjustLayout body = do+  wid <- currentId+  ctx <- askContext+  winSz <- windowSize+  base <- askDefaultLayout+  let layout0 = f (fillW (tight base))+      Padding pl pr pt pb = layoutPadding layout0+      innerOf (Rect _ _ rw rh) = Size (max 0 (rw - pl - pr)) (max 0 (rh - pt - pb))+      fallback = Size (max 0 (sizeW winSz - pl - pr)) (max 0 (sizeH winSz - pt - pb))+      valOf = project . maybe fallback innerOf+  q <- liftIO $ do+    cur <- valOf <$> getPrevRect ctx wid+    recordLayoutRead ctx (intKey wid) $ do+      next <- valOf <$> getPrevRect ctx wid+      pure (changed cur next)+    pure cur+  container NodeContainer (adjustLayout q layout0) (tagContainer wid >> body q)++-- | Run @body@ inside an unpadded container that fills the available width+-- (unless @f@ overrides sizing), projecting the container's inner content+-- 'Size' to a discrete value @a@. A follow-up frame is scheduled only when+-- the projected value changes (not on every pixel of divider drag), making+-- this ideal for multi-tier breakpoints or responsive grid column counts.+withContainerQuery :: Eq a => LayoutModifier -> (Size -> a) -> (a -> NanoUI r) -> NanoUI r+withContainerQuery f project = containerQuery f project (/=) (\_ l -> l)++-- | Run @body@ inside an unpadded container that fills the available width+-- (unless @f@ overrides sizing), passing the container's inner content 'Size'+-- (outer laid-out bounds less its padding, or 'windowSize' before its first+-- layout). When layout changes that size by more than half a pixel, a+-- follow-up frame is scheduled; pure scrolling or movement does not.+withContainerSize :: LayoutModifier -> (Size -> NanoUI a) -> NanoUI a+withContainerSize f =+  containerQuery f id (\(Size w h) (Size w' h') -> abs (w' - w) > 0.5 || abs (h' - h) > 0.5) (\_ l -> l)++-- | Like 'withContainerSize', passing only the container's inner content width+-- and scheduling a follow-up frame only when that width changes.+withContainerWidth :: LayoutModifier -> (Float -> NanoUI a) -> NanoUI a+withContainerWidth f =+  containerQuery f sizeW (\w w' -> abs (w' - w) > 0.5) (\_ l -> l)++-- | Container-scoped counterpart to 'responsive': chooses between+-- @wideContainer@ and @narrowContainer@ based on the enclosing container's+-- laid-out inner width (rather than 'windowWidth'), settling automatically+-- when a split pane or parent resizes across @breakpoint@.+responsiveIn :: Float -> (NanoUI a -> NanoUI a) -> (NanoUI a -> NanoUI a) -> NanoUI a -> NanoUI a+responsiveIn breakpoint wideContainer narrowContainer child =+  withContainerQuery (direction Column) ((>= breakpoint) . sizeW) $ \isWide ->+    if isWide then wideContainer child else narrowContainer child++-- | A row while its own laid-out inner width is at least @breakpoint@, a+-- column below it. Defaults to 'fillW' and 'tight' unless @f@ overrides them.+responsiveRowColIn :: Float -> LayoutModifier -> NanoUI a -> NanoUI a+responsiveRowColIn breakpoint f child =+  containerQuery+    f+    ((>= breakpoint) . sizeW)+    (/=)+    (\isWide l -> l {layoutDirection = if isWide then Row else Column})+    (const child)++-- | A line of text. Newlines start new lines.+label :: Text -> NanoUI ()+label txt = do+  base <- askDefaultLayout+  wid <- nextId+  addWidgetVoid wid NodeText txt 0 base++-- | 'label' returning its 'Response', for a tooltip or an anchored popup.+label' :: Text -> NanoUI Response+label' txt = do+  base <- askDefaultLayout+  wid <- nextId+  addWidget wid NodeText txt 0 base++-- | 'label' with a layout modifier, for example @labelWith fontMono@.+--+-- A label wider than its room wraps in a column. In a row, a single-line+-- label with 'fillW' or 'maxW' instead ends in @...@ where it is cut, so+-- @labelWith fillW name@ beside a row's buttons uses the remaining width.+-- 'NanoUI.truncateTextUi' cuts text the same way for a drawing.+labelWith :: (Layout -> Layout) -> Text -> NanoUI ()+labelWith f txt = do+  base <- askDefaultLayout+  wid <- nextId+  addWidgetVoid wid NodeText txt 0 (f base)++-- | 'labelWith' returning geometry and interaction information in a 'Response'.+labelWith' :: (Layout -> Layout) -> Text -> NanoUI Response+labelWith' f txt = do+  base <- askDefaultLayout+  wid <- nextId+  addWidget wid NodeText txt 0 (f base)++labelEx :: Layout -> Text -> NanoUI Response+labelEx layout txt = do+  wid <- nextId+  addWidget wid NodeText txt 0 layout++-- | Takes up the remaining space along the parent's direction: across a row,+-- down a column. Flexes in one container share that space equally.+flex :: NanoUI ()+flex = axisLeaf NodeSpacer Fit (Grow 1)++-- | A one-pixel rule: horizontal in a column, vertical in a row.+separator :: NanoUI ()+separator = axisLeaf NodeSeparator (Grow 1) (Fixed 1)++-- | A leaf sized @across@ and @along@ the current parent's direction (a+-- column at the root).+axisLeaf :: NodeType -> Sizing -> Sizing -> NanoUI ()+axisLeaf nt across along = do+  wid <- nextId+  withContext $ \ctx -> do+    parent <- currentParent ctx+    dir <- if parent < 0 then pure DirColumn else getDirection (ctxNodeArena ctx) parent+    case dir of+      DirColumn -> addSizedLeaf ctx wid nt Column across along+      DirRow -> addSizedLeaf ctx wid nt Row along across++-- | Empty space with the given sizing on each axis.+{-# INLINE spacer #-}+spacer :: Sizing -> Sizing -> NanoUI ()+spacer w h = do+  wid <- nextId+  withContext (\ctx -> addSizedLeaf ctx wid NodeSpacer Row w h)++-- | Fixed horizontal space in logical pixels.+{-# INLINE spacerW #-}+spacerW :: Float -> NanoUI ()+spacerW w = spacer (Fixed w) Fit++-- | Fixed vertical space in logical pixels.+{-# INLINE spacerH #-}+spacerH :: Float -> NanoUI ()+spacerH h = spacer Fit (Fixed h)++-- | A leaf with no content under the current parent, sized on each axis. It+-- takes no input, so it resolves no 'Response'.+addSizedLeaf :: Context -> WidgetId -> NodeType -> Direction -> Sizing -> Sizing -> IO ()+addSizedLeaf ctx wid nt dir w h = do+  parent <- currentParent ctx+  idx <-+    addNode (ctxNodeArena ctx) nt parent . gap 0 . tight $+      defaultLayout {layoutDirection = dir, layoutWidth = w, layoutHeight = h}+  setWidgetId (ctxNodeArena ctx) idx wid++-- | Fill the available space and put the body in its middle on both axes.+-- The body is one block whose children stack top to bottom as in a+-- 'column', each placed across the block by its own alignment: give a child+-- narrower than its siblings 'alignCenter' to center it under them too.+{-# INLINE center #-}+center :: NanoUI a -> NanoUI a+center = layersWith grow . columnWith (tight . alignCenter . alignMiddle)++-- | Scroll along the current layout direction, vertical by default. Constrain+-- the viewport size so content can overflow it; the body still runs each frame.+scroll :: NanoUI a -> NanoUI a+scroll = scrollWith id++-- | 'scroll' with modified viewport layout. Use 'scrollWith'' when scroll+-- commands or overlays need the container's 'Response' ('respId', 'respRect').+scrollWith :: LayoutModifier -> NanoUI a -> NanoUI a+scrollWith = scrollFrom (scrollDefault1D . layoutDirection)++-- | 'scrollWith' returning the body's result and the container's 'Response',+-- whose 'respId' keys its scroll offset.+scrollWith' :: LayoutModifier -> NanoUI a -> NanoUI (a, Response)+scrollWith' = scrollFrom' (scrollDefault1D . layoutDirection)++scrollAreaIdConfigured :: WidgetId -> Layout -> ScrollConfig -> NanoUI a -> NanoUI a+scrollAreaIdConfigured wid layout cfg child = do+  idx <- withContext $ \ctx -> do+    parent <- currentParent ctx+    idx <- addNodeFromLayout (ctxNodeArena ctx) NodeScrollContainer parent layout+    setWidgetId (ctxNodeArena ctx) idx wid+    setStyleIdx (ctxNodeArena ctx) idx (encodeScrollConfig cfg)+    when (scrollFocusable cfg) $+      registerFocusable ctx wid+    pure idx+  -- Unscoped: a scroll container's children keep their parent's id scope.+  withContainerNode False idx child++-- | Scroll container on both axes.+scroll2D :: NanoUI a -> NanoUI a+scroll2D = scroll2DWith id++-- | 'scroll2D' with modified viewport layout.+scroll2DWith :: LayoutModifier -> NanoUI a -> NanoUI a+scroll2DWith = scrollFrom (const scroll2DConfig)++-- | 'scroll2DWith' returning the body's result and the container's 'Response'.+scroll2DWith' :: LayoutModifier -> NanoUI a -> NanoUI (a, Response)+scroll2DWith' = scrollFrom' (const scroll2DConfig)++-- | Scroll container with an explicit 'ScrollConfig' and viewport layout.+scrollConfigured :: ScrollConfig -> LayoutModifier -> NanoUI a -> NanoUI a+scrollConfigured cfg = scrollFrom (const cfg)++-- | 'scrollConfigured' returning the body's result and the container's 'Response'.+scrollConfigured' :: ScrollConfig -> LayoutModifier -> NanoUI a -> NanoUI (a, Response)+scrollConfigured' cfg = scrollFrom' (const cfg)++scrollFrom ::+  (Layout -> ScrollConfig) -> LayoutModifier -> NanoUI a -> NanoUI a+scrollFrom config f child = do+  layout <- f <$> askDefaultLayout+  wid <- nextId+  scrollAreaIdConfigured wid layout (config layout) child++scrollFrom' ::+  (Layout -> ScrollConfig) -> LayoutModifier -> NanoUI a -> NanoUI (a, Response)+scrollFrom' config f child = do+  layout <- f <$> askDefaultLayout+  wid <- nextId+  inp <- askInput+  r <- scrollAreaIdConfigured wid layout (config layout) child+  resp <- withContext (\ctx -> resolveInteraction ctx inp (-1) wid)+  pure (r, resp)
+ lib/NanoUI/Internal/Widgets/Menu.hs view
@@ -0,0 +1,194 @@+-- | Menu rows, menu-bar buttons, and context-menu state for application views.+module NanoUI.Internal.Widgets.Menu+  ( contextMenu+  , contextMenuArea+  , menuButton+  , menuButton'+  , menuButtonWith+  , menuButtonWith'+  , menuItem+  , menuItem'+  , menuItemShortcut+  , menuItemDisabled+  , menuSeparator+  , menuHeader+  )+where++import Control.Monad (void, when)+import Data.IORef (readIORef)+import Data.Map.Strict qualified as M+import Data.Text (Text)+import NanoUI.Internal.Context (Context (..), PressPoint (..), getStore, intKey, modifyStore)+import NanoUI.Internal.Frame.Hit (withWidgetNode)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Font (menuItemPadX, menuItemRowH, menuMinW, menuOuterPad, menuSepH, widgetContentInset)+import NanoUI.Internal.Input (MouseButton (..), Pressable (..), inputMousePos, inputWindowSize)+import NanoUI.Internal.Monad (NanoUI, askContext, askInput, freshWidget, liftIO, (<&&>))+import NanoUI.Internal.Store (findSpec, insertSpec)+import NanoUI.Internal.Store.Slots (setFlagSpec, slotMenuOpen, slotMenuPos)+import NanoUI.Internal.Style (Layout (..), Padding (..), defaultLayout, fillW, fixedH, fontMuted, gap, grow, maxH, minW, padXY, tight, windowMargin)+import NanoUI.Internal.Types (PopupAnchor (..), PopupPlacement (..), Size (..), V2 (..))+import NanoUI.Internal.WidgetText (ButtonKind (..), buttonFlagMenu, buttonFlagMenuBar, buttonKindOf)+import NanoUI.Internal.Widgets.Combinators (buttonStyledEx)+import NanoUI.Internal.Widgets.Layout (columnWith, labelEx, rowWith, scrollWith, separator, withDefaultWith)+import NanoUI.Internal.Layout.Arena (NodeType (..), getNodeType, getStyleIdx)+import NanoUI.Internal.Widgets.Node (HasResponse, Response (..), containerResponse, inertResponse, respClicked, respHovered, respRightClicked)+import NanoUI.Internal.Var.Types (constVar)+import NanoUI.Internal.Widgets.Popup (PopupConfig (..), defaultPopupConfig, popupWith')+import NanoUI.Internal.Widgets.Shortcut (shortcut)+import NanoUI.Internal.Shortcut (Shortcut, shortcutLabel)++-- | A context menu for any widget response, opened by right-clicking it.+-- Returns the menu body's result while the menu is open. A click on a row+-- closes it, and a menu taller than the window scrolls.+contextMenu ::+  HasResponse r =>+  r ->+  NanoUI a ->+  NanoUI (Maybe a)+contextMenu target child = do+  menu <- freshWidget+  runContextMenu menu (respRightClicked target) (const child)++-- | A container whose right-click opens a context menu. The menu body+-- receives the position it was opened at.+contextMenuArea ::+  (Layout -> Layout) ->+  NanoUI a ->+  (V2 -> NanoUI b) ->+  NanoUI (a, Maybe b)+contextMenuArea f areaContent menuContent = do+  menu <- freshWidget+  (areaRes, areaResp) <- withDefaultWith f (containerResponse NodeContainer) areaContent+  (,) areaRes <$> runContextMenu menu (respRightClicked areaResp) menuContent++-- | Open the menu at the pointer on a right click, show it while open, and+-- close it once a row is picked or it is dismissed. Whether it is open, and+-- where, is kept in the store under the menu's id.+runContextMenu ::+  (WidgetId, Context) ->+  Bool ->+  (V2 -> NanoUI a) ->+  NanoUI (Maybe a)+runContextMenu (wid, ctx) rightClick child = do+  inp <- askInput+  store <- liftIO (getStore ctx)+  let key = intKey wid+      mouse = inputMousePos inp+      pos = if rightClick then mouse else findSpec slotMenuPos (V2 0 0) key store+      cfg = (defaultPopupConfig (AnchorPoint pos)) {popupPlacement = PlacementAtCursor, popupOffset = 0}+      -- A menu taller than the window is held inside it, as a modal is, and+      -- its rows scroll.+      Size _ winH = inputWindowSize inp+      fitWindow = maxH (max 1 (winH - 2 * windowMargin))+  when rightClick $ liftIO (modifyStore ctx (setFlagSpec slotMenuOpen key True . insertSpec slotMenuPos key mouse))+  -- A left-button release inside the menu popup picks the row the press went+  -- down on. One on a disabled row, a header, a separator or the padding+  -- picks nothing.+  (popupResp, mBody) <-+    popupWith' (constVar (findSpec slotMenuOpen False key store || rightClick)) cfg fitWindow $ do+      r <- scrollWith (tight . gap 0 . grow) (child pos)+      onRow <- (releasedIn MouseLeft <$> askInput) <&&> liftIO (pressedMenuRow ctx)+      pure (onRow, r)+  let picked = respHovered popupResp && maybe False fst mBody+  when (respClicked popupResp || picked) $ liftIO (modifyStore ctx (setFlagSpec slotMenuOpen key False))+  pure (snd <$> mBody)++-- | Whether the left button went down on a menu row, added this frame.+pressedMenuRow :: Context -> IO Bool+pressedMenuRow ctx = do+  let na = ctxNodeArena ctx+  presses <- readIORef (ctxPressPos ctx)+  case M.lookup MouseLeft presses of+    Just PressPoint {ppOwner = Just row} ->+      withWidgetNode ctx row False $ \idx ->+        ((== NodeButton) <$> getNodeType na idx) <&&> ((== ButtonMenu) . buttonKindOf <$> getStyleIdx na idx)+    _ -> pure False++-- | A menu row with an optional shortcut hint after the label. A disabled+-- row is a muted label, not a button (hover would still light a disabled+-- button), padded to match an enabled row. It reports no interaction.+menuItemWith :: Text -> Maybe Text -> Bool -> NanoUI Response+menuItemWith lbl hint enabled+  | enabled = buttonStyledEx True text 0 menuRowLayout buttonFlagMenu+  | otherwise = do+      ctx <- askContext+      let (ix, _) = widgetContentInset (ctxFontMetrics ctx)+          padLeft = menuItemPadX + ix+          padRight = max 0 (2 * (menuOuterPad + menuItemPadX) - padLeft)+          rowLayout = (minW menuMinW defaultLayout) {layoutPadding = Padding padLeft padRight 0 0}+      (_, resp) <-+        containerResponse NodeContainer rowLayout $+          labelEx (fixedH menuItemRowH . tight . fontMuted $ defaultLayout) text+      pure (inertResponse resp)+  where+    text = maybe lbl (\s -> mconcat [lbl, "  ", s]) hint++-- | Menu row. 'True' on the frame it is clicked.+--+-- > whenM (menuItem "Open...") openFile+{-# INLINE menuItem #-}+menuItem :: Text -> NanoUI Bool+menuItem txt = respClicked <$> menuItem' txt++{-# INLINE menuItem' #-}+-- | 'menuItem' returning its response; activation is in @respClicked@.+menuItem' :: Text -> NanoUI Response+menuItem' txt = menuItemWith txt Nothing True++-- | Menu row bound to a shortcut, showing the chord's 'shortcutLabel' after+-- the label. 'True' on the frame it is clicked, or when its chord is pressed+-- while the menu is open ('shortcut'); a click closes the menu, the chord+-- leaves it open. For the chord to work while the menu is closed, also bind+-- it with 'shortcut' outside the menu.+--+-- > whenM (menuItemShortcut "Save" (ctrl <> key 's')) saveFile+menuItemShortcut :: Text -> Shortcut -> NanoUI Bool+menuItemShortcut txt chord = do+  clicked <- respClicked <$> menuItemWith txt (Just (shortcutLabel chord)) True+  pressed <- shortcut chord+  pure (clicked || pressed)++-- | Dimmed menu row that cannot be clicked.+menuItemDisabled :: Text -> NanoUI ()+menuItemDisabled txt = void (menuItemWith txt Nothing False)++-- | Row layout shared by menu items, matching the text-field context menu.+menuRowLayout :: Layout+menuRowLayout = minW menuMinW . fixedH menuItemRowH . tight . fillW $ defaultLayout++-- | Menu-bar title: a flat, label-sized button. @open@ tints the title while+-- its drop-down is showing. 'True' on the frame it is clicked.+{-# INLINE menuButton #-}+menuButton :: Text -> Bool -> NanoUI Bool+menuButton txt open = respClicked <$> menuButton' txt open++-- | 'menuButton' returning its 'Response', whose rect anchors the drop-down.+menuButton' :: Text -> Bool -> NanoUI Response+menuButton' = menuButtonWith' id++-- | 'menuButton' with modified layout. A menu bar whose row is taller than a+-- label gives its titles 'NanoUI.fillH', so that each one covers the bar it+-- is in and its text sits in the middle of it rather than at the top.+{-# INLINE menuButtonWith #-}+menuButtonWith :: (Layout -> Layout) -> Text -> Bool -> NanoUI Bool+menuButtonWith f txt open = respClicked <$> menuButtonWith' f txt open++-- | 'menuButtonWith' returning its 'Response'.+menuButtonWith' :: (Layout -> Layout) -> Text -> Bool -> NanoUI Response+menuButtonWith' f txt open =+  buttonStyledEx True txt (if open then 1 else 0) (f (tight defaultLayout)) buttonFlagMenuBar++-- | Separator line inside a context menu, matching the text-field context+-- menu: a 1px rule inset 'menuItemPadX' from the panel edge, centred in a+-- 'menuSepH' band. The tight column keeps the rule horizontal.+menuSeparator :: NanoUI ()+menuSeparator = do+  rowWith (fixedH menuSepH . padXY (menuItemPadX - menuOuterPad) 4.5 . fillW) $+    columnWith (tight . fillW) separator++-- | Header / category title inside a context menu.+menuHeader :: Text -> NanoUI ()+menuHeader txt =+  void (labelEx (padXY 6 2 defaultLayout) txt)
+ lib/NanoUI/Internal/Widgets/Node.hs view
@@ -0,0 +1,564 @@+-- | Widget node construction and interaction responses.+module NanoUI.Internal.Widgets.Node+  ( Response (..)+  , HasResponse (..)+  , respId+  , respRect+  , respHovered+  , respPressed+  , respClicked+  , respChanged+  , respSubmitted+  , respHeldWith+  , respClickedWith+  , respRightPressed+  , respRightClicked+  , pointerOnWidget+  , pointerReachable+  , anyControlHitInRange+  , mkResponse+  , setClicked+  , setChanged+  , setSubmitted+  , inertResponse+  , currentParent+  , container+  , styledContainer+  , containerResponse+  , mouseArea+  , inertContainer+  , clipContainer+  , withContainerNode+  , withWidgetChildren+  , floatingPanel+  , dropdownInput+  , dropdownBodyInput+  , inDropdownScope+  , addWidget+  , addWidgetVoid+  , addWidgetStyled+  , addWidgetNode+  , addWidgetWithOptions+  , tagContainer+  , setWidgetValue+  , moveSelection+  , resolveInteraction+  )+where++import Control.Monad (forM, forM_, unless, when)+import Data.Bits ((.|.))+import Data.IORef (readIORef)+import Data.IntSet qualified as IS+import Data.Map.Strict qualified as M+import Data.Text (Text)+import Data.Word (Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Context.Types (peekContainer, popContainer, pushContainer)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId, mix64, scopeIdContext, scopeTag)+import NanoUI.Internal.Id.Cursor (popIdScope, pushIdScope)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (NanoUI, (<&&>), askContext, askDefaultLayout, askFrameInput, askInput, currentId, inertView, localInput, nextId, liftIO, withContext, withIdFrame, withKey)+import NanoUI.Internal.WidgetText (containerFlagClip, containerFlagInert, labelFontStyle, packTextNodeStyle)+import NanoUI.Internal.Style (Layout (..), tight)+import NanoUI.Internal.Types (Rect (..), V2, rectContains, rectH, rectUnion, rectW)+import NanoUI.Internal.Frame.Hit (findNodeByWidgetId, nodeInteractionHit, passesPointer, withWidgetNode)++-- | The innermost open container, or @-1@ at the root.+{-# INLINE currentParent #-}+currentParent :: Context -> IO Int+currentParent ctx = peekContainer (ctxContainerStack ctx)++-- | Anything that carries a widget 'Response' (composite widget results such+-- as 'NanoUI.TabResponse'). The @resp*@ accessors work on all of them.+class HasResponse r where+  toResponse :: r -> Response++instance HasResponse Response where+  {-# INLINE toResponse #-}+  toResponse = id++-- | Widget identity used for state, tooltips, and commands.+{-# INLINE respId #-}+respId :: HasResponse r => r -> WidgetId+respId = rawRespId . toResponse++-- | Widget bounds in logical window coordinates. During view construction,+-- these come from the previous frame and can be empty on first appearance.+{-# INLINE respRect #-}+respRect :: HasResponse r => r -> Rect+respRect = rawRespRect . toResponse++-- | Whether the routed pointer is over the widget's visible hit area.+{-# INLINE respHovered #-}+respHovered :: HasResponse r => r -> Bool+respHovered = rawRespHovered . toResponse++-- | 'respHeldWith' 'MouseLeft'. A held state, not a one-frame button-down+-- event.+{-# INLINE respPressed #-}+respPressed :: HasResponse r => r -> Bool+respPressed = respHeldWith MouseLeft++-- | Whether the widget was activated this frame: a left click, or whatever+-- key activates it while focused (usually Enter or Space). For clicks of a+-- specific button only, use 'respClickedWith'.+{-# INLINE respClicked #-}+respClicked :: HasResponse r => r -> Bool+respClicked = rawRespClicked . toResponse++-- | Whether the widget reports a value change. Search fields debounce this flag.+{-# INLINE respChanged #-}+respChanged :: HasResponse r => r -> Bool+respChanged = rawRespChanged . toResponse++-- | Whether the widget reports a commit, such as Enter in a text field.+{-# INLINE respSubmitted #-}+respSubmitted :: HasResponse r => r -> Bool+respSubmitted = rawRespSubmitted . toResponse++-- | Whether the button went down on the widget and is held over it. A+-- button pressed elsewhere and dragged over does not count.+--+-- > (_, area) <- mouseArea id (label "Pan me")+-- > when (respHeldWith MouseMiddle area) (pan =<< uiMousePos)+{-# INLINE respHeldWith #-}+respHeldWith :: HasResponse r => MouseButton -> r -> Bool+respHeldWith b = buttonsMember b . rawRespHeld . toResponse++-- | Whether the button was pressed and released on the widget this frame.+-- Non-left clicks are reported only here, for the view to handle (a middle+-- click closing a tab, say). Left clicks also set 'respClicked'.+{-# INLINE respClickedWith #-}+respClickedWith :: HasResponse r => MouseButton -> r -> Bool+respClickedWith b = buttonsMember b . rawRespClickedWith . toResponse++-- | 'respHeldWith' 'MouseRight'.+{-# INLINE respRightPressed #-}+respRightPressed :: HasResponse r => r -> Bool+respRightPressed = respHeldWith MouseRight++-- | 'respClickedWith' 'MouseRight'.+{-# INLINE respRightClicked #-}+respRightClicked :: HasResponse r => r -> Bool+respRightClicked = respClickedWith MouseRight++-- | Per-frame widget identity, bounds, and interaction flags. Primed widget+-- variants expose this alongside their value. Combining responses unions+-- bounds, flags and buttons, and keeps the last nonzero id.+data Response = Response+  { rawRespId :: {-# UNPACK #-} !WidgetId+  , rawRespRect :: {-# UNPACK #-} !Rect+  , rawRespHovered :: !Bool+  , rawRespClicked :: !Bool+  , rawRespChanged :: !Bool+  , rawRespSubmitted :: !Bool+  , rawRespHeld :: {-# UNPACK #-} !MouseButtons+  -- ^ See 'respHeldWith'.+  , rawRespClickedWith :: {-# UNPACK #-} !MouseButtons+  -- ^ See 'respClickedWith'.+  }+  deriving (Eq, Show)++instance Semigroup Response where+  Response i1 r1 h1 c1 ch1 s1 held1 cw1 <> Response i2 r2 h2 c2 ch2 s2 held2 cw2 =+    Response+      (if i2 == WidgetId 0 then i1 else i2)+      (unionRespRect r1 r2)+      (h1 || h2) (c1 || c2) (ch1 || ch2) (s1 || s2) (held1 <> held2) (cw1 <> cw2)++instance Monoid Response where+  mempty = mkResponse (WidgetId 0) (Rect 0 0 0 0) False False False++unionRespRect :: Rect -> Rect -> Rect+unionRespRect a b+  | rectW a <= 0 || rectH a <= 0 = b+  | rectW b <= 0 || rectH b <= 0 = a+  | otherwise = rectUnion a b++-- | Replace only the activation flag, for composite widgets.+{-# INLINE setClicked #-}+setClicked :: Bool -> Response -> Response+setClicked c r = if rawRespClicked r == c then r else r {rawRespClicked = c}++-- | Replace only the value-change flag.+{-# INLINE setChanged #-}+setChanged :: Bool -> Response -> Response+setChanged c r = if rawRespChanged r == c then r else r {rawRespChanged = c}++-- | Replace only the commit flag.+{-# INLINE setSubmitted #-}+setSubmitted :: Bool -> Response -> Response+setSubmitted s r = if rawRespSubmitted r == s then r else r {rawRespSubmitted = s}++-- | The response of a control that takes no input: its id and rect, and no+-- interaction.+inertResponse :: Response -> Response+inertResponse r =+  r {rawRespHovered = False, rawRespClicked = False, rawRespHeld = noButtons, rawRespClickedWith = noButtons}++-- | An unpressed response with the given hover, click, and change flags.+mkResponse :: WidgetId -> Rect -> Bool -> Bool -> Bool -> Response+mkResponse wid rect hovered clicked changed =+  Response wid rect hovered clicked changed False noButtons noButtons++container :: NodeType -> Layout -> NanoUI a -> NanoUI a+container nt layout child = do+  ctx <- askContext+  liftIO $ do+    parent <- currentParent ctx+    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout+    pushContainer (ctxContainerStack ctx) idx+    pushIdScope (ctxIdCursor ctx) scopeTag+  r <- child+  liftIO $ do+    popContainer (ctxContainerStack ctx)+    popIdScope (ctxIdCursor ctx)+  pure r++-- | A display-only container: child widgets receive no interaction, and+-- pointer events pass through to the enclosing widget+-- ('NanoUI.Internal.Frame.Hit.innermostHit').+inertContainer :: Layout -> NanoUI a -> NanoUI a+inertContainer layout = styledContainer NodeContainer containerFlagInert layout . inertView++-- | A plain container that clips its children to its rect, drawing none of+-- its own. It takes a fresh id, so the pointer is clipped from the frame+-- after it is laid out.+clipContainer :: Layout -> NanoUI a -> NanoUI a+clipContainer layout child = do+  wid <- nextId+  styledContainer NodeContainer containerFlagClip layout (tagContainer wid *> child)++-- | A 'container' of type @nt@ with style index @si@: a plain container's+-- flags, or a panel's row fill (@panelSurface@).+styledContainer :: NodeType -> Word64 -> Layout -> NanoUI a -> NanoUI a+styledContainer nt si layout child = do+  ctx <- askContext+  liftIO $ do+    parent <- currentParent ctx+    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout+    when (si /= 0) (setStyleIdx (ctxNodeArena ctx) idx si)+    pushContainer (ctxContainerStack ctx) idx+    pushIdScope (ctxIdCursor ctx) scopeTag+  r <- child+  liftIO $ do+    popContainer (ctxContainerStack ctx)+    popIdScope (ctxIdCursor ctx)+  pure r++-- | Whether @mouse@ reaches container @wid@: neither covered, disabled, nor+-- outside its enclosing clip from last frame.+pointerReachable :: Context -> WidgetId -> V2 -> IO Bool+pointerReachable ctx wid mouse =+  (not <$> pointerCovered ctx wid)+    <&&> (not <$> isDisabled ctx wid)+    <&&> (maybe True (`rectContains` mouse) <$> getPrevClipRect ctx wid)++-- | Whether @mouse@ is on an enabled, uncovered widget node in @[from .. to)@.+anyControlHitInRange :: Context -> V2 -> Int -> Int -> IO Bool+anyControlHitInRange ctx mouse from to = go from+  where+    na = ctxNodeArena ctx+    go !i+      | i >= to = pure False+      | otherwise = do+          hit <-+            (isWidgetNode <$> getNodeType na i) <&&> do+              w <- getWidgetId na i+              (not <$> isDisabled ctx w)+                <&&> (not <$> pointerCovered ctx w)+                <&&> (maybe (pure False) (\r -> nodeInteractionHit ctx i r mouse) =<< getPrevRect ctx w)+          if hit then pure True else go (i + 1)++-- | A 'container' tagged with a fresh id, and its interaction under that id.+containerResponse :: NodeType -> Layout -> NanoUI a -> NanoUI (a, Response)+containerResponse nt layout child = do+  wid <- nextId+  inp <- askInput+  r <- container nt layout (tagContainer wid >> child)+  resp <- withContext (\ctx -> resolveInteraction ctx inp (-1) wid)+  pure (r, resp)++-- | An unpadded column that reports pointer activity over itself and its+-- contents, like iced's @mouse_area@: 'respHovered', 'respHeldWith',+-- 'respClickedWith' and 'respClicked'. A press on an interactive child (a+-- button, field or slider) belongs to that child, whichever mouse button it+-- is; presses on passive content such as labels, and between children, go+-- to the area. Children do not cover the area, so hover stays true while the+-- pointer is over them:+--+-- > hovered <- useVar False+-- > (_, item) <- mouseArea (fillW . gap 6) $ do+-- >   label name+-- >   whenM (readVar hovered) (void (button "Delete"))+-- > writeVar hovered (respHovered item)+-- > when (respClickedWith MouseMiddle item) (openInNewTab name)+mouseArea :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)+mouseArea f body = do+  base <- askDefaultLayout+  containerResponse NodeContainer (f (tight base)) body++-- | Push container node @idx@ (already added under the current parent), run+-- @child@ inside it, then pop. @scoped@ also runs the children in a fresh id+-- scope; it changes the children's widget ids (and so their store keys), so+-- callers pick it explicitly: plain containers scope, scroll containers do not.+--+-- Like every view build scope, it installs no exception handler+-- ('NanoUI.Internal.Monad.withBuildScope'); 'NanoUI.Internal.Monad.catchView'+-- restores the container stack for a view that recovers.+withContainerNode :: Bool -> NodeIdx -> NanoUI a -> NanoUI a+withContainerNode scoped idx child = do+  ctx <- askContext+  liftIO $ do+    pushContainer (ctxContainerStack ctx) idx+    when scoped $ pushIdScope (ctxIdCursor ctx) scopeTag+  r <- child+  liftIO $ do+    popContainer (ctxContainerStack ctx)+    when scoped $ popIdScope (ctxIdCursor ctx)+  pure r++-- | Run @child@ inside the node of widget @wid@, just added, in the id scope+-- the widget's id opens, so its siblings' ids do not move; 'Nothing' when it+-- has no node.+withWidgetChildren :: WidgetId -> NanoUI a -> NanoUI (Maybe a)+withWidgetChildren wid@(WidgetId w) child = do+  mIdx <- withContext (\ctx -> lookupNodeByWidgetId (ctxNodeArena ctx) wid)+  forM mIdx $ \idx ->+    withContainerNode False idx (withIdFrame (\ids -> (ids, scopeIdContext (mix64 w scopeTag))) child)++-- | A floating panel (popup, modal, window): its node attaches to the root+-- layer, and @body@ runs as a layer of its own, with the pointer when the+-- panel is what the frame routed it to. @addPanel@ adds the node under the+-- given parent; @enter@ runs once the node is pushed (seeding its rect,+-- opening a modal). The body runs in a fresh id scope.+floatingPanel ::+  WidgetId -> (Int -> IO NodeIdx) -> IO () -> NanoUI a -> NanoUI a+floatingPanel wid addPanel enter body = do+  ctx <- askContext+  let arena = ctxNodeArena ctx+  idx <- liftIO $ do+    idx <- addPanel =<< rootAttachParent arena =<< currentParent ctx+    setWidgetId arena idx wid+    pure idx+  withContainerNode True idx $ do+    -- A modal has to be entered first: that is what lets its own body through.+    liftIO enter+    frame <- askFrameInput+    inp <- liftIO (routedInput ctx (intKey wid) frame)+    localInput inp body++-- | Run @body@ in the keyed scope that holds field @owner@'s dropdown popup:+-- the popup is the first id the scope issues, so 'dropdownInput' knows its+-- key before it is declared.+inDropdownScope :: WidgetId -> NanoUI a -> NanoUI a+inDropdownScope owner = withKey (intKey owner, dropdownScopeTag)++dropdownScopeTag :: Text+dropdownScopeTag = "dropdown"++-- | The input for field @owner@ of a dropdown it declares in+-- 'inDropdownScope': the frame's while the pointer is routed to that+-- dropdown, and the view's otherwise.+dropdownInput :: WidgetId -> NanoUI Input+dropdownInput owner = do+  popup <- inDropdownScope owner currentId+  withContext (\ctx -> getsInteraction ctx isPointerRoute) >>= \case+    RouteDropdown k | k == intKey popup -> askFrameInput+    _ -> askInput++-- | The input for the body of field @owner@'s dropdown popup: its layer's,+-- or the frame's while the left press that went down on @owner@ is held, so+-- that a press on the field released on a row picks that row.+dropdownBodyInput :: WidgetId -> NanoUI Input+dropdownBodyInput owner = do+  inp <- askInput+  active <- withContext (readIORef . ctxActiveId)+  if active == owner && hashWidgetId owner /= 0 then askFrameInput else pure inp++{-# INLINE addWidget #-}+addWidget ::+  WidgetId+  -> NodeType+  -> Text+  -> Float+  -> Layout+  -> NanoUI Response+addWidget wid nt txt value layout = addWidgetStyled wid nt txt value layout 0++-- | Add a passive node (such as a plain label) without computing an+-- interaction 'Response'.+{-# INLINE addWidgetVoid #-}+addWidgetVoid ::+  WidgetId+  -> NodeType+  -> Text+  -> Float+  -> Layout+  -> NanoUI ()+addWidgetVoid wid nt txt value layout = do+  ctx <- askContext+  liftIO $ do+    parent <- currentParent ctx+    let na = ctxNodeArena ctx+    idx <- addNodeFromLayout na nt parent layout+    setNodeText na idx txt+    setNodeValue na idx value+    setStyleIdx na idx $ case nt of+      NodeText -> packTextNodeStyle layout 0+      NodeButton -> labelFontStyle layout+      _ -> 0+    setWidgetId na idx wid++{-# INLINE addWidgetStyled #-}+addWidgetStyled ::+  WidgetId+  -> NodeType+  -> Text+  -> Float+  -> Layout+  -> Word64+  -> NanoUI Response+addWidgetStyled wid nt txt value layout styleIdx =+  addWidgetNode wid nt txt value layout $ \arena idx ->+    setStyleIdx arena idx $ case nt of+      NodeText -> packTextNodeStyle layout (fromIntegral styleIdx)+      NodeButton -> styleIdx .|. labelFontStyle layout+      _ -> styleIdx++-- The initializer specializes at each call site; the node allocation, identity+-- and interaction path are shared by styled leaves and option controls.+{-# INLINE addWidgetNode #-}+addWidgetNode ::+  WidgetId+  -> NodeType+  -> Text+  -> Float+  -> Layout+  -> (NodeArena -> NodeIdx -> IO ())+  -> NanoUI Response+addWidgetNode wid nt txt value layout initialize = do+  ctx <- askContext+  inp <- askInput+  liftIO $ do+    parent <- currentParent ctx+    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout+    setNodeText (ctxNodeArena ctx) idx txt+    setNodeValue (ctxNodeArena ctx) idx value+    initialize (ctxNodeArena ctx) idx+    setWidgetId (ctxNodeArena ctx) idx wid+    resolveInteraction ctx inp idx wid++addWidgetWithOptions ::+  WidgetId+  -> NodeType+  -> Text+  -> [Text]+  -> Float+  -> Layout+  -> NanoUI Response+addWidgetWithOptions wid nt txt opts value layout =+  addWidgetNode wid nt txt value layout $ \arena idx -> do+    setOptions arena idx opts+    setStyleIdx arena idx (if nt == NodeSelect then labelFontStyle layout else 0)++-- | Whether @mouse@ is on widget @wid@ (last frame's @rect@, node @mIdx@):+-- inside its scroll-visible part ('nodeInteractionHit'), not covered by+-- another pointer-taking node ('pointerCovered'), and not 'passesPointer'.+-- Disabled and drag-capture checks are left to the caller.+pointerOnWidget :: Context -> Maybe NodeIdx -> WidgetId -> Rect -> V2 -> IO Bool+pointerOnWidget ctx mIdx wid rect mouse =+  (not <$> pointerCovered ctx wid)+    <&&> (not <$> maybe (pure False) (passesPointer (ctxNodeArena ctx)) mIdx)+    <&&> widgetHit ctx mIdx rect mouse++-- | Whether @p@ is inside the scroll-visible part of @rect@+-- ('nodeInteractionHit'), or inside @rect@ when there is no node.+widgetHit :: Context -> Maybe NodeIdx -> Rect -> V2 -> IO Bool+widgetHit ctx mIdx rect p = maybe (pure (rectContains rect p)) (\idx -> nodeInteractionHit ctx idx rect p) mIdx++-- | The interaction of widget @wid@, declared as node @idx@ (or -1), with+-- the pointer and buttons of @inp@, judged against its last-frame rect.+-- Inlined so unhovered widgets whose callers only inspect 'respClicked' or+-- discard the 'Response' never allocate it.+{-# INLINE resolveInteraction #-}+resolveInteraction :: Context -> Input -> NodeIdx -> WidgetId -> IO Response+resolveInteraction ctx inp idx wid = do+  rect <- getPrevRectAt ctx idx wid+  pending <- readIORef (ctxClickedId ctx)+  if not (rectContains rect (inputMousePos inp) || pending == wid)+    then pure $! mkResponse wid rect False False False+    else resolveInteractionSlow ctx inp wid rect pending++{-# NOINLINE resolveInteractionSlow #-}+resolveInteractionSlow :: Context -> Input -> WidgetId -> Rect -> WidgetId -> IO Response+resolveInteractionSlow ctx inp wid rect pending = do+  let mouse = inputMousePos inp+  active <- readIORef (ctxActiveId ctx)+  disabled <- isDisabled ctx wid+  mIdx <- findNodeByWidgetId ctx wid+  presses <- readIORef (ctxPressPos ctx)+  let+    -- Whether the button press started on this widget, in the frame the+    -- user saw: a left press on the widget it reached or one of its+    -- ancestors, another button only on the widget itself. A press that+    -- reached nothing (passive content) is judged by this widget's+    -- rect, and one with no record (synthesized or swallowed input) is+    -- allowed.+    startedHere b = case M.lookup b presses of+      Just PressPoint {ppOwner = Just owner, ppReached = reached}+        | b /= MouseLeft -> pure (owner == wid)+        | otherwise -> pure (IS.member (intKey wid) reached)+      Just PressPoint {ppPos = p} -> widgetHit ctx mIdx rect p+      Nothing -> pure True+  -- A held left button belongs to the widget it went down on; others+  -- the drag passes over are not hovered.+  -- A container the press went down inside (a mouse area around the+  -- pressed button) keeps its hover.+  enclosing <- maybe (pure False) (fmap (not . isWidgetNode) . getNodeType (ctxNodeArena ctx)) mIdx+  captured <-+    pure (heldIn MouseLeft inp)+      <&&> if hashWidgetId active /= 0 && active /= wid && not enclosing+        then pure True+        else not <$> startedHere MouseLeft+  -- Covered widgets and 'PointerPass' nodes get no hover.+  hovered <- pure (not (disabled || captured)) <&&> pointerOnWidget ctx mIdx wid rect mouse+  -- Other buttons count only if pressed here. A hovered widget already+  -- owns a held left button.+  let ownedHere bs = if hovered then buttonsFilterM startedHere bs else pure noButtons+      leftHeld = if hovered && heldIn MouseLeft inp then buttonsInsert MouseLeft noButtons else noButtons+  held <- (leftHeld <>) <$> ownedHere (buttonsDelete MouseLeft (inputButtonsHeld inp))+  released <- ownedHere (inputButtonsReleased inp)+  -- The click belongs to whatever the press went down on: a release that+  -- drifted here from a neighbouring widget is not this widget's click,+  -- nor is one on a widget that moved under the pointer after another+  -- widget took the press.+  let ownsRelease = hashWidgetId active == 0 || active == wid+      clickedWith = if ownsRelease then released else buttonsDelete MouseLeft released+      leftClicked = buttonsMember MouseLeft clickedWith+      clicked = leftClicked || pending == wid+  pure $! Response wid rect hovered clicked False False held clickedWith++-- | Set the value of widget @wid@'s node, added this frame: a checkbox+-- showing the click read after it was added.+setWidgetValue :: Context -> WidgetId -> Float -> IO ()+setWidgetValue ctx wid v = withWidgetNode ctx wid () (\i -> setNodeValue (ctxNodeArena ctx) i v)++-- | Move a group's selection, which its members' values mark, from member+-- @old@ to member @new@. The members were added with @old@ selected, since the+-- click or key that moves it is read after them.+moveSelection :: Eq k => Context -> k -> k -> [(k, Response)] -> IO ()+moveSelection ctx old new members =+  unless (old == new) $ forM_ members $ \(k, r) ->+    when (k == old || k == new) $ setWidgetValue ctx (rawRespId r) (if k == new then 1 else 0)++-- | Stamp the current container with a widget id (a radio or tree group key),+-- so store keys and damage requests under that id resolve to the container.+-- Containers are never hot, so the id does not make it hoverable.+tagContainer :: WidgetId -> NanoUI ()+tagContainer wid = do+  withContext $ \ctx -> do+    parent <- currentParent ctx+    when (parent >= 0) $ setWidgetId (ctxNodeArena ctx) parent wid
+ lib/NanoUI/Internal/Widgets/NumericInput.hs view
@@ -0,0 +1,285 @@+-- | Numeric field: a text field that only accepts numbers, with an up / down+-- stepper, arrow-key steps, and an optional hexadecimal mode.+module NanoUI.Internal.Widgets.NumericInput+  ( NumericInputConfig (..)+  , defaultNumericInputConfig+  , numericInput+  , numericInput'+  , numericInputConfigured+  , numericInputConfigured'+  , numericInputCore+  )+where++import Control.Monad (mfilter, void, when)+import Data.Bits ((.|.))+import Data.Char (isDigit, isHexDigit)+import Data.Maybe (fromMaybe)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, smallArrayFromList)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Read qualified as TR+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.Context (getStore, intKey, requestWakeAt, modifyStore)+import NanoUI.Internal.Equality (sameDouble)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askInput, freshWidget, liftIO)+import NanoUI.Internal.Store (deleteSpec, fieldDouble, fieldText, findSlot, findSpec, insertSlot, insertSpec, lookupSlot, memberSpec)+import NanoUI.Internal.Store.Slots (slotNumericHeld, slotNumericRepeat, slotTextChanged, slotTextMode)+import NanoUI.Internal.Style (Layout (..), LayoutModifier, Sizing (..), defaultLayout)+import NanoUI.Internal.Types (Rect (..), clamp, rectContains)+import NanoUI.Internal.WidgetText (numericStepperRects, packTextNodeStyle, textInputFlagNumeric)+import NanoUI.Internal.Widgets.Combinators (widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response, addWidgetStyled, respHovered, respRect, setChanged, setSubmitted)+import NanoUI.Widgets.TextEditor (singleLineMode)+import NanoUI.Internal.Widgets.TextInput (TextInputState (..), editTextInput, editorTextState, focusAndIme, loadTextInputState, saveTextEditor, saveTextInputState)+import NanoUI.Internal.Var (Binding (..), bindVarBy)+import NanoUI.Internal.Var.Types (Var)+import Numeric (showFFloat, showHex)++-- | How a numeric field reads, shows, and steps its value.+data NumericInputConfig = NumericInputConfig+  { nicMin :: !Double+    -- ^ Smallest value (default: no limit).+  , nicMax :: !Double+    -- ^ Largest value (default: no limit).+  , nicStep :: !Double+    -- ^ What one arrow key or stepper click adds (default 1). Shift steps ten+    -- times as far. A step is rounded to 'nicDecimals' places, so those must+    -- show it: a step of 0.1 needs at least one decimal.+  , nicDecimals :: !Int+    -- ^ Digits after the decimal point, both shown and accepted (default 0).+  , nicHex :: !Bool+    -- ^ Show and accept the value as a whole hexadecimal number (default+    -- 'False'). 'nicDecimals' is ignored in this mode.+  , nicLayout :: !LayoutModifier+    -- ^ Layout modifier applied on top of the default numeric layout (grows to+    -- fill, at least 80 wide).+  }++-- | Unbounded decimal range, integer display, step 1, and an 80-pixel minimum width.+defaultNumericInputConfig :: NumericInputConfig+defaultNumericInputConfig =+  NumericInputConfig+    { nicMin = -1 / 0+    , nicMax = 1 / 0+    , nicStep = 1+    , nicDecimals = 0+    , nicHex = False+    , nicLayout = id+    }++-- | Numeric field over whole numbers bound to mutable state ('Var'): typing,+-- arrow keys and stepper clicks mutate it in place.+--+-- Only digits, and a leading minus sign when the range reaches below zero, can+-- be typed. Up and Down step the value, Shift steps ten times as far, and+-- holding a stepper arrow repeats. Enter, a step, or leaving the field rewrites+-- the text as the value, clamped to the range. A value written to the Var+-- while the field is focused replaces the text being typed.+{-# INLINE numericInput #-}+numericInput :: Var Double -> NanoUI ()+numericInput v = void (numericInputConfigured' defaultNumericInputConfig v)++-- | 'numericInput' returning its 'Response'.+{-# INLINE numericInput' #-}+numericInput' :: Var Double -> NanoUI Response+numericInput' = numericInputConfigured' defaultNumericInputConfig++-- | 'numericInput' with a range, a step, decimal places, hexadecimal mode, or+-- its own layout.+--+-- > numericInputConfigured defaultNumericInputConfig {nicMin = 0, nicMax = 255, nicHex = True} byte+{-# INLINE numericInputConfigured #-}+numericInputConfigured :: NumericInputConfig -> Var Double -> NanoUI ()+numericInputConfigured cfg v = void (numericInputConfigured' cfg v)++-- | 'numericInputConfigured' returning its 'Response'.+{-# INLINE numericInputConfigured' #-}+numericInputConfigured' :: NumericInputConfig -> Var Double -> NanoUI Response+numericInputConfigured' cfg v = bindVarBy sameDouble RenderFinal v (numericInputCore cfg)++numericBaseLayout :: Layout+numericBaseLayout = defaultLayout {layoutWidth = Grow 1, layoutMinW = 80}++-- | Preformatted decimal strings for common small non-negative integers so+-- idle numeric fields (such as colour-picker channels) allocate nothing.+smallIntTexts :: SmallArray Text+smallIntTexts = smallArrayFromList [T.pack (show i) | i <- [0 .. 512 :: Int]]++-- | 'numericInputConfigured' on a plain value: the response and the value+-- after this frame.+numericInputCore :: NumericInputConfig -> Double -> NanoUI (Response, Double)+numericInputCore cfg value = do+  (wid, ctx) <- freshWidget+  inp <- askInput+  -- Hex input needs letters, so it gets the normal text keyboard.+  isFocus <- focusAndIme ctx wid True (if nicHex cfg then InputNormal else InputNumeric)+  store <- liftIO (getStore ctx)+  let+    !key = intKey wid+    !given = clampNumber cfg value+    stored = lookupSlot fieldText key store+    !held0 = findSpec slotNumericHeld 0 key store+    !repeatAt0 = findSpec slotNumericRepeat 0 key store+  lay <- widgetBaseLayout numericBaseLayout (nicLayout cfg)+  -- Its font face, weight and slant ride in the style bits, as on a label.+  resp <- addWidgetStyled wid NodeTextInput "" 0 lay (textInputFlagNumeric .|. packTextNodeStyle lay 0)+  if not isFocus+    && held0 == 0+    && repeatAt0 == 0+    && not (pressedIn MouseLeft inp)+    && lookupSlot fieldDouble key store == Just given+    && not (memberSpec slotTextChanged key store)+    && stored == Just (formatNumber cfg given)+    then pure (setChanged (given /= value) resp, given)+    else do+      let+        -- A value other than the last one the field returned was set by the+        -- caller, and replaces the text even while the field is focused.+        adopted = isFocus && maybe False (/= given) (lookupSlot fieldDouble key store)+        -- Unfocused, the field shows the caller's value; focused, it keeps the+        -- text being typed.+        -- Stored text that fails 'acceptsNumberText' (pasted from the context+        -- menu, which skips the filter) is replaced so subsequent edits are not+        -- rejected.+        text0 = if isFocus && not adopted then fromMaybe (formatNumber cfg given) (mfilter (acceptsNumberText cfg) stored) else formatNumber cfg given+        s0 = loadTextInputState store key text0+        lastValue = if adopted then given else findSlot fieldDouble given key store+      mEdited <- if isFocus then liftIO (editTextInput ctx singleLineMode inp store key s0) else pure Nothing+      let+        -- An edit that would leave text no number can start with is dropped.+        typed = maybe s0 editorTextState mEdited+        s1 = if acceptsNumberText cfg (tisText typed) then typed else s0+        current+          -- Text that still reads as the last value formatted is that value,+          -- which can hold more precision than the text shows.+          | isFocus && tisText s1 == formatNumber cfg lastValue = lastValue+          | isFocus = maybe lastValue (clampNumber cfg) (parseNumber cfg (tisText s1))+          | otherwise = given+      (dir, held1, repeatAt1) <- liftIO (stepNumericStepper resp isFocus inp held0 repeatAt0)+      let+        scale = if modShift (inputModifiers inp) then 10 else 1+        final+          | dir /= 0 = clampNumber cfg (roundNumber cfg (current + fromIntegral dir * scale * nicStep cfg))+          | otherwise = current+        submitted = isFocus && pressedOnceIn KeyEnter inp+        -- A step or Enter rewrites the text as the value, caret at its end.+        s2+          | dir /= 0 || submitted =+              let t = formatNumber cfg final+               in TextInputState t (T.length t) (T.length t)+          | otherwise = s1+        dirty =+          stored /= Just (tisText s2)+            || s2 /= s0+            || lookupSlot fieldDouble key store /= Just final+            || held1 /= held0+            || repeatAt1 /= repeatAt0+            || memberSpec slotTextChanged key store+      when dirty $+        liftIO $ do+          -- An accepted edit keeps its undo history; a rejected one or a step+          -- rewrites the text without it.+          let save = case mEdited of+                Just ed | editorTextState ed == s2 -> saveTextEditor key ed+                _ -> saveTextInputState key s2+          -- Commands sent between frames read the mode ('runTextCommand'); the+          -- change pulse an edit of theirs leaves is reported as the value's+          -- change.+          modifyStore ctx $+            (if held1 == 0 then deleteSpec slotNumericHeld key else insertSpec slotNumericHeld key held1)+              . insertSlot fieldDouble key final+              . insertSpec slotNumericRepeat key repeatAt1+              . insertSpec slotTextMode key singleLineMode+              . deleteSpec slotTextChanged key+              . save+      -- A held arrow repeats on a schedule: ask for the frame of its next step+      -- instead of running frames back to back until then.+      when (held1 /= 0) $ liftIO (requestWakeAt ctx repeatAt1)+      pure (setSubmitted submitted (setChanged (final /= value) resp), final)++-- | Step the stepper arrows' press, auto-repeat timer, and Up/Down keys,+-- returning @(stepDir, heldDir, nextRepeatAt)@.+stepNumericStepper :: Response -> Bool -> Input -> Int -> Double -> IO (Int, Int, Double)+stepNumericStepper resp isFocus inp held0 repeatAt0 = do+  let Rect rx ry rw rh = respRect resp+      (upRect, downRect) = numericStepperRects rx ry rw rh+      mouse = inputMousePos inp+      over r d = if respHovered resp && rectContains r mouse then d else 0+      pressDir+        | pressedIn MouseLeft inp = over upRect 1 + over downRect (-1)+        | otherwise = 0+      holding =+        held0 /= 0+          && heldIn MouseLeft inp+          && over (if held0 > 0 then upRect else downRect) held0 /= 0+      keyDir+        | not isFocus = 0+        | pressedIn KeyUp inp = 1+        | pressedIn KeyDown inp = -1+        | otherwise = 0+  now <- if pressDir /= 0 || holding then getMonotonicTime else pure 0+  let step+        | pressDir /= 0 = (pressDir, pressDir, now + 0.4)+        | holding && now >= repeatAt0 = (held0, held0, now + 0.06)+        | holding = (keyDir, held0, repeatAt0)+        | otherwise = (keyDir, 0, 0)+  pure step++clampNumber :: NumericInputConfig -> Double -> Double+clampNumber cfg = clamp (nicMin cfg) (nicMax cfg)++roundNumber :: NumericInputConfig -> Double -> Double+roundNumber cfg v+  | nicHex cfg || nicDecimals cfg <= 0 = fromInteger (round v)+  | otherwise = fromInteger (round (v * scale)) / scale+  where+    scale = 10 ^ nicDecimals cfg++formatNumber :: NumericInputConfig -> Double -> Text+formatNumber cfg v0+  -- NaN and infinity format as empty text because their string representations+  -- fail 'acceptsNumberText'.+  | isNaN v0 || isInfinite v0 = T.empty+  | nicHex cfg =+      let n = round v :: Integer+       in (if n < 0 then "-" else "") <> T.toUpper (T.pack (showHex (abs n) ""))+  | nicDecimals cfg <= 0 =+      let n = round v :: Integer+       in if n >= 0 && n <= 512+            then indexSmallArray smallIntTexts (fromInteger n)+            else T.pack (show n)+  | otherwise = T.pack (showFFloat (Just (nicDecimals cfg)) v "")+  where+    -- Normalize -0.0 to +0.0 so a non-negative field does not format "-0.00"+    -- and reject it.+    v = v0 + 0++-- | Whether @t@ can stand in the field mid-edit: an optional minus sign when+-- the range reaches below zero, then digits (hexadecimal ones in hex mode),+-- and with decimal places, one point followed by at most that many digits.+acceptsNumberText :: NumericInputConfig -> Text -> Bool+acceptsNumberText cfg t =+  signOk && case T.splitOn "." body of+    [whole] -> T.all digit whole+    [whole, frac] -> decimals > 0 && T.all isDigit whole && T.all isDigit frac && T.length frac <= decimals+    _ -> False+  where+    (negative, body) = maybe (False, t) ((,) True) (T.stripPrefix "-" t)+    signOk = not negative || nicMin cfg < 0+    digit = if nicHex cfg then isHexDigit else isDigit+    decimals = if nicHex cfg then 0 else nicDecimals cfg++parseNumber :: NumericInputConfig -> Text -> Maybe Double+parseNumber cfg t+  | nicHex cfg = case TR.signed TR.hexadecimal t of+      Right (n, rest) | T.null rest -> Just (fromInteger n)+      _ -> Nothing+  | otherwise = case TR.signed (TR.rational . leadingZero) (T.dropWhileEnd (== '.') t) of+      Right (v, rest) | T.null rest -> Just v+      _ -> Nothing+  where+    -- 'TR.rational' needs a digit before the point, which ".5" leaves out.+    leadingZero s = if "." `T.isPrefixOf` s then "0" <> s else s
+ lib/NanoUI/Internal/Widgets/Overlay.hs view
@@ -0,0 +1,225 @@+-- | Modal dialogs and panels, and floating in-app windows.+module NanoUI.Internal.Widgets.Overlay+  ( modal+  , modal'+  , modalWith+  , modalWith'+  , modalPanel+  , modalPanel'+  , modalPanelWith+  , modalPanelWith'+  , floatingWindow+  , floatingWindow'+  , floatingWindowWith+  , floatingWindowWith'+  , windowTitleBarH+  , windowChromeSepH+  )+where++import Control.Monad (unless, void, when)+import Data.Bits ((.|.))+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Context+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (NodeType (..), addNodeFromLayout)+import NanoUI.Internal.Monad+import NanoUI.Internal.Style+import NanoUI.Internal.Types (Rect (..), Size (..), clamp)+import NanoUI.Internal.WidgetText (buttonCloseTrailing, buttonFlagClose)+import NanoUI.Internal.Widgets.Combinators (buttonStyledEx)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Popup (bindOpen, floatingOverlay)+import NanoUI.Internal.Widgets.Layout hiding (panel)+import NanoUI.Internal.Widgets.Node++-- | A window's chrome above its body: the title bar, the 10px above it and+-- the rule under it, which the frame paints ('windowChromeSepH').+windowTitleBarH :: Float+windowTitleBarH = 28 + 10 + windowChromeSepH++windowChromeSepH :: Float+windowChromeSepH = 1++-- | A modal dialog with a title bar, shown while the Var holds 'True',+-- blocking interaction with the content behind it. Escape, a click outside+-- or its close button write 'False', so it closes in the same frame:+--+-- > asking <- useVar False+-- > whenM (button "Delete...") (writeVar asking True)+-- > modal asking "Delete the file?" $ do+-- >   whenM (button "Delete") (deleteFile >> writeVar asking False)+--+-- For an open flag derived from other state, or a dialog that must not+-- close until answered, pass a constant and act on the response from+-- 'modal''.+--+-- Open a dialog from a modal by declaring it inside that modal's body:+-- Escape, or a click on the outer modal, then closes only the inner one.+-- Modals declared side by side close in declaration order: Escape closes+-- the first even when the second is on top, and so does a click on the+-- second outside the first.+modal :: Var Bool -> Text -> NanoUI () -> NanoUI ()+modal open title body = void (modalWith' id open title body)++-- | 'modal' returning the body's result while open, and a 'Response' that+-- reports a close request as a click.+modal' :: Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)+modal' = modalWith' id++-- | 'modal' with a layout modifier for its panel, which by default fits its+-- body. The title bar, the rule under it and the padding are the panel's+-- own. A panel given a fixed height holds its body rather than scrolling it,+-- and the body fills what the title bar leaves, so a body laid out with+-- @fillW . fillH@ takes exactly the panel's inside:+--+-- > winW <- windowWidth+-- > winH <- windowHeight+-- > modalWith (fixedWH (winW - 40) (winH - 40)) open "Find" $+-- >   columnWith (fillW . fillH) body+--+-- A panel is never larger than the window, less the margin every floating+-- panel keeps from its edge.+modalWith :: (Layout -> Layout) -> Var Bool -> Text -> NanoUI () -> NanoUI ()+modalWith f open title body = void (modalWith' f open title body)++-- | 'modalWith' returning the body's result and the 'Response'.+modalWith' :: (Layout -> Layout) -> Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)+modalWith' f open title body = bindOpen open (\shown -> overlay True True f shown title body)++-- | A modal panel without a title bar, close button or surrounding padding.+-- The panel surface and modal backdrop remain; Escape or a click outside+-- writes 'False'.+modalPanel :: Var Bool -> NanoUI () -> NanoUI ()+modalPanel = modalPanelWith id++-- | 'modalPanel' returning the body's result and the 'Response'.+modalPanel' :: Var Bool -> NanoUI a -> NanoUI (Response, Maybe a)+modalPanel' = modalPanelWith' id++-- | 'modalPanel' with a layout modifier for its panel. A fixed-size panel's+-- body fills the panel, so a body laid out with @fillW . fillH@ takes exactly+-- the panel's inside. Use a small amount of padding only when the body should+-- sit clear of the panel's border.+modalPanelWith :: (Layout -> Layout) -> Var Bool -> NanoUI () -> NanoUI ()+modalPanelWith shape open body = void (modalPanelWith' shape open body)++-- | 'modalPanelWith' returning the body's result and the 'Response'.+modalPanelWith' :: (Layout -> Layout) -> Var Bool -> NanoUI a -> NanoUI (Response, Maybe a)+modalPanelWith' shape open body = bindOpen open (\shown -> overlay True False shape shown "" body)++-- | A draggable, resizable in-app floating window with a scrolling body, shown+-- while the Var holds 'True'. Its close button writes 'False'. Other windows+-- and the page remain interactive outside its bounds.+floatingWindow :: Var Bool -> Text -> NanoUI () -> NanoUI ()+floatingWindow = floatingWindowWith id++-- | 'floatingWindow' returning the body's result while open, and a 'Response'+-- that reports a close request as a click.+floatingWindow' :: Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)+floatingWindow' = floatingWindowWith' id++-- | 'floatingWindow' with a layout modifier for its panel (for example,+-- 'fixedWH' or 'minW').+floatingWindowWith :: LayoutModifier -> Var Bool -> Text -> NanoUI () -> NanoUI ()+floatingWindowWith f open title body = void (floatingWindowWith' f open title body)++-- | 'floatingWindowWith' returning the body's result and the 'Response'.+floatingWindowWith' :: LayoutModifier -> Var Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)+floatingWindowWith' f open title body = bindOpen open (\shown -> overlay False True f shown title body)++overlay ::+  Bool -> Bool -> (Layout -> Layout) -> Bool -> Text -> NanoUI a -> NanoUI (Response, Maybe a)+overlay isModal hasChrome shape open title child = do+  ctx <- askContext+  inp <- askInput+  let+    Size winW winH = inputWindowSize inp+    margin = windowMargin+    availW = max 1 (winW - 2 * margin)+    availH = max 1 (winH - 2 * margin)+    -- Chrome-bearing modals share the window's side padding. The body's+    -- scrollbar sits out in it just inside the panel's edge, that padding+    -- from the content. A bare modal panel has no padding of its own.+    padding+      | not hasChrome = Padding 0 0 0 0+      | isModal = windowPad {padB = 12}+      | otherwise = windowPad+    barH+      | not hasChrome = 0+      | isModal = 40+      | otherwise = windowTitleBarH+    -- Windows keep a side-pad between the chrome and the body. Standard+    -- modals keep their larger gap; a bare modal panel has none.+    bodyGap+      | not hasChrome = 0+      | isModal = 8+      | otherwise = 10+    minWidth = clamp 1 availW (if isModal then 260 else 280)+    minHeight =+      if isModal+        then 0+        else+          min availH (padT padding + windowTitleBarH + bodyGap + padB padding)+    -- The panel's own layout, as the caller shapes it. Its sizes are held+    -- inside the window, whatever the caller asked for.+    panel =+      shape+        defaultLayout+          { layoutDirection = Column+          , layoutWidth = Fit+          , layoutHeight = Fit+          , layoutPadding = padding+          , layoutGap = bodyGap+          , layoutMinW = minWidth+          , layoutMinH = minHeight+          , layoutMaxW = availW+          , layoutMaxH = availH+          , layoutAlignX = AlignStart+          , layoutAlignY = AlignTop+          }+    within avail = \case+      Fixed v -> Fixed (min avail v)+      sz -> sz+    panelW = within availW (layoutWidth panel)+    panelH = within availH (layoutHeight panel)+    addOverlayNode _ parent =+      addNodeFromLayout+        (ctxNodeArena ctx)+        (if isModal then NodeModal else NodeWindow)+        parent+        panel+          { layoutWidth = panelW+          , layoutHeight = panelH+          , layoutMinW = min availW (layoutMinW panel)+          , layoutMinH = min availH (layoutMinH panel)+          , layoutMaxW = min availW (layoutMaxW panel)+          , layoutMaxH = min availH (layoutMaxH panel)+          }+    enter = when isModal (beginModal ctx)+    titleLayout =+      (fixedH barH . alignMiddle . tight) defaultLayout {layoutMinH = barH, layoutMaxH = barH}+  floatingOverlay open (if isModal then Just (Rect 0 0 0 0) else Nothing) addOverlayNode enter $ do+    closed <-+      if hasChrome+        then do+          close <-+            row' (tight . gap 6 . itemsCenter . fixedH barH . fillW $ defaultLayout) $ do+              unless (T.null title) $+                (if isModal then id else withKey title) (void (labelEx titleLayout title))+              flex+              withKey ("close" :: Text) $+                buttonStyledEx True "" 0 (tight . fixedWH 24 24 . alignMiddle $ defaultLayout) $+                  buttonFlagClose .|. buttonCloseTrailing+          when (isModal && not (T.null title)) separator+          pure (respClicked close)+        else pure False+    -- A panel of a fixed height holds its body, which fills what the title+    -- bar leaves when there is one; any other panel scrolls a body taller+    -- than the window.+    r <- case panelH of+      Fixed _ -> columnWith (tight . grow . fillW) child+      _ -> scrollWith (tight . grow) child+    when isModal (liftIO (endModal ctx))+    pure (closed, r)
+ lib/NanoUI/Internal/Widgets/Popup.hs view
@@ -0,0 +1,337 @@+-- | Anchored floating panels controlled by mutable state ('Var'), and tooltips.+module NanoUI.Internal.Widgets.Popup+  ( PopupAnchor (..)+  , PopupPlacement (..)+  , PopupConfig (..)+  , defaultPopupConfig+  , popup+  , popup'+  , popupWith+  , popupWith'+  , bindOpen+  , floatingOverlay+  , tooltipWidget+  , tooltipAt+  , tooltip+  , withTooltip+  , TooltipConfig (..)+  , defaultTooltipConfig+  , tooltipConfigured+  , tooltipWidgetConfigured+  )+where++import Control.Monad (void, when)+import Data.IntMap.Strict qualified as IM+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.Context+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Frame.Hit (findNodeByWidgetId)+import NanoUI.Internal.Layout.Arena (NodeIdx, NodeType (..), addNodeFromLayout)+import NanoUI.Internal.Monad+import NanoUI.Internal.Store (deleteSpec, findSpec, insertSpec)+import NanoUI.Internal.Store.Slots (slotTooltipShow)+import NanoUI.Internal.Style+import NanoUI.Internal.Tasks (holdAction)+import NanoUI.Internal.Types+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var, constVar)+import NanoUI.Internal.Widgets.Behavior (useDismissable)+import NanoUI.Internal.Widgets.Layout (label)+import NanoUI.Internal.Widgets.Node++-- | Anchor, preferred side, dismissal, and gap in logical pixels.+-- Anchors use logical window coordinates.+data PopupConfig = PopupConfig+  { popupAnchor :: !PopupAnchor+  , popupPlacement :: !PopupPlacement+  , popupDismissable :: !Bool+  -- ^ Close on Escape and on a press outside the panel and an 'AnchorRect'.+  , popupOffset :: !Float+  }+  deriving (Eq, Show)++-- | Automatic placement with a 4-pixel gap and dismissal enabled.+defaultPopupConfig :: PopupAnchor -> PopupConfig+defaultPopupConfig anchor =+  PopupConfig+    { popupAnchor = anchor+    , popupPlacement = PlacementAuto+    , popupDismissable = True+    , popupOffset = 4+    }++-- | A floating panel placed by the config, shown while the Var holds+-- 'True'. A dismissal (Escape or a click outside, when 'popupDismissable')+-- writes 'False', so the panel closes in the same frame. A press on an+-- 'AnchorRect' is not outside, so a button that toggles the Var on+-- 'respClicked' closes the popup rather than closing and reopening it. The+-- panel fits its body, however tall: for a body that could outgrow the+-- window, cap the panel through 'popupWith' ('NanoUI.maxH') and scroll the+-- body in a 'NanoUI.scrollWith' that 'NanoUI.grow's.+--+-- > filterOpen <- useVar False+-- > filterR <- button' "Filter"+-- > when (respClicked filterR) (modifyVar filterOpen not)+-- > popup filterOpen (defaultPopupConfig (AnchorRect (respRect filterR))) $ do+-- >   checkbox "Fruit" showFruit+--+-- For an open flag derived from other state, or one the caller may refuse+-- to clear, pass a constant and act on the response from 'popup'' instead.+popup :: Var Bool -> PopupConfig -> NanoUI () -> NanoUI ()+popup open cfg child = void (popupWith' open cfg id child)++-- | 'popup' returning the body's result while open, and a 'Response' that+-- reports a dismissal as a click.+popup' :: Var Bool -> PopupConfig -> NanoUI a -> NanoUI (Response, Maybe a)+popup' open cfg = popupWith' open cfg id++-- | 'popup' with a modifier applied to its tight default layout.+popupWith :: Var Bool -> PopupConfig -> (Layout -> Layout) -> NanoUI () -> NanoUI ()+popupWith open cfg f child = void (popupWith' open cfg f child)++-- | 'popupWith' returning the body's result and the 'Response'.+popupWith' :: Var Bool -> PopupConfig -> (Layout -> Layout) -> NanoUI a -> NanoUI (Response, Maybe a)+popupWith' open cfg f child = bindOpen open $ \shown -> do+  ctx <- askContext+  let -- The popup's padding and gap are defaults the caller's modifier can change.+      layout = f ((tight defaultLayout) {layoutPadding = Padding 6 6 6 6, layoutGap = 4})+      addPopupNode wid parent = do+        registerPopupConfig ctx wid (popupAnchor cfg) (popupPlacement cfg) (popupOffset cfg)+        addNodeFromLayout (ctxNodeArena ctx) NodePopup parent layout+      dismiss+        | not (popupDismissable cfg) = Nothing+        | AnchorRect r <- popupAnchor cfg = Just r+        | otherwise = Just (Rect 0 0 0 0)+  floatingOverlay shown dismiss addPopupNode (pure ()) ((,) False <$> child)++-- | Bind a floating panel's open state to a 'Var', mutating it to 'False' when+-- the panel reports a dismissal. Because the panel nodes were already emitted+-- before dismissal is resolved, closing triggers a re-render.+{-# INLINE bindOpen #-}+bindOpen :: Var Bool -> (Bool -> NanoUI (Response, Maybe a)) -> NanoUI (Response, Maybe a)+bindOpen v run = bindVar Conservative v $ \open -> do+  r <- run open+  let !keep = open && not (respClicked (fst r))+  pure (r, keep)++-- | The floating panel behind popups, modals and windows, shown while @open@+-- with its body in its own id scope. @addPanel@, given the panel's id, and+-- @enter@ are those of 'floatingPanel'. The body returns whether it closed+-- the panel along with its result. The 'Response' reports a dismissal (the+-- body's close, Escape, or a click outside when @dismiss@ is 'Just' the rect+-- of what opened the panel, where a press is not outside) as a click. A+-- closed panel still consumes its id scope, so the ids of later siblings do+-- not shift when it opens.+floatingOverlay ::+  Bool ->+  Maybe Rect ->+  (WidgetId -> Int -> IO NodeIdx) ->+  IO () ->+  NanoUI (Bool, a) ->+  NanoUI (Response, Maybe a)+floatingOverlay open dismiss addPanel enter body = do+  (wid, _) <- freshWidget+  if not open+    then do+      burstNextIds 1+      pure (mempty {rawRespId = wid}, Nothing)+    else do+      -- Hover uses the pointer routed to the panel's layer, so layers in+      -- front of the panel occlude hover.+      (mouse, (closed, r)) <-+        floatingPanel wid (addPanel wid) enter ((,) <$> uiMousePos <*> body)+      panel <- fromMaybe (Rect 0 0 0 0) <$> lastRect wid+      outside <- case dismiss of+        Just opener | rectNonEmpty panel -> useDismissable wid panel opener+        _ -> pure False+      let dismissed = closed || outside+      pure+        ( mkResponse wid panel (rectContains panel mouse) dismissed dismissed+        , Just r+        )++-- | When a tooltip opens, and where.+data TooltipConfig = TooltipConfig+  { tooltipDelay :: !Double+  -- ^ Seconds the pointer must rest on the target before the tooltip+  -- opens; 0 opens it at once. Moving within the target does not restart it.+  , tooltipGrace :: !Double+  -- ^ Seconds after the last tooltip closed during which this one skips its+  -- delay, so the pointer can sweep along a toolbar reading each tooltip.+  , tooltipPlacement :: !PopupPlacement+  -- ^ The side of the target to open on. 'PlacementAtCursor' instead puts+  -- it below the pointer (above if there is no room) and follows it.+  , tooltipGap :: !Float+  -- ^ Logical pixels between the tooltip and its target or the pointer.+  }+  deriving (Eq, Show)++-- | 4 pixels below the target, after a 0.5 s rest, or at once within 0.3 s+-- of another tooltip.+defaultTooltipConfig :: TooltipConfig+defaultTooltipConfig =+  TooltipConfig+    { tooltipDelay = 0.5+    , tooltipGrace = 0.3+    , tooltipPlacement = PlacementBelow+    , tooltipGap = 4+    }++-- | Attach a rich tooltip widget to any target response, shown once the+-- pointer rests on it ('defaultTooltipConfig').+tooltipWidget ::+  HasResponse r =>+  r ->+  NanoUI () ->+  NanoUI ()+tooltipWidget = tooltipWidgetConfigured defaultTooltipConfig++-- | 'tooltipWidget' with a configured delay, placement and gap. The target+-- counts as hovered when the routed pointer is on its visible, uncovered+-- part ('pointerOnWidget'), even when disabled or inert.+tooltipWidgetConfigured ::+  HasResponse r =>+  TooltipConfig ->+  r ->+  NanoUI () ->+  NanoUI ()+tooltipWidgetConfigured cfg target child = do+  -- The id 'popup' takes next; the timer is keyed on it to avoid using a+  -- sibling id.+  wid <- currentId+  ctx <- askContext+  frame <- askFrameInput+  routed <- inputMousePos <$> askInput+  let V2 mx my = inputMousePos frame+      follow = tooltipPlacement cfg == PlacementAtCursor+      rect = respRect target+      tid = respId target+  hovered <-+    if rectContains rect routed+      then liftIO (findNodeByWidgetId ctx tid >>= \mIdx -> pointerOnWidget ctx mIdx tid rect routed)+      else pure False+  (open, armed) <- liftIO (tooltipTimer ctx cfg (intKey wid) hovered frame)+  -- Request a frame when the pointer enters or leaves the target, even a+  -- label or container, and on every move while a following tooltip is open.+  liftIO (registerHoverZone ctx (open && follow) rect)+  let (anchor, placement)+        | follow = (AnchorRect (Rect mx my 0 pointerClearance), PlacementBelow)+        | otherwise = (AnchorRect rect, tooltipPlacement cfg)+  void $+    popupWith'+      (constVar open)+      ((defaultPopupConfig anchor) {popupPlacement = placement, popupDismissable = False, popupOffset = tooltipGap cfg})+      (pointer PointerPass)+      (inertView child)+  -- Clear the stored timestamp when a tooltip is no longer declared+  -- ('holdAction'), so if it reappears later it waits for the full delay+  -- rather than opening immediately or ending other tooltips' delays. The+  -- hook consumes one id on both branches.+  if armed+    then scope (holdAction (modifyStore ctx (deleteSpec slotTooltipShow (intKey wid))))+    else burstNextIds 1++-- | Offset below the pointer's hot spot for a following tooltip, before the+-- gap: roughly an arrow cursor's height, so the cursor does not cover it.+pointerClearance :: Float+pointerClearance = 16++-- | Whether the tooltip with store key @k@ is open this frame, and whether it+-- keeps a time (waits or shows) for the next frame. The delay+-- starts when the target becomes @hovered@ and ends after 'tooltipDelay', or+-- at once within 'tooltipGrace' of the last tooltip closing. A held button+-- keeps the tooltip shut and restarts the delay on release; a wheel turn+-- restarts it. Both also end the grace period.+--+-- The times live in quiet store slots, which neither damage nor wake.+-- Opening and closing repaint as a floating panel, and the opening frame is+-- scheduled with 'requestWakeAt', so an idle app draws nothing while waiting.+tooltipTimer :: Context -> TooltipConfig -> Int -> Bool -> Input -> IO (Bool, Bool)+tooltipTimer ctx cfg k hovered inp = do+  store <- getStore ctx+  let showAt0 = findSpec slotTooltipShow 0 k store+      lastUp0 = findSpec slotTooltipShow 0 0 store+      held = inputPointerHeld inp+      interrupted = anyButtonPressed inp || inputScroll inp /= V2 0 0+  -- Fast path: most targets are not near the pointer.+  if not hovered && showAt0 == 0 && (lastUp0 == 0 || not interrupted)+    then pure (False, False)+    else do+      now <- getMonotonicTime+      let micros t = round (t * 1e6) :: Int+          nowUs = micros now+          delayUs = micros (max 0 (tooltipDelay cfg))+          graceUs = micros (tooltipGrace cfg)+          -- No frames run while a tooltip sits open, so the closing frame+          -- counts as the last one it was up.+          wasUp = showAt0 > 0 && nowUs >= showAt0+          starting = hovered && not held && not interrupted && showAt0 == 0+          -- A tooltip open last frame whose call comes after this one has+          -- not yet recorded closing.+          otherUp = any (\k' -> k' /= k && findSpec slotTooltipShow 0 k' store > 0) . IM.keys+      warm <-+        if not starting || graceUs <= 0 || lastUp0 == 0+          then pure False+          else (nowUs - lastUp0 < graceUs ||) . otherUp <$> getsOverlay ctx osPrevFloatingRects+      let showAt+            | not hovered || held = 0+            | interrupted = nowUs + delayUs+            | showAt0 > 0 = showAt0+            | warm = nowUs+            | otherwise = nowUs + delayUs+          open = showAt > 0 && nowUs >= showAt+          lastUp+            | interrupted = 0+            | open || wasUp = nowUs+            | otherwise = lastUp0+          set key v = if v > 0 then insertSpec slotTooltipShow key v else deleteSpec slotTooltipShow key+      when (showAt /= showAt0 || lastUp /= lastUp0) $+        modifyStore ctx (set k showAt . set 0 lastUp)+      when (showAt > 0 && not open) $+        requestWakeAt ctx (fromIntegral showAt / 1e6)+      pure (open, showAt > 0)++-- | Attach a rich tooltip widget to an inner UI computation.+withTooltip ::+  NanoUI a ->+  NanoUI () ->+  NanoUI a+withTooltip mainChild tipChild = do+  (res, contResp) <- mouseArea id mainChild+  res <$ tooltipWidget contResp tipChild++-- | 'tooltip' with a placement. 'PlacementAtCursor' follows the pointer.+tooltipAt ::+  HasResponse r =>+  PopupPlacement ->+  r ->+  Text ->+  NanoUI ()+tooltipAt placement = tooltipConfigured defaultTooltipConfig {tooltipPlacement = placement}++-- | 'tooltip' with a configured delay and placement.+--+-- > tooltipConfigured defaultTooltipConfig {tooltipPlacement = PlacementAtCursor} swatch name+tooltipConfigured ::+  HasResponse r =>+  TooltipConfig ->+  r ->+  Text ->+  NanoUI ()+tooltipConfigured cfg target txt = void (tooltipWidgetConfigured cfg target (label txt))++-- | Text shown below a widget after the pointer rests on it for half a+-- second, until it leaves or a button is pressed ('defaultTooltipConfig').+--+-- > save <- button' "Save"+-- > tooltip save "Write the file to disk"+tooltip ::+  HasResponse r =>+  r ->+  Text ->+  NanoUI ()+tooltip = tooltipConfigured defaultTooltipConfig
+ lib/NanoUI/Internal/Widgets/Radio.hs view
@@ -0,0 +1,104 @@+-- | Controlled radio groups over zero-based option indices or bounded enum+-- values. Each option is a button in the choice look ('buttonFlagChoice').+module NanoUI.Internal.Widgets.Radio+  ( radio+  , radio'+  , enumRadioBy+  , enumRadioBy'+  , enumRadio+  , enumRadio'+  )+where++import Control.Monad (void, zipWithM)+import Data.List (findIndex)+import Data.Maybe (fromMaybe, isNothing)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Context (adoptSlot, registerFocusable)+import NanoUI.Internal.Store (fieldInt)+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, freshWidget, nextId, scope, liftIO)+import NanoUI.Internal.Style (Layout, defaultLayout, fillW, gap, tight)+import NanoUI.Internal.Types (clamp)+import NanoUI.Internal.WidgetText (buttonFlagChoice)+import NanoUI.Internal.Widgets.Behavior (KeyNav (..), useKeyNav)+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Combinators (bindEnumPicker, finishInput, nonEmptyOpts, widgetBaseLayout)+import NanoUI.Internal.Widgets.Layout (column')+import NanoUI.Internal.Widgets.Node (Response (..), addWidgetStyled, moveSelection, setChanged, tagContainer)++radioLay :: Layout+radioLay = tight (fillW defaultLayout)++radioGroupLay :: Layout+radioGroupLay = tight (gap 4 (fillW defaultLayout))++-- | A column of radio buttons over @options@ in fold order, bound to mutable+-- state ('Var'): a click or the arrow keys update the zero-based selected index.+{-# INLINE radio #-}+radio :: Foldable f => f Text -> Var Int -> NanoUI ()+radio options = void . radio' options++-- | 'radio' returning the group's 'Response'.+{-# INLINE radio' #-}+radio' :: Foldable f => f Text -> Var Int -> NanoUI Response+radio' options v = bindVar RenderFinal v (radioCore options)++-- | 'radio' on a plain index: the response and the index after this frame.+radioCore ::+  Foldable f => f Text -> Int -> NanoUI (Response, Int)+radioCore options index =+  -- A positional scope: groups declared side by side keep separate ids.+  scope $ do+    (gid, ctx) <- freshWidget+    itemLay <- widgetBaseLayout radioLay id+    let opts = nonEmptyOpts options+        !len = length opts+        !given = clamp 0 (len - 1) index+    stored <- liftIO $ adoptSlot fieldInt ctx gid given+    let !sel = clamp 0 (len - 1) stored+    liftIO $ registerFocusable ctx gid+    nav <- useKeyNav gid+    let !navDelta = fromEnum (knDown nav || knRight nav) - fromEnum (knUp nav || knLeft nav)+        !selNav = clamp 0 (len - 1) (sel + navDelta)+        option i txt = do+          wid <- nextId+          -- Visual style 1 draws a ring.+          addWidgetStyled wid NodeButton txt (if selNav == i then 1 else 0) itemLay (buttonFlagChoice + 1)+    column' radioGroupLay $ do+      tagContainer gid+      resps <- zipWithM option [0 ..] opts+      let clicked = findIndex rawRespClicked resps+          final = fromMaybe selNav clicked+      liftIO (moveSelection ctx selNav final (zip [0 ..] resps))+      -- Compare with the caller's index, as 'NanoUI.Internal.Widgets.Select' does, so a+      -- selection stored between frames still reports a change. An index the+      -- options do not reach yet stays the caller's until the user picks,+      -- even the option it shows.+      (resp, s) <- finishInput fieldInt ctx gid given (mconcat resps) final+      pure $+        if isNothing clicked && navDelta == 0 && s == given+          then (resp, index)+          else (setChanged (s /= index) resp, s)++-- | Radio buttons for every value of a bounded enum, labeled by @encode@.+{-# INLINE enumRadioBy #-}+enumRadioBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()+enumRadioBy encode = void . enumRadioBy' encode++-- | 'enumRadioBy' returning the group's 'Response'.+{-# INLINE enumRadioBy' #-}+enumRadioBy' :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI Response+enumRadioBy' = bindEnumPicker radioCore++-- | 'enumRadioBy' labeled with 'show'.+{-# INLINE enumRadio #-}+enumRadio :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()+enumRadio = enumRadioBy (T.pack . show)++-- | 'enumRadio' returning the group's 'Response'.+{-# INLINE enumRadio' #-}+enumRadio' :: (Bounded a, Enum a, Show a) => Var a -> NanoUI Response+enumRadio' = enumRadioBy' (T.pack . show)
+ lib/NanoUI/Internal/Widgets/Select.hs view
@@ -0,0 +1,202 @@+-- | Dropdown select.+module NanoUI.Internal.Widgets.Select+  ( select+  , select'+  , selectWith+  , selectWith'+  , enumSelectBy+  , enumSelectBy'+  , enumSelect+  , enumSelect'+  , dropdownPopup+  , paintDropdownRows+  )+where++import Control.Monad (forM_, join, mfilter, unless, void, when)+import Data.Hashable (hash)+import Data.IORef (writeIORef)+import Data.Maybe (isJust, isNothing)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Canvas (CanvasM, drawRect, drawRoundedRect, drawText, runCanvasFor)+import NanoUI.Internal.Context+import NanoUI.Internal.Font (FontMetrics (..), centeredTextY, menuItemRowH, menuOuterPad)+import NanoUI.Internal.Frame.Select (DropdownRow (..), dropdownPopupRows, dropdownVisibleRows, selectRowAt)+import NanoUI.Internal.Frame.Hit (findNodeByWidgetId)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input (Input, MouseButton (..), Pressable (..), UiCursorKind (..), inputMousePos, inputWindowSize)+import NanoUI.Internal.Layout.Arena (NodeType (..), addNodeFromLayout)+import NanoUI.Internal.Monad (NanoUI, (<&&>), askContext, askInput, freshWidget, liftIO, nextId)+import NanoUI.Internal.Store (fieldInt, insertSlot)+import NanoUI.Internal.Style (AlignX (..), AlignY (..), Layout (..), Theme (..), defaultLayout, fillW, fixedH, tight)+import NanoUI.Internal.Types (Rect (..), Size (..), V2 (..), clamp, rectIntersect)+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Combinators (bindEnumPicker, nonEmptyOpts, widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response, addWidget, addWidgetWithOptions, dropdownBodyInput, inDropdownScope, pointerOnWidget, respRect, setChanged)+import NanoUI.Internal.Widgets.Popup (floatingOverlay)++-- | Dropdown over @options@ in fold order, bound to mutable state ('Var')+-- holding the zero-based selected index.+{-# INLINE select #-}+select :: Foldable f => f Text -> Var Int -> NanoUI ()+select options = void . select' options++-- | 'select' returning its 'Response'.+{-# INLINE select' #-}+select' :: Foldable f => f Text -> Var Int -> NanoUI Response+select' = selectWith' id++-- | 'select' with a layout modifier.+{-# INLINE selectWith #-}+selectWith :: Foldable f => (Layout -> Layout) -> f Text -> Var Int -> NanoUI ()+selectWith f options = void . selectWith' f options++-- | 'selectWith' returning its 'Response'.+{-# INLINE selectWith' #-}+selectWith' :: Foldable f => (Layout -> Layout) -> f Text -> Var Int -> NanoUI Response+selectWith' f options v = bindVar RenderFinal v (selectCore f options)++-- | 'selectWith' on a plain index: the response and the index after this+-- frame's pick.+selectCore ::+  Foldable f =>+  (Layout -> Layout) ->+  f Text ->+  Int ->+  NanoUI (Response, Int)+selectCore f options index = do+  (wid, ctx) <- freshWidget+  liftIO $ registerFocusable ctx wid+  let opts = nonEmptyOpts options+      n = length opts+      key = intKey wid+  -- The store holds the caller's index until a pick replaces it, even one+  -- the options do not reach: a pick of the option it shows is a change.+  stored <- liftIO $ adoptSlot fieldInt ctx wid index+  store0 <- liftIO (getStore ctx)+  let current = clamp 0 (n - 1) stored+      open = isSelectOpen store0 key+  lay <- widgetBaseLayout defaultLayout f+  resp <- addWidgetWithOptions wid NodeSelect "" opts 0 lay+  inp <- askInput+  let rect = respRect resp+  -- Ignore presses where layers or a pinned node cover the widget, or where+  -- it is scrolled out of its viewport. The press that opens the dropdown+  -- shows it in the same pass.+  pressed <-+    liftIO $+      pure (pressedIn MouseLeft inp)+        <&&> (findNodeByWidgetId ctx wid >>= \mIdx -> pointerOnWidget ctx mIdx wid rect (inputMousePos inp))+  -- A field scrolled out of its viewport, under a modal it is not in, or+  -- disabled hangs no dropdown.+  shown <-+    if open /= pressed+      then liftIO $+        (maybe True (isJust . rectIntersect rect) <$> getPrevClipRect ctx wid)+          <&&> (not <$> pointerBlockedByModal ctx)+          <&&> (not <$> isDisabled ctx wid)+      else pure False+  pick <- if shown then selectDropdown wid opts current else pure Nothing+  let+    -- A release on a row picks in this pass. A press picks in the store+    -- only, which the next frame reads, as a keyboard pick does.+    picked = fst <$> mfilter snd pick+    finalIdx = maybe current (clamp 0 (n - 1)) picked+    -- An index the options do not reach yet stays the caller's until a pick.+    result = if isNothing picked && stored == index then index else finalIdx+  -- Opening, closing or picking changes the store, which wakes the loop.+  liftIO $ do+    when pressed $ do+      modifyStore ctx (\st -> setSelectOpen st key (not open))+      writeIORef (ctxFocusId ctx) wid+    forM_ pick $ \(i, _) -> do+      modifyStore ctx (\st -> setSelectOpen (insertSlot fieldInt key i st) key False)+      writeIORef (ctxFocusId ctx) wid+    recordSlot fieldInt ctx key result+  -- Compare with the caller's index, not 'current': a dropdown or keyboard+  -- pick lands in the store between frames and must still report a change.+  pure (setChanged (result /= index) resp, result)++-- | The open dropdown of select @wid@ over @opts@, with row @current@+-- picked ('dropdownPopup'). Returns the row a left press or release on the+-- dropdown picks, and whether it was a release. A press on the field that is+-- released on a row picks it ('dropdownBodyInput').+selectDropdown :: WidgetId -> [Text] -> Int -> NanoUI (Maybe (Int, Bool))+selectDropdown wid opts current =+  fmap join . dropdownPopup wid dp (menuItemRowH * fromIntegral n + 2 * menuOuterPad) $ \inp dropR@(Rect _ dy _ _) ->+    let+      mouse = inputMousePos inp+      Size _ winH = inputWindowSize inp+      hovered = selectRowAt dropR n mouse+      released = releasedIn MouseLeft inp+      picked+        | hovered >= 0 && (pressedIn MouseLeft inp || released) = Just (hovered, released)+        | otherwise = Nothing+      -- The rows in the window where the dropdown was last laid out; the+      -- drawing is rebuilt when they, the hover or the pick change.+      (first, lastRow) = dropdownVisibleRows n winH (dy + menuOuterPad)+      content = hash (hovered, current, first, hash (take (lastRow - first + 1) (drop first opts)))+      build cdc rect = runCanvasFor cdc (paintDropdownRows cdc (dropdownPopupRows (cdcFont cdc) (cdcTheme cdc) winH mouse dp opts rect))+     in+      (picked, content, build)+  where+    n = length opts+    dp = DropdownPopup wid current False 0++-- | Field @owner@'s open dropdown: a popup the frame places below or above+-- the field ('NanoUI.Internal.Frame.Select.dropdownPlacement'), as wide as+-- it, holding one drawing @dropH@ tall. @body@, given the popup's input+-- ('dropdownBodyInput') and the drawing's rect last frame, returns a result,+-- the drawing's content key and its build. The popup is declared in+-- 'inDropdownScope'.+dropdownPopup :: WidgetId -> DropdownPopup -> Float -> (Input -> Rect -> (a, Int, CustomDrawBuild)) -> NanoUI (Maybe a)+dropdownPopup owner dp dropH body = inDropdownScope owner $ do+  ctx <- askContext+  let+    layout = fillW ((tight defaultLayout) {layoutGap = 0})+    addPanel pwid parent = do+      registerDropdownPopup ctx pwid dp+      addNodeFromLayout (ctxNodeArena ctx) NodePopup parent layout+  (_, r) <- floatingOverlay True Nothing addPanel (pure ()) $ do+    inp <- dropdownBodyInput owner+    dwid <- nextId+    resp <- addWidget dwid NodeDrawing T.empty 0 (fillW (fixedH dropH defaultLayout))+    let (a, content, build) = body inp (respRect resp)+    liftIO (registerCustomEntry ctx dwid (CustomDrawingEntry content build (Just (\_ _ _ -> UiCursorPointer)) 0 True KeysNone))+    pure (False, a)+  pure r++-- | Paint dropdown rows: each one's fill, the accent marker at the hovered+-- row's left edge, and its text.+paintDropdownRows :: CustomDrawContext -> [DropdownRow] -> CanvasM ()+paintDropdownRows cdc rows =+  forM_ rows $ \row -> do+    let r@(Rect rx ry _ rh) = drRect row+    mapM_ (drawRect r) (drFill row)+    when (drHovered row) $ drawRoundedRect (Rect rx (ry + 3) 2 (max 0 (rh - 6))) 1 (themeAccent (cdcTheme cdc))+    unless (T.null (drOption row)) $+      drawText (V2 (drTextX row) (centeredTextY fm ry rh (fmLineHeight fm))) AlignStart AlignTop (drOption row) (drFg row)+  where+    fm = cdcFont cdc++-- | Select over every value of a bounded enum, labeled by @encode@.+{-# INLINE enumSelectBy #-}+enumSelectBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()+enumSelectBy encode = void . enumSelectBy' encode++-- | 'enumSelectBy' returning its 'Response'.+{-# INLINE enumSelectBy' #-}+enumSelectBy' :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI Response+enumSelectBy' = bindEnumPicker (selectCore id)++-- | 'enumSelectBy' labeled with 'show'.+{-# INLINE enumSelect #-}+enumSelect :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()+enumSelect = enumSelectBy (T.pack . show)++-- | 'enumSelect' returning its 'Response'.+{-# INLINE enumSelect' #-}+enumSelect' :: (Bounded a, Enum a, Show a) => Var a -> NanoUI Response+enumSelect' = enumSelectBy' (T.pack . show)
+ lib/NanoUI/Internal/Widgets/Sensor.hs view
@@ -0,0 +1,232 @@+{-# LANGUAGE StrictData #-}++-- | Visibility sensors: whether a widget is on screen, and when it scrolls+-- into or out of view.+--+-- The view registers a watch each build ('sensorConfigured', 'useVisibility'),+-- keyed by the sensor's widget id. After layout, 'updateSensors' measures each+-- target and stores the result for the next build, so like+-- 'NanoUI.Internal.Widgets.Node.respRect' it reflects last frame's layout.+-- A visibility change requests a follow-up frame. Sensors not built in a+-- pass are dropped.+module NanoUI.Internal.Widgets.Sensor+  ( Visibility (..)+  , VisibilityEvent (..)+  , becameVisible+  , becameHidden+  , SensorConfig (..)+  , defaultSensorConfig+  , sensor+  , sensorWith+  , sensorConfigured+  , useVisibility+  , watchSensor+  , beginSensors+  , updateSensors+  ) where++import Control.Monad (foldM, unless, void, when)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.Maybe (fromMaybe, isJust)+import Data.Primitive.Array (newArray, readArray, sizeofMutableArray, writeArray)+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.Context+import NanoUI.Internal.Host qualified as Host+import NanoUI.Internal.Sensor.Types+import NanoUI.Internal.Frame.Node (childPaintClip)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena+import NanoUI.Internal.Monad (NanoUI, askDefaultLayout, currentId, freshWidget, liftIO, withContext)+import NanoUI.Internal.Style (Direction (..), Layout (..), tight)+import NanoUI.Internal.Types (Rect (..), Size (..), rectInflate, rectIntersect)+import NanoUI.Internal.Widgets.Node (container, tagContainer)++-- | Whether the widget came into view at the last layout.+becameVisible :: Visibility -> Bool+becameVisible v = visEvent v == Just BecameVisible++-- | Whether the widget went out of view at the last layout.+becameHidden :: Visibility -> Bool+becameHidden v = visEvent v == Just BecameHidden++-- | No margin, no delay, unpadded column.+defaultSensorConfig :: SensorConfig+defaultSensorConfig = SensorConfig {sensorAnticipate = 0, sensorDelay = 0, sensorLayout = id}++-- | Run @body@ in a container that reports its 'Visibility'. The container is+-- a column without padding.+--+-- > (vis, _) <- sensor (label "Row 42")+-- > when (becameVisible vis) (liftIO (putStrLn "row 42 scrolled into view"))+{-# INLINE sensor #-}+sensor :: NanoUI a -> NanoUI (Visibility, a)+sensor = sensorConfigured defaultSensorConfig++-- | 'sensor' with modified layout.+{-# INLINE sensorWith #-}+sensorWith :: (Layout -> Layout) -> NanoUI a -> NanoUI (Visibility, a)+sensorWith f = sensorConfigured defaultSensorConfig {sensorLayout = f}++-- | 'sensor' with a full 'SensorConfig'. Like+-- 'NanoUI.column', the container takes one widget id+-- and runs its body in its own id scope.+sensorConfigured :: SensorConfig -> NanoUI a -> NanoUI (Visibility, a)+sensorConfigured cfg body = do+  -- The container's own id, unique to it; the sensor is keyed by it.+  wid <- currentId+  base <- askDefaultLayout+  let layout = sensorLayout cfg (tight base) {layoutDirection = Column}+  a <- container NodeContainer layout (tagContainer wid >> body)+  vis <- withContext (\ctx -> watchSensor ctx wid (Watch wid cfg))+  pure (vis, a)++-- | The 'Visibility' of the widget @target@, such as @respId resp@ of an+-- earlier widget. This is a hook: it takes the next widget id, so call it+-- every frame. A target with no node is hidden.+--+-- > resp <- image' (fixedWH 96 96) thumb+-- > vis <- useVisibility defaultSensorConfig {sensorAnticipate = 200} (respId resp)+useVisibility :: SensorConfig -> WidgetId -> NanoUI Visibility+useVisibility cfg target = do+  (wid, ctx) <- freshWidget+  liftIO (watchSensor ctx wid (Watch target cfg))++-- | Initial state for a new sensor: hidden, no node.+unseen :: Visibility+unseen = Visibility False Nothing (Rect 0 0 0 0) (Rect 0 0 0 0)++-- | Register a watch for this pass and return the last result. Reading+-- consumes the event, so a second view pass in the frame sees none.+watchSensor :: Context -> WidgetId -> Watch -> IO Visibility+watchSensor ctx wid watch = do+  Sensors ref _ <- Host.hostOrInit (ctxSensors ctx) (Sensors <$> newIORef (SensorState 1 [] 0 IM.empty 0) <*> (newIORef . ClipMemo 0 =<< newArray 0 NoClips))+  SensorState pass watched n cells size <- readIORef ref+  let k = intKey wid+  case IM.lookup k cells of+    Just cell@(Cell _ cref) -> do+      CellState stamp _ seen@(Seen vis since) <- readIORef cref+      -- The last watch of a key wins; the cell is listed once.+      writeIORef cref $! CellState pass watch (if isJust (visEvent vis) then Seen vis {visEvent = Nothing} since else seen)+      when (stamp /= pass) $ writeIORef ref $! SensorState pass (cell : watched) (n + 1) cells size+      pure vis+    Nothing -> do+      cell <- Cell k <$> newIORef (CellState pass watch (Seen unseen 0))+      writeIORef ref $! SensorState pass (cell : watched) (n + 1) (IM.insert k cell cells) (size + 1)+      pure unseen++-- | Start a pass: clear the last pass's watches before the view reruns.+beginSensors :: Context -> IO ()+beginSensors ctx =+  Host.askHostIO (ctxSensors ctx) >>= mapM_ (\(Sensors ref _) -> modifyIORef' ref (\(SensorState pass _ _ cells size) -> SensorState (pass + 1) [] 0 cells size))++-- | Measure every watch against the final layout. Sensors not built this+-- pass are dropped. A visibility change marks the context dirty: the view's+-- reaction may change paint state no diff describes, so the follow-up frame+-- repaints like a model change.+updateSensors :: Context -> Size -> IO ()+updateSensors ctx size =+  Host.askHostIO (ctxSensors ctx) >>= mapM_ (\(Sensors ref memoRef) -> do+    SensorState pass watched n _ count <- readIORef ref+    unless (n == 0 && count == 0) $ do+      memo <- freshMemo ctx memoRef+      let step !event (Cell _ cref) = do+            CellState stamp watch old <- readIORef cref+            new@(Seen vis _) <- measureSensor ctx memo size old watch+            unless (old == new) $ writeIORef cref $! CellState stamp watch new+            pure (event || isJust (visEvent vis))+      event <- foldM step False watched+      -- Every cell is listed at most once, so a count short of the map's+      -- means some sensor was not built this pass.+      when (count /= n) $+        writeIORef ref $! SensorState pass watched n (IM.fromList [(k, c) | c@(Cell k _) <- watched]) n+      when event (markDirty ctx))++-- | Measure one watch. While 'sensorDelay' runs, request a wake-up for when+-- it ends, as 'NanoUI.Internal.Widgets.Popup.tooltipTimer' does.+measureSensor :: Context -> ClipMemo -> Size -> Seen -> Watch -> IO Seen+measureSensor ctx@Context {ctxNodeArena = na} memo size (Seen before since0) (Watch target cfg) = do+  mIdx <- lookupNodeByWidgetId na target+  (inView, bounds, onScreen) <- case mIdx of+    Nothing -> pure (False, Rect 0 0 0 0, Nothing)+    Just idx -> do+      rect <- getNodeRect na idx+      (exact, grown) <- paintClips ctx memo size (max 0 (sensorAnticipate cfg)) idx+      pure (maybe False (overlaps rect) grown, rect, exact >>= rectIntersect rect)+  let was = visVisible before+      delay = sensorDelay cfg+  -- @since@ is kept only while the widget is in view but not yet visible.+  (shown, since) <-+    if not inView || was || delay <= 0+      then pure (inView, 0)+      else do+        now <- getMonotonicTime+        let t = if since0 > 0 then since0 else now+            due = t + delay+        if now >= due+          then pure (True, 0)+          else (False, t) <$ requestWakeAt ctx due+  let event+        | shown == was = Nothing+        | shown = Just BecameVisible+        | otherwise = Just BecameHidden+  pure (Seen (Visibility shown event (fromMaybe (Rect 0 0 0 0) onScreen) bounds) since)++-- | The clip node @idx@ is painted within, exactly and with every clip grown+-- by @margin@; 'Nothing' when paint never reaches it. Mirrors paint: clip to+-- each enclosing scroller viewport, panel interior and widget rect, and skip+-- subtrees that are empty or outside their clip, except plain containers with+-- a pinned node below. Floating panels clip only to themselves.+paintClips :: Context -> ClipMemo -> Size -> Float -> NodeIdx -> IO (Maybe Rect, Maybe Rect)+paintClips ctx@Context {ctxNodeArena = na} memo size margin idx = do+  floating <- isFloatingNode <$> getNodeType na idx+  if floating then pure (windowClips size margin) else getParent na idx >>= clipsInside ctx memo size margin++windowClips :: Size -> Float -> (Maybe Rect, Maybe Rect)+windowClips (Size ww wh) margin = let window = Rect 0 0 ww wh in (Just window, Just (rectInflate margin window))++-- | The clips inside ancestor @i@ ('windowClips' for none), entered from the+-- root or the first floating panel down. Sensors under one ancestor share+-- them through the memo.+clipsInside :: Context -> ClipMemo -> Size -> Float -> NodeIdx -> IO (Maybe Rect, Maybe Rect)+clipsInside ctx memo@(ClipMemo stamp entries) size margin i+  | i < 0 = pure (windowClips size margin)+  | otherwise = do+      entry <- readArray entries i+      case entry of+        Clips s m clips | s == stamp && m == margin -> pure clips+        _ -> do+          outer <- paintClips ctx memo size margin i+          clips <- enterClips ctx margin outer i+          clips <$ writeArray entries i (Clips stamp margin clips)++-- | The clips inside node @i@, given those outside it.+enterClips :: Context -> Float -> (Maybe Rect, Maybe Rect) -> NodeIdx -> IO (Maybe Rect, Maybe Rect)+enterClips _ _ clips@(_, Nothing) _ = pure clips+enterClips ctx@Context {ctxNodeArena = na} margin (exact, grown) i = do+  nt <- getNodeType na i+  rect <- getNodeRect na i+  cut <- childPaintClip ctx i nt rect+  -- A plain container clips nothing, so a pinned descendant can show+  -- even when the container is empty or off screen.+  walked <- if nt == NodeContainer then hasPinnedBelow na i else pure False+  let within grow clip = do+        c <- clip+        unless walked (void (rectIntersect c rect))+        maybe (Just c) (rectIntersect c . grow) cut+  pure (within id exact, within (rectInflate margin) grown)++-- | Bump the stamp and make room for every node of this layout.+freshMemo :: Context -> IORef ClipMemo -> IO ClipMemo+freshMemo Context {ctxNodeArena = na} ref = do+  ClipMemo stamp memo <- readIORef ref+  nodes <- arenaCount na+  memo' <- if sizeofMutableArray memo >= nodes then pure memo else newArray (max nodes (2 * sizeofMutableArray memo)) NoClips+  let fresh = ClipMemo (stamp + 1) memo'+  fresh <$ writeIORef ref fresh++-- | Whether @r@ overlaps @clip@. An empty extent counts as a line or point.+overlaps :: Rect -> Rect -> Bool+overlaps (Rect x y w h) (Rect cx cy cw ch) = along x w cx cw && along y h cy ch+  where+    along a len c clen = a < c + clen && (if len > 0 then c < a + len else c <= a)
+ lib/NanoUI/Internal/Widgets/Shader.hs view
@@ -0,0 +1,158 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE StrictData #-}++-- | Leaf surface shader nodes ('shaderBox', 'shaderConfigured') and Tier 2+-- subtree effect wrappers ('withShader', 'withShaderWith').+module NanoUI.Internal.Widgets.Shader+  ( shaderBox+  , shaderBox'+  , shaderConfigured+  , shaderConfigured'+  , withShader+  , withShader'+  , withShaderWith+  , withShaderWith'+  , askShaderCapabilities+  ) where++import Control.Monad (void)+import Data.Bits (xor)+import Data.Primitive.ByteArray (emptyByteArray)+import Data.Proxy (Proxy (..))+import Data.Text qualified as T+import GHC.Float (castFloatToWord32)+import NanoUI.Internal.Context+  ( Context (..)+  , getShaderCapabilities+  , registerNodeShaderAt+  , registerShaderEffectAt+  )+import NanoUI.Internal.Id (mix64)+import NanoUI.Internal.Layout.Arena+  ( NodeType (NodeContainer, NodeShader)+  , addNodeFromLayout+  , mixNodePaintHash+  , setStyleIdx+  , setWidgetId+  )+import NanoUI.Internal.Monad (NanoUI, askContext, askDefaultLayout, askInput, liftIO, nextId, withContext)+import NanoUI.Internal.Shader+  ( IsNodeEffect (..)+  , PackedShaderPass (..)+  , Shader (..)+  , ShaderCapabilities (..)+  , ShaderConfig (..)+  , ShaderEffectEntry (..)+  , ShaderKind (Surface)+  , ShaderNodeEntry (..)+  , defaultShaderConfig+  , emptyShaderProgram+  , packShaderPass+  )+import NanoUI.Internal.Style (LayoutModifier, defaultLayout, tight)+import NanoUI.Internal.Types (V2 (..), colorToWord32)+import NanoUI.Internal.WidgetText (containerFlagShaderEffect)+import NanoUI.Internal.Widgets.Combinators (widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response, addWidgetNode, currentParent, resolveInteraction, withContainerNode)++-- | Paint a leaf rectangle using a 'Surface' fragment shader and typed+-- uniform value @u@. Uniform changes invalidate the node automatically via+-- its paint hash; unchanged uniforms produce zero damage.+{-# INLINE shaderBox #-}+shaderBox :: LayoutModifier -> Shader 'Surface u -> u -> NanoUI ()+shaderBox f sh = void . shaderBox' f sh++-- | Like 'shaderBox', returning the node's 'Response'.+{-# INLINE shaderBox' #-}+shaderBox' :: LayoutModifier -> Shader 'Surface u -> u -> NanoUI Response+shaderBox' f = shaderConfigured' defaultShaderConfig {scLayout = f}++-- | Paint a leaf 'Surface' shader node with explicit corner radius, fallback+-- color (used on non-GPU backends and SVG export), and vertex tint.+{-# INLINE shaderConfigured #-}+shaderConfigured :: ShaderConfig -> Shader 'Surface u -> u -> NanoUI ()+shaderConfigured cfg sh = void . shaderConfigured' cfg sh++-- | Like 'shaderConfigured', returning the node's 'Response'.+shaderConfigured' :: ShaderConfig -> Shader 'Surface u -> u -> NanoUI Response+shaderConfigured' cfg sh u = do+  wid <- nextId+  ctx <- askContext+  !lay <- widgetBaseLayout defaultLayout (scLayout cfg)+  pass <- liftIO $ case shaderPasses sh of+    (p : _) -> packShaderPass p u+    [] -> pure (PackedShaderPass (shaderHash sh) emptyShaderProgram emptyByteArray 0)+  let !radius = max 0 (scCornerRadius cfg)+      !fallback = scFallback cfg+      !tint = scTint cfg+      !paintH =+        mix64+          (pspHash pass `xor` pspUniformHash pass)+          ( fromIntegral (castFloatToWord32 radius)+              `xor` mix64 (fromIntegral (colorToWord32 fallback)) (fromIntegral (colorToWord32 tint))+          )+      !entry =+        ShaderNodeEntry+          { snePass = pass+          , sneCornerRadius = radius+          , sneFallback = fallback+          , sneTint = tint+          }+  addWidgetNode wid NodeShader T.empty 0 lay $ \arena idx -> do+    mixNodePaintHash arena idx paintH+    registerNodeShaderAt ctx idx entry++-- | Wrap a child subtree in a Tier 2 fragment effect ('NanoUI.ColorEffect',+-- 'NanoUI.DistortionEffect', or 'NanoUI.LayerEffect'). On backends that do not support+-- offscreen node effects, children render straight through with no effect.+{-# INLINE withShader #-}+withShader :: IsNodeEffect k => Shader k u -> u -> NanoUI a -> NanoUI a+withShader = withShaderWith id++-- | Like 'withShader', returning the body's result and the effect container's+-- 'Response' (for hover, clicks, or size-reactive shader uniforms).+{-# INLINE withShader' #-}+withShader' :: IsNodeEffect k => Shader k u -> u -> NanoUI a -> NanoUI (a, Response)+withShader' = withShaderWith' id++-- | Like 'withShader', applying a 'LayoutModifier' to the effect container.+{-# INLINE withShaderWith #-}+withShaderWith :: forall k u a. IsNodeEffect k => LayoutModifier -> Shader k u -> u -> NanoUI a -> NanoUI a+withShaderWith f sh u child = fst <$> withShaderWith' f sh u child++-- | Like 'withShaderWith', returning the body's result and the effect+-- container's 'Response'.+withShaderWith' :: forall k u a. IsNodeEffect k => LayoutModifier -> Shader k u -> u -> NanoUI a -> NanoUI (a, Response)+withShaderWith' f sh u child = do+  let !_ = nodeEffectKind (Proxy @k)+  wid <- nextId+  inp <- askInput+  base <- askDefaultLayout+  let !lay = f (tight base)+  idx <- withContext $ \ctx -> do+    passes <- mapM (`packShaderPass` u) (shaderPasses sh)+    let V2 mx0 my0 = shaderMargin sh u+        !margin = V2 (max 0 mx0) (max 0 my0)+        !entry =+          ShaderEffectEntry+            { seePasses = passes+            , seeMargin = margin+            , seeSvgOpacity = fmap ($ u) (shaderSvgOpacity sh)+            }+        !uHash = foldl' (\acc p -> mix64 acc (pspHash p `xor` pspUniformHash p)) (shaderHash sh) passes+        !mHash = mix64 (fromIntegral (castFloatToWord32 (v2X margin))) (fromIntegral (castFloatToWord32 (v2Y margin)))+    parent <- currentParent ctx+    let arena = ctxNodeArena ctx+    i <- addNodeFromLayout arena NodeContainer parent lay+    setWidgetId arena i wid+    setStyleIdx arena i containerFlagShaderEffect+    mixNodePaintHash arena i (mix64 uHash mHash)+    registerShaderEffectAt ctx i entry+    pure i+  r <- withContainerNode True idx child+  resp <- withContext (\ctx -> resolveInteraction ctx inp (-1) wid)+  pure (r, resp)++-- | Query which shader tiers the active backend supports.+askShaderCapabilities :: NanoUI ShaderCapabilities+askShaderCapabilities = withContext getShaderCapabilities
+ lib/NanoUI/Internal/Widgets/Shortcut.hs view
@@ -0,0 +1,182 @@+-- | Keyboard listeners for a view (key pressed, released or held this frame)+-- and shortcuts. Both skip keys that the focused widget uses itself.+module NanoUI.Internal.Widgets.Shortcut+  ( keyPressed+  , keyPressedOnce+  , keyReleased+  , keyHeld+  , shortcut+  , shortcutOnce+  , hardQuitUsed+  , focusTakesChord+  ) where++import Control.Monad (when)+import Data.Foldable (toList)+import Data.IntSet qualified as IS+import Data.List (elemIndices)+import Data.Maybe (isJust)+import NanoUI.Internal.Context+import NanoUI.Internal.Input+import NanoUI.Internal.Monad (NanoUI, askInput, takeEscape, withContext, (<&&>))+import NanoUI.Internal.Shortcut+import NanoUI.Widgets.TextEditor (keyCommand, multiLineMode, singleLineMode)++-- | Whether the key went down this frame, including auto-repeats, with any+-- modifiers. 'False' behind an open modal, inside 'NanoUI.disabledWhen', and+-- when the focused widget uses the key itself ('focusTakesChord'), such as+-- Delete in a focused text field. Also 'False' for an Escape that closes an+-- open dropdown, a focused combo box's list or a text-edit menu, or that+-- something earlier in the view took ('NanoUI.takeEscape'), and for its+-- repeats and its release ('keyReleased', 'keyHeld'). Like iced's+-- @keyboard::listen@, this only reports keys not claimed by the focused+-- widget; 'pressedIn' checks raw frame input. To bind a command to a key,+-- use 'shortcut'.+keyPressed :: Key -> NanoUI Bool+keyPressed = keyIn pressedIn++-- | 'keyPressed' without auto-repeats, so holding the key acts once.+keyPressedOnce :: Key -> NanoUI Bool+keyPressedOnce = keyIn pressedOnceIn++-- | Whether the key came up this frame. Filtered like 'keyPressed'.+keyReleased :: Key -> NanoUI Bool+keyReleased = keyIn releasedIn++-- | Whether the key is down. Filtered like 'keyPressed'.+keyHeld :: Key -> NanoUI Bool+keyHeld = keyIn heldIn++keyIn :: (Key -> Input -> Bool) -> Key -> NanoUI Bool+keyIn happened k = do+  inp <- askInput+  if happened k inp+    then withContext $ \ctx ->+      keyFree ctx (inputModifiers inp) k <&&> (if k == KeyEscape then not <$> escapeReserved ctx else pure True)+    else pure False++-- | Whether the view may handle this key: no modal is open and the focused+-- widget does not use it ('focusTakesChord').+keyFree :: Context -> Modifiers -> Key -> IO Bool+keyFree ctx mods k = do+  blocked <- pointerBlockedByModal ctx+  kind <- getsInteraction ctx isFocusKind+  if blocked || not (focusTakesChord kind mods k)+    then pure (not blocked)+    else getFocusId ctx >>= \focus -> (||) <$> isDisabled ctx focus <*> isInert ctx focus++-- | 'True' on a frame where the chord is pressed with exactly its modifiers.+-- Auto-repeats count as presses. Only the first shortcut declared for a chord+-- fires, and it consumes the frame's presses of that key. So a menu item and+-- a view binding the same chord do not both act, and a view that runs twice+-- in a frame only matches the press once. The chord does not fire:+--+-- * behind an open modal, or inside 'NanoUI.disabledWhen';+-- * when the focused widget uses the key itself ('focusTakesChord'). A+--   button keeps Enter and Space; a slider or list also keeps the arrows+--   (each alone or with Shift). A text field keeps typing, cursor and delete+--   keys and its own shortcuts such as Ctrl+A and Ctrl+Z; a multi-line field+--   leaves Ctrl or Alt with Enter, Up or Down free. During input method+--   composition, and on the frame it commits, the field keeps every key. A custom widget+--   keeps the keys its 'NanoUI.Widgets.Custom.widgetKeys' names;+-- * for Escape, when 'NanoUI.takeEscape' fails. Otherwise the shortcut+--   consumes the Escape.+--+-- A Tab chord does not move focus. A Ctrl+C that no shortcut takes, and that+-- the focused widget does not use, closes the window+-- ('NanoUI.Runner.runSessionLoop').+--+-- > whenM (shortcut (ctrl <> key 's')) save+-- > whenM (shortcut (cmdOrCtrl <> shift <> key 'p')) (setPaletteOpen True)+-- > whenM (shortcut (key (KeyF 5))) refresh+--+-- A chord with no key never fires.+shortcut :: Shortcut -> NanoUI Bool+shortcut = chordShortcut False++-- | 'shortcut' without auto-repeats, so holding a toggle chord toggles once.+-- On a frame with only auto-repeats, a later 'shortcut' for the same chord+-- can still take them.+--+-- > whenM (shortcutOnce (key (KeyF 11))) toggleFullscreen+shortcutOnce :: Shortcut -> NanoUI Bool+shortcutOnce = chordShortcut True++chordShortcut :: Bool -> Shortcut -> NanoUI Bool+chordShortcut _ (Shortcut Nothing _) = pure False+chordShortcut once (Shortcut (Just pressedKey) mods) = do+  inp <- askInput+  if inputModifiers inp /= mods || not ((if once then pressedOnceIn else pressedIn) pressedKey inp)+    then pure False+    else do+      free <- withContext (\ctx -> keyFree ctx mods pressedKey)+      -- Open overlays close on Escape, and they get it first.+      ours <- if free && pressedKey == KeyEscape then takeEscape else pure free+      if not ours+        then pure False+        else withContext $ \ctx -> do+          -- Consume every press of the key, including auto-repeats, so a second+          -- binding of the chord does not fire.+          took <- or <$> mapM (takeKeyPress ctx) (elemIndices pressedKey (toList (inputKeys inp)))+          when (took && pressedKey == KeyTab) (markTabConsumed ctx)+          pure took++-- | Whether the frame just run used its Ctrl+C ('isHardQuitInput'): a+-- shortcut took the press, the focused widget uses the chord itself+-- ('focusTakesChord') or copies with the platform's copy chord, as a text+-- field does, or a text-edit menu is open. The session loop quits only on a+-- Ctrl+C that nothing used.+hardQuitUsed :: Context -> Input -> IO Bool+hardQuitUsed ctx inp = do+  kind <- getsInteraction ctx isFocusKind+  menu <- getsInteraction ctx isTextInputMenu+  let presses = elemIndices (KeyChar 'c') (toList (inputKeys inp))+      -- On macOS a field copies with Cmd+C and leaves Ctrl+C alone, but a+      -- Ctrl+C typed there out of habit must not close the window either.+      takes mods = focusTakesChord kind mods (KeyChar 'c')+  taken <- getsOverlay ctx (\os -> any (`IS.member` osKeysTaken os) presses)+  pure (taken || isJust menu || takes (inputModifiers inp) || takes primaryModifiers)++-- | Whether the focused widget uses this key and modifier combination+-- itself. If so, shortcuts and key listeners ignore it.+--+-- A control takes only its own keys, alone or with Shift ('shiftAtMost'),+-- so chords such as Alt+Left or Ctrl+Enter still reach shortcuts. Buttons+-- and checkboxes take Enter and Space ('KeysActivate'). Sliders, selects,+-- lists and pane grids also take the arrows, Home, End, Page Up and Page+-- Down ('KeysNavigate'). A custom widget takes what its+-- 'NanoUI.Widgets.Custom.widgetKeys' names.+--+-- A text field takes Left, Right, Home and End with any modifiers, typing+-- keys ('isCommandKey'), and its editing keys and shortcuts+-- ('NanoUI.Widgets.TextEditor.keyCommand'). A single-line field also takes+-- Enter, and Up and Down with any modifiers, which step a numeric field or a+-- combo's list. A multi-line field leaves Ctrl or Alt with Enter, Up or Down+-- free, for example to submit. A read-only selectable text takes only Left,+-- Right, Home and End, and select-all and copy. During input+-- method composition, and on the frame it commits, the field takes every+-- key, so a chord that ends a composition does not also run a shortcut.+focusTakesChord :: FocusKind -> Modifiers -> Key -> Bool+focusTakesChord kind mods k =+  case kind of+    FocusNone -> False+    FocusControl KeysActivate -> activates+    FocusControl KeysNavigate -> activates || moves+    FocusControl KeysType -> fieldTakes True+    FocusControl KeysAll -> True+    FocusControl KeysNone -> False+    FocusControl KeysReadOnly -> readOnlyTakes+    FocusControl (KeysOnly chords) -> Shortcut (Just k) mods `elem` chords+    FocusTextLine -> fieldTakes False+    FocusTextSelectable -> readOnlyTakes+    FocusComposing -> True+  where+    readOnlyTakes = k `elem` [KeyLeft, KeyRight, KeyHome, KeyEnd]+      || (chordModifiers mods && k `elem` [KeyChar 'a', KeyChar 'c'])+    activates = shiftAtMost mods && (k == KeyEnter || k == KeySpace)+    moves = shiftAtMost mods && k `elem` [KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, KeyPageUp, KeyPageDown]+    fieldTakes multi =+      k `elem` [KeyLeft, KeyRight, KeyHome, KeyEnd]+        || (not multi && k `elem` [KeyEnter, KeyUp, KeyDown])+        || not (isCommandKey mods k)+        || isJust (keyCommand (if multi then multiLineMode else singleLineMode) mods k)
+ lib/NanoUI/Internal/Widgets/Slider.hs view
@@ -0,0 +1,85 @@+-- | Horizontal slider control.+module NanoUI.Internal.Widgets.Slider+  ( slider+  , slider'+  , sliderWith+  , sliderWith'+  )+where++import Control.Monad (void, when)+import NanoUI.Internal.Context+import NanoUI.Internal.Equality (sameFloat)+import NanoUI.Internal.Font (sliderHitBounds)+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, freshWidget, scope, liftIO)+import NanoUI.Internal.Style (Layout, defaultLayout, fillW)+import NanoUI.Internal.Store (fieldFloat)+import NanoUI.Internal.Types (Rect (..), clamp)+import NanoUI.Internal.Var (Binding (..), bindVarBy)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Behavior (DragAxis (..), holdActiveWhile, navStep, useDrag1D, useKeyNav)+import NanoUI.Internal.Widgets.Combinators (finishInput, widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response, addWidget, respRect, setWidgetValue)++-- | Slider over @[minV, maxV]@ that fills the available width, bound to+-- mutable state ('Var'): a drag or the arrow keys update it in place.+--+-- > slider 0 100 app.volume+{-# INLINE slider #-}+slider :: Float -> Float -> Var Float -> NanoUI ()+slider minV maxV v = void (sliderWith' id minV maxV v)++-- | 'slider' returning its 'Response'.+{-# INLINE slider' #-}+slider' :: Float -> Float -> Var Float -> NanoUI Response+slider' = sliderWith' id++-- | 'slider' with a layout modifier.+--+-- > sliderWith (fixedW 200) 0 100 volume+{-# INLINE sliderWith #-}+sliderWith :: (Layout -> Layout) -> Float -> Float -> Var Float -> NanoUI ()+sliderWith f minV maxV v = void (sliderWith' f minV maxV v)++-- | 'sliderWith' returning its 'Response'.+{-# INLINE sliderWith' #-}+sliderWith' :: (Layout -> Layout) -> Float -> Float -> Var Float -> NanoUI Response+sliderWith' f minV maxV v = bindVarBy sameFloat RenderFinal v (sliderCore f minV maxV)++sliderBaseLayout :: Layout+sliderBaseLayout = fillW defaultLayout++-- | 'sliderWith' on a plain value: the response and the value after this+-- frame's drag or arrow keys.+sliderCore ::+  (Layout -> Layout) -> Float -> Float -> Float -> NanoUI (Response, Float)+sliderCore f minV maxV value+  -- A NaN bound gives way to 0 or the other bound, and a reversed range+  -- reads low to high, so neither leaves the value NaN or pinned to a bound.+  | isNaN minV = sliderCore f 0 maxV value+  | isNaN maxV = sliderCore f minV minV value+  | minV > maxV = sliderCore f maxV minV value+sliderCore f minV maxV value = do+  (wid, ctx) <- freshWidget+  liftIO $ registerFocusable ctx wid+  -- Adopt the value the slider can show, so one outside the range (or NaN)+  -- is not adopted afresh, and written back clamped, on every frame.+  let !given = if isNaN value then minV else clamp minV maxV value+  current <- liftIO $ adoptSlot fieldFloat ctx wid given+  let !range = maxV - minV+      fracOf x = if range > 0 then (x - minV) / range else 0+  lay <- widgetBaseLayout sliderBaseLayout f+  resp <- addWidget wid NodeSlider "" (fracOf current) lay+  let Rect rx ry rw rh = respRect resp+      track = if rw > 0 && rh > 0 then sliderHitBounds rx ry rw rh else Rect 0 0 0 0+  -- Scope the drag to this slider's position so sibling sliders keep separate drag state.+  (dragged, dragging, _) <- scope (useDrag1D DragAxisX wid minV maxV current track)+  holdActiveWhile wid dragging+  nav <- useKeyNav wid+  let !step = if range > 0 then range / 100 else 0+      !finalVal = clamp minV maxV (dragged + fromIntegral (navStep nav) * step)+  -- The node was added before the drag was read: show where it ended, so+  -- this pass draws the value it returns.+  when (finalVal /= current) . liftIO $ setWidgetValue ctx wid (fracOf finalVal)+  finishInput fieldFloat ctx wid current resp finalVal
+ lib/NanoUI/Internal/Widgets/SplitPane.hs view
@@ -0,0 +1,500 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Pure tree model and geometry for "NanoUI.Widgets.PaneGrid". A+-- 'GridNode' is a binary split tree. Each split has an axis, a ratio in+-- @[0,1]@ for its first (A) side, and two subtrees. Panes and splits have+-- unique 'Word64' ids, so pane state stays keyed to a pane as it moves.+module NanoUI.Internal.Widgets.SplitPane+  ( GridAxis (..)+  , CenterDropMode (..)+  , GridNode (..)+  , PaneDrop (..)+  , treePanes+  , treeSize+  , treeMaxId+  , paneExist+  , MinTree (..)+  , buildMinTree+  , minTreeDims+  , splitMinChildren+  , alongAxis+  , mainLen+  , layoutNode+  , DividerInfo (..)+  , dividerLength+  , clampRatio+  , treeSplit+  , splitBeside+  , treeAddTab+  , treeSelectTab+  , treeSetRatio+  , pinnedSide+  , reflowFixed+  , treeRemovePane+  , DropPreview (..)+  , dropPreviewTreeSized+  , dropTargetForPane+  , dropTargetForPaneWith+  , rectDistSq+  , nearestPane+  , bestPane+  , topLevelDropTarget+  ) where++import Control.Applicative ((<|>))+import Data.List (elemIndex, find, sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as M+import Data.Maybe (fromMaybe, listToMaybe)+import Data.Word (Word64)+import NanoUI.Internal.GridNode (CenterDropMode (..), GridAxis (..), GridNode (..))+import NanoUI.Internal.Types (Rect (..), V2 (..), clamp, clamp01, rectContains, rectH, rectNonEmpty, rectW, rectX, rectY)++-- | Result of dropping a dragged pane on a target pane.+data PaneDrop+  = DropSwap Word64+      -- ^ Drop on the center of the pane: the two panes swap places.+  | DropTab Word64 (Maybe Int)+      -- ^ Drop on a pane center (when 'CenterTab' is enabled) or tab bar:+      -- merge the dragged pane into the target's 'PaneTabs' stack at an optional+      -- index (or at the end when 'Nothing').+  | DropSplit Word64 GridAxis Bool+      -- ^ Drop near an edge: the target pane splits along the axis and the+      -- dragged pane moves into the new child. 'True' puts the dragged pane on+      -- the A (left/top) side, 'False' on the B (right/bottom) side.+  | DropTop GridAxis Bool+      -- ^ Drop on the grid's outer edge: the whole tree is wrapped in a new+      -- top-level split. 'True' puts the dragged pane on the A side.+  deriving (Eq, Show)++forceWords :: [Word64] -> [Word64]+forceWords [] = []+forceWords (!x : xs) = let !rest = forceWords xs in x : rest++normalizeTabs :: Word64 -> [Word64] -> Word64 -> Maybe GridNode+normalizeTabs gid pids0 active =+  case forceWords pids0 of+    [] -> Nothing+    [only] -> Just (Pane only)+    pids@(first : _) ->+      let !act = if elem active pids then active else first+       in Just (PaneTabs gid pids act)++-- | Fold a tree bottom-up: @onPane@ for each pane leaf, @onTabs@ for each+-- tabbed stack, and @onSplit@ for each split (id, axis, ratio) with its+-- already-folded A and B sides.+foldGrid ::+  (Word64 -> r) ->+  (Word64 -> [Word64] -> Word64 -> r) ->+  (Word64 -> GridAxis -> Float -> r -> r -> r) ->+  GridNode ->+  r+foldGrid onPane onTabs onSplit = go+  where+    go (Pane pid) = onPane pid+    go (PaneTabs gid pids active) = onTabs gid pids active+    go (Split sid axis ratio a b) = onSplit sid axis ratio (go a) (go b)++-- | Pane ids in the tree (depth-first, A then B, and tab-order within 'PaneTabs').+treePanes :: GridNode -> [Word64]+treePanes = foldGrid pure (\_ pids _ -> pids) (\_ _ _ a b -> a <> b)++-- | Number of panes.+treeSize :: GridNode -> Int+treeSize = foldGrid (const 1) (\_ pids _ -> length pids) (\_ _ _ a b -> a + b)++-- | The largest pane, tab-group, or split id in the tree.+treeMaxId :: GridNode -> Word64+treeMaxId = foldGrid id (\gid pids _ -> foldl' max gid pids) (\sid _ _ a b -> maximum [sid, a, b])++-- | Does a pane with the given id exist?+paneExist :: GridNode -> Word64 -> Bool+paneExist t p = foldGrid (== p) (\_ pids _ -> elem p pids) (\_ _ _ a b -> a || b) t++-- | Cached bottom-up subtree minimum extents so tree traversals read each+-- split's child minima in O(1).+data MinTree+  = MinLeaf {-# UNPACK #-} !Float {-# UNPACK #-} !Float+  | MinBranch {-# UNPACK #-} !Float {-# UNPACK #-} !Float !MinTree !MinTree++-- | Total minimum @(width, height)@ of a 'MinTree'.+{-# INLINE minTreeDims #-}+minTreeDims :: MinTree -> (Float, Float)+minTreeDims (MinLeaf w h) = (w, h)+minTreeDims (MinBranch w h _ _) = (w, h)++-- | Extract the child minimum trees for a 'Split' node, rebuilding them if the+-- supplied 'MinTree' does not match the branch shape.+{-# INLINE splitMinChildren #-}+splitMinChildren :: Float -> Float -> GridNode -> GridNode -> MinTree -> (MinTree, MinTree)+splitMinChildren _ _ _ _ (MinBranch _ _ l r) = (l, r)+splitMinChildren minSize spacing a b _ = (buildMinTree minSize spacing a, buildMinTree minSize spacing b)++-- | Compute the minimum @(width, height)@ for every node of @GridNode@ in a+-- single O(P) bottom-up pass.+buildMinTree :: Float -> Float -> GridNode -> MinTree+buildMinTree minSize spacing = go+  where+    go (Pane _) = MinLeaf minSize minSize+    go (PaneTabs _ _ _) = MinLeaf minSize minSize+    go (Split _ axis _ a b) =+      let ma = go a+          mb = go b+          (wa, ha) = minTreeDims ma+          (wb, hb) = minTreeDims mb+          (w, h) = case axis of+            AxisV -> (wa + spacing + wb, max ha hb)+            AxisH -> (max wa wb, ha + spacing + hb)+       in MinBranch w h ma mb++-- | A rect seen along a split's main axis: as it is for 'AxisV', with x and y+-- (and width and height) swapped for 'AxisH', so per-axis geometry is written+-- once, for a vertical divider. Its own inverse.+alongAxis :: GridAxis -> Rect -> Rect+alongAxis AxisV r = r+alongAxis AxisH (Rect x y w h) = Rect y x h w++-- | Extent of a region along a split's main axis.+mainLen :: GridAxis -> Rect -> Float+mainLen ax = rectW . alongAxis ax++-- | The minima of two cached subtrees along @axis@.+splitMinsTree :: GridAxis -> MinTree -> MinTree -> (Float, Float)+splitMinsTree axis ma mb =+  let (wa, ha) = minTreeDims ma+      (wb, hb) = minTreeDims mb+   in case axis of+        AxisV -> (wa, wb)+        AxisH -> (ha, hb)++-- | A-side extent for a split along its main axis, honouring the subtree+-- minima. The ratio shares out the extent left after the gutter between the+-- sides, so a 0.5 split gives both sides the same length. Falls back to the+-- raw share when the region is too small to satisfy both minima.+splitLength :: Float -> Float -> Float -> Float -> Float -> Float+splitLength spacing avail minA minB ratio+  | avail <= 0 = 0+  | lo <= hi = clamp lo hi share+  | otherwise = clamp 0 avail share+  where+    share = ratio * max 0 (avail - spacing)+    lo = minA+    hi = avail - spacing - minB++-- | Carve a region at offset @d@ along the main axis into (A, B, divider band).+splitBounds :: GridAxis -> Float -> Rect -> Float -> (Rect, Rect, Rect)+splitBounds ax spacing r d =+  let Rect x y w h = alongAxis ax r+   in ( alongAxis ax (Rect x y (max 0 d) h)+      , alongAxis ax (Rect (x + d + spacing) y (max 0 (w - d - spacing)) h)+      , alongAxis ax (Rect (x + d) y spacing h)+      )++-- | A split's divider: id, axis, ratio, the split's region, the spacing+-- band, and each side's minimum extent along the axis.+data DividerInfo = DividerInfo+  { diSplitId :: {-# UNPACK #-} !Word64+  , diAxis :: !GridAxis+  , diRegion :: !Rect+  , diBand :: !Rect+  , diRatio :: {-# UNPACK #-} !Float+  , diMins :: !(Float, Float)+  }+  deriving (Eq, Show)++-- | The A side's extent for a ratio in the divider's region ('splitLength').+dividerLength :: Float -> DividerInfo -> Float -> Float+dividerLength spacing d = uncurry (splitLength spacing (mainLen (diAxis d) (diRegion d))) (diMins d)++-- | Clamp a proposed ratio for a divider so both of its sides keep at least+-- their minimum size within its region.+clampRatio :: Float -> DividerInfo -> Float -> Float+clampRatio spacing d r0+  | usable <= 0 = r0+  | otherwise = dividerLength spacing d r0 / usable+  where+    usable = mainLen (diAxis d) (diRegion d) - spacing++-- | Lay out a tree into per-pane regions and divider bands within 'Rect'.+-- Dividers are reported parent-before-child so dragging a divider resizes its+-- immediate subtrees relative to the same region.+layoutNode :: Float -> Float -> GridNode -> Rect -> (Map Word64 Rect, [DividerInfo])+layoutNode minSize spacing root = go root (buildMinTree minSize spacing root)+  where+    go sp mt r = case sp of+      Pane pid -> (M.singleton pid r, [])+      PaneTabs _ _ active -> (M.singleton active r, [])+      Split sid axis ratio0 a b ->+        let (ma, mb) = splitMinChildren minSize spacing a b mt+            mins = splitMinsTree axis ma mb+            (rA, rB, band) = splitBounds axis spacing r (uncurry (splitLength spacing (mainLen axis r)) mins ratio0)+            self = DividerInfo sid axis r band ratio0 mins+            (regionsA, divsA) = go a ma rA+            (regionsB, divsB) = go b mb rB+         in (M.union regionsA regionsB, self : divsA <> divsB)++-- | Split the pane (first arg) along the axis with a 0.5 ratio, inserting the+-- new pane. @newOnA@ places the new pane on the A (left/top) side of the new+-- split; 'False' puts it on the B (right/bottom) side. Returns the updated+-- tree (unchanged if the pane does not exist).+treeSplit :: Word64 -> Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode+treeSplit targetPaneId splitId axis newOnA newPaneId = foldGrid onPane onTabs Split+  where+    onPane p+      | p /= targetPaneId = Pane p+      | otherwise = splitBeside splitId axis newOnA newPaneId (Pane p)+    onTabs gid pids active+      | notElem targetPaneId pids = PaneTabs gid pids active+      | otherwise = splitBeside splitId axis newOnA newPaneId (PaneTabs gid pids active)++-- | Wrap @node@ and @newPane@ in a 50/50 split along @axis@, placing @newPane@ on side A when @newOnA@ is set.+splitBeside :: Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode+splitBeside splitId axis newOnA newPane node+  | newOnA = Split splitId axis 0.5 (Pane newPane) node+  | otherwise = Split splitId axis 0.5 node (Pane newPane)++-- | Merge @newPaneId@ into the 'Pane' or 'PaneTabs' stack containing @targetPaneId@,+-- using @groupId@ when promoting a single 'Pane' into 'PaneTabs', and activating+-- @newPaneId@.+treeAddTab :: Word64 -> Word64 -> Maybe Int -> Word64 -> GridNode -> GridNode+treeAddTab targetPaneId groupId mIdx newPaneId = foldGrid onPane onTabs Split+  where+    insertAt xs x = case mIdx of+      Nothing -> forceWords (xs ++ [x])+      Just i ->+        let k = clamp 0 (length xs) i+            (pre, post) = splitAt k xs+         in forceWords (pre ++ [x] ++ post)+    onPane p+      | p /= targetPaneId = Pane p+      | otherwise = PaneTabs groupId (insertAt [p] newPaneId) newPaneId+    onTabs gid pids active+      | notElem targetPaneId pids = PaneTabs gid pids active+      | otherwise =+          let clean = filter (/= newPaneId) pids+           in PaneTabs gid (insertAt clean newPaneId) newPaneId++-- | Set the active pane in whichever 'PaneTabs' stack contains @paneId@.+treeSelectTab :: Word64 -> GridNode -> GridNode+treeSelectTab paneId =+  foldGrid+    Pane+    (\gid pids active -> PaneTabs gid pids (if elem paneId pids then paneId else active))+    Split++-- | Set the raw ratio of a split (clamped to @[0,1]@).+treeSetRatio :: Word64 -> Float -> GridNode -> GridNode+treeSetRatio splitId r =+  foldGrid Pane PaneTabs (\sid ax r0 -> Split sid ax (if sid == splitId then clamp01 r else r0))++-- | Whether this side of a split is itself a pinned pane. A pin only fixes+-- a pane's extent along its direct parent split's axis.+pinnedSide :: (Word64 -> Bool) -> GridNode -> Bool+pinnedSide isFixed = \case+  Pane p -> isFixed p+  PaneTabs _ pids active -> isFixed active || any isFixed pids+  Split{} -> False++-- | The A-side ratio that gives this region's split an A extent of @d@. The+-- inverse of 'splitLength', clamped to the subtree minima so the ratio+-- matches the real split. Zero when the region has no room beside the gutter.+lengthRatio :: Float -> Float -> Float -> Float -> Float -> Float+lengthRatio spacing avail minA minB d+  | usable <= 0 = 0+  | otherwise = clamp01 (splitLength spacing avail minA minB (d / usable) / usable)+  where+    usable = avail - spacing++-- | Re-ratio a tree for a resized region so the panes the predicate selects+-- keep their extent along their parent split's axis. The other side of that+-- split ('pinnedSide') absorbs the change. All other splits keep their+-- ratio, including splits pinned on both sides or neither and splits with no+-- room beside the gutter. A pinned pane squeezed below its extent keeps the+-- smaller extent when the region grows back.+reflowFixed :: (Word64 -> Bool) -> Float -> Float -> Rect -> Rect -> GridNode -> GridNode+reflowFixed isFixed minSize spacing oldR0 newR0 root = go oldR0 newR0 root (buildMinTree minSize spacing root)+  where+    go _ _ n@(Pane _) _ = n+    go _ _ n@(PaneTabs _ _ _) _ = n+    go oldR newR (Split sid axis ratio a b) mt =+      Split sid axis ratio' (go oldA newA a ma) (go oldB newB b mb)+      where+        (ma, mb) = splitMinChildren minSize spacing a b mt+        (mA, mB) = splitMinsTree axis ma mb+        oldAvail = mainLen axis oldR+        newAvail = mainLen axis newR+        dOld = splitLength spacing oldAvail mA mB ratio+        fixedA = pinnedSide isFixed a+        fixedB = pinnedSide isFixed b+        -- A-side extent that preserves the pinned side. The pinned extent is+        -- rounded to a whole unit so per-frame reflows during a resize don't+        -- drift through ratio round trips.+        wanted+          | fixedA = whole dOld+          | otherwise = (newAvail - spacing) - whole (oldAvail - spacing - dOld)+        whole v = fromIntegral (round v :: Int)+        ratio'+          | fixedA == fixedB = ratio+          | oldAvail - spacing <= 0 || newAvail - spacing <= 0 = ratio+          | otherwise = lengthRatio spacing newAvail mA mB wanted+        (oldA, oldB, _) = splitBounds axis spacing oldR dOld+        (newA, newB, _) = splitBounds axis spacing newR (splitLength spacing newAvail mA mB ratio')++-- | Remove a pane. The sibling subtree absorbs its space. The tree comes back+-- unchanged if the pane does not exist, and @Nothing@ when removing it would+-- empty the tree.+treeRemovePane :: Word64 -> GridNode -> Maybe GridNode+treeRemovePane pid = foldGrid onPane onTabs onSplit+  where+    onPane p = if p == pid then Nothing else Just (Pane p)+    onTabs gid pids active+      | notElem pid pids = Just (PaneTabs gid pids active)+      | otherwise =+          let rest = filter (/= pid) pids+              nextAct+                | active /= pid = active+                | Just idx <- elemIndex pid pids+                , not (null rest) =+                    rest !! min (length rest - 1) idx+                | otherwise = fromMaybe active (listToMaybe rest)+           in normalizeTabs gid rest nextAct+    onSplit sid ax r0 ma mb = liftA2 (Split sid ax r0) ma mb <|> ma <|> mb++-- | Swap two panes by id (content follows the pane id).+treeSwapPanes :: Word64 -> Word64 -> GridNode -> GridNode+treeSwapPanes a b =+  let swap p = if p == a then b else if p == b then a else p+   in foldGrid (Pane . swap) (\gid pids act -> PaneTabs gid (forceWords (map swap pids)) (swap act)) Split++findTabGroup :: Word64 -> GridNode -> Maybe Word64+findTabGroup p =+  foldGrid+    (const Nothing)+    (\gid pids _ -> if elem p pids then Just gid else Nothing)+    (\_ _ _ l r -> l <|> r)++-- | Move a pane onto a drop target. Center drops swap or tab-merge the panes;+-- edge drops split the target pane with the given fresh split id and move the+-- dragged pane into the new child; top-level drops wrap the whole tree in a+-- new root split with the dragged pane on one side.+treeMovePane :: Word64 -> Word64 -> PaneDrop -> GridNode -> Maybe GridNode+treeMovePane moved splitId dt tree+  | not (paneExist tree moved) = Nothing+  | otherwise =+      case dt of+        DropSwap tgt -> onTarget tgt (Just (treeSwapPanes moved tgt tree))+        DropTab tgt mIdx ->+          let gid = fromMaybe splitId (findTabGroup tgt tree)+           in onTarget tgt (treeAddTab tgt gid mIdx moved <$> treeRemovePane moved tree)+        DropSplit tgt axis onA -> onTarget tgt (treeSplit tgt splitId axis onA moved <$> treeRemovePane moved tree)+        -- Removing the only pane leaves nothing to wrap.+        DropTop axis onA -> splitBeside splitId axis onA moved <$> treeRemovePane moved tree+  where+    -- A drop onto a pane needs another pane of the tree.+    onTarget tgt r = if tgt /= moved && paneExist tree tgt then r else Nothing++-- | Classify a drop point on a target pane into the 'PaneDrop' the drop+-- performs under 'CenterSwap'.+dropTargetForPane :: Rect -> V2 -> Word64 -> PaneDrop+dropTargetForPane = dropTargetForPaneWith CenterSwap++-- | Like 'dropTargetForPane', choosing whether a center drop swaps panes+-- ('CenterSwap') or merges them into a 'PaneTabs' stack ('CenterTab').+dropTargetForPaneWith :: CenterDropMode -> Rect -> V2 -> Word64 -> PaneDrop+dropTargetForPaneWith centerMode r (V2 mx my) tgt+  | not (rectNonEmpty r) = centerDrop+  | tx < 0.25 = DropSplit tgt AxisV True+  | tx > 0.75 = DropSplit tgt AxisV False+  | ty < 0.25 = DropSplit tgt AxisH True+  | ty > 0.75 = DropSplit tgt AxisH False+  | otherwise = centerDrop+  where+    centerDrop = case centerMode of+      CenterSwap -> DropSwap tgt+      CenterTab -> DropTab tgt Nothing+    tx = (mx - rectX r) / rectW r+    ty = (my - rectY r) / rectH r++-- | Squared Euclidean distance from a point to a rectangle (0 when inside).+{-# INLINE rectDistSq #-}+rectDistSq :: Rect -> V2 -> Float+rectDistSq (Rect x y w h) (V2 mx my) =+  let dx = max 0 (max (x - mx) (mx - (x + w)))+      dy = max 0 (max (y - my) (my - (y + h)))+   in dx * dx + dy * dy++-- | The laid-out pane whose region is closest to the point: the pane under+-- it, or across a gutter the pane on the nearer side. A pointer crossing a+-- gutter therefore always has a drop target, and 'dropTargetForPane' reads a+-- point just outside a region as that region's near edge. 'Nothing' only when+-- no pane has been laid out.+nearestPane :: Map Word64 Rect -> V2 -> Maybe (Word64, Rect)+nearestPane regions p = bestPane (Just . (`rectDistSq` p)) regions++-- | The laid-out pane with the least score, among those the scorer accepts;+-- the first in id order on a tie.+bestPane :: (Rect -> Maybe Float) -> Map Word64 Rect -> Maybe (Word64, Rect)+bestPane score regions =+  snd <$> listToMaybe (sortOn fst [(s, (p, r)) | (p, r) <- M.toList regions, rectNonEmpty r, Just s <- [score r]])++-- | Classify a drop point against the grid's outer boundary. If the pointer+-- sits inside the grid within @band@ px of an edge, return the 'DropTop'+-- target for that edge; otherwise 'Nothing'. Checked before pane-level drops+-- so the outermost edge always restructures the whole grid. A pointer outside+-- the grid is no target at all, so releasing there cancels the drag.+topLevelDropTarget :: Float -> Rect -> V2 -> Maybe PaneDrop+topLevelDropTarget band r@(Rect l t w h) p@(V2 x y)+  | not (rectContains r p) = Nothing+  | x <= l + band = Just (DropTop AxisV True)+  | x >= l + w - band = Just (DropTop AxisV False)+  | y <= t + band = Just (DropTop AxisH True)+  | y >= t + h - band = Just (DropTop AxisH False)+  | otherwise = Nothing++-- | A simulated drop, laid out: everything needed to draw the grid as the+-- drop will leave it without laying the tree out a second time.+data DropPreview = DropPreview+  { dpTree :: !GridNode+    -- ^ The tree the drop produces.+  , dpRegions :: !(Map Word64 Rect)+    -- ^ Its pane regions ('layoutNode'), the dragged pane's included.+  , dpDividers :: ![DividerInfo]+    -- ^ Its dividers ('layoutNode').+  , dpRect :: !Rect+    -- ^ The dragged pane's region.+  }+  deriving (Eq, Show)++-- | Preview a drop by simulating it ('treeMovePane') and laying out the+-- result ('layoutNode') in the grid rect. 'dpRect' is exactly where the+-- dragged pane lands. Other panes move too, so draw the rest of the grid+-- from 'dpTree'.+--+-- @spacing@ must be the gutter actually laid out between panes. The new+-- split, if any, gets @splitId@. With a @source@ rect (from the committed+-- layout) the pane keeps its extent along its old parent split's axis,+-- clamped to the destination's minima; center swaps ignore it. 'Nothing'+-- when the drop is impossible.+dropPreviewTreeSized :: Maybe Rect -> Float -> Float -> GridNode -> Word64 -> Word64 -> Rect -> PaneDrop -> Maybe DropPreview+dropPreviewTreeSized source minSize spacing tree moved splitId baseRect dt = do+  t' <- treeMovePane moved splitId dt tree+  let sized = case (source, dt) of+        (Just r, DropSplit _ axis onA) -> retain r axis onA t'+        (Just r, DropTop axis onA) -> retain r axis onA t'+        _ -> t'+      sourceAxis (Pane _) = Nothing+      sourceAxis (PaneTabs _ _ _) = Nothing+      sourceAxis (Split _ axis _ a b)+        | pinnedSide (== moved) a || pinnedSide (== moved) b = Just axis+        | otherwise = sourceAxis a <|> sourceAxis b+      retain r axis onA t =+        case find ((== splitId) . diSplitId) (snd (layoutNode minSize spacing t baseRect)) of+          Just d+            | let usable = mainLen axis (diRegion d) - spacing+            , usable > 0 ->+                let share = mainLen (fromMaybe axis (sourceAxis tree)) r / usable+                 in treeSetRatio splitId (clampRatio spacing d (if onA then share else 1 - share)) t+          _ -> t+      (regions, dividers) = layoutNode minSize spacing sized baseRect+  r <- M.lookup moved regions+  pure (DropPreview sized regions dividers r)
+ lib/NanoUI/Internal/Widgets/Table.hs view
@@ -0,0 +1,1243 @@+-- | Text tables described by Colonnade columns, with sorting, frozen panes,+-- column resizing/reordering, and row virtualization.+module NanoUI.Internal.Widgets.Table+  ( SortDir (..)+  , SortCol (..)+  , SortKey (..)+  , ColSize (..)+  , TableConfig (..)+  , TableResponse (..)+  , defaultTableConfig+  , table+  , tableWith+  , tableConfigured+  , table'+  , tableWith'+  , tableConfigured'+  , simpleTable+  , tableHiddenIndices+  , sortRows+  , Colonnade+  , Headed (..)+  , headed+  , headless+  , ToCell (..)+  , Cell (..)+  , textCell+  , cellWidget+  , cellSort+  , cellSortKey+  , cellSortNum+  , cellSortInt+  , cellWidthText+  )+where++import Colonnade (Colonnade, Headed (..), headed, headless)+import Colonnade.Encode qualified as Encode+import Control.Monad (forM, forM_, mfilter, unless, void, when)+import Control.Monad.Primitive (RealWorld)+import Control.Monad.ST (runST)+import Data.Char (isDigit)+import Data.Foldable (toList)+import Data.IORef (modifyIORef')+import Data.IntSet (IntSet)+import Data.IntSet qualified as IS+import Data.List (find)+import Data.List qualified as L+import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe)+import Data.Ord (Down (..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word64)+import Data.Primitive.PrimArray (PrimArray, copyMutablePrimArray, copyPrimArray, generatePrimArray, indexPrimArray, newPrimArray, primArrayFromList, readPrimArray, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)+import Data.Primitive.SmallArray (SmallArray, SmallMutableArray, emptySmallArray, indexSmallArray, mapSmallArray', newSmallArray, sizeofSmallArray, smallArrayFromList, smallArrayFromListN, unsafeFreezeSmallArray, writeSmallArray)+import Data.Primitive.Types (Prim)+import Data.Vector qualified as V+import Data.Vector.Mutable qualified as MV+import NanoUI.Internal.Context (Context (..), InteractionState (..), ScrollMetrics (..), getPrevRect, readScrollMetrics, recordLayoutRead, getPrevClipRect, getScrollOffset2D, getStore, intKey, linkScrollAxes, modifyInteraction, writeSlot, writeSlots)+import NanoUI.Internal.Var (Binding (..), bindVarOn, useVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Derived (TableDerived (..), Opaque (..), SortCol (..), SortDir (..), SortKey (..), tableCache)+import NanoUI.Internal.Font (FontMetrics (..), ScrollBarSlot (..), scrollBarGutter, tableCellInset, lineWidthIO)+import NanoUI.Internal.Input (Input (..), MouseButton (..), Pressable (..), UiCursorKind (..))+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askInput, freshWidget, lastRect, nextId, liftIO, scope, withKey)+import NanoUI.Internal.Store (SlotWrites, WidgetStore, eqByPtr, fieldInt, fieldTableState, lookupSlot, ptrEq, slotWrite, specKey)+import NanoUI.Internal.Store.Slots (slotScrollRange)+import NanoUI.Internal.Store.Types (TableState (..))+import NanoUI.Internal.Style (AlignX (..), AlignY (..), Direction (..), FontVariant (..), Layout (..), Sizing (..), defaultLayout, fillH, fillW, minW, tight)+import Data.Bits ((.|.))+import Data.String (IsString (..))+import NanoUI.Internal.Types (Rect (..), clamp, rectH, rectW, v2X, V2 (..), rectContains, noLimit)+import NanoUI.Internal.WidgetText (buttonFlagTable, rowStripe, stripeBits, tableHeaderPadX)+import qualified NanoUI.Internal.StyleBits as SB+import NanoUI.Internal.Widgets.Button (buttonContentStyled)+import NanoUI.Internal.Widgets.Behavior (Reorder (..), useReorder)+import NanoUI.Internal.Widgets.Combinators (buttonStyledEx, readDerived, writeDerived)+import NanoUI.Internal.Widgets.Layout (column', panel', row', scrollAreaIdConfigured, separator, spacer)+import NanoUI.Internal.Layout.ScrollGeometry (defaultScrollConfig, scroll2DConfig, scrollHorizontalHidden, scrollVerticalHidden)+import NanoUI.Internal.Widgets.Node++-- | Size to content, share spare space, or request a fixed logical-pixel width.+data ColSize = ColContent | ColStretch | ColFixed Float+  deriving (Eq, Show)++-- | Frozen leading row/column counts, column sizing, and hidden source-column+-- indices. Column indices are zero-based; unspecified sizes use content sizing.+data TableConfig = TableConfig+  { tableFreezeCols :: {-# UNPACK #-} !Int+  , tableFreezeRows :: {-# UNPACK #-} !Int+  , tableColSizes :: ![ColSize]+  , tableHidden :: !IntSet+  -- ^ The columns hidden on the table's first frame. From then on the table+  -- keeps its own set, which a right-click on a header changes, and a later+  -- change here is ignored.+  , tableSqueeze :: !Bool+  -- ^ Squeeze instead of scroll: when the table is narrower than the sum of+  -- its pinned widths (fixed columns, content floors, dragged widths), the+  -- unfrozen columns shrink in proportion (never below the 40-pixel column+  -- floor) rather than surfacing a horizontal scrollbar. A stretch column takes+  -- part with a bounded share, frozen columns keep their widths, and the+  -- vertical scrollbar's lane comes off the room first. Off by default: a table+  -- too wide for its pane keeps its sideways scroll.+  , tableBare :: !Bool+  -- ^ Omit the outer panel border and background well so a table embedded+  -- inside a pane blends directly onto the pane's surface (default 'False').+  }+  deriving (Eq, Show)++-- | No frozen or hidden rows/columns and content-sized columns.+defaultTableConfig :: TableConfig+defaultTableConfig = TableConfig 0 0 [] IS.empty False False++-- | Widget interaction plus updated sort, display order, and hidden-column set.+-- Indices refer to the original column definitions.+data TableResponse = TableResponse+  { tableWidgetResponse :: !Response+  , tableSort :: !SortCol+  , tableColOrder :: ![Int]+  , tableHiddenCols :: !IntSet+  }+  deriving (Eq, Show)++instance HasResponse TableResponse where+  {-# INLINE toResponse #-}+  toResponse = tableWidgetResponse++-- | Hidden source-column indices in ascending order.+tableHiddenIndices :: TableResponse -> [Int]+tableHiddenIndices = IS.toAscList . tableHiddenCols++clampSortCol :: Int -> SortCol -> SortCol+clampSortCol n (SortCol idx dir) = SortCol (clamp 0 (max 0 (n - 1)) idx) dir++-- The sort mark of column @idx@ in its header's style ('SB.headerSortMark',+-- read back by 'NanoUI.Internal.WidgetText.tableSortMarkOf').+sortMarkStyle :: SortCol -> Int -> Word64+sortMarkStyle sort idx+  | sortColIndex sort /= idx = 0+  | sortColDir sort == SortDesc = SB.placeField SB.headerSortMark 2+  | otherwise = SB.placeField SB.headerSortMark 1++minColW :: Float+minColW = 40++-- | The sort the headers show, as an int on the table's container: twice the+-- column, plus one when descending. The headers show the sort only through+-- their style, which no diff covers, so a change of this slot repaints the+-- table.+{-# INLINE sortShownCode #-}+sortShownCode :: SortCol -> Int+sortShownCode sort = 2 * sortColIndex sort + fromEnum (sortColDir sort == SortDesc)++-- | What one table cell (or header) shows.+data Cell = Cell+  { cellKey  :: !(Maybe SortKey)+  -- ^ Sort key; 'Nothing' = unsortable by this cell (unless 'cellText' is set).+  , cellText :: !Text+  -- ^ Measured for width; drawn when there is no widget view.+  , cellView :: Maybe (NanoUI ())+  -- ^ Replaces drawn text when present. Built only for visible rows.+  }++-- | Anything a 'Colonnade' column can encode to. Pure and user-implementable.+class ToCell c where+  toCell :: c -> Cell++instance ToCell Text where+  {-# INLINE toCell #-}+  toCell = textCell++instance ToCell Cell where+  {-# INLINE toCell #-}+  toCell = id++instance ToCell (NanoUI ()) where+  {-# INLINE toCell #-}+  toCell = cellWidget++instance IsString Cell where+  {-# INLINE fromString #-}+  fromString = textCell . T.pack++-- | Plain text cell (sortable by its text).+textCell :: Text -> Cell+textCell t = Cell (Just (SortText t)) t Nothing++-- | Arbitrary interactive widget cell (unsortable by default).+cellWidget :: NanoUI () -> Cell+cellWidget w = Cell Nothing T.empty (Just w)++-- | Attach a text sort key to a cell. If the cell's 'cellText' is empty,+-- also populates 'cellText' with the key so column width can be estimated.+cellSort :: Text -> Cell -> Cell+cellSort k c = c { cellKey = Just (SortText k), cellText = if T.null (cellText c) then k else cellText c }++-- | Attach an explicit 'SortKey' ('SortText', 'SortNum', or 'SortInt') to a cell.+cellSortKey :: SortKey -> Cell -> Cell+cellSortKey k c = c { cellKey = Just k }++-- | Attach a floating-point numeric sort key ('SortNum') to a cell.+cellSortNum :: RealFloat a => a -> Cell -> Cell+cellSortNum x c =+  let !d+        | isNaN x = 0 / 0+        | isInfinite x = if x < 0 then -1 / 0 else 1 / 0+        | otherwise = realToFrac x+   in c { cellKey = Just (SortNum d) }++-- | Attach a 64-bit integer sort key ('SortInt') to a cell.+cellSortInt :: Integral a => a -> Cell -> Cell+cellSortInt n c = c { cellKey = Just (SortInt (fromIntegral n)) }++-- | Attach an explicit text label for column width estimation.+cellWidthText :: Text -> Cell -> Cell+cellWidthText t c = c { cellText = t }++-- | Stable sort by the selected column's sort key (or text).+-- Out-of-range or unsortable column indices retain input order: an+-- unsortable column's keys are all empty, so the stable sort keeps it.+sortRows :: (Foldable f, ToCell c) => Colonnade Headed row c -> SortCol -> f row -> [row]+sortRows cols sort inputRows =+  let rows = toList inputRows+      n = V.length (Encode.getColonnade cols)+      idx = sortColIndex (clampSortCol n sort)+   in case Encode.getColonnade cols V.!? idx of+        Nothing -> rows+        Just col ->+          let key r = let c = toCell (Encode.oneColonnadeEncode col r) in fromMaybe (SortText (cellText c)) (cellKey c)+           in case sortColDir sort of+                SortAsc -> L.sortOn key rows+                SortDesc -> L.sortOn (Down . key) rows++isNumericCell :: Text -> Bool+isNumericCell txt =+  let s = T.strip txt+      digits = case T.uncons s of+        Just (c, rest) | c == '-' || c == '+' -> rest+        _ -> s+   in not (T.null digits) && T.all isDigit digits++samePtr :: Opaque -> b -> Bool+samePtr (Opaque a) = ptrEq a++-- | The table's derived data for @rows@ under @sort@: the cached data when+-- the rows and columns are the ones it was derived from, else derived again+-- from what it holds. The rows and columns are evaluated first, so the+-- pointers kept and compared are their values, whether or not the code that+-- derives the data evaluates them before keeping them.+tableDerived :: (Foldable f, ToCell c) => Context -> Int -> Colonnade Headed row c -> f row -> SortCol -> IO TableDerived+tableDerived ctx key !cols !rows sort = do+  cached <- readDerived tableCache ctx key+  let encoders = Encode.getColonnade cols+      hdrs = V.map (cellText . toCell . getHeaded . Encode.oneColonnadeHead) encoders+  derived <- case cached of+    Just d | samePtr (tdRows d) rows && samePtr (tdCols d) cols -> pure d+    _ -> rederive ctx cols rows sort hdrs (mfilter ((== hdrs) . tdHeaders) cached)+  let !resorted+        | tdSort derived == sort = derived+        | otherwise = derived {tdSort = sort, tdOrder = orderFor sort (tdKeys derived)}+  case cached of+    Just d | samePtr (Opaque d) resorted -> pure ()+    _ -> writeDerived tableCache ctx key resorted+  pure resorted++-- | Row indices sorted by the sort column's key or text. An unsortable+-- column's keys are all empty, so the stable sort keeps the input order.+orderFor :: SortCol -> SmallArray (V.Vector SortKey) -> PrimArray Int+orderFor sort keys = sortIndices (sortColDir sort) (mapSmallArray' (sortKey sort) keys)++sortKey :: SortCol -> V.Vector SortKey -> SortKey+sortKey sort row = fromMaybe (SortText T.empty) (row V.!? sortColIndex sort)++sameSortKey :: SortKey -> SortKey -> Bool+sameSortKey a b = case (a, b) of+  (SortText x, SortText y) -> eqByPtr x y+  (SortNum x, SortNum y) -> (isNaN x && isNaN y) || x == y+  (SortInt x, SortInt y) -> x == y+  _ -> False++-- | A row's cells, each evaluated, and their sort keys. Marks in @sortable@+-- each column with a key or text, and in @views@ each column with a widget+-- view.+encodeRow :: ToCell c => SmallMutableArray RealWorld Bool -> SmallMutableArray RealWorld Bool -> V.Vector (Encode.OneColonnade Headed row c) -> row -> IO (V.Vector Text, V.Vector SortKey)+encodeRow sortable views encoders r = do+  let k = V.length encoders+  txts <- MV.unsafeNew k+  keys <- MV.unsafeNew k+  let fill !j+        | j >= k = pure ()+        | otherwise = do+            let !c = toCell (Encode.oneColonnadeEncode (V.unsafeIndex encoders j) r)+                !t = cellText c+                !ky = fromMaybe (SortText t) (cellKey c)+            MV.unsafeWrite txts j t+            MV.unsafeWrite keys j ky+            when (isJust (cellKey c) || not (T.null t)) (writeSmallArray sortable j True)+            when (isJust (cellView c)) (writeSmallArray views j True)+            fill (j + 1)+  fill 0+  !vTxts <- V.unsafeFreeze txts+  !vKeys <- V.unsafeFreeze keys+  pure (vTxts, vKeys)++-- | The first cell at which two rows differ under @eq@, or -1 when equal.+firstDiffBy :: (a -> a -> Bool) -> V.Vector a -> V.Vector a -> Int+firstDiffBy eq a b = go 0+  where+    k = min (V.length a) (V.length b)+    go !j+      | j >= k = if V.length a == V.length b then -1 else j+      | eq (V.unsafeIndex a j) (V.unsafeIndex b j) = go (j + 1)+      | otherwise = j++-- | The first cell at which two rows differ, or -1 when they are the same.+firstDiff :: V.Vector Text -> V.Vector Text -> Int+firstDiff = firstDiffBy eqByPtr++firstKeyDiff :: V.Vector SortKey -> V.Vector SortKey -> Int+firstKeyDiff = firstDiffBy sameSortKey++-- | Check whether row @r@'s encoded text and sort keys match @oldTxt@ and+-- @oldKey@ without allocating intermediate vectors or 'SortText' wrappers.+-- Returns 'True' when every cell matches (and @sortable@/@views@ flags are+-- already satisfied by @oldSortable@/@oldViews@), else 'False'.+rowMatchesOld ::+  ToCell c =>+  V.Vector (Encode.OneColonnade Headed row c) ->+  SmallArray Bool ->+  SmallArray Bool ->+  V.Vector Text ->+  V.Vector SortKey ->+  row ->+  Bool+rowMatchesOld encoders oldSortable oldViews oldTxt oldKey r =+  V.length oldTxt == k && V.length oldKey == k && go 0+  where+    !k = V.length encoders+    go !j+      | j >= k = True+      | otherwise =+          let !c = toCell (Encode.oneColonnadeEncode (V.unsafeIndex encoders j) r)+              !t = cellText c+              !ot = V.unsafeIndex oldTxt j+              !ok = V.unsafeIndex oldKey j+              !sameTxt = eqByPtr t ot+              !sameKey = case cellKey c of+                Nothing -> case ok of+                  SortText kt -> eqByPtr t kt+                  _ -> False+                Just ky -> sameSortKey ky ok+              !sortOk = (not (isJust (cellKey c)) && T.null t) || smallAt oldSortable j False+              !viewOk = isNothing (cellView c) || smallAt oldViews j False+           in sameTxt && sameKey && sortOk && viewOk && go (j + 1)++-- | Derive from @rows@, reusing @old@ (derived under the same headers):+-- each row that is the same object under the same columns keeps its text,+-- each cell whose text is unchanged keeps its width, and the order stands+-- while no sort key changed. Widths measured with other fonts are kept only+-- while no text changed.+rederive :: (Foldable f, ToCell c) => Context -> Colonnade Headed row c -> f row -> SortCol -> V.Vector Text -> Maybe TableDerived -> IO TableDerived+rederive Context {ctxFontMetrics = fm, ctxMonoFontMetrics = mono} cols rows sort hdrs old = do+  -- Bound evaluated, so the loops below do not enter them again.+  let !rowList = toList rows+      !n = length rowList+      !c = V.length hdrs+      !oldN = maybe 0 (sizeofSmallArray . tdEncoded) old+      !oldObjs = maybe emptySmallArray tdRowObjs old+      !oldEnc = maybe emptySmallArray tdEncoded old+      !oldKeys = maybe emptySmallArray tdKeys old+      !sameCols = any (\d -> samePtr (tdCols d) cols) old+      !encoders = Encode.getColonnade cols+  -- Fast path: when reusing a same-length table, verify rows directly against+  -- the cached vectors without allocating row vectors or scratch arrays. Only+  -- if a row actually differs do we materialize the mutable arrays from that+  -- point forward.+  objsM <- newSmallArray n (Opaque ())+  let scanUnchanged d !_ [] = do+        objs <- unsafeFreezeSmallArray objsM+        pure (Right (d {tdRows = Opaque rows, tdCols = Opaque cols, tdRowObjs = objs}))+      scanUnchanged d !i (!r : rs) = do+        let !o = indexSmallArray oldObjs i+        if sameCols && samePtr o r+          then writeSmallArray objsM i o >> scanUnchanged d (i + 1) rs+          else+            if rowMatchesOld encoders (tdSortable d) (tdViews d) (indexSmallArray oldEnc i) (indexSmallArray oldKeys i) r+              then writeSmallArray objsM i (Opaque r) >> scanUnchanged d (i + 1) rs+              else pure (Left (i, r : rs))+  fastRes <- case old of+    Just d | n == oldN -> scanUnchanged d 0 rowList+    _ -> pure (Left (0, rowList))+  case fastRes of+    Right reused -> pure reused+    Left (!startIdx, !startRows) -> do+      encM <- newSmallArray n V.empty+      keysM <- newSmallArray n V.empty+      changedM <- newPrimArray n+      diffM <- newPrimArray n+      sortableM <- newSmallArray c False+      viewsM <- newSmallArray c False+      case old of+        Just d -> forM_ [0 .. c - 1] $ \j -> do+          writeSmallArray sortableM j (smallAt (tdSortable d) j False)+          writeSmallArray viewsM j (smallAt (tdViews d) j False)+        Nothing -> pure ()+      let copyPrefix !i+            | i >= startIdx = pure ()+            | otherwise = do+                writeSmallArray encM i (indexSmallArray oldEnc i)+                writeSmallArray keysM i (indexSmallArray oldKeys i)+                copyPrefix (i + 1)+      copyPrefix 0+      let store i o e k = writeSmallArray objsM i o >> writeSmallArray encM i e >> writeSmallArray keysM i k+          encodeNew = encodeRow sortableM viewsM encoders+          note k i d = writePrimArray changedM k i >> writePrimArray diffM k d+          -- Lists the rows whose text changed or is new, each with its first+          -- changed cell (0 for a new row), and returns their count. Rows are+          -- compared evaluated: a list's elements are often fresh thunks over the+          -- same objects. Old entries are read strictly, so kept text does not+          -- hold on to last frame's arrays.+          walk !_ !k [] = pure k+          walk !i !k (!r : rs)+            | i < oldN = do+                let !o = indexSmallArray oldObjs i+                    !e = indexSmallArray oldEnc i+                    !ky = indexSmallArray oldKeys i+                if sameCols && samePtr o r+                  then store i o e ky >> walk (i + 1) k rs+                  else do+                    (!e', !ky') <- encodeNew r+                    let !d = firstDiff e' e+                        !kd = firstKeyDiff ky' ky+                        !diffCol = case (d < 0, kd < 0) of+                          (True, True) -> -1+                          (False, True) -> d+                          (True, False) -> kd+                          (False, False) -> min d kd+                    if diffCol < 0+                      then store i (Opaque r) e ky >> walk (i + 1) k rs+                      else store i (Opaque r) (if d < 0 then e else e') ky' >> note k i diffCol >> walk (i + 1) (k + 1) rs+            | otherwise = do+                (!e', !ky') <- encodeNew r+                store i (Opaque r) e' ky' >> note k i 0 >> walk (i + 1) (k + 1) rs+      nChanged <- walk startIdx (0 :: Int) startRows+      objs <- unsafeFreezeSmallArray objsM+      sortable <- unsafeFreezeSmallArray sortableM+      views <- unsafeFreezeSmallArray viewsM+      case old of+        Just d | n == oldN && nChanged == 0 -> pure d {tdRows = Opaque rows, tdCols = Opaque cols, tdRowObjs = objs, tdSortable = sortable, tdViews = views}+        _ -> do+          encoded <- unsafeFreezeSmallArray encM+          keys <- unsafeFreezeSmallArray keysM+          changedRows <- unsafeFreezePrimArray changedM+          firstDiffs <- unsafeFreezePrimArray diffM+          let !cellPadX = 2 * tableCellInset+              cell r i = indexSmallArray encoded r V.! i+              oldCell r i = indexSmallArray oldEnc r V.! i+              -- Whether cell i of changed row r, first changed at cell f, is+              -- kept: cells before f are, f is not, later ones are compared.+              keptCell !r !f !i = r < oldN && (i < f || (i > f && eqByPtr (oldCell r i) (cell r i)))+              -- The first changed row r, first changed at f, with p r f; or -1.+              {-# INLINE findChanged #-}+              findChanged p = go 0+                where+                  go !j+                    | j >= nChanged = -1+                    | p r (indexPrimArray firstDiffs j) = r+                    | otherwise = go (j + 1)+                    where+                      r = indexPrimArray changedRows j+              -- Each column's row whose cell is not numeric, or -1. The old row+              -- stands while its cell still is not; a column whose old cells were+              -- all numeric looks only at changed rows, from their first changed+              -- cell; any other column is scanned to its first cell that is not,+              -- as without old data.+              !textRows = generatePrimArray c $ \i ->+                let isText r = not (isNumericCell (cell r i))+                    scan !r+                      | r >= n = -1+                      | isText r = r+                      | otherwise = scan (r + 1)+                 in case old of+                      Just d+                        | w < 0 -> findChanged (\r f -> not (r < oldN && i < f) && isText r)+                        | w < n && isText w -> w+                        where+                          w = indexPrimArray (tdTextRow d) i+                      _ -> scan 0+              isNum i = n > 0 && indexPrimArray textRows i < 0+              -- The old data, if measured with these fonts.+              prior = mfilter (\d -> samePtr (tdFont d) fm && samePtr (tdMonoFont d) mono) old+          cellWM <- newPrimArray (n * c)+          hdrWM <- newPrimArray c+          forM_ [0 .. c - 1] $ \i -> do+            let font = if isNum i then mono else fm+                measure !r = do+                  let !t = cell r i+                  writePrimArray cellWM (i * n + r) . (+ cellPadX) =<< lineWidthIO font t+            case prior of+              -- The column's font is unchanged, so its cells whose text is+              -- unchanged keep their widths, in changed rows too.+              Just d | indexSmallArray (tdNumeric d) i == isNum i -> do+                copyPrimArray cellWM (i * n) (tdCellW d) (i * oldN) (min n oldN)+                let remeasure !j = when (j < nChanged) $ do+                      let !r = indexPrimArray changedRows j+                      unless (keptCell r (indexPrimArray firstDiffs j) i) (measure r)+                      remeasure (j + 1)+                remeasure 0+              _ -> mapM_ measure [0 .. n - 1]+            -- As the header shows it, with the sort mark's lane beside it.+            writePrimArray hdrWM i . (+ tableHeaderPadX) =<< lineWidthIO fm (hdrs V.! i)+          cellWs <- unsafeFreezePrimArray cellWM+          hdrWs <- unsafeFreezePrimArray hdrWM+          let widest i !r !w = if r >= n then w else widest i (r + 1) (max w (indexPrimArray cellWs (i * n + r)))+              widths = generatePrimArray c $ \i ->+                let hdrW = indexPrimArray hdrWs i in if n == 0 then hdrW else max hdrW (widest i 0 minColW)+          -- The order stands while no row came or went and no sort key changed.+          let keysKept d =+                let key = sortKey (tdSort d)+                    s = sortColIndex (tdSort d)+                    keyChanged r f = s == f || (s > f && not (sameSortKey (key (indexSmallArray oldKeys r)) (key (indexSmallArray keys r))))+                 in n == oldN && findChanged keyChanged < 0+              (sort', order) = case old of+                Just d | keysKept d -> (tdSort d, tdOrder d)+                _ -> (sort, orderFor sort keys)+          pure+            TableDerived+              { tdRows = Opaque rows+              , tdCols = Opaque cols+              , tdFont = Opaque fm+              , tdMonoFont = Opaque mono+              , tdRowObjs = objs+              , tdHeaders = hdrs+              , tdEncoded = encoded+              , tdKeys = keys+              , tdSortable = sortable+              , tdViews = views+              , tdCellW = cellWs+              , tdTextRow = textRows+              , tdWidths = widths+              , tdNumeric = smallArrayFromListN c (map isNum [0 .. c - 1])+              , tdSort = sort'+              , tdOrder = order+              }++-- | The sort after a click on column @clicked@: the same column flips its+-- direction, another sorts ascending.+nextSortCol :: SortCol -> Int -> SortCol+nextSortCol cur clicked+  | clicked == sortColIndex cur = SortCol clicked (if sortColDir cur == SortAsc then SortDesc else SortAsc)+  | otherwise = SortCol clicked SortAsc++-- Column metadata by source column index, or the fallback when out of range.+{-# INLINE primAt #-}+primAt :: Prim a => PrimArray a -> Int -> a -> a+primAt xs i fallback = if i >= 0 && i < sizeofPrimArray xs then indexPrimArray xs i else fallback++{-# INLINE smallAt #-}+smallAt :: SmallArray a -> Int -> a -> a+smallAt xs i fallback = if i >= 0 && i < sizeofSmallArray xs then indexSmallArray xs i else fallback++-- Initial column width before any user drag: the declared fixed width, else the+-- content minimum so undragged cells do not wrap. Once dragged, a column can+-- shrink down to 'minColW'.+colFloor :: SmallArray ColSize -> PrimArray Float -> Int -> Float+colFloor sizes contentWs i = case smallAt sizes i ColContent of+  ColFixed f -> max minColW f+  ColStretch -> minColW+  ColContent -> max minColW (primAt contentWs i minColW)++flatLayout :: Layout+flatLayout = tight defaultLayout {layoutGap = 0}++tableRowMinH :: Float+tableRowMinH = 28++textCellLayout, numCellLayout, numHeaderLayout :: Layout+textCellLayout =+  (tight defaultLayout)+    { layoutWidth = Grow 1+    , layoutHeight = Grow 1+    , layoutAlignX = AlignStart+    , layoutAlignY = AlignMiddle+    , layoutMinH = tableRowMinH+    , layoutFontVariant = FontRegular+    }+numCellLayout =+  textCellLayout+    { layoutAlignX = AlignEnd+    , layoutFontVariant = FontMono+    }+numHeaderLayout =+  numCellLayout+    { layoutFontVariant = FontRegular+    }++-- | Column @i@'s box: its stored width (never under 'minColW') once it has+-- one, else a share of the spare width when the columns fill the table, else+-- its initial floor. Columns stretch to the row height so every cell's+-- background and borders span the full row even when one cell wraps.+--+-- A stretch column is the table's slack: its minimum is an explicit zero,+-- so it compresses (under a vertical scrollbar's lane, say, which narrows+-- the viewport by the lane's width) rather than reporting its content as a+-- minimum that surfaces a horizontal bar under a table that fits the+-- scroller's full width.+--+-- Under the squeeze ('tableSqueeze') the box instead grows by its pinned+-- width (its dragged width once it has one, else its floor) up to that+-- width, so a table narrower than their sum shrinks the columns in+-- proportion to it, none under 'minColW', and scrolls sideways only once+-- every column sits at that floor. A stretch column takes part with a+-- bounded share, which keeps fixed columns from crushing it to nothing, and+-- has no cap, so it takes what the others leave; so do the content columns+-- of a table that fills its width with no stretch column.+colBoxLayout :: Bool -> Bool -> Bool -> SmallArray ColSize -> PrimArray Float -> PrimArray Float -> Int -> Layout+colBoxLayout squeeze fillInner hasStretch sizes contentWs stored i+  | squeeze = box {layoutWidth = Grow pinned, layoutMinW = minColW, layoutMaxW = if grows then noLimit else pinned}+  | saved > 0 = fixed (max minColW saved)+  | grows, ColStretch <- size = minW 0 box {layoutWidth = Grow 1}+  | grows = box {layoutWidth = Grow 1}+  | otherwise = fixed floorW+  where+    saved = primAt stored i 0+    floorW = colFloor sizes contentWs i+    size = smallAt sizes i ColContent+    -- Whether the column takes the spare width once it has no stored width.+    grows = saved <= 0 && fillInner && (size == ColStretch || size == ColContent && not hasStretch)+    pinned+      | saved > 0 = max minColW saved+      | ColStretch <- size = max minColW (min 120 (primAt contentWs i minColW))+      | otherwise = floorW+    box = (fillH flatLayout) {layoutMinW = floorW}+    fixed w = box {layoutWidth = Fixed w, layoutMinW = w, layoutMaxW = w}++-- | Sortable table with resizable, reorderable columns, with sort state bound+-- to a 'Var': a header click updates it in place. @key@ distinguishes tables+-- in one scope, and the columns are a colonnade over @row@. A right-click on+-- a header hides its column while another column stays in view, and a "Show+-- all columns" button above the table then brings them all back.+--+-- > table "files" cols files app.sort+{-# INLINE table #-}+table :: (Foldable f, ToCell c) => Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI ()+table = tableConfigured defaultTableConfig id++-- | 'table' returning the 'TableResponse': the column order and hidden+-- columns along with the response.+{-# INLINE table' #-}+table' :: (Foldable f, ToCell c) => Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI TableResponse+table' = tableConfigured' defaultTableConfig id++-- | 'table' with a layout modifier.+{-# INLINE tableWith #-}+tableWith :: (Foldable f, ToCell c) => (Layout -> Layout) -> Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI ()+tableWith = tableConfigured defaultTableConfig++-- | 'tableWith' returning the 'TableResponse'.+{-# INLINE tableWith' #-}+tableWith' :: (Foldable f, ToCell c) => (Layout -> Layout) -> Text -> Colonnade Headed row c -> f row -> Var SortCol -> NanoUI TableResponse+tableWith' = tableConfigured' defaultTableConfig++-- | A table of text rows under the given headers, sorted by the first column+-- until a header click sorts by another. The sort is kept in a positional+-- 'useVar'. Its columns are built again on every pass, so every row is read+-- again too; for many rows, use 'table' with columns kept outside the view.+simpleTable :: Foldable f => [Text] -> f [Text] -> NanoUI TableResponse+simpleTable headers rows = do+  sortVar <- useVar (SortCol 0 SortAsc)+  -- The cells are read from the rows themselves, not from a copy of each.+  let cols = mconcat [headed h (fromMaybe "" . listToMaybe . drop i) | (i, h) <- zip [0 ..] headers]+  -- A positional scope, like the sort, so sibling simple tables keep apart.+  scope (tableConfigured' defaultTableConfig id "simple" cols rows sortVar)+++-- | 'tableWith' with column sizes, frozen rows and columns, and initially+-- hidden columns.+{-# INLINE tableConfigured #-}+tableConfigured ::+  (Foldable f, ToCell c) =>+  TableConfig ->+  (Layout -> Layout) ->+  Text ->+  Colonnade Headed row c ->+  f row ->+  Var SortCol ->+  NanoUI ()+tableConfigured cfg f key cols rows v = void (tableConfigured' cfg f key cols rows v)++-- | 'tableConfigured' returning the 'TableResponse'. The rows are ordered+-- before a header click is read, so a click that changes the sort runs the+-- view again to show them in the new order.+tableConfigured' ::+  (Foldable f, ToCell c) =>+  TableConfig ->+  (Layout -> Layout) ->+  Text ->+  Colonnade Headed row c ->+  f row ->+  Var SortCol ->+  NanoUI TableResponse+tableConfigured' cfg f key cols rows v =+  bindVarOn Conservative tableSort v (tableCore cfg f key cols rows)++-- | The state of a table of @n@ columns under @stateKey@ in @st@.+readTableState :: TableConfig -> Int -> Int -> WidgetStore -> TableState+readTableState cfg n stateKey st = case lookupSlot fieldTableState stateKey st of+  Nothing -> TableState [0 .. n - 1] (replicate n 0) (tableHidden cfg) (-1) 0 0+  Just ts -> ts {tsOrder = normalizeOrder n (tsOrder ts), tsWidths = take n (tsWidths ts ++ repeat 0)}++-- | Write @ts@ under @stateKey@ when it differs from the stored state.+writeTableState :: Int -> TableState -> SlotWrites+writeTableState = slotWrite fieldTableState++-- | The column widths this frame lays out: @ts@'s, with the column a held+-- resize drags set to its start width plus the pointer's travel, never under+-- 'minColW'.+resizedWidths :: Input -> TableState -> [Float]+resizedWidths inp ts+  | col >= 0 && heldIn MouseLeft inp =+      setAt col (max minColW (tsResizeW ts + v2X (inputMousePos inp) - tsResizeX ts)) (tsWidths ts)+  | otherwise = tsWidths ts+  where+    col = tsResizeCol ts++-- | Where a table's columns go this frame: which show, in which pane, and+-- each one's box.+data TableGeometry = TableGeometry+  { tgOuter :: !Layout+  -- ^ The layout of the column holding the table.+  , tgVisible :: ![Int]+  -- ^ The shown columns in display order.+  , tgFrozen :: ![Int]+  -- ^ The shown columns of the frozen pane.+  , tgUnfrozen :: ![Int]+  -- ^ The shown columns of the scrolling pane.+  , tgPinned :: !Int+  -- ^ Rows pinned under the header.+  , tgScrolled :: !Int+  -- ^ Rows in the body below them.+  , tgFill :: !Bool+  -- ^ The columns fill the table's width: one stretches or the table grows.+  , tgRowH :: !Float+  , tgColBoxes :: !(SmallArray Layout)+  -- ^ Each source column's box ('colBoxLayout').+  }++-- | The geometry of a table of @n@ columns and @nRows@ rows under config+-- @cfg@ and layout modifier @f@, its columns sized @widths@ this frame.+tableGeometry :: TableConfig -> (Layout -> Layout) -> FontMetrics -> Int -> Int -> SmallArray ColSize -> PrimArray Float -> [Float] -> TableState -> TableGeometry+tableGeometry cfg f fm n nRows sizes contentWs widths ts =+  TableGeometry+    { tgOuter = outerLayout+    , tgVisible = vis+    , tgFrozen = frozenIdx+    , tgUnfrozen = drop freezeN vis+    , tgPinned = pinnedN+    , tgScrolled = nRows - pinnedN+    , tgFill = fillInner+    , tgRowH = max tableRowMinH (fmLineHeight fm + 6)+    , tgColBoxes =+        smallArrayFromList+          [ colBoxLayout (squeezed i) fillInner hasStretch sizes contentWs widthsArr i+          | i <- [0 .. n - 1]+          ]+    }+  where+    widthsArr = primArrayFromList widths+    outerLayout = f (fillW flatLayout)+    hidden = tsHidden ts+    vis = filter (`IS.notMember` hidden) (tsOrder ts)+    hasStretch = any (\i -> smallAt sizes i ColContent == ColStretch) vis+    freezeN = clamp 0 (length vis) (tableFreezeCols cfg)+    frozenIdx = take freezeN vis+    pinnedN = clamp 0 nRows (tableFreezeRows cfg)+    fillInner =+      hasStretch || case layoutWidth outerLayout of+        Grow _ -> True+        _ -> False+    -- Under the squeeze the unfrozen columns shrink to the body in the same+    -- frame; frozen columns keep their widths.+    squeezed i = tableSqueeze cfg && i `notElem` frozenIdx++-- | The widgets a table's panes are made of: the body scroller, the bar-less+-- header scroller that follows it, and the panel holding both panes.+data TableIds = TableIds+  { tidBody :: !WidgetId+  , tidHeader :: !WidgetId+  , tidPanel :: !WidgetId+  }++-- | A table's panel: the frozen pane and the scrolling pane, each a header+-- row, the pinned rows and the body's rows in view. Returns each shown+-- column's header response.+tablePanes ::+  ToCell c =>+  Bool ->+  Context ->+  TableIds ->+  V.Vector (Encode.OneColonnade Headed row c) ->+  V.Vector row ->+  TableDerived ->+  TableGeometry ->+  SortCol ->+  Bool ->+  NanoUI [(Int, Response)]+tablePanes+  bare+  ctx+  ids+  encoders+  rowsVec+  TableDerived {tdEncoded = encoded, tdSortable = sortable, tdViews = views, tdNumeric = numeric, tdOrder = sorted}+  TableGeometry {tgFrozen = frozenIdx, tgUnfrozen = unfrozenIdx, tgPinned = pinnedN, tgScrolled = scrollN, tgFill = fillInner, tgRowH = rowH, tgColBoxes = colBoxes}+  sort0+  hasVertBar =+  (if bare then container NodeContainer paneRoot else panel' paneRoot) $ do+    tagContainer (tidPanel ids)+    row' (paneRoot {layoutGap = 0}) $ do+      frozenHs <-+        if null frozenIdx+          then pure []+          else zip frozenIdx <$> frozenPane+      unless (null frozenIdx || null unfrozenIdx) $ void separator+      unfrozenHs <-+        if null unfrozenIdx then pure [] else zip unfrozenIdx <$> unfrozenPane+      pure (frozenHs ++ unfrozenHs)+  where+    vWid = tidBody ids+    hWid = tidHeader ids+    rowStep = rowH + 1+    fillIf b = if b then fillW else id+    colBox i = smallAt colBoxes i (tight defaultLayout)+    cellLayout i = if smallAt numeric i False then numCellLayout else textCellLayout+    isSortable i = smallAt sortable i False+    renderHeader i active cellLay flags = do+      let oneCol = encoders V.! i+          hdrCell = toCell (getHeaded (Encode.oneColonnadeHead oneCol))+          styleIx = if active then 1 else 0+      case cellView hdrCell of+        Nothing ->+          buttonStyledEx True (cellText hdrCell) styleIx cellLay flags+        Just hdrAct -> buttonContentStyled styleIx flags cellLay hdrAct+    textCellAt ri i t = do+      wid <- nextId+      void (addWidgetStyled wid NodeText t 0 (cellLayout i) (fromIntegral (rowStripe ri)))+    -- Text cells show their cached text; only a column with widget views+    -- encodes its visible cells again, for the views.+    renderCell ri r i+      | not (smallAt views i False) = textCellAt ri i (indexSmallArray encoded r V.! i)+      | otherwise = case cellView (toCell (Encode.oneColonnadeEncode (V.unsafeIndex encoders i) (rowsVec V.! r))) of+        Nothing -> textCellAt ri i (indexSmallArray encoded r V.! i)+        -- The cell's panel carries the row fill in its style index+        -- ('panelSurface'), as a text cell's node does.+        Just widgetAct -> styledContainer NodePanel (stripeBits (rowStripe ri)) (cellLayout i) widgetAct+    rowCells rowLay idxs colLays ri =+      gridColumnsLay rowLay idxs colLays [renderCell ri (indexPrimArray sorted ri) i | i <- idxs]+    paneRoot = fillIf fillInner (tight (fillH defaultLayout))+    minSum idxs = sum (map (layoutMinW . colBox) idxs) + fromIntegral (max 0 (length idxs - 1))+    paneLay fill idxs+      | fill = fillW (fillH flatLayout)+      | otherwise = (fillH flatLayout) {layoutMinW = minSum idxs}+    gridRowLay idxs = fillIf fillInner flatLayout {layoutMinW = minSum idxs}+    -- Header row and pinned rows, each followed by a rule. Used by both panes.+    headerBlock idxs = do+      let !rowLay = gridRowLay idxs+          !colLays = map colBox idxs+      hs <- row' rowLay $+        forM (zip [0 :: Int ..] idxs) $ \(k, i) -> do+          when (k > 0) $ void separator+          let isSort = isSortable i+              isActive = sortColIndex sort0 == i && isSort+              flags = (if isSort then sortMarkStyle sort0 i else 0) .|. buttonFlagTable+              hdrLay = if smallAt numeric i False then numHeaderLayout else textCellLayout+          withKey i $+            column' (colBox i) $+              renderHeader i isActive hdrLay flags+      void separator+      forM_ [0 .. pinnedN - 1] $ \ri -> do+        let !sourceIdx = indexPrimArray sorted ri+        withKey ("pin" :: Text, sourceIdx) $ do+          when (ri > 0) $ void separator+          rowCells rowLay idxs colLays ri+      when (pinnedN > 0 && scrollN > 0) $ void separator+      pure hs+    bodyBlock idxs = do+      (lo, hi) <-+        if scrollN == 0+          then pure (0, -1)+          else liftIO $ do+            V2 _ scrollY <- getScrollOffset2D ctx vWid+            viewH <- maybe (rowStep * 8) rectH <$> getPrevRect ctx vWid+            pure (listClipper scrollN scrollY viewH rowStep)+      let !rowLay = gridRowLay idxs+          !colLays = map colBox idxs+          topH = if lo <= 0 then 0 else fromIntegral lo * rowH + fromIntegral (lo - 1)+          botH = fromIntegral (max 0 (scrollN - hi - 1)) * rowStep+      column' rowLay $ do+        when (topH > 0) $ void (spacer Fit (Fixed topH))+        forM_ [lo .. hi] $ \rowIdx -> do+          let !ri = rowIdx + pinnedN+              !sourceIdx = indexPrimArray sorted ri+          withKey sourceIdx $ do+            when (rowIdx > 0) $ void separator+            rowCells rowLay idxs colLays ri+        when (botH > 0) $ void (spacer Fit (Fixed botH))+    frozenPane =+      column' (paneLay False frozenIdx) $ do+        hs <- headerBlock frozenIdx+        scrollAreaIdConfigured+          vWid+          (fillH flatLayout)+          (if null unfrozenIdx then defaultScrollConfig else scrollVerticalHidden)+          (bodyBlock frozenIdx)+        pure hs+    unfrozenPane = do+      -- Uses last frame's rect, so the header's spacer lags the body's+      -- vertical bar by one frame when the bar appears or disappears.+      column' (paneLay fillInner unfrozenIdx) $ do+        hs <-+          row' (fillIf fillInner flatLayout) $ do+            hs' <-+              scrollAreaIdConfigured+                hWid+                ((if fillInner then fillW else minW (minSum unfrozenIdx)) flatLayout {layoutDirection = Row})+                -- Bar-less scroller that follows the body's horizontal+                -- offset (linkScrollAxes below) and clips the header row.+                scrollHorizontalHidden+                (column' (gridRowLay unfrozenIdx) (headerBlock unfrozenIdx))+            -- The body scroller has no padding, so its whole lane is gutter.+            when hasVertBar $ void (spacer (Fixed (scrollBarGutter ScrollBarList 0)) Fit)+            pure hs'+        liftIO (linkScrollAxes ctx vWid hWid)+        -- The body owns both scrollbars.+        scrollAreaIdConfigured+          vWid+          (fillIf fillInner (fillH flatLayout))+          scroll2DConfig+          (bodyBlock unfrozenIdx)+        pure hs++-- | What one frame of a table's headers did, for 'resolveTableInput'.+data TableInput = TableInput+  { tiInput :: !Input+  , tiSort :: !SortCol+  -- ^ The sort the rows are in.+  , tiSortable :: !(SmallArray Bool)+  -- ^ Whether each source column can sort.+  , tiVisible :: ![Int]+  -- ^ The shown columns in display order, as laid out.+  , tiWidths :: ![Float]+  -- ^ The column widths laid out ('resizedWidths').+  , tiSizes :: !(SmallArray ColSize)+  -- ^ Declared column sizing policies.+  , tiContentWs :: !(PrimArray Float)+  -- ^ Measured content width of each source column.+  , tiFill :: !Bool+  -- ^ Whether columns fill the table width.+  , tiHeaders :: ![(Int, Response)]+  -- ^ Each shown column's header response.+  , tiShowAll :: !(Maybe Response)+  -- ^ The "Show all columns" button, while a column is hidden.+  , tiEdge :: !(Maybe (Int, Float))+  -- ^ The column whose resize edge is under the pointer, and its header's+  -- width.+  , tiReorder :: !Reorder+  }++-- | A table's state after one frame, from 'resolveTableInput'.+data TableStep = TableStep+  { tableStepState :: !TableState+  , tableStepSort :: !SortCol+  , tableStepSortClicked :: !Bool+  -- ^ A header click changed the sort.+  , tableStepChanged :: !Bool+  -- ^ The sort, order, hidden columns or widths changed.+  }++-- | One frame of a table's headers: a resize starting, running, auto-fitting+-- on double-click, or ending, a column reordered, hidden or shown again, and+-- a header click sorting.+resolveTableInput :: TableInput -> TableState -> TableStep+resolveTableInput ti ts0 =+  TableStep+    { tableStepState =+        TableState+          { tsOrder = nextOrder+          , tsWidths = nextWidths+          , tsHidden = nextHidden+          , tsResizeCol = nextDrag+          , tsResizeX = nextDragX+          , tsResizeW = nextDragW+          }+    , tableStepSort = nextSort+    , tableStepSortClicked = hasChanged && isJust sortClick+    , tableStepChanged = hasChanged+    }+  where+    inp = tiInput ti+    sort0 = tiSort ti+    vis = tiVisible ti+    order0 = tsOrder ts0+    hidden0 = tsHidden ts0+    headerPairs = tiHeaders ti+    reorder = tiReorder ti+    edgeCol = fst <$> tiEdge ti+    isResize = tsResizeCol ts0 >= 0+    doubleClick = pressedIn MouseLeft inp && inputMouseClicks inp >= 2+    autoFit col =+      let fitW = max minColW (primAt (tiContentWs ti) col minColW)+          curSaved = fromMaybe 0 (listToMaybe (drop col (tiWidths ti)))+          size = smallAt (tiSizes ti) col ColContent+       in if curSaved > 0 && abs (curSaved - fitW) <= 1+            then 0+            else if size == ColContent && not (tiFill ti)+              then 0+              else fitW+    nextWidths = case tiEdge ti of+      Just (col, _) | doubleClick -> setAt col (autoFit col) (tiWidths ti)+      _ -> tiWidths ti+    vis' = reorderOrder reorder+    mReorder = reorderDragging reorder+    (nextDrag, nextDragX, nextDragW)+      | doubleClick, isJust (tiEdge ti) = (-1, 0, 0)+      | pressedIn MouseLeft inp, Just (col, w) <- tiEdge ti = (col, v2X (inputMousePos inp), w)+      | pressedIn MouseLeft inp || releasedIn MouseLeft inp || not (heldIn MouseLeft inp) || not isResize = (-1, 0, 0)+      | otherwise = (tsResizeCol ts0, tsResizeX ts0, tsResizeW ts0)+    nextOrder = if vis' /= vis then rebuildOrder hidden0 vis' order0 else order0+    -- respRightClicked, not a bare release: a right press that went down+    -- elsewhere and came up over a header must not hide that column.+    hideClicked = [i | (i, r) <- headerPairs, respRightClicked r, not isResize, isNothing mReorder]+    nextHidden = case tiShowAll ti of+      Just r | respClicked r -> IS.empty+      _ -> case hideClicked of+        (i : _) | length vis > 1 -> IS.insert i hidden0+        _ -> hidden0+    sortClick =+      if reorderMoved reorder || isJust mReorder || isResize || (isJust edgeCol && (heldIn MouseLeft inp || releasedIn MouseLeft inp))+        then Nothing+        else listToMaybe [i | (i, r) <- headerPairs, respClicked r, smallAt (tiSortable ti) i False]+    nextSort = maybe sort0 (nextSortCol sort0) sortClick+    hasChanged = nextSort /= sort0 || nextOrder /= order0 || nextHidden /= hidden0 || nextWidths /= tsWidths ts0++-- | 'tableConfigured' on a plain sort.+tableCore ::+  (Foldable f, ToCell c) =>+  TableConfig ->+  (Layout -> Layout) ->+  Text ->+  Colonnade Headed row c ->+  f row ->+  SortCol ->+  NanoUI TableResponse+tableCore cfg f key cols inputRows curSort =+  let encoders = Encode.getColonnade cols+      n = V.length encoders+      -- Built only for a column with widget views, which reads its rows.+      rowsVec = V.fromList (toList inputRows)+  in withKey ("table:" <> key) $ do+    (stateWid, ctx) <- freshWidget+    vWid <- nextId+    hWid <- nextId+    tableWid <- nextId+    let sort0 = clampSortCol n curSort+        stateKey = intKey stateWid+        ids = TableIds {tidBody = vWid, tidHeader = hWid, tidPanel = tableWid}+    inp <- askInput+    !ts0 <- readTableState cfg n stateKey <$> liftIO (getStore ctx)+    derived <- liftIO (tableDerived ctx stateKey cols inputRows sort0)+    let sizes = smallArrayFromList (tableColSizes cfg)+        contentWs = tdWidths derived+        widths1 = resizedWidths inp ts0+        geom = tableGeometry cfg f (ctxFontMetrics ctx) n (sizeofSmallArray (tdEncoded derived)) sizes contentWs widths1 ts0+        vis = tgVisible geom+    -- Last frame's body rect, for the header's resize edges.+    mPrevBody <- lastRect vWid+    -- Whether the body showed its vertical bar last frame. The header then+    -- keeps a spacer the width of the bar's lane, so its columns line up+    -- with the rows; it follows the body a frame late when the bar comes or+    -- goes. Only a change in the bar itself asks for that frame, not every+    -- change in the body's metrics.+    hasVertBar <- liftIO $ do+      let barOf = maybe False ((> 0) . v2Y . scrollRange)+      bar <- barOf <$> readScrollMetrics ctx vWid+      recordLayoutRead ctx (specKey slotScrollRange (intKey vWid)) ((/= bar) . barOf <$> readScrollMetrics ctx vWid)+      pure bar+    column' (tgOuter geom) $ do+      showAllResp <-+        if IS.null (tsHidden ts0)+          then pure Nothing+          else fmap Just $+            buttonStyledEx True "Show all columns" 0 (tight . fillW $ defaultLayout) 0+      headerPairs <- tablePanes (tableBare cfg) ctx ids encoders rowsVec derived geom sort0 hasVertBar+      let mouse = inputMousePos inp+      reachable <- liftIO (pointerReachable ctx tableWid mouse)+      headerClips <- liftIO (mapM (getPrevClipRect ctx . rawRespId . snd) headerPairs)+      let+          headerRects = [(i, rawRespRect r) | (i, r) <- headerPairs]+          -- Only edges in view: a header scrolled under the frozen pane or+          -- past the body's right edge has its edge outside its clip.+          shownEdges = [h | (h@(_, Rect x _ w _), Just (Rect cx _ cw _)) <- zip headerRects headerClips, x + w >= cx, x + w <= cx + cw + 0.5]+          -- Also used as the resize cursor's zones.+          edgeZones = headerEdgeZones 4 mPrevBody shownEdges+          hitCol zones = fst <$> find (\(_, r) -> rectContains r mouse) zones+          edgeCol = if reachable then hitCol edgeZones else Nothing+          headerW i = case lookup i headerRects of+            Just r | rectW r > 0 -> rectW r+            _ -> layoutMinW (smallAt (tgColBoxes geom) i (tight defaultLayout))+      -- A press on an edge resizes and arms no reorder, but a column already+      -- held can still be dropped by an edge.+      reorder <-+        withKey ("reorder" :: Text) $+          useReorder vis (if pressedIn MouseLeft inp && isJust edgeCol then [] else headerPairs)+      -- No resize arrow over the edges while a column is held.+      when (reachable && isNothing (reorderDragging reorder) && not (null edgeZones)) . liftIO $+        -- Strict in the spine and the rects, so no thunk waits in the IORef.+        modifyIORef' (ctxCursorZones ctx) (\zs -> foldl' (\acc (_, !r) -> (r, UiCursorColResize) : acc) zs edgeZones)+      let !(TableStep ts1 nextSort sortClicked hasChanged) =+            resolveTableInput+              TableInput+                { tiInput = inp+                , tiSort = sort0+                , tiSortable = tdSortable derived+                , tiVisible = vis+                , tiWidths = widths1+                , tiSizes = sizes+                , tiContentWs = contentWs+                , tiFill = tgFill geom+                , tiHeaders = headerPairs+                , tiShowAll = showAllResp+                , tiEdge = (\col -> (col, headerW col)) <$> edgeCol+                , tiReorder = reorder+                }+              ts0+          widgetResp =+            setChanged hasChanged $+              setClicked sortClicked (mconcat (map snd headerPairs ++ maybe [] pure showAllResp))+      liftIO (writeSlots ctx (writeTableState stateKey ts1))+      -- Repaints the table when the sort shown changes, however it came (a+      -- header click or a write to the Var).+      liftIO (writeSlot fieldInt ctx tableWid (intKey tableWid) (sortShownCode sort0))+      -- Keep the resize cursor for the whole drag, wherever the pointer is.+      when (tsResizeCol ts1 >= 0 && heldIn MouseLeft inp) $+        liftIO (modifyInteraction ctx (\s -> s {isColumnResize = True}))+      pure (TableResponse widgetResp nextSort (tsOrder ts1) (tsHidden ts1))++-- | One row of cells with custom row layout.+gridColumnsLay :: Layout -> [Int] -> [Layout] -> [NanoUI ()] -> NanoUI ()+gridColumnsLay lay keys layouts cells =+  void (row' lay (go True keys layouts cells))+ where+  -- Walk in lockstep without allocating zip tuples and indices per cell.+  go first (key : moreKeys) (layout : moreLayouts) (cell : moreCells) = do+    unless first $ void separator+    void (withKey key (column' layout cell))+    go False moreKeys moreLayouts moreCells+  go _ _ _ _ = pure ()++-- | Indices of @keys@ stably sorted by key: a bottom-up merge sort between+-- two index buffers.+sortIndices :: Ord k => SortDir -> SmallArray k -> PrimArray Int+sortIndices dir keys = runST $ do+  let n = sizeofSmallArray keys+      before l r = case compare (indexSmallArray keys l) (indexSmallArray keys r) of+        LT -> dir == SortAsc+        GT -> dir == SortDesc+        EQ -> True+  start <- newPrimArray n+  let fill !i = when (i < n) (writePrimArray start i i >> fill (i + 1))+  fill 0+  spare <- newPrimArray n+  let pass !src !dst !width+        | width >= n = unsafeFreezePrimArray src+        | otherwise = do+            let mergeFrom !lo = when (lo < n) $ do+                  let !mid = min n (lo + width)+                      !hi = min n (lo + 2 * width)+                      copy from to len = copyMutablePrimArray dst to src from len+                      takeLeft !i !j !k = readPrimArray src i >>= writePrimArray dst k >> go (i + 1) j (k + 1)+                      takeRight !i !j !k = readPrimArray src j >>= writePrimArray dst k >> go i (j + 1) (k + 1)+                      go !i !j !k+                        | k >= hi = pure ()+                        | i >= mid = takeRight i j k+                        | j >= hi = takeLeft i j k+                        | otherwise = do+                            l <- readPrimArray src i+                            r <- readPrimArray src j+                            if before l r then takeLeft i j k else takeRight i j k+                  -- Runs already in order, or wholly reversed, are copied+                  -- without a merge, so sorted input costs O(n) compares.+                  -- Reversed means every right key is strictly first, so+                  -- swapping the runs keeps the sort stable.+                  inOrder <- if mid >= hi then pure True else before <$> readPrimArray src (mid - 1) <*> readPrimArray src mid+                  if inOrder+                    then copy lo lo (hi - lo)+                    else do+                      merge <- before <$> readPrimArray src lo <*> readPrimArray src (hi - 1)+                      if merge then go lo mid lo else copy mid lo (hi - mid) >> copy lo (lo + hi - mid) (mid - lo)+                  mergeFrom hi+            mergeFrom 0+            pass dst src (2 * width)+  pass start spare 1++-- | First and last visible item index for a uniform-height list, or+-- @(0, -1)@ when nothing is visible.+{-# INLINE listClipper #-}+listClipper :: Int -> Float -> Float -> Float -> (Int, Int)+listClipper itemCount scrollOff viewH itemH+  | itemCount <= 0 || itemH <= 0 || viewH <= 0 = (0, -1)+  | otherwise =+      let firstVis = max 0 (floor (scrollOff / itemH))+          lastVis = min (itemCount - 1) (floor ((scrollOff + viewH - 1) / itemH))+       in if lastVis < firstVis then (0, -1) else (firstVis, lastVis)++setAt :: Int -> a -> [a] -> [a]+setAt i x = zipWith (\j y -> if j == i then x else y) [0 ..]++normalizeOrder :: Int -> [Int] -> [Int]+normalizeOrder n stored =+  let valid = filter (\i -> i >= 0 && i < n) stored+      seen = IS.fromList valid+   in valid ++ [i | i <- [0 .. n - 1], not (IS.member i seen)]++rebuildOrder :: IntSet -> [Int] -> [Int] -> [Int]+rebuildOrder hidden newVis old =+  let go [] vs = vs+      go (i : is) vs+        | IS.member i hidden = i : go is vs+        | otherwise = case vs of+            (v : vs') -> v : go is vs'+            [] -> i : is+   in go old newVis++-- | Each column's resize zone: @pad@ either side of its header's right edge,+-- from the top of the header band to the bottom of the body's last-frame+-- rect (or of the header band, before the body has a rect).+headerEdgeZones :: Float -> Maybe Rect -> [(Int, Rect)] -> [(Int, Rect)]+headerEdgeZones pad mBody hdrs =+  [(i, Rect (x + w - pad) top (2 * pad) (bot - top)) | (i, Rect x _ w h) <- hdrs, w > 0 && h > 0]+  where+    top = minimum [y | (_, Rect _ y _ _) <- hdrs]+    bot = maximum ([y + h | (_, Rect _ y _ h) <- hdrs] ++ [by + bh | Rect _ by _ bh <- toList mBody])
+ lib/NanoUI/Internal/Widgets/Tabs.hs view
@@ -0,0 +1,522 @@+-- | Controlled tab selection, header styles, close requests, and header geometry.+module NanoUI.Internal.Widgets.Tabs+  ( Tab (..), TabStyle (..), TabOrientation (..), TabResponse (..)+  , TabsConfig (..), defaultTabsConfig+  , tab, closableTab+  , tabs, tabs', tabsConfigured, tabsConfigured'+  , tabBar, tabBar', tabBarConfigured, tabBarConfigured'+  , enumTabsBy, enumTabsByConfigured, enumTabs+  , enumTabBarBy, enumTabBarByConfigured, enumTabBar+  )+where++import Control.Monad (void, when)+import Data.Bits ((.|.))+import Data.Foldable (toList)+import Data.Hashable (Hashable (..))+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.List (find)+import Data.Maybe (fromMaybe, isJust, listToMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Context+import NanoUI.Internal.Frame.Chrome (tabHeaderVisualStyle)+import NanoUI.Internal.Layout.ScrollGeometry (scrollAxisRange, scrollBare, scrollHorizontalHidden)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input (MouseButton (..), inputMousePos, inputScroll)+import NanoUI.Internal.Layout.Arena (setStyleIdx, setWidgetId)+import NanoUI.Internal.Monad (NanoUI, askInput, disabledWhen, freshWidget, lastRect, nextId, liftIO, styled, uiFontSize, uiTheme, withContext, withKey)+import NanoUI.Internal.Var (Binding (..), bindVarOn)+import NanoUI.Internal.Var.Types (Var, zoomVar)+import NanoUI.Internal.Store (fieldInt, findSpec, lookupSlot, slotWrite, specKey, specWrite)+import NanoUI.Internal.Store.Slots (slotScrollContent)+import NanoUI.Internal.Style+import NanoUI.Internal.Types (Color, Rect (..), clamp, rectContains, rectIntersect, rectW, v2Y)+import NanoUI.Internal.WidgetText (TabChrome (..), buttonCloseTab, buttonFlagClose, tabChromeEncode, tabEncodeStyle)+import NanoUI.Internal.Widgets.Adornment (Adornments, adornButton, control, trailing, view)+import NanoUI.Internal.Widgets.Combinators (buttonStyledEx, widgetBaseLayout)+import NanoUI.Internal.Widgets.Layout (column', columnWith, labelEx, panel', row', rowWith, scrollAreaIdConfigured)+import NanoUI.Internal.Widgets.Node++-- | Visual treatment of the tab headers; does not change tab identity.+data TabStyle+  = TabUnderline+  -- ^ Headers on a rule, the selected one marked by an accent bar on it.+  | TabPill+  -- ^ The selected header filled with the accent colour.+  | TabSegmented+  -- ^ Headers in a rounded track, the selected one raised out of it, as a+  -- segmented control.+  | TabContained+  -- ^ Folder tabs: the selected header opens onto a bordered body, which+  -- 'tabs' draws round the tab's content.+  deriving (Eq, Ord, Show, Enum, Bounded)++instance Hashable TabStyle where+  hashWithSalt salt = hashWithSalt salt . fromEnum++-- | Header strip position relative to the selected tab's body.+data TabOrientation = TabTop | TabBottom | TabLeft | TabRight+  deriving (Eq, Ord, Show, Enum, Bounded)++instance Hashable TabOrientation where+  hashWithSalt salt = hashWithSalt salt . fromEnum++isVertical :: TabOrientation -> Bool+isVertical o = o == TabLeft || o == TabRight++-- | Header look and placement for 'tabsConfigured' and 'tabBarConfigured'.+data TabsConfig = TabsConfig+  { tabsStyle :: !TabStyle+  , tabsOrientation :: !TabOrientation+  , tabsTrailing :: NanoUI ()+  -- ^ Drawn after the headers: at the far end of a horizontal strip, below+  -- a vertical strip's headers. For actions on the strip as a whole, such+  -- as a button that opens a new tab. Child widgets handle their own pointer events.+  }++-- | The trailing view shows as @\<view\>@.+instance Show TabsConfig where+  showsPrec d (TabsConfig style orient _) =+    showParen (d > 10) $+      showString "TabsConfig " . showsPrec 11 style . showChar ' ' . showsPrec 11 orient . showString " <view>"++-- | Underlined headers along the top, with nothing after them.+defaultTabsConfig :: TabsConfig+defaultTabsConfig = TabsConfig TabUnderline TabTop (pure ())++-- | Tab key, header options, and body. Keys must be distinct within the bar.+-- Closing is a request to the caller; the widget does not remove the tab.+data Tab a body = Tab+  { tabKey :: !a+  , tabTitle :: !Text+  , tabClosable :: !Bool+  , tabDisabled :: !Bool+  , tabBadge :: !(Maybe Text)+  -- ^ A short count or status drawn in a pill after the title.+  , tabAdornments :: !Adornments+  -- ^ Icons, texts and views drawn in the header beside its title+  -- ("NanoUI.Adornment"), in the header's label colour. An 'NanoUI.Adornment.AdornControl',+  -- such as a pin button, handles its own pointer events without selecting+  -- or closing the tab.+  , tabBody :: !body+  }++-- | Controlled selection and close requests, with geometry for optional+-- drag sources and insertion targets.+data TabResponse a = TabResponse+  { tabResponse :: !Response+  , tabClosed :: !(Maybe a)+  , tabActive :: !a+  , tabHeaders :: ![(a, Response)]+    -- ^ Ordered header responses, suitable for 'NanoUI.useDrag'.+  , tabStripRect :: !Rect+    -- ^ Visible header viewport, excluding paging buttons and trailing controls.+  }+  deriving (Eq, Show)++instance HasResponse (TabResponse a) where+  {-# INLINE toResponse #-}+  toResponse = tabResponse++-- | Enabled tab without a close button, badge or adornments.+tab :: a -> Text -> body -> Tab a body+tab key title body = Tab key title False False Nothing mempty body++-- | Enabled tab with a close button. A click on it, or a middle click on the+-- header, is reported through 'tabClosed'.+closableTab :: a -> Text -> body -> Tab a body+closableTab key title body = Tab key title True False Nothing mempty body++-- | Header height, shared by the strip, its scroller and the paging arrows.+tabHeaderH :: Float+tabHeaderH = 30++-- | A header's layout. The headers of a vertical strip share its width, and+-- start their labels at their padding (@tabLabelAtStart@).+tabHeaderLay :: Bool -> Layout+tabHeaderLay vertical = (if vertical then fillW else id) . fixedH tabHeaderH . alignMiddle . gap 6 $ defaultLayout++-- | Name the current container @wid@ and give it @part@ of a strip's chrome,+-- painted under its children ('NanoUI.Internal.Frame.Chrome.paintTabChrome').+-- The id tracks the container's rect, so what it paints repaints as it moves.+tagTabChrome :: WidgetId -> TabChrome -> TabStyle -> TabOrientation -> NanoUI ()+tagTabChrome wid part style orient = do+  withContext $ \ctx -> do+    parent <- currentParent ctx+    when (parent >= 0) $ do+      setWidgetId (ctxNodeArena ctx) parent wid+      setStyleIdx (ctxNodeArena ctx) parent (tabChromeEncode part (fromEnum style) (fromEnum orient))++tabStrip ::+  Hashable a =>+  TabsConfig ->+  a ->+  [Tab a body] ->+  Maybe (a -> NanoUI ()) ->+  NanoUI (TabResponse a)+tabStrip (TabsConfig style orient trailingView) cur tabList mRenderBody = do+  (groupId, ctx) <- freshWidget+  let vertical = isVertical orient+      -- Headers ahead of the body take this frame's clicks. A body ahead of+      -- them ran with the key passed in, so they show it too, and the+      -- binding reruns the view to show the new one.+      bodyFirst = bodyAhead orient (isJust mRenderBody)+      headers = renderHeaders ctx style orient (not bodyFirst) cur tabList+      barGap = if style == TabPill then 4 else 2+      edgeChrome = case style of+        TabUnderline -> TabChromeRule+        TabContained -> TabChromeRule+        _ -> TabChromeNone+      -- Contained headers stand off the rule's ends and the strip's far side.+      contained+        | style /= TabContained = id+        | otherwise = case orient of+            TabTop -> padLRTB 6 6 4 0+            TabBottom -> padLRTB 6 6 0 4+            TabLeft -> padLRTB 4 0 6 6+            TabRight -> padLRTB 0 4 6 6+      -- Headers sit on the rule, whatever the trailing view's height.+      onEdge = if orient == TabBottom then alignTop else alignBottom+      headerBar+        | vertical = column' (contained . segmentedColumn . tight . gap barGap $ defaultLayout) $ do+            tagTabChrome groupId (if style == TabSegmented then TabChromeTrack else edgeChrome) style orient+            headers <* trailingView+        | otherwise = row' (contained . onEdge . tight . fillW . gap 8 $ defaultLayout) $ do+            tagTabChrome groupId edgeChrome style orient+            scrollableHeaders ctx style barGap headers <* trailingView+      -- A segmented column hugs its headers in its track; the others run the+      -- body's length.+      segmentedColumn = if style == TabSegmented then padAll 3 else fillH+      bodyGap = if style == TabContained then 0 else if vertical then 16 else 12+  result <- case mRenderBody of+    Nothing -> headerBar+    Just bodyRender ->+      (if vertical then rowWith (tight . fillW . grow . gap bodyGap) else columnWith (tight . fillW . gap bodyGap)) $+        if bodyFirst+          then bodyRender cur *> headerBar+          else headerBar >>= \r -> r <$ bodyRender (tabActive r)+  -- The headers show the selection only through their node values, which no+  -- diff covers, so a slot on the strip damages it when the shown tab changes,+  -- however the change came (a click, a key, a write to the Var).+  liftIO (writeSlot fieldInt ctx groupId (intKey groupId) (hash (if bodyFirst then cur else tabActive result)))+  clip <- liftIO (getPrevClipRect ctx groupId)+  let bounds = tabStripRect result+      visible = maybe bounds (fromMaybe (Rect 0 0 0 0) . rectIntersect bounds) clip+  pure result {tabStripRect = visible}++-- | Horizontal headers that page with chevron buttons when they overflow,+-- in a row that takes the strip's width less its trailing view. Overflowing+-- headers move into a bare horizontal scroller that grows between the two+-- arrows; the vertical wheel over it pages it too, and scrolls nothing+-- round it. Segmented headers sit in their track, which scrolls with them.+scrollableHeaders ::+  Hashable a =>+  Context ->+  TabStyle ->+  Float ->+  NanoUI (TabResponse a) ->+  NanoUI (TabResponse a)+scrollableHeaders ctx style barGap headers = withKey ("tab-headers" :: Text) $ do+  groupId <- nextId+  scrollWid <- nextId+  trackId <- nextId+  let rangeKey = intKey scrollWid+      segmented = style == TabSegmented+      stripH = if segmented then tabHeaderH + 6 else tabHeaderH+      renderInner =+        withKey ("tab-strip" :: Text) $+          row' ((if segmented then padAll 3 else id) . tight . fixedH stripH . gap barGap $ defaultLayout) $ do+            when segmented $ tagTabChrome trackId TabChromeTrack style TabTop+            headers+      -- Whether the strip overflows and can page left and right, at reachable+      -- range @r@ and offset @o@.+      paging r o = (r > 0.5, r > 0.5 && o > 0.5, o < r - 0.5)+  -- The reachable range measured after last frame's layout decides whether+  -- the strip needs the scroller. It is a float slot published after layout,+  -- so the frame that changes it counts as a layout change, not a scroll+  -- ('NanoUI.Internal.Damage.writeDamage').+  store <- liftIO (getStore ctx)+  let maxOff = max 0 (findSpec slotScrollContent 0 rangeKey store)+      -- The hash of the tab the strip last brought into view, if any: a key+      -- that hashes to 0 is followed too.+      followKey = intKey groupId+      followed = lookupSlot fieldInt followKey store+  off <- liftIO (getScrollOffset ctx scrollWid)+  let (overflow, canLeft, canRight) = paging maxOff off+  wheelStep <- liftIO (resolveScrollStep ctx scrollWid)+  -- Not 'lastRect': the strip checks its own layout below, and the bar+  -- moving alone needs no second frame.+  mBar <- liftIO (getPrevRect ctx groupId)+  mScr <- liftIO (getPrevRect ctx scrollWid)+  mClip <- liftIO (getPrevClipRect ctx scrollWid)+  inp <- askInput+  -- Over the scroller only: it keeps the vertical wheel from the scrollers+  -- round it, which the arrows do not. The wheel counts as a scroller takes+  -- it, fractions of a notch from a trackpad too.+  let visScr = maybe mScr (\c -> mScr >>= rectIntersect c) mClip+      overStrip = maybe False (\r -> rectContains r (inputMousePos inp)) visScr+      wheelY = if overStrip then v2Y (inputScroll inp) else 0+      -- A paging arrow while the bar overflows, muted at its end. The muted+      -- look is a font colour, which no diff covers, so a slot at the arrow+      -- repaints it when it turns.+      arrow k enabled glyph+        | overflow = withKey (k :: Text) $ do+            theme <- uiTheme+            let muted = if enabled then Nothing else Just (themeMuted theme)+                lay = (fixedWH 26 stripH . alignCenter . alignMiddle $ defaultLayout) {layoutFontColor = muted}+            resp <- styled subtle (buttonStyledEx enabled glyph 0 lay 0)+            liftIO (writeSlot fieldInt ctx (respId resp) (intKey (respId resp)) (fromEnum enabled))+            pure (respClicked resp)+        | otherwise = pure False+  (leftClicked, tabResp, rightClicked) <-+    row' (tight . grow . alignMiddle . fixedH stripH $ defaultLayout) $ do+      tagContainer groupId+      (,,)+        <$> arrow "tab-arrow-left" canLeft "\8249"+        <*> ( if overflow+                then+                  scrollAreaIdConfigured+                    scrollWid+                    (tight . fillW . fixedH stripH $ defaultLayout {layoutDirection = Row})+                    scrollHorizontalHidden {scrollBare = True}+                    renderInner+                else renderInner+            )+        <*> arrow "tab-arrow-right" canRight "\8250"+  let+    hdrs = tabHeaders tabResp+    viewport = fromMaybe (Rect 0 0 0 0) (if overflow then mScr else mBar)+    viewX = rectX viewport+    viewW = rectW viewport+    page = max 1 (viewW * 0.9)+    -- The range this frame's layout leaves: the headers' right edge past the+    -- start of what shows them, less its width. The first overflow frame has+    -- no scroller rect yet, and keeps the range it has. Headers that would+    -- fit the whole bar without the arrows leave no range, so the arrows go+    -- once the bar is wide enough, however narrow the scroller between them.+    measure = do+      mView <- getPrevRect ctx (if overflow then scrollWid else groupId)+      mBarNow <- if overflow then getPrevRect ctx groupId else pure Nothing+      rights <- mapM (fmap (maybe 0 (\r -> rectX r + rectW r)) . getPrevRect ctx . respId . snd) hdrs+      o <- getScrollOffset ctx scrollWid+      let extent vx = maximum (0 : rights) - vx + (if overflow then o else 0)+          range (Rect vx _ vw _)+            | Just bar <- mBarNow, scrollAxisRange (extent vx) (rectW bar) 0 == 0 = 0+            | otherwise = scrollAxisRange (extent vx) vw 0+      pure (maybe maxOff range mView, o)+  -- After layout, measure the strip for the next frame and request a+  -- follow-up frame only when the overflow or arrow state changes: a width+  -- change that keeps them settles in the frame it happens in. Sub-pixel+  -- churn is ignored so a parked strip never writes.+  liftIO . recordLayoutRead ctx (specKey slotScrollContent rangeKey) $ do+    (maxOff', o) <- measure+    when (abs (maxOff' - maxOff) > 0.5) $+      publishLayoutSlots ctx (specWrite slotScrollContent rangeKey maxOff')+    pure (paging maxOff' o /= paging maxOff off)+  -- While the shown tab is not the one last brought into view, however it+  -- came to be shown (a click, a key, a write to the Var), its header's rect+  -- and the scroller's. Each is last frame's, or, for one laid out for the+  -- first time this frame, a read that brings another frame once it is.+  let shown = tabActive tabResp+      laidOut w = liftIO (getPrevRect ctx w) >>= maybe (lastRect w) (pure . Just)+  target <-+    if overflow && Just (hash shown) /= followed+      then do+        scroller <- laidOut scrollWid+        header <- maybe (pure Nothing) (laidOut . respId) (lookup shown hdrs)+        pure (scroller *> header)+      else pure Nothing+  -- One offset per frame: arrow pages, the wheel and the end clamp, or+  -- whatever brings that header into view.+  let pagedOff+        | leftClicked, canLeft = max 0 (off - page)+        | rightClicked, canRight = min maxOff (off + page)+        | overflow, wheelY /= 0, maxOff > 0 =+            clamp 0 maxOff (off + wheelY * wheelStep)+        | overflow, off > maxOff + 0.5 = maxOff+        | otherwise = off+      follow hr+        | rectX hr < viewX = max 0 (off - (viewX - rectX hr))+        | rectX hr + rectW hr > viewX + viewW =+            min maxOff (off + (rectX hr + rectW hr - viewX - viewW))+        | otherwise = pagedOff+      finalOff = maybe pagedOff follow target+  when (finalOff /= off) $+    liftIO (setScrollOffset ctx scrollWid finalOff)+  -- Compared first, so a parked strip writes nothing.+  when (isJust target) $+    liftIO (publishLayoutSlots ctx (slotWrite fieldInt followKey (hash shown)))+  pure tabResp {tabStripRect = viewport}++-- | The headers and the selection after this frame's clicks, with each+-- header's key and response for the scrolling strip. With @follow@ the+-- headers show the clicked tab as selected at once; without it they show+-- @cur@, the key passed in.+renderHeaders ::+  Hashable a =>+  Context ->+  TabStyle ->+  TabOrientation ->+  Bool ->+  a ->+  [Tab a body] ->+  NanoUI (TabResponse a)+renderHeaders ctx style orient follow cur tabList = do+  hdrs <- mapM (\t -> withKey (tabKey t) (renderHeader style orient cur t)) tabList+  let clickedKeys = [k | (k, r, False) <- hdrs, respClicked r]+      closedKey = listToMaybe [k | (k, _, True) <- hdrs]+      keyed = [(k, r) | (k, r, _) <- hdrs]+      nextTab = fromMaybe cur (listToMaybe clickedKeys)+      hasChanged = nextTab /= cur+      resp = setChanged hasChanged (setClicked (not (null clickedKeys)) (foldMap snd keyed))+  when follow $ liftIO (moveSelection ctx cur nextTab keyed)+  pure (TabResponse resp closedKey nextTab keyed (respRect resp))++-- | One header: its key, its response, and whether it was closed (close+-- button clicked, or header or close button middle-clicked, as in a+-- browser). The header is one button; its adornments, badge and close+-- button are drawn inside it, in its label colour. A press on the close+-- button or on a control among the adornments is theirs, not the header's.+renderHeader :: Eq a => TabStyle -> TabOrientation -> a -> Tab a body -> NanoUI (a, Response, Bool)+renderHeader style orient cur t = disabledWhen (tabDisabled t) $ do+  theme <- uiTheme+  lay <- widgetBaseLayout (tabHeaderLay (isVertical orient)) id+  let isActive = tabKey t == cur+      packed = tabEncodeStyle (fromEnum style) (fromEnum orient)+      labelCol = styleFg (tabHeaderVisualStyle theme packed isActive)+  resp <- buttonStyledEx (not (tabDisabled t)) (tabTitle t) (if isActive then 1 else 0) lay packed+  closeRef <- if tabClosable t then Just <$> liftIO (newIORef False) else pure Nothing+  let badge = foldMap (trailing . view . tabBadgeView labelCol) (tabBadge t)+      closeButton ref = do+        c <- buttonStyledEx True "\215" 0 (tight . fixedWH 18 18 . fontColor labelCol $ defaultLayout) (buttonFlagClose .|. buttonCloseTab)+        liftIO (writeIORef ref (respClicked c || respClickedWith MouseMiddle c))+  header <- adornButton resp lay (const labelCol) (tabAdornments t <> badge <> foldMap (trailing . control . closeButton) closeRef)+  btnClosed <- maybe (pure False) (liftIO . readIORef) closeRef+  pure (tabKey t, header, tabClosable t && (btnClosed || respClickedWith MouseMiddle header))++-- | A badge: its text, smaller, in a pill of the label colour @col@.+tabBadgeView :: Color -> Text -> NanoUI ()+tabBadgeView col txt = do+  -- Scaled from the base size the title is drawn at.+  size <- uiFontSize+  styled (panelStyle (\s -> s {styleBg = fadeAlpha col 44, styleBorderWidth = 0, styleCornerRadius = 8})) $+    panel' (padXY 6 1 . tight . minH 17 . alignCenter . alignMiddle $ defaultLayout) $+      () <$ labelEx (tight . fontSize (size * 0.78) . fontColor col $ defaultLayout) txt++-- | Tab headers and the active tab's body, with the active key bound to+-- mutable state ('Var'): a click, or Enter or Space on a focused header,+-- updates it in place. Only the active tab's body runs. A key no tab has,+-- such as a removed tab's, selects the first tab, and the 'Var' is set to it.+{-# INLINE tabs #-}+tabs :: (Foldable f, Hashable a) => Var a -> f (Tab a (NanoUI ())) -> NanoUI ()+tabs = tabsConfigured defaultTabsConfig++-- | 'tabs' returning the 'TabResponse', which also reports a closed tab.+{-# INLINE tabs' #-}+tabs' :: (Foldable f, Hashable a) => Var a -> f (Tab a (NanoUI ())) -> NanoUI (TabResponse a)+tabs' = tabsConfigured' defaultTabsConfig++-- | 'tabs' with a header style and placement.+{-# INLINE tabsConfigured #-}+tabsConfigured :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a (NanoUI ())) -> NanoUI ()+tabsConfigured cfg active ts = void (tabsConfigured' cfg active ts)++-- | 'tabsConfigured' with selection, close requests, and header interaction details.+tabsConfigured' :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a (NanoUI ())) -> NanoUI (TabResponse a)+tabsConfigured' cfg active inputTabs = bindTabs cfg True active (\cur -> tabStrip cfg (shown cur) ts (Just body))+  where+    ts = toList inputTabs+    -- A key no tab has shows the first tab, its header as well as its body,+    -- and the binding writes that tab's key back.+    shown k = if any ((== k) . tabKey) ts then k else maybe k tabKey (listToMaybe ts)+    -- Only the active tab's body runs. Both bodies and headers use the+    -- semantic key: their widget state and focus follow the tab through+    -- reordering and removal of neighbours. A contained body is a bordered+    -- surface the selected header opens onto.+    body k = do+      let contained = tabsStyle cfg == TabContained+          surface = if contained then padAll 12 . (if isVertical (tabsOrientation cfg) then fillH else id) else id+      bodyId <- if contained then withKey ("tab-body" :: Text) (Just <$> nextId) else pure Nothing+      columnWith (surface . tight . fillW) $ do+        mapM_ (\wid -> tagTabChrome wid TabChromeBody (tabsStyle cfg) (tabsOrientation cfg)) bodyId+        mapM_+          (\t -> withKey (tabKey t) (tabBody t))+          (find ((== k) . tabKey) ts)++-- | Run a tab strip on the active key in a Var. A body placed ahead of the+-- headers has already run for the old key when a header is clicked, so a+-- change there runs the view again.+bindTabs :: Hashable a => TabsConfig -> Bool -> Var a -> (a -> NanoUI (TabResponse a)) -> NanoUI (TabResponse a)+bindTabs cfg hasBody active =+  bindVarOn (if bodyAhead (tabsOrientation cfg) hasBody then Conservative else RenderFinal) tabActive active++bodyAhead :: TabOrientation -> Bool -> Bool+bodyAhead orient hasBody = hasBody && (orient == TabBottom || orient == TabRight)++-- | Tab headers only, bound to mutable state ('Var') for the active key; the+-- caller renders the body.+{-# INLINE tabBar #-}+tabBar :: (Foldable f, Hashable a) => Var a -> f (Tab a body) -> NanoUI ()+tabBar = tabBarConfigured defaultTabsConfig++{-# INLINE tabBar' #-}+-- | Header-only 'tabBar' with selection and close requests. Does not run tab bodies.+tabBar' :: (Foldable f, Hashable a) => Var a -> f (Tab a body) -> NanoUI (TabResponse a)+tabBar' = tabBarConfigured' defaultTabsConfig++-- | Header-only bar with explicit style/orientation.+{-# INLINE tabBarConfigured #-}+tabBarConfigured :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a body) -> NanoUI ()+tabBarConfigured cfg active ts = void (tabBarConfigured' cfg active ts)++-- | 'tabBarConfigured' with interaction details and optional close request.+tabBarConfigured' :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a body) -> NanoUI (TabResponse a)+tabBarConfigured' cfg active ts = bindTabs cfg False active (\cur -> tabStrip cfg cur (toList ts) Nothing)++-- | 'tabs' with a tab for every value of a bounded enumeration, labeled by+-- @encode@, each showing @body@ of its value. The Var holds the selected+-- value itself, so the enumeration needs no 'Hashable' instance.+--+-- > page <- useEnumVar Overview+-- > enumTabsBy pageTitle page pageBody+{-# INLINE enumTabsBy #-}+enumTabsBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> (a -> NanoUI ()) -> NanoUI ()+enumTabsBy = enumTabsByConfigured defaultTabsConfig++-- | 'enumTabsBy' with a header style and placement.+{-# INLINE enumTabsByConfigured #-}+enumTabsByConfigured :: (Bounded a, Enum a) => TabsConfig -> (a -> Text) -> Var a -> (a -> NanoUI ()) -> NanoUI ()+enumTabsByConfigured cfg encode active body =+  tabsConfigured cfg (enumIndex active) (map (\x -> tab (fromEnum x) (encode x) (body x)) [minBound .. maxBound])++-- | 'enumTabsBy' labeled with 'show'.+{-# INLINE enumTabs #-}+enumTabs :: (Bounded a, Enum a, Show a) => Var a -> (a -> NanoUI ()) -> NanoUI ()+enumTabs = enumTabsBy (T.pack . show)++-- | 'tabBar' with a header for every value of a bounded enumeration,+-- labeled by @encode@.+{-# INLINE enumTabBarBy #-}+enumTabBarBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()+enumTabBarBy = enumTabBarByConfigured defaultTabsConfig++-- | 'enumTabBarBy' with a header style and placement; with 'TabSegmented'+-- it is a segmented control:+--+-- > enumTabBarByConfigured defaultTabsConfig {tabsStyle = TabSegmented} alignName alignment+{-# INLINE enumTabBarByConfigured #-}+enumTabBarByConfigured :: (Bounded a, Enum a) => TabsConfig -> (a -> Text) -> Var a -> NanoUI ()+enumTabBarByConfigured cfg encode active =+  tabBarConfigured cfg (enumIndex active) (map (\x -> tab (fromEnum x) (encode x) ()) [minBound .. maxBound])++-- | 'enumTabBarBy' labeled with 'show'.+{-# INLINE enumTabBar #-}+enumTabBar :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()+enumTabBar = enumTabBarBy (T.pack . show)++-- | An enumeration's Var seen as its index, which keys the tabs. The tabs+-- only ever write the index of a value they list.+{-# INLINE enumIndex #-}+enumIndex :: Enum a => Var a -> Var Int+enumIndex = zoomVar fromEnum (\i _ -> toEnum i)
+ lib/NanoUI/Internal/Widgets/TextArea.hs view
@@ -0,0 +1,343 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Implementation of "NanoUI.Widgets.TextArea", plus loading and saving a+-- text area's state in the widget store and running commands on it from+-- outside its frame.+module NanoUI.Internal.Widgets.TextArea+  ( -- * Pure state+    TextAreaState (..)+  , initTextAreaState+  , setTextAreaViewport+  , setTextAreaSelection+    -- * Widget+  , textArea+  , textArea'+  , textAreaWith+  , textAreaWith'+  , textAreaDocument+  , textAreaDocument'+  , textAreaDocumentWith+  , textAreaDocumentWith'+  , textAreaLayout+  , textAreaBuffer+  , loadTextAreaState+  , saveTextAreaState+  , runTextAreaCommand+  , textAreaFieldEditor+  ) where++import Control.Monad (foldM, unless, void, when)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.IntMap.Strict as IM+import NanoUI.Internal.Context+import NanoUI.Internal.Font (fmLineHeight, fmSnapScale)+import NanoUI.Internal.Frame.Node (packedTextFont, resolveTextFont)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askContext, askInput, freshWidget, nextId, liftIO)+import NanoUI.Internal.Store+import NanoUI.Internal.Store.Slots (slotSeen, slotTextAreaAnchorCol, slotTextAreaAnchorRow, slotTextAreaBuffer, slotTextAreaLineH, slotTextAreaReveal, slotTextAreaScroll, slotTextAreaText, slotTextAreaViewport, slotTextChanged, slotTextHistory, slotTextMode)+import NanoUI.Internal.Store.Types (TextHistory (..))+import NanoUI.Internal.Style (Layout (..), defaultLayout, fillW, fixedH, minW)+import NanoUI.Internal.Types (DamageBounds (..), V2 (..), clamp, onGrid)+import NanoUI.Internal.Var (Binding (..), bindVar, bindVarBy)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.WidgetText (packTextNodeStyle)+import NanoUI.Internal.Widgets.Node (Response, addWidgetStyled, setChanged)+import NanoUI.Internal.Widgets.TextInput (fieldTextCommands, focusAndIme)+import qualified NanoUI.Widgets.TextBuffer as TB+import NanoUI.Internal.Widgets.TextDocument+import NanoUI.Widgets.TextEditor++-- | Editor buffer, selection anchor, viewport, scroll offsets, and undo history.+-- Positions use zero-based character rows/columns; viewport and scrolling use+-- logical pixels. The widget stores this under its stable id.+data TextAreaState = TextAreaState+  { tasBuffer :: !TB.TextBuffer+  , tasSelectionAnchor :: !TB.Cursor+  , tasScrollOffset :: !(Double, Double)+  , tasViewportSize :: !(Double, Double)+  , tasLineHeight :: !Double+  , tasHistory :: !EditHistory+  }+  deriving (Show)++-- | Start at the document origin with no selection or history and an unset viewport.+initTextAreaState :: T.Text -> TextAreaState+initTextAreaState initial =+  TextAreaState+    { tasBuffer = TB.fromText initial+    , tasSelectionAnchor = TB.Cursor 0 0+    , tasScrollOffset = (0.0, 0.0)+    , tasViewportSize = (0.0, 0.0)+    , tasLineHeight = 16.0+    , tasHistory = emptyHistory+    }++-- | Set logical viewport width/height and line height without moving the caret.+setTextAreaViewport :: (Double, Double) -> Double -> TextAreaState -> TextAreaState+setTextAreaViewport vp lh state =+  state {tasViewportSize = vp, tasLineHeight = lh}++-- | Set anchor and cursor, in that order, both clamped into the document, and+-- scroll vertically to reveal the caret.+setTextAreaSelection :: TB.Cursor -> TB.Cursor -> TextAreaState -> TextAreaState+setTextAreaSelection anchor cursor state =+  ensureCaretVisible state {tasBuffer = TB.withCursor cursor (tasBuffer state), tasSelectionAnchor = TB.clampCursor (tasBuffer state) anchor}++-- | Extract buffer, selection, and history for the shared text-command engine.+textAreaEditor :: TextAreaState -> Editor+textAreaEditor state = Editor (tasBuffer state) (tasSelectionAnchor state) (tasHistory state)++withEditor :: TextAreaState -> Editor -> TextAreaState+withEditor state ed =+  ensureCaretVisible state {tasBuffer = editorBuffer ed, tasSelectionAnchor = editorAnchor ed, tasHistory = editorHistory ed}++-- | Run a command that needs no clipboard, keeping the caret in view.+runTextAreaCommand :: TextCommand -> TextAreaState -> TextAreaState+runTextAreaCommand cmd state = withEditor state (runCommand multiLineMode cmd (textAreaEditor state))++ensureCaretVisible :: TextAreaState -> TextAreaState+ensureCaretVisible state =+  let TB.Cursor r _ = TB.getCursor (tasBuffer state)+      lh = tasLineHeight state+      vh = snd (tasViewportSize state)+      (sx, sy) = tasScrollOffset state+      caretY = fromIntegral r * lh+      maxSy = max 0 (fromIntegral (TB.getLineCount (tasBuffer state)) * lh - vh)+      sy'+        | vh <= 0 = 0+        | caretY < sy = caretY+        | caretY + lh > sy + vh = caretY + lh - vh+        | otherwise = sy+   in state {tasScrollOffset = (sx, clamp 0 maxSy sy')}++--------------------------------------------------------------------------------+-- Widget+--------------------------------------------------------------------------------++-- | Default viewport: grow horizontally, at least 200 pixels wide, 140 pixels tall.+textAreaLayout :: Layout+textAreaLayout = fixedH 140 . minW 200 . fillW $ defaultLayout++-- | Multi-line text editor over 'Text' bound to mutable state ('Var'). Pair it+-- with a 'label' when a caption is needed.+--+-- A frame that changes the text joins the whole document and mutates the+-- 'Var' in place, its Windows line ends (@\\r\\n@) written back as @\\n@.+-- For long documents use 'textAreaDocument', whose edits cost only the lines+-- they touch.+{-# INLINE textArea #-}+textArea :: Var Text -> NanoUI ()+textArea = void . textArea'++-- | 'textArea' returning its 'Response'. 'respChanged' reports a frame+-- that changed the text; caret and selection moves leave it unset.+{-# INLINE textArea' #-}+textArea' :: Var Text -> NanoUI Response+textArea' = textAreaWith' id++-- | 'textArea' with a modifier applied to 'textAreaLayout', for example+-- 'grow' to fill the parent. Font modifiers ('fontSize', 'fontMono',+-- 'fontColor' and the like) set the text.+{-# INLINE textAreaWith #-}+textAreaWith :: (Layout -> Layout) -> Var Text -> NanoUI ()+textAreaWith f = void . textAreaWith' f++-- | 'textAreaWith' returning its 'Response'.+textAreaWith' :: (Layout -> Layout) -> Var Text -> NanoUI Response+textAreaWith' f v = bindVar RenderFinal v $ \value -> do+  (wid, ctx) <- freshWidget+  store <- liftIO (getStore ctx)+  let -- The text last passed or returned, and its document: passing it back+      -- neither splits it again nor, while nothing is edited, joins it.+      cached = lookupSpec slotTextAreaText (intKey wid) store+      incoming = case cached of+        Just (t, doc) | t == value -> doc+        _ -> textDocument value+  (resp, doc) <- textAreaCore f wid incoming+  case cached of+    Just (t, d) | sameDocument d doc -> pure (resp, t)+    _ -> do+      let out = if sameDocument doc incoming then value else documentText doc+      liftIO $ modifyStore ctx (insertSpec slotTextAreaText (intKey wid) (out, doc))+      pure (resp, out)++-- | Multi-line text editor over a 'TextDocument' bound to mutable state ('Var').+-- An edit replaces the lines it touches and shares the rest, and a frame+-- without edits leaves the document as it was. Edits avoid joining the whole+-- document, though their cost still depends on affected lines and tree+-- operations. Join it with 'documentText' when the whole text is needed.+{-# INLINE textAreaDocument #-}+textAreaDocument :: Var TextDocument -> NanoUI ()+textAreaDocument = void . textAreaDocument'++-- | 'textAreaDocument' returning its 'Response'. 'respChanged' reports a+-- frame that changed the document; caret and selection moves leave it unset.+{-# INLINE textAreaDocument' #-}+textAreaDocument' :: Var TextDocument -> NanoUI Response+textAreaDocument' = textAreaDocumentWith' id++-- | 'textAreaDocument' with a modifier applied to 'textAreaLayout'.+{-# INLINE textAreaDocumentWith #-}+textAreaDocumentWith :: (Layout -> Layout) -> Var TextDocument -> NanoUI ()+textAreaDocumentWith f = void . textAreaDocumentWith' f++-- | 'textAreaDocumentWith' returning its 'Response'. Documents compare by+-- identity: walking their lines on every frame would cost what they save.+{-# INLINE textAreaDocumentWith' #-}+textAreaDocumentWith' :: (Layout -> Layout) -> Var TextDocument -> NanoUI Response+textAreaDocumentWith' f v = bindVarBy sameDocument RenderFinal v $ \value -> do+  wid <- nextId+  textAreaCore f wid value++-- | The text area at @wid@ over a document, returning its 'Response' and the+-- edited document. The text-area entry points share it after taking an id.+textAreaCore :: (Layout -> Layout) -> WidgetId -> TextDocument -> NanoUI (Response, TextDocument)+textAreaCore f wid value = do+  ctx <- askContext+  inp <- askInput+  store0 <- liftIO (getStore ctx)+  let layout = f textAreaLayout+      -- The face, weight and slant, packed as a text field's are.+      styleIdx = packTextNodeStyle layout 0+      key = intKey wid+      stored = lookupSpec slotTextAreaBuffer key store0+      adoptDocument+        | fmap bufferDocument stored == Just value = id+        | otherwise =+            insertSpec slotTextAreaBuffer key (maybe id keepCaret stored (documentBuffer value))+              . deleteSpec slotTextHistory key+      keepCaret old new = (TB.withCursor (TB.snapToCluster new (TB.getCursor old)) new) {TB.preferredCol = TB.preferredCol old}+  -- Adopt the caller's document the way 'adoptSlot' does. Comparing the+  -- document the caller passes back with the stored one is O(1) ('==' checks+  -- identity first). A replaced document gets a buffer over its lines, whose+  -- widths are then measured afresh, keeping the caret where it was, and its+  -- undo history, recorded against the old text, goes. Seed the scroll slot+  -- too: the wheel and drag paths write offsets through setScrollOffset2D,+  -- which only updates the text area's slot once it exists.+  when (lookupSpec (slotSeen fieldDocument) key store0 /= Just value) $+    liftIO . setStore ctx $+      insertSpec (slotSeen fieldDocument) key value+        . adoptDocument+        . overField fieldPoint (IM.insertWith (\_ old -> old) (specKey slotTextAreaScroll key) (V2 0 0))+        . insertSpec slotTextMode key multiLineMode+        $ store0+  store <- liftIO (getStore ctx)+  let current = maybe value bufferDocument (lookupSpec slotTextAreaBuffer key store)+      -- Set by commands run outside the frame ('applyTextFieldCommand') that+      -- changed the text; their edits carry no keys or chars, so this is the+      -- caller's respChanged pulse for them. Cleared in the state write below.+      menuPulse = memberSpec slotTextChanged key store+  isFocus <- focusAndIme ctx wid True InputNormal+  (newDoc, edited) <-+    if isFocus+      then do+        -- The font the rows are painted in ('resolveTextAreaFont').+        editFm <- fst <$> liftIO (resolveTextFont ctx (packedTextFont (layoutFontSize layout) styleIdx))+        let oldState = loadTextAreaState store key+            -- Rows sit on the device pixel grid ('textAreaLineHeight').+            s1 = setTextAreaViewport (tasViewportSize oldState) (realToFrac (onGrid (fmSnapScale editFm) (fmLineHeight editFm))) oldState+            hadInput = not (T.null (inputChars inp)) || not (inputKeysNull (inputKeys inp))+        newState <- liftIO $ do+          when hadInput $ modifyInteraction ctx (\s -> s {isTextInputDrag = Nothing})+          fieldTextCommands ctx multiLineMode inp >>= \case+            [] -> pure s1+            cmds -> withEditor s1 <$> foldM (flip (runCommandIO ctx multiLineMode)) (textAreaEditor s1) cmds+        let newBuf = tasBuffer newState+            -- Edits make new lines and moves keep them, so this reads no+            -- text; the editor drops edits that would change nothing.+            textChanged = not (sameLines (TB.bufferLines newBuf) (documentLines current))+            doc+              | textChanged = bufferDocument newBuf+              | otherwise = current+            edited = textChanged || menuPulse+            changed =+              edited+                || TB.getCursor newBuf /= TB.getCursor (tasBuffer oldState)+                || tasSelectionAnchor newState /= tasSelectionAnchor oldState+                || tasScrollOffset newState /= tasScrollOffset oldState+        -- Saving writes the new buffer, which is the document, and drops the+        -- menu pulse. The store damage is keyed on slots, not the widget, so+        -- damage the widget itself: a selection-only change (Ctrl+A) would+        -- otherwise repaint nothing until the next frame.+        when changed $+          liftIO $ do+            damageWidget ctx wid DamageSelf+            modifyStore ctx (deleteSpec slotTextChanged key . saveTextAreaState key newState)+        pure (doc, edited)+      else do+        -- A command run on the unfocused area ('applyTextFieldCommand') still+        -- pulses this frame's respChanged, once.+        when menuPulse $+          liftIO $ modifyStore ctx (deleteSpec slotTextChanged key)+        pure (current, menuPulse)+  -- Record what is returned as seen, so the caller passing it back is not+  -- taken for a replacement. A caller that passes an equal copy each frame+  -- gets the stored document back every frame; rewriting the slot then would+  -- damage it and wake the loop forever.+  unless (sameDocument newDoc value) $+    liftIO $ modifyStore ctx $ \st ->+      case lookupSpec (slotSeen fieldDocument) key st of+        Just seen | sameDocument seen newDoc -> st+        _ -> insertSpec (slotSeen fieldDocument) key newDoc st+  resp <- addWidgetStyled wid NodeTextArea "" 0 layout styleIdx+  -- respChanged reports an edit to the text, as on a text input; caret,+  -- selection and scroll moves only repaint the area.+  pure (setChanged edited resp, newDoc)++-- | The text area's 'TB.TextBuffer', which holds its document and caret. The+-- widget stores one over the lines of every document it adopts, so it is only+-- missing for a text area never declared, which holds an empty document.+textAreaBuffer :: WidgetStore -> Int -> TB.TextBuffer+textAreaBuffer store key = fromMaybe TB.empty (lookupSpec slotTextAreaBuffer key store)++-- | The text area's editor state as stored.+loadTextAreaState :: WidgetStore -> Int -> TextAreaState+loadTextAreaState store key =+  let buf = textAreaBuffer store key+      TB.Cursor row col = TB.getCursor buf+      anchorRow = findSpec slotTextAreaAnchorRow row key store+      anchorCol = findSpec slotTextAreaAnchorCol col key store+      V2 sx sy = findSpec slotTextAreaScroll (V2 0 0) key store+      V2 vw vh = findSpec slotTextAreaViewport (V2 200 96) key store+   in TextAreaState+        { tasBuffer = buf+        , tasSelectionAnchor = TB.clampCursor buf (TB.Cursor anchorRow anchorCol)+        , tasScrollOffset = (realToFrac sx, realToFrac sy)+        , tasViewportSize = (realToFrac vw, realToFrac vh)+        , tasLineHeight = realToFrac (findSpec slotTextAreaLineH 16 key store)++        , -- Replacing the document drops its history, so the history is+          -- always the current document's.+          tasHistory = case lookupSpec slotTextHistory key store of+            Just (AreaHistory h) -> h+            _ -> emptyHistory+        }++-- | Store the editor state. The buffer holds the document and the caret. The+-- state keeps the caret in view vertically; the next paint, which has the+-- font, brings it into view across ('SlotTextAreaReveal').+saveTextAreaState :: Int -> TextAreaState -> WidgetStore -> WidgetStore+saveTextAreaState key state =+  insertSpec slotTextAreaScroll key (V2 (realToFrac sx) (realToFrac sy))+    . insertSpec slotTextAreaReveal key 1+    . insertSpec slotTextAreaViewport key (V2 (realToFrac vw) (realToFrac vh))+    . insertSpec slotTextAreaBuffer key (tasBuffer state)+    . insertSpec slotTextHistory key (AreaHistory (tasHistory state))+    . insertSpec slotTextAreaAnchorRow key anchorRow+    . insertSpec slotTextAreaAnchorCol key anchorCol+  where+    TB.Cursor anchorRow anchorCol = tasSelectionAnchor state+    (sx, sy) = tasScrollOffset state+    (vw, vh) = tasViewportSize state++-- | A text area's stored editor, for a command run outside its frame, and+-- how to store the edited editor, keeping the caret in view.+textAreaFieldEditor :: WidgetStore -> Int -> (Editor, Editor -> WidgetStore -> WidgetStore)+textAreaFieldEditor store key =+  let state = loadTextAreaState store key+   in (textAreaEditor state, saveTextAreaState key . withEditor state)
+ lib/NanoUI/Internal/Widgets/TextDocument.hs view
@@ -0,0 +1,122 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Implementation of "NanoUI.Widgets.TextDocument", plus the conversions+-- between a document and the widgets' text buffer.+module NanoUI.Internal.Widgets.TextDocument+  ( TextDocument+  , textDocument+  , emptyDocument+  , documentText+  , documentLines+  , documentLine+  , documentLineCount+  , sameDocument+  , documentRange+  , editDocument+  , replaceDocumentRange+  , documentBuffer+  , bufferDocument++    -- * For the widgets+  , sameLines+  ) where++import Data.Functor.Classes (liftEq)+import Data.Maybe (fromMaybe)+import Data.Sequence (Seq)+import Data.Sequence qualified as Seq+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Internal.Equality (eqByPtr, ptrEq)+import NanoUI.Widgets.TextBuffer qualified as TB++-- | A text as its lines, without their newlines. There is always at least+-- one line.+newtype TextDocument = TextDocument (Seq Text)++-- | Documents with the same text are equal. A document compared with itself,+-- such as the one a text area returned last frame, is equal at once, however+-- long it is. An edited document shares its untouched lines with the one it+-- was edited from, so comparing the two reads no text before the edit.+instance Eq TextDocument where+  a == b =+    sameDocument a b+      || liftEq eqByPtr (documentLines a) (documentLines b)++instance Show TextDocument where+  showsPrec d doc =+    showParen+      (d > 10)+      (showString "textDocument " . showsPrec 11 (documentText doc))++-- | Split a text into a document. O(length of the text). A Windows line end+-- (@\\r\\n@) is one line break, so 'documentText' ends lines with @\\n@.+textDocument :: Text -> TextDocument+textDocument = TextDocument . TB.splitLines++-- | A document holding one empty line.+emptyDocument :: TextDocument+emptyDocument = TextDocument (Seq.singleton T.empty)++-- | The lines joined with newlines. O(length of the text).+documentText :: TextDocument -> Text+documentText = TB.joinLines . documentLines++-- | Share the document's line sequence without joining or copying text. Lines+-- exclude newline separators; the sequence always contains at least one line.+documentLines :: TextDocument -> Seq Text+documentLines (TextDocument lns) = lns++-- | The text of a line, or empty outside the document. O(log lines).+documentLine :: Int -> TextDocument -> Text+documentLine row doc = fromMaybe T.empty (Seq.lookup row (documentLines doc))++-- | Number of lines in O(1), including the empty line in an empty document.+documentLineCount :: TextDocument -> Int+documentLineCount = Seq.length . documentLines++-- | Whether two documents are the same value, in O(1). Equal documents built+-- separately may still return 'False'; '==' compares their text.+sameDocument :: TextDocument -> TextDocument -> Bool+sameDocument a b = sameLines (documentLines a) (documentLines b)++-- | The text between two positions, in either order and clamped to the+-- document, with a newline for each line break crossed. Reads only the lines+-- between them.+documentRange :: TB.Cursor -> TB.Cursor -> TextDocument -> Text+documentRange a b = TB.selectedText a b . documentBuffer++-- | Apply an edit, as a text area records one ('TB.replaceEdit' makes one).+-- The new document shares every line the edit does not touch, so it costs+-- O(log lines) plus the lines it spans, and a text area given it redraws+-- only those lines.+editDocument :: TB.TextEdit -> TextDocument -> TextDocument+editDocument e = bufferDocument . TB.applyEdit e . documentBuffer++-- | Replace the text between two positions (in either order, clamped) with+-- @inserted@, which may hold newlines:+--+-- > replaceDocumentRange (Cursor 0 0) (Cursor 0 5) "Hello" doc+replaceDocumentRange :: TB.Cursor -> TB.Cursor -> Text -> TextDocument -> TextDocument+replaceDocumentRange a b inserted doc = editDocument (TB.replaceEdit inserted a b (documentBuffer doc)) doc++-- | The document a buffer holds, sharing its lines, in O(1). The buffer's+-- lines must not contain newlines, as no buffer built by 'TB.fromText' or+-- edited with 'TB.applyEdit' does.+bufferDocument :: TB.TextBuffer -> TextDocument+bufferDocument = TextDocument . TB.bufferLines++-- | A buffer over the document's lines, sharing them, with the cursor at the+-- start, in O(1): for moving through a document or running+-- "NanoUI.Widgets.TextBuffer" functions over it.+documentBuffer :: TextDocument -> TB.TextBuffer+documentBuffer = TB.fromLines . documentLines++-- | Whether two line sequences are the same heap object. An edit makes new+-- lines and a cursor move keeps them, so this tells an edited buffer from a+-- moved one without reading any text. It can return 'False' for the same+-- lines (GHC may compare an evaluated value with a reference to it before+-- evaluation), never 'True' for different ones; callers treat 'False' as+-- "maybe changed". Both arguments are forced first, so neither is a thunk.+sameLines :: Seq Text -> Seq Text -> Bool+sameLines !a !b = ptrEq a b
+ lib/NanoUI/Internal/Widgets/TextInput.hs view
@@ -0,0 +1,437 @@+-- | Single-line text fields: editable inputs, debounced search fields, and+-- selectable read-only labels, plus the key handling they share.+module NanoUI.Internal.Widgets.TextInput+  ( TextInputState (..)+  , loadTextInputState+  , saveTextInputState+  , searchInputLayout+  , editorTextState+  , cursorOffset+  , cursorAtOffset+  , saveTextEditor+  , editTextInput+  , fieldTextCommands+  , textInputMode+  , textInputFieldEditor+    -- * Text fields+  , TextInputConfig (..)+  , defaultTextInputConfig+  , textInput+  , textInput'+  , textInputConfigured+  , textInputConfigured'+  , SearchInputConfig (..)+  , defaultSearchInputConfig+  , searchInput+  , searchInput'+  , searchInputConfigured+  , searchInputConfigured'+  , buildTextInput+  , editTextField+  , focusAndIme+    -- * Selectable text+  , selectableText+  , selectableText'+  , selectableTextWith+  , selectableTextWith'+  )+where++import Control.Monad (foldM, void, when)+import Data.Bits ((.|.))+import Data.Char (isControl)+import Data.Maybe (fromMaybe, isNothing, listToMaybe)+import Data.Sequence qualified as Seq+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word64)+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.Context+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Monad (NanoUI, askContext, askDefaultLayout, askInput, freshWidget, nextId, liftIO, withContext)+import NanoUI.Internal.Store+import NanoUI.Internal.Store.Slots (slotSearchAge, slotSearchCommitted, slotTextChanged, slotTextHistory, slotTextMode)+import NanoUI.Internal.Store.Types (TextHistory (..))+import NanoUI.Internal.Style (Layout (..), LayoutModifier, Style (..), Theme (..), defaultLayout, fieldIconColor, fillW, minW)+import NanoUI.Internal.Types (Color, clamp)+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.WidgetText (hasFlag, packTextNodeStyle, textInputFlagPassword, textInputFlagSearch, textInputFlagSelectable)+import NanoUI.Internal.Widgets.Adornment (Adornments, adornWidget)+import NanoUI.Internal.Widgets.Behavior (keyboardFocused)+import NanoUI.Internal.Widgets.Combinators (widgetBaseLayout)+import NanoUI.Internal.Widgets.Node (Response (..), addWidgetStyled, inertResponse, respId, setChanged, setSubmitted)+import NanoUI.Widgets.TextBuffer qualified as TB+import NanoUI.Widgets.TextEditor++textInputLayout :: Layout+textInputLayout = minW 160 (fillW defaultLayout)++-- | Layout for a caption-less search field. Grows to fill, keeps a little more+-- room for the embedded magnifier / clear chrome than a plain text input.+searchInputLayout :: Layout+searchInputLayout = minW 180 (fillW defaultLayout)++data TextInputState = TextInputState+  { tisText :: !Text+  , tisCursor :: !Int+  , tisAnchor :: !Int+  }+  deriving (Eq, Show)++-- | A field's cursor and anchor for @text@ ('fieldSelection').+loadTextInputState :: WidgetStore -> Int -> Text -> TextInputState+loadTextInputState store key text =+  let (anchor, cursor) = fieldSelection store key text+   in TextInputState text cursor anchor++saveTextInputState :: Int -> TextInputState -> WidgetStore -> WidgetStore+saveTextInputState key s =+  insertSlot fieldText key (tisText s) . setFieldSelection key (tisAnchor s) (tisCursor s)++-- | The editor for a field's state, with the undo history stored for it. A+-- history recorded against other text (the caller replaced the value) is+-- dropped. The rows keep a Windows line end's @\\r@ ('TB.fromText' would drop+-- it), so the value comes back as it was and its offsets count every+-- character.+textInputEditor :: WidgetStore -> Int -> TextInputState -> Editor+textInputEditor store key s =+  let buf0 = TB.fromLines (Seq.fromList (T.splitOn "\n" (tisText s)))+      buf = TB.withCursor (cursorAtOffset (tisText s) (tisCursor s)) buf0+      history = case lookupSpec slotTextHistory key store of+        Just (FieldHistory text h) | text == tisText s -> h+        _ -> emptyHistory+   in Editor buf (cursorAtOffset (tisText s) (tisAnchor s)) history++editorTextState :: Editor -> TextInputState+editorTextState ed =+  let buf = editorBuffer ed+      txt = TB.toText buf+   in TextInputState txt (cursorOffset txt (TB.getCursor buf)) (cursorOffset txt (editorAnchor ed))++-- | The character a row and column of @txt@'s lines (split at @\\n@) is at,+-- clamped into the text.+cursorOffset :: Text -> TB.Cursor -> Int+cursorOffset txt (TB.Cursor row col) =+  let ls = T.splitOn "\n" txt+      row' = clamp 0 (length ls - 1) row+      before = sum (map T.length (take row' ls)) + row'+      line = fromMaybe "" (listToMaybe (drop row' ls))+   in before + clamp 0 (T.length line) col++-- | The row and column of character @offset@ of @txt@ ('cursorOffset'),+-- clamped into the text.+cursorAtOffset :: Text -> Int -> TB.Cursor+cursorAtOffset txt offset =+  let prefix = T.take (clamp 0 (T.length txt) offset) txt+      row = T.count "\n" prefix+      col = T.length (T.takeWhileEnd (/= '\n') prefix)+   in TB.Cursor row col++-- | Store an editor's text, selection and history.+saveTextEditor :: Int -> Editor -> WidgetStore -> WidgetStore+saveTextEditor key ed =+  let s = editorTextState ed+   in insertSpec slotTextHistory key (FieldHistory (tisText s) (editorHistory ed)) . saveTextInputState key s++-- | Run this frame's commands on a field, or 'Nothing' when it had none.+editTextInput :: Context -> EditorMode -> Input -> WidgetStore -> Int -> TextInputState -> IO (Maybe Editor)+editTextInput ctx mode inp store key s0 =+  fieldTextCommands ctx mode inp >>= \case+    [] -> pure Nothing+    cmds -> Just <$> foldM (flip (runCommandIO ctx mode)) (textInputEditor store key s0) cmds++-- | This frame's edit commands for the focused field ('inputTextCommands').+-- Under 'FocusComposing' the typed text is the IME commit and is inserted+-- regardless of modifiers, so a chord that ends a composition keeps it.+fieldTextCommands :: Context -> EditorMode -> Input -> IO [TextCommand]+fieldTextCommands ctx mode inp = do+  kind <- getsInteraction ctx isFocusKind+  pure $+    if kind == FocusComposing+      then+        let committed = T.filter (not . isControl) (inputChars inp)+         in ([InsertText committed | not (T.null committed)])+              ++ inputTextCommands mode inp {inputChars = T.empty}+      else inputTextCommands mode inp++-- | The editor mode of a single-line field with these style flags.+textInputMode :: Word64 -> EditorMode+textInputMode si =+  singleLineMode+    { modeEditable = not (hasFlag textInputFlagSelectable si)+    , modeCopyable = not (hasFlag textInputFlagPassword si)+    }++-- | A single-line field's stored editor, for a command run outside its frame,+-- and how to store the edited editor.+textInputFieldEditor :: WidgetStore -> Int -> (Editor, Editor -> WidgetStore -> WidgetStore)+textInputFieldEditor store key =+  (textInputEditor store key (loadTextInputState store key (findSlot fieldText "" key store)), saveTextEditor key)++-- -----------------------------------------------------------------------------+-- Text fields+-- -----------------------------------------------------------------------------++-- | Placeholder, password-display masking, layout, and adornments+-- ("NanoUI.Adornment", in a muted text colour) for a single-line field.+-- Masking affects display; the caller and widget store still hold the+-- original text.+data TextInputConfig = TextInputConfig+  { ticPlaceholder :: !Text+  , ticPassword :: !Bool+  , ticLayout :: !LayoutModifier+  , ticAdornments :: !Adornments+  }++-- | No placeholder, no password masking, the standard text-input layout, and+-- no adornments.+defaultTextInputConfig :: TextInputConfig+defaultTextInputConfig =+  TextInputConfig+    { ticPlaceholder = ""+    , ticPassword = False+    , ticLayout = id+    , ticAdornments = mempty+    }++-- | Single-line text field bound to mutable state ('Var'): typing, pastes and+-- menu edits update it in place.+--+-- > textInput draft+{-# INLINE textInput #-}+textInput :: Var Text -> NanoUI ()+textInput v = void (textInputConfigured' defaultTextInputConfig v)++-- | 'textInput' returning its 'Response', with change and submit flags.+{-# INLINE textInput' #-}+textInput' :: Var Text -> NanoUI Response+textInput' = textInputConfigured' defaultTextInputConfig++-- | 'textInput' with a placeholder, password masking, its own layout, or+-- adornments.+--+-- > textInputConfigured defaultTextInputConfig {ticPassword = True} secret+-- > textInputConfigured defaultTextInputConfig {ticAdornments = A.trailing (A.affix "kg")} weight+{-# INLINE textInputConfigured #-}+textInputConfigured :: TextInputConfig -> Var Text -> NanoUI ()+textInputConfigured cfg v = void (textInputConfigured' cfg v)++-- | 'textInputConfigured' returning its 'Response'.+{-# INLINE textInputConfigured' #-}+textInputConfigured' :: TextInputConfig -> Var Text -> NanoUI Response+textInputConfigured' (TextInputConfig placeholder password f adorns) v = do+  lay <- widgetBaseLayout textInputLayout f+  -- Write the field's text before running adornments so an adornment+  -- control that modifies the 'Var' overwrites the field's value.+  resp <-+    bindVar RenderFinal v $ \value ->+      buildTextInput (if password then textInputFlagPassword else 0) lay placeholder value Nothing+  -- Suppress the field's response when an adornment control captures the pointer.+  taken <- adornWidget (respId resp) lay (fieldAdornmentColor lay) adorns+  pure (if taken then inertResponse resp else resp)++fieldAdornmentColor :: Layout -> Theme -> Color+fieldAdornmentColor lay theme =+  let s = themeInput theme+   in fieldIconColor s {styleFg = fromMaybe (styleFg s) (layoutFontColor lay)}++-- | Register a focusable field and request IME input when it holds keyboard+-- focus and @acceptIme@ is 'True'.+focusAndIme :: Context -> WidgetId -> Bool -> InputPurpose -> NanoUI Bool+focusAndIme ctx wid acceptIme purpose = do+  liftIO $ registerFocusable ctx wid+  isFocus <- keyboardFocused wid+  when (isFocus && acceptIme) $+    liftIO (requestInputMethod ctx wid Nothing purpose)+  pure isFocus++singleLinePasswordMode :: EditorMode+singleLinePasswordMode = singleLineMode {modeCopyable = False}++-- | One frame of a single-line field's text state: load the text (seeding+-- @initial@ on first use) with its cursor and anchor, run the editor while+-- focused, and save any change. While unfocused, @unfocusedText@ (when given)+-- replaces the stored text, so a field that mirrors another value follows it.+-- Returns the text before and after this frame, whether it is focused, and+-- whether a command run from outside the frame changed it.+editTextField :: WidgetId -> EditorMode -> Text -> Maybe Text -> NanoUI (Text, Text, Bool, Bool)+editTextField wid mode initial unfocusedText = do+  ctx <- askContext+  store <- liftIO (getStore ctx)+  let !key = intKey wid+      stored = lookupSlot fieldText key store+      !pulse = memberSpec slotTextChanged key store+      !modeMatches = case lookupSpec slotTextMode key store of+        Just m -> m == mode+        Nothing -> False+  when (isNothing stored || not modeMatches || pulse) $+    liftIO . modifyStore ctx $+      (if isNothing stored then insertSlot fieldText key initial else id)+        . deleteSpec slotTextChanged key+        . insertSpec slotTextMode key mode+  -- Password fields request 'InputSecure' so the IME does not display or+  -- record their text.+  isFocus <- focusAndIme ctx wid (modeEditable mode) (if modeCopyable mode then InputNormal else InputSecure)+  let !curText = fromMaybe initial stored+  if not isFocus && maybe True (eqByPtr curText) unfocusedText+    then pure (curText, curText, False, pulse)+    else do+      inp <- askInput+      let s0 = loadTextInputState store key curText+      mEdited <- if isFocus then liftIO (editTextInput ctx mode inp store key s0) else pure Nothing+      let s1 = case mEdited of+            Just ed -> editorTextState ed+            Nothing+              -- A focused field keeps what the user typed, or a command run+              -- between frames stored, until it loses focus.+              | isFocus -> s0+              | otherwise -> maybe s0 (\t -> s0 {tisText = t}) unfocusedText+      when (s1 /= s0) $+        liftIO $ modifyStore ctx (maybe (saveTextInputState key s1) (saveTextEditor key) mEdited)+      pure (tisText s0, tisText s1, isFocus, pulse)++-- | Shared single-line field builder. The caller's @value@ is adopted as by+-- 'adoptSlot'. @styleIdx@ may carry the search or password+-- flag on a @NodeTextInput@; when @mDebounceMs@ is present the returned change+-- pulse is delayed until the text has been idle for that long (immediate for+-- clear clicks).+buildTextInput ::+  Word64 ->+  Layout ->+  Text ->+  Text ->+  Maybe Float ->+  NanoUI (Response, Text)+buildTextInput styleIdx layout placeholder value mDebounceMs = do+  (wid, ctx) <- freshWidget+  let !key = intKey wid+  _ <- liftIO $ adoptSlot fieldText ctx wid value+  -- Both modes are constants, so an idle field allocates no mode record.+  let mode = if hasFlag textInputFlagPassword styleIdx then singleLinePasswordMode else singleLineMode+  (oldText, newText, isFocus, pulse) <- editTextField wid mode value Nothing+  liftIO $ recordSlot fieldText ctx key newText+  inp <- askInput+  let !submitted = isFocus && pressedOnceIn KeyEnter inp+      !edited = pulse || not (eqByPtr newText oldText)+  changed <- maybe (pure edited) (liftIO . debounceSearchChanged ctx key isFocus edited) mDebounceMs+  -- The layout's font face, weight and slant ride in the style bits, as on+  -- a label; the flags sit above them.+  resp <- addWidgetStyled wid NodeTextInput placeholder 0 layout (styleIdx .|. packTextNodeStyle layout 0)+  pure (setSubmitted submitted (setChanged changed resp), newText)++-- | Debounced change pulse for a search field. Fires when the text differs from+-- the last committed query and either the field is empty, lost focus, or has+-- been idle for @ms@ (trailing edge). Field text lives under @key@; the last+-- committed query under 'SlotSearchCommitted'. While an edit waits to commit,+-- the frame that will commit it is scheduled with 'requestWakeAt'.+debounceSearchChanged :: Context -> Int -> Bool -> Bool -> Float -> IO Bool+debounceSearchChanged ctx key focused rawChanged ms = do+  store <- getStore ctx+  let+    current = findSlot fieldText "" key store+    committedMissing = not (memberSpec slotSearchCommitted key store)+    committed = findSpec slotSearchCommitted current key store+    dirty = current /= committed+    needClock = rawChanged || dirty+  now <- if needClock then getMonotonicTime else pure 0+  let+    -- Debounce timing stays in Double: wall-clock seconds as Float lose+    -- resolution at long uptimes (~125 ms at 12 days), which would shift+    -- (or skip) the trailing-edge window.+    lastEdit = findSpec slotSearchAge now key store+    deadline = realToFrac ms :: Double+    idleMs = (now - lastEdit) * 1000+    -- An edit this frame has not been idle for any time yet.+    commit = dirty && (T.null current || not focused || (not rawChanged && idleMs >= deadline))+    -- Text the caller changed, in a field nobody has typed in, has no edit+    -- time to age from. Its pause starts now: left unstamped, every frame+    -- would see a fresh edit, and the commit would never come.+    stamp = rawChanged || commit || (dirty && not (memberSpec slotSearchAge key store))+  when (stamp || committedMissing) $+    modifyStore ctx $+      (if commit || committedMissing then insertSpec slotSearchCommitted key current else id)+        . (if stamp then insertSpec slotSearchAge key now else id)+  -- Schedule a wake-up at the debounce deadline since no input event will+  -- arrive when the pause expires.+  when (dirty && not commit) $+    requestWakeAt ctx ((if rawChanged then now else lastEdit) + deadline / 1000 + 0.001)+  pure commit++-- | Search field: a caption-less 'NodeTextInput' with an embedded magnifier and+-- clear button. The label acts as the placeholder. Change pulses are debounced+-- (trailing edge); clearing with the embedded button fires immediately.+data SearchInputConfig = SearchInputConfig+  { sicPlaceholder :: !Text+  , sicDebounceMs :: !Float+  , sicLayout :: !LayoutModifier+  }++-- | Search placeholder, a 300 ms trailing debounce, and the standard search layout.+defaultSearchInputConfig :: SearchInputConfig+defaultSearchInputConfig =+  SearchInputConfig+    { sicPlaceholder = "Search…"+    , sicDebounceMs = 300+    , sicLayout = id+    }++-- | Search box with a magnifier and a clear button, bound to mutable state+-- ('Var'); the first argument is the placeholder. The 'Var' is mutated in place+-- as the user types; @respChanged@ on @searchInput'@ is debounced and fires+-- once typing pauses, or immediately when the field is cleared.+{-# INLINE searchInput #-}+searchInput :: Text -> Var Text -> NanoUI ()+searchInput placeholder v = void (searchInput' placeholder v)++-- | 'searchInput' returning its 'Response'.+{-# INLINE searchInput' #-}+searchInput' :: Text -> Var Text -> NanoUI Response+searchInput' placeholder =+  searchInputConfigured' (defaultSearchInputConfig {sicPlaceholder = placeholder})++-- | Search field with explicit placeholder, debounce in milliseconds, and layout.+{-# INLINE searchInputConfigured #-}+searchInputConfigured :: SearchInputConfig -> Var Text -> NanoUI ()+searchInputConfigured cfg v = void (searchInputConfigured' cfg v)++-- | 'searchInputConfigured' returning its 'Response'.+{-# INLINE searchInputConfigured' #-}+searchInputConfigured' :: SearchInputConfig -> Var Text -> NanoUI Response+searchInputConfigured' cfg v = do+  lay <- widgetBaseLayout searchInputLayout (sicLayout cfg)+  bindVar RenderFinal v $ \value ->+    buildTextInput textInputFlagSearch lay (sicPlaceholder cfg) value (Just (sicDebounceMs cfg))++-- -----------------------------------------------------------------------------+-- Selectable text+-- -----------------------------------------------------------------------------++-- | Read-only text that can be selected with the mouse and copied with the+-- platform's copy shortcut (Ctrl+C, Command+C on macOS) or the context menu.+{-# INLINE selectableText #-}+selectableText :: Text -> NanoUI ()+selectableText = selectableTextWith id++-- | 'selectableText' with its response, for hover or anchored UI.+{-# INLINE selectableText' #-}+selectableText' :: Text -> NanoUI Response+selectableText' = selectableTextWith' id++-- | Read-only selectable text with a layout/font modifier.+{-# INLINE selectableTextWith #-}+selectableTextWith :: (Layout -> Layout) -> Text -> NanoUI ()+selectableTextWith f txt = void (selectableTextWith' f txt)++-- | 'selectableTextWith' returning its response; text remains caller-owned.+selectableTextWith' :: (Layout -> Layout) -> Text -> NanoUI Response+selectableTextWith' f txt = do+  layout <- f <$> askDefaultLayout+  wid <- nextId+  -- The caller owns the text; the editor only moves the selection.+  _ <- withContext (\ctx -> adoptSlot fieldText ctx wid txt)+  _ <- editTextField wid singleLineMode {modeEditable = False} txt Nothing+  let styleIdx = textInputFlagSelectable .|. packTextNodeStyle layout 0+  addWidgetStyled wid NodeTextInput txt 0 layout styleIdx
+ lib/NanoUI/Internal/Widgets/Tree.hs view
@@ -0,0 +1,185 @@+-- | Expandable tree rows with a controlled pre-order selection index. Each+-- row is a button in the row look (@buttonFlagRow@).+module NanoUI.Internal.Widgets.Tree (TreeItem (..), tree, tree') where++import Control.Monad (void, when, zipWithM)+import Data.IORef (writeIORef)+import Data.Foldable (asum, find, fold, toList)+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray, smallArrayFromList)+import qualified Data.IntSet as IS+import NanoUI.Internal.Context (Context (..), adoptSlot, getPrevRect, getStore, intKey, registerFocusable, writeSlots)+import NanoUI.Internal.Font (treeChevronRect)+import NanoUI.Internal.Derived (TreeItem (..), TreeRow, TreeRows (..), treeCache)+import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)+import NanoUI.Internal.Input (inputMousePos)+import NanoUI.Internal.Layout.Arena (NodeType (..))+import NanoUI.Internal.Store (fieldInt, fieldIntSet, lookupSlot, ptrEq, slotWrite)+import NanoUI.Internal.Monad (NanoUI, askInput, focusedWidget, freshWidget, liftIO, withKey)+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Style (defaultLayout, fillW, gap, tight)+import NanoUI.Internal.Types (Rect (..), clamp, rectContains)+import NanoUI.Internal.WidgetText (treeEncodeStyle)+import NanoUI.Internal.Widgets.Behavior (KeyNav (..), useKeyNav)+import NanoUI.Internal.Widgets.Combinators (finishInput, readDerived, writeDerived)+import NanoUI.Internal.Widgets.Layout (columnWith)+import NanoUI.Internal.Widgets.Node (Response (..), addWidgetStyled, moveSelection, setChanged, tagContainer)++subtreeSize :: TreeItem -> Int+subtreeSize item = 1 + forestSize (treeItemChildren item)++forestSize :: [TreeItem] -> Int+forestSize = foldl' (\acc x -> acc + subtreeSize x) 0++-- | Visible rows in pre-order, skipping the children of collapsed nodes.+-- Single pass: each subtree passes the next pre-order index to the+-- continuation for its remaining siblings.+visibleRows :: (Int -> Bool) -> [TreeItem] -> SmallArray TreeRow+visibleRows expanded items = smallArrayFromList (go 0 0 items (const []))+  where+    go !idx !_ [] k = k idx+    go !idx !depth (item@(TreeItem lbl kids) : rest) k =+      let hasKids = not (null kids)+       in (idx, depth, hasKids, lbl)+            : if hasKids && expanded idx+              then go (idx + 1) (depth + 1) kids (\next -> go next depth rest k)+              else go (idx + subtreeSize item) depth rest k++-- | The item count and visible rows, from the cache while the items are the+-- same container and the expansion set is equal. The caller's container is+-- compared, not a list made from it, so a vector or sequence hits too. The+-- items are compared evaluated: an argument that is a top-level constant is+-- a thunk until forced.+cachedRows :: Foldable f => Context -> Int -> f TreeItem -> IS.IntSet -> IO (Int, SmallArray TreeRow)+cachedRows ctx key !items !expanded = do+  cached <- readDerived treeCache ctx key+  case cached of+    Just (TreeRows items' expanded' total rows)+      | ptrEq items' items && expanded' == expanded -> pure (total, rows)+    _ -> do+      let list = toList items+          !total = forestSize list+          !rows = visibleRows (`IS.member` expanded) list+      (total, rows) <$ writeDerived treeCache ctx key (TreeRows items expanded total rows)++treeKeyNav ::+  KeyNav ->+  SmallArray TreeRow ->+  SmallArray Response ->+  WidgetId ->+  Int ->+  IS.IntSet ->+  (Int, IS.IntSet, Maybe WidgetId)+treeKeyNav nav rows resps focus selected expanded+  | hashWidgetId focus == 0 || not moving = stay+  | otherwise = maybe stay (\pos -> step pos (rowAt pos)) (find ((== focus) . widAt) [0 .. n - 1])+ where+  moving = knUp nav || knDown nav || knLeft nav || knRight nav || knEnter nav || knSpace nav+  n = sizeofSmallArray rows+  rowAt = indexSmallArray rows+  widAt i = rawRespId (indexSmallArray resps i)+  stay = (selected, expanded, Nothing)+  moveTo p = let (idx, _, _, _) = rowAt p in (idx, expanded, Just (widAt p))+  expandTo s = (selected, s, Nothing)+  step pos (nodeIdx, depth, hasKids, _)+    | knDown nav, pos + 1 < n = moveTo (pos + 1)+    | knUp nav, pos > 0 = moveTo (pos - 1)+    | knEnter nav || knSpace nav, hasKids = expandTo (toggle nodeIdx expanded)+    | knRight nav, hasKids, not open = expandTo (IS.insert nodeIdx expanded)+    | knLeft nav, hasKids, open = expandTo (IS.delete nodeIdx expanded)+    | knLeft nav, depth > 0 =+        maybe (nodeIdx, expanded, Nothing) moveTo $+          find (\i -> let (_, d, _, _) = rowAt i in d < depth) [pos - 1, pos - 2 .. 0]+    | otherwise = stay+   where+    open = IS.member nodeIdx expanded++toggle :: Int -> IS.IntSet -> IS.IntSet+toggle idx s = if IS.member idx s then IS.delete idx s else IS.insert idx s++-- | Render one visible row and return any selection or expansion change:+-- clicking a parent's chevron toggles expansion without changing selection.+treeRow ::+  Int -> TreeRow -> Int -> IS.IntSet -> NanoUI (Response, Maybe (Int, IS.IntSet))+treeRow rowIdx (nodeIdx, depth, hasKids, lbl) selected expanded = do+  (wid, ctx) <- freshWidget+  inp <- askInput+  let style = treeEncodeStyle depth hasKids (IS.member nodeIdx expanded) (odd rowIdx)+      value = if selected == nodeIdx then 1 else 0+  resp <- addWidgetStyled wid NodeButton lbl value (tight . fillW $ defaultLayout) style+  liftIO $ registerFocusable ctx wid+  if not (rawRespClicked resp)+    then pure (resp, Nothing)+    else liftIO $ do+      mrect <- getPrevRect ctx wid+      let mouse = inputMousePos inp+          onChevron = case mrect of+            Just rect@(Rect x y _ h) ->+              rectContains (treeChevronRect (ctxFontMetrics ctx) x y h depth) mouse+                && rectContains rect mouse+            _ -> False+      pure . (resp,) . Just $+        if hasKids && onChevron then (selected, toggle nodeIdx expanded) else (nodeIdx, expanded)++-- | Collapsible tree with the selected row bound to mutable state ('Var').+-- Rows are numbered in pre-order; a click or the arrow keys update the+-- selection in place. Expansion state is stored internally by the widget.+-- @key@ distinguishes trees in one scope.+{-# INLINE tree #-}+tree :: Foldable f => Text -> f TreeItem -> Var Int -> NanoUI ()+tree key items v = void (tree' key items v)++-- | 'tree' returning its 'Response'.+{-# INLINE tree' #-}+tree' :: Foldable f => Text -> f TreeItem -> Var Int -> NanoUI Response+tree' key items v = bindVar RenderFinal v (treeCore key items)++-- | 'tree' on a plain row index: the response and the selection after this+-- frame.+treeCore :: Foldable f => Text -> f TreeItem -> Int -> NanoUI (Response, Int)+treeCore key inputItems index =+  withKey ("tree:" <> key) $ do+    (groupId, ctx) <- freshWidget+    let groupKey = intKey groupId+        -- Every parent starts expanded. Any parent sits under one at the top+        -- level, so the top level alone tells a forest that has none.+        allParents+          | any (not . null . treeItemChildren) inputItems =+              IS.fromList [i | (i, _, True, _) <- toList (visibleRows (const True) (toList inputItems))]+          | otherwise = IS.empty+    storedExp <- lookupSlot fieldIntSet groupKey <$> liftIO (getStore ctx)+    let expandedSet = fromMaybe allParents storedExp+    (total, rows) <- liftIO (cachedRows ctx groupKey inputItems expandedSet)+    let clamped = if total <= 0 then 0 else clamp 0 (total - 1) index+    selected <- liftIO $ adoptSlot fieldInt ctx groupId clamped+    columnWith (tight . gap 0 . fillW) $ do+      tagContainer groupId+      results <-+        zipWithM+          (\rowIdx row@(i, _, _, _) -> withKey i (treeRow rowIdx row selected expandedSet))+          [0 ..]+          (toList rows)+      let resps = smallArrayFromList (map fst results)+          clicked = asum (map snd results)+          (clickSel, clickExp) = fromMaybe (selected, expandedSet) clicked+      focus <- focusedWidget+      nav <- useKeyNav focus+      let (keySel, keyExp, mFocus) = treeKeyNav nav rows resps focus clickSel clickExp+          -- A click on a row picks it, and one on a chevron only expands; the+          -- arrow keys pick the row they move focus to.+          picked = isJust mFocus || maybe False ((== expandedSet) . snd) clicked+      liftIO (moveSelection ctx selected keySel [(i, r) | ((i, _, _, _), (r, _)) <- zip (toList rows) results])+      (resp, s) <- finishInput fieldInt ctx groupId selected (fold resps) keySel+      -- Items that arrive after a first frame without parents start expanded+      -- too: nothing is stored until there is something to expand.+      when (isJust storedExp || not (IS.null keyExp)) $+        liftIO (writeSlots ctx (slotWrite fieldIntSet groupKey keyExp))+      mapM_ (liftIO . writeIORef (ctxFocusId ctx)) mFocus+      -- An index the items do not reach yet stays the caller's until the+      -- user picks a row, even the one it shows.+      pure $+        if not picked && s == clamped+          then (resp, index)+          else (setChanged (s /= index) resp, s)
− lib/NanoUI/Layout/Arena.hs
@@ -1,1289 +0,0 @@-{-# LANGUAGE RecordWildCards #-}---- | The node arena: one frame's layout nodes stored column-wise in primitive--- arrays (geometry, style, tags and tree links), with accessors, traversals--- and the layout cache.-module NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , NodeArenaArrays (..)-  , isWidgetNode-  , hasCenteredLabel-  , isContainerNode-  , isScrollNode-  , isFloatingNode-  , SizingTag (..)-  , DirTag (..)-  , NodeArena (..)-  , FlexScratch (..)-  , newNodeArena-  , resetNodeArena-  , arenaCount-  , topModalNode-  , floatingNodeCount-  , arenaArrays-  , withArenaArraysSnap-  , geomX-  , geomY-  , geomW-  , geomH-  , styleWVal-  , styleHVal-  , styleMinW-  , styleMinH-  , styleMaxW-  , styleMaxH-  , stylePadL-  , stylePadR-  , stylePadT-  , stylePadB-  , styleGap-  , styleGridMinColW-  , tagNodeType-  , tagDirection-  , tagWSizing-  , tagHSizing-  , tagScrollBarSlot-  , treeParent-  , treeFirstChild-  , treeNextSibling-  , treeStyleIdx-  , treeGridCols-  , readGeom-  , writeGeom-  , readStyle-  , readTagEnum-  , writeTagEnum-  , readTree-  , writeTree-  , addNode-  , addNodeFromLayout-  , rootAttachParent-  , setNodeText-  , getParent-  , getFirstChild-  , getNextSibling-  , getChildCount-  , getNodeType-  , getDirection-  , getGridCols-  , getGridMinColW-  , getScrollContentW-  , setScrollContentW-  , getWidthSizing-  , getHeightSizing-  , getPadding-  , getGap-  , getMinMax-  , parentIsRow-  , getAlignX-  , getAlignY-  , getRect-  , setRect-  , getLayoutRect-  , getClipRect-  , setClipRect-  , snapshotLayoutRects-  , getText-  , getOptions-  , setOptions-  , getWidgetId-  , setWidgetId-  , lookupNodeByWidgetId-  , lookupNodeByKey-  , getStyleIdx-  , setStyleIdx-  , getNodeValue-  , setNodeValue-  , getNodeFontSize-  , getNodeFontColor-  , getNodeScope-  , getArenaScope-  , setArenaScope-  , getScopeSignature-  , ensureScratchCapacity-  , AxisSnapshot (..)-  , ensureAxisSnapshot-  , memoizeWidth-  , forNodes_-  , forChildNodes_-  , foldFlowChildrenM-  , findNodeRevM-  , foldNodeRevM-  , findNodeM-  , foldNodesM-  , findChildM-  , LayoutCache (..)-  , newLayoutCache-  , captureLayoutCache-  , layoutCacheEligible-  , layoutInputsMatch-  , restoreLayoutCache-  ) where--import Control.Exception (bracket_)-import Control.Monad (forM_, when)-import Data.Bits (shiftL, shiftR, xor, (.&.), (.|.))-import Data.HashTable.IO (BasicHashTable)-import qualified Data.HashTable.IO as HT-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Primitive.Array (MutableArray, copyMutableArray, newArray, readArray, sizeofMutableArray, writeArray)-import Data.Primitive.PrimArray-  ( MutablePrimArray-  , copyMutablePrimArray-  , newPrimArray-  , readPrimArray-  , setPrimArray-  , writePrimArray-  , resizeMutablePrimArray-  )-import Data.Primitive.Types (Prim)-import GHC.Exts (RealWorld)-import Data.Text (Text)-import Data.Word (Word8, Word32, Word64)-import qualified Data.Text as T-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Style (AlignX, AlignY, Direction (..), Layout (..), Padding (..), Sizing (..))-import NanoUI.Types (Color (..), Rect (..))--type NodeIdx = Int--data NodeType-  = NodeContainer-  | NodeText-  | NodeSpacer-  | NodeSeparator-  | NodeWidget-  | NodeButton-  | NodeCheckbox-  | NodeSlider-  | NodeTextInput-  | NodeTextArea-  | NodeScrollContainer-  | NodeSelect-  | NodeModal-  | NodeImage-  | NodePanel-  | NodeWindow-  -- Appended last: stored as Word8 in the arena. Update every exhaustive-  -- NodeType case when adding variants.-  | NodeBox-  | NodeRadio-  | NodeColorPicker-  | NodeTree-  | NodePopup-  | NodeDrawing-  deriving (Eq, Show, Enum, Bounded)--isWidgetNode :: NodeType -> Bool-isWidgetNode nt =-  case nt of-    NodeWidget -> True-    NodeButton -> True-    NodeCheckbox -> True-    NodeRadio -> True-    NodeSlider -> True-    NodeTextInput -> True-    NodeTextArea -> True-    NodeSelect -> True-    NodeColorPicker -> True-    NodeTree -> True-    NodeDrawing -> True-    _ -> False---- | Widgets that paint one line of label text vertically centered in their box--- ('computeWidgetLabel'), which is also their baseline.-hasCenteredLabel :: NodeType -> Bool-hasCenteredLabel nt =-  case nt of-    NodeButton -> True-    NodeSelect -> True-    NodeTree -> True-    NodeCheckbox -> True-    NodeRadio -> True-    _ -> False--isContainerNode :: NodeType -> Bool-isContainerNode nt =-  case nt of-    NodeContainer -> True-    NodeScrollContainer -> True-    NodeModal -> True-    NodePanel -> True-    NodeWindow -> True-    NodePopup -> True-    _ -> False--isScrollNode :: NodeType -> Bool-isScrollNode nt = nt == NodeScrollContainer--isFloatingNode :: NodeType -> Bool-isFloatingNode nt = nt == NodeModal || nt == NodeWindow || nt == NodePopup--data SizingTag-  = SizingFixed-  | SizingFit-  | SizingGrow-  | SizingShrink-  | SizingPercent-  deriving (Eq, Show, Enum, Bounded)--data DirTag = DirRow | DirColumn-  deriving (Eq, Show, Enum, Bounded)---- | Node columns. Each array holds one row of @*Stride@ slots per node; the--- column constants below name the slots.-data NodeArenaArrays = NodeArenaArrays-  { naArrGeom :: !(MutablePrimArray RealWorld Float)-  , naArrStyle :: !(MutablePrimArray RealWorld Float)-  , naArrTags :: !(MutablePrimArray RealWorld Word8)-  , naArrTree :: !(MutablePrimArray RealWorld Int)-  , naArrTextStore :: !(MutableArray RealWorld Text)-  , naArrOptionsStore :: !(MutableArray RealWorld [Text])-  , naArrFontColor :: !(MutablePrimArray RealWorld Int)-  , naArrScope :: !(MutablePrimArray RealWorld Int)-  -- ^ The paint scope each node was added under: a theme index shifted left-  -- one bit, and the disabled flag in bit 0. See-  -- 'NanoUI.Context.Types.ThemeScopes'.-  }--data NodeArena = NodeArena-  { naCount :: IORef Int-  , naCapacity :: IORef Int-  , naArrays :: IORef NodeArenaArrays-  , naArraysSnap :: IORef (Maybe NodeArenaArrays)-  , naScratch :: IORef FlexScratch-  -- Per-depth copies of the axis scratch while the position pass recurses.-  -- Children reuse the working scratch, so a container's child list must be-  -- snapshotted at its own depth to survive recursive positioning.-  , naSnapCap :: IORef Int-  , naSnapLevels :: IORef (MutableArray RealWorld (Maybe AxisSnapshot))-  -- Per-frame memos keyed by (node, quantized width): wrapped text sizes and-  -- fit heights. Text and style are fixed per node within a frame, so the-  -- frame tag is all that is needed to invalidate across frames.-  , naFrameTag :: IORef Word32-  , naWrapMemo :: IORef WidthMemo-  , naFitMemo :: IORef WidthMemo-  , naEpoch :: IORef Word32-  , naIndex :: IORef (BasicHashTable WidgetId Word64)-  -- The scope new nodes are stamped with, and a signature of the scoped-  -- nodes added this frame, so a frame that only changes scopes can tell.-  , naScope :: IORef Int-  , naScopeSig :: IORef Word64-  , naTopModal :: IORef Int-  -- ^ Index of the last modal node added this frame, or -1. Node types are-  -- fixed when a node is added and indices only grow until a reset, so this-  -- is the topmost modal without a scan.-  , naFloatingCount :: IORef Int-  -- ^ Floating nodes (windows, modals, popups) added this frame.-  }---- | Flex solver scratch: child node indices, their measured widths and--- heights, and the distributed output sizes.-data FlexScratch = FlexScratch-  { fsCap :: !Int-  , fsIdx :: !(MutablePrimArray RealWorld Int)-  , fsW :: !(MutablePrimArray RealWorld Float)-  , fsH :: !(MutablePrimArray RealWorld Float)-  , fsOutW :: !(MutablePrimArray RealWorld Float)-  , fsOutH :: !(MutablePrimArray RealWorld Float)-  }---- | A per-frame memo of two floats per node keyed by a width. Slots hold--- @(key, a, b)@ per node; an entry is live only while its tag equals the--- arena's frame tag.-data WidthMemo = WidthMemo-  { wmTags :: !(MutablePrimArray RealWorld Word32)-  , wmSlots :: !(MutablePrimArray RealWorld Float)-  }---- | Initial number of per-depth layout snapshot levels. The level array grows--- on demand (see 'ensureSnapLevelsArr'), so this is not a depth limit.-maxSnapDepth :: Int-maxSnapDepth = 256---- | One depth level's frozen child indices and distributed main-axis sizes.-data AxisSnapshot = AxisSnapshot-  { asIdx :: !(MutablePrimArray RealWorld Int)-  , asOut :: !(MutablePrimArray RealWorld Float)-  }--initialCapacity :: Int-initialCapacity = 256---- | Geometry columns: solved rect, the position snapshot taken by--- 'snapshotLayoutRects', and the clip rect.-geomStride, geomX, geomY, geomW, geomH, geomLayoutX, geomLayoutY :: Int-geomStride = 10-geomX = 0-geomY = 1-geomW = 2-geomH = 3-geomLayoutX = 4-geomLayoutY = 5--geomClipX, geomClipY, geomClipW, geomClipH :: Int-geomClipX = 6-geomClipY = 7-geomClipW = 8-geomClipH = 9---- | Style columns: sizing values, padding, gap, min/max, grow, and per-node--- values that are not layout inputs (scroll extent, node value, font size).-styleStride, styleWVal, styleHVal, stylePadL, stylePadR, stylePadT, stylePadB :: Int-styleStride = 16-styleWVal = 0-styleHVal = 1-stylePadL = 2-stylePadR = 3-stylePadT = 4-stylePadB = 5--styleGap, styleMinW, styleMinH, styleMaxW, styleMaxH, styleGrow :: Int-styleGap = 6-styleMinW = 7-styleMinH = 8-styleMaxW = 9-styleMaxH = 10-styleGrow = 11--styleScrollContentW, styleNodeValue, styleGridMinColW, styleFontSize :: Int-styleScrollContentW = 12-styleNodeValue = 13-styleGridMinColW = 14-styleFontSize = 15---- | Tag columns (enum values as 'Word8'). Column 7 is unused. The scrollbar--- slot is a solver output: measurement writes it for scroll containers, so--- the layout cache skips it when comparing inputs and restores it on a hit.-tagStride, tagNodeType, tagDirection, tagWSizing, tagHSizing, tagScrollBarSlot, tagAlignX, tagAlignY :: Int-tagStride = 8 -- a power of two: layoutInputsMatch masks by it-tagNodeType = 0-tagDirection = 1-tagWSizing = 2-tagHSizing = 3-tagScrollBarSlot = 4-tagAlignX = 5-tagAlignY = 6---- | Tree columns: links, widget id, style index, text index (-1 for no text),--- and the grid column count (containers only).-treeStride, treeParent, treeFirstChild, treeNextSibling, treeChildCount :: Int-treeStride = 8-treeParent = 0-treeFirstChild = 1-treeNextSibling = 2-treeChildCount = 3--treeWidgetId, treeStyleIdx, treeTextIdx, treeGridCols :: Int-treeWidgetId = 4-treeStyleIdx = 5-treeTextIdx = 6-treeGridCols = 7--{-# INLINE readGeom #-}-readGeom :: NodeArenaArrays -> NodeIdx -> Int -> IO Float-readGeom a idx col = readPrimArray (naArrGeom a) (idx * geomStride + col)--{-# INLINE writeGeom #-}-writeGeom :: NodeArenaArrays -> NodeIdx -> Int -> Float -> IO ()-writeGeom a idx col = writePrimArray (naArrGeom a) (idx * geomStride + col)--{-# INLINE readStyle #-}-readStyle :: NodeArenaArrays -> NodeIdx -> Int -> IO Float-readStyle a idx col = readPrimArray (naArrStyle a) (idx * styleStride + col)--{-# INLINE writeStyle #-}-writeStyle :: NodeArenaArrays -> NodeIdx -> Int -> Float -> IO ()-writeStyle a idx col = writePrimArray (naArrStyle a) (idx * styleStride + col)--{-# INLINE readTagEnum #-}-readTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> Int -> IO e-readTagEnum a idx col = do-  t <- readPrimArray (naArrTags a) (idx * tagStride + col)-  pure $! toEnum (fromIntegral t)--{-# INLINE writeTagEnum #-}-writeTagEnum :: Enum e => NodeArenaArrays -> NodeIdx -> Int -> e -> IO ()-writeTagEnum a idx col v = writePrimArray (naArrTags a) (idx * tagStride + col) (fromIntegral (fromEnum v))--{-# INLINE readTree #-}-readTree :: NodeArenaArrays -> NodeIdx -> Int -> IO Int-readTree a idx col = readPrimArray (naArrTree a) (idx * treeStride + col)--{-# INLINE writeTree #-}-writeTree :: NodeArenaArrays -> NodeIdx -> Int -> Int -> IO ()-writeTree a idx col = writePrimArray (naArrTree a) (idx * treeStride + col)--newNodeArenaArrays :: Int -> IO NodeArenaArrays-newNodeArenaArrays cap = do-  naArrGeom <- newPrimArray (cap * geomStride)-  naArrStyle <- newPrimArray (cap * styleStride)-  naArrTags <- newPrimArray (cap * tagStride)-  naArrTree <- newPrimArray (cap * treeStride)-  naArrTextStore <- newArray cap T.empty-  naArrOptionsStore <- newArray cap []-  naArrFontColor <- newPrimArray cap-  naArrScope <- newPrimArray cap-  pure NodeArenaArrays {..}--newFlexScratch :: Int -> IO FlexScratch-newFlexScratch fsCap = do-  fsIdx <- newPrimArray fsCap-  fsW <- newPrimArray fsCap-  fsH <- newPrimArray fsCap-  fsOutW <- newPrimArray fsCap-  fsOutH <- newPrimArray fsCap-  pure FlexScratch {..}---- | Memo slots per node: key and two values.-memoStride :: Int-memoStride = 3---- Tags start zeroed: frame tags are never 0, so fresh entries always miss.-newWidthMemo :: Int -> IO WidthMemo-newWidthMemo cap = do-  wmTags <- newPrimArray cap-  setPrimArray wmTags 0 cap 0-  wmSlots <- newPrimArray (cap * memoStride)-  pure WidthMemo {..}--newNodeArena :: IO NodeArena-newNodeArena = do-  let cap = initialCapacity-      scratchCap = 64-  naCount <- newIORef 0-  naCapacity <- newIORef cap-  naArrays <- newIORef =<< newNodeArenaArrays cap-  naArraysSnap <- newIORef Nothing-  naScratch <- newIORef =<< newFlexScratch scratchCap-  naSnapCap <- newIORef scratchCap-  naSnapLevels <- newIORef =<< newArray maxSnapDepth Nothing-  naFrameTag <- newIORef 1-  naWrapMemo <- newIORef =<< newWidthMemo cap-  naFitMemo <- newIORef =<< newWidthMemo cap-  naEpoch <- newIORef 1-  naIndex <- newIORef =<< HT.new-  naScope <- newIORef 0-  naScopeSig <- newIORef 0-  naTopModal <- newIORef (-1)-  naFloatingCount <- newIORef 0-  pure NodeArena {..}--resetNodeArena :: NodeArena -> IO ()-resetNodeArena na = do-  writeIORef (naCount na) 0-  writeIORef (naScope na) 0-  writeIORef (naScopeSig na) 0-  writeIORef (naTopModal na) (-1)-  writeIORef (naFloatingCount na) 0-  !ft <- readIORef (naFrameTag na)-  writeIORef (naFrameTag na) (if ft == maxBound then 1 else ft + 1)-  !ep <- readIORef (naEpoch na)-  let !ep' = ep + 1-  if ep' == 0 || (ep' .&. 0x7F == 0)-    then do-      let !nextEp = if ep' == 0 then 1 else ep'-      writeIORef (naEpoch na) nextEp-      writeIORef (naIndex na) =<< HT.new-    else writeIORef (naEpoch na) ep'---- | The topmost (last added) modal node, if any.-{-# INLINE topModalNode #-}-topModalNode :: NodeArena -> IO (Maybe NodeIdx)-topModalNode na = do-  i <- readIORef (naTopModal na)-  pure (if i >= 0 then Just i else Nothing)--{-# INLINE floatingNodeCount #-}-floatingNodeCount :: NodeArena -> IO Int-floatingNodeCount na = readIORef (naFloatingCount na)--{-# INLINE arenaCount #-}-arenaCount :: NodeArena -> IO Int-arenaCount na = readIORef (naCount na)--{-# INLINE arenaArrays #-}-arenaArrays :: NodeArena -> IO NodeArenaArrays-arenaArrays na = do-  m <- readIORef (naArraysSnap na)-  case m of-    Just a -> pure a-    Nothing -> readIORef (naArrays na)---- | Pin arena column arrays for a layout pass so field reads skip naArrays IORef.-withArenaArraysSnap :: NodeArena -> IO a -> IO a-withArenaArraysSnap na act =-  bracket_-    (readIORef (naArrays na) >>= writeIORef (naArraysSnap na) . Just)-    (writeIORef (naArraysSnap na) Nothing)-    act--{-# NOINLINE ensureCapacity #-}-ensureCapacity :: NodeArena -> Int -> IO ()-ensureCapacity na needed = do-  cap <- readIORef (naCapacity na)-  if needed < cap-    then pure ()-    else do-      let newCap = cap * 2-      newA <- readIORef (naArrays na) >>= growNodeArenaArrays cap newCap-      growWidthMemo (naWrapMemo na) cap newCap-      growWidthMemo (naFitMemo na) cap newCap-      writeIORef (naArrays na) newA-      m <- readIORef (naArraysSnap na)-      case m of-        Just{} -> writeIORef (naArraysSnap na) (Just newA)-        Nothing -> pure ()-      writeIORef (naCapacity na) newCap---- | Copy of @a@ with room for @newCap@ nodes; new slots are zero or empty.-growNodeArenaArrays :: Int -> Int -> NodeArenaArrays -> IO NodeArenaArrays-growNodeArenaArrays cap newCap a = do-  naArrGeom <- growPrimArrayCopy (naArrGeom a) (cap * geomStride) (newCap * geomStride) 0-  naArrStyle <- growPrimArrayCopy (naArrStyle a) (cap * styleStride) (newCap * styleStride) 0-  naArrTags <- growPrimArrayCopy (naArrTags a) (cap * tagStride) (newCap * tagStride) 0-  naArrTree <- growPrimArrayCopy (naArrTree a) (cap * treeStride) (newCap * treeStride) 0-  naArrTextStore <- growBoxedStoreCopy T.empty (naArrTextStore a) cap newCap-  naArrOptionsStore <- growBoxedStoreCopy [] (naArrOptionsStore a) cap newCap-  naArrFontColor <- growPrimArrayCopy (naArrFontColor a) cap newCap 0-  naArrScope <- growPrimArrayCopy (naArrScope a) cap newCap 0-  pure NodeArenaArrays {..}--{-# NOINLINE growPrimArrayCopy #-}-growPrimArrayCopy :: Prim a => MutablePrimArray RealWorld a -> Int -> Int -> a -> IO (MutablePrimArray RealWorld a)-growPrimArrayCopy oldArr cap newCap defVal = do-  newArr <- resizeMutablePrimArray oldArr newCap-  setPrimArray newArr cap (newCap - cap) defVal-  pure newArr--growWidthMemo :: IORef WidthMemo -> Int -> Int -> IO ()-growWidthMemo ref cap newCap = do-  WidthMemo tags slots <- readIORef ref-  wmTags <- growPrimArrayCopy tags cap newCap 0-  wmSlots <- growPrimArrayCopy slots (cap * memoStride) (newCap * memoStride) 0-  writeIORef ref WidthMemo {..}--{-# NOINLINE growBoxedStoreCopy #-}-growBoxedStoreCopy :: a -> MutableArray RealWorld a -> Int -> Int -> IO (MutableArray RealWorld a)-growBoxedStoreCopy emptyVal arr oldCap newCap = do-  newArr <- newArray newCap emptyVal-  copyMutableArray newArr 0 arr 0 oldCap-  pure newArr--{-# INLINE sizingTag #-}-sizingTag :: Sizing -> (SizingTag, Float)-sizingTag (Fixed v) = (SizingFixed, v)-sizingTag Fit = (SizingFit, 0)-sizingTag (Grow g) = (SizingGrow, g)-sizingTag (Shrink s) = (SizingShrink, s)-sizingTag (Percent p) = (SizingPercent, p)---- Empty stack attaches to node 0 so walks from the page root still reach--- windows/modals/popups built as UI siblings.-rootAttachParent :: NodeArena -> Int -> IO Int-rootAttachParent na parent-  | parent >= 0 = pure parent-  | otherwise = do-      n <- arenaCount na-      pure (if n > 0 then 0 else -1)--{-# INLINE addNode #-}-addNode ::-  NodeArena ->-  NodeType ->-  Int ->-  Direction ->-  Sizing ->-  Sizing ->-  Padding ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  AlignX ->-  AlignY ->-  IO NodeIdx-addNode na nt parent dir wSiz hSiz pad gap minW minH maxW maxH grow ax ay = do-  idx <- readIORef (naCount na)-  ensureCapacity na (idx + 1)-  let (wTag, wVal) = sizingTag wSiz-      (hTag, hVal) = sizingTag hSiz-  a <- arenaArrays na--  setPrimArray (naArrGeom a) (idx * geomStride) geomStride 0--  writeStyle a idx styleWVal wVal-  writeStyle a idx styleHVal hVal-  writeStyle a idx stylePadL (padL pad)-  writeStyle a idx stylePadR (padR pad)-  writeStyle a idx stylePadT (padT pad)-  writeStyle a idx stylePadB (padB pad)-  writeStyle a idx styleGap gap-  writeStyle a idx styleMinW minW-  writeStyle a idx styleMinH minH-  writeStyle a idx styleMaxW maxW-  writeStyle a idx styleMaxH maxH-  writeStyle a idx styleGrow grow-  setPrimArray (naArrStyle a) (idx * styleStride + styleScrollContentW) (styleStride - styleScrollContentW) 0--  setPrimArray (naArrTags a) (idx * tagStride) tagStride 0-  writeTagEnum a idx tagNodeType nt-  writeTagEnum a idx tagDirection $ case dir of-    Row -> DirRow-    Column -> DirColumn-  writeTagEnum a idx tagWSizing wTag-  writeTagEnum a idx tagHSizing hTag-  writeTagEnum a idx tagAlignX ax-  writeTagEnum a idx tagAlignY ay--  setPrimArray (naArrTree a) (idx * treeStride) treeStride 0-  writeTree a idx treeParent parent-  writeTree a idx treeFirstChild (-1)-  writeTree a idx treeNextSibling (-1)-  writeTree a idx treeTextIdx (-1)-  writePrimArray (naArrFontColor a) idx 0-  scope <- readIORef (naScope na)-  writePrimArray (naArrScope a) idx scope-  when (scope /= 0) $ do-    sig <- readIORef (naScopeSig na)-    writeIORef (naScopeSig na) $! (sig * 0x100000001b3) `xor` (fromIntegral idx `shiftL` 32 .|. fromIntegral scope)-  writeArray (naArrOptionsStore a) idx []--  when (parent >= 0) $ do-    fc <- readTree a parent treeFirstChild-    writeTree a idx treeNextSibling fc-    writeTree a parent treeFirstChild idx-    cc <- readTree a parent treeChildCount-    writeTree a parent treeChildCount (cc + 1)-  when (isFloatingNode nt) $ do-    when (nt == NodeModal) $ writeIORef (naTopModal na) idx-    fc <- readIORef (naFloatingCount na)-    writeIORef (naFloatingCount na) (fc + 1)-  writeIORef (naCount na) (idx + 1)-  pure idx--addNodeFromLayout :: NodeArena -> NodeType -> Int -> Layout -> IO NodeIdx-addNodeFromLayout na nt parent l = do-  idx <--    addNode-      na-      nt-      parent-      (layoutDirection l)-      (layoutWidth l)-      (layoutHeight l)-      (layoutPadding l)-      (layoutGap l)-      (layoutMinW l)-      (layoutMinH l)-      (layoutMaxW l)-      (layoutMaxH l)-      0-      (layoutAlignX l)-      (layoutAlignY l)-  setGridCols na idx (layoutGridCols l)-  setGridMinColW na idx (layoutGridMinColW l)-  setNodeFontSize na idx (layoutFontSize l)-  setNodeFontColor na idx (layoutFontColor l)-  pure idx--{-# INLINE setNodeText #-}-setNodeText :: NodeArena -> NodeIdx -> Text -> IO ()-setNodeText na idx txt = do-  a <- arenaArrays na-  writeArray (naArrTextStore a) idx txt-  writeTree a idx treeTextIdx idx--{-# INLINE getParent #-}-getParent :: NodeArena -> NodeIdx -> IO NodeIdx-getParent na idx = arenaArrays na >>= \a -> readTree a idx treeParent--{-# INLINE getFirstChild #-}-getFirstChild :: NodeArena -> NodeIdx -> IO NodeIdx-getFirstChild na idx = arenaArrays na >>= \a -> readTree a idx treeFirstChild--{-# INLINE getNextSibling #-}-getNextSibling :: NodeArena -> NodeIdx -> IO NodeIdx-getNextSibling na idx = arenaArrays na >>= \a -> readTree a idx treeNextSibling--{-# INLINE getChildCount #-}-getChildCount :: NodeArena -> NodeIdx -> IO Int-getChildCount na idx = arenaArrays na >>= \a -> readTree a idx treeChildCount--{-# INLINE getNodeType #-}-getNodeType :: NodeArena -> NodeIdx -> IO NodeType-getNodeType na idx = arenaArrays na >>= \a -> readTagEnum a idx tagNodeType--{-# INLINE getDirection #-}-getDirection :: NodeArena -> NodeIdx -> IO DirTag-getDirection na idx = arenaArrays na >>= \a -> readTagEnum a idx tagDirection--{-# INLINE getGridCols #-}-getGridCols :: NodeArena -> NodeIdx -> IO Int-getGridCols na idx = arenaArrays na >>= \a -> readTree a idx treeGridCols--{-# INLINE setGridCols #-}-setGridCols :: NodeArena -> NodeIdx -> Int -> IO ()-setGridCols na idx c = arenaArrays na >>= \a -> writeTree a idx treeGridCols c--{-# INLINE getWidthSizing #-}-getWidthSizing :: NodeArena -> NodeIdx -> IO (SizingTag, Float)-getWidthSizing na idx = arenaArrays na >>= \a -> (,) <$> readTagEnum a idx tagWSizing <*> readStyle a idx styleWVal--{-# INLINE getHeightSizing #-}-getHeightSizing :: NodeArena -> NodeIdx -> IO (SizingTag, Float)-getHeightSizing na idx = arenaArrays na >>= \a -> (,) <$> readTagEnum a idx tagHSizing <*> readStyle a idx styleHVal--{-# INLINE getPadding #-}-getPadding :: NodeArena -> NodeIdx -> IO Padding-getPadding na idx = do-  a <- arenaArrays na-  Padding <$> readStyle a idx stylePadL <*> readStyle a idx stylePadR <*> readStyle a idx stylePadT <*> readStyle a idx stylePadB--{-# INLINE getGap #-}-getGap :: NodeArena -> NodeIdx -> IO Float-getGap na idx = arenaArrays na >>= \a -> readStyle a idx styleGap--{-# INLINE getMinMax #-}-getMinMax :: NodeArena -> NodeIdx -> IO (Float, Float, Float, Float)-getMinMax na idx = do-  a <- arenaArrays na-  (,,,) <$> readStyle a idx styleMinW <*> readStyle a idx styleMinH <*> readStyle a idx styleMaxW <*> readStyle a idx styleMaxH--{-# INLINE getScrollContentW #-}-getScrollContentW :: NodeArena -> NodeIdx -> IO Float-getScrollContentW na idx = arenaArrays na >>= \a -> readStyle a idx styleScrollContentW--{-# INLINE setScrollContentW #-}-setScrollContentW :: NodeArena -> NodeIdx -> Float -> IO ()-setScrollContentW na idx v = arenaArrays na >>= \a -> writeStyle a idx styleScrollContentW v--{-# INLINE getGridMinColW #-}-getGridMinColW :: NodeArena -> NodeIdx -> IO Float-getGridMinColW na idx = arenaArrays na >>= \a -> readStyle a idx styleGridMinColW--{-# INLINE setGridMinColW #-}-setGridMinColW :: NodeArena -> NodeIdx -> Float -> IO ()-setGridMinColW na idx v = arenaArrays na >>= \a -> writeStyle a idx styleGridMinColW v--{-# INLINE parentIsRow #-}-parentIsRow :: NodeArena -> NodeIdx -> IO Bool-parentIsRow na idx = do-  p <- getParent na idx-  if p < 0-    then pure False-    else do-      dir <- getDirection na p-      pure (dir == DirRow)--{-# INLINE getAlignX #-}-getAlignX :: NodeArena -> NodeIdx -> IO AlignX-getAlignX na idx = arenaArrays na >>= \a -> readTagEnum a idx tagAlignX--{-# INLINE getAlignY #-}-getAlignY :: NodeArena -> NodeIdx -> IO AlignY-getAlignY na idx = arenaArrays na >>= \a -> readTagEnum a idx tagAlignY--{-# INLINE getRect #-}-getRect :: NodeArena -> NodeIdx -> IO (Float, Float, Float, Float)-getRect na idx = do-  a <- arenaArrays na-  (,,,) <$> readGeom a idx geomX <*> readGeom a idx geomY <*> readGeom a idx geomW <*> readGeom a idx geomH--{-# INLINE setRect #-}-setRect :: NodeArena -> NodeIdx -> Float -> Float -> Float -> Float -> IO ()-setRect na idx x y w h = do-  a <- arenaArrays na-  writeGeom a idx geomX x-  writeGeom a idx geomY y-  writeGeom a idx geomW w-  writeGeom a idx geomH h--{-# INLINE getLayoutRect #-}-getLayoutRect :: NodeArena -> NodeIdx -> IO (Float, Float, Float, Float)-getLayoutRect na idx = do-  a <- arenaArrays na-  (,,,) <$> readGeom a idx geomLayoutX <*> readGeom a idx geomLayoutY <*> readGeom a idx geomW <*> readGeom a idx geomH--{-# INLINE getClipRect #-}-getClipRect :: NodeArena -> NodeIdx -> IO (Maybe Rect)-getClipRect na idx = do-  a <- arenaArrays na-  x <- readGeom a idx geomClipX-  y <- readGeom a idx geomClipY-  w <- readGeom a idx geomClipW-  h <- readGeom a idx geomClipH-  let r = Rect x y w h-  pure (if w > 0 && h > 0 then Just r else Nothing)--{-# INLINE setClipRect #-}-setClipRect :: NodeArena -> NodeIdx -> Rect -> IO ()-setClipRect na idx (Rect x y w h) = do-  a <- arenaArrays na-  writeGeom a idx geomClipX x-  writeGeom a idx geomClipY y-  writeGeom a idx geomClipW w-  writeGeom a idx geomClipH h--{-# INLINE snapshotLayoutRects #-}-snapshotLayoutRects :: NodeArena -> IO ()-snapshotLayoutRects na = do-  a <- arenaArrays na-  forNodes_ na $ \i -> do-    readGeom a i geomX >>= writeGeom a i geomLayoutX-    readGeom a i geomY >>= writeGeom a i geomLayoutY---- | Cached layout signature and solved geometry for whole-layout reuse. The--- backing arrays are reused; only cache misses capture a new solved frame.--- The font colour and scope columns are paint state and stay unused.-data LayoutCache = LayoutCache-  { lcCap :: !Int-  , lcCount :: !Int-  , lcArrays :: !NodeArenaArrays-  }--newLayoutCache :: Int -> IO LayoutCache-newLayoutCache cap0 = do-  let !cap = max 16 cap0-  LayoutCache cap 0 <$> newNodeArenaArrays cap---- | Snapshot the current (post-solve) arena form, constraints and rects.-captureLayoutCache :: NodeArena -> LayoutCache -> IO LayoutCache-captureLayoutCache na lc0 = do-  n <- arenaCount na-  let !oldCap = lcCap lc0-      !newCap = max n (oldCap * 2)-  lc <--    if n <= oldCap-      then pure lc0-      else LayoutCache newCap (lcCount lc0) <$> growNodeArenaArrays oldCap newCap (lcArrays lc0)-  a <- arenaArrays na-  let c = lcArrays lc-  copyMutablePrimArray (naArrGeom c) 0 (naArrGeom a) 0 (n * geomStride)-  copyMutablePrimArray (naArrStyle c) 0 (naArrStyle a) 0 (n * styleStride)-  copyMutablePrimArray (naArrTags c) 0 (naArrTags a) 0 (n * tagStride)-  copyMutablePrimArray (naArrTree c) 0 (naArrTree a) 0 (n * treeStride)-  copyMutableArray (naArrTextStore c) 0 (naArrTextStore a) 0 n-  copyMutableArray (naArrOptionsStore c) 0 (naArrOptionsStore a) 0 n-  pure lc {lcCount = n}---- | Floating placement depends on state outside the arena descriptor. Custom--- measurement is checked separately by Frame, which owns its registration.-layoutCacheEligible :: NodeArena -> IO Bool-layoutCacheEligible na = do-  n <- arenaCount na-  a <- arenaArrays na-  if n <= 0-    then pure False-    else allRangeM 0 n $ \i -> not . isFloatingNode <$> readTagEnum a i tagNodeType---- | Compare layout inputs, stopping at the first mismatch. Node values are--- paint state except on scroll containers, where they are solver outputs.--- Neither belongs in the layout-input signature.-layoutInputsMatch :: NodeArena -> LayoutCache -> IO Bool-layoutInputsMatch na lc = do-  n <- arenaCount na-  if n <= 0 || n /= lcCount lc-    then pure False-    else do-      -- The cache only holds eligible layouts, and matching node types-      -- keep the current one eligible too.-      a <- arenaArrays na-      let c = lcArrays lc-      andThen (styleMatch (naArrStyle a) (naArrStyle c) n) $-        andThen (allRangeM 0 (n * tagStride) (\k -> if k .&. (tagStride - 1) == tagScrollBarSlot then pure True else primEqAt (naArrTags a) (naArrTags c) k)) $-          andThen (treeMatch a (naArrTree c) n) $-            andThen (allRangeM 0 n (boxedEqAt (naArrTextStore a) (naArrTextStore c))) $-              allRangeM 0 n (boxedEqAt (naArrOptionsStore a) (naArrOptionsStore c))--{-# INLINE andThen #-}-andThen :: IO Bool -> IO Bool -> IO Bool-andThen check next = do-  ok <- check-  if ok then next else pure False---- | Whether @p@ holds at every index in @[lo, hi)@, stopping at the first miss.-{-# INLINE allRangeM #-}-allRangeM :: Int -> Int -> (Int -> IO Bool) -> IO Bool-allRangeM lo hi p = go lo-  where-    go !i-      | i >= hi = pure True-      | otherwise = do-          ok <- p i-          if ok then go (i + 1) else pure False--{-# INLINE primEqAt #-}-primEqAt :: (Prim a, Eq a) => MutablePrimArray RealWorld a -> MutablePrimArray RealWorld a -> Int -> IO Bool-primEqAt x y i = (==) <$> readPrimArray x i <*> readPrimArray y i--{-# INLINE boxedEqAt #-}-boxedEqAt :: Eq a => MutableArray RealWorld a -> MutableArray RealWorld a -> Int -> IO Bool-boxedEqAt x y i = (==) <$> readArray x i <*> readArray y i---- The scroll-extent and node-value columns hold solver outputs or paint-only--- values, so they are skipped.-styleMatch :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Int -> IO Bool-styleMatch x y n =-  allRangeM 0 n $ \i ->-    let !base = i * styleStride-     in andThen (allRangeM base (base + styleScrollContentW) (primEqAt x y)) $-          allRangeM (base + styleGridMinColW) (base + styleStride) (primEqAt x y)---- Box/image/drawing style IDs are paint data; their intrinsic dimensions come--- from sizing constraints. The grid column count only matters to containers.-treeMatch :: NodeArenaArrays -> MutablePrimArray RealWorld Int -> Int -> IO Bool-treeMatch a cached n =-  allRangeM 0 n $ \i -> do-    nt <- readTagEnum a i tagNodeType-    let paintStyle = nt == NodeBox || nt == NodeImage || nt == NodeDrawing-        !base = i * treeStride-    allRangeM 0 treeStride $ \j ->-      if (j == treeStyleIdx && paintStyle) || (j == treeGridCols && not (isContainerNode nt))-        then pure True-        else (==) <$> readTree a i j <*> readPrimArray cached (base + j)---- | Restore only solver outputs. Rebuilt paint values/colors must survive a--- cache hit; copying the entire cached style array would revert them.-restoreLayoutCache :: NodeArena -> LayoutCache -> IO ()-restoreLayoutCache na lc = do-  a <- arenaArrays na-  let !n = lcCount lc-      c = lcArrays lc-  copyMutablePrimArray (naArrGeom a) 0 (naArrGeom c) 0 (n * geomStride)-  let go !i-        | i >= n = pure ()-        | otherwise = do-            nt <- readTagEnum a i tagNodeType-            -- Scroll content width, node value (the content height) and-            -- scrollbar slot.-            when (isScrollNode nt) $ do-              let !off = i * styleStride + styleScrollContentW-                  !slotOff = i * tagStride + tagScrollBarSlot-              copyMutablePrimArray (naArrStyle a) off (naArrStyle c) off 2-              readPrimArray (naArrTags c) slotOff >>= writePrimArray (naArrTags a) slotOff-            go (i + 1)-  go 0--{-# INLINE getText #-}-getText :: NodeArena -> NodeIdx -> IO Text-getText na idx = do-  a <- arenaArrays na-  ti <- readTree a idx treeTextIdx-  if ti < 0-    then pure T.empty-    else readArray (naArrTextStore a) ti--{-# INLINE getOptions #-}-getOptions :: NodeArena -> NodeIdx -> IO [Text]-getOptions na idx = do-  a <- arenaArrays na-  readArray (naArrOptionsStore a) idx--{-# INLINE setOptions #-}-setOptions :: NodeArena -> NodeIdx -> [Text] -> IO ()-setOptions na idx opts = do-  a <- arenaArrays na-  writeArray (naArrOptionsStore a) idx opts--{-# INLINE getWidgetId #-}-getWidgetId :: NodeArena -> NodeIdx -> IO WidgetId-getWidgetId na idx = arenaArrays na >>= \a -> WidgetId . fromIntegral <$> readTree a idx treeWidgetId--{-# INLINE packEpochNode #-}-packEpochNode :: Word32 -> NodeIdx -> Word64-packEpochNode !epoch !idx = (fromIntegral epoch `shiftL` 32) .|. (fromIntegral idx .&. 0xFFFFFFFF)--{-# INLINE unpackEpochNode #-}-unpackEpochNode :: Word64 -> (Word32, NodeIdx)-unpackEpochNode !w = (fromIntegral (w `shiftR` 32), fromIntegral (w .&. 0xFFFFFFFF))--{-# INLINE setWidgetId #-}-setWidgetId :: NodeArena -> NodeIdx -> WidgetId -> IO ()-setWidgetId na idx wid = do-  a <- arenaArrays na-  let WidgetId w = wid-  writeTree a idx treeWidgetId (fromIntegral w)-  when (hashWidgetId wid /= 0) $ do-    !ep <- readIORef (naEpoch na)-    table <- readIORef (naIndex na)-    HT.insert table wid (packEpochNode ep idx)--{-# INLINE lookupNodeByWidgetId #-}-lookupNodeByWidgetId :: NodeArena -> WidgetId -> IO (Maybe NodeIdx)-lookupNodeByWidgetId na wid-  | hashWidgetId wid == 0 = pure Nothing-  | otherwise = do-      table <- readIORef (naIndex na)-      mVal <- HT.lookup table wid-      case mVal of-        Nothing -> pure Nothing-        Just val -> do-          !ep <- readIORef (naEpoch na)-          let (!entryEp, !idx) = unpackEpochNode val-          pure (if entryEp == ep then Just idx else Nothing)--{-# INLINE lookupNodeByKey #-}-lookupNodeByKey :: NodeArena -> Int -> IO (Maybe NodeIdx)-lookupNodeByKey na key = lookupNodeByWidgetId na (WidgetId (fromIntegral key))--{-# INLINE getNodeValue #-}-getNodeValue :: NodeArena -> NodeIdx -> IO Float-getNodeValue na idx = arenaArrays na >>= \a -> readStyle a idx styleNodeValue--{-# INLINE setNodeValue #-}-setNodeValue :: NodeArena -> NodeIdx -> Float -> IO ()-setNodeValue na idx v = arenaArrays na >>= \a -> writeStyle a idx styleNodeValue v--{-# INLINE getNodeFontSize #-}-getNodeFontSize :: NodeArena -> NodeIdx -> IO Float-getNodeFontSize na idx = arenaArrays na >>= \a -> readStyle a idx styleFontSize--{-# INLINE setNodeFontSize #-}-setNodeFontSize :: NodeArena -> NodeIdx -> Float -> IO ()-setNodeFontSize na idx v = arenaArrays na >>= \a -> writeStyle a idx styleFontSize v---- | Per-node font color (paint-only, kept out of @naArrTree@--- where 'treeGridCols' holds the grid column count for containers).-{-# INLINE getNodeFontColor #-}-getNodeFontColor :: NodeArena -> NodeIdx -> IO (Maybe Color)-getNodeFontColor na idx = do-  a <- arenaArrays na-  val <- readPrimArray (naArrFontColor a) idx-  if (val .&. 0x100000000) /= 0-    then pure (Just (Color (fromIntegral (val .&. 0xFFFFFFFF))))-    else pure Nothing--{-# INLINE setNodeFontColor #-}-setNodeFontColor :: NodeArena -> NodeIdx -> Maybe Color -> IO ()-setNodeFontColor na idx mCol = do-  a <- arenaArrays na-  let val = case mCol of-        Nothing -> 0-        Just (Color w) -> 0x100000000 .|. fromIntegral w-  writePrimArray (naArrFontColor a) idx val--{-# INLINE getNodeScope #-}-getNodeScope :: NodeArena -> NodeIdx -> IO Int-getNodeScope na idx = arenaArrays na >>= \a -> readPrimArray (naArrScope a) idx--{-# INLINE getArenaScope #-}-getArenaScope :: NodeArena -> IO Int-getArenaScope na = readIORef (naScope na)--{-# INLINE setArenaScope #-}-setArenaScope :: NodeArena -> Int -> IO ()-setArenaScope na = writeIORef (naScope na)--{-# INLINE getScopeSignature #-}-getScopeSignature :: NodeArena -> IO Word64-getScopeSignature na = readIORef (naScopeSig na)--{-# INLINE getStyleIdx #-}-getStyleIdx :: NodeArena -> NodeIdx -> IO Int-getStyleIdx na idx = arenaArrays na >>= \a -> readTree a idx treeStyleIdx--{-# INLINE setStyleIdx #-}-setStyleIdx :: NodeArena -> NodeIdx -> Int -> IO ()-setStyleIdx na idx v = arenaArrays na >>= \a -> writeTree a idx treeStyleIdx v---- | Get the snapshot buffers for a recursion depth, grown to hold at least--- @needed@ entries. Buffers are reused across frames; nothing is allocated in--- steady state once capacity is warm.-{-# NOINLINE ensureAxisSnapshot #-}-ensureAxisSnapshot :: NodeArena -> Int -> Int -> IO AxisSnapshot-ensureAxisSnapshot na depth needed = do-  arr0 <- readIORef (naSnapLevels na)-  let !d = max 0 depth-  arr <- ensureSnapLevelsArr na arr0 (d + 1)-  cap <- readIORef (naSnapCap na)-  if needed <= cap-    then getLevel arr d cap-    else do-      let !newCap = max needed (cap * 2)-          !levels = sizeofMutableArray arr-      forM_ [0 .. levels - 1] $ \i -> do-        m <- readArray arr i-        case m of-          Nothing -> pure ()-          Just (AxisSnapshot idx out) -> do-            idx' <- growPrimArrayCopy idx cap newCap 0-            out' <- growPrimArrayCopy out cap newCap 0-            writeArray arr i (Just (AxisSnapshot idx' out'))-      writeIORef (naSnapCap na) newCap-      getLevel arr d newCap-  where-    getLevel arr d currentCap = do-      m <- readArray arr d-      case m of-        Just s -> pure s-        Nothing -> do-          asIdx <- newPrimArray currentCap-          asOut <- newPrimArray currentCap-          let s = AxisSnapshot asIdx asOut-          writeArray arr d (Just s)-          pure s---- | Grow the per-depth snapshot-level array to hold at least @need@ levels,--- so nesting depth has no fixed limit.-ensureSnapLevelsArr :: NodeArena -> MutableArray RealWorld (Maybe AxisSnapshot) -> Int -> IO (MutableArray RealWorld (Maybe AxisSnapshot))-ensureSnapLevelsArr na arr need = do-  let !sz = sizeofMutableArray arr-  if need <= sz-    then pure arr-    else do-      let !newSz = max need (sz * 2)-      arr' <- newArray newSz Nothing-      copyMutableArray arr' 0 arr 0 sz-      writeIORef (naSnapLevels na) arr'-      pure arr'---- | Memoize @compute@ for node @idx@ at width @key@ in one of the arena's--- per-frame memos. Widths within 0.25 px share an entry so near-identical--- reflows still hit.-{-# INLINE memoizeWidth #-}-memoizeWidth :: NodeArena -> IORef WidthMemo -> NodeIdx -> Float -> IO (Float, Float) -> IO (Float, Float)-memoizeWidth na ref idx key compute = do-  ft <- readIORef (naFrameTag na)-  WidthMemo tags slots <- readIORef ref-  tag <- readPrimArray tags idx-  let !base = idx * memoStride-  hit <--    if tag /= ft-      then pure False-      else do-        k <- readPrimArray slots base-        pure (abs (k - key) <= 0.25)-  if hit-    then (,) <$> readPrimArray slots (base + 1) <*> readPrimArray slots (base + 2)-    else do-      r@(x, y) <- compute-      WidthMemo tags' slots' <- readIORef ref-      writePrimArray tags' idx ft-      writePrimArray slots' base key-      writePrimArray slots' (base + 1) x-      writePrimArray slots' (base + 2) y-      pure r---- | The flex scratch, grown to hold at least @needed@ entries.-{-# INLINE ensureScratchCapacity #-}-ensureScratchCapacity :: NodeArena -> Int -> IO FlexScratch-ensureScratchCapacity na needed = do-  s <- readIORef (naScratch na)-  if needed <= fsCap s then pure s else growScratch na s needed--{-# NOINLINE growScratch #-}-growScratch :: NodeArena -> FlexScratch -> Int -> IO FlexScratch-growScratch na s needed = do-  let !cap = fsCap s-      !newCap = max needed (cap * 2)-  fsIdx <- growPrimArrayCopy (fsIdx s) cap newCap (-1)-  fsW <- growPrimArrayCopy (fsW s) cap newCap 0-  fsH <- growPrimArrayCopy (fsH s) cap newCap 0-  fsOutW <- growPrimArrayCopy (fsOutW s) cap newCap 0-  fsOutH <- growPrimArrayCopy (fsOutH s) cap newCap 0-  let s' = FlexScratch {fsCap = newCap, ..}-  writeIORef (naScratch na) s'-  pure s'--{-# INLINE forNodes_ #-}-forNodes_ :: NodeArena -> (NodeIdx -> IO ()) -> IO ()-forNodes_ na f = do-  n <- arenaCount na-  let go !i-        | i >= n = pure ()-        | otherwise = f i >> go (i + 1)-  go 0--{-# INLINE forChildNodes_ #-}-forChildNodes_ :: NodeArena -> NodeIdx -> (NodeIdx -> IO ()) -> IO ()-forChildNodes_ na parentIdx f = do-  fc <- getFirstChild na parentIdx-  let go !ci-        | ci < 0 = pure ()-        | otherwise = do-            f ci-            ns <- getNextSibling na ci-            go ns-  go fc---- | Fold over a node's children in sibling order, skipping floating--- (modal, window, popup) children, which are placed outside the flow.-{-# INLINE foldFlowChildrenM #-}-foldFlowChildrenM :: NodeArena -> NodeIdx -> (acc -> NodeIdx -> IO acc) -> acc -> IO acc-foldFlowChildrenM na parentIdx f z = do-  fc <- getFirstChild na parentIdx-  let go !ci !acc-        | ci < 0 = pure acc-        | otherwise = do-            nt <- getNodeType na ci-            ns <- getNextSibling na ci-            if isFloatingNode nt-              then go ns acc-              else f acc ci >>= go ns-  go fc z--{-# INLINE findNodeRevM #-}-findNodeRevM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)-findNodeRevM na p = do-  n <- arenaCount na-  let go !i-        | i < 0 = pure Nothing-        | otherwise = do-            ok <- p i-            if ok then pure (Just i) else go (i - 1)-  go (n - 1)---{-# INLINE foldNodeRevM #-}-foldNodeRevM :: NodeArena -> (a -> NodeIdx -> IO a) -> a -> IO a-foldNodeRevM na f z = do-  n <- arenaCount na-  let go !i !acc-        | i < 0 = pure acc-        | otherwise = do-            acc' <- f acc i-            go (i - 1) acc'-  go (n - 1) z---- ------------------------------------------------------------------------------ Frame traversal helpers: forward node scans and child searches, shaped like--- 'forNodes_' and 'findNodeRevM'.--- ------------------------------------------------------------------------------- | First node, in arena order, satisfying the predicate.-{-# INLINE findNodeM #-}-findNodeM :: NodeArena -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)-findNodeM na p = do-  n <- arenaCount na-  let go !i-        | i >= n = pure Nothing-        | otherwise = do-            ok <- p i-            if ok then pure (Just i) else go (i + 1)-  go 0---- | Left fold over every node in arena order.-{-# INLINE foldNodesM #-}-foldNodesM :: NodeArena -> (a -> NodeIdx -> IO a) -> a -> IO a-foldNodesM na f z = do-  n <- arenaCount na-  let go !i !acc-        | i >= n = pure acc-        | otherwise = f acc i >>= go (i + 1)-  go 0 z---- | First direct child of @parentIdx@ satisfying the predicate.-{-# INLINE findChildM #-}-findChildM :: NodeArena -> NodeIdx -> (NodeIdx -> IO Bool) -> IO (Maybe NodeIdx)-findChildM na parentIdx p = do-  fc <- getFirstChild na parentIdx-  let go !ci-        | ci < 0 = pure Nothing-        | otherwise = do-            ok <- p ci-            if ok then pure (Just ci) else getNextSibling na ci >>= go-  go fc
− lib/NanoUI/Layout/Solve.hs
@@ -1,1880 +0,0 @@--- | The layout solver: measures and places the node arena's flow tree, then--- positions modals, windows and popups.-module NanoUI.Layout.Solve-  ( solveLayout-  , FontResolver-  , Measurers (..)-  , placeModals-  , placeWindows-  , placePopups-  , computePopupPosition-  , placeWindowNode-  , scrollBarSlotOf-  , findAncestorMaxW-  , textWrapCap-  ) where--import Control.Monad (foldM, forM, unless, when)-import Data.IORef (readIORef)-import Data.Maybe (fromMaybe)-import Data.Primitive.PrimArray-  ( MutablePrimArray-  , copyMutablePrimArray-  , newPrimArray-  , readPrimArray-  , writePrimArray-  )-import Data.Primitive.Types (Prim)-import Data.Text (Text)-import qualified Data.Text as T-import Data.Word (Word8)-import GHC.Exts (RealWorld)-import NanoUI.Font-  ( CustomMeasureFn-  , FontMetrics (..)-  , checkboxBoxSize-  , checkboxLeading-  , treeRowLeading-  , treeItemPadding-  , classifyScrollBar-  , measureTextIO-  , lineWidthIO-  , measureTextWrappedIO-  , tableCellInset-  , ScrollBarSlot (..)-  , widgetPadding-  , buttonPadding-  , menuItemPadX-  , menuOuterPad-  , selectPadding-  , isDefaultNodeFont-  , sliderTrackHeight-  , sliderHandleDiameter-  , sliderHandleSlack-  , centeredTextY-  )-import NanoUI.Layout.Arena-  ( DirTag (..)-  , FlexScratch (..)-  , NodeArena-  , NodeArenaArrays-  , NodeIdx-  , NodeType (..)-  , SizingTag (..)-  , arenaArrays-  , arenaCount-  , hasCenteredLabel-  , withArenaArraysSnap-  , geomX-  , geomY-  , geomW-  , geomH-  , styleWVal-  , styleHVal-  , styleMinW-  , styleMinH-  , styleMaxW-  , styleMaxH-  , stylePadL-  , stylePadR-  , stylePadT-  , stylePadB-  , styleGap-  , styleGridMinColW-  , tagNodeType-  , tagDirection-  , treeStyleIdx-  , treeGridCols-  , tagWSizing-  , tagHSizing-  , tagScrollBarSlot-  , readGeom-  , writeTagEnum-  , writeGeom-  , readStyle-  , readTagEnum-  , readTree-  , treeParent-  , getAlignX-  , getAlignY-  , getChildCount-  , getDirection-  , getFirstChild-  , getGap-  , getGridCols-  , getGridMinColW-  , getHeightSizing-  , getMinMax-  , getNodeType-  , getOptions-  , getParent-  , getStyleIdx-  , getPadding-  , getRect-  , getText-  , getWidgetId-  , getWidthSizing-  , parentIsRow-  , isContainerNode-  , isFloatingNode-  , isScrollNode-  , setRect-  , getNodeValue-  , setNodeValue-  , getNodeFontSize-  , getScrollContentW-  , setScrollContentW-  , ensureScratchCapacity-  , AxisSnapshot (..)-  , ensureAxisSnapshot-  , memoizeWidth-  , forNodes_-  , foldFlowChildrenM-  , naScratch-  , naWrapMemo-  , naFitMemo-  )-import NanoUI.Id (WidgetId)-import NanoUI.Style (AlignX (..), AlignY (..), FontStyle (..), FontVariant (..), FontWeight (..), Padding (..), windowMargin)-import NanoUI.Types (PopupAnchor (..), PopupPlacement (..), Rect (..), V2 (..), clamp, onGrid)-import NanoUI.WidgetText-  ( colorPickerSvH-  , textNodeFontVariant-  , textNodeFontWeight-  , textNodeFontStyle-  , treeDecodeStyle-  , selectDisplayText-  , selectChevronReserve-  , textInputFieldHeight-  , textInputMinWidth-  , textInputSearchMode-  , textInputNumericMode-  , numericStepperW-  , textInputSelectableMode-  , searchFieldReserveW-  , isTableHeaderStyle-  , isMenuItemStyle-  , isCloseButtonStyle-  , tableHeaderDisplayText-  )-import NanoUI.Frame.Scroll.Geometry-  ( decodeScrollConfig-  , isScrollStyle2D-  , scrollAxisGutter-  , scrollGutters2D-  , scrollPolicyX-  , scrollPolicyY-  )--type FontResolver = Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Text -> IO (Float, Float))---- | Per-solve constants threaded through the measure and position passes.-data SolveEnv = SolveEnv-  { seArena :: !NodeArena-  , seArrays :: !NodeArenaArrays-  , seFm :: !FontMetrics-  , seMonoFm :: !FontMetrics-  , seMeasure :: !(Text -> IO (Float, Float))-  , seResolveFont :: !FontResolver-  , seLookupMeasure :: !(WidgetId -> IO (Maybe CustomMeasureFn))-  }---- | How text and custom widgets are measured. The solve and the placement of--- floating nodes after it measure with the same, so a label placed in a modal--- wraps exactly as the solve measured it for the modal's size.-data Measurers = Measurers-  { msFm :: !FontMetrics-  , msMonoFm :: !FontMetrics-  , msMeasure :: !(Text -> IO (Float, Float))-  , msResolveFont :: !FontResolver-  , msLookupMeasure :: !(WidgetId -> IO (Maybe CustomMeasureFn))-  }--solveEnv :: NodeArena -> Measurers -> IO SolveEnv-solveEnv na Measurers {msFm, msMonoFm, msMeasure, msResolveFont, msLookupMeasure} = do-  a <- arenaArrays na-  pure (SolveEnv na a msFm msMonoFm msMeasure msResolveFont msLookupMeasure)---- | Strict accumulator for flow-child folds: a child count and two running--- sums or extents. The strict fields keep the folds unboxed.-data FlowAcc = FlowAcc !Int !Float !Float---- Keep font selection and single-line/wrapped measurement together so every--- layout pass uses the same policy. Monospaced text uses its metrics directly;--- proportional text uses the host's shaping-aware measurement callback.-data TextMeasurer = TextMeasurer-  { tmMetrics :: !FontMetrics-  , tmVariant :: !FontVariant-  , tmHostLine :: Text -> IO (Float, Float)-  }--textNodeMeasurer :: SolveEnv -> NodeIdx -> IO TextMeasurer-textNodeMeasurer SolveEnv {seArena = na, seFm = fm, seMonoFm = monoFm, seMeasure = measure, seResolveFont = resolveFont} idx = do-  si <- getStyleIdx na idx-  size <- getNodeFontSize na idx-  let variant = textNodeFontVariant si-      weight = textNodeFontWeight si-      style = textNodeFontStyle si-  (metrics, measureLine) <--    if isDefaultNodeFont size weight style variant-      then pure (if variant == FontMono then monoFm else fm, measure)-      else resolveFont size weight style variant-  pure (TextMeasurer metrics variant measureLine)---- Keep these operations as inline functions rather than allocating two--- closures for every resolved node, including nodes that never wrap.-{-# INLINE measureFontLine #-}-measureFontLine :: TextMeasurer -> Text -> IO (Float, Float)-measureFontLine TextMeasurer {tmMetrics = metrics, tmVariant = variant, tmHostLine = hostLine} text-  | variant == FontMono = measureTextIO metrics text-  | otherwise = hostLine text--{-# INLINE measureFontWrapped #-}-measureFontWrapped :: TextMeasurer -> Text -> Float -> IO (Float, Float)-measureFontWrapped TextMeasurer {tmMetrics = metrics, tmVariant = variant, tmHostLine = hostLine} text width-  | variant == FontMono = measureTextWrappedIO (lineWidthIO metrics) metrics text width-  | otherwise = measureTextWrappedIO (fmap fst . hostLine) metrics text width---- | A measured text node: whether it wrapped, its content size, and the line--- height of its font.-data TextBox = TextBox-  { tbWrapped :: !Bool-  , tbW :: !Float-  , tbH :: !Float-  , tbLineH :: !Float-  }---- | Measure a text node's content for the width @outerW@. The text wraps at--- @outerW@ minus its label inset when it has explicit newlines, or when--- @shouldWrap wrapW lineW@ holds for its single-line width.-measureTextNodeAt :: SolveEnv -> NodeIdx -> Text -> Float -> (Float -> Float -> Bool) -> IO TextBox-measureTextNodeAt env idx txt outerW shouldWrap = do-  measurer@TextMeasurer {tmMetrics = textFm} <- textNodeMeasurer env idx-  (tw0, th0) <- measureFontLine measurer txt-  let wrapW = max 0 outerW-      lineH = fmLineHeight textFm-      na = seArena env-  if T.any (== '\n') txt || shouldWrap wrapW tw0-    then do-      (tw, th) <- memoizeWidth na (naWrapMemo na) idx wrapW (measureFontWrapped measurer txt wrapW)-      pure (TextBox True tw th lineH)-    else pure (TextBox False tw0 th0 lineH)---- | Wrap policy once a width is assigned: wrap when allowed and the single--- line overflows a positive wrap width.-{-# INLINE wrapsNarrower #-}-wrapsNarrower :: Bool -> Float -> Float -> Bool-wrapsNarrower allowed wrapW lineW = allowed && wrapW + 0.5 < lineW && wrapW > 0--solveLayout :: NodeArena -> Measurers -> Float -> Float -> IO ()-solveLayout na ms rootW rootH =-  withArenaArraysSnap na $ do-    count <- arenaCount na-    when (count > 0) $ do-      env <- solveEnv na ms-      measurePass env count-      positionNodeA env 0 0 0 0 rootW rootH-      quantizeResultsA (seArrays env) count (fmSnapScale (msFm ms))--quantizeResultsA :: NodeArenaArrays -> Int -> Float -> IO ()-quantizeResultsA a count s-  | s <= 0 = pure ()-  | otherwise = do-      -- A floating node (modal, window, popup) and everything inside it is-      -- laid out by placement after the solve, which sizes the subtree from-      -- these measured sizes. Rounding them here would size a dialog and its-      -- content-sized parts off their content, so the subtree keeps them;-      -- placement overwrites its geometry anyway. A parent always precedes-      -- its children, so one pass marks each node from its parent.-      floating <- newPrimArray count :: IO (MutablePrimArray RealWorld Word8)-      let go i-            | i >= count = pure ()-            | otherwise = do-                nt <- readTagEnum a i tagNodeType-                parent <- readTree a i treeParent-                inFloating <--                  if isFloatingNode nt-                    then pure True-                    else if parent >= 0 then (/= 0) <$> readPrimArray floating parent else pure False-                writePrimArray floating i (if inFloating then 1 else 0)-                unless inFloating $ do-                  x <- readGeom a i geomX-                  y <- readGeom a i geomY-                  w <- readGeom a i geomW-                  h <- readGeom a i geomH-                  writeGeom a i geomX (onGrid s x)-                  writeGeom a i geomY (onGrid s y)-                  writeGeom a i geomW (max 0 (onGrid s w))-                  writeGeom a i geomH (max 0 (onGrid s h))-                go (i + 1)-      go 0--measurePass :: SolveEnv -> Int -> IO ()-measurePass env count = do-  let go !idx-        | idx < 0 = pure ()-        | otherwise = do-            measureNode env idx-            go (idx - 1)-  go (count - 1)--measureNode :: SolveEnv -> NodeIdx -> IO ()-measureNode env@SolveEnv {seArena = na, seFm = fm} idx = do-  nt <- readTagEnum (seArrays env) idx tagNodeType-  case nt of-    NodeText -> measureTextNode env idx-    NodeSpacer -> measureSpacer na idx-    NodeSeparator -> measureSeparator na idx-    NodeScrollContainer -> measureScrollContainer env idx-    NodeImage -> measureImage na idx-    NodeBox -> measureImage na idx-    NodeDrawing -> do-      wid <- getWidgetId na idx-      mFn <- seLookupMeasure env wid-      case mFn of-        Just fn -> measureCustomNode na fm fn idx-        Nothing -> measureImage na idx-    _-      | isContainerNode nt -> do-          measureContainer env idx-          when (nt == NodeModal) $ setNodeValue na idx 0-      | otherwise -> measureWidget env idx--measureCustomNode ::-  NodeArena ->-  FontMetrics ->-  CustomMeasureFn ->-  NodeIdx ->-  IO ()-measureCustomNode na fm measureFn idx = do-  (minW, minH, maxW, maxH) <- getMinMax na idx-  (wTag, wVal) <- getWidthSizing na idx-  (hTag, hVal) <- getHeightSizing na idx-  let availW = case wTag of SizingFixed -> wVal; _ -> if maxW < 1e8 then maxW else 1e9-      availH = case hTag of SizingFixed -> hVal; _ -> if maxH < 1e8 then maxH else 1e9-      (mw, mh) = measureFn fm (availW, availH)-      w = case wTag of SizingFixed -> wVal; _ -> clamp minW maxW mw-      h = case hTag of SizingFixed -> hVal; _ -> clamp minH maxH mh-  setRect na idx 0 0 w h---- | The width a text node that is not a row's child wraps at, from its--- effective max width, width sizing and assigned width: 1e8 or more when--- nothing caps it ('collectNodeTextSpans').-textWrapCap :: Float -> SizingTag -> Float -> Float-textWrapCap effMaxW wTag w-  | effMaxW < 1e8 = max 0 effMaxW-  | wTag == SizingGrow && w > 0 = w-  | otherwise = effMaxW--findAncestorMaxW :: NodeArena -> NodeIdx -> IO Float-findAncestorMaxW na idx = go idx 0-  where-    go cur !padAccum = do-      p <- getParent na cur-      if p < 0-        then pure 1e9-        else do-          pad <- getPadding na p-          let padAccum' = padAccum + padL pad + padR pad-          (_, _, pMaxW, _) <- getMinMax na p-          (pwTag, pwVal) <- getWidthSizing na p-          if pwTag == SizingFixed-            then pure (max 0 (pwVal - padAccum'))-            else if pMaxW < 1e8-              then pure (max 0 (pMaxW - padAccum'))-              else go p padAccum'--measureTextNode :: SolveEnv -> NodeIdx -> IO ()-measureTextNode env@SolveEnv {seArena = na} idx = do-  (minW, minH, maxW, maxH) <- getMinMax na idx-  (wTag, _) <- getWidthSizing na idx-  (hTag, hVal) <- getHeightSizing na idx-  parentAssigns <- growParent na idx-  txt <- getText na idx-  isRowChild <- parentIsRow na idx-  effMaxW <--    if maxW < 1e8-      then pure maxW-      else findAncestorMaxW na idx-  let canWrap = not isRowChild && effMaxW < 1e8-  TextBox {tbW = tw, tbH = th, tbLineH = lineH} <--    measureTextNodeAt env idx txt effMaxW (\_ lineW -> canWrap && effMaxW + 0.5 < lineW)-  let reportedW =-        if wTag == SizingGrow && parentAssigns-          then clamp minW maxW 0-          else clamp minW maxW tw-  setRect na idx 0 0 reportedW $-    case hTag of-      SizingFixed -> clamp minH maxH hVal-      _ -> clamp minH maxH (max lineH th)---- | Whether a grow-width node's width is assigned from above rather than--- reported: its parent grows, and the nearest ancestor that does not grow is--- not a modal. A modal takes its width from what it holds, so a grow label--- inside one still reports its natural width; otherwise the modal could never--- widen for it and the label would wrap into more lines than the modal--- measured. Windows keep their own width and truncate long lines instead.-growParent :: NodeArena -> NodeIdx -> IO Bool-growParent na idx = getParent na idx >>= go True-  where-    go isParent p-      | p < 0 = pure (not isParent)-      | otherwise = do-          (pwTag, _) <- getWidthSizing na p-          if pwTag == SizingGrow-            then getParent na p >>= go False-            else-              if isParent-                then pure False-                else do-                  nt <- getNodeType na p-                  pure (nt /= NodeModal)--measureImage :: NodeArena -> NodeIdx -> IO ()-measureImage na idx = do-  (minW, minH, maxW, maxH) <- getMinMax na idx-  (wTag, wVal) <- getWidthSizing na idx-  (hTag, hVal) <- getHeightSizing na idx-  let w =-        case wTag of-          SizingFixed -> wVal-          _ -> if minW > 0 then minW else 32-      h =-        case hTag of-          SizingFixed -> hVal-          _ -> if minH > 0 then minH else 32-  setRect na idx 0 0 (clamp minW maxW w) (clamp minH maxH h)--measureSpacer :: NodeArena -> NodeIdx -> IO ()-measureSpacer na idx = do-  (wTag, wVal) <- getWidthSizing na idx-  (hTag, hVal) <- getHeightSizing na idx-  -- Non-fixed spacers reserve the default 8px extent.-  let w = if wTag == SizingFixed then wVal else 8-      h = if hTag == SizingFixed then hVal else 8-  setRect na idx 0 0 w h--measureSeparator :: NodeArena -> NodeIdx -> IO ()-measureSeparator na idx = do-  dir <- getDirection na idx-  case dir of-    DirRow -> setRect na idx 0 0 1 20-    DirColumn -> setRect na idx 0 0 20 1--{-# INLINE measureMarkedWidget #-}-measureMarkedWidget ::-  FontMetrics ->-  (Text -> IO (Float, Float)) ->-  Text ->-  Float ->-  IO (Float, Float, Float, Float)-measureMarkedWidget fm measure body leading = do-  (mw, mh) <- measure (if T.null body then " " else body)-  pure (mw, max mh (checkboxBoxSize fm), leading, 0)--measureTextField ::-  FontMetrics ->-  (Text -> IO (Float, Float)) ->-  Text ->-  Bool ->-  IO (Float, Float, Float, Float)-measureTextField fm measure txt multiline = do-  pw <- if multiline || T.null txt then pure 0 else fst <$> measure txt-  let fieldH = if multiline then max 96 (textInputFieldHeight fm * 4) else textInputFieldHeight fm-      contentW = max textInputMinWidth pw-  pure (contentW, fieldH, 0, 0)---- Caption-less search box: single row tall, icons counted in the width budget.-measureSearchField ::-  FontMetrics ->-  (Text -> IO (Float, Float)) ->-  Text ->-  IO (Float, Float, Float, Float)-measureSearchField fm measure txt = do-  let lbl = if T.null txt then " " else txt-  (lw, _) <- measure lbl-  let contentW = max textInputMinWidth lw + searchFieldReserveW fm-  pure (contentW, textInputFieldHeight fm, 0, 0)--measureWidget :: SolveEnv -> NodeIdx -> IO ()-measureWidget env@SolveEnv {seArena = na, seArrays = a, seFm = fm, seMeasure = measure} idx = do-  nt <- readTagEnum a idx tagNodeType-  txt <- getText na idx-  si <- readTree a idx treeStyleIdx-  minW <- readStyle a idx styleMinW-  minH <- readStyle a idx styleMinH-  maxW <- readStyle a idx styleMaxW-  maxH <- readStyle a idx styleMaxH-  wTag <- readTagEnum a idx tagWSizing-  wVal <- readStyle a idx styleWVal-  hTag <- readTagEnum a idx tagHSizing-  hVal <- readStyle a idx styleHVal-  let (padX, padY) =-        case nt of-          NodeButton-            | isTableHeaderStyle si ->-                (2 * tableCellInset, 0)-            -- Menu rows reserve the same gutter the text-field context menu-            -- paints (outer pad + item pad on each side of the label), so the-            -- generic popup panel sizes identically.-            | isMenuItemStyle si ->-                (2 * (menuOuterPad + menuItemPadX), snd (buttonPadding fm))-            | otherwise -> buttonPadding fm-          NodeSelect -> selectPadding fm-          NodeTree -> treeItemPadding fm-          NodeTextInput-            | textInputSelectableMode si -> (0, 0)-          _-            | nt == NodeColorPicker-                || nt == NodeSlider-                || nt == NodeCheckbox-                || nt == NodeRadio-                || nt == NodeTextInput-                || nt == NodeTextArea ->-                (0, 0)-            | otherwise -> widgetPadding fm-  (tw, th, extraW, extraH) <--    case nt of-      NodeSlider -> do-        let contentW = 60-            contentH = max sliderHandleDiameter (sliderTrackHeight + 2 * sliderHandleSlack)-        pure (contentW, contentH, 0, 0)-      NodeTree -> do-        let (_, depth, _, _) = treeDecodeStyle si-        measureMarkedWidget fm measure txt (treeRowLeading fm depth)-      NodeSelect -> do-        opts <- getOptions na idx-        let choices = if null opts then [""] else opts-        (mw, mh) <--          foldM-            (\(!mw, !mh) c -> (\(w, h) -> (max mw w, max mh h)) <$> measure (selectDisplayText txt c))-            (0, 0)-            choices-        pure (mw, mh, selectChevronReserve, 0)-      -- Picker parts carry fixed layouts; the field grows to its square.-      NodeColorPicker -> pure (0, colorPickerSvH, 0, 0)-      NodeTextInput-        | textInputSelectableMode si -> do-            -- Size with the node's own font (paint and span placement resolve-            -- it too); the ambient `measure` is the default font only.-            measurer <- textNodeMeasurer env idx-            (mw, mh) <- measureFontLine measurer (if T.null txt then " " else txt)-            pure (mw, mh, 0, 0)-        -- Numeric field: a short editable box and its stepper.-        | textInputNumericMode si ->-            pure (56, textInputFieldHeight fm, numericStepperW, 0)-        | textInputSearchMode si ->-            measureSearchField fm measure txt-        | otherwise -> measureTextField fm measure txt False-      NodeTextArea -> measureTextField fm measure txt True-      _-        | nt == NodeCheckbox || nt == NodeRadio ->-            measureMarkedWidget fm measure txt (checkboxLeading fm)-        | otherwise -> do-            body <--              if T.null txt-                then pure " "-                else-                  if isTableHeaderStyle si-                    then pure (tableHeaderDisplayText txt)-                    else pure txt-            (mw, mh) <- measure body-            pure (mw, mh, 0, 0)-  let rawW = tw + padX + extraW-      rawH = th + padY + extraH-      w = case wTag of SizingFixed -> wVal; _ -> clamp minW maxW rawW-      h = case hTag of SizingFixed -> hVal; _ -> clamp minH maxH rawH-  setRect na idx 0 0 w h--measureContainer :: SolveEnv -> NodeIdx -> IO ()-measureContainer env@SolveEnv {seArena = na, seArrays = a} idx = do-  (pad, gap, dir) <- containerFlow a idx-  gCols <- readTree a idx treeGridCols-  minColW <- readStyle a idx styleGridMinColW-  minW <- readStyle a idx styleMinW-  minH <- readStyle a idx styleMinH-  maxW <- readStyle a idx styleMaxW-  maxH <- readStyle a idx styleMaxH-  wTag <- readTagEnum a idx tagWSizing-  wVal <- readStyle a idx styleWVal-  hTag <- readTagEnum a idx tagHSizing-  hVal <- readStyle a idx styleHVal-  nt <- readTagEnum a idx tagNodeType-  let chrome = isChromeColumn nt dir-      padX = padL pad + padR pad-      padY = padT pad + padB pad-      innerMaxW =-        case wTag of-          SizingFixed -> max 0 (wVal - padX)-          _ -> max 0 (maxW - padX)-      innerAvailH =-        case hTag of-          SizingFixed -> max 0 (hVal - padY)-          _ -> max 0 (maxH - padY)-  (contentW, contentH) <--    if gCols > 0 || minColW > 0-      then measureGridScratch env idx gCols minColW innerMaxW innerAvailH gap-      else if dir == DirColumn && chrome-        then do-          n <- loadChildrenScratch na idx (flowChildSize env False innerMaxW innerAvailH)-          foldChromeColumnScratch na n gap-        else foldChildDimsFromParent env idx dir gap-  -- A grow container with its own minimum width, whose width is assigned from-  -- above, reports that minimum rather than its content: it shrinks that far-  -- in a row that is short of space, so that is the least it needs. As with-  -- CSS's min-width on a flex item, the explicit minimum replaces the-  -- content-based one. Otherwise a 2D scroller, which lays its content out at-  -- the width it reports, scrolls sideways for a long label in a cell that-  -- would have fit. Without a minimum the content still counts, so a grow-  -- wrapper around a wide table keeps its sideways scroll.-  minAssigned <--    if wTag == SizingGrow && minW > 0 && not (isFloatingNode nt)-      then growParent na idx-      else pure False-  let w =-        case wTag of-          SizingFixed -> clamp minW maxW wVal-          _-            | minAssigned -> clamp minW maxW 0-            | otherwise -> clamp minW maxW (contentW + padX)-      h =-        case hTag of-          SizingFixed -> clamp minH maxH hVal-          _ -> clamp minH maxH (contentH + padY)-  setRect na idx 0 0 w h--measureScrollContainer :: SolveEnv -> NodeIdx -> IO ()-measureScrollContainer env@SolveEnv {seArena = na, seArrays = a} idx = do-  (pad, gap, dir) <- containerFlow a idx-  let padX = padL pad + padR pad-      padY = padT pad + padB pad-  si <- getStyleIdx na idx-  (minW, minH, maxW, maxH) <- getMinMax na idx-  (wTag, wVal) <- getWidthSizing na idx-  (hTag, hVal) <- getHeightSizing na idx-  (contentW, contentH) <- foldChildDimsFromParent env idx dir gap-  parent <- getParent na idx-  -- A modal's body scrolls like a window's: its bar sits just inside the-  -- panel's edge, out in the panel padding.-  isWin <--    if parent < 0-      then pure False-      else do-        pnt <- getNodeType na parent-        pure (pnt == NodeWindow || pnt == NodeModal)-  inPanel <- hasPanelAncestor na parent-  let slot = classifyScrollBar isWin (wTag == SizingGrow && hTag == SizingGrow && not inPanel)-  writeTagEnum a idx tagScrollBarSlot slot-  let fullW = contentW + padX-      fullH = contentH + padY-      assignedInnerH =-        case hTag of-          SizingFixed -> max 0 (hVal - padY)-          _ -> contentH-      cfg = decodeScrollConfig si-      fitGutterW-        | wTag == SizingGrow || wTag == SizingFixed = 0-        | isScrollStyle2D si = 0-        | otherwise =-            case dir of-              DirColumn -> scrollAxisGutter (scrollPolicyY cfg) slot (padR pad) contentH assignedInnerH-              DirRow -> 0-      viewportW =-        case wTag of-          SizingFixed -> wVal-          _ -> fullW + fitGutterW-      viewportH =-        case hTag of-          SizingFixed -> hVal-          _ -> fullH-  if isScrollStyle2D si-    then do-      setNodeValue na idx contentH-      setScrollContentW na idx contentW-    else setNodeValue na idx (case dir of DirColumn -> contentH; DirRow -> contentW)-  setRect na idx 0 0 (clamp minW maxW viewportW) (clamp minH maxH viewportH)--foldChildDimsFromParent :: SolveEnv -> NodeIdx -> DirTag -> Float -> IO (Float, Float)-foldChildDimsFromParent env@SolveEnv {seArena = na} idx dir gap = do-  FlowAcc count main cross <- foldFlowChildrenM na idx step (FlowAcc 0 0 0)-  -- A row's baseline-aligned children stand on one line, so together they are-  -- as tall as the most room any takes above it plus the most any takes below.-  baseline <--    if dir == DirRow-      then foldFlowChildrenM na idx baselineStep (0, 0)-      else pure (0, 0)-  pure-    ( case dir of-        DirRow ->-          ( main + gap * fromIntegral (max 0 (count - 1))-          , if count <= 0 then 0 else max cross (uncurry (+) baseline)-          )-        DirColumn ->-          ( if count <= 0 then 0 else main-          , cross + gap * fromIntegral (max 0 (count - 1))-          )-    )-  where-    step (FlowAcc count main cross) ci = do-      (_, _, w, h) <- getRect na ci-      pure $-        case dir of-          DirRow -> FlowAcc (count + 1) (main + w) (max cross h)-          DirColumn -> FlowAcc (count + 1) (max main w) (cross + h)-    baselineStep acc@(above, below) ci = do-      ay <- getAlignY na ci-      if ay /= AlignBaseline-        then pure acc-        else do-          (_, _, _, h) <- getRect na ci-          b <- childBaseline env ci h-          pure (max above b, max below (h - b))--isChromeColumn :: NodeType -> DirTag -> Bool-isChromeColumn nt dir =-  dir == DirColumn && (nt == NodeWindow || nt == NodeModal)---- | Gap before child @b@ in a column; chrome columns drop it before separators.-pairColumnGap :: NodeArena -> Bool -> NodeIdx -> Float -> IO Float-pairColumnGap _ False _ gap = pure gap-pairColumnGap na True b gap = do-  ntB <- getNodeType na b-  pure (if ntB == NodeSeparator then 0 else gap)--foldChromeColumnScratch :: NodeArena -> Int -> Float -> IO (Float, Float)-foldChromeColumnScratch na n gap = do-  FlexScratch {fsW = wArr, fsH = hArr} <- readIORef (naScratch na)-  gapSum <- columnGapSumScratch na True n gap-  let go !i !maxW !totalH-        | i >= n = pure (maxW, totalH + gapSum)-        | otherwise = do-            w <- readPrimArray wArr i-            h <- readPrimArray hArr i-            go (i + 1) (max maxW w) (totalH + h)-  go 0 0 0---- | Grid column count: explicit, else as many @minColW@ columns as fit in a--- positive @availW@, else one.-{-# INLINE gridColumnCount #-}-gridColumnCount :: Int -> Float -> Float -> Float -> Int-gridColumnCount gCols minColW availW gap-  | gCols > 0 = gCols-  | minColW > 0 && availW > 0 = max 1 (floor ((availW + gap) / (minColW + gap)))-  | otherwise = 1---- | Height of grid row @r@: its tallest child.-gridRowHeight :: MutablePrimArray RealWorld Float -> Int -> Int -> Int -> IO Float-gridRowHeight hArr n cols r = go 0 0-  where-    go !j !accH-      | j >= cols = pure accH-      | otherwise = do-          let k = r * cols + j-          if k >= n-            then pure accH-            else do-              h <- readPrimArray hArr k-              go (j + 1) (max accH h)--measureGridScratch ::-  SolveEnv ->-  NodeIdx ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO (Float, Float)-measureGridScratch env idx gCols minColW innerMaxW innerAvailH gap = do-  n <- loadChildrenScratch (seArena env) idx (flowChildSize env False innerMaxW innerAvailH)-  if n <= 0-    then pure (0, 0)-    else do-      FlexScratch {fsW = wArr, fsH = hArr} <- readIORef (naScratch (seArena env))-      let cols = gridColumnCount gCols minColW (if innerMaxW < 1e8 then innerMaxW else 0) gap-          numRows = (n + cols - 1) `quot` cols-          calcRows !r !totalH-            | r >= numRows = pure totalH-            | otherwise = do-                rowH <- gridRowHeight hArr n cols r-                calcRows (r + 1) (totalH + rowH)-      totalH <- calcRows 0 0-      let contentH = totalH + gap * fromIntegral (max 0 (numRows - 1))-      contentW <--        if innerMaxW > 0 && innerMaxW < 1e8-          then pure innerMaxW-          else if minColW > 0-            then pure (fromIntegral cols * minColW + gap * fromIntegral (max 0 (cols - 1)))-            else do-              let getMaxChildW !i !accW-                    | i >= n = pure accW-                    | otherwise = do-                        w <- readPrimArray wArr i-                        getMaxChildW (i + 1) (max accW w)-              maxChildW <- getMaxChildW 0 0-              pure (fromIntegral cols * maxChildW + gap * fromIntegral (max 0 (cols - 1)))-      pure (contentW, contentH)--recomputeFitHeightAtWidth :: SolveEnv -> NodeIdx -> Float -> IO Float-recomputeFitHeightAtWidth env idx availW = do-  let na = seArena env-  (_, h) <- memoizeWidth na (naFitMemo na) idx availW ((,) 0 <$> recomputeFitHeightAtWidthGo env idx availW)-  pure h--recomputeFitHeightAtWidthGo :: SolveEnv -> NodeIdx -> Float -> IO Float-recomputeFitHeightAtWidthGo env@SolveEnv {seArena = na, seFm = fm, seLookupMeasure = lookupMeasure} idx availW = do-  nt <- getNodeType na idx-  (minW, minH, maxW, maxH) <- getMinMax na idx-  (wTag, wVal) <- getWidthSizing na idx-  (hTag, _) <- getHeightSizing na idx-  (_, _, _, oldH) <- getRect na idx-  let effW = case wTag of-        SizingPercent -> availW * wVal / 100-        SizingFixed -> wVal-        _ -> availW-      effW' = clamp minW maxW effW-  case nt of-    NodeText-      | hTag /= SizingFixed -> do-          isRowChild <- parentIsRow na idx-          txt <- getText na idx-          if T.null txt-            then pure (clamp minH maxH 0)-            else do-              TextBox {tbWrapped, tbH, tbLineH} <--                measureTextNodeAt env idx txt effW' (wrapsNarrower (wTag /= SizingFit && not isRowChild))-              pure (if tbWrapped then clamp minH maxH (max tbLineH tbH) else oldH)-      | otherwise -> pure oldH--    -- A measured drawing, like wrapped text, can be taller when narrower.-    NodeDrawing-      | hTag == SizingFit -> do-          wid <- getWidgetId na idx-          lookupMeasure wid >>= \case-            Just measure -> pure (clamp minH maxH (snd (measure fm (effW', if maxH < 1e8 then maxH else 1e9))))-            Nothing -> pure oldH-      | otherwise -> pure oldH--    _ | (nt == NodeContainer || nt == NodePanel), hTag /= SizingFixed -> do-          dir <- getDirection na idx-          if dir == DirRow-            then pure oldH-            else do-              pad <- getPadding na idx-              gap <- getGap na idx-              let innerW = max 0 (effW' - padL pad - padR pad)-                  step (FlowAcc count contentH _) ci = do-                    (subWTag, subWVal) <- getWidthSizing na ci-                    (_, _, subMaxW, _) <- getMinMax na ci-                    let subW = case subWTag of-                          SizingPercent -> innerW * subWVal / 100-                          SizingFixed -> subWVal-                          _ -> innerW-                        subW' = if subMaxW < 1e8 then min subW subMaxW else subW-                    subH <- recomputeFitHeightAtWidth env ci subW'-                    pure (FlowAcc (count + 1) (contentH + subH) 0)-              FlowAcc count contentH _ <- foldFlowChildrenM na idx step (FlowAcc 0 0 0)-              let totalH =-                    if count <= 0-                      then 0-                      else contentH + gap * fromIntegral (count - 1)-              pure (clamp minH maxH (totalH + padT pad + padB pad))--    _ -> pure oldH---- | Load a parent's flow children into the flex scratch in child order, with--- each child's (width, height) from @sizeOf@. Returns the child count.-{-# INLINE loadChildrenScratch #-}-loadChildrenScratch :: NodeArena -> NodeIdx -> (NodeIdx -> IO (Float, Float)) -> IO Int-loadChildrenScratch na parent sizeOf = do-  cc <- getChildCount na parent-  FlexScratch {fsIdx = idxArr, fsW = wArr, fsH = hArr} <- ensureScratchCapacity na cc-  let write !i ci = do-        (w, h) <- sizeOf ci-        writePrimArray idxArr i ci-        writePrimArray wArr i w-        writePrimArray hArr i h-        pure (i + 1)-  n <- foldFlowChildrenM na parent write 0-  reverseScratchTriple idxArr wArr hArr 0 (n - 1)-  pure n---- | Scratch size of a flow child: its measured box, with percent sizing--- resolved against the parent's inner box. With @refit@, a fit-height child--- that the parent narrows (grow or percent width, or wider than @availW@) is--- re-measured at the assigned width.-flowChildSize :: SolveEnv -> Bool -> Float -> Float -> NodeIdx -> IO (Float, Float)-flowChildSize env refit availW availH ci = do-  let a = seArrays env-  w <- readGeom a ci geomW-  h <- readGeom a ci geomH-  wTag <- readTagEnum a ci tagWSizing-  wVal <- readStyle a ci styleWVal-  hTag <- readTagEnum a ci tagHSizing-  hVal <- readStyle a ci styleHVal-  minW <- readStyle a ci styleMinW-  minH <- readStyle a ci styleMinH-  maxW <- readStyle a ci styleMaxW-  maxH <- readStyle a ci styleMaxH-  let w' =-        case wTag of-          SizingPercent -> clamp minW maxW (availW * wVal / 100)-          _ -> w-  h' <--    if refit && hTag /= SizingFixed && hTag /= SizingPercent && (wTag == SizingGrow || wTag == SizingPercent || availW < w)-      then recomputeFitHeightAtWidth env ci (if wTag == SizingPercent then w' else availW)-      else pure $-        case hTag of-          SizingPercent -> clamp minH maxH (availH * hVal / 100)-          _ -> h-  pure (w', h')--positionNodeA ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionNodeA env@SolveEnv {seArena = na, seArrays = a, seFm = fm, seLookupMeasure = lookupMeasure} depth idx x y availW availH = do-  minW <- readStyle a idx styleMinW-  minH <- readStyle a idx styleMinH-  maxW <- readStyle a idx styleMaxW-  maxH <- readStyle a idx styleMaxH-  wTag <- readTagEnum a idx tagWSizing-  wVal <- readStyle a idx styleWVal-  hTag <- readTagEnum a idx tagHSizing-  hVal <- readStyle a idx styleHVal-  intrinsicW <- readGeom a idx geomW-  intrinsicH <- readGeom a idx geomH-  nt <- readTagEnum a idx tagNodeType-  let w = clamp minW maxW (resolveSize wTag wVal intrinsicW availW minW maxW)-  isRowChild <- parentIsRow na idx-  h <--    if nt == NodeText && hTag /= SizingFixed && not isRowChild-      then do-        txt <- getText na idx-        if T.null txt-          then pure (clamp minH maxH 0)-          else do-            TextBox {tbWrapped, tbH, tbLineH} <--              measureTextNodeAt env idx txt w (wrapsNarrower (wTag /= SizingFit))-            pure . clamp minH maxH $-              if tbWrapped-                then max tbLineH tbH-                else resolveSize hTag hVal intrinsicH availH minH maxH-      else-        if (nt == NodeContainer || nt == NodePanel) && hTag == SizingFit-          then pure (clamp minH maxH (max intrinsicH availH))-          else-            if nt == NodeDrawing && hTag == SizingFit && w /= intrinsicW-              then do-                -- A measured drawing laid out at another width than it was-                -- measured at takes its height at the width it got.-                wid <- getWidgetId na idx-                lookupMeasure wid >>= \case-                  Just measure -> pure (clamp minH maxH (snd (measure fm (w, if maxH < 1e8 then maxH else 1e9))))-                  Nothing -> pure (clamp minH maxH (resolveSize hTag hVal intrinsicH availH minH maxH))-              else pure (clamp minH maxH (resolveSize hTag hVal intrinsicH availH minH maxH))-  setRect na idx x y w h-  when (isContainerNode nt) $ do-    (pad, gap, dir) <- containerFlow a idx-    if isScrollNode nt-      then positionScrollChildren env depth idx dir gap pad x y w h-      else positionChildren env depth idx dir gap pad x y w h-  when (hTag == SizingFit && isContainerNode nt && not (isScrollNode nt)) $-    adjustFitHeight na fm idx minH maxH x y w---- | A container's resolved padding and gap, and its direction.-{-# INLINE containerFlow #-}-containerFlow :: NodeArenaArrays -> NodeIdx -> IO (Padding, Float, DirTag)-containerFlow a idx = do-  pad <- Padding <$> readStyle a idx stylePadL <*> readStyle a idx stylePadR <*> readStyle a idx stylePadT <*> readStyle a idx stylePadB-  gap <- readStyle a idx styleGap-  dir <- readTagEnum a idx tagDirection-  pure (pad, gap, dir)--adjustFitHeight :: NodeArena -> FontMetrics -> NodeIdx -> Float -> Float -> Float -> Float -> Float -> IO ()-adjustFitHeight na fm idx minH maxH x y w = do-  fc <- getFirstChild na idx-  when (fc >= 0) $ do-    pad <- getPadding na idx-    let step maxB ci = do-          (_, subY, _, subH) <- getRect na ci-          pure (max maxB (subY + subH))-        -- Rounding a child's origin to the nearest device pixel can put its-        -- bottom up to half a pixel below where measurement did. That is not-        -- content outgrowing the measurement: growing for it adds half a-        -- pixel at every nested content-sized level, until a dialog sized to-        -- its content overflows its own scroll viewport. The small epsilon-        -- absorbs float error in the rounding.-        s = fmSnapScale fm-        snapSlack = if s > 0 then 0.5 / s + 1.0e-3 else 0-    maxB <- foldFlowChildrenM na idx step y-    let fitH = clamp minH maxH (maxB + padB pad - y)-    (_, _, _, curH) <- getRect na idx-    when (fitH > curH + snapSlack) $-      setRect na idx x y w fitH--positionScrollChildren ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  DirTag ->-  Float ->-  Padding ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionScrollChildren env@SolveEnv {seArena = na} depth idx dir gap pad px py pw ph = do-  si <- getStyleIdx na idx-  contentSize <- getNodeValue na idx-  slot <- scrollBarSlotOf na idx-  let cx = px + padL pad-      cy = py + padT pad-      innerW = pw - padL pad - padR pad-      innerH = ph - padT pad - padB pad-      cfg = decodeScrollConfig si-  if isScrollStyle2D si-    then do-      contentW <- getScrollContentW na idx-      let (gutterW, gutterH) = scrollGutters2D slot cfg pad contentW contentSize innerW innerH-          viewW = max 0 (innerW - gutterW)-          viewH = max 0 (innerH - gutterH)-          -- Keep measured content. Shrinking to the clip wraps table columns.-          layoutW = max contentW viewW-          layoutH = max contentSize viewH-      -- cx/cy and the layout box are already inside the padding.-      positionChildren env depth idx DirColumn gap (Padding 0 0 0 0) cx cy layoutW layoutH-    else do-      let gutterCol = scrollAxisGutter (scrollPolicyY cfg) slot (padR pad) contentSize innerH-          gutterRow = scrollAxisGutter (scrollPolicyX cfg) slot (padB pad) contentSize innerW-      case dir of-        DirRow -> do-          (wTag, _) <- getWidthSizing na idx-          let rowMain =-                if wTag == SizingGrow-                  then max contentSize (innerW - gutterRow)-                  else contentSize-          positionRowFromParent env depth idx gap cx cy rowMain (innerH - gutterRow)-        DirColumn -> positionColumnScroll env depth idx gap cx cy (innerW - gutterCol) innerH contentSize-  fc <- getFirstChild na idx-  when (fc >= 0) $ do-    let step (FlowAcc count maxB maxR) ci = do-          (subX, subY, subW, subH) <- getRect na ci-          pure (FlowAcc (count + 1) (max maxB (subY + subH)) (max maxR (subX + subW)))-    FlowAcc _ maxB maxR <- foldFlowChildrenM na idx step (FlowAcc 0 cy cx)-    -- Content size is measured from the content origin (px+padL, py+padT) so-    -- it compares against the padded viewport (innerW/innerH) on the same-    -- scale. Measuring from the padding-box origin double-counts the leading-    -- padding and makes a child that exactly fills the viewport look-    -- padX/padY bigger, surfacing a phantom scrollbar on padded scrollers.-    -- The trailing padding is excluded here too (so it cannot-    -- surface a bar by itself); scrollAxisRange adds it back into the-    -- reachable range once an axis genuinely overflows, so scrolling to the-    -- end still reveals it.-    let actualContentH = maxB - py - padT pad-        actualContentW = maxR - px - padL pad-    if isScrollStyle2D si-      then do-        oldH <- getNodeValue na idx-        oldW <- getScrollContentW na idx-        setNodeValue na idx (max oldH actualContentH)-        setScrollContentW na idx (max oldW actualContentW)-      else do-        oldVal <- getNodeValue na idx-        let actual = case dir of DirColumn -> actualContentH; DirRow -> actualContentW-        setNodeValue na idx (max oldVal actual)---- | Where a scroll container's bar sits, as measurement stored it. Text--- areas and other nodes read 'ScrollBarList'.-{-# INLINE scrollBarSlotOf #-}-scrollBarSlotOf :: NodeArena -> NodeIdx -> IO ScrollBarSlot-scrollBarSlotOf na idx = arenaArrays na >>= \a -> readTagEnum a idx tagScrollBarSlot--hasPanelAncestor :: NodeArena -> NodeIdx -> IO Bool-hasPanelAncestor na = go-  where-    go p-      | p < 0 = pure False-      | otherwise = do-          nt <- getNodeType na p-          case nt of-            NodePanel -> pure True-            NodeWindow -> pure False-            NodeModal -> pure False-            NodePopup -> pure False-            _ -> getParent na p >>= go--positionColumnScroll ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionColumnScroll env@SolveEnv {seArena = na} depth parent gap cx cy innerW innerH contentSize = do-  n <- loadChildrenScratch (seArena env) parent (flowChildSize env True innerW innerH)-  withAxisSnaps na depth n contentSize (gap * fromIntegral (max 0 (n - 1))) False $ \idxSnap outSnap -> do-    let go !i !curY-          | i >= n = pure ()-          | otherwise = do-              ci <- readPrimArray idxSnap i-              fh <- readPrimArray outSnap i-              nt <- getNodeType na ci-              fx <- columnChildX na ci cx innerW-              let cw = innerW-                  visibleSlice = max 0 (innerH - (curY - cy))-                  nodeH =-                    if isScrollNode nt-                      then min fh visibleSlice-                      else fh-              positionNodeA env (depth + 1) ci fx curY cw nodeH-              (_, _, _, placedH) <- getRect na ci-              go (i + 1) (curY + placedH + gap)-    go 0 cy---- | Left edge of column child @ci@ in a column of width @cw@ at @cx@. Grow and--- percent children already take the full width; alignment is for content--- narrower than the column, not for shifting a full-width box past it.-{-# INLINE columnChildX #-}-columnChildX :: NodeArena -> NodeIdx -> Float -> Float -> IO Float-columnChildX na ci cx cw = do-  (wTag, _) <- getWidthSizing na ci-  if wTag == SizingGrow || wTag == SizingPercent-    then pure cx-    else do-      (_, _, iw, _) <- getRect na ci-      ax <- getAlignX na ci-      pure $! alignX ax cx cw iw--{-# INLINE resolveSize #-}-resolveSize :: SizingTag -> Float -> Float -> Float -> Float -> Float -> Float-resolveSize SizingFixed v _ _ _ _ = v-resolveSize SizingFit _ intrinsic avail minS maxS = clamp minS maxS (min intrinsic avail)-resolveSize SizingShrink _ intrinsic avail minS maxS = clamp minS maxS (min intrinsic avail)-resolveSize SizingGrow _ _ avail _ maxS = min avail maxS-resolveSize SizingPercent _ _ avail _ maxS = min avail maxS--positionChildren ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  DirTag ->-  Float ->-  Padding ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionChildren env@SolveEnv {seArena = na} depth idx dir gap pad px py pw ph = do-  nt <- getNodeType na idx-  gCols <- getGridCols na idx-  minColW <- getGridMinColW na idx-  let chrome = isChromeColumn nt dir-      cx = px + padL pad-      cy = py + padT pad-      cw = pw - padL pad - padR pad-      ch = ph - padT pad - padB pad-  if gCols > 0 || minColW > 0-    then positionGrid env depth idx gCols minColW gap cx cy cw ch-    else case dir of-      DirRow -> positionRowFromParent env depth idx gap cx cy cw ch-      DirColumn -> positionColumnFromParent env depth idx gap chrome px pw cx cy cw ch--childRowCrossSize :: NodeArena -> NodeIdx -> Float -> IO Float-childRowCrossSize na ci availCross = do-  (hTag, hVal) <- getHeightSizing na ci-  (_, _, _, intrinsic) <- getRect na ci-  (_, minH, _, maxH) <- getMinMax na ci-  let resolved = clamp minH maxH (resolveSize hTag hVal intrinsic availCross minH maxH)-  case hTag of-    SizingFixed -> pure (clamp minH maxH hVal)-    SizingGrow -> pure resolved-    SizingPercent -> pure resolved-    _ ->-      -- Fit/Shrink keep the measured box. Do not use the wrap-line-      -- or row slot as availH: that stretches every child when leftover-      -- leaks into scratch `fh`.-      pure (max minH intrinsic)---- Column leftover must not change Fixed step height.-columnChildHeight :: NodeArena -> NodeIdx -> Float -> IO Float-columnChildHeight na ci scratchH = do-  (hTag, _) <- getHeightSizing na ci-  case hTag of-    SizingFixed -> do-      (_, minH, _, maxH) <- getMinMax na ci-      (_, _, _, ih) <- getRect na ci-      pure (clamp minH maxH ih)-    _ -> do-      (_, minH, _, maxH) <- getMinMax na ci-      pure (clamp minH maxH scratchH)--{-# INLINE withAxisSnaps #-}-withAxisSnaps ::-  NodeArena ->-  Int ->-  Int ->-  Float ->-  Float ->-  Bool ->-  (MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Float -> IO a) ->-  IO a-withAxisSnaps na depth n availMain gapSum horizontal act = do-  distributeScratch na n availMain gapSum horizontal-  FlexScratch {fsIdx = idxArr, fsOutW = outW, fsOutH = outH} <- readIORef (naScratch na)-  let outArr = if horizontal then outW else outH-  AxisSnapshot idxSnap outSnap <- ensureAxisSnapshot na depth n-  copyMutablePrimArray idxSnap 0 idxArr 0 n-  copyMutablePrimArray outSnap 0 outArr 0 n-  act idxSnap outSnap---- | Like 'withAxisSnaps' but snapshots the unscaled child cross sizes instead--- of the distributed main-axis result. Grids compute rows from the measured--- child heights, so freezing them lets the recursion reuse the working scratch.-withGridScratch :: NodeArena -> Int -> Int -> (MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Float -> IO a) -> IO a-withGridScratch na depth n act = do-  FlexScratch {fsIdx = idxArr, fsH = hArr} <- readIORef (naScratch na)-  AxisSnapshot idxSnap crossSnap <- ensureAxisSnapshot na depth n-  copyMutablePrimArray idxSnap 0 idxArr 0 n-  copyMutablePrimArray crossSnap 0 hArr 0 n-  act idxSnap crossSnap--positionRowFromParent ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionRowFromParent env@SolveEnv {seArena = na, seFm = fm} depth parent gap cx cy cw ch = do-  n <- loadChildrenScratch (seArena env) parent (flowChildSize env False cw ch)-  withAxisSnaps na depth n cw (gap * fromIntegral (max 0 (n - 1))) True $ \idxSnap outSnap -> do-    -- The shared baseline sits as low as the deepest one among the children-    -- aligned on it, so the child with the tallest ascent stays at the top.-    let goBase !i !acc-          | i >= n = pure acc-          | otherwise = do-              ci <- readPrimArray idxSnap i-              ay <- getAlignY na ci-              if ay /= AlignBaseline-                then goBase (i + 1) acc-                else do-                  b <- childRowCrossSize na ci ch >>= childBaseline env ci-                  goBase (i + 1) (max acc b)-    rowBase <- goBase 0 0-    let goRow !i !cur !prev-          | i >= n = pure ()-          | otherwise = do-              ci <- readPrimArray idxSnap i-              fw <- readPrimArray outSnap i-              let x = snappedOrigin (fmSnapScale fm) cur prev-              -- Fit/fixed children keep content height. Only Grow/Percent eat `ch`.-              crossH <- childRowCrossSize na ci ch-              ay <- getAlignY na ci-              fy <--                if ay == AlignBaseline-                  then (\b -> cy + rowBase - b) <$> childBaseline env ci crossH-                  else pure (alignY ay cy ch crossH)-              positionNodeA env (depth + 1) ci x fy fw crossH-              -- A grow child that its max width stopped short of its share-              -- hands the rest to the siblings after it instead of leaving a-              -- hole.-              placedW <- readGeom (seArrays env) ci geomW-              goRow (i + 1) (cur + min fw placedW + gap) x-    goRow 0 cx (-1 / 0)---- | Placed origin of the flow child at raw cursor @cur@ when the previous--- sibling was placed at @prev@ (negative infinity for the first child), on a--- device grid of scale @s@.------ Flex positions stay exact: the cursor accumulates in raw floats and only the--- placed origin snaps, never the running sum. Rounding the cumulative cursor--- re-compounds error every child (1.667 -> 2.0 -> ...) so a shrink row--- overruns its fixed width. The one-pixel floor past @prev@ keeps two--- siblings from quantizing to the same origin while resisting that drift.-{-# INLINE snappedOrigin #-}-snappedOrigin :: Float -> Float -> Float -> Float-snappedOrigin s cur prev-  | s > 0 = max (onGrid s cur) (prev + 1 / s)-  | otherwise = cur--positionGrid ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionGrid env@SolveEnv {seArena = na} depth parent gCols minColW gap cx cy cw ch = do-  n <- loadChildrenScratch (seArena env) parent (flowChildSize env False cw ch)-  when (n > 0) $ do-    let cols = gridColumnCount gCols minColW cw gap-        colW = max 0 ((cw - gap * fromIntegral (cols - 1)) / fromIntegral cols)-        numRows = (n + cols - 1) `quot` cols-    -- Freeze child indices and their measured cross sizes before recursing.-    -- Children reuse the working scratch while this grid iterates rows and-    -- columns, so the live arrays would be clobbered by the first child.-    withGridScratch na depth n $ \idxArr hArr ->-      do-        let goRows !r !curY-              | r >= numRows = pure ()-              | otherwise = do-                  rowH <- gridRowHeight hArr n cols r-                  let goCols !j-                        | j >= cols = pure ()-                        | otherwise = do-                            let k = r * cols + j-                            if k >= n-                              then pure ()-                              else do-                                ci <- readPrimArray idxArr k-                                (minW, minH, maxW, maxH) <- getMinMax na ci-                                (wTag, wVal) <- getWidthSizing na ci-                                (hTag, hVal) <- getHeightSizing na ci-                                (_, _, iw, ih) <- getRect na ci-                                let childW = clamp minW maxW (resolveSize wTag wVal iw colW minW maxW)-                                    childH = clamp minH maxH (resolveSize hTag hVal ih rowH minH maxH)-                                    itemX = cx + fromIntegral j * (colW + gap)-                                ax <- getAlignX na ci-                                ay <- getAlignY na ci-                                let fx = alignX ax itemX colW childW-                                    fy = alignY ay curY rowH childH-                                positionNodeA env (depth + 1) ci fx fy colW rowH-                                goCols (j + 1)-                  goCols 0-                  goRows (r + 1) (curY + rowH + gap)-        goRows 0 cy--positionColumnFromParent ::-  SolveEnv ->-  Int ->-  NodeIdx ->-  Float ->-  Bool ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-positionColumnFromParent env@SolveEnv {seArena = na, seFm = fm} depth parent gap chrome px pw cx cy cw ch = do-  n <- loadChildrenScratch (seArena env) parent (flowChildSize env True cw ch)-  gapSum <- columnGapSumScratch na chrome n gap-  withAxisSnaps na depth n ch gapSum False $ \idxSnap outSnap -> do-    let go !i !cur !prev-          | i >= n = pure ()-          | otherwise = do-              ci <- readPrimArray idxSnap i-              fh <- readPrimArray outSnap i-              let y = snappedOrigin (fmSnapScale fm) cur prev-              nt <- getNodeType na ci-              (fx, nodeW) <--                if chrome && nt == NodeSeparator-                  then pure (px, pw)-                  else (,cw) <$> columnChildX na ci cx cw-              childH <- columnChildHeight na ci fh-              positionNodeA env (depth + 1) ci fx y nodeW childH-              (_, _, _, placedH) <- getRect na ci-              gapAfter <--                if i + 1 >= n-                  then pure 0-                  else do-                    nextCi <- readPrimArray idxSnap (i + 1)-                    pairColumnGap na chrome nextCi gap-              go (i + 1) (cur + placedH + gapAfter) y-    go 0 cy (-1 / 0)---{-# INLINE reverseScratchTriple #-}-reverseScratchTriple ::-  MutablePrimArray RealWorld Int ->-  MutablePrimArray RealWorld Float ->-  MutablePrimArray RealWorld Float ->-  Int ->-  Int ->-  IO ()-reverseScratchTriple idxArr mainArr crossArr lo hi = do-  let go !a !b-        | a >= b = pure ()-        | otherwise = do-            swapPrim idxArr a b-            swapPrim mainArr a b-            swapPrim crossArr a b-            go (a + 1) (b - 1)-  go lo hi--{-# INLINE swapPrim #-}-swapPrim :: (Prim a) => MutablePrimArray RealWorld a -> Int -> Int -> IO ()-swapPrim arr a b = do-  x <- readPrimArray arr a-  y <- readPrimArray arr b-  writePrimArray arr a y-  writePrimArray arr b x-{-# SPECIALIZE swapPrim :: MutablePrimArray RealWorld Int -> Int -> Int -> IO () #-}-{-# SPECIALIZE swapPrim :: MutablePrimArray RealWorld Float -> Int -> Int -> IO () #-}--columnGapSumScratch :: NodeArena -> Bool -> Int -> Float -> IO Float-columnGapSumScratch _ False _ _ = pure 0-columnGapSumScratch _ True n _-  | n <= 1 = pure 0-columnGapSumScratch na True n gap = do-  FlexScratch {fsIdx = idxArr} <- readIORef (naScratch na)-  let go !i !acc-        | i >= n - 1 = pure acc-        | otherwise = do-            b <- readPrimArray idxArr (i + 1)-            g <- pairColumnGap na True b gap-            go (i + 1) (acc + g)-  go 0 0---- | Resolve the main-axis sizes of the first @n@ scratch children.-distributeScratch :: NodeArena -> Int -> Float -> Float -> Bool -> IO ()-distributeScratch na n avail gapSum horizontal = do-  FlexScratch {fsIdx = idxArr, fsW = wArr, fsH = hArr, fsOutW = outW, fsOutH = outH} <- readIORef (naScratch na)-  total <- sumScratchAxis wArr hArr horizontal 0 n 0-  let slack = avail - (total + gapSum)-  if slack > 0.001-    then do-      growTotal <- sumFactors growFactor na idxArr horizontal n-      if growTotal <= 0-        then copyScratchRange wArr hArr outW outH 0 n-        else do-          -- Grow children share the free space by factor, but no child is-          -- squeezed below its content size (a min-content floor, like CSS-          -- flex with min-width:auto): two fillW columns come out equal unless-          -- one column's content needs more, and that one then takes exactly-          -- what it needs while the rest re-share what is left.-          ---          -- Grow factors live in the cross output (0 once a child is not or-          -- no longer growing): withAxisSnaps only consumes the main-axis-          -- array, so it is free scratch here and is restored to real cross-          -- sizes before returning. mainArr keeps the exact content size-          -- throughout; no arithmetic on markers.-          let mainArr = if horizontal then outW else outH-              crossArr = if horizontal then outH else outW-          markGrowFlags na idxArr wArr hArr mainArr crossArr horizontal 0 n-          (free, gfSum) <- settleGrow mainArr crossArr avail gapSum n (n + 1)-          applyGrowShares wArr hArr mainArr crossArr horizontal free gfSum 0 n-    else-      if slack < -0.001-        then do-          shrinkTotal <- sumFactors shrinkFactor na idxArr horizontal n-          if shrinkTotal <= 0-            then copyScratchRange wArr hArr outW outH 0 n-            else applyShrink na idxArr wArr hArr outW outH horizontal (negate slack) shrinkTotal 0 n-        else copyScratchRange wArr hArr outW outH 0 n---- | @out[i] = (w[i], h[i])@ for the range.-copyScratchRange :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Int -> Int -> IO ()-{-# INLINE copyScratchRange #-}-copyScratchRange wArr hArr outW outH !i !end-  | i >= end = pure ()-  | otherwise = do-      w <- readPrimArray wArr i-      h <- readPrimArray hArr i-      writePrimArray outW i w-      writePrimArray outH i h-      copyScratchRange wArr hArr outW outH (i + 1) end--{-# INLINE sumScratchAxis #-}-sumScratchAxis :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Bool -> Int -> Int -> Float -> IO Float-sumScratchAxis wArr hArr horizontal !i !end !acc-  | i >= end = pure acc-  | otherwise = do-      v <- if horizontal then readPrimArray wArr i else readPrimArray hArr i-      sumScratchAxis wArr hArr horizontal (i + 1) end (acc + v)---- | Sizing along the main axis: width when @horizontal@, else height.-{-# INLINE getAxisSizing #-}-getAxisSizing :: NodeArena -> NodeIdx -> Bool -> IO (SizingTag, Float)-getAxisSizing na idx horizontal =-  if horizontal then getWidthSizing na idx else getHeightSizing na idx---- | Sum a sizing-derived flex factor over the first @n@ scratch children.-{-# INLINE sumFactors #-}-sumFactors :: (SizingTag -> Float -> Float) -> NodeArena -> MutablePrimArray RealWorld Int -> Bool -> Int -> IO Float-sumFactors factor na idxArr horizontal n = go 0 0-  where-    go !i !acc-      | i >= n = pure acc-      | otherwise = do-          ci <- readPrimArray idxArr i-          (tag, val) <- getAxisSizing na ci horizontal-          go (i + 1) (acc + factor tag val)--{-# INLINE growFactor #-}-growFactor :: SizingTag -> Float -> Float-growFactor tag val = if tag == SizingGrow then val else 0--{-# INLINE shrinkFactor #-}-shrinkFactor :: SizingTag -> Float -> Float-shrinkFactor tag val =-  case tag of-    SizingShrink -> val-    -- Grow also gives space back when the window is smaller than content.-    SizingGrow -> if val > 0 then val else 1-    -- Percent flexes like CSS: when siblings plus gaps overflow the axis,-    -- percent children give the overflow back so e.g. two 50% columns and a-    -- gap land exactly on the row width. Covers percent on either axis,-    -- should height percent ever be sized that way.-    SizingPercent -> 1-    -- Fit stays content-sized. A pinned header must not squash when a Grow-    -- sibling (page scroll) is taller than the window.-    _ -> 0--markGrowFlags :: NodeArena -> MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Bool -> Int -> Int -> IO ()-markGrowFlags na idxArr wArr hArr mainArr crossArr horizontal !i !end-  | i >= end = pure ()-  | otherwise = do-      ci <- readPrimArray idxArr i-      iw <- readPrimArray wArr i-      ih <- readPrimArray hArr i-      (tag, val) <- getAxisSizing na ci horizontal-      let gf = growFactor tag val-      writePrimArray mainArr i (if horizontal then iw else ih)-      writePrimArray crossArr i (if gf > 0 then gf else 0)-      markGrowFlags na idxArr wArr hArr mainArr crossArr horizontal (i + 1) end---- One sweep: sum content of non-grow + already-locked children (factor 0) and--- grow factors of the still-unlocked.-{-# INLINE scanGrow #-}-scanGrow :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Int -> Int -> Float -> Float -> IO (Float, Float)-scanGrow mainArr crossArr !i !end !occupied !gfSum-  | i >= end = pure (occupied, gfSum)-  | otherwise = do-      gf <- readPrimArray crossArr i-      if gf > 0-        then scanGrow mainArr crossArr (i + 1) end occupied (gfSum + gf)-        else do-          main <- readPrimArray mainArr i-          scanGrow mainArr crossArr (i + 1) end (occupied + main) gfSum---- Pin every grow child whose content exceeds its would-be share by clearing--- its factor; its content stays in mainArr.-lockGrow :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Float -> Float -> Int -> Int -> Int -> IO Int-lockGrow mainArr crossArr !free !gfSum !i !end !acc-  | i >= end = pure acc-  | otherwise = do-      gf <- readPrimArray crossArr i-      if gf > 0-        then do-          need <- readPrimArray mainArr i-          if need * gfSum > gf * free-            then do-              writePrimArray crossArr i 0-              lockGrow mainArr crossArr free gfSum (i + 1) end (acc + 1)-            else lockGrow mainArr crossArr free gfSum (i + 1) end acc-        else lockGrow mainArr crossArr free gfSum (i + 1) end acc---- Each lock shrinks the share pool, possibly locking more children; the--- locked set only grows, so this fixpoints within n sweeps.-settleGrow :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Float -> Float -> Int -> Int -> IO (Float, Float)-settleGrow mainArr crossArr avail gapSum n !passes = do-  (occupied, gfSum) <- scanGrow mainArr crossArr 0 n 0 0-  let free = avail - gapSum - occupied-  locked <- lockGrow mainArr crossArr free gfSum 0 n 0-  if locked == 0 || passes <= 1-    then pure (free, gfSum)-    else settleGrow mainArr crossArr avail gapSum n (passes - 1)---- Hand shares to unlocked grow children and restore real cross sizes where--- the factors clobbered them.-applyGrowShares :: MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Bool -> Float -> Float -> Int -> Int -> IO ()-applyGrowShares wArr hArr mainArr crossArr horizontal !free !gfSum !i !end-  | i >= end = pure ()-  | otherwise = do-      iw <- readPrimArray wArr i-      ih <- readPrimArray hArr i-      gf <- readPrimArray crossArr i-      when (gf > 0) $-        writePrimArray mainArr i (max 0 (free * gf / gfSum))-      writePrimArray crossArr i (if horizontal then ih else iw)-      applyGrowShares wArr hArr mainArr crossArr horizontal free gfSum (i + 1) end--applyShrink :: NodeArena -> MutablePrimArray RealWorld Int -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> MutablePrimArray RealWorld Float -> Bool -> Float -> Float -> Int -> Int -> IO ()-applyShrink na idxArr wArr hArr outW outH horizontal !overflow !shrinkTotal !i !end-  | i >= end = pure ()-  | otherwise = do-      ci <- readPrimArray idxArr i-      iw <- readPrimArray wArr i-      ih <- readPrimArray hArr i-      (minW, minH, _, _) <- getMinMax na ci-      (tag, val) <- getAxisSizing na ci horizontal-      let sf = shrinkFactor tag val-          main = if horizontal then iw else ih-          minMain = if horizontal then minW else minH-          delta = overflow * sf / shrinkTotal-          shrunk = max minMain (main - delta)-      if horizontal-        then writePrimArray outW i shrunk >> writePrimArray outH i ih-        else writePrimArray outW i iw >> writePrimArray outH i shrunk-      applyShrink na idxArr wArr hArr outW outH horizontal overflow shrinkTotal (i + 1) end--alignX :: AlignX -> Float -> Float -> Float -> Float-alignX AlignStart cx _ _ = cx-alignX AlignCenter cx cw iw = cx + (cw - iw) / 2-alignX AlignEnd cx cw iw = cx + cw - iw--alignY :: AlignY -> Float -> Float -> Float -> Float-alignY AlignTop cy _ _ = cy-alignY AlignMiddle cy ch ih = cy + (ch - ih) / 2-alignY AlignBottom cy ch ih = cy + ch - ih--- Only a row has a baseline to share; 'positionRowFromParent' places these.-alignY AlignBaseline cy _ _ = cy---- | Distance from the top of node @ci@, laid out @h@ tall, to its first--- baseline, as in CSS:------ * text: its first line's, where paint puts it ('collectNodeTextSpans'). One---   line is centered in the box, and wrapped lines start at the top. Paint---   wraps at explicit newlines, and outside a row where the line overflows---   'textWrapCap'.--- * a widget with a label (a button, select, checkbox): the label's, which---   paint centers in the widget.--- * a container: the baseline its baseline-aligned children share if it is a---   row that has some, and otherwise its first child's.--- * anything else: its bottom edge.-childBaseline :: SolveEnv -> NodeIdx -> Float -> IO Float-childBaseline env@SolveEnv {seArena = na, seArrays = a, seFm = defaultFm, seResolveFont = resolveFont} ci h = do-  nt <- getNodeType na ci-  si <- getStyleIdx na ci-  case nt of-    NodeText -> do-      raw <- getText na ci-      if T.null raw-        then pure h-        else do-          measurer@TextMeasurer {tmMetrics = fm} <- textNodeMeasurer env ci-          rowChild <- parentIsRow na ci-          wrapped <--            if T.any (== '\n') raw-              then pure True-              else-                if rowChild-                  then pure False-                  else do-                    (_, _, maxW, _) <- getMinMax na ci-                    (wTag, _) <- getWidthSizing na ci-                    (_, _, w, _) <- getRect na ci-                    effMaxW <- if maxW < 1e8 then pure maxW else findAncestorMaxW na ci-                    let cap = textWrapCap effMaxW wTag w-                    (tw, _) <- measureFontLine measurer raw-                    pure (cap < 1e8 && cap + 0.5 < tw)-          pure (textBaseline fm (if wrapped then fmLineHeight fm else h))-    _-      | hasCenteredLabel nt && not (nt == NodeButton && isCloseButtonStyle si) -> do-          -- Widget labels take the node's font size in the default face-          -- ('resolveFontFor').-          size <- getNodeFontSize na ci-          let weight = textNodeFontWeight 0-              style = textNodeFontStyle 0-              variant = textNodeFontVariant 0-          fm <--            if isDefaultNodeFont size weight style variant-              then pure defaultFm-              else fst <$> resolveFont size weight style variant-          pure (textBaseline fm h)-      | isContainerNode nt -> do-          -- Children are linked last first, so consing them up as they are-          -- visited leaves the list in child order.-          kids <- foldFlowChildrenM na ci (\acc k -> pure (k : acc)) []-          case kids of-            [] -> pure h-            first : _ -> do-              (pad, _, dir) <- containerFlow a ci-              let innerH = max 0 (h - padT pad - padB pad)-                  heightOf k = (\(_, _, _, kh) -> kh) <$> getRect na k-              grouped <--                if dir /= DirRow-                  then pure []-                  else-                    fmap concat . forM kids $ \k -> do-                      ay <- getAlignY na k-                      if ay /= AlignBaseline then pure [] else (: []) <$> (heightOf k >>= childBaseline env k)-              (padT pad +) <$> case grouped of-                _ : _ -> pure (maximum grouped)-                [] -> do-                  fh <- heightOf first-                  ay <- if dir == DirRow then getAlignY na first else pure AlignTop-                  (alignY ay 0 innerH fh +) <$> childBaseline env first fh-      | otherwise -> pure h-  where-    textBaseline fm boxH = centeredTextY fm 0 boxH (fmLineHeight fm) + fmAscent fm--placeModals :: NodeArena -> Measurers -> Float -> Float -> IO ()-placeModals na ms winW winH = do-  env <- solveEnv na ms-  let margin = windowMargin-  forNodes_ na $ \idx -> do-    nt <- getNodeType na idx-    when (nt == NodeModal) $ do-      (_, _, iw, ih) <- getRect na idx-      let maxW = max 0 (winW - 2 * margin)-          maxH = max 0 (winH - 2 * margin)-          w = min iw maxW-          h = min ih maxH-          x = max 0 ((winW - w) / 2)-          y = max 0 ((winH - h) / 2)-      positionNodeA env 0 idx x y w h--placeWindows ::-  NodeArena ->-  Measurers ->-  Float ->-  Float ->-  (WidgetId -> IO (Maybe (Float, Float))) ->-  (WidgetId -> IO (Maybe (Float, Float))) ->-  IO ()-placeWindows na ms winW winH lookupPos lookupSize = do-  let margin = windowMargin-  forNodes_ na $ \idx -> do-    nt <- getNodeType na idx-    when (nt == NodeWindow) $ do-      wid <- getWidgetId na idx-      (_, _, iw, ih) <- getRect na idx-      (w0, h0) <- fromMaybe (min iw winW, min ih winH) <$> lookupSize wid-      mpos <- lookupPos wid-      placeWindowNode na ms winW winH idx w0 h0 $ \w -> fromMaybe (winW - w - margin, margin) mpos---- | Lay out window @idx@ at size @w0 h0@, clamped to its min and max size and--- the screen, with its origin, given that size, clamped on screen. Fit sizing--- caps at intrinsic size; floating windows use an explicit frame size.-placeWindowNode :: NodeArena -> Measurers -> Float -> Float -> NodeIdx -> Float -> Float -> (Float -> (Float, Float)) -> IO ()-placeWindowNode na ms winW winH idx w0 h0 originFor = do-  (minW, minH, maxW, maxH) <- getMinMax na idx-  let w = clamp minW (min maxW winW) w0-      h = clamp minH (min maxH winH) h0-      (x0, y0) = originFor w-      x = clamp 0 (max 0 (winW - w)) x0-      y = clamp 0 (max 0 (winH - h)) y0-  setRect na idx x y w h-  env <- solveEnv na ms-  (pad, gap, dir) <- containerFlow (seArrays env) idx-  positionChildren env 0 idx dir gap pad x y w h---- | Horizontal placement for a widget-anchored popup. Aligns the popup's left--- edge with the anchor even when the anchor sits inside the window margin (a--- menu bar flush to the left, say); the margin is only there to keep the popup--- clear of the right edge.-clampPopupX :: Float -> Float -> Float -> Float -> Float-clampPopupX margin winW iw x0-  | x0 < margin && x0 + iw <= winW = max 0 x0-  | otherwise = max margin (min (winW - iw - margin) x0)--computePopupPosition ::-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  PopupAnchor ->-  PopupPlacement ->-  Float ->-  (Float, Float)-computePopupPosition winW winH margin iw ih anchor placement offset =-  case anchor of-    AnchorPoint (V2 px py) ->-      let x0 = case placement of-            PlacementLeft -> px - iw - offset-            PlacementRight -> px + offset-            _ -> px-          y0 = case placement of-            PlacementAbove -> py - ih - offset-            PlacementBelow -> py + offset-            _ -> py-          x = if x0 + iw > winW - margin && px - iw - margin >= 0-                then px - iw - offset-                else max margin (min (winW - iw - margin) x0)-          y = if y0 + ih > winH - margin && py - ih - margin >= 0-                then py - ih - offset-                else clampY y0-       in (x, y)-    AnchorRect (Rect rx ry rw rh) ->-      case placement of-        PlacementBelow ->-          let x0 = rx-              y0 = ry + rh + offset-              y = if y0 + ih > winH - margin && ry - ih - offset >= margin-                    then ry - ih - offset-                    else y0-              x = clampPopupX margin winW iw x0-           in (x, clampY y)-        PlacementAbove ->-          let x0 = rx-              y0 = ry - ih - offset-              y = if y0 < margin && ry + rh + offset + ih <= winH - margin-                    then ry + rh + offset-                    else y0-              x = clampPopupX margin winW iw x0-           in (x, clampY y)-        PlacementRight ->-          let x0 = rx + rw + offset-              y0 = ry-              x = if x0 + iw > winW - margin && rx - iw - offset >= margin-                    then rx - iw - offset-                    else x0-              y = clampY y0-           in (clampPopupX margin winW iw x, y)-        PlacementLeft ->-          let x0 = rx - iw - offset-              y0 = ry-              x = if x0 < margin && rx + rw + offset + iw <= winW - margin-                    then rx + rw + offset-                    else x0-              y = clampY y0-           in (clampPopupX margin winW iw x, y)-        PlacementAuto ->-          let spaceBelow = winH - margin - (ry + rh + offset)-              spaceAbove = ry - offset - margin-              y = if spaceBelow >= ih || spaceBelow >= spaceAbove-                    then ry + rh + offset-                    else ry - ih - offset-              x = clampPopupX margin winW iw rx-           in (x, clampY y)-        PlacementAtCursor ->-          (clampPopupX margin winW iw rx, clampY (ry + rh + offset))-  where-    -- Keep the popup's top edge within the window margins.-    clampY y = max margin (min (winH - ih - margin) y)--placePopups ::-  NodeArena ->-  Measurers ->-  Float ->-  Float ->-  (WidgetId -> IO (Maybe (PopupAnchor, PopupPlacement, Float))) ->-  IO ()-placePopups na ms winW winH lookupAnchor = do-  env <- solveEnv na ms-  let margin = windowMargin-  forNodes_ na $ \idx -> do-    nt <- getNodeType na idx-    when (nt == NodePopup) $ do-      wid <- getWidgetId na idx-      (_, _, iw, ih) <- getRect na idx-      mcfg <- lookupAnchor wid-      let (anchor, placement, offset) = case mcfg of-            Just (a, p, o) -> (a, p, o)-            Nothing -> (AnchorPoint (V2 0 0), PlacementAuto, 4)-          (x, y) = computePopupPosition winW winH margin iw ih anchor placement offset-      positionNodeA env 0 idx x y iw ih
lib/NanoUI/Monad.hs view
@@ -1,386 +1,112 @@-{-# LANGUAGE DataKinds #-}-{-# LANGUAGE TypeFamilies #-}---- | The 'Ui' effect and the 'NanoUI' view type: running a view, widget id--- scopes and keys, theme scopes, and damage requests from inside a view.+-- | The 'NanoUI' monad: widget id scopes and keys, frame input and time,+-- theme scopes, focus, clipboard, scrolling, and damage requests from inside+-- a view. "NanoUI" re-exports the most common operations; this module exports+-- the rest. Running a view against a context is in "NanoUI.Backend", and+-- mixing views with other @effectful@ effects in "NanoUI.Effectful". module NanoUI.Monad-  ( NanoUI-  , Ui-  , runNanoUI-  , runUi-  , uiIO-  , emit+  ( -- * Views+    NanoUI+  , liftIO+  , withUiResource+  , catchView++    -- | The functions of "NanoUI" that take a 'Context' (scrolling, themes)+    -- take the view's from 'askContext'.+  , Context+  , askContext++    -- * Widget ids   , withKey-  , keyed   , keyedTag   , scope-  , withIdFrame   , nextId-  , burstNextIds   , currentId-  , askContext++    -- * Input and time   , askInput+  , askFrameInput+  , localInput+  , uiMousePos+  , mousePressed+  , mouseReleased+  , mouseHeld+  , uiTime+  , windowSize+  , windowWidth+  , windowHeight+  , lastRect+  , takeEscape++    -- * Layout, fonts and themes   , askDefaultLayout   , withDefaultLayout-  , askHost   , uiFontMetrics-  , uiTime+  , uiFontSize+  , resolveFontUi+  , lineWidthUi+  , truncateTextUi+  , truncateTextWithUi   , uiTheme-  , setUiTheme+  , setTheme+  , followSystemTheme   , styled   , themed   , disabledWhen-  , uiMousePos-  , windowSize-  , windowWidth-  , windowHeight+  , systemAppearance++    -- * Focus and clipboard+  , holdFocus+  , releaseFocus+  , focusedWidget+  , requestFocus+  , focusNext+  , focusPrevious+  , clearFocus+  , isFocused+  , getClipboard+  , setClipboard++    -- * Host++    -- | A 'Host' is a typed slot that holds one value or none, for the UI+    -- thread: 'setHost' installs the value and 'askHost' reads it in a view.+  , Host+  , newHost+  , setHost+  , askHost++    -- * Scrolling+  , getScrollTuning+  , setScrollTuning+  , getScrollMetrics+  , setScrollOffset+  , scrollTo+  , scrollBy+  , scrollPages+  , scrollToStart+  , scrollToEnd+  , scrollIntoView+  , scrollRectIntoView+  , setScrollStep++    -- * Redraw and damage+  , requestFrame+  , DamageBounds (..)   , damageWidgetNow   , damageKeyNow   , damageRectNow   , damageGroupNow   , damageFullNow-  , FrameMsg (..)-  , decodeMessages-  , reduceMessages-  , reduceUpdates++    -- * Monadic helpers   , whenM   , unlessM   , ifM+  , (<&&>)   ) where --import Control.Exception (bracket)-import Control.Monad (unless, when)-import Data.Bits (shiftL, (.&.), (.|.))-import Data.Hashable (Hashable, hash)-import Data.IORef (modifyIORef', readIORef, writeIORef)-import Data.Typeable (Typeable)-import Data.Word (Word64)-import Effectful-  ( Dispatch (Static)-  , DispatchOf-  , Eff-  , Effect-  , IOE-  , runEff-  , type (:>)-  )-import Effectful.Dispatch.Static-  ( SideEffects (WithSideEffects)-  , StaticRep-  , evalStaticRep-  , getStaticRep-  , localStaticRep-  , unEff-  , unsafeEff-  , unsafeEff_-  )-import GHC.Clock (getMonotonicTime)-import NanoUI.Context-  ( Context (..)-  , FrameMsg (..)-  , askHostIO-  , damageFull-  , damageKey-  , damagePeers-  , damageRect-  , damageWidget-  , decodeMessages-  , currentTheme-  , pushMessage-  , pushThemeScope-  , scopeRawTheme-  , setTheme-  , reduceMessages-  , reduceUpdates-  )-import NanoUI.Font (FontMetrics)-import NanoUI.Id-  ( IdContext (siblingId)-  , WidgetId-  , enterKeyed-  , enterScope-  , idContextWidgetId-  , scopeTag-  )-import NanoUI.Layout.Arena (getArenaScope, setArenaScope)-import NanoUI.Style (Layout, Theme, disabledTheme)-import NanoUI.Input (Input (..), inputMousePos, inputWindowSize, stripInteractionInput)-import NanoUI.Types (DamageBounds, Rect, Size (..), V2)--type NanoUI = Eff '[Ui, IOE]--data Ui :: Effect--type instance DispatchOf Ui = Static WithSideEffects--data instance StaticRep Ui = UiRep !Context !Input !Layout--{-# INLINE runUi #-}-runUi :: IOE :> es => Context -> Input -> Eff (Ui : es) a -> Eff es a-runUi ctx inp ui = do-  lay <- unsafeEff_ (readIORef (ctxDefaultLayout ctx))-  evalStaticRep (UiRep ctx inp lay) ui--{-# INLINE runNanoUI #-}-runNanoUI :: Context -> Input -> NanoUI a -> IO a-runNanoUI ctx inp = runEff . runUi ctx inp--{-# INLINE uiIO #-}-uiIO :: Ui :> es => IO a -> Eff es a-uiIO m = do-  UiRep {} <- getStaticRep-  unsafeEff_ m--{-# INLINE emit #-}-emit :: (Typeable msg, Ui :> es) => msg -> Eff es ()-emit msg = do-  ctx <- askContext-  uiIO (pushMessage ctx (FrameMsg msg))---- | The id 'nextId' would issue, without consuming it.-{-# INLINE currentId #-}-currentId :: Ui :> es => Eff es WidgetId-currentId = do-  ctx <- askContext-  ic <- uiIO (readIORef (ctxIdContext ctx))-  pure (idContextWidgetId ic)--{-# INLINE nextId #-}-nextId :: Ui :> es => Eff es WidgetId-nextId = do-  ctx <- askContext-  uiIO $ do-    ic <- readIORef (ctxIdContext ctx)-    writeIORef (ctxIdContext ctx) $! ic {siblingId = siblingId ic + 1}-    pure (idContextWidgetId ic)---- | Issue many widget ids in one IO loop (avoids deep Eff bind chains).-{-# INLINE burstNextIds #-}-burstNextIds :: Ui :> es => Int -> Eff es ()-burstNextIds n-  | n <= 0 = pure ()-  | otherwise = do-      ctx <- askContext-      uiIO $ modifyIORef' (ctxIdContext ctx) $ \ic ->-        let !sid = siblingId ic + fromIntegral n-         in ic {siblingId = sid}---- Run @m@ in the child context from @enter@, then restore the advanced parent--- (also on exceptions).-{-# INLINE withIdFrame #-}-withIdFrame ::-  Ui :> es => (IdContext -> (IdContext, IdContext)) -> Eff es a -> Eff es a-withIdFrame enter m = do-  ctx <- askContext-  unsafeEff $ \es ->-    bracket-      (do-        old <- readIORef (ctxIdContext ctx)-        let !(!p, !c) = enter old-        writeIORef (ctxIdContext ctx) c-        pure p)-      (\parent' -> writeIORef (ctxIdContext ctx) parent')-      (\_ -> unEff m es)--{-# INLINE scope #-}-scope :: Ui :> es => Eff es a -> Eff es a-scope = withIdFrame (enterScope scopeTag)--{-# INLINE keyed #-}---- | Stable child path from @tag@. Keys must be unique among siblings in the same scope.-keyed :: (Hashable k, Ui :> es) => k -> Eff es a -> Eff es a-keyed k = keyedTag (fromIntegral (hash k))--{-# INLINE keyedTag #-}-keyedTag :: Ui :> es => Word64 -> Eff es a -> Eff es a-keyedTag tag = withIdFrame (enterKeyed tag)--{-# INLINE withKey #-}-withKey :: (Hashable k, Ui :> es) => k -> Eff es a -> Eff es a-withKey = keyed--{-# INLINE askContext #-}-askContext :: Ui :> es => Eff es Context-askContext = do-  UiRep ctx _ _ <- getStaticRep-  pure ctx--{-# INLINE askDefaultLayout #-}-askDefaultLayout :: Ui :> es => Eff es Layout-askDefaultLayout = do-  UiRep _ _ l <- getStaticRep-  pure l--{-# INLINE withDefaultLayout #-}-withDefaultLayout :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a-withDefaultLayout f = localStaticRep (\(UiRep ctx inp l) -> UiRep ctx inp (f l))--{-# INLINE uiFontMetrics #-}-uiFontMetrics :: Ui :> es => Eff es FontMetrics-uiFontMetrics = fmap ctxFontMetrics askContext--{-# INLINE uiTime #-}--- | Monotonic seconds since some fixed epoch (process boot), as a 'Double'.--- Use it for time-based animation math inside the UI effect. It stays in--- 'Double' on purpose: converting wall-clock seconds to 'Float' loses ~3 ms--- of resolution at 8 h uptime (worse longer), which is coarser than a frame--- and quantizes animation sweeps into visible steps.-uiTime :: Ui :> es => Eff es Double-uiTime = uiIO getMonotonicTime---- | The theme the view is drawn with where this is called: the context theme--- as modified by the enclosing 'styled' and 'disabledWhen' scopes.-{-# INLINE uiTheme #-}-uiTheme :: Ui :> es => Eff es Theme-uiTheme = do-  ctx <- askContext-  uiIO (currentTheme ctx)---- | Draw a part of the view with a modified theme. Widgets declared inside--- take their colours, borders and corner radii from it, and 'styled' scopes--- nest, each modifying the theme of the scope around it:------ > styled (buttonStyle (cornerRadius 8)) $ do--- >   styled primary (button "Save")--- >   button "Cancel"------ The modifier runs once per scope per frame. The theme only affects how--- widgets look, never their layout.-{-# INLINE styled #-}-styled :: Ui :> es => (Theme -> Theme) -> Eff es a -> Eff es a-styled f = withPaintScope $ \ctx outer -> do-  raw <- f <$> scopeRawTheme ctx outer-  let !disabled = outer .&. 1-  ti <- pushThemeScope ctx (disabled /= 0) raw (if disabled /= 0 then disabledTheme raw else raw)-  pure ((ti `shiftL` 1) .|. disabled)---- | Draw a part of the view with another theme, whatever the theme around it.-{-# INLINE themed #-}-themed :: Ui :> es => Theme -> Eff es a -> Eff es a-themed theme = styled (const theme)---- | Disable every widget declared inside when the condition holds. Disabled--- widgets keep their place, state and layout, but take no pointer or--- keyboard input, cannot be focused, and are drawn with 'disabledTheme'.------ > disabledWhen (T.null name) $ whenM (button "Save") save-{-# INLINE disabledWhen #-}-disabledWhen :: Ui :> es => Bool -> Eff es a -> Eff es a-disabledWhen False m = m-disabledWhen True m =-  -- The view inside sees no presses, keys or wheel, so no widget's own input-  -- handling can fire; the frame's focus and click passes check the scope.-  localStaticRep-    (\(UiRep ctx inp l) -> UiRep ctx (stripInteractionInput inp) {inputMouseDown = False, inputMouseRightDown = False} l)-    (withPaintScope enter m)-  where-    enter ctx outer-      | outer .&. 1 /= 0 = pure outer-      | otherwise = do-          raw <- scopeRawTheme ctx outer-          ti <- pushThemeScope ctx True raw (disabledTheme raw)-          pure ((ti `shiftL` 1) .|. 1)---- Run @m@ with the arena scope @enter@ picks, then restore the scope around it--- (also on exceptions).-{-# INLINE withPaintScope #-}-withPaintScope :: Ui :> es => (Context -> Int -> IO Int) -> Eff es a -> Eff es a-withPaintScope enter m = do-  ctx <- askContext-  let na = ctxNodeArena ctx-  unsafeEff $ \es ->-    bracket-      (do-        old <- getArenaScope na-        setArenaScope na =<< enter ctx old-        pure old)-      (setArenaScope na)-      (\_ -> unEff m es)--{-# INLINE setUiTheme #-}-setUiTheme :: Ui :> es => Theme -> Eff es ()-setUiTheme th = do-  ctx <- askContext-  uiIO (setTheme ctx th)--{-# INLINE uiMousePos #-}-uiMousePos :: Ui :> es => Eff es V2-uiMousePos = fmap inputMousePos askInput--{-# INLINE askInput #-}-askInput :: Ui :> es => Eff es Input-askInput = do-  UiRep _ inp _ <- getStaticRep-  pure inp--{-# INLINE windowSize #-}-windowSize :: Ui :> es => Eff es Size-windowSize = fmap inputWindowSize askInput--{-# INLINE windowWidth #-}-windowWidth :: Ui :> es => Eff es Float-windowWidth = fmap (sizeW . inputWindowSize) askInput--{-# INLINE windowHeight #-}-windowHeight :: Ui :> es => Eff es Float-windowHeight = fmap (sizeH . inputWindowSize) askInput--{-# INLINE askHost #-}-askHost :: (Typeable a, Ui :> es) => Eff es (Maybe a)-askHost = do-  ctx <- askContext-  uiIO (askHostIO ctx)--{-# INLINE damageWidgetNow #-}-damageWidgetNow :: (Ui :> es) => WidgetId -> DamageBounds -> Eff es ()-damageWidgetNow wid bounds = do-  ctx <- askContext-  uiIO (damageWidget ctx wid bounds)--{-# INLINE damageKeyNow #-}-damageKeyNow :: (Ui :> es) => Int -> DamageBounds -> Eff es ()-damageKeyNow k bounds = do-  ctx <- askContext-  uiIO (damageKey ctx k bounds)--{-# INLINE damageRectNow #-}-damageRectNow :: (Ui :> es) => Rect -> Eff es ()-damageRectNow r = do-  ctx <- askContext-  uiIO (damageRect ctx r)--{-# INLINE damageGroupNow #-}-damageGroupNow :: (Ui :> es) => [WidgetId] -> DamageBounds -> Eff es ()-damageGroupNow wids bounds = do-  ctx <- askContext-  uiIO (damagePeers ctx wids bounds)--{-# INLINE damageFullNow #-}-damageFullNow :: (Ui :> es) => Eff es ()-damageFullNow = do-  ctx <- askContext-  uiIO (damageFull ctx)---- | Monadic variant of 'when'. Runs the second action if the first returns 'True'.------ Example:------ @--- whenM (button "Save") saveDocument--- @-{-# INLINE whenM #-}-whenM :: Monad m => m Bool -> m () -> m ()-whenM mb ma = mb >>= \b -> when b ma---- | Monadic variant of 'unless'. Runs the second action if the first returns 'False'.-{-# INLINE unlessM #-}-unlessM :: Monad m => m Bool -> m () -> m ()-unlessM mb ma = mb >>= \b -> unless b ma---- | Monadic conditional selection.-{-# INLINE ifM #-}-ifM :: Monad m => m Bool -> m a -> m a -> m a-ifM mb t f = mb >>= \b -> if b then t else f+import NanoUI.Internal.Context (Context)+import NanoUI.Internal.Monad+import NanoUI.Internal.Host (Host, newHost, setHost)+import NanoUI.Internal.Types (DamageBounds (..))
+ lib/NanoUI/Path.hs view
@@ -0,0 +1,81 @@+-- | Paths, transforms and paints for canvas drawing. Import qualified:+--+-- > import NanoUI.Path qualified as P+-- >+-- > sketch :: Rect -> CanvasM ()+-- > sketch (Rect x y w h) = do+-- >   let c = V2 (x + w / 2) (y + h / 2)+-- >       slice a0 sweep col = drawPath (P.moveTo c <> P.arc c 40 a0 sweep <> P.close) col+-- >   slice 0 (pi / 2) (colorRGBA 220 80 60 255)+-- >   slice (pi / 2) (3 * pi / 2) (colorRGBA 60 120 220 255)+-- >   -- A ring: the inner circle is a hole in the outer one.+-- >   drawPathWith P.EvenOdd (P.circle c 30 <> P.circle c 20) (P.Solid (colorRGBA 30 30 30 255))+-- >   withTransform (P.rotateAround c (pi / 8)) $+-- >     drawStrokePathWith (P.stroke 2) {P.strokeJoin = P.RoundJoin, P.strokeDash = [6, 3]}+-- >       (P.rect (Rect (x + 10) (y + 10) 40 40))+-- >       (P.Linear (V2 x y) (V2 (x + 60) y) [(0, colorRGBA 30 30 30 255), (1, colorRGBA 60 120 220 255)])+--+-- A 'Path' is a sequence of steps joined with '<>'. 'moveTo' starts a+-- subpath; 'lineTo', 'quadTo', 'cubicTo', 'arc' and 'arcTo' extend it from+-- the current point; 'close' draws a line back to its start. A step with no+-- open subpath starts one where the last subpath closed, or at the origin.+-- Shapes ('rect', 'roundedRect', 'circle', 'ellipse', 'polygon', 'polyline')+-- are separate subpaths and never join onto what precedes them.+--+-- Angles are in radians. Since y points down, positive angles turn clockwise+-- on screen.+--+-- 'NanoUI.Widgets.Custom.drawPath' and 'NanoUI.Widgets.Custom.drawPathWith'+-- fill a path; 'NanoUI.Widgets.Custom.drawStrokePath' and+-- 'NanoUI.Widgets.Custom.drawStrokePathWith' stroke it. Curves are flattened+-- to within a quarter of a device pixel.+--+-- A fill closes every subpath and fills the inside given by its 'FillRule'.+-- A nested subpath is a hole when the rule leaves it unfilled: with+-- 'EvenOdd', or with 'NonZero' when the two subpaths wind in opposite+-- directions. Intersections are not resolved: crossing subpaths fill+-- independently, as may a subpath that touches the one around it along an+-- edge or at a corner, and a self-intersecting one (a pentagram in one line)+-- may fill only partly.+--+-- A stroke is centred on its path; 'Stroke' sets its width, caps, joins and+-- dashes.+module NanoUI.Path+  ( -- * Paths+    Path+  , moveTo+  , lineTo+  , quadTo+  , cubicTo+  , arc+  , ellipticalArc+  , arcTo+  , close+    -- * Shapes+  , rect+  , roundedRect+  , roundedRectCorners+  , circle+  , ellipse+  , polygon+  , polyline+    -- * Strokes+  , Stroke (strokeWidth, strokeCap, strokeJoin, strokeMiterLimit, strokeDash, strokeDashOffset)+  , stroke+  , LineCap (..)+  , LineJoin (..)+    -- * Fills and paints+  , FillRule (..)+  , Paint (..)+    -- * Transforms+  , Transform+  , translate+  , rotate+  , rotateAround+  , scale+  , affine+  , transformPoint+  , invert+  ) where++import NanoUI.Internal.Path
lib/NanoUI/Runner.hs view
@@ -8,49 +8,50 @@   , tryWithDrawingLock     -- * Redraw Decision   , shouldRedrawFrame+  , ClickTracker+  , newClickTracker+  , stampClicks+  , maxFrameDt+  , wakeTimeoutMs+  , shorterWait+  , windowTimeoutMs+  , takeDueWake+    -- * Frame pacing+  , pacingMsFor+  , waitUntil     -- * Session loop   , SessionDriver (..)+  , LoopWindows (..)+  , DebugSamplerRef+  , newDebugSampler   , runSessionLoop   ) where -import Control.Concurrent (threadDelay)+import Control.Concurrent (myThreadId, threadDelay) import Control.Exception (finally, mask)-import Control.Monad (when)+import Control.Monad (forM_, unless, when)+import Data.Maybe (isJust)+import Data.Text qualified as T+import Numeric (showFFloat)+import System.Environment (lookupEnv)+import System.IO (BufferMode (LineBuffering), hFlush, hPutStrLn, hSetBuffering, stderr) import Data.IORef   ( IORef   , atomicModifyIORef'+  , atomicWriteIORef   , newIORef   , readIORef   , writeIORef   ) import GHC.Clock (getMonotonicTime)-import NanoUI.Context-  ( Context-  , anyAnimating-  , isDirty-  , overlayConsumesQuit-  , textInputEditActive-  )-import NanoUI.Debug-  ( DebugSamplerRef-  , debugRefreshDue-  , debugRefreshSec-  , isDebugActive-  , noteDebugLoop-  , noteDebugSkip-  )-import NanoUI.Frame.Redraw (needsRedraw, textFieldActive)-import NanoUI.Input-  ( Input (..)-  , clearEphemeral-  , inputDeltaTime-  , inputMouseClicks-  , inputMousePos-  , inputMousePressed-  , isHardQuitInput-  , splitFrame-  )-import NanoUI.Types (V2 (..))+import NanoUI.Internal.Context+import NanoUI.Internal.Debug+import NanoUI.Internal.Frame.Input (needsRedraw)+import NanoUI.Internal.Input+import NanoUI.Internal.NativeWindow (closeWindowSlot, quitRequested, requestWindowClose)+import NanoUI.Internal.Tasks (cancelTasksOf)+import NanoUI.Internal.Widgets.Shortcut (hardQuitUsed)+import NanoUI.Internal.Types (V2 (..))  -- | Standard upper bound for single-frame delta-time (50ms). maxFrameDt :: Float@@ -60,50 +61,63 @@ -- When pacing is active the backend requests a wait of ~period, but a one-shot -- sleep lets frame starts drift by the scheduler's timer granularity (and land -- late whenever the event waiter overruns), which reads as choppy animation on--- uneven frame times. Sleep the bulk, then busy-wind the ≤1ms tail so frame+-- uneven frame times. 'waitUntil' sleeps the bulk and spins the tail, so frame -- starts fall on uniform slices of the pacing period. The spin only runs when -- an animation is actively presenting without vsync, and is bounded to about a -- millisecond.+--+-- The grid starts at @lastT@, when the loop took the previous pass's events.+-- SDL aligns in its own 'sdPacedWait' instead, from when its pass began and+-- by the refresh period of the display the window is on now, which a fixed+-- 'sdAlignSec' cannot follow. alignFrameStart :: Double -> Double -> IO ()-alignFrameStart periodSec lastT = do+alignFrameStart periodSec lastT = waitUntil (lastT + periodSec)++-- | Wait until a 'getMonotonicTime' time: sleep for most of it, then spin+-- the last quarter millisecond, which a sleep overshoots. Returns at once for+-- a time already past.+waitUntil :: Double -> IO ()+waitUntil target = do   t0 <- getMonotonicTime-  let target = lastT + periodSec-      remain = target - t0-      bulkUs = max 0 (round ((remain - tailSlack) * 1e6))+  let bulkUs = round ((target - t0 - tailSlack) * 1e6) :: Int   when (bulkUs > 0) (threadDelay bulkUs)-  fullSpin target+  spin   where     tailSlack = 2.5e-4-    fullSpin target = do+    spin = do       now <- getMonotonicTime-      when (now < target) (fullSpin target)+      when (now < target) spin --- | State for multi-click detection (double/triple click).-data ClickTrack = ClickTrack-  { ctTime :: !Double-  , ctPos :: !V2-  , ctCount :: !Int-  }+-- | The event wait, in milliseconds, between the frames of an animation+-- whose presents do not wait for the display, for a refresh period in+-- seconds: 2 ms short of the period, at least 1. An event wait can overrun+-- by about a millisecond, and a wait that returns past the frame boundary+-- makes the frame late; the loop spins the rest of the way to the boundary+-- ('waitUntil').+pacingMsFor :: Double -> Int+pacingMsFor period = max 1 (floor (period * 1000) - 2) --- | Stamp multi-click counts into an 'Input' record: presses within 5 pixels--- and 0.4 seconds of the previous one count up to a triple click.-stampClicks :: IORef ClickTrack -> Input -> IO Input+-- | The previous press's time, position, buttons and click count.+type ClickTracker = IORef (Double, V2, MouseButtons, Int)++-- | Allocate an empty multi-click state tracker for 'stampClicks'.+newClickTracker :: IO ClickTracker+newClickTracker = newIORef (0, V2 (-999) (-999), noButtons, 0)++-- | Stamp multi-click counts into an 'Input'. A press of the same buttons+-- within 5 pixels and 0.4 seconds of the previous press counts up, to a+-- triple click at most.+stampClicks :: ClickTracker -> Input -> IO Input stampClicks ref inp-  | not (inputMousePressed inp) = pure inp+  | not (anyButtonPressed inp) = pure inp   | otherwise = do       now <- getMonotonicTime-      prev <- readIORef ref-      let t = ctTime prev-          n = ctCount prev-          V2 x y = inputMousePos inp-          V2 px py = ctPos prev-          dx = x - px-          dy = y - py-          distSq = dx * dx + dy * dy-          close = distSq <= 25-          quick = (now - t) <= 0.4-          n' = if close && quick then min 3 (n + 1) else 1-      writeIORef ref ClickTrack {ctTime = now, ctPos = inputMousePos inp, ctCount = n'}+      (t, V2 px py, prevButtons, n) <- readIORef ref+      let pos@(V2 x y) = inputMousePos inp+          buttons = inputButtonsPressed inp+          close = (x - px) * (x - px) + (y - py) * (y - py) <= 25+          !n' = if close && buttons == prevButtons && now - t <= 0.4 then min 3 (n + 1) else 1+      writeIORef ref (now, pos, buttons, n')       pure (inp {inputMouseClicks = n'})  -- | Concurrency lock for drawing vs async callbacks (e.g. resize watchers).@@ -116,9 +130,9 @@ -- | Attempt to execute an action under the drawing lock without blocking. tryWithDrawingLock :: DrawingLock -> IO a -> IO (Maybe a) tryWithDrawingLock (DrawingLock ref) act = mask $ \restore -> do-  ok <- atomicModifyIORef' ref $ \busy -> if busy then (True, False) else (True, True)+  ok <- atomicModifyIORef' ref $ \busy -> (True, not busy)   if ok-    then Just <$> (restore act `finally` writeIORef ref False)+    then Just <$> (restore act `finally` atomicWriteIORef ref False)     else pure Nothing  -- | Centralized decision predicate: should the host backend redraw this frame?@@ -128,23 +142,28 @@   Input ->       -- ^ Current input   Bool ->        -- ^ Was animating on previous frame?   Bool ->        -- ^ Continuous redraw requested?-  Bool ->        -- ^ Debug live refresh requested?+  Bool ->        -- ^ A frame is due without input: a timed wake or a debug readout refresh?   IO Bool-shouldRedrawFrame ctx prevInp curInp wasAnim continuous wantDebug = do-  if continuous || wantDebug+shouldRedrawFrame ctx prevInp curInp wasAnim continuous refreshDue = do+  if continuous || refreshDue     then pure True     else do-      -- 'needsRedraw' already covers a dirty context, running animations and-      -- an active text field, so an animation that just ended is the only-      -- animation case left: it needs one final frame.+      -- 'needsRedraw' already covers a dirty context and running animations,+      -- so an animation that just ended is the only animation case left: it+      -- needs one final frame.       need <- needsRedraw ctx prevInp curInp-      let pointerEdge =-            inputMousePressed curInp-              || inputMouseReleased curInp-              || inputMouseRightPressed curInp-              || inputMouseRightReleased curInp+      -- A 'NanoUI.Internal.Context.wakeFromThread' not yet taken by a frame:+      -- a background job has published something the view reads. The frame+      -- takes it ('takeThreadWake'), so only peek here.+      woken <- readIORef (ctxWoken ctx)+      let pointerEdge = anyButtonPressed curInp || anyButtonReleased curInp           scrollEdge = inputScroll curInp /= V2 0 0-      pure (need || wasAnim || pointerEdge || scrollEdge)+          -- Two auto-repeats of a held key, or one character typed twice,+          -- arrive as equal inputs, which 'needsRedraw' cannot tell apart.+          keyEdge =+            not (inputKeysNull (inputKeys curInp) && inputKeysNull (inputKeysReleased curInp))+              || not (T.null (inputChars curInp) && null (inputDrops curInp))+      pure (need || woken || wasAnim || pointerEdge || scrollEdge || keyEdge)  -- | What a backend provides to 'runSessionLoop'. data SessionDriver ev = SessionDriver@@ -152,24 +171,40 @@     -- ^ Non-blocking poll for pending backend events.   , sdWaitEvents    :: Int -> IO [ev]     -- ^ Wait for events with a timeout in milliseconds (-1 indicates blocking wait).+  , sdPacedWait     :: Maybe (Int -> IO [ev])+    -- ^ The backend's own wait between the frames of a running animation,+    -- if it has one. The loop calls it in place of 'sdWaitEvents' when its+    -- timeout is this window's 'sdPacingMs' wait for an animation (or a+    -- continuous session paced by time), and does not wind a frame it+    -- times out of onto 'sdAlignSec': the backend's wait starts the next+    -- frame on its own grid. With 'Nothing' the loop calls 'sdWaitEvents'+    -- and aligns the frame itself.   , sdApplyEvent    :: Input -> ev -> Input     -- ^ Fold an event into the 'Input' state.   , sdIsButtonEdge  :: ev -> Bool-    -- ^ Predicate identifying click/press boundaries where the event stream should be split.-  , sdIsHardQuit    :: ev -> Bool-    -- ^ Predicate for immediate OS/SIGINT hard-quit signals (e.g. Ctrl+C).+    -- ^ Predicate identifying click/press boundaries where the event stream+    -- should be split. 'NanoUI.Internal.Input.takeFrame' also splits after a+    -- command key whose order relative to other input matters.   , sdIsSessionQuit :: ev -> Bool-    -- ^ Predicate for window close requests.+    -- ^ Predicate for window close requests. A request ends the session+    -- unless 'NanoUI.wsExitOnCloseRequest' is off, in which case it is+    -- reported on the next frame via 'NanoUI.winCloseRequested'.   , sdSyncDisplay   :: Context -> Input -> IO (Context, Input)     -- ^ Backend-specific display synchronization (window dimensions, DPI scale).   , sdDebug         :: DebugSamplerRef     -- ^ The session's debug sampler: loop timing, skips, and the 4 Hz     -- readout refresh.   , sdContinuous    :: !Bool-    -- ^ Redraw every pass without waiting for events.+    -- ^ Redraw every pass without waiting for events. The loop waits 0 ms+    -- between passes while 'sdPresentPaces' holds or 'sdVsyncOff' is set,+    -- and 'sdPacingMs' otherwise, as for an animation.+  , sdVsyncOff      :: !Bool+    -- ^ Whether the backend turned vertical sync off on purpose, so a+    -- continuous session draws as fast as it can. With this 'False', a+    -- continuous session whose presents stop waiting for the display (a+    -- driver ignoring vsync) is paced at 'sdPacingMs' instead.   , sdPacingMs      :: !Int-    -- ^ Event wait in milliseconds while something animates or a text field-    -- is being edited.+    -- ^ Event wait in milliseconds while something animates.   , sdPresentPaces  :: IO Bool     -- ^ Whether the last present waited for the display (vsync), so a running     -- animation can loop without waiting and still be frame-locked.@@ -179,102 +214,238 @@     -- cadence matches the host, instead of drifting with the event waiter's     -- timer granularity.   , sdShouldDraw    :: Context -> Input -> Input -> Bool -> Bool -> IO Bool-    -- ^ Decision predicate: (ctx, prevInp, curInp, wasAnimating, debugDue) ->-    -- should this frame be rendered? Usually 'shouldRedrawFrame'.-  , sdDraw          :: Context -> Input -> Bool -> IO (Bool, Input)-    -- ^ Render frame: (ctx, curInp, forceFull) -> (dirtyAfterRender, syncedInput).+    -- ^ Decision predicate: (ctx, prevInp, curInp, wasAnimating, refreshDue) ->+    -- should this frame be rendered? Usually 'shouldRedrawFrame' with the+    -- driver's 'sdContinuous' as its continuous flag:+    -- @\\c p i a r -> shouldRedrawFrame c p i a continuous r@.+  , sdDraw          :: Context -> Input -> Bool -> IO Bool+    -- ^ Render frame: (ctx, curInp, forceFull) -> dirtyAfterRender.   , sdOnCursor      :: Context -> Input -> IO ()     -- ^ Sync the host cursor icon after every pass.   , sdShouldQuit    :: Input -> Bool     -- ^ Application-level quit predicate.+  , sdWindows       :: Maybe LoopWindows+    -- ^ Further windows the session runs beside this one+    -- ("NanoUI.Runner.Windows"), if the backend has them.   } +-- | What the loop needs of a session's further windows.+data LoopWindows = LoopWindows+  { lwWait :: IO Int+    -- ^ The longest wait, in milliseconds, they allow; -1 for no limit.+  , lwFirstDue :: IO Bool+    -- ^ Whether this window must run its view: a 'NanoUI.Var' it may read+    -- changed since it last did.+  , lwDrew :: IO ()+    -- ^ This window just ran its view.+  , lwAfterPass :: Context -> IO ()+    -- ^ Run their passes, after each of this window's.+  }++-- | NANO_LOOP_TRACE: on the first pass a second or more after the last line,+-- print to stderr the time covered, how many passes the loop made in it, how+-- many of them drew, and why. A busy loop prints a line a second. An idle+-- window prints nothing, and the line after a quiet spell covers all of it,+-- so whatever prints steadily is what keeps the process awake. The+-- reasons are @D@ a dirty context, @A@ an animation, @R@ a window redraw+-- request, and @T@ a timed wake or a debug readout refresh; a pass with none+-- of them was caused by input.+data LoopTraceState = LoopTraceState !Double !Int !Int !Int ![String]++type LoopTrace = Maybe (IORef LoopTraceState)++newLoopTrace :: Double -> IO LoopTrace+newLoopTrace now = do+  on <- isJust <$> lookupEnv "NANO_LOOP_TRACE"+  -- stderr is unbuffered by default, which writes a line a character at a+  -- time: enough system calls to show up in the measurement being taken.+  when on (hSetBuffering stderr LineBuffering)+  if on then Just <$> newIORef (LoopTraceState now 0 0 0 []) else pure Nothing++traceLoopPass :: LoopTrace -> Int -> Bool -> String -> IO ()+traceLoopPass lt nEvents drew why = forM_ lt $ \ref -> do+  now <- getMonotonicTime+  LoopTraceState t0 passes draws events whys <- readIORef ref+  let !passes' = passes + 1+      !draws' = if drew then draws + 1 else draws+      !events' = events + nEvents+      whys' = if passes < 24 then (if null why then "-" else why) : whys else whys+  if now - t0 >= 1+    then do+      hPutStrLn stderr $+        "LOOP " ++ showFFloat (Just 1) (now - t0) "s passes=" ++ show passes' ++ " draws=" ++ show draws'+          ++ " events=" ++ show events' ++ " why=" ++ unwords (reverse whys')+      hFlush stderr+      writeIORef ref $! LoopTraceState now 0 0 0 []+    else writeIORef ref $! LoopTraceState t0 passes' draws' events' whys'++-- | Added to the wait for a timed wake, so the wait ends at or after the time+-- asked for. An OS wait can return a millisecond or two early, and a backend+-- that counts its timeout in whole milliseconds turns the fraction then left+-- into a wait of zero: without the pad the loop spins through that last+-- millisecond, dozens of empty passes for every wake. The frame comes this+-- much late instead, which nothing scheduled to the millisecond can notice;+-- animation is paced separately.+wakePadMs :: Int+wakePadMs = 2++-- | The event wait, in milliseconds, until a timed wake at @wakeAt@ (0 for+-- none, which waits without limit) from @now@. An hour at most: the backends+-- take a 32-bit timeout, and the loop waits again when it runs out.+wakeTimeoutMs :: Double -> Double -> Int+wakeTimeoutMs wakeAt now+  | wakeAt <= 0 = -1+  | wakeAt <= now = 0+  | otherwise = ceiling (min 3600 (wakeAt - now) * 1000) + wakePadMs++-- | The shorter of two waits, where -1 is no limit.+shorterWait :: Int -> Int -> Int+shorterWait a b+  | a < 0 = b+  | b < 0 = a+  | otherwise = min a b++-- | Milliseconds a window may sleep before its next frame: @pacingMs@ when an+-- animation is active or just ended, else the remaining time until 'getWakeAt'.+windowTimeoutMs :: Bool -> Int -> Context -> IO Int+windowTimeoutMs wasAnim pacingMs ctx = do+  animating <- (wasAnim ||) <$> anyAnimating ctx+  if animating+    then pure pacingMs+    else wakeTimeoutMs <$> getWakeAt ctx <*> getMonotonicTime++-- | Check whether a scheduled wake deadline has arrived; if so, clear it so a+-- skipped frame does not spin on an expired timestamp, and return 'True'.+takeDueWake :: Context -> IO Bool+takeDueWake ctx = do+  wakeAt <- getWakeAt ctx+  due <- if wakeAt > 0 then (>= wakeAt) <$> getMonotonicTime else pure False+  when due (clearWakeAt ctx)+  pure due+ -- | Event wait while only the debug readout needs frames: its refresh period. debugHudTimeout :: Int debugHudTimeout = round (debugRefreshSec * 1000) --- | Run an event-driven session loop until a termination event or user quit condition.+-- | Run an event-driven session loop until the window is closed, a view+-- calls 'NanoUI.quit', or 'sdShouldQuit' returns 'True'. Ctrl+C closes the+-- window too, after its frame, unless a shortcut took it or the focused+-- widget uses it, as a text field does to copy. Background tasks started by+-- the view are cancelled on exit. runSessionLoop ::   SessionDriver ev ->   Context ->   Input ->   IO () runSessionLoop drv ctx0 inp0 = do-  clickTracker <- newIORef ClickTrack {ctTime = 0, ctPos = V2 (-999) (-999), ctCount = 0}+  clickTracker <- newClickTracker   startT <- getMonotonicTime+  trace <- newLoopTrace startT -  let waitForEvents timeout lastT+  let -- A paced wait is one a running animation times out of, so the frame it+      -- ends on is wound onto the pacing grid. Any other wait ends whenever+      -- its event or deadline arrives.+      waitForEvents timeout paced lastT         | timeout < 0 = sdWaitEvents drv (-1)         | otherwise = do             polled <- sdPollEvents drv             if not (null polled)               then pure polled-              else do-                events <- sdWaitEvents drv timeout-                -- Only a timed-out paced wait needs frame alignment.-                when (timeout > 0 && null events) $-                  alignFrameStart (sdAlignSec drv) lastT-                pure events+              else case sdPacedWait drv of+                Just pacedWait | paced && timeout > 0 -> pacedWait timeout+                _ -> do+                  events <- sdWaitEvents drv timeout+                  when (paced && timeout > 0 && null events) $+                    alignFrameStart (sdAlignSec drv) lastT+                  pure events +      nextBatch ctx queued lastT pendingDirty wasAnim+        | not (null queued) = pure (queued, False)+        | pendingDirty = (,False) <$> waitForEvents 0 False lastT+        | otherwise = do+            (debugActive, dueNow) <- debugCadence (sdDebug drv)+            animating <- anyAnimating ctx+            dirty <- isDirty ctx+            woken <- readIORef (ctxWoken ctx)+            presentPaces <- sdPresentPaces drv+            wakeAt <- getWakeAt ctx+            waitT <- if wakeAt > 0 then getMonotonicTime else pure 0+            others <- maybe (pure (-1)) lwWait (sdWindows drv)+            let wakeMs = wakeTimeoutMs wakeAt waitT+                idleMs = if debugActive then shorterWait debugHudTimeout wakeMs else wakeMs+                -- A continuous session whose presents do not wait for the+                -- display, though vsync was asked for, is paced by time.+                continuousPaced = sdContinuous drv && not presentPaces && not (sdVsyncOff drv)+                own+                  | dueNow || dirty || woken || (animating && presentPaces) = 0+                  | sdContinuous drv && not continuousPaced = 0+                  | wasAnim || animating || continuousPaced = sdPacingMs drv+                  | otherwise = idleMs+                timeout = shorterWait own others+                -- A wait another window shortened ends off this one's grid.+                paced = (wasAnim || animating || continuousPaced) && timeout == own+            events <- waitForEvents timeout paced lastT+            wakeDue <- takeDueWake ctx+            let hudDue = timeout == debugHudTimeout && debugActive && null events+            firstDue <- maybe (pure False) lwFirstDue (sdWindows drv)+            pure (events, dueNow || wakeDue || hudDue || firstDue)+       loop ctx inp queued lastT pendingDirty wasAnim = do-        (pending, debugDue) <--          if not (null queued)-            then pure (queued, False)-            else if pendingDirty-              then (,False) <$> waitForEvents 0 lastT-              else do-                debugActive <- isDebugActive (sdDebug drv)-                refreshDue <- debugRefreshDue (sdDebug drv)-                animating <- anyAnimating ctx-                editing <- textFieldActive ctx-                dirty <- isDirty ctx-                presentPaces <- sdPresentPaces drv-                let dueNow = debugActive && refreshDue-                    timeout-                      | sdContinuous drv || dueNow || dirty || (animating && presentPaces) = 0-                      | wasAnim || animating || editing = sdPacingMs drv-                      | debugActive = debugHudTimeout-                      | otherwise = -1-                events <- waitForEvents timeout lastT-                -- A readout wait that timed out ends on its refresh.-                pure (events, dueNow || (timeout == debugHudTimeout && debugActive && null events))+        (pending, refreshDue) <- nextBatch ctx queued lastT pendingDirty wasAnim+        -- Reset the wake latch before reading state updated by background+        -- threads, so a subsequent wake triggers the callback again.+        takeWakes ctx -        let (group, rest) = splitFrame (sdIsButtonEdge drv) pending-        editActive <- textInputEditActive ctx-        let hardQuitEv = any (sdIsHardQuit drv) group && not editActive-            sessionQuitEv = any (sdIsSessionQuit drv) group-        if hardQuitEv || sessionQuitEv-          then pure ()-          else do-            now <- getMonotonicTime-            let !dt = min maxFrameDt (realToFrac (now - lastT))-            noteDebugLoop (sdDebug drv) dt-            let inpFolded = foldl' (sdApplyEvent drv) (clearEphemeral inp {inputDeltaTime = dt}) group-            inpStamped <- stampClicks clickTracker inpFolded-            (ctx', inpSynced) <- sdSyncDisplay drv ctx inpStamped-            -- Hard quit (e.g. Ctrl+C) is ignored while a text editor is active.-            editActiveSynced <- textInputEditActive ctx'-            if isHardQuitInput inpSynced && not editActiveSynced-              then pure ()-              else do-                shouldDraw <- if pendingDirty-                  then pure True-                  else sdShouldDraw drv ctx' inp inpSynced wasAnim debugDue-                -- Force a full present only on the settle frame where an-                -- animation just finished (wasAnim && not animNow), so running-                -- animations keep clip damage.-                animNow <- anyAnimating ctx'-                (dirtyOut, synced) <- if shouldDraw-                  then sdDraw drv ctx' inpSynced (wasAnim && not animNow)-                  else do-                    noteDebugSkip (sdDebug drv)-                    pure (pendingDirty, inpSynced)-                sdOnCursor drv ctx' synced-                animAfter <- anyAnimating ctx'-                -- Open modals/overlays consume Escape/Quit before the app sees it.-                overlayQuit <- overlayConsumesQuit ctx' synced-                if sdShouldQuit drv synced && not overlayQuit-                  then pure ()-                  else loop ctx' synced rest now dirtyOut animAfter+        now <- getMonotonicTime+        let !dt = min maxFrameDt (realToFrac (now - lastT))+            (frameInp, group, rest) =+              takeFrame (sdApplyEvent drv) (sdIsButtonEdge drv) (clearEphemeral inp {inputDeltaTime = dt}) pending+        let closing = any (sdIsSessionQuit drv) group+        closeNow <- if closing then requestWindowClose ctx else pure False+        unless closeNow $ do+          noteDebugLoop (sdDebug drv) dt+          inpStamped <- stampClicks clickTracker frameInp+          (ctx', inpSynced) <- sdSyncDisplay drv ctx inpStamped+          shouldDraw <- if pendingDirty+            then pure True+            else sdShouldDraw drv ctx' inp inpSynced wasAnim refreshDue+          -- Force a full present only on the settle frame where an+          -- animation just finished (wasAnim && not animNow), so running+          -- animations keep clip damage.+          animNow <- anyAnimating ctx'+          dirtyOut <- if shouldDraw+            then sdDraw drv ctx' inpSynced (wasAnim && not animNow) <* mapM_ lwDrew (sdWindows drv)+            else pendingDirty <$ noteDebugSkip (sdDebug drv)+          sdOnCursor drv ctx' inpSynced+          mapM_ (`lwAfterPass` ctx') (sdWindows drv)+          animAfter <- anyAnimating ctx'+          traceLoopPass trace (length group) shouldDraw $+            (if pendingDirty then "D" else "")+              ++ (if wasAnim || animAfter then "A" else "")+              ++ (if inputWindowRedraw inpSynced then "R" else "")+              ++ (if refreshDue then "T" else "")+          -- Ctrl+C closes the window as its close button does, once the frame+          -- has shown that nothing in the view used it.+          used <- if isHardQuitInput frameInp then hardQuitUsed ctx' inpSynced else pure True+          hardQuit <- if used then pure False else requestWindowClose ctx'+          overlayQuit <- overlayConsumesQuit ctx' inpSynced+          quit <- quitRequested ctx'+          -- The next pass was animating if this frame was, even when this+          -- frame's tick finished the animation: its view read the value+          -- before that tick, so one more (settle) frame draws the end value.+          unless (quit || hardQuit || (sdShouldQuit drv inpSynced && not overlayQuit)) $+            loop ctx' inpSynced rest now dirtyOut animNow -  loop ctx0 inp0 [] startT False False+  -- The session's end needs only refs that every copy of the context shares.+  -- Holding 'ctx0' until then would keep its font metrics, and their caches,+  -- alive after a font reload hands the loop a new context.+  let !window = ctxNativeWindow ctx0+      !wake = ctxWakeLoop ctx0+      !held = ctxHeld ctx0+      !loopThread = ctxLoopThread ctx0+  -- This thread's dirty marks need no wake action ('markDirty').+  myThreadId >>= writeIORef loopThread . Just+  -- An opening frame the backend drew before the loop may have called+  -- 'NanoUI.quit' already; waiting first could block for good.+  (quitRequested ctx0 >>= \quit -> unless quit (loop ctx0 inp0 [] startT False False))+    `finally` (closeWindowSlot window `finally` cancelTasksOf wake held `finally` writeIORef loopThread Nothing)
+ lib/NanoUI/Runner/Windows.hs view
@@ -0,0 +1,326 @@+-- | A session's further windows ('NanoUI.nativeWindow'), for a backend that+-- runs its first window with 'NanoUI.Runner.runSessionLoop': opening and+-- closing them as views declare them, and running their frames after each+-- pass of the first window's loop. The backend supplies 'WindowOps', hands+-- 'loopWindows' to the loop ('NanoUI.Runner.sdWindows'), and routes each+-- further window's events to it ('openWindows').+--+-- A further window runs its view when it has input, when its last frame+-- asked for another, an animation or timed wake is due, a 'NanoUI.Var'+-- changed since its view last ran ('varChangeCount'), or the window that+-- declared it ran a frame, whose view the declaration's body may close over.+-- A session whose views declare none does none of this beyond finding the+-- list empty.+module NanoUI.Runner.Windows+  ( WindowOps (..)+  , Windows+  , newWindows+  , openWindows+  , hasWindows+  , loopWindows+  , afterMainPass+  , closeWindows+  ) where++import Control.Concurrent (myThreadId)+import Control.Exception (finally, onException)+import Control.Monad (filterM, forM_, join, unless, when)+import Data.Foldable (foldlM)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (find)+import Data.Word (Word64)+import GHC.Clock (getMonotonicTime)+import NanoUI.Internal.ChildWindow (ChildWindow (..), childView, childWindows)+import NanoUI.Internal.Context+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input+import NanoUI.Internal.Monad (NanoUI, unlessM)+import NanoUI.Internal.NativeWindow (quitRequested, requestWindowClose)+import NanoUI.Internal.NativeWindow.Types (WindowSettings (..))+import NanoUI.Internal.Var (readVarIO, writeVarIO)+import NanoUI.Internal.Var.Cell (varChangeCount)+import NanoUI.Runner (ClickTracker, LoopWindows (..), maxFrameDt, newClickTracker, shorterWait, shouldRedrawFrame, stampClicks, takeDueWake, windowTimeoutMs)++-- | How a backend opens, draws and closes a further window @w@ with events+-- @ev@.+data WindowOps w ev = WindowOps+  { woOpen :: Context -> WindowSettings -> IO (w, Context)+  -- ^ Open a window for a declaration in the view of the given context.+  -- Answer the window and the context its view runs on, with the backend's+  -- session and wake installed.+  , woClose :: w -> IO ()+  -- ^ Close it, cancelling its view's background jobs.+  , woApplyEvent :: Input -> ev -> Input+  , woIsButtonEdge :: ev -> Bool+  , woIsClose :: ev -> Bool+  -- ^ The desktop asked to close the window.+  , woSync :: w -> Context -> Input -> IO (Context, Input)+  -- ^ As 'NanoUI.Runner.sdSyncDisplay', for this window.+  , woDraw :: w -> Context -> NanoUI () -> Input -> Bool -> IO Bool+  -- ^ Draw a frame of the view, forcing a full repaint with the flag, and+  -- answer whether the context needs another.+  , woCursor :: w -> Context -> Input -> IO ()+  -- ^ Sync the cursor, after every pass of the window.+  , woPacingMs :: w -> Int+  -- ^ The wait between frames while the window animates.+  , woWatchResize :: w -> IO () -> IO (IO ())+  -- ^ Run the action whenever the host resizes the window, including while+  -- it holds the first window's loop in a modal size loop (Windows does+  -- while a window border is dragged); answer the action that stops it. The+  -- action draws the window at its new size. A backend whose loop keeps+  -- running during a resize answers @\\_ _ -> pure (pure ())@.+  }++-- | Active set of secondary native windows owned by a session runner.+data Windows w ev = Windows+  { wOps :: !(WindowOps w ev)+  , wTop :: !(IORef [Child w ev])+  , wFirstSeen :: !(IORef Word64)+  -- ^ 'varChangeCount' when the first window's view last ran.+  }++-- | One further window.+data Child w ev = Child+  { chKey :: !WidgetId+  , chWin :: !w+  , chParent :: !Context+  -- ^ The declaring window's context, which a close asks for a frame.+  , chDecl :: !(IORef ChildWindow)+  -- ^ The latest declaration, whose view and 'NanoUI.Var' are current.+  , chClosed :: !(IORef Bool)+  -- ^ Closed, though a sweep that began before may still hold it.+  , chSiblings :: !(IORef [Child w ev])+  , chChildren :: !(IORef [Child w ev])+  , chQueue :: !(IORef [ev])+  -- ^ Events not yet taken, newest first.+  , chClicks :: !ClickTracker+  , chLoop :: !(IORef ChildLoop)+  , chUnwatch :: !(IORef (IO ()))+  -- ^ Stops its resize watch ('woWatchResize').+  }++-- | A further window's loop state between its passes.+data ChildLoop = ChildLoop+  { clCtx :: !Context+  , clInput :: !Input+  , clLastT :: !Double+  , clWasAnim :: !Bool+  , clDraw :: !Bool+  -- ^ Draw next pass: the last frame asked for another, or the declaring+  -- window drew.+  , clSettle :: !Int+  -- ^ Opening frames still to draw: the first lays out against no previous+  -- rectangles, as the first window's opening frames do.+  , clSeen :: !Word64+  -- ^ 'varChangeCount' when its view last ran.+  , clParentFrame :: !Int+  -- ^ The declaring window's frame number at the last sync.+  , clResized :: !Bool+  -- ^ A resize watch frame ('liveResize') drew the window since its last+  -- pass.+  }++-- | Create an empty 'Windows' manager using the given backend callbacks.+newWindows :: WindowOps w ev -> IO (Windows w ev)+newWindows ops = Windows ops <$> newIORef [] <*> (newIORef =<< varChangeCount)++allChildren :: IORef [Child w ev] -> IO [Child w ev]+allChildren ref = readIORef ref >>= fmap concat . mapM (\c -> (c :) <$> allChildren (chChildren c))++-- | Every open further window, each before those it opened, with an action+-- that queues an event for it.+openWindows :: Windows w ev -> IO [(w, ev -> IO ())]+openWindows w = map (\c -> (chWin c, \ev -> modifyIORef' (chQueue c) (ev :))) <$> allChildren (wTop w)++-- | Whether any further window is open.+hasWindows :: Windows w ev -> IO Bool+hasWindows w = not . null <$> readIORef (wTop w)++-- | The windows for 'NanoUI.Runner.sdWindows'. The first window runs its view+-- when a 'NanoUI.Var' changed since it last did, which matters only while+-- further windows are open.+loopWindows :: Windows w ev -> LoopWindows+loopWindows w =+  LoopWindows+    { lwWait = allChildren (wTop w) >>= foldlM (\acc c -> shorterWait acc <$> childWait w c) (-1)+    , lwFirstDue = do+        open <- hasWindows w+        if open then (/=) <$> varChangeCount <*> readIORef (wFirstSeen w) else pure False+    , lwDrew = writeIORef (wFirstSeen w) =<< varChangeCount+    , lwAfterPass = afterMainPass w+    }++childWait :: Windows w ev -> Child w ev -> IO Int+childWait w c = do+  cl <- readIORef (chLoop c)+  due <- childDue c cl+  if due+    then pure 0+    else windowTimeoutMs (clWasAnim cl) (woPacingMs (wOps w) (chWin c)) (clCtx cl)++-- | Whether a window must draw next pass, whatever its input.+mustDraw :: ChildLoop -> IO Bool+mustDraw cl = (\gen -> clSettle cl > 0 || clDraw cl || clSeen cl /= gen) <$> varChangeCount++-- | Whether a window has something to do now, animations and timed wakes+-- aside.+childDue :: Child w ev -> ChildLoop -> IO Bool+childDue c cl = do+  queued <- not . null <$> readIORef (chQueue c)+  forced <- mustDraw cl+  woken <- readIORef (ctxWoken (clCtx cl))+  ctxDirty <- isDirty (clCtx cl)+  pure (queued || forced || woken || ctxDirty)++-- | After a pass of the first window's loop: open and close windows for what+-- its view declared and run the further windows' passes.+afterMainPass :: Windows w ev -> Context -> IO ()+afterMainPass w ctx = do+  syncChildren w ctx (wTop w)+  kids <- allChildren (wTop w)+  forM_ kids $ \c -> unlessM (readIORef (chClosed c)) (stepChild w c)++-- | Open a window for each new declaration of @parent@'s view and close+-- those it no longer declares, or declares closed. A parent that drew a+-- frame since the last sync makes each of its windows draw.+syncChildren :: Windows w ev -> Context -> IORef [Child w ev] -> IO ()+syncChildren w parent ref = do+  decls <- childWindows parent+  old <- readIORef ref+  unless (null decls && null old) $ do+    frame <- frameNumber parent+    open <- filterM (readVarIO . childOpen) decls+    openedRef <- newIORef []+    new <-+      let go [] acc = pure (reverse acc)+          go (d : ds) acc = case find ((== childKey d) . chKey) old of+            Just c -> do+              writeIORef (chDecl c) d+              modifyIORef' (chLoop c) $ \cl ->+                if clParentFrame cl == frame then cl else cl {clParentFrame = frame, clDraw = True}+              go ds (c : acc)+            Nothing -> do+              c <- openChild w parent ref frame d+              modifyIORef' openedRef (c :)+              go ds (c : acc)+       in go open [] `onException` (readIORef openedRef >>= mapM_ (closeChild w))+    forM_ old $ \c -> unless (any ((== chKey c) . chKey) new) (closeChild w c)+    writeIORef ref new++openChild :: Windows w ev -> Context -> IORef [Child w ev] -> Int -> ChildWindow -> IO (Child w ev)+openChild w parent siblings frame decl = do+  (win, ctx) <- woOpen (wOps w) parent (childSettings decl)+  -- This thread runs its frames, so its own dirty marks need no wake.+  myThreadId >>= writeIORef (ctxLoopThread ctx) . Just+  now <- getMonotonicTime+  let inp = applyPointerLeave emptyInput {inputWindowSize = wsSize (childSettings decl)}+  c <-+    Child (childKey decl) win parent+      <$> newIORef decl+      <*> newIORef False+      <*> pure siblings+      <*> newIORef []+      <*> newIORef []+      <*> newClickTracker+      <*> newIORef (ChildLoop ctx inp now False False 2 0 frame False)+      <*> newIORef (pure ())+  unwatch <- woWatchResize (wOps w) win (liveResize w c) `onException` woClose (wOps w) win+  c <$ writeIORef (chUnwatch c) unwatch++-- | Close a window and those it declared.+closeChild :: Windows w ev -> Child w ev -> IO ()+closeChild w c = unlessM (readIORef (chClosed c)) $ do+  writeIORef (chClosed c) True+  mapM_ (closeChild w) =<< readIORef (chChildren c)+  writeIORef (chChildren c) []+  join (readIORef (chUnwatch c)) `finally` woClose (wOps w) (chWin c)++-- | Close every further window, when the session ends.+closeWindows :: Windows w ev -> IO ()+closeWindows w = do+  mapM_ (closeChild w) =<< readIORef (wTop w)+  writeIORef (wTop w) []++-- | The window asked to close (its close button, or 'NanoUI.quit' in its+-- view): write 'False' to its 'NanoUI.Var', close it now, and ask the+-- declaring window for the frame that shows it closed, which nothing else+-- would ask for once no further window is open. A read-only 'NanoUI.Var'+-- keeps it open.+closeRequested :: Windows w ev -> Child w ev -> IO ()+closeRequested w c = do+  open <- childOpen <$> readIORef (chDecl c)+  writeVarIO open False+  unlessM (readVarIO open) $ do+    closeChild w c+    modifyIORef' (chSiblings c) (filter ((/= chKey c) . chKey))+    markDirty (chParent c)++drawChildPass :: WindowOps w ev -> Child w ev -> ChildLoop -> Context -> Input -> Bool -> IO ChildLoop+drawChildPass ops c cl ctx' inp full = do+  view <- childView <$> readIORef (chDecl c)+  more <- woDraw ops (chWin c) ctx' view inp full+  seen <- varChangeCount+  pure cl {clDraw = more, clSettle = max 0 (clSettle cl - 1), clSeen = seen}++-- | One pass of a further window's loop: take its events into a frame's+-- input, as the first window's loop does, and draw when anything calls for+-- it. Nothing to do costs a few reads.+stepChild :: Windows w ev -> Child w ev -> IO ()+stepChild w c = do+  cl <- readIORef (chLoop c)+  let ctx = clCtx cl+  due <- childDue c cl+  animating <- anyAnimating ctx+  wakeDue <- takeDueWake ctx+  now <- getMonotonicTime+  when (due || clWasAnim cl || animating || wakeDue) $ do+    takeWakes ctx+    evs <- reverse <$> readIORef (chQueue c)+    let dt = min maxFrameDt (realToFrac (now - clLastT cl))+        (frameInp, group, rest) = takeFrame (woApplyEvent ops) (woIsButtonEdge ops) (clearEphemeral (clInput cl) {inputDeltaTime = dt}) evs+    writeIORef (chQueue c) $! reverse rest+    closing <- if any (woIsClose ops) group then requestWindowClose ctx else pure False+    if closing+      then closeRequested w c+      else do+        stamped <- stampClicks (chClicks c) frameInp+        (ctx', syncedRaw) <- woSync ops win ctx stamped+        -- A resize watch frame since the last pass drew this size already,+        -- which covers the redraw requests the resize queued.+        let synced+              | clResized cl && inputWindowSize syncedRaw == inputWindowSize (clInput cl) =+                  syncedRaw {inputWindowRedraw = False}+              | otherwise = syncedRaw+        forced <- mustDraw cl+        draw <- if forced then pure True else shouldRedrawFrame ctx' (clInput cl) synced (clWasAnim cl) False wakeDue+        animNow <- anyAnimating ctx'+        cl' <- if draw then drawChildPass ops c cl ctx' synced (clSettle cl > 0 || (clWasAnim cl && not animNow)) else pure cl+        writeIORef (chLoop c) $! cl' {clCtx = ctx', clInput = synced, clLastT = now, clWasAnim = animNow, clResized = False}+        woCursor ops win ctx' synced+        quit <- quitRequested ctx'+        if quit then closeRequested w c else syncChildren w ctx' (chChildren c)+  where+    ops = wOps w+    win = chWin c++-- | A frame of a further window run by its resize watch ('woWatchResize').+-- While the host holds the first window's loop in a modal size loop,+-- 'stepChild' does not run, so the watch draws the window at each new size+-- as the first window's own watch does. It syncs the window and draws when+-- its size changed or its context is dirty (a display scale change marks+-- it); the next 'stepChild' then takes the resize's events without drawing+-- that size again.+liveResize :: Windows w ev -> Child w ev -> IO ()+liveResize w c = unlessM (readIORef (chClosed c)) $ do+  cl <- readIORef (chLoop c)+  (ctx', synced) <- woSync ops win (clCtx cl) (clearEphemeral (clInput cl))+  dirty <- isDirty ctx'+  when (dirty || inputWindowSize synced /= inputWindowSize (clInput cl)) $ do+    now <- getMonotonicTime+    let dt = min maxFrameDt (realToFrac (now - clLastT cl))+    cl' <- drawChildPass ops c cl ctx' synced {inputDeltaTime = dt} True+    animNow <- anyAnimating ctx'+    writeIORef (chLoop c) $! cl' {clCtx = ctx', clInput = synced, clLastT = now, clWasAnim = animNow, clResized = True}+  where+    ops = wOps w+    win = chWin c
− lib/NanoUI/SIMD.hs
@@ -1,152 +0,0 @@--- | Vertex and index writers for the draw buffers. Each vertex is written with--- two 128-bit GHC SIMD stores (FloatX4#) instead of eight scalar stores.-module NanoUI.SIMD-  ( pokeVertexSIMD-  , pokeQuadSIMD-  , pokeQuadGradientSIMD-  , concentricOffsetsSIMD-  ) where--import GHC.Ptr (Ptr (..))-import Foreign.Storable (pokeByteOff)-import GHC.Exts-  ( Float (F#)-  , Int (I#)-  , packFloatX4#-  , packWord32X4#-  , plusAddr#-  , writeFloatOffAddrAsFloatX4#-  , writeWord32OffAddrAsWord32X4#-  )-import GHC.Word (Word32 (W32#))-import GHC.IO (IO (..))-import Data.Word (Word8)---- | Writes one 32-byte Vertex (8 floats) into memory using two 128-bit SIMD stores--- instead of 8 scalar stores.-{-# INLINE pokeVertexSIMD #-}-pokeVertexSIMD ::-  Ptr Word8 ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  IO ()-pokeVertexSIMD (Ptr addr#) (I# byteOff#) (F# px#) (F# py#) (F# r#) (F# g#) (F# b#) (F# a#) (F# u#) (F# v#) = IO $ \s0 ->-  -- Offsets are recomputed inline (the address add is a single lea) so the-  -- simplified body stays free of let bindings; the inspection test guards-  -- this with a NoAllocation obligation.-  case packFloatX4# (# px#, py#, r#, g# #) of-    v0# ->-      case packFloatX4# (# b#, a#, u#, v# #) of-        v1# ->-          case writeFloatOffAddrAsFloatX4# (plusAddr# addr# byteOff#) 0# v0# s0 of-            s1 -> case writeFloatOffAddrAsFloatX4# (plusAddr# (plusAddr# addr# byteOff#) 16#) 0# v1# s1 of-              s2 -> (# s2, () #)---- | Vectorized Quad Poking: writes 4 vertices (128 bytes total) and 6 indices (24 bytes total)--- with SIMD vector stores.-{-# INLINE pokeQuadSIMD #-}-pokeQuadSIMD ::-  Ptr Word8 ->-  Int ->-  Ptr Word8 ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Word32 ->-  IO ()-pokeQuadSIMD vertices vOffset indices iOffset x y w h u0 v0 u1 v1 r g b a baseIdx = do-  let x1 = x + w-      y1 = y + h-  pokeVertexSIMD vertices vOffset x y r g b a u0 v0-  pokeVertexSIMD vertices (vOffset + 32) x1 y r g b a u1 v0-  pokeVertexSIMD vertices (vOffset + 64) x1 y1 r g b a u1 v1-  pokeVertexSIMD vertices (vOffset + 96) x y1 r g b a u0 v1-  pokeQuadIndicesSIMD indices iOffset baseIdx---- Six indices form the same two triangles for both solid and gradient quads.-{-# INLINE pokeQuadIndicesSIMD #-}-pokeQuadIndicesSIMD :: Ptr Word8 -> Int -> Word32 -> IO ()-pokeQuadIndicesSIMD (Ptr addr#) offset@(I# offset#) baseIdx = do-  let !(W32# b0#) = baseIdx-      !(W32# b1#) = baseIdx + 1-      !(W32# b2#) = baseIdx + 2-      !idxVec# = packWord32X4# (# b0#, b1#, b2#, b0# #)-  IO $ \s0 ->-    case writeWord32OffAddrAsWord32X4# (plusAddr# addr# offset#) 0# idxVec# s0 of-      s1 -> (# s1, () #)-  pokeByteOff (Ptr addr#) (offset + 16) (baseIdx + 2)-  pokeByteOff (Ptr addr#) (offset + 20) (baseIdx + 3)---- | Vectorized Quad with 4 distinct corner colors (top-left, top-right, bottom-right, bottom-left)-{-# INLINE pokeQuadGradientSIMD #-}-pokeQuadGradientSIMD ::-  Ptr Word8 ->-  Int ->-  Ptr Word8 ->-  Int ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  (Float, Float, Float, Float) ->-  (Float, Float, Float, Float) ->-  (Float, Float, Float, Float) ->-  (Float, Float, Float, Float) ->-  Word32 ->-  IO ()-pokeQuadGradientSIMD-  vertices vOffset indices iOffset x y w h u v-  (r0, g0, b0, a0) (r1, g1, b1, a1)-  (r2, g2, b2, a2) (r3, g3, b3, a3) baseIdx = do-  let x1 = x + w-      y1 = y + h-  pokeVertexSIMD vertices vOffset x y r0 g0 b0 a0 u v-  pokeVertexSIMD vertices (vOffset + 32) x1 y r1 g1 b1 a1 u v-  pokeVertexSIMD vertices (vOffset + 64) x1 y1 r2 g2 b2 a2 u v-  pokeVertexSIMD vertices (vOffset + 96) x y1 r3 g3 b3 a3 u v-  pokeQuadIndicesSIMD indices iOffset baseIdx---- | Evaluates 4 concentric arc positions:--- xs = cx + radii * ct--- ys = cy + radii * st------ Scalar on purpose: GHC 9.14.1 miscompiles the broadcast/pack/unpack FloatX4#--- version at -O2 once it is inlined into a loop (liberate-case computed the y--- lane from cx), corrupting anti-aliased border vertices. The results are--- bit-identical to the vector version, which also multiplied and added separately.-{-# INLINE concentricOffsetsSIMD #-}-concentricOffsetsSIMD ::-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  Float ->-  ((Float, Float), (Float, Float), (Float, Float), (Float, Float))-concentricOffsetsSIMD cx cy ct st r0 r1 r2 r3 =-  ( (cx + r0 * ct, cy + r0 * st)-  , (cx + r1 * ct, cy + r1 * st)-  , (cx + r2 * ct, cy + r2 * st)-  , (cx + r3 * ct, cy + r3 * st)-  )
+ lib/NanoUI/Shader/Raw.hs view
@@ -0,0 +1,40 @@+-- | Low-level shader compilation payloads, std140 uniform layouts, raw+-- backend shader constructors, and CPU evaluation hooks.+--+-- Application code authoring shaders in typed Haskell should use+-- @nano-ui-shader@ ("NanoUI.Shader") together with 'NanoUI.shaderBox' and+-- 'NanoUI.withShader' from "NanoUI". Import this module when embedding+-- hand-written GLSL, MSL, or SPIR-V shader programs directly, or inspecting+-- compiled shader metadata.+module NanoUI.Shader.Raw+  ( -- * Uniform layout+    GpuType (..)+  , UniformField (..)+  , uniformLayout+  , uniformSize++    -- * Raw programs+  , ShaderProgram (..)+  , emptyShaderProgram+  , rawShader+  , rawLayerShader++    -- * CPU evaluation+  , CpuFragCtx (..)+  , CpuShaderEval+  ) where++import NanoUI.Internal.Shader+  ( CpuFragCtx (..)+  , CpuShaderEval+  , ShaderProgram (..)+  , emptyShaderProgram+  , rawLayerShader+  , rawShader+  )+import NanoUI.Internal.Uniforms+  ( GpuType (..)+  , UniformField (..)+  , uniformLayout+  , uniformSize+  )
+ lib/NanoUI/Shortcut.hs view
@@ -0,0 +1,35 @@+-- | Key chords for 'NanoUI.shortcut' and 'NanoUI.menuItemShortcut', built+-- from modifiers and a key with '<>'.+--+-- > import NanoUI.Shortcut+-- >+-- > whenM (shortcut (ctrl <> key 's')) save+-- > whenM (shortcut (cmdOrCtrl <> shift <> key 'p')) (setPaletteOpen True)+-- > whenM (shortcut (alt <> key KeyEnter)) toggleFullscreen+-- > whenM (shortcut (key (KeyF 5))) refresh+--+-- The short names are meant for unqualified import where chords are+-- written, or qualified (@K.ctrl <> K.key \'s\'@). Chords are typed values, so+-- they cannot be misspelled; 'parseShortcut' reads one from text, such as a+-- settings file.+module NanoUI.Shortcut+  ( -- * Chords+    Shortcut (..)+  , ToKey (..)+  , key+  , ctrl+  , shift+  , alt+  , super+  , cmdOrCtrl++    -- * Text and labels+  , parseShortcut+  , shortcutLabel+  , keyLabel++    -- * Input+  , shortcutIn+  ) where++import NanoUI.Internal.Shortcut
− lib/NanoUI/Store.hs
@@ -1,268 +0,0 @@--- | The widget store: per-widget state in maps by value type, keyed by widget--- id and 'Slot'.-module NanoUI.Store-  ( WidgetStore (..)-  , emptyWidgetStore-  , mirrorStoresChanged-  , bumpMirror-  , slotKey-  , Slot (..)-  , boolInt-  , intBool-  , anySelectOpen-  , isSelectOpen-  , setSelectOpen-  , closeSelects-  , ptrEq-  , eqByPtr-  )-where--import Data.Dynamic (Dynamic)-import Data.IntMap.Strict (IntMap)-import Data.IntSet (IntSet)-import Data.Text (Text)-import Data.Word (Word64)-import qualified Data.IntMap.Strict as IM-import GHC.Exts (isTrue#, reallyUnsafePtrEquality#)-import NanoUI.Id (mix64)---- | Physical-equality shortcut. Pointer equality implies value equality for--- immutable values, so callers may use 'True' to skip a structural comparison--- of a field the caller never rebuilt. 'False' only means \"compare properly\".-{-# INLINE ptrEq #-}-ptrEq :: a -> a -> Bool-ptrEq a b = isTrue# (reallyUnsafePtrEquality# a b)---- | '==' with a physical-equality fast path. Unchanged fields of a--- record-updated store keep their identity, so whole-store comparisons become--- cheap when only one map was rebuilt.-{-# INLINE eqByPtr #-}-eqByPtr :: Eq a => a -> a -> Bool-eqByPtr a b = ptrEq a b || a == b---- | Dynamic values do not implement Eq, but we can verify equality via--- pointer equality fast path followed by checking key structure and--- pointer equality of each Dynamic element.-{-# INLINE eqDynMap #-}-eqDynMap :: IntMap Dynamic -> IntMap Dynamic -> Bool-eqDynMap a b =-  ptrEq a b-    || (IM.size a == IM.size b && IM.isSubmapOfBy ptrEq a b)---- | Widget state for every widget, in maps by value type. Same-type fields--- that share a widget key use 'slotKey'.-data WidgetStore = WidgetStore-  { storeMirrorGen :: {-# UNPACK #-} !Word64-  , storeOpenSelect :: {-# UNPACK #-} !Int-  , storeInt :: !(IntMap Int)-  , storeFloat :: !(IntMap Float)-  , storeDouble :: !(IntMap Double)-  , storePoint :: !(IntMap (Float, Float))-  , storeText :: !(IntMap Text)-  , storeIntSet :: !(IntMap IntSet)-  , storeFloatList :: !(IntMap [Float])-  , storeIntList :: !(IntMap [Int])-  , storeDyn :: !(IntMap Dynamic)-  }--instance Eq WidgetStore where-  a == b =-    storeMirrorGen a == storeMirrorGen b-      && storeOpenSelect a == storeOpenSelect b-      && eqByPtr (storeInt a) (storeInt b)-      && eqByPtr (storeFloat a) (storeFloat b)-      && eqByPtr (storeDouble a) (storeDouble b)-      && eqByPtr (storePoint a) (storePoint b)-      && eqByPtr (storeText a) (storeText b)-      && eqByPtr (storeIntSet a) (storeIntSet b)-      && eqByPtr (storeFloatList a) (storeFloatList b)-      && eqByPtr (storeIntList a) (storeIntList b)-      && eqDynMap (storeDyn a) (storeDyn b)--instance Show WidgetStore where-  show st =-    "WidgetStore { "-      ++ "storeMirrorGen = " ++ show (storeMirrorGen st)-      ++ ", storeOpenSelect = " ++ show (storeOpenSelect st)-      ++ ", storeInt = " ++ show (storeInt st)-      ++ ", storeFloat = " ++ show (storeFloat st)-      ++ ", storeDouble = " ++ show (storeDouble st)-      ++ ", storePoint = " ++ show (storePoint st)-      ++ ", storeText = " ++ show (storeText st)-      ++ ", storeIntSet = " ++ show (storeIntSet st)-      ++ ", storeFloatList = " ++ show (storeFloatList st)-      ++ ", storeIntList = " ++ show (storeIntList st)-      ++ ", storeDynCount = " ++ show (IM.size (storeDyn st))-      ++ " }"--emptyWidgetStore :: WidgetStore-emptyWidgetStore =-  WidgetStore-    { storeMirrorGen = 0-    , storeOpenSelect = 0-    , storeInt = IM.empty-    , storeFloat = IM.empty-    , storeDouble = IM.empty-    , storePoint = IM.empty-    , storeText = IM.empty-    , storeIntSet = IM.empty-    , storeFloatList = IM.empty-    , storeIntList = IM.empty-    , storeDyn = IM.empty-    }---- useText/useFlag bump this so Frame can re-run UI without watching every map.-{-# INLINE mirrorStoresChanged #-}-mirrorStoresChanged :: WidgetStore -> WidgetStore -> Bool-mirrorStoresChanged old new = storeMirrorGen old /= storeMirrorGen new--{-# INLINE bumpMirror #-}-bumpMirror :: WidgetStore -> WidgetStore-bumpMirror st = st {storeMirrorGen = storeMirrorGen st + 1}---- Mix a field tag into a widget key so two Ints (cursor vs anchor) do not collide.-{-# INLINE slotKey #-}-slotKey :: Slot -> Int -> Int-slotKey s k = fromIntegral (mix64 (fromIntegral k) (slotTag s))---- | Every built-in slot.-data Slot-  = SlotCursor-  | SlotAnchor-  | SlotDrag-  | SlotDragW-  | SlotDrop-  | SlotDropPos-  | SlotWinSize-  | SlotMenuOpen-  | SlotMenuPos-  | SlotScrollCfg-  | SlotScrollOff-  | SlotScrollCross-  | SlotScrollLinkX-  | SlotScrollLinkY-  | SlotScrollStep-  | SlotScrollAxes-  | SlotScrollViewPos-  | SlotScrollViewSize-  | SlotScrollRange-  | SlotScrollContent-  | SlotTextAreaRow-  | SlotTextAreaCol-  | SlotTextAreaPrefCol-  | SlotTextAreaScroll-  | SlotTextAreaViewport-  | SlotTextAreaAnchorRow-  | SlotTextAreaAnchorCol-  | -- | Cached text-area content extent (max line width, line count * line-    -- height) and the node font size they were measured at. Recomputing the width-    -- scans every character of the document, so it is cached and only refreshed-    -- when the text or font changes.-    SlotTextAreaContentW-  | SlotTextAreaContentH-  | SlotTextAreaContentFont-  | -- | Cached 'TextBuffer' for the text area, keyed by its flat 'Text'. Loads and-    -- paint reuse it so the document is not re-split into lines every call.-    SlotTextAreaBuffer-  | -- | Set (value 1) to signal that the text area's text changed through a path-    -- that does not flow through 'Input' (e.g. a context-menu cut/paste). The-    -- text area widget reads and clears this on its next frame, so the caller-    -- still gets a 'respChanged' pulse for edits that carry no keys or chars.-    SlotTextAreaChanged-  | -- | A text field's undo history with the text it was recorded against, in-    -- 'storeDyn'.-    SlotTextHistory-  | -- | Which kind of text field a widget id is: 1 single-line, 2 multi-line.-    -- Commands sent to the id between frames read it.-    SlotTextMode-  | -- | A text area's measured line widths, in 'storeDyn', kept in step with its-    -- lines so an edit remeasures only the lines it changed.-    SlotTextAreaWidths-  | SlotTextInputScroll-  | -- | Search-field debounce bookkeeping. Text slots on the text widget id: the last-    -- committed query and the monotonic timestamp of the last edit.-    SlotSearchCommitted-  | SlotSearchAge-  | -- | Combo box suggestion state (storeInt/storeFloat, keyed by the field-    -- widget): the highlighted option index (absolute into the filtered list),-    -- the start of the visible window slice (keyboard / wheel / scrollbar-    -- scrolling), and the scrollbar bookkeeping the overlay painter and the-    -- widget's thumb-drag gesture share (total filtered count, widest row, x-    -- offset, drag axis + grab offset).-    SlotComboHighlight-  | SlotComboScroll-  | SlotComboCount-  | SlotComboScrollX-  | SlotComboContentW-  | SlotComboDrag-  | SlotComboDragOff-  | -- | The last committed value (storeText): typing edits the live field text but-    -- only Enter, a row click, or losing focus commits it (Escape reverts).-    SlotComboCommitted-  | -- | Had-focus flag (storeInt) so the widget can see the focus-lost transition-    -- on the frame after blur and commit then.-    SlotComboFocus-  | -- | The field text as the widget last produced it (storeText): a frame-start-    -- value that differs from it changed externally (a frame-side row pick or a-    -- clipboard menu action), not by typing.-    SlotComboLive-  | -- | PaneGrid gesture slot (storeInt): 0 none, positive = dragged pane id,-    -- negative = split id being resized. Mirrors 'SlotDrag''s press-held-release-    -- lifecycle but keyed by the grid widget instead of a per-pane leaf.-    SlotPaneGest-  | -- | PaneGrid drag grab offset (storePoint): (mouse - pane origin) at grab start.-    SlotPaneGrab-  | -- | PaneGrid keyboard-navigation focus: focused pane id (0 = none, auto-first).-    SlotPaneFocus-  | -- | PaneGrid maximize state: maximized pane id (0 = none).-    SlotPaneMax-  | -- | PaneGrid resize start (storePoint): (ratio, main-axis mouse) captured when a-    -- divider is first grabbed, so dragging moves it by delta rather than snapping.-    SlotPaneResize-  | -- | PaneGrid id seed (storeInt): next split / pane id to allocate. Strictly-    -- monotonic per grid: ids are never reused, so per-pane state keyed by pane-    -- id cannot collide with a closed pane's state.-    SlotPaneNext-  | -- | The value a controlled widget last returned to its caller.-    SlotSeen-  | -- | A colour picker's opening colour.-    SlotColorBase-  | -- | The stepper arrow a numeric field's press holds: 1 up, -1 down.-    SlotNumericHeld-  | -- | When a numeric field's held stepper arrow next repeats, in monotonic-    -- seconds.-    SlotNumericRepeat-  deriving (Enum)---- | Tag for a built-in slot: the constructor index mixed with a salt, so tags--- are well spread.-{-# INLINE slotTag #-}-slotTag :: Slot -> Word64-slotTag s = mix64 0x534C4F5454414753 (fromIntegral (fromEnum s))--boolInt :: Bool -> Int-boolInt b = if b then 1 else 0--intBool :: Int -> Bool-intBool n = n /= 0---- One open select at a time.-{-# INLINE anySelectOpen #-}-anySelectOpen :: WidgetStore -> Bool-anySelectOpen st = storeOpenSelect st /= 0--{-# INLINE isSelectOpen #-}-isSelectOpen :: WidgetStore -> Int -> Bool-isSelectOpen st k = k /= 0 && storeOpenSelect st == k--{-# INLINE setSelectOpen #-}-setSelectOpen :: WidgetStore -> Int -> Bool -> WidgetStore-setSelectOpen st k True = st {storeOpenSelect = k}-setSelectOpen st k False-  | isSelectOpen st k = closeSelects st-  | otherwise = st--{-# INLINE closeSelects #-}-closeSelects :: WidgetStore -> WidgetStore-closeSelects st = st {storeOpenSelect = 0}
− lib/NanoUI/Style.hs
@@ -1,1009 +0,0 @@-{-# LANGUAGE StrictData #-}--module NanoUI.Style-  ( Sizing (..)-  , Direction (..)-  , AlignX (..)-  , AlignY (..)-  , Padding (..)-  , Layout (..)-  , defaultLayout-  , Style (..)-  , Theme (..)-  , defaultTheme-  , tomorrowNightMinDarkTheme-  , tomorrowMinLightTheme-  , tomorrowMidnightMinDarkTheme-  , Base16 (..)-  , themeFromBase16-  , themeFromBase16Dark-  , themeFromBase16Light-  , base16TomorrowNight-  , base16TomorrowLight-  -- * Style modifiers-  , background-  , foreground-  , borderColor-  , borderWidth-  , cornerRadius-  , hoverBackground-  , pressBackground-  , fillColor-  -- * Theme modifiers-  , buttonStyle-  , inputStyle-  , panelStyle-  , windowStyle-  , everyStyle-  , accentColor-  , textColor-  , mutedColor-  , linkColor-  , selectionColor-  , windowColor-  , rounded-  , tinted-  , primary-  , destructive-  , success-  , subtle-  , readableOn-  , disabledTheme-  , themeSeries-  , separatorTrackColor-  , scrollBarTrackColor-  , scrollBarThumbColor-  , fadeAlpha-  , windowPad-  , windowMargin-  , padAll-  , padXY-  , gap-  , fillW-  , fillH-  , grow-  , minW-  , maxW-  , fixedW-  , minH-  , maxH-  , fixedH-  , fixedWH-  , alignMid-  , alignEnd-  , tight-  , percent-  , gridMinColW-  , fixedAspectW-  , fixedAspectH-  , gridCols-  , FontVariant (..)-  , FontWeight (..)-  , FontStyle (..)-  , TextDecoration (..)-  , LayoutModifier-  , fontRegular-  , fontHeading-  , fontMuted-  , fontMono-  , fontDanger-  , fontSize-  , fontSizeScale-  , fontColor-  , fontWeight-  , fontBold-  , fontLight-  , fontMedium-  , fontSemiBold-  , fontExtraBold-  , fontBlack-  , fontStyle-  , fontItalic-  , fontOblique-  , textDecoration-  , fontUnderline-  , fontStrike-  , alignStart-  , alignCenter-  , alignTop-  , alignBottom-  , alignBaseline-  ) where--import Data.Bits ((.&.), (.|.))-import Data.Word (Word8)-import NanoUI.Types (Color (..), colorA, colorLuminance, colorRGBA, contrastRatio, lerpColor)--data Sizing-  = Fixed Float-  | Fit-  | Grow Float-  | Shrink Float-  | Percent Float-  deriving (Eq, Show)--data Direction = Row | Column-  deriving (Eq, Show, Enum, Bounded)--data AlignX = AlignStart | AlignCenter | AlignEnd-  deriving (Eq, Show, Enum, Bounded)---- | 'AlignBaseline' lines a row's text children up on their first baseline, and--- sits any other child on it by its bottom edge. Outside a row it is--- 'AlignTop'.-data AlignY = AlignTop | AlignMiddle | AlignBottom | AlignBaseline-  deriving (Eq, Show, Enum, Bounded)--data Padding = Padding-  { padL :: {-# UNPACK #-} !Float-  , padR :: {-# UNPACK #-} !Float-  , padT :: {-# UNPACK #-} !Float-  , padB :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)---- Floating window chrome. The body sits one side-pad below the chrome and one--- side-pad above the window's bottom edge (the window's own column gap fills--- the top; see 'NanoUI.Widgets.Overlay').-windowPad :: Padding-windowPad = Padding 10 10 0 10---- Screen inset for floating window/modal max size and default placement.-windowMargin :: Float-windowMargin = 14--data FontVariant-  = FontRegular-  | FontHeading-  | FontMuted-  | FontMono-  | FontDanger-  deriving (Eq, Show, Enum, Bounded, Ord)--data FontWeight-  = WeightNormal-  | WeightBold-  | WeightLight-  | WeightMedium-  | WeightSemiBold-  | WeightExtraBold-  | WeightBlack-  deriving (Eq, Show, Enum, Bounded, Ord)--data FontStyle-  = FontStyleNormal-  | FontStyleItalic-  | FontStyleOblique-  deriving (Eq, Show, Enum, Bounded, Ord)--data TextDecoration-  = DecorationNone-  | DecorationUnderline-  | DecorationStrikethrough-  | DecorationUnderlineStrike-  deriving (Eq, Show, Enum, Bounded, Ord)--type LayoutModifier = Layout -> Layout--data Layout = Layout-  { layoutDirection :: !Direction-  , layoutWidth :: !Sizing-  , layoutHeight :: !Sizing-  , layoutPadding :: !Padding-  , layoutGap :: {-# UNPACK #-} !Float-  , layoutAlignX :: !AlignX-  , layoutAlignY :: !AlignY-  , layoutMinW :: {-# UNPACK #-} !Float-  , layoutMinH :: {-# UNPACK #-} !Float-  , layoutMaxW :: {-# UNPACK #-} !Float-  , layoutMaxH :: {-# UNPACK #-} !Float-  , layoutFontVariant :: !FontVariant-  , layoutGridCols :: {-# UNPACK #-} !Int-  , layoutGridMinColW :: {-# UNPACK #-} !Float-  , layoutFontSize :: {-# UNPACK #-} !Float-  , layoutFontColor :: !(Maybe Color)-  , layoutFontWeight :: !FontWeight-  , layoutFontStyle :: !FontStyle-  , layoutTextDecoration :: !TextDecoration-  }-  deriving (Eq, Show)--defaultLayout :: Layout-defaultLayout =-  Layout-    { layoutDirection = Column-    , layoutWidth = Fit-    , layoutHeight = Fit-    , layoutPadding = Padding 3 3 3 3-    , layoutGap = 8-    , layoutAlignX = AlignStart-    , layoutAlignY = AlignTop-    , layoutMinW = 0-    , layoutMinH = 0-    , layoutMaxW = 1e9-    , layoutMaxH = 1e9-    , layoutFontVariant = FontRegular-    , layoutGridCols = 0-    , layoutGridMinColW = 0-    , layoutFontSize = 0-    , layoutFontColor = Nothing-    , layoutFontWeight = WeightNormal-    , layoutFontStyle = FontStyleNormal-    , layoutTextDecoration = DecorationNone-    }--padAll :: Float -> Layout -> Layout-padAll n l = l {layoutPadding = Padding n n n n}--padXY :: Float -> Float -> Layout -> Layout-padXY x y l = l {layoutPadding = Padding x x y y}--gap :: Float -> Layout -> Layout-gap n l = l {layoutGap = n}--fillW :: Layout -> Layout-fillW l = l {layoutWidth = Grow 1}--fillH :: Layout -> Layout-fillH l = l {layoutHeight = Grow 1}--grow :: Layout -> Layout-grow = fillW . fillH--minW :: Float -> Layout -> Layout-minW n l = l {layoutMinW = n}--maxW :: Float -> Layout -> Layout-maxW n l = l {layoutMaxW = n}--fixedW :: Float -> Layout -> Layout-fixedW n l = l {layoutWidth = Fixed n, layoutMinW = n, layoutMaxW = n}--minH :: Float -> Layout -> Layout-minH n l = l {layoutMinH = n}--maxH :: Float -> Layout -> Layout-maxH n l = l {layoutMaxH = n}--fixedH :: Float -> Layout -> Layout-fixedH n l = l {layoutHeight = Fixed n}--fixedWH :: Float -> Float -> Layout -> Layout-fixedWH w h l = l {layoutWidth = Fixed w, layoutHeight = Fixed h}--alignMid :: Layout -> Layout-alignMid l = l {layoutAlignY = AlignMiddle}--alignEnd :: Layout -> Layout-alignEnd l = l {layoutAlignX = AlignEnd}--tight :: Layout -> Layout-tight l = l {layoutPadding = Padding 0 0 0 0}--percent :: Float -> Layout -> Layout-percent p l = l {layoutWidth = Percent p}--gridMinColW :: Float -> Layout -> Layout-gridMinColW w l = l {layoutGridMinColW = max 0 w}--fixedAspectW :: Float -> Float -> Layout -> Layout-fixedAspectW w ratio = fixedWH w (w / ratio)--fixedAspectH :: Float -> Float -> Layout -> Layout-fixedAspectH h ratio = fixedWH (h * ratio) h--gridCols :: Int -> Layout -> Layout-gridCols n l = l {layoutGridCols = max 0 n}--fontRegular :: Layout -> Layout-fontRegular l = l {layoutFontVariant = FontRegular}--fontHeading :: Layout -> Layout-fontHeading l = l {layoutFontVariant = FontHeading}--fontMuted :: Layout -> Layout-fontMuted l = l {layoutFontVariant = FontMuted}--fontMono :: Layout -> Layout-fontMono l = l {layoutFontVariant = FontMono}--fontDanger :: Layout -> Layout-fontDanger l = l {layoutFontVariant = FontDanger}--fontSize :: Float -> Layout -> Layout-fontSize sz l = l {layoutFontSize = max 0 sz}--fontSizeScale :: Float -> Layout -> Layout-fontSizeScale s l =-  let cur = layoutFontSize l-      sz = if cur > 0 then cur * s else 16 * s-   in l {layoutFontSize = max 0 sz}--fontColor :: Color -> Layout -> Layout-fontColor col l = l {layoutFontColor = Just col}--fontWeight :: FontWeight -> Layout -> Layout-fontWeight w l = l {layoutFontWeight = w}--fontBold :: Layout -> Layout-fontBold = fontWeight WeightBold--fontLight :: Layout -> Layout-fontLight = fontWeight WeightLight--fontMedium :: Layout -> Layout-fontMedium = fontWeight WeightMedium--fontSemiBold :: Layout -> Layout-fontSemiBold = fontWeight WeightSemiBold--fontExtraBold :: Layout -> Layout-fontExtraBold = fontWeight WeightExtraBold--fontBlack :: Layout -> Layout-fontBlack = fontWeight WeightBlack--fontStyle :: FontStyle -> Layout -> Layout-fontStyle s l = l {layoutFontStyle = s}--fontItalic :: Layout -> Layout-fontItalic = fontStyle FontStyleItalic--fontOblique :: Layout -> Layout-fontOblique = fontStyle FontStyleOblique--textDecoration :: TextDecoration -> Layout -> Layout-textDecoration d l = l {layoutTextDecoration = d}--fontUnderline :: Layout -> Layout-fontUnderline l =-  let newDeco = case layoutTextDecoration l of-        DecorationStrikethrough -> DecorationUnderlineStrike-        DecorationUnderlineStrike -> DecorationUnderlineStrike-        _ -> DecorationUnderline-   in l {layoutTextDecoration = newDeco}--fontStrike :: Layout -> Layout-fontStrike l =-  let newDeco = case layoutTextDecoration l of-        DecorationUnderline -> DecorationUnderlineStrike-        DecorationUnderlineStrike -> DecorationUnderlineStrike-        _ -> DecorationStrikethrough-   in l {layoutTextDecoration = newDeco}--alignStart :: Layout -> Layout-alignStart l = l {layoutAlignX = AlignStart}--alignCenter :: Layout -> Layout-alignCenter l = l {layoutAlignX = AlignCenter}--alignTop :: Layout -> Layout-alignTop l = l {layoutAlignY = AlignTop}--alignBottom :: Layout -> Layout-alignBottom l = l {layoutAlignY = AlignBottom}---- | Sit on the row's shared text baseline, so labels of different sizes read--- as one line of type. 'alignBottom' lines up their boxes instead, and a larger--- font's deeper descent lifts its baseline above the smaller one's.-alignBaseline :: Layout -> Layout-alignBaseline l = l {layoutAlignY = AlignBaseline}--data Style = Style-  { styleBg :: {-# UNPACK #-} !Color-  , styleFg :: {-# UNPACK #-} !Color-  , styleBorder :: {-# UNPACK #-} !Color-  , styleBorderWidth :: {-# UNPACK #-} !Float-  , styleCornerRadius :: {-# UNPACK #-} !Float-  , styleHoverBg :: {-# UNPACK #-} !Color-  , styleActiveBg :: {-# UNPACK #-} !Color-  }-  deriving (Eq, Show)--data Theme = Theme-  { themeWindow :: {-# UNPACK #-} !Color-  , themePanel :: !Style-  , themeFloatingWindow :: !Style-  , themeButton :: !Style-  , themeInput :: !Style-  , themeSeparator :: {-# UNPACK #-} !Color-  , themeAccent :: {-# UNPACK #-} !Color-  , themeMuted :: {-# UNPACK #-} !Color-  , themeRed :: {-# UNPACK #-} !Color-  , themeOrange :: {-# UNPACK #-} !Color-  , themeYellow :: {-# UNPACK #-} !Color-  , themeGreen :: {-# UNPACK #-} !Color-  , themePurple :: {-# UNPACK #-} !Color-  , themeOverlayDim :: {-# UNPACK #-} !Color-  , themeOnAccent :: {-# UNPACK #-} !Color-  -- ^ Text and marks drawn on an accent fill: a checked box, an active tab,-  -- a primary button.-  , themeSelection :: {-# UNPACK #-} !Color-  -- ^ Selected text's highlight, drawn under the text. Usually translucent.-  , themeFocusRing :: {-# UNPACK #-} !Color-  , themeLink :: {-# UNPACK #-} !Color-  , themeShadow :: {-# UNPACK #-} !Color-  -- ^ Offset shadow under menus, dropdowns and floating windows. A zero alpha-  -- draws none.-  , themeDisabledFade :: {-# UNPACK #-} !Float-  -- ^ How far a disabled widget's colours fade toward the window colour, from-  -- 0 (not at all) to 1 (invisible).-  }-  deriving (Eq, Show)---- -------------------------------------------------------------------------------- Style and theme modifiers--- --------------------------------------------------------------------------------- $modifiers--- Styles and themes change the way layouts do: through functions that--- compose with @(.)@. A @Style -> Style@ edits one surface, and a--- @Theme -> Theme@ edits the theme a part of the view is drawn with (see--- @styled@ in "NanoUI"):------ > styled (buttonStyle (cornerRadius 8) . accentColor teal) $ do ...--- > styled primary (button "Save")--background :: Color -> Style -> Style-background c s = s {styleBg = c}--foreground :: Color -> Style -> Style-foreground c s = s {styleFg = c}--borderColor :: Color -> Style -> Style-borderColor c s = s {styleBorder = c}--borderWidth :: Float -> Style -> Style-borderWidth w s = s {styleBorderWidth = max 0 w}--cornerRadius :: Float -> Style -> Style-cornerRadius r s = s {styleCornerRadius = max 0 r}--hoverBackground :: Color -> Style -> Style-hoverBackground c s = s {styleHoverBg = c}--pressBackground :: Color -> Style -> Style-pressBackground c s = s {styleActiveBg = c}---- | A background with hover and press shades derived from it: hovering mixes--- in some of the foreground, pressing darkens.-fillColor :: Color -> Style -> Style-fillColor c s =-  s-    { styleBg = c-    , styleHoverBg = lerpColor c (styleFg s) 0.12-    , styleActiveBg = lerpColor c (colorRGBA 0 0 0 (colorA c)) 0.18-    }--buttonStyle :: (Style -> Style) -> Theme -> Theme-buttonStyle f t = t {themeButton = f (themeButton t)}---- | Text fields, text areas, sliders' wells and scroller wells.-inputStyle :: (Style -> Style) -> Theme -> Theme-inputStyle f t = t {themeInput = f (themeInput t)}---- | Panels, cards, menus, and label text.-panelStyle :: (Style -> Style) -> Theme -> Theme-panelStyle f t = t {themePanel = f (themePanel t)}---- | Floating windows.-windowStyle :: (Style -> Style) -> Theme -> Theme-windowStyle f t = t {themeFloatingWindow = f (themeFloatingWindow t)}--everyStyle :: (Style -> Style) -> Theme -> Theme-everyStyle f = buttonStyle f . inputStyle f . panelStyle f . windowStyle f--accentColor :: Color -> Theme -> Theme-accentColor c t = t {themeAccent = c, themeFocusRing = c, themeSelection = fadeAlpha c (colorA (themeSelection t))}---- | The foreground of every surface.-textColor :: Color -> Theme -> Theme-textColor c = everyStyle (foreground c)--mutedColor :: Color -> Theme -> Theme-mutedColor c t = t {themeMuted = c}--linkColor :: Color -> Theme -> Theme-linkColor c t = t {themeLink = c}--selectionColor :: Color -> Theme -> Theme-selectionColor c t = t {themeSelection = c}---- | The backdrop behind everything, which disabled widgets also fade toward.-windowColor :: Color -> Theme -> Theme-windowColor c t = t {themeWindow = c}---- | The corner radius of every surface.-rounded :: Float -> Theme -> Theme-rounded r = everyStyle (cornerRadius r)---- | Buttons filled with a colour picked from the theme, with a readable label.------ > styled (tinted themePurple) (button "Tag")-tinted :: (Theme -> Color) -> Theme -> Theme-tinted pick t =-  let c = pick t-      label = readableOn t c-   in buttonStyle-        ( \s ->-            s-              { styleBg = c-              , styleFg = label-              , styleBorder = c-              , styleHoverBg = lerpColor c label 0.14-              , styleActiveBg = lerpColor c (themeWindow t) 0.22-              }-        )-        t---- | Buttons in the accent colour, for the action a view is for.-primary :: Theme -> Theme-primary = tinted themeAccent---- | Buttons in the theme's red, for destructive actions.-destructive :: Theme -> Theme-destructive = tinted themeRed--success :: Theme -> Theme-success = tinted themeGreen---- | Buttons without a fill or border until hovered, for toolbars and--- secondary actions.-subtle :: Theme -> Theme-subtle =-  buttonStyle $ \s ->-    s-      { styleBg = clear-      , styleBorder = clear-      , styleBorderWidth = 0-      , styleHoverBg = fadeAlpha (styleFg s) 30-      , styleActiveBg = fadeAlpha (styleFg s) 48-      }-  where-    clear = colorRGBA 0 0 0 0---- | Whichever of the theme's text colours reads best on @c@.-readableOn :: Theme -> Color -> Color-readableOn t c =-  let candidates = [themeOnAccent t, styleFg (themePanel t), themeWindow t]-      best a b = if contrastRatio a c >= contrastRatio b c then a else b-   in foldr1 best candidates---- | The theme disabled widgets are drawn with: every colour faded toward the--- window colour by 'themeDisabledFade', and no hover or press feedback.-disabledTheme :: Theme -> Theme-disabledTheme t =-  let f = themeDisabledFade t-      fade c-        | colorA c == 0 = c-        | otherwise = fadeAlpha (lerpColor c (themeWindow t) f) (colorA c)-      fadeStyle s =-        let bg = fade (styleBg s)-         in s {styleBg = bg, styleFg = fade (styleFg s), styleBorder = fade (styleBorder s), styleHoverBg = bg, styleActiveBg = bg}-   in t-        { themePanel = fadeStyle (themePanel t)-        , themeFloatingWindow = fadeStyle (themeFloatingWindow t)-        , themeButton = fadeStyle (themeButton t)-        , themeInput = fadeStyle (themeInput t)-        , themeSeparator = fade (themeSeparator t)-        , themeAccent = fade (themeAccent t)-        , themeMuted = fade (themeMuted t)-        , themeRed = fade (themeRed t)-        , themeOrange = fade (themeOrange t)-        , themeYellow = fade (themeYellow t)-        , themeGreen = fade (themeGreen t)-        , themePurple = fade (themePurple t)-        , themeOnAccent = fade (themeOnAccent t)-        , themeFocusRing = fade (themeFocusRing t)-        , themeLink = fade (themeLink t)-        }---- | Flat widget style: bg/fg/border plus hover and active fills.--- Border width 1 and corner radius 2, as the built-in themes use.-flatStyle :: Color -> Color -> Color -> Color -> Color -> Style-flatStyle bg fg border hoverBg activeBg =-  Style-    { styleBg = bg-    , styleFg = fg-    , styleBorder = border-    , styleBorderWidth = 1-    , styleCornerRadius = 2-    , styleHoverBg = hoverBg-    , styleActiveBg = activeBg-    }---- | Neutral charcoal surfaces, warm text, and a blue selection accent.--- Keep structural edges quiet; interactive borders and focus carry contrast.-defaultTheme :: Theme-defaultTheme =-  let panelSurface =-        flatStyle-          (colorRGBA 34 34 38 255)-          (colorRGBA 236 234 230 255)-          (colorRGBA 54 54 62 255)-          (colorRGBA 34 34 38 255)-          (colorRGBA 30 30 34 255)-   in Theme-        { themeWindow = colorRGBA 24 24 27 255-        , themePanel = panelSurface-        , themeFloatingWindow = panelSurface-        , themeButton =-            flatStyle-              (colorRGBA 52 52 58 255)-              (colorRGBA 248 247 245 255)-              (colorRGBA 74 76 84 255)-              (colorRGBA 68 70 78 255)-              (colorRGBA 42 42 48 255)-        , themeInput =-            flatStyle-              (colorRGBA 18 18 21 255)-              (colorRGBA 236 234 230 255)-              (colorRGBA 70 72 80 255)-              (colorRGBA 24 24 28 255)-              (colorRGBA 14 14 17 255)-        , themeSeparator = colorRGBA 62 64 72 255-        , themeAccent = colorRGBA 88 156 246 255-        , themeMuted = colorRGBA 176 172 164 255-        , themeRed = colorRGBA 252 165 165 255-        , themeOrange = colorRGBA 216 140 72 255-        , themeYellow = colorRGBA 212 176 88 255-        , themeGreen = colorRGBA 104 168 124 255-        , themePurple = colorRGBA 176 140 220 255-        , themeOverlayDim = colorRGBA 8 8 10 176-        , themeOnAccent = colorRGBA 255 255 255 255-        , themeSelection = fadeAlpha (colorRGBA 88 156 246 255) 115-        , themeFocusRing = colorRGBA 88 156 246 255-        , themeLink = colorRGBA 124 178 250 255-        , themeShadow = colorRGBA 0 0 0 72-        , themeDisabledFade = 0.55-        }---- Status and series colours in hue order, then accent.-themeSeries :: Theme -> [Color]-themeSeries t =-  [ themeRed t-  , themeOrange t-  , themeYellow t-  , themeGreen t-  , themeAccent t-  , themePurple t-  ]---- | Opaque tint of a base surface toward the separator color: the track color--- for scrollbar tracks, divider strips, and similar hairline chrome.-separatorTrackColor :: Style -> Theme -> Color-separatorTrackColor base theme =-  lerpColor (styleBg base) (themeSeparator theme) 0.28---- Scroll track/thumb tints. The track is an opaque mix of the surface it sits--- on (the scroller well / floating window body) toward the separator colour, so--- the lane reads against that surface on every theme. The thumb stays a--- translucent foreground mix so the track shows through it.-scrollBarTrackColor :: Style -> Theme -> Color-scrollBarTrackColor base theme =-  separatorTrackColor base theme--scrollBarThumbColor :: Style -> Theme -> Color-scrollBarThumbColor base theme =-  let solid = lerpColor (themeSeparator theme) (styleFg base) 0.58-   in fadeAlpha solid 130---- | Replaces the alpha channel of a color.-fadeAlpha :: Color -> Word8 -> Color-fadeAlpha (Color w) a = Color ((w .&. 0xFFFFFF00) .|. fromIntegral a)---- | Ported from "Tomorrow Night Min" in https://github.com/biaqat/tomorrow-min-theme-zed-tomorrowNightMinDarkTheme :: Theme-tomorrowNightMinDarkTheme =-  let panelSurface =-        flatStyle-          (colorRGBA 30 31 33 255)  -- base.bg #1E1F21 (elevated panel canvas)-          (colorRGBA 234 234 234 255)  -- bright.fg #EAEAEA-          edgeCol-          (colorRGBA 52 54 62 255)  -- #34363E-          (colorRGBA 26 27 29 255)  -- #1A1B1D-   in Theme-        { themeWindow = colorRGBA 23 24 26 255         -- #17181A (dark root window backdrop)-        , themePanel = panelSurface-        , themeFloatingWindow = panelSurface-        , themeButton =-            flatStyle-              (colorRGBA 44 46 51 255)  -- elevated button surface-              (colorRGBA 245 245 245 255)  -- bright.fg / white-              edgeCol-              (colorRGBA 69 74 83 255)  -- #454A53-              (colorRGBA 28 29 32 255)  -- depressed on click-        , themeInput =-            flatStyle-              (colorRGBA 23 24 26 255)  -- #17181A (recessed into #1E1F21 panel)-              (colorRGBA 234 234 234 255)  -- bright.fg #EAEAEA-              edgeCol-              (colorRGBA 29 30 33 255)-              (colorRGBA 19 20 22 255)-        , themeSeparator = sepCol-        , themeAccent = accentCol-        , themeMuted = colorRGBA 150 152 150 255       -- comment #969896-        , themeRed = colorRGBA 204 102 102 255         -- base.red #CC6666-        , themeOrange = colorRGBA 222 147 95 255       -- base.orange #DE935F-        , themeYellow = colorRGBA 240 198 116 255      -- base.yellow #F0C674-        , themeGreen = colorRGBA 181 189 104 255       -- base.green #B5BD68-        , themePurple = colorRGBA 178 148 187 255      -- base.purple #B294BB-        , themeOverlayDim = colorRGBA 0 0 0 160-        , themeOnAccent = colorRGBA 255 255 255 255-        , themeSelection = fadeAlpha accentCol 115-        , themeFocusRing = accentCol-        , themeLink = accentCol-        , themeShadow = colorRGBA 0 0 0 72-        , themeDisabledFade = 0.55-        }-  where-  edgeCol    = colorRGBA 77 80 87 255              -- window #4D5057 (touch brighter crisp border)-  sepCol = colorRGBA 55 59 65 255              -- base.selection #373B41 (subtle divider)-  accentCol    = colorRGBA 103 150 230 255           -- vscode.cornflower_blue #6796E6---- | Ported from "Tomorrow Min" in https://github.com/biaqat/tomorrow-min-theme-zed-tomorrowMinLightTheme :: Theme-tomorrowMinLightTheme =-  let panelSurface =-        flatStyle-          (colorRGBA 242 242 242 255)  -- #F2F2F2-          (colorRGBA 55 59 65 255)  -- #373B41-          (colorRGBA 222 222 222 255)  -- #DEDEDE-          (colorRGBA 231 231 231 255)  -- #E7E7E7 (darker than #F2F2F2 so hover reads)-          (colorRGBA 219 219 219 255)  -- #DBDBDB-   in Theme-        { themeWindow = colorRGBA 255 255 255 255     -- #FFFFFF-        , themePanel = panelSurface-        , themeFloatingWindow = panelSurface-        , themeButton =-            flatStyle-              (colorRGBA 232 232 232 255)  -- #E8E8E8 (step down from panel for zebra rows)-              (colorRGBA 55 59 65 255)  -- #373B41-              (colorRGBA 214 214 214 255)  -- #D6D6D6-              (colorRGBA 214 214 214 255)  -- #D6D6D6-              (colorRGBA 196 196 196 255)  -- #C4C4C4-        , themeInput =-            flatStyle-              (colorRGBA 255 255 255 255)  -- #FFFFFF-              (colorRGBA 55 59 65 255)-              (colorRGBA 210 210 210 255)-              (colorRGBA 243 243 243 255)  -- #F3F3F3 (darker than white so hover reads)-              (colorRGBA 255 255 255 255)  -- focus keeps the normal white bg; accent border signals focus-        , themeSeparator = colorRGBA 222 222 222 255  -- #DEDEDE-        , themeAccent = colorRGBA 82 134 188 255      -- #5286BC (Tomorrow Blue)-        , themeMuted = colorRGBA 140 140 140 255      -- #8C8C8C-        , themeRed = colorRGBA 197 78 82 255          -- Tomorrow Red #C54E52-        , themeOrange = colorRGBA 231 140 69 255      -- Tomorrow Orange #E78C45-        , themeYellow = colorRGBA 231 197 71 255      -- Tomorrow Yellow #E7C547-        , themeGreen = colorRGBA 113 140 0 255        -- Tomorrow Green #718C00-        , themePurple = colorRGBA 137 91 144 255      -- Tomorrow Purple #895B90-        , themeOverlayDim = colorRGBA 0 0 0 100-        , themeOnAccent = colorRGBA 255 255 255 255-        , themeSelection = fadeAlpha (colorRGBA 82 134 188 255) 80-        , themeFocusRing = colorRGBA 82 134 188 255-        , themeLink = colorRGBA 66 113 174 255-        , themeShadow = colorRGBA 0 0 0 36-        , themeDisabledFade = 0.55-        }---- | Ported from "Tomorrow at Midnight Min" in https://github.com/biaqat/tomorrow-min-theme-zed-tomorrowMidnightMinDarkTheme :: Theme-tomorrowMidnightMinDarkTheme =-  let panelSurface =-        flatStyle-          (colorRGBA 16 17 20 255)  -- #101114 (elevated panel canvas)-          (colorRGBA 238 238 238 255)  -- #EEEEEE-          edgeCol-          (colorRGBA 46 48 56 255)  -- #2E3038-          (colorRGBA 12 13 15 255)  -- #0C0D0F-   in Theme-        { themeWindow = colorRGBA 0 0 0 255           -- #000000 (pitch black root window backdrop)-        , themePanel = panelSurface-        , themeFloatingWindow = panelSurface-        , themeButton =-            flatStyle-              (colorRGBA 26 27 34 255)  -- #1A1B22-              (colorRGBA 238 238 238 255)  -- #EEEEEE-              edgeCol-              (colorRGBA 54 58 72 255)  -- #363A48-              (colorRGBA 56 60 81 255)  -- #383C51-        , themeInput =-            flatStyle-              (colorRGBA 13 14 18 255)  -- #0D0E12 (recessed into panel)-              (colorRGBA 238 238 238 255)-              edgeCol-              (colorRGBA 21 22 28 255)-              (colorRGBA 8 9 11 255)-        , themeSeparator = sepCol-        , themeAccent = accentCol-        , themeMuted = colorRGBA 128 132 150 255       -- #808496-        , themeRed = colorRGBA 213 78 83 255           -- bright.red #D54E53-        , themeOrange = colorRGBA 231 140 69 255       -- bright.orange #E78C45-        , themeYellow = colorRGBA 231 197 71 255       -- bright.yellow #E7C547-        , themeGreen = colorRGBA 185 202 74 255        -- bright.green #B9CA4A-        , themePurple = colorRGBA 195 151 216 255      -- bright.purple #C397D8-        , themeOverlayDim = colorRGBA 0 0 0 160-        , themeOnAccent = colorRGBA 255 255 255 255-        , themeSelection = fadeAlpha accentCol 115-        , themeFocusRing = accentCol-        , themeLink = accentCol-        , themeShadow = colorRGBA 0 0 0 96-        , themeDisabledFade = 0.55-        }-  where-  edgeCol    = colorRGBA 48 52 70 255              -- #303446-  sepCol = colorRGBA 48 52 70 255              -- #303446-  accentCol    = colorRGBA 140 182 226 255           -- #8CB6E2---- -------------------------------------------------------------------------------- Base16 Colorschemes--- --------------------------------------------------------------------------------- | Standard Base16 palette containing 16 styling tones and syntax colours--- following Chris Kempson's Base16 specification.-data Base16 = Base16-  { base00 :: {-# UNPACK #-} !Color -- ^ Default Background-  , base01 :: {-# UNPACK #-} !Color -- ^ Lighter Background (status bars, line numbers, panel backgrounds)-  , base02 :: {-# UNPACK #-} !Color -- ^ Selection Background (active elements, subtle highlights)-  , base03 :: {-# UNPACK #-} !Color -- ^ Comments, Invisibles, Line Highlighting (muted text, borders)-  , base04 :: {-# UNPACK #-} !Color -- ^ Dark Foreground (status bar foreground, secondary text)-  , base05 :: {-# UNPACK #-} !Color -- ^ Default Foreground, Caret, Delimiters, Operators-  , base06 :: {-# UNPACK #-} !Color -- ^ Light Foreground-  , base07 :: {-# UNPACK #-} !Color -- ^ Light Background / Highest contrast foreground-  , base08 :: {-# UNPACK #-} !Color -- ^ Variables, XML Tags, Markup Link Text, Markup Lists, Diff Deleted (Red)-  , base09 :: {-# UNPACK #-} !Color -- ^ Integers, Boolean, Constants, XML Attributes, Markup Link Url (Orange)-  , base0A :: {-# UNPACK #-} !Color -- ^ Classes, Markup Bold, Search Text Background (Yellow)-  , base0B :: {-# UNPACK #-} !Color -- ^ Strings, Inherited Class, Markup Code, Diff Inserted (Green)-  , base0C :: {-# UNPACK #-} !Color -- ^ Support, Regular Expressions, Escape Characters, Markup Quotes (Cyan)-  , base0D :: {-# UNPACK #-} !Color -- ^ Functions, Methods, Attribute IDs, Headings (Blue / Primary Accent)-  , base0E :: {-# UNPACK #-} !Color -- ^ Keywords, Storage, Selector, Markup Italic, Diff Changed (Purple / Magenta)-  , base0F :: {-# UNPACK #-} !Color -- ^ Deprecated, Opening/Closing Embedded Language Tags (Brown)-  }-  deriving (Eq, Show)---- | Calculate a 'Theme' from a 'Base16' colorscheme, automatically selecting--- dark or light styling based on background vs foreground luminance.-themeFromBase16 :: Base16 -> Theme-themeFromBase16 b-  | isDark = themeFromBase16Dark b-  | otherwise = themeFromBase16Light b-  where-    isDark = colorLuminance (base00 b) < colorLuminance (base05 b)---- | Calculate a dark 'Theme' from a 'Base16' colorscheme.-themeFromBase16Dark :: Base16 -> Theme-themeFromBase16Dark b =-  let edgeCol = lerpColor (base02 b) (base03 b) 0.35-      panelBg = lerpColor (base01 b) (base02 b) 0.3-      panelSurface =-        flatStyle-          panelBg-          (base05 b)-          edgeCol-          (lerpColor panelBg (base02 b) 0.5)-          (lerpColor panelBg (base00 b) 0.4)-   in Theme-        { themeWindow = base00 b-        , themePanel = panelSurface-        , themeFloatingWindow = panelSurface-        , themeButton =-            flatStyle-              (base02 b)-              (base07 b)-              edgeCol-              (lerpColor (base02 b) (base03 b) 0.4)-              (base01 b)-        , themeInput =-            flatStyle-              (base00 b)-              (base05 b)-              edgeCol-              (base01 b)-              (base00 b)-        , themeSeparator = edgeCol-        , themeAccent = base0D b-        , themeMuted = base03 b-        , themeRed = base08 b-        , themeOrange = base09 b-        , themeYellow = base0A b-        , themeGreen = base0B b-        , themePurple = base0E b-        , themeOverlayDim = colorRGBA 0 0 0 160-        , themeOnAccent = if colorLuminance (base0D b) > 0.6 then base00 b else colorRGBA 255 255 255 255-        , themeSelection = fadeAlpha (base0D b) 115-        , themeFocusRing = base0D b-        , themeLink = base0D b-        , themeShadow = colorRGBA 0 0 0 72-        , themeDisabledFade = 0.55-        }---- | Calculate a light 'Theme' from a 'Base16' colorscheme.-themeFromBase16Light :: Base16 -> Theme-themeFromBase16Light b =-  let edgeCol = base02 b-      panelBg = lerpColor (base00 b) (base01 b) 0.5-      panelSurface =-        flatStyle-          panelBg-          (base05 b)-          edgeCol-          (lerpColor panelBg (base00 b) 0.4)-          (lerpColor panelBg (base02 b) 0.4)-   in Theme-        { themeWindow = base00 b-        , themePanel = panelSurface-        , themeFloatingWindow = panelSurface-        , themeButton =-            flatStyle-              (base01 b)-              (base05 b)-              edgeCol-              (base02 b)-              (lerpColor (base02 b) (base03 b) 0.35)-        , themeInput =-            flatStyle-              (base00 b)-              (base05 b)-              edgeCol-              (lerpColor (base00 b) (base01 b) 0.3)-              (lerpColor (base00 b) (base01 b) 0.6)-        , themeSeparator = edgeCol-        , themeAccent = base0D b-        , themeMuted = base03 b-        , themeRed = base08 b-        , themeOrange = base09 b-        , themeYellow = base0A b-        , themeGreen = base0B b-        , themePurple = base0E b-        , themeOverlayDim = colorRGBA 0 0 0 100-        , themeOnAccent = if colorLuminance (base0D b) > 0.6 then base07 b else colorRGBA 255 255 255 255-        , themeSelection = fadeAlpha (base0D b) 80-        , themeFocusRing = base0D b-        , themeLink = base0D b-        , themeShadow = colorRGBA 0 0 0 36-        , themeDisabledFade = 0.55-        }---- | Tomorrow Night Base16 reference palette.-base16TomorrowNight :: Base16-base16TomorrowNight =-  Base16-    { base00 = colorRGBA 29 31 33 255     -- #1D1F21-    , base01 = colorRGBA 40 42 46 255     -- #282A2E-    , base02 = colorRGBA 55 59 65 255     -- #373B41-    , base03 = colorRGBA 150 152 150 255 -- #969896-    , base04 = colorRGBA 180 183 180 255 -- #B4B7B4-    , base05 = colorRGBA 197 200 198 255 -- #C5C8C6-    , base06 = colorRGBA 224 224 224 255 -- #E0E0E0-    , base07 = colorRGBA 255 255 255 255 -- #FFFFFF-    , base08 = colorRGBA 213 78 83 255   -- #D54E53-    , base09 = colorRGBA 231 140 69 255  -- #E78C45-    , base0A = colorRGBA 231 197 71 255  -- #E7C547-    , base0B = colorRGBA 185 202 74 255  -- #B9CA4A-    , base0C = colorRGBA 112 192 186 255 -- #70C0BA-    , base0D = colorRGBA 103 150 230 255 -- #6796E6-    , base0E = colorRGBA 195 151 216 255 -- #C397D8-    , base0F = colorRGBA 163 104 90 255  -- #A3685A-    }---- | Tomorrow Light Base16 reference palette.-base16TomorrowLight :: Base16-base16TomorrowLight =-  Base16-    { base00 = colorRGBA 255 255 255 255 -- #FFFFFF-    , base01 = colorRGBA 242 242 242 255 -- #F2F2F2-    , base02 = colorRGBA 222 222 222 255 -- #DEDEDE-    , base03 = colorRGBA 140 140 140 255 -- #8C8C8C-    , base04 = colorRGBA 150 152 150 255 -- #969896-    , base05 = colorRGBA 55 59 65 255    -- #373B41-    , base06 = colorRGBA 40 42 46 255    -- #282A2E-    , base07 = colorRGBA 29 31 33 255    -- #1D1F21-    , base08 = colorRGBA 197 78 82 255   -- #C54E52-    , base09 = colorRGBA 231 140 69 255  -- #E78C45-    , base0A = colorRGBA 231 197 71 255  -- #E7C547-    , base0B = colorRGBA 113 140 0 255   -- #718C00-    , base0C = colorRGBA 62 153 159 255  -- #3E999F-    , base0D = colorRGBA 82 134 188 255  -- #5286BC-    , base0E = colorRGBA 137 91 144 255  -- #895B90-    , base0F = colorRGBA 163 104 90 255  -- #A3685A-    }
lib/NanoUI/Svg.hs view
@@ -1,1040 +1,507 @@-{-# LANGUAGE BangPatterns #-}---- | SVG documents for icons: a parser for the static subset icon sets use and--- an anti-aliased rasterizer.------ Supported: @svg@ (with @viewBox@, @width@, @height@), @g@, @path@, @rect@,--- @circle@, @ellipse@, @line@, @polyline@ and @polygon@; the presentation--- attributes @fill@, @stroke@, @stroke-width@, @stroke-linecap@,--- @stroke-linejoin@, @stroke-miterlimit@, @fill-rule@, @opacity@,--- @fill-opacity@ and @stroke-opacity@, also inside @style@; @transform@; and--- colours as names, @#rgb@, @#rrggbb@, @rgb()@ and @currentColor@. Gradients,--- patterns, text, masks, clipping, filters and @use@ are ignored.-module NanoUI.Svg-  ( Svg-  , svgSize-  , svgKey-  , svgMonochrome-  , parseSvg-  , rasterizeSvg-  ) where--import Control.Monad (forM_, unless, when)-import Control.Monad.ST (ST, runST)-import Foreign.Storable (pokeByteOff)-import Data.Bits (xor)-import Data.ByteString (ByteString)-import Data.ByteString qualified as BS-import Data.ByteString.Internal qualified as BSI-import Data.Char (isAlpha, isDigit, isSpace, toLower)-import Data.Maybe (fromMaybe, mapMaybe)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Text.Encoding qualified as TE-import Data.Text.Read qualified as TR-import Text.XML.Hexml qualified as Hexml-import Data.Primitive.PrimArray (MutablePrimArray, PrimArray, copyMutablePrimArray, indexPrimArray, newPrimArray, readPrimArray, setPrimArray, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)-import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray, smallArrayFromList)-import Data.Word (Word8)-import NanoUI.Types (Color (..), clamp01, colorA, colorB, colorG, colorR, colorRGBA)---- | A parsed SVG document.-data Svg = Svg-  { svgViewBox :: !Box-  , svgSize :: !(Float, Float)-  -- ^ The document's own width and height, from its @width@ and @height@ or-  -- else its @viewBox@.-  , svgShapes :: !(SmallArray Shape)-  , svgKey :: !Int-  -- ^ A hash of the source, for caching rasters.-  , svgMonochrome :: !Bool-  -- ^ Every paint is @currentColor@ or unspecified, so the drawing is one-  -- colour and can be tinted.-  }---- | Documents are equal when their sources hash the same.-instance Eq Svg where-  a == b = svgKey a == svgKey b--instance Show Svg where-  show doc = "<svg " <> show (svgSize doc) <> ">"--data Box = Box !Float !Float !Float !Float--data Paint = PaintNone | PaintCurrent | PaintColor !Color-  deriving (Eq)--data FillRule = NonZero | EvenOdd-  deriving (Eq)--data LineCap = CapButt | CapRound | CapSquare-  deriving (Eq)--data LineJoin = JoinMiter | JoinRound | JoinBevel-  deriving (Eq)---- | Presentation state inherited from ancestors.-data PaintStyle = PaintStyle-  { psFill :: !(Maybe Paint)-  , psStroke :: !(Maybe Paint)-  , psStrokeWidth :: !Float-  , psCap :: !LineCap-  , psJoin :: !LineJoin-  , psMiterLimit :: !Float-  , psRule :: !FillRule-  , psOpacity :: !Float-  , psFillOpacity :: !Float-  , psStrokeOpacity :: !Float-  }---- | Segments, the transform to user space, and the paint.-data Shape = Shape !(SmallArray Segment) !Matrix !PaintStyle--shapeStyle :: Shape -> PaintStyle-shapeStyle (Shape _ _ style) = style--data Segment-  = MoveTo !P-  | LineTo !P-  | CubicTo !P !P !P-  | QuadTo !P !P-  | ArcTo !Float !Float !Float !Bool !Bool !P-  | ClosePath--data P = P {-# UNPACK #-} !Float {-# UNPACK #-} !Float---- | @a c e / b d f@, mapping @(x, y)@ to @(a x + c y + e, b x + d y + f)@.-data Matrix = Matrix !Float !Float !Float !Float !Float !Float--identity :: Matrix-identity = Matrix 1 0 0 1 0 0--mul :: Matrix -> Matrix -> Matrix-mul (Matrix a b c d e f) (Matrix a' b' c' d' e' f') =-  Matrix-    (a * a' + c * b')-    (b * a' + d * b')-    (a * c' + c * d')-    (b * c' + d * d')-    (a * e' + c * f' + e)-    (b * e' + d * f' + f)--apply :: Matrix -> P -> P-apply (Matrix a b c d e f) (P x y) = P (a * x + c * y + e) (b * x + d * y + f)------------------------------------------------------------------------------------- XML-----------------------------------------------------------------------------------data Element = Element !Text ![(Text, Text)] ![Element]---- | The elements of a document, by hexml. Text, comments and processing--- instructions are not elements; a DOCTYPE, which hexml rejects, is blanked--- out first.-parseElements :: Text -> Either String [Element]-parseElements src =-  case Hexml.parse (withoutDoctype (TE.encodeUtf8 src)) of-    Left err -> Left (T.unpack (TE.decodeUtf8Lenient err))-    Right doc -> Right (map element (Hexml.children doc))-  where-    element node =-      Element-        (localName (TE.decodeUtf8Lenient (Hexml.name node)))-        [ (localName (TE.decodeUtf8Lenient (Hexml.attributeName a)), decodeEntities (TE.decodeUtf8Lenient (Hexml.attributeValue a)))-        | a <- Hexml.attributes node-        ]-        (map element (Hexml.children node))-    localName n = T.takeWhileEnd (/= ':') n---- | The document with its DOCTYPE, internal subset included, replaced by--- spaces, so positions in parse errors still match the source.-withoutDoctype :: ByteString -> ByteString-withoutDoctype bytes =-  case BS.breakSubstring "<!DOCTYPE" bytes of-    (_, rest) | BS.null rest -> bytes-    (before, rest) ->-      let close !depth !k-            | k >= BS.length rest = k-            | otherwise = case BS.index rest k of-                91 -> close (depth + 1 :: Int) (k + 1)-                93 -> close (depth - 1) (k + 1)-                62 | depth <= 0 -> k + 1-                _ -> close depth (k + 1)-          end = close 0 0-       in before <> BS.replicate end 32 <> BS.drop end rest--decodeEntities :: Text -> Text-decodeEntities =-  T.replace "&amp;" "&" . T.replace "&lt;" "<" . T.replace "&gt;" ">" . T.replace "&quot;" "\"" . T.replace "&apos;" "'"------------------------------------------------------------------------------------- Document------------------------------------------------------------------------------------- | Parse an SVG document.-parseSvg :: Text -> Either String Svg-parseSvg src = do-  els <- parseElements src-  root <- case [e | e@(Element n _ _) <- els, n == "svg"] of-    r : _ -> Right r-    [] -> Left "no svg element"-  let Element _ attrs _ = root-      attr k = lookup k attrs-      box = case attr "viewBox" >>= numbers4 of-        Just (x, y, w, h) | w > 0 && h > 0 -> Box x y w h-        _ -> Box 0 0 (fromMaybe 24 (attr "width" >>= length1)) (fromMaybe 24 (attr "height" >>= length1))-      Box _ _ bw bh = box-      width = fromMaybe bw (attr "width" >>= length1)-      height = fromMaybe bh (attr "height" >>= length1)-      shapes = collect identity defaultStyle root-      -- Unspecified paints and currentColor follow the tint; an explicit-      -- colour anywhere makes the drawing multicoloured.-      monochromePaint p = case p of-        Just (PaintColor _) -> False-        _ -> True-  pure-    Svg-      { svgViewBox = box-      , svgSize = (width, height)-      , svgShapes = smallArrayFromList shapes-      , svgKey = T.foldl' (\h c -> (h * 16777619) `xor` fromEnum c) 2166136261 src-      , svgMonochrome = all (\sh -> monochromePaint (psFill (shapeStyle sh)) && monochromePaint (psStroke (shapeStyle sh))) shapes-      }-  where-    numbers4 t = case numberList t of-      [a, b, c, d] -> Just (a, b, c, d)-      _ -> Nothing--defaultStyle :: PaintStyle-defaultStyle =-  PaintStyle-    { psFill = Nothing-    , psStroke = Just PaintNone-    , psStrokeWidth = 1-    , psCap = CapButt-    , psJoin = JoinMiter-    , psMiterLimit = 4-    , psRule = NonZero-    , psOpacity = 1-    , psFillOpacity = 1-    , psStrokeOpacity = 1-    }---- | Shapes in document order, each with its full transform and style.-collect :: Matrix -> PaintStyle -> Element -> [Shape]-collect m0 style0 (Element name attrs children) =-  let props = attrs ++ styleProperties (fromMaybe "" (lookup "style" attrs))-      m = maybe m0 (mul m0 . parseTransform) (lookup "transform" attrs)-      -- Opacity multiplies down the tree; the other properties replace.-      style = (applyProperties props style0) {psOpacity = psOpacity style0 * maybe 1 clamp01 (lookup "opacity" props >>= number1)}-      shape segs = [Shape (smallArrayFromList segs) m style]-      num k = fromMaybe 0 (lookup k attrs >>= length1)-   in case name of-        "svg" -> concatMap (collect m style) children-        "g" -> concatMap (collect m style) children-        "a" -> concatMap (collect m style) children-        "path" -> shape (parsePath (fromMaybe "" (lookup "d" attrs)))-        "rect" -> shape (rectSegments (num "x") (num "y") (num "width") (num "height") (lookup "rx" attrs >>= length1) (lookup "ry" attrs >>= length1))-        "circle" -> shape (ellipseSegments (num "cx") (num "cy") (num "r") (num "r"))-        "ellipse" -> shape (ellipseSegments (num "cx") (num "cy") (num "rx") (num "ry"))-        "line" -> shape [MoveTo (P (num "x1") (num "y1")), LineTo (P (num "x2") (num "y2"))]-        "polyline" -> shape (polySegments False (fromMaybe "" (lookup "points" attrs)))-        "polygon" -> shape (polySegments True (fromMaybe "" (lookup "points" attrs)))-        _ -> []--styleProperties :: Text -> [(Text, Text)]-styleProperties =-  mapMaybe-    ( \decl -> case T.breakOn ":" decl of-        (k, v) | not (T.null v) -> Just (T.strip k, T.strip (T.drop 1 v))-        _ -> Nothing-    )-    . T.splitOn ";"--applyProperties :: [(Text, Text)] -> PaintStyle -> PaintStyle-applyProperties props s0 = foldl step s0 props-  where-    step s (k, v) = case k of-      "fill" -> s {psFill = Just (parsePaint v)}-      "stroke" -> s {psStroke = Just (parsePaint v)}-      "stroke-width" -> maybe s (\w -> s {psStrokeWidth = max 0 w}) (length1 v)-      "stroke-linecap" -> case v of-        "round" -> s {psCap = CapRound}-        "square" -> s {psCap = CapSquare}-        _ -> s {psCap = CapButt}-      "stroke-linejoin" -> case v of-        "round" -> s {psJoin = JoinRound}-        "bevel" -> s {psJoin = JoinBevel}-        _ -> s {psJoin = JoinMiter}-      "stroke-miterlimit" -> maybe s (\l -> s {psMiterLimit = max 1 l}) (number1 v)-      "fill-rule" -> s {psRule = if v == "evenodd" then EvenOdd else NonZero}-      "fill-opacity" -> maybe s (\o -> s {psFillOpacity = clamp01 o}) (number1 v)-      "stroke-opacity" -> maybe s (\o -> s {psStrokeOpacity = clamp01 o}) (number1 v)-      _ -> s---parsePaint :: Text -> Paint-parsePaint raw-  | v == "none" || v == "transparent" = PaintNone-  | v == "currentcolor" = PaintCurrent-  | Just hex <- T.stripPrefix "#" v = maybe PaintNone PaintColor (hexColor hex)-  | Just args <- T.stripPrefix "rgb(" v = case numberList (T.takeWhile (/= ')') args) of-      [r, g, b] -> PaintColor (colorRGBA (channel r) (channel g) (channel b) 255)-      _ -> PaintNone-  | otherwise = maybe (PaintColor (colorRGBA 0 0 0 255)) PaintColor (lookup v namedColors)-  where-    v = T.toLower (T.strip raw)-    channel x = fromIntegral (max 0 (min 255 (round x :: Int)))-    hexColor h = case T.unpack h of-      [r, g, b] -> rgb (hex2 r r) (hex2 g g) (hex2 b b)-      [r1, r2, g1, g2, b1, b2] -> rgb (hex2 r1 r2) (hex2 g1 g2) (hex2 b1 b2)-      _ -> Nothing-    rgb (Just r) (Just g) (Just b) = Just (colorRGBA r g b 255)-    rgb _ _ _ = Nothing-    hex2 a b = (\x y -> fromIntegral (x * 16 + y)) <$> hexDigit a <*> hexDigit b-    hexDigit c-      | isDigit c = Just (fromEnum c - fromEnum '0')-      | c >= 'a' && c <= 'f' = Just (fromEnum c - fromEnum 'a' + 10)-      | otherwise = Nothing--namedColors :: [(Text, Color)]-namedColors =-  [ ("black", colorRGBA 0 0 0 255)-  , ("white", colorRGBA 255 255 255 255)-  , ("red", colorRGBA 255 0 0 255)-  , ("green", colorRGBA 0 128 0 255)-  , ("lime", colorRGBA 0 255 0 255)-  , ("blue", colorRGBA 0 0 255 255)-  , ("yellow", colorRGBA 255 255 0 255)-  , ("orange", colorRGBA 255 165 0 255)-  , ("purple", colorRGBA 128 0 128 255)-  , ("gray", colorRGBA 128 128 128 255)-  , ("grey", colorRGBA 128 128 128 255)-  , ("silver", colorRGBA 192 192 192 255)-  , ("navy", colorRGBA 0 0 128 255)-  , ("teal", colorRGBA 0 128 128 255)-  , ("maroon", colorRGBA 128 0 0 255)-  , ("olive", colorRGBA 128 128 0 255)-  , ("aqua", colorRGBA 0 255 255 255)-  , ("cyan", colorRGBA 0 255 255 255)-  , ("fuchsia", colorRGBA 255 0 255 255)-  , ("magenta", colorRGBA 255 0 255 255)-  ]------------------------------------------------------------------------------------- Numbers, transforms and path data------------------------------------------------------------------------------------- | Numbers separated by spaces or commas, stopping at the first thing that--- is not a number.-numberList :: Text -> [Float]-numberList t0 = go (skipSep t0)-  where-    go t = case readNumber t of-      Just (x, rest) -> x : go (skipSep rest)-      Nothing -> []--skipSep :: Text -> Text-skipSep = T.dropWhile (\c -> isSpace c || c == ',')---- | A number at the start of the text, allowing @.5@, @-.5e-3@ and a--- following number that starts with a sign or a second decimal point.-readNumber :: Text -> Maybe (Float, Text)-readNumber t =-  let (sign, t1) = case T.uncons t of-        Just (c, r) | c == '-' || c == '+' -> (T.singleton c, r)-        _ -> (T.empty, t)-      intPart = T.takeWhile isDigit t1-      afterInt = T.drop (T.length intPart) t1-      (fracPart, afterFrac) = case T.uncons afterInt of-        Just ('.', r) -> let ds = T.takeWhile isDigit r in (T.cons '.' ds, T.drop (T.length ds) r)-        _ -> (T.empty, afterInt)-      (expPart, rest) = case T.uncons afterFrac of-        Just (e, r)-          | e == 'e' || e == 'E' ->-              let (esign, r1) = case T.uncons r of-                    Just (c, r') | c == '-' || c == '+' -> (T.singleton c, r')-                    _ -> (T.empty, r)-                  eds = T.takeWhile isDigit r1-               in if T.null eds then (T.empty, afterFrac) else (T.concat ["e", esign, eds], T.drop (T.length eds) r1)-        _ -> (T.empty, afterFrac)-      mantissa = intPart <> fracPart-   in if T.null (T.filter isDigit mantissa)-        then Nothing-        else case TR.signed TR.rational (T.concat [sign, if T.null intPart then "0" else "", mantissa, expPart]) of-          Right (x, _) -> Just (realToFrac (x :: Double), rest)-          Left _ -> Nothing--number1 :: Text -> Maybe Float-number1 t = fst <$> readNumber (T.strip t)---- | A length in user units: a number with an optional @px@. Percentages and--- other units are not lengths here.-length1 :: Text -> Maybe Float-length1 t = case readNumber (T.strip t) of-  Just (x, rest) | T.null rest || rest == "px" -> Just x-  _ -> Nothing--parseTransform :: Text -> Matrix-parseTransform t0 = go identity (T.stripStart t0)-  where-    go m t-      | T.null t = m-      | otherwise =-          let (name, rest) = T.span isAlpha t-              (args, rest') = T.breakOn ")" (T.drop 1 (T.dropWhile (/= '(') rest))-              next = T.dropWhile (\c -> isSpace c || c == ',') (T.drop 1 rest')-              m' = case (name, numberList args) of-                ("matrix", [a, b, c, d, e, f]) -> Matrix a b c d e f-                ("translate", [x]) -> Matrix 1 0 0 1 x 0-                ("translate", [x, y]) -> Matrix 1 0 0 1 x y-                ("scale", [s]) -> Matrix s 0 0 s 0 0-                ("scale", [sx, sy]) -> Matrix sx 0 0 sy 0 0-                ("rotate", [a]) -> rotation a-                ("rotate", [a, cx, cy]) -> Matrix 1 0 0 1 cx cy `mul` rotation a `mul` Matrix 1 0 0 1 (-cx) (-cy)-                ("skewX", [a]) -> Matrix 1 0 (tan (a * pi / 180)) 1 0 0-                ("skewY", [a]) -> Matrix 1 (tan (a * pi / 180)) 0 1 0 0-                _ -> identity-           in if T.null name then m else go (m `mul` m') next-    rotation a =-      let r = a * pi / 180-       in Matrix (cos r) (sin r) (negate (sin r)) (cos r) 0 0---- | Path data as absolute segments. Parsing stops at the first error, keeping--- what came before, as renderers do.-parsePath :: Text -> [Segment]-parsePath = go 'M' (P 0 0) (P 0 0) Nothing . skipSep-  where-    -- cmd: the current (repeatable) command; cur: the current point; start:-    -- the subpath start; ctrl: the last control point, for S and T.-    go cmd cur start ctrl t = case T.uncons t of-      Nothing -> []-      Just (c, rest)-        | isAlpha c && c /= 'e' && c /= 'E' ->-            if toLower c == 'z'-              then ClosePath : go (if c == 'z' then 'm' else 'M') start start Nothing (skipSep rest)-              else run c cur start ctrl (skipSep rest)-        | otherwise -> run cmd cur start ctrl t-    run cmd cur@(P cx cy) start ctrl t =-      let rel = cmd >= 'a'-          pt (P x y) = if rel then P (cx + x) (cy + y) else P x y-          nums n = takeNumbers n t-       in case toLower cmd of-            'm' -> case nums 2 of-              Just ([x, y], r) ->-                let p = pt (P x y)-                 in MoveTo p : go (if rel then 'l' else 'L') p p Nothing (skipSep r)-              _ -> []-            'l' -> case nums 2 of-              Just ([x, y], r) -> let p = pt (P x y) in LineTo p : go cmd p start Nothing (skipSep r)-              _ -> []-            'h' -> case nums 1 of-              Just ([x], r) -> let p = P (if rel then cx + x else x) cy in LineTo p : go cmd p start Nothing (skipSep r)-              _ -> []-            'v' -> case nums 1 of-              Just ([y], r) -> let p = P cx (if rel then cy + y else y) in LineTo p : go cmd p start Nothing (skipSep r)-              _ -> []-            'c' -> case nums 6 of-              Just ([x1, y1, x2, y2, x, y], r) ->-                let c2 = pt (P x2 y2)-                    p = pt (P x y)-                 in CubicTo (pt (P x1 y1)) c2 p : go cmd p start (Just c2) (skipSep r)-              _ -> []-            's' -> case nums 4 of-              Just ([x2, y2, x, y], r) ->-                let c1 = maybe cur (reflect cur) ctrl-                    c2 = pt (P x2 y2)-                    p = pt (P x y)-                 in CubicTo c1 c2 p : go cmd p start (Just c2) (skipSep r)-              _ -> []-            'q' -> case nums 4 of-              Just ([x1, y1, x, y], r) ->-                let c1 = pt (P x1 y1)-                    p = pt (P x y)-                 in QuadTo c1 p : go cmd p start (Just c1) (skipSep r)-              _ -> []-            't' -> case nums 2 of-              Just ([x, y], r) ->-                let c1 = maybe cur (reflect cur) ctrl-                    p = pt (P x y)-                 in QuadTo c1 p : go cmd p start (Just c1) (skipSep r)-              _ -> []-            'a' -> case arcArgs t of-              Just ((rx, ry, rot, large, sweep, x, y), r) ->-                let p = pt (P x y)-                 in ArcTo rx ry rot large sweep p : go cmd p start Nothing (skipSep r)-              _ -> []-            _ -> []-    reflect (P cx cy) (P x y) = P (2 * cx - x) (2 * cy - y)-    takeNumbers :: Int -> Text -> Maybe ([Float], Text)-    takeNumbers 0 t = Just ([], t)-    takeNumbers n t = do-      (x, rest) <- readNumber t-      (xs, rest') <- takeNumbers (n - 1) (skipSep rest)-      pure (x : xs, rest')-    -- Arc flags may be written without separators: @a1 1 0 00.5.5@.-    arcArgs t = do-      (rx, r1) <- readNumber t-      (ry, r2) <- readNumber (skipSep r1)-      (rot, r3) <- readNumber (skipSep r2)-      (large, r4) <- flag (skipSep r3)-      (sweep, r5) <- flag (skipSep r4)-      (x, r6) <- readNumber (skipSep r5)-      (y, r7) <- readNumber (skipSep r6)-      pure ((rx, ry, rot, large, sweep, x, y), r7)-    flag t = case T.uncons t of-      Just ('0', r) -> Just (False, r)-      Just ('1', r) -> Just (True, r)-      _ -> Nothing--rectSegments :: Float -> Float -> Float -> Float -> Maybe Float -> Maybe Float -> [Segment]-rectSegments x y w h mrx mry-  | w <= 0 || h <= 0 = []-  | rx <= 0 || ry <= 0 = [MoveTo (P x y), LineTo (P (x + w) y), LineTo (P (x + w) (y + h)), LineTo (P x (y + h)), ClosePath]-  | otherwise =-      [ MoveTo (P (x + rx) y)-      , LineTo (P (x + w - rx) y)-      , ArcTo rx ry 0 False True (P (x + w) (y + ry))-      , LineTo (P (x + w) (y + h - ry))-      , ArcTo rx ry 0 False True (P (x + w - rx) (y + h))-      , LineTo (P (x + rx) (y + h))-      , ArcTo rx ry 0 False True (P x (y + h - ry))-      , LineTo (P x (y + ry))-      , ArcTo rx ry 0 False True (P (x + rx) y)-      , ClosePath-      ]-  where-    rx = min (w / 2) (fromMaybe (fromMaybe 0 mry) mrx)-    ry = min (h / 2) (fromMaybe (fromMaybe 0 mrx) mry)--ellipseSegments :: Float -> Float -> Float -> Float -> [Segment]-ellipseSegments cx cy rx ry-  | rx <= 0 || ry <= 0 = []-  | otherwise =-      [ MoveTo (P (cx + rx) cy)-      , ArcTo rx ry 0 False True (P (cx - rx) cy)-      , ArcTo rx ry 0 False True (P (cx + rx) cy)-      , ClosePath-      ]--polySegments :: Bool -> Text -> [Segment]-polySegments closed pts = case pairs (numberList pts) of-  [] -> []-  p : ps -> MoveTo p : map LineTo ps ++ [ClosePath | closed]-  where-    pairs (x : y : rest) = P x y : pairs rest-    pairs _ = []------------------------------------------------------------------------------------- Rings------------------------------------------------------------------------------------- | Point lists in flat arrays: ring @i@ is points @starts[i]@ up to--- @starts[i + 1]@, stored x then y, with a number the builder tagged it with.-data Rings = Rings !(PrimArray Float) !(PrimArray Int) !(PrimArray Int)--ringCount :: Rings -> Int-ringCount (Rings _ starts _) = sizeofPrimArray starts - 1---- | Rings from a walk that calls @point x y@ for each point and @end tag@--- after each ring's last. The walk runs twice, to size the arrays and then--- to fill them, so it must visit the same points both times.-{-# INLINE buildRings #-}-buildRings :: (forall s. (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()) -> Rings-buildRings walk = runST $ do-  counts <- newPrimArray 2-  setPrimArray counts 0 2 (0 :: Int)-  let bump k = readPrimArray counts k >>= writePrimArray counts k . (+ 1)-  walk (\_ _ -> bump 0) (\_ -> bump 1)-  nPoints <- readPrimArray counts 0-  nRings <- readPrimArray counts 1-  points <- newPrimArray (2 * nPoints)-  starts <- newPrimArray (nRings + 1)-  tags <- newPrimArray nRings-  writePrimArray starts 0 0-  setPrimArray counts 0 2 0-  walk-    ( \x y -> do-        k <- readPrimArray counts 0-        writePrimArray points (2 * k) x-        writePrimArray points (2 * k + 1) y-        writePrimArray counts 0 (k + 1)-    )-    ( \tag -> do-        r <- readPrimArray counts 1-        readPrimArray counts 0 >>= writePrimArray starts (r + 1)-        writePrimArray tags r tag-        writePrimArray counts 1 (r + 1)-    )-  Rings <$> unsafeFreezePrimArray points <*> unsafeFreezePrimArray starts <*> unsafeFreezePrimArray tags------------------------------------------------------------------------------------- Flattening------------------------------------------------------------------------------------- | Flatten segments through a transform into contours in device pixels,--- each tagged 1 when closed. Curves are split until they are within a--- quarter pixel of their chords.-flatten :: Matrix -> SmallArray Segment -> Rings-flatten m segs = buildRings (flattenWalk m segs)--{-# INLINE flattenWalk #-}-flattenWalk :: Matrix -> SmallArray Segment -> (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()-flattenWalk m segs point end =-  let count = sizeofSmallArray segs-      emit p = let P x y = apply m p in point x y-      finish n closed = when (n > 0) (end (if closed then 1 else 0))-      -- A segment with no subpath open starts one at the current point.-      begin n started cur = if started || n > 0 then pure n else emit cur >> pure (1 :: Int)-      go !i !n !started cur start-        | i >= count = finish n False-        | otherwise = case indexSmallArray segs i of-            MoveTo p -> finish n False >> emit p >> go (i + 1) 1 True p p-            LineTo p -> do-              n1 <- begin n started cur-              emit p-              go (i + 1) (n1 + 1) True p start-            CubicTo c1 c2 p -> do-              n1 <- begin n started cur-              k <- cubicPoints point (apply m cur) (apply m c1) (apply m c2) (apply m p)-              go (i + 1) (n1 + k) True p start-            QuadTo c1 p -> do-              n1 <- begin n started cur-              let P x0 y0 = cur-                  P x1 y1 = c1-                  P x2 y2 = p-                  q1 = P (x0 + 2 / 3 * (x1 - x0)) (y0 + 2 / 3 * (y1 - y0))-                  q2 = P (x2 + 2 / 3 * (x1 - x2)) (y2 + 2 / 3 * (y1 - y2))-              k <- cubicPoints point (apply m cur) (apply m q1) (apply m q2) (apply m p)-              go (i + 1) (n1 + k) True p start-            ArcTo rx ry rot large sweep p -> do-              n1 <- begin n started cur-              k <- arcPoints emit cur rx ry rot large sweep p-              go (i + 1) (n1 + k) True p start-            ClosePath -> finish n True >> go (i + 1) 0 False start start-   in go 0 0 False (P 0 0) (P 0 0)---- | The points after the start of a cubic, subdividing by flatness, and how--- many there were.-{-# INLINE cubicPoints #-}-cubicPoints :: (Float -> Float -> ST s ()) -> P -> P -> P -> P -> ST s Int-cubicPoints point = go (0 :: Int)-  where-    go depth a b c d-      | depth >= 12 || flat a b c d = let P x y = d in point x y >> pure 1-      | otherwise = do-          let ab = mid a b-              bc = mid b c-              cd = mid c d-              abc = mid ab bc-              bcd = mid bc cd-              abcd = mid abc bcd-          k1 <- go (depth + 1) a ab abc abcd-          k2 <- go (depth + 1) abcd bcd cd d-          pure (k1 + k2)-    mid (P x0 y0) (P x1 y1) = P ((x0 + x1) / 2) ((y0 + y1) / 2)-    flat (P x0 y0) (P x1 y1) (P x2 y2) (P x3 y3) =-      let ux = 3 * x1 - 2 * x0 - x3-          uy = 3 * y1 - 2 * y0 - y3-          vx = 3 * x2 - 2 * x3 - x0-          vy = 3 * y2 - 2 * y3 - y0-       in max (ux * ux) (vx * vx) + max (uy * uy) (vy * vy) <= 16 * 0.25 * 0.25---- | The points after the start of an SVG arc, by the endpoint-to-centre--- conversion in the SVG specification, in user space, and how many there--- were.-{-# INLINE arcPoints #-}-arcPoints :: (P -> ST s ()) -> P -> Float -> Float -> Float -> Bool -> Bool -> P -> ST s Int-arcPoints emit (P x1 y1) rx0 ry0 rotDeg large sweep (P x2 y2)-  | rx0 == 0 || ry0 == 0 || (x1 == x2 && y1 == y2) = emit (P x2 y2) >> pure 1-  | otherwise = do-      forM_ [1 .. steps - 1] $ \i -> emit (pointAt i)-      emit (P x2 y2)-      pure steps-  where-    phi = rotDeg * pi / 180-    cosP = cos phi-    sinP = sin phi-    dx = (x1 - x2) / 2-    dy = (y1 - y2) / 2-    x1' = cosP * dx + sinP * dy-    y1' = negate sinP * dx + cosP * dy-    lambda = (x1' * x1') / (rx0 * rx0) + (y1' * y1') / (ry0 * ry0)-    scale = if lambda > 1 then sqrt lambda else 1-    rx = abs rx0 * scale-    ry = abs ry0 * scale-    num = rx * rx * ry * ry - rx * rx * y1' * y1' - ry * ry * x1' * x1'-    den = rx * rx * y1' * y1' + ry * ry * x1' * x1'-    coef = (if large == sweep then -1 else 1) * sqrt (max 0 (num / den))-    cx' = coef * rx * y1' / ry-    cy' = coef * negate (ry * x1' / rx)-    cx = cosP * cx' - sinP * cy' + (x1 + x2) / 2-    cy = sinP * cx' + cosP * cy' + (y1 + y2) / 2-    angle ux uy vx vy = atan2 (ux * vy - uy * vx) (ux * vx + uy * vy)-    theta1 = angle 1 0 ((x1' - cx') / rx) ((y1' - cy') / ry)-    dtheta0 = angle ((x1' - cx') / rx) ((y1' - cy') / ry) ((negate x1' - cx') / rx) ((negate y1' - cy') / ry)-    dtheta-      | not sweep && dtheta0 > 0 = dtheta0 - 2 * pi-      | sweep && dtheta0 < 0 = dtheta0 + 2 * pi-      | otherwise = dtheta0-    steps = max 4 (ceiling (abs dtheta / (pi / 16)) :: Int)-    pointAt i =-      let t = theta1 + dtheta * fromIntegral i / fromIntegral steps-          ex = rx * cos t-          ey = ry * sin t-       in P (cosP * ex - sinP * ey + cx) (sinP * ex + cosP * ey + cy)------------------------------------------------------------------------------------- Stroking------------------------------------------------------------------------------------- | Polygons covering a stroke of width @w@ along the contours, each wound--- counter-clockwise so a non-zero fill of all of them is their union.-strokePolygons :: Float -> LineCap -> LineJoin -> Float -> Rings -> Rings-strokePolygons w cap join miterLimit contours = buildRings (strokeWalk w cap join miterLimit contours)--{-# INLINE strokeWalk #-}-strokeWalk :: Float -> LineCap -> LineJoin -> Float -> Rings -> (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()-strokeWalk w cap join miterLimit contours@(Rings cpts cstarts ctags) point end =-  let hw = w / 2-      at k = P (indexPrimArray cpts (2 * k)) (indexPrimArray cpts (2 * k + 1))-      close (P x0 y0) (P x1 y1) = abs (x0 - x1) < 1e-4 && abs (y0 - y1) < 1e-4-      emitP (P x y) = point x y-      -- Twice the signed area of a polygon's corners, positive when they-      -- wind counter-clockwise.-      turn (P x0 y0) (P x1 y1) = x0 * y1 - x1 * y0-      -- A triangle or quad in the order given, or reversed when that winds-      -- clockwise.-      triangle a b c = do-        if turn a b + turn b c + turn c a < 0-          then emitP c >> emitP b >> emitP a-          else emitP a >> emitP b >> emitP c-        end 0-      quad a b c d = do-        if turn a b + turn b c + turn c d + turn d a < 0-          then emitP d >> emitP c >> emitP b >> emitP a-          else emitP a >> emitP b >> emitP c >> emitP d-        end 0-      normal (P x0 y0) (P x1 y1) =-        let dx = x1 - x0-            dy = y1 - y0-            len = max 1e-6 (sqrt (dx * dx + dy * dy))-         in (negate dy / len * hw, dx / len * hw)-      segmentQuad a@(P ax ay) b@(P bx by) = do-        let (nx, ny) = normal a b-        -- The quad winds clockwise as built, whatever its direction.-        emitP (P (ax - nx) (ay - ny))-        emitP (P (bx - nx) (by - ny))-        emitP (P (bx + nx) (by + ny))-        emitP (P (ax + nx) (ay + ny))-        end 0-      corner prev v@(P vx vy) next = do-        let (n1x, n1y) = normal prev v-            (n2x, n2y) = normal v next-            bevel = do-              triangle v (P (vx + n1x) (vy + n1y)) (P (vx + n2x) (vy + n2y))-              triangle v (P (vx - n1x) (vy - n1y)) (P (vx - n2x) (vy - n2y))-        case join of-          JoinRound -> disc v-          JoinBevel -> bevel-          JoinMiter -> do-            let mx = n1x + n2x-                my = n1y + n2y-                mlen2 = mx * mx + my * my-                -- The miter point sits along the bisector at hw / cos(half angle).-                scale = if mlen2 < 1e-9 then 0 else 2 * hw * hw / mlen2-                ratio = if mlen2 < 1e-9 then 1 / 0 else sqrt (scale * scale * mlen2) / hw-            if ratio > miterLimit-              then bevel-              else do-                quad v (P (vx + n1x) (vy + n1y)) (P (vx + mx * scale) (vy + my * scale)) (P (vx + n2x) (vy + n2y))-                quad v (P (vx - n1x) (vy - n1y)) (P (vx - mx * scale) (vy - my * scale)) (P (vx - n2x) (vy - n2y))-      endCap inner@(P ix iy) e@(P ex ey) = case cap of-        CapButt -> pure ()-        CapRound -> disc e-        CapSquare -> do-          let dx = ex - ix-              dy = ey - iy-              len = max 1e-6 (sqrt (dx * dx + dy * dy))-              ux = dx / len * hw-              uy = dy / len * hw-              (nx, ny) = normal inner e-          -- Wound clockwise as built, like a segment's quad.-          emitP (P (ex - nx) (ey - ny))-          emitP (P (ex - nx + ux) (ey - ny + uy))-          emitP (P (ex + nx + ux) (ey + ny + uy))-          emitP (P (ex + nx) (ey + ny))-          end 0-      disc (P cx cy) = do-        let n = max 8 (min 48 (ceiling (hw * 2.5) :: Int))-        forM_ [0 .. n - 1] $ \i ->-          let t = 2 * pi * fromIntegral i / fromIntegral n in point (cx + hw * cos t) (cy + hw * sin t)-        end 0-      square (P cx cy) = do-        emitP (P (cx - hw) (cy - hw))-        emitP (P (cx + hw) (cy - hw))-        emitP (P (cx + hw) (cy + hw))-        emitP (P (cx - hw) (cy + hw))-        end 0-      contour r = do-        let from = indexPrimArray cstarts r-            to = indexPrimArray cstarts (r + 1)-            closed = indexPrimArray ctags r /= 0-        -- The contour's points, dropping any that repeat the one before.-        kept <- newPrimArray (to - from)-        let dedupe !k !n-              | k >= to = pure n-              | n > 0 = do-                  prevK <- readPrimArray kept (n - 1)-                  if close (at prevK) (at k)-                    then dedupe (k + 1) n-                    else writePrimArray kept n k >> dedupe (k + 1) (n + 1)-              | otherwise = writePrimArray kept 0 k >> dedupe (k + 1) 1-        n0 <- dedupe from 0-        firstK <- readPrimArray kept 0-        lastK <- readPrimArray kept (max 0 (n0 - 1))-        -- A closed contour that returns to its start ends on that point.-        let n = if closed && n0 >= 2 && close (at firstK) (at lastK) then n0 - 1 else n0-            pt i = at <$> readPrimArray kept i-        case n of-          0 -> pure ()-          1 -> do-            p <- pt 0-            when (cap == CapRound) (disc p)-            when (cap == CapSquare) (square p)-          _ -> do-            forM_ [0 .. n - 2] $ \i -> do-              a <- pt i-              b <- pt (i + 1)-              segmentQuad a b-            when closed $ do-              a <- pt (n - 1)-              b <- pt 0-              segmentQuad a b-            let cornerAt i = do-                  prev <- pt ((i - 1 + n) `mod` n)-                  v <- pt i-                  next <- pt ((i + 1) `mod` n)-                  corner prev v next-            if closed-              then forM_ [0 .. n - 1] cornerAt-              else forM_ [1 .. n - 2] cornerAt-            unless closed $ do-              first <- pt 0-              second <- pt 1-              beforeLast <- pt (n - 2)-              final <- pt (n - 1)-              endCap second first-              endCap beforeLast final-   in forM_ [0 .. ringCount contours - 1] contour------------------------------------------------------------------------------------- Rasterizing------------------------------------------------------------------------------------- | Render the document into a @width@ by @height@ RGBA image (rows top to--- bottom), scaled to fit and centred as SVG's default @xMidYMid meet@ does.--- @current@ is what @currentColor@, and an unspecified fill, paint with.-rasterizeSvg :: Int -> Int -> Color -> Svg -> ByteString-rasterizeSvg width height current svg-  | width <= 0 || height <= 0 = BS.empty-  | otherwise = BSI.unsafeCreate (width * height * 4) $ \out ->-      forM_ [0 .. width * height - 1] $ \i -> do-        let al = indexPrimArray image (i * 4 + 3)-            byte x = fromIntegral (max 0 (min 255 (round (x * 255) :: Int))) :: Word8-            unpremul k = pokeByteOff out (i * 4 + k) (if al <= 0 then 0 else byte (indexPrimArray image (i * 4 + k) / al))-        unpremul 0-        unpremul 1-        unpremul 2-        pokeByteOff out (i * 4 + 3) (byte al)-  where-    image = runST $ do-      -- Premultiplied RGBA in [0, 1].-      acc <- newPrimArray (width * height * 4)-      setPrimArray acc 0 (width * height * 4) (0 :: Float)-      cov <- newPrimArray (width * height)-      let Box vx vy vw vh = svgViewBox svg-          s = min (fromIntegral width / vw) (fromIntegral height / vh)-          tx = (fromIntegral width - vw * s) / 2 - vx * s-          ty = (fromIntegral height - vh * s) / 2 - vy * s-          view = Matrix s 0 0 s tx ty-      forM_ (svgShapes svg) $ \(Shape segs m style) -> do-        let full = view `mul` m-            contours = flatten full segs-            Matrix a b c d _ _ = full-            scaleOf = sqrt (abs (a * d - b * c))-            opacity = psOpacity style-            paintColor p = case p of-              PaintNone -> Nothing-              PaintCurrent -> Just current-              PaintColor col -> Just col-            -- An unspecified fill paints black, or the current colour in a-            -- monochrome document, so an icon without paints tints.-            fill = fromMaybe (if svgMonochrome svg then PaintCurrent else PaintColor (colorRGBA 0 0 0 255)) (psFill style)-        forM_ (paintColor fill) $ \col -> do-          coverPolygons width height cov (psRule style) contours-          composite width height acc cov col (opacity * psFillOpacity style)-        forM_ (paintColor (fromMaybe PaintNone (psStroke style))) $ \col ->-          when (psStrokeWidth style > 0) $ do-            let wanted = psStrokeWidth style * scaleOf-                w = max 1 wanted-                polys = strokePolygons w (psCap style) (psJoin style) (psMiterLimit style) contours-            coverPolygons width height cov NonZero polys-            -- A hairline thinner than a pixel keeps its weight as opacity.-            composite width height acc cov col (opacity * psStrokeOpacity style * min 1 (wanted / w))-      unsafeFreezePrimArray acc---- | Coverage of the rings with at least three points in @cov@ (cleared--- first): five sample rows a pixel, each span's coverage split exactly--- across the pixels it crosses.------ Edges are counted per pixel row they start in and then written in row--- order, so the sweep down the rows admits each row's edges as a block,--- drops an edge past its bottom, and insertion sorts a row's few crossings--- in a scratch array.-coverPolygons :: Int -> Int -> MutablePrimArray s Float -> FillRule -> Rings -> ST s ()-coverPolygons width height cov rule rings@(Rings pts starts _) = do-  setPrimArray cov 0 (width * height) 0-  let capacity = sizeofPrimArray pts `div` 2-      -- Each edge that can cover a row: its first row, top, bottom, x at the-      -- top, slope and winding.-      {-# INLINE forEdges #-}-      forEdges :: (Int -> Float -> Float -> Float -> Float -> Int -> ST s ()) -> ST s ()-      forEdges visit =-        forM_ [0 .. ringCount rings - 1] $ \r -> do-          let from = indexPrimArray starts r-              to = indexPrimArray starts (r + 1)-          when (to - from >= 3) $-            forM_ [from .. to - 1] $ \k -> do-              let k' = if k + 1 == to then from else k + 1-                  ax = indexPrimArray pts (2 * k)-                  ay = indexPrimArray pts (2 * k + 1)-                  bx = indexPrimArray pts (2 * k')-                  by = indexPrimArray pts (2 * k' + 1)-                  up = ay < by-                  x0 = if up then ax else bx-                  y0 = if up then ay else by-                  x1 = if up then bx else ax-                  y1 = if up then by else ay-              when (ay /= by && y1 > 0 && y0 < fromIntegral height) $-                visit (max 0 (floor y0)) y0 y1 x0 ((x1 - x0) / (y1 - y0)) (if up then 1 else -1)-  -- Where each row's edges begin: counts, then running totals.-  rowStart <- newPrimArray (height + 1)-  setPrimArray rowStart 0 (height + 1) (0 :: Int)-  forEdges $ \row _ _ _ _ _ -> readPrimArray rowStart (row + 1) >>= writePrimArray rowStart (row + 1) . (+ 1)-  forM_ [1 .. height] $ \row -> do-    before <- readPrimArray rowStart (row - 1)-    readPrimArray rowStart row >>= writePrimArray rowStart row . (+ before)-  -- Four numbers an edge, in row order: top, bottom, x at the top, slope;-  -- windings apart.-  edges <- newPrimArray (capacity * 4)-  windings <- newPrimArray capacity-  cursor <- newPrimArray height-  copyMutablePrimArray cursor 0 rowStart 0 height-  forEdges $ \row y0 y1 x0 slope dir -> do-    e <- readPrimArray cursor row-    writePrimArray cursor row (e + 1)-    writePrimArray edges (e * 4) y0-    writePrimArray edges (e * 4 + 1) y1-    writePrimArray edges (e * 4 + 2) x0-    writePrimArray edges (e * 4 + 3) slope-    writePrimArray windings e (dir :: Int)-  totalEdges <- readPrimArray rowStart height-  active <- newPrimArray capacity-  crossX <- newPrimArray capacity-  crossDir <- newPrimArray capacity-  let samples = 5 :: Int-      weight = 1 / fromIntegral samples :: Float-      inside :: Int -> Bool-      inside w = case rule of-        NonZero -> w /= 0-        EvenOdd -> odd w-      add i v = readPrimArray cov i >>= \c -> writePrimArray cov i (c + v)-      spanCover base xa0 xb0 = do-        let xa = max 0 (min (fromIntegral width) xa0)-            xb = max 0 (min (fromIntegral width) xb0)-        when (xb > xa) $ do-          let ia = floor xa :: Int-              ib = min (width - 1) (floor xb)-          if ia == ib-            then add (base + ia) ((xb - xa) * weight)-            else do-              add (base + ia) ((fromIntegral (ia + 1) - xa) * weight)-              forM_ [ia + 1 .. ib - 1] $ \i -> add (base + i) weight-              when (ib < width) $ add (base + ib) ((xb - fromIntegral ib) * weight)-      -- The row's edges join the active list.-      admit !e !stop !n-        | e >= stop = pure n-        | otherwise = writePrimArray active n e >> admit (e + 1) stop (n + 1)-      -- A crossing goes where it sorts among the @j@ before it.-      insertCrossing !j !x !d-        | j > 0 = do-            xj <- readPrimArray crossX (j - 1)-            if xj > x-              then do-                writePrimArray crossX j xj-                readPrimArray crossDir (j - 1) >>= writePrimArray crossDir j-                insertCrossing (j - 1) x d-              else writePrimArray crossX j x >> writePrimArray crossDir j (d :: Int)-        | otherwise = writePrimArray crossX 0 x >> writePrimArray crossDir 0 d-      walk !base !crossings !k !w-        | k + 1 >= crossings = pure ()-        | otherwise = do-            d <- readPrimArray crossDir k-            let w' = w + d-            when (inside w') $ do-              xa <- readPrimArray crossX k-              xb <- readPrimArray crossX (k + 1)-              spanCover base xa xb-            walk base crossings (k + 1) w'-      -- One sample row: drop edges above it, collect the crossings of the-      -- rest, then cover the spans inside the fill.-      sample !r !si !n !a !kept !crossings-        | a < n = do-            e <- readPrimArray active a-            let sy = fromIntegral r + (fromIntegral si + 0.5) * weight-            y1 <- readPrimArray edges (e * 4 + 1)-            if y1 <= sy-              then sample r si n (a + 1) kept crossings-              else do-                writePrimArray active kept e-                y0 <- readPrimArray edges (e * 4)-                if sy < y0-                  then sample r si n (a + 1) (kept + 1) crossings-                  else do-                    x0 <- readPrimArray edges (e * 4 + 2)-                    slope <- readPrimArray edges (e * 4 + 3)-                    d <- readPrimArray windings e-                    insertCrossing crossings (x0 + (sy - y0) * slope) d-                    sample r si n (a + 1) (kept + 1) (crossings + 1)-        | otherwise = do-            walk (r * width) crossings 0 0-            if si + 1 < samples-              then sample r (si + 1) kept 0 0 0-              else rows (r + 1) kept-      rows !r !n-        | r >= height = pure ()-        | otherwise = do-            from <- readPrimArray rowStart r-            to <- readPrimArray rowStart (r + 1)-            -- Past the last edge's bottom nothing is left to cover.-            if n == 0 && from >= totalEdges-              then pure ()-              else admit from to n >>= \n' -> sample r 0 n' 0 0 0-  rows 0 0---- | Draw @col@ at @alpha@ through the coverage over the accumulated image.-composite :: Int -> Int -> MutablePrimArray s Float -> MutablePrimArray s Float -> Color -> Float -> ST s ()-composite width height acc cov col alpha =-  forM_ [0 .. width * height - 1] $ \i -> do-    c <- readPrimArray cov i-    when (c > 0) $ do-      let sa = min 1 c * alpha * fromIntegral (colorA col) / 255-          blend k src = do-            dst <- readPrimArray acc (i * 4 + k)-            writePrimArray acc (i * 4 + k) (src * sa + dst * (1 - sa))-      blend 0 (fromIntegral (colorR col) / 255)-      blend 1 (fromIntegral (colorG col) / 255)-      blend 2 (fromIntegral (colorB col) / 255)-      dstA <- readPrimArray acc (i * 4 + 3)-      writePrimArray acc (i * 4 + 3) (sa + dstA * (1 - sa))+-- | An anti-aliased rasterizer for the SVG icons that @nano-svg@ parses.+--+-- @nano-svg@ reads the document into shapes with absolute segments, a+-- transform and a resolved style; this module flattens those to contours,+-- strokes them and scan-converts the result into an RGBA image. See+-- "Graphics.NanoSvg" for what the parser supports; gradients, patterns,+-- text, masks, clipping and filters are not among them.+module NanoUI.Svg+  ( Svg+  , svgDocument+  , svgSize+  , svgKey+  , svgMonochrome+  , parseSvg+  , rasterizeSvg+  , rasterizeSvgIn+  ) where++import Control.Monad (forM_, when)+import Control.Monad.Primitive (PrimMonad, PrimState)+import Control.Monad.ST (ST, runST)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Internal qualified as BSI+import Data.Maybe (fromMaybe)+import Data.Foldable (toList)+import Data.Primitive.PrimArray (MutablePrimArray, PrimArray, indexPrimArray, newPrimArray, readPrimArray, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)+import Data.Primitive.SmallArray (SmallArray)+import Data.Word (Word16, Word8)+import Foreign.Marshal.Utils (fillBytes)+import Foreign.Storable (pokeByteOff)+import Graphics.NanoSvg+  ( Box (..)+  , Document (..)+  , FillRule (..)+  , LineCap (..)+  , LineJoin (..)+  , Matrix (..)+  , Paint (..)+  , Point (..)+  , RGBA (..)+  , Segment (..)+  , Shape (..)+  , Style (..)+  , black+  )+import Graphics.NanoSvg qualified as NanoSvg+import NanoUI.Internal.Path (Rings (..), buildRings, cleanRings, ringCount)+import NanoUI.Internal.Path qualified as P+import NanoUI.Internal.Types (Color (..), Rect (..), bucketOffsets, clamp, colorA, colorB, colorG, colorR, newZeroedPrimArray)++-- | A parsed SVG document. Only 'parseSvg' makes one, so its raster cache+-- key ('svgKey') always describes its source: an edited @nano-svg@+-- 'Document' cannot reuse another drawing's rasters.+newtype Svg = Svg Document+  deriving newtype (Eq, Show)++-- | Parse an SVG document's bytes.+parseSvg :: ByteString -> Either String Svg+parseSvg = fmap Svg . NanoSvg.parseSvg++-- | The parsed shapes, read-only, as @nano-svg@ returns them.+svgDocument :: Svg -> Document+svgDocument (Svg doc) = doc++-- | The document's own width and height, from its @width@ and @height@ or+-- else its @viewBox@.+svgSize :: Svg -> (Float, Float)+svgSize = documentSize . svgDocument++-- | A hash of the source, for caching rasters.+svgKey :: Svg -> Int+svgKey = documentKey . svgDocument++-- | Every paint is @currentColor@ or unspecified, so the drawing is one+-- colour and can be tinted.+svgMonochrome :: Svg -> Bool+svgMonochrome = documentMonochrome . svgDocument++--------------------------------------------------------------------------------+-- Flattening+--------------------------------------------------------------------------------++-- | Convert a @nano-svg@ matrix into a path 'P.Transform'.+toTransform :: Matrix -> P.Transform+toTransform (Matrix a b c d e f) = P.Transform a b c d e f++-- | Flatten segments through a transform into contours in device pixels,+-- each tagged 1 when closed. Curves are split until they are within a+-- quarter pixel of their chords. Arcs use steps of at most pi/16, and at+-- least four steps.+flatten :: P.Transform -> SmallArray Segment -> Rings+flatten tr segs =+  P.flattenPath 0.25 (\_ sweep -> max 4 (ceiling (abs sweep / (pi / 16)))) tr (P.Path (map segment (toList segs)))+  where+    segment = \case+      MoveTo (Point x y) -> P.SegMove x y+      LineTo (Point x y) -> P.SegLine x y+      CubicTo (Point x1 y1) (Point x2 y2) (Point x y) -> P.SegCubic x1 y1 x2 y2 x y+      QuadTo (Point qx qy) (Point x y) -> P.SegQuad qx qy x y+      ArcTo rx ry rot large sweep (Point x y) -> P.SegArcTo rx ry (rot * pi / 180) large sweep x y+      ClosePath -> P.SegClose++--------------------------------------------------------------------------------+-- Stroking+--------------------------------------------------------------------------------++-- | Polygons covering a stroke of width @w@ along the contours, each wound+-- clockwise on screen so a non-zero fill of all of them is their union.+strokePolygons :: Float -> LineCap -> LineJoin -> Float -> Rings -> Rings+strokePolygons w cap join miterLimit contours = buildRings (strokeWalk w cap join miterLimit (cleanRings False contours))++-- | The outline walk behind 'strokePolygons'. Contours must have no+-- repeated points.+{-# INLINE strokeWalk #-}+strokeWalk :: Float -> LineCap -> LineJoin -> Float -> [(PrimArray Float, Bool)] -> (Float -> Float -> ST s ()) -> (Int -> ST s ()) -> ST s ()+strokeWalk w cap join miterLimit contours point end =+  let hw = w / 2+      emitP (Point x y) = point x y+      -- Twice the signed area of a polygon's corners, positive when they+      -- wind clockwise on screen, as 'P.shoelace' counts.+      turn (Point x0 y0) (Point x1 y1) = x0 * y1 - x1 * y0+      -- A triangle or quad in the order given, or reversed when that winds+      -- anticlockwise on screen.+      triangle a b c = do+        if turn a b + turn b c + turn c a < 0+          then emitP c >> emitP b >> emitP a+          else emitP a >> emitP b >> emitP c+        end 0+      quad a b c d+        | turn a b + turn b c + turn c d + turn d a < 0 = emit4 d c b a+        | otherwise = emit4 a b c d+      emit4 a b c d = emitP a >> emitP b >> emitP c >> emitP d >> end 0+      normal (Point x0 y0) (Point x1 y1) =+        let dx = x1 - x0+            dy = y1 - y0+            len = max 1e-6 (sqrt (dx * dx + dy * dy))+         in (negate dy / len * hw, dx / len * hw)+      segmentQuad a@(Point ax ay) b@(Point bx by) = do+        let (nx, ny) = normal a b+        -- The quad winds clockwise as built, whatever its direction.+        emit4 (Point (ax - nx) (ay - ny)) (Point (bx - nx) (by - ny)) (Point (bx + nx) (by + ny)) (Point (ax + nx) (ay + ny))+      corner prev v@(Point vx vy) next = do+        let (n1x, n1y) = normal prev v+            (n2x, n2y) = normal v next+            bevel = do+              triangle v (Point (vx + n1x) (vy + n1y)) (Point (vx + n2x) (vy + n2y))+              triangle v (Point (vx - n1x) (vy - n1y)) (Point (vx - n2x) (vy - n2y))+        case join of+          JoinRound -> disc v+          JoinBevel -> bevel+          JoinMiter -> case P.miterOffset miterLimit (n1x / hw) (n1y / hw) (n2x / hw) (n2y / hw) of+            Nothing -> bevel+            Just (mx, my) -> do+              quad v (Point (vx + n1x) (vy + n1y)) (Point (vx + mx * hw) (vy + my * hw)) (Point (vx + n2x) (vy + n2y))+              quad v (Point (vx - n1x) (vy - n1y)) (Point (vx - mx * hw) (vy - my * hw)) (Point (vx - n2x) (vy - n2y))+      endCap inner e@(Point ex ey) = case cap of+        CapButt -> pure ()+        CapRound -> disc e+        CapSquare -> do+          -- The outward direction, hw long: the normal turned back.+          let (nx, ny) = normal inner e+              ux = ny+              uy = negate nx+          -- Wound clockwise as built, like a segment's quad.+          emit4 (Point (ex - nx) (ey - ny)) (Point (ex - nx + ux) (ey - ny + uy)) (Point (ex + nx + ux) (ey + ny + uy)) (Point (ex + nx) (ey + ny))+      disc (Point cx cy) = do+        let n = clamp 8 48 (ceiling (hw * 2.5) :: Int)+        forM_ [0 .. n - 1] $ \i ->+          let t = 2 * pi * fromIntegral i / fromIntegral n in point (cx + hw * cos t) (cy + hw * sin t)+        end 0+      square (Point cx cy) =+        emit4 (Point (cx - hw) (cy - hw)) (Point (cx + hw) (cy - hw)) (Point (cx + hw) (cy + hw)) (Point (cx - hw) (cy + hw))+      contour (pts, closed) = do+        let n = sizeofPrimArray pts `div` 2+            pt i = Point (indexPrimArray pts (2 * i)) (indexPrimArray pts (2 * i + 1))+            cornerAt i = corner (pt ((i - 1 + n) `mod` n)) (pt i) (pt ((i + 1) `mod` n))+        case n of+          0 -> pure ()+          1 -> case cap of+            CapButt -> pure ()+            CapRound -> disc (pt 0)+            CapSquare -> square (pt 0)+          _ -> do+            forM_ [0 .. n - 2] $ \i -> segmentQuad (pt i) (pt (i + 1))+            if closed+              then segmentQuad (pt (n - 1)) (pt 0) >> forM_ [0 .. n - 1] cornerAt+              else do+                forM_ [1 .. n - 2] cornerAt+                endCap (pt 1) (pt 0)+                endCap (pt (n - 2)) (pt (n - 1))+   in mapM_ contour contours++--------------------------------------------------------------------------------+-- Rasterizing+--------------------------------------------------------------------------------++-- | Render the document into a @width@ by @height@ RGBA image (rows top to+-- bottom), scaled to fit and centred as SVG's default @xMidYMid meet@ does.+-- @current@ is what @currentColor@ paints with, and an unspecified fill too+-- when the document is one colour ('svgMonochrome'); otherwise an+-- unspecified fill is black, as in SVG.+rasterizeSvg :: Int -> Int -> Color -> Svg -> ByteString+rasterizeSvg width height current (Svg svg) =+  rasterizeView width height (meet (documentViewBox svg) (fromIntegral width) (fromIntegral height)) current svg++-- | 'rasterizeSvg' with the document's own viewport ('svgSize') drawn over+-- @Rect x y w h@, in raster pixels, instead of fitted to the raster. A rect of+-- another shape stretches the document, and whatever falls outside the raster+-- is cut off. The viewBox keeps @xMidYMid meet@ within the viewport.+--+-- > rasterizeSvgIn 64 64 (Rect (-16) 0 96 64) white doc  -- a 3:2 icon covering a square+rasterizeSvgIn :: Int -> Int -> Rect -> Color -> Svg -> ByteString+rasterizeSvgIn width height (Rect x y w h) current (Svg svg) =+  rasterizeView width height (P.Transform (w / dw) 0 0 (h / dh) x y <> meet (documentViewBox svg) dw dh) current svg+  where+    (dw, dh) = documentSize svg++-- | The viewBox fitted into a @w@ by @h@ viewport and centred, as SVG's+-- default @xMidYMid meet@ does.+meet :: Box -> Float -> Float -> P.Transform+meet (Box vx vy vw vh) w h = P.Transform s 0 0 s ((w - vw * s) / 2 - vx * s) ((h - vh * s) / 2 - vy * s)+  where+    s = min (w / vw) (h / vh)++-- | Render with @view@ mapping viewBox units to raster pixels.+rasterizeView :: Int -> Int -> P.Transform -> Color -> Document -> ByteString+rasterizeView width height view current svg+  | width <= 0 || height <= 0 = BS.empty+  -- A degenerate viewBox or rect makes a view of infinities or NaNs.+  | not (P.transformFinite view) = BS.replicate (width * height * 4) 0+  | otherwise =+      case collectPaints of+        [] -> BS.replicate (width * height * 4) 0+        [(rule, rings, col, alpha)] ->+          -- Single-paint SVG (most UI icons): write straight to the output+          -- buffer row by row with no full-frame accumulator or coverage array.+          BSI.unsafeCreate (width * height * 4) $ \out -> do+            fillBytes out 0 (width * height * 4)+            cov <- newZeroedPrimArray width+            let !rByte = colorR col+                !gByte = colorG col+                !bByte = colorB col+                !aScale = alpha * fromIntegral (colorA col) / 255+                writeRow !row = go 0+                  where+                    !rowBase = row * width * 4+                    go !x+                      | x >= width = pure ()+                      | otherwise = do+                          c <- readPrimArray cov x+                          when (c > 0) $ do+                            writePrimArray cov x 0+                            let !sa = min 1 c * aScale+                                !aByte = toByte sa+                            when (aByte > 0) $ do+                              let !off = rowBase + x * 4+                              pokeByteOff out off rByte+                              pokeByteOff out (off + 1) gByte+                              pokeByteOff out (off + 2) bByte+                              pokeByteOff out (off + 3) aByte+                          go (x + 1)+            coverPolygons width height cov rule rings writeRow+        paints ->+          let !image = rasterizeMulti paints+           in BSI.unsafeCreate (width * height * 4) $ \out ->+                let !n = width * height+                    go !i+                      | i >= n = pure ()+                      | otherwise = do+                          let !off = i * 4+                              !al16 = indexPrimArray image (off + 3)+                          if al16 == 0+                            then do+                              pokeByteOff out off (0 :: Word8)+                              pokeByteOff out (off + 1) (0 :: Word8)+                              pokeByteOff out (off + 2) (0 :: Word8)+                              pokeByteOff out (off + 3) (0 :: Word8)+                            else if al16 == 65535+                              then do+                                pokeByteOff out off (toByte16 (indexPrimArray image off))+                                pokeByteOff out (off + 1) (toByte16 (indexPrimArray image (off + 1)))+                                pokeByteOff out (off + 2) (toByte16 (indexPrimArray image (off + 2)))+                                pokeByteOff out (off + 3) (255 :: Word8)+                              else do+                                let !invA = 255.0 / fromIntegral al16 :: Float+                                pokeByteOff out off (clampByte (fromIntegral (indexPrimArray image off) * invA))+                                pokeByteOff out (off + 1) (clampByte (fromIntegral (indexPrimArray image (off + 1)) * invA))+                                pokeByteOff out (off + 2) (clampByte (fromIntegral (indexPrimArray image (off + 2)) * invA))+                                pokeByteOff out (off + 3) (toByte16 al16)+                          go (i + 1)+                 in go 0+  where+    {-# INLINE toByte #-}+    toByte :: Float -> Word8+    toByte x+      | x <= 0 = 0+      | x >= 1 = 255+      | otherwise = fromIntegral (round (x * 255) :: Int)++    {-# INLINE toByte16 #-}+    toByte16 :: Word16 -> Word8+    toByte16 w = fromIntegral ((fromIntegral w * (255 :: Int) + 32767) `quot` 65535)++    {-# INLINE clampByte #-}+    clampByte :: Float -> Word8+    clampByte x+      | x <= 0 = 0+      | x >= 255 = 255+      | otherwise = fromIntegral (round x :: Int)++    paintColor p = case p of+      PaintNone -> Nothing+      PaintCurrent -> Just current+      PaintColor col -> Just (Color (rgbaToWord32 col))++    collectPaints = concatMap shapePaints (toList (documentShapes svg))+      where+        shapePaints (Shape segs m style) =+          let full = view <> toTransform m+              contours = flatten full segs+              scaleOf = P.averageStretch full+              opacity = styleOpacity style+              fill = fromMaybe (if documentMonochrome svg then PaintCurrent else PaintColor black) (styleFill style)+              fillItem = case paintColor fill of+                Just col -> [(styleFillRule style, contours, col, opacity * styleFillOpacity style)]+                Nothing -> []+              strokeItem = case paintColor (fromMaybe PaintNone (styleStroke style)) of+                Just col+                  | styleStrokeWidth style > 0 ->+                      let wanted = styleStrokeWidth style * scaleOf+                          w = max 1 wanted+                          polys = strokePolygons w (styleCap style) (styleJoin style) (styleMiterLimit style) contours+                       in [(NonZero, polys, col, opacity * styleStrokeOpacity style * min 1 (wanted / w))]+                _ -> []+           in fillItem ++ strokeItem++    -- Multi-paint SVG: 16-bit premultiplied RGBA accumulator (half the size+    -- of Float with 256x 8-bit precision) plus a single scanline coverage row.+    rasterizeMulti :: [(FillRule, Rings, Color, Float)] -> PrimArray Word16+    rasterizeMulti paints = runST $ do+      acc <- newZeroedPrimArray (width * height * 4)+      cov <- newZeroedPrimArray width+      forM_ paints $ \(rule, rings, col, alpha) ->+        coverPolygons width height cov rule rings (compositeRow16 width acc cov col alpha)+      unsafeFreezePrimArray acc++-- | Scan-convert @rings@ row by row into the single-row buffer @cov@ (of+-- length @width@, initially zero), invoking @onRow r@ after each covered row+-- @r@. @onRow@ must zero every non-zero entry it reads from @cov@.+{-# SPECIALIZE coverPolygons :: Int -> Int -> MutablePrimArray s Float -> FillRule -> Rings -> (Int -> ST s ()) -> ST s () #-}+{-# SPECIALIZE coverPolygons :: Int -> Int -> MutablePrimArray (PrimState IO) Float -> FillRule -> Rings -> (Int -> IO ()) -> IO () #-}+coverPolygons :: PrimMonad m => Int -> Int -> MutablePrimArray (PrimState m) Float -> FillRule -> Rings -> (Int -> m ()) -> m ()+coverPolygons width height cov rule rings@(Rings pts starts _) onRow = do+  let {-# INLINE forEdges #-}+      forEdges visit =+        forM_ [0 .. ringCount rings - 1] $ \r -> do+          let from = indexPrimArray starts r+              to = indexPrimArray starts (r + 1)+          when (to - from >= 3) $+            forM_ [from .. to - 1] $ \k -> do+              let k' = if k + 1 == to then from else k + 1+                  ax = indexPrimArray pts (2 * k)+                  ay = indexPrimArray pts (2 * k + 1)+                  bx = indexPrimArray pts (2 * k')+                  by = indexPrimArray pts (2 * k' + 1)+                  up = ay < by+                  x0 = if up then ax else bx+                  y0 = if up then ay else by+                  x1 = if up then bx else ax+                  y1 = if up then by else ay+              -- The row is tested before 'floor': an edge from far above (a+              -- huge or infinite coordinate) floors to garbage, not a row.+              when (ay /= by && y1 > 0 && y0 < fromIntegral height) $+                visit (if y0 <= 0 then 0 else floor y0) y0 y1 x0 ((x1 - x0) / (y1 - y0)) (if up then 1 else -1)+  (rowStart, cursor) <- bucketOffsets height (\emit -> forEdges (\row _ _ _ _ _ -> emit row))+  totalEdges <- readPrimArray rowStart height+  when (totalEdges > 0) $ do+    edges <- newPrimArray (totalEdges * 4)+    windings <- newPrimArray totalEdges+    forEdges $ \row y0 y1 x0 slope dir -> do+      e <- readPrimArray cursor row+      writePrimArray cursor row (e + 1)+      writePrimArray edges (e * 4) y0+      writePrimArray edges (e * 4 + 1) y1+      writePrimArray edges (e * 4 + 2) x0+      writePrimArray edges (e * 4 + 3) slope+      writePrimArray windings e (dir :: Int)+    let firstRow !r+          | r >= height = pure height+          | otherwise = readPrimArray rowStart (r + 1) >>= \e -> if e > 0 then pure r else firstRow (r + 1)+    top <- firstRow 0+    active <- newPrimArray totalEdges+    crossX <- newPrimArray totalEdges+    crossDir <- newPrimArray totalEdges+    let samples = 5 :: Int+        weight = 1 / fromIntegral samples :: Float+        inside :: Int -> Bool+        inside = P.fillsWinding $ case rule of+          NonZero -> P.NonZero+          EvenOdd -> P.EvenOdd+        add !i !v = readPrimArray cov i >>= \c -> writePrimArray cov i (c + v)+        spanCover !xa0 !xb0 = do+          let !xa = clamp 0 (fromIntegral width) xa0+              !xb = clamp 0 (fromIntegral width) xb0+          when (xb > xa) $ do+            let !ia = floor xa :: Int+                !ib = min (width - 1) (floor xb)+            if ia == ib+              then add ia ((xb - xa) * weight)+              else do+                add ia ((fromIntegral (ia + 1) - xa) * weight)+                let fillSpan !i+                      | i >= ib = pure ()+                      | otherwise = add i weight >> fillSpan (i + 1)+                fillSpan (ia + 1)+                when (ib < width) $ add ib ((xb - fromIntegral ib) * weight)+        admit !e !stop !n+          | e >= stop = pure n+          | otherwise = writePrimArray active n e >> admit (e + 1) stop (n + 1)+        insertCrossing !j !x !d+          | j > 0 = do+              xj <- readPrimArray crossX (j - 1)+              if xj > x+                then do+                  writePrimArray crossX j xj+                  readPrimArray crossDir (j - 1) >>= writePrimArray crossDir j+                  insertCrossing (j - 1) x d+                else writePrimArray crossX j x >> writePrimArray crossDir j (d :: Int)+          | otherwise = writePrimArray crossX 0 x >> writePrimArray crossDir 0 d+        walk !crossings !k !w+          | k + 1 >= crossings = pure ()+          | otherwise = do+              d <- readPrimArray crossDir k+              let !w' = w + d+              when (inside w') $ do+                xa <- readPrimArray crossX k+                xb <- readPrimArray crossX (k + 1)+                spanCover xa xb+              walk crossings (k + 1) w'+        sample !r !si !n !a !kept !crossings+          | a < n = do+              e <- readPrimArray active a+              let !sy = fromIntegral r + (fromIntegral si + 0.5) * weight+              y1 <- readPrimArray edges (e * 4 + 1)+              if y1 <= sy+                then sample r si n (a + 1) kept crossings+                else do+                  writePrimArray active kept e+                  y0 <- readPrimArray edges (e * 4)+                  if sy < y0+                    then sample r si n (a + 1) (kept + 1) crossings+                    else do+                      x0 <- readPrimArray edges (e * 4 + 2)+                      slope <- readPrimArray edges (e * 4 + 3)+                      d <- readPrimArray windings e+                      insertCrossing crossings (x0 + (sy - y0) * slope) d+                      sample r si n (a + 1) (kept + 1) (crossings + 1)+          | otherwise = do+              walk crossings 0 0+              if si + 1 < samples+                then sample r (si + 1) kept 0 0 0+                else onRow r >> rows (r + 1) kept+        rows !r !n+          | r >= height = pure ()+          | otherwise = do+              from <- readPrimArray rowStart r+              to <- readPrimArray rowStart (r + 1)+              if n == 0 && from >= totalEdges+                then pure ()+                else admit from to n >>= \n' -> sample r 0 n' 0 0 0+    rows top 0++-- | Composite one row @r@ from the single-row coverage buffer @cov@ into the+-- 16-bit premultiplied RGBA accumulator @acc@, zeroing @cov@ as it goes.+compositeRow16 :: Int -> MutablePrimArray s Word16 -> MutablePrimArray s Float -> Color -> Float -> Int -> ST s ()+compositeRow16 width acc cov col alpha !row = go 0+  where+    !rowBase = row * width * 4+    !sr = fromIntegral (colorR col) * (65535.0 / 255.0) :: Float+    !sg = fromIntegral (colorG col) * (65535.0 / 255.0) :: Float+    !sb = fromIntegral (colorB col) * (65535.0 / 255.0) :: Float+    !aScale = alpha * fromIntegral (colorA col) / 255.0 :: Float+    {-# INLINE toW16 #-}+    toW16 :: Float -> Word16+    toW16 x+      | x <= 0 = 0+      | x >= 65535 = 65535+      | otherwise = fromIntegral (round x :: Int)+    go !x+      | x >= width = pure ()+      | otherwise = do+          c <- readPrimArray cov x+          when (c > 0) $ do+            writePrimArray cov x 0+            let !sa = min 1 c * aScale+                !invSa = 1 - sa+                !off = rowBase + x * 4+            dr <- readPrimArray acc off+            dg <- readPrimArray acc (off + 1)+            db <- readPrimArray acc (off + 2)+            da <- readPrimArray acc (off + 3)+            writePrimArray acc off (toW16 (sr * sa + fromIntegral dr * invSa))+            writePrimArray acc (off + 1) (toW16 (sg * sa + fromIntegral dg * invSa))+            writePrimArray acc (off + 2) (toW16 (sb * sa + fromIntegral db * invSa))+            writePrimArray acc (off + 3) (toW16 (65535.0 * sa + fromIntegral da * invSa))+          go (x + 1)
lib/NanoUI/Testing.hs view
@@ -4,16 +4,16 @@ module NanoUI.Testing   ( -- * Frame     runFrame-  , runFrameEff-  , runFrameReduce-  , runFrameReduceEff   , needsRedraw   , pointerDragActive   , textFieldActive+  , textInputArea+  , TextInputArea (..)   , floatingPanelActive   , floatingPanelRects-  , debugPanelOpen+  , floatingWindowOpen   , widgetNodeCount+  , NodeType (..)   , pointerCursorWanted   , cursorKindIs   , uiCursorKind@@ -21,8 +21,11 @@   , computePopupPosition   , scrollBarLayout   , ScrollBarLayout (..)+  , ScrollBarSlot (..)+  , DirTag (..)   , sliderTrackBounds   , colorPickerSvSquare+  , WidgetStore   , widgetStoreBaseColor   , widgetStoreColor   , collectTextSpans@@ -39,24 +42,32 @@   , newPixelContext   , ctxTheme   , ctxPaintFull+  , setDrawReuse   , ctxFontMetrics   , setHost+  , Host+  , newHost   , askHost   , withFontMetrics   , withMonoFontMetrics   , withMeasureText   , withFontResolver+  , withFontSize   , wrapMeasureCache-  , withExternalText   , enableMeasureCache   , withTheme-  , setTheme-  , getTheme+  , setThemeIO+  , getThemeIO+  , followSystemThemeIO   , markDirty   , clearDirty   , clearMeasureCache   , isDirty+  , lastFramePasses   , setWakeLoop+  , requestWakeAt+  , requestWakeAfter+  , getWakeAt   , DamageRequest (..)   , requestDamage   , damageWidget@@ -69,8 +80,23 @@   , getPrevRect   , getPrevClipRect   , getStore-  , getScrollOffset-  , setScrollOffset+  , getScrollOffsetIO+  , setScrollOffsetIO+  , getScrollOffset2DIO+  , setScrollOffset2DIO+  , getScrollMetricsIO+  , getScrollTuningIO+  , setScrollTuningIO+  , getScrollStepIO+  , setScrollStepIO+  , scrollToIO+  , scrollByIO+  , scrollPagesIO+  , scrollToStartIO+  , scrollToEndIO+  , scrollIntoViewIO+  , scrollRectIntoViewIO+  , scrollGlidingIO   , textInputEditActive   , modalActive   , overlayConsumesQuit@@ -87,18 +113,15 @@   , registerImages   , atlasTextureId   , atlasSnapshot-    -- * Messages-  , FrameMsg (..)-  , decodeMessages-  , reduceMessages-  , reduceUpdates+  , atlasChanges+  , AtlasUpload (..)     -- * Draw   , DrawData (..)   , DrawCmd (..)   , DrawOp (..)+  , Shade (..)   , drawTextBox   , Layer (..)-  , LayerSlice (..)   , drawCmdNull   , drawCmdElems   , forDrawCmdsInLayer_@@ -107,140 +130,122 @@   , indexSize   , backdropDimTextureId   , glyphAtlasTextureId+  , glyphAtlasPages+  , glyphPageTextureId+  , textureGlyphPage   , Damage (..)   , takeDamage+  , takeDamagePieces+  , damagePieces   , damageIsEmpty-    -- * Effectful-  , Eff-  , runEff-  , IOE-  , type (:>)+  , clipPixelEdges+    -- * View   , askContext   , askInput-  , Ui-  , uiIO-    -- * Compact-  , Compact-  , compactHost-  , askCompact+  , liftIO     -- * Text measurement   , lineWidth   , textIndexAtX+  , WrapResult (..)+  , wrapTextIO+  , wrapTextLinesIO   , caretX   , selectionSpans+  , alignedTextPen+  , textInkEnd+  , textNodeFontVariant+  , textNodeFontTone   , textNodeFontWeight   , textNodeFontStyle   , textNodeTextDecoration   ) where -import NanoUI.Compact (Compact, askCompact, compactHost)-import NanoUI.Context-  ( Context (..)-  , FrameMsg (..)-  , anyAnimating-  , atlasSnapshot-  , atlasTextureId-  , clearDirty-  , clearMeasureCache-  , ctxTheme-  , DamageRequest (..)-  , damageFull-  , damageKey-  , damagePeers-  , damageRect-  , damageWidget-  , decodeMessages-  , enableMeasureCache-  , getAnimationValue-  , getFocusId-  , getHotId-  , getPrevRect-  , getPrevClipRect-  , getScrollOffset-  , setScrollOffset-  , getStore-  , isDirty-  , markDirty-  , modalActive-  , overlayConsumesQuit-  , reduceMessages-  , reduceUpdates-  , registerImage-  , registerImages-  , requestDamage-  , setAnimationValue-  , setHost-  , setWakeLoop-  , startAnimation-  , startAnimationEase-  , startAnimationEaseDelay-  , startSpring-  , takeDamage-  , textInputEditActive-  , withClipboard-  , withExternalText-  , withFontMetrics-  , withMeasureText-  , withFontResolver-  , withMonoFontMetrics-  , withTheme-  , setTheme-  , getTheme-  , wrapMeasureCache-  )-import NanoUI.Context (newContext, newPixelHostContext)-import NanoUI.Frame.SpanArena (SpanArena, foldSpanArena, spanArenaCount)-import NanoUI.Draw-  ( DrawCmd (..)-  , DrawData (..)-  , DrawOp (..)-  , Layer (..)-  , LayerSlice (..)-  , backdropDimTextureId-  , glyphAtlasTextureId-  , drawCmdElems-  , forDrawCmdsInLayer_-  , drawCmdNull-  , drawCmdCount-  , drawTextBox-  , drawVertices-  , indexSize-  , vertexSize-  )-import NanoUI.Damage (floatingPanelRects)-import NanoUI.Font (caretX, lineWidth, selectionSpans, sliderTrackBounds, textIndexAtX)-import NanoUI.Widgets.ColorPicker-  ( colorPickerSvSquare-  , widgetStoreBaseColor-  , widgetStoreColor-  )-import NanoUI.Frame-  ( UiCursorKind (..)-  , collectOverlayTextSpans-  , collectRasterSpans-  , collectTextSpans-  , cursorKindIs-  , debugPanelOpen-  , floatingPanelActive-  , needsRedraw-  , pointerCursorWanted-  , pointerDragActive-  , runFrame-  , runFrameEff-  , runFrameReduce-  , runFrameReduceEff-  , textFieldActive-  , uiCursorKind-  , widgetNodeCount-  )-import NanoUI.Frame.Scroll (ScrollBarLayout (..), scrollBarLayout)-import NanoUI.Layout.Solve (computePopupPosition)-import NanoUI.Monad (Ui, askContext, askHost, askInput, uiIO)-import NanoUI.WidgetText (textNodeFontStyle, textNodeFontWeight, textNodeTextDecoration)-import NanoUI.Types (Damage (..), damageIsEmpty)-import Effectful (Eff, IOE, runEff, type (:>))+import NanoUI.Backend (followSystemThemeIO, getThemeIO, setThemeIO)+import NanoUI.Internal.Context qualified as Ctx+import NanoUI.Internal.Context hiding (followSystemTheme, getScrollMetrics, getScrollOffset, getScrollOffset2D, getScrollStep, getScrollTuning, getTheme, scrollBy, scrollGliding, scrollIntoView, scrollPages, scrollRectIntoView, scrollTo, scrollToEnd, scrollToStart, setScrollOffset, setScrollOffset2D, setScrollStep, setScrollTuning, setTheme)+import NanoUI.Internal.Frame.SpanArena (SpanArena, foldSpanArena, spanArenaCount)+import NanoUI.Internal.Draw+import NanoUI.Internal.Damage (clipPixelEdges, damagePieces, floatingPanelRects)+import NanoUI.Internal.Font (ScrollBarSlot (..), WrapResult (..), alignedTextPen, caretX, lineWidth, selectionSpans, sliderTrackBounds, textIndexAtX, textInkEnd, wrapTextIO, wrapTextLinesIO)+import NanoUI.Internal.Widgets.ColorPicker+import NanoUI.Internal.Frame (runFrame)+import NanoUI.Internal.Frame.Cursor (UiCursorKind (..), cursorKindIs, pointerCursorWanted, uiCursorKind)+import NanoUI.Internal.Frame.Input+import NanoUI.Internal.Frame.Spans (collectOverlayTextSpans, collectRasterSpans, collectTextSpans, widgetNodeCount)+import NanoUI.Internal.Frame.Scroll (ScrollBarLayout (..), scrollBarLayout)+import NanoUI.Internal.Frame.TextArea (TextInputArea (..), textInputArea)+import NanoUI.Internal.Layout.Arena (DirTag (..), NodeType (..))+import NanoUI.Internal.Layout.Solve (computePopupPosition)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Monad (askContext, askHost, askInput, liftIO)+import NanoUI.Internal.WidgetText (textNodeFontStyle, textNodeFontTone, textNodeFontVariant, textNodeFontWeight, textNodeTextDecoration)+import NanoUI.Internal.Types (Damage (..), Rect, V2, damageIsEmpty)+import NanoUI.Internal.Var (lastFramePasses) --- | A headless context for tests: 16px monospace metrics, the measure cache--- on, text kept out of the vertex buffer, and the default theme.-newPixelContext :: IO Context-newPixelContext = newPixelHostContext+-- | Read the main-axis scroll offset of a scroller from outside a view.+getScrollOffsetIO :: Context -> WidgetId -> IO Float+getScrollOffsetIO = Ctx.getScrollOffset++-- | Set the main-axis scroll offset of a scroller from outside a view.+setScrollOffsetIO :: Context -> WidgetId -> Float -> IO ()+setScrollOffsetIO = Ctx.setScrollOffset++-- | Read both axes of a scroller's stored offset from outside a view.+getScrollOffset2DIO :: Context -> WidgetId -> IO V2+getScrollOffset2DIO = Ctx.getScrollOffset2D++-- | Set both axes of a scroller's stored offset from outside a view.+setScrollOffset2DIO :: Context -> WidgetId -> V2 -> IO ()+setScrollOffset2DIO = Ctx.setScrollOffset2D++-- | Read a scroller's cached metrics from outside a view.+getScrollMetricsIO :: Context -> WidgetId -> IO (Maybe ScrollMetrics)+getScrollMetricsIO = Ctx.getScrollMetrics++-- | Read the context's global scroll tuning from outside a view.+getScrollTuningIO :: Context -> IO ScrollTuning+getScrollTuningIO = Ctx.getScrollTuning++-- | Set the context's global scroll tuning from outside a view.+setScrollTuningIO :: Context -> ScrollTuning -> IO ()+setScrollTuningIO = Ctx.setScrollTuning++-- | Read a scroller's wheel step override from outside a view.+getScrollStepIO :: Context -> WidgetId -> IO Float+getScrollStepIO = Ctx.getScrollStep++-- | Set a scroller's wheel step override from outside a view.+setScrollStepIO :: Context -> WidgetId -> Float -> IO ()+setScrollStepIO = Ctx.setScrollStep++-- | Scroll to an offset from outside a view.+scrollToIO :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()+scrollToIO = Ctx.scrollTo++-- | Scroll by a pixel delta from outside a view.+scrollByIO :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()+scrollByIO = Ctx.scrollBy++-- | Scroll by viewport fractions from outside a view.+scrollPagesIO :: Context -> WidgetId -> V2 -> ScrollBehavior -> IO ()+scrollPagesIO = Ctx.scrollPages++-- | Scroll to the start from outside a view.+scrollToStartIO :: Context -> WidgetId -> ScrollBehavior -> IO ()+scrollToStartIO = Ctx.scrollToStart++-- | Scroll to the end from outside a view.+scrollToEndIO :: Context -> WidgetId -> ScrollBehavior -> IO ()+scrollToEndIO = Ctx.scrollToEnd++-- | Scroll a target widget into a scroller's viewport from outside a view.+scrollIntoViewIO :: Context -> WidgetId -> WidgetId -> ScrollAlign -> ScrollBehavior -> IO ()+scrollIntoViewIO = Ctx.scrollIntoView++-- | Scroll a content rectangle into a scroller's viewport from outside a view.+scrollRectIntoViewIO :: Context -> WidgetId -> Rect -> ScrollAlign -> ScrollBehavior -> IO ()+scrollRectIntoViewIO = Ctx.scrollRectIntoView++-- | Whether a scroller has a smooth-scroll glide in flight.+scrollGlidingIO :: Context -> WidgetId -> IO Bool+scrollGlidingIO = Ctx.scrollGliding
lib/NanoUI/Testing/Assert.hs view
@@ -1,27 +1,33 @@ -- | Assertion and frame helpers for the integration test suite. ----- Assertions count failures in a shared 'IORef' instead of aborting, so one+-- Assertions count failures in a shared 'Data.IORef.IORef' instead of aborting, so one -- test reports every broken expectation. Each failure prints the caller's--- source location and, where there are any, the compared values.+-- source location and, where there are any, the compared values. 'require'+-- and 'requireEq' fail at once instead, for a suite whose later checks make+-- no sense after a miss. module NanoUI.Testing.Assert   ( bump   , assert   , assertEq   , assertGt   , assertLt+  , assertJust+  , assertJustM+  , require+  , requireEq   , withInput   , run2Frames   , evalUi-  , runClickReduce   ) where  import Control.Monad (unless, when) import Data.IORef (IORef, modifyIORef')-import Data.Typeable (Typeable) import GHC.Stack (HasCallStack, callStack, prettyCallStack, withFrozenCallStack)-import NanoUI (emptyInput, Input (..), NanoUI, Response (..), Size (..), V2 (..))-import NanoUI.Testing (Context, DrawData, FrameMsg, runFrame, runFrameReduce)+import NanoUI (Input (..), NanoUI, Size (..))+import NanoUI.Backend (emptyInput)+import NanoUI.Testing (Context, DrawData, runFrame) +-- | Increment a test's failure counter without printing a diagnostic. bump :: IORef Int -> IO () bump r = modifyIORef' r (+ 1) @@ -32,55 +38,50 @@   putStrLn (prettyCallStack callStack)   bump r +-- | Count and report a failure when the condition is false, then continue. assert :: HasCallStack => IORef Int -> Bool -> IO () assert r ok = unless ok (withFrozenCallStack (failWith r "")) +-- | Require equality, printing both values and the call site on failure. assertEq :: (HasCallStack, Eq a, Show a) => IORef Int -> a -> a -> IO () assertEq r a b = when (a /= b) (withFrozenCallStack (failWith r (show a <> " /= " <> show b))) +-- | Require the first value to be strictly greater than the second. assertGt :: (HasCallStack, Ord a, Show a) => IORef Int -> a -> a -> IO () assertGt r a b = when (a <= b) (withFrozenCallStack (failWith r (show a <> " <= " <> show b))) +-- | Require the first value to be strictly less than the second. assertLt :: (HasCallStack, Ord a, Show a) => IORef Int -> a -> a -> IO () assertLt r a b = when (a >= b) (withFrozenCallStack (failWith r (show a <> " >= " <> show b))) +-- | Run the continuation if the value is 'Just', or record a failure on 'Nothing'.+assertJust :: HasCallStack => IORef Int -> Maybe a -> (a -> IO ()) -> IO ()+assertJust r m k = maybe (withFrozenCallStack (failWith r "Nothing")) k m++-- | 'assertJust' on the result of an action.+assertJustM :: HasCallStack => IORef Int -> IO (Maybe a) -> (a -> IO ()) -> IO ()+assertJustM r act k = act >>= \m -> withFrozenCallStack (assertJust r m k)++-- | Fail at once, naming the check and the caller's line, unless the+-- condition holds.+require :: HasCallStack => String -> Bool -> IO ()+require name ok = unless ok (ioError (userError (name <> "\n" <> prettyCallStack callStack)))++-- | Fail at once unless the second value (got) equals the first (wanted),+-- printing both.+requireEq :: (HasCallStack, Eq a, Show a) => String -> a -> a -> IO ()+requireEq name want got =+  withFrozenCallStack (require (name <> ": wanted " <> show want <> ", got " <> show got) (want == got))++-- | Event-free input for a logical window width and height. withInput :: Float -> Float -> Input withInput w h = emptyInput {inputWindowSize = Size w h} -run2Frames :: Context -> Input -> NanoUI a -> IO (a, [FrameMsg], DrawData, Bool)-run2Frames ctx inp ui = do-  _ <- runFrame ctx inp ui-  runFrame ctx inp ui+-- | Run twice with the same input and return the second frame. Use event-free+-- input for warmup; press/key events would otherwise be delivered twice.+run2Frames :: Context -> Input -> NanoUI a -> IO (a, DrawData, Bool)+run2Frames ctx inp ui = runFrame ctx inp ui >> runFrame ctx inp ui +-- | Run a complete headless frame and return only the view's result. evalUi :: Context -> Input -> NanoUI a -> IO a-evalUi ctx inp ui = do-  (a, _, _, _) <- runFrame ctx inp ui-  pure a--runClickReduce ::-  (Typeable msg, Eq model) =>-  (msg -> model -> model)-  -> Context-  -> Input-  -> model-  -> (model -> NanoUI Response)-  -> V2-  -> IO (model, [msg], Bool)-runClickReduce reduce ctx inp0 model0 view pos = do-  let-    press =-      inp0-        { inputMousePos = pos-        , inputMouseDown = True-        , inputMousePressed = True-        , inputMouseReleased = False-        }-    release =-      press-        { inputMousePressed = False-        , inputMouseDown = False-        , inputMouseReleased = True-        }-  (_, modelP, _, _, _) <- runFrameReduce reduce ctx press model0 view-  (_, modelR, msgs, _, dirty) <- runFrameReduce reduce ctx release modelP view-  pure (modelR, msgs, dirty)+evalUi ctx inp ui = (\(a, _, _) -> a) <$> runFrame ctx inp ui
lib/NanoUI/Testing/Harness.hs view
@@ -1,31 +1,41 @@ -- | Shared helpers for integration tests: input gestures, spans, scroll checks. module NanoUI.Testing.Harness-  ( clickPair+  ( -- * Input gestures+    clickPair+  , clickPairWith   , rightClickPair   , pressAt+  , pressWith+  , holdAt   , releaseAt+  , releaseWith   , keyInp+  , keyRepeatInp+  , chordInp+  , keyUpInp   , tabInp   , withInputOff   , withDelta   , centerOf++    -- * Frame warmup and interaction drivers   , warmup   , warmup2   , warmupDraw+  , warmupFocused+  , setFocus   , held   , runClick-  , assertSpansHas-  , spanYOf-  , spanXOf-  , assertScrollGutterPad-  , assertWheelTitlePinned-  , findGrabHover-  , dragWindowEdge-  , vertUv-  , checkLabelAlignEndInk-  , checkIdleFullDamage-  , windowTitleGrab+  , runRightClick   , runDragFrom+  , clickPos+  , clickTab+  , dragPos+  , dragWindowEdge+  , findGrabHover+  , cursorOver++    -- * Text spans and bounds   , DemoSpan   , spanCenter   , hasText@@ -35,87 +45,175 @@   , findRightmost   , requireSpan   , expectText-  , clickPos-  , clickTab-  , dragPos+  , assertSpansHas+  , spanYOf+  , spanXOf+  , spanRect+  , spanRectOf+  , covers+  , clipCovers+  , damageCovers++    -- * Draw buffer and arena inspection+  , Vertex (..)+  , vertexColor+  , vertUv+  , drawnVertices+  , indexedVertices+  , textureVertices+  , drawTriangles+  , trianglePicture   , drawQuads+  , nodesOfType++    -- * Timing, wakes, and benchmarks+  , FrameCost (..)+  , frameCost+  , newWakeSignal+  , measureRuns   ) where -import Control.Monad (forM, unless, void, when)-import Data.IORef (IORef, readIORef, writeIORef)+import Control.Applicative ((<|>))+import Control.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar, tryTakeMVar)+import Control.Monad (filterM, foldM, forM, forM_, replicateM_, unless, void, when)+import Data.Hashable (hash, hashWithSalt)+import Data.IORef (IORef, writeIORef)+import Data.List (maximumBy)+import Data.Map.Strict qualified as M+import Data.Maybe (fromMaybe, isJust, listToMaybe)+import Data.Ord (comparing) import Data.Text qualified as T import Data.Word (Word32, Word8)-import Foreign.C.Types (CSize (..)) import Foreign.ForeignPtr (withForeignPtr)-import Foreign.Marshal.Alloc (allocaBytes)-import Foreign.Ptr (Ptr, plusPtr)+import Foreign.Ptr (Ptr) import Foreign.Storable (peekByteOff)+import GHC.Clock (getMonotonicTimeNSec) import GHC.Stack (HasCallStack)+import GHC.Stats (RTSStats (..), getRTSStats) import NanoUI-import NanoUI.Font (alignedTextPen, textInkEnd)+import NanoUI.Backend+import NanoUI.Internal.Context (ctxFocusId, ctxNodeArena, takeWakes)+import NanoUI.Internal.Layout.Arena (arenaCount, getNodeRect, getNodeType, getWidgetId)+import NanoUI.Internal.Types (clamp)+import NanoUI.Shortcut (Shortcut (..))+import NanoUI.Var (peekVar) import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertLt, bump, withInput)+import NanoUI.Testing.Assert (assert, evalUi, run2Frames, withInput)+import System.Environment (lookupEnv)+import System.Mem (performGC)+import System.Timeout (timeout)+import Text.Printf (printf)+import Text.Read (readMaybe) +-- | Text bounds, text, foreground, background, and clip in logical window coordinates. type DemoSpan = (Rect, T.Text, Color, Color, Rect) -foreign import ccall unsafe "string.h memcpy" c_memcpy :: Ptr Word8 -> Ptr Word8 -> CSize -> IO ()+-- | One vertex of a frame's draw buffer: position, colour, alpha and UV.+data Vertex = Vertex {vX, vY :: Float, vRgb :: (Float, Float, Float), vA, vU, vV :: Float}+  deriving (Eq, Show) +-- The vertex at index @i@, read at the buffer's vertex stride.+vertexAt :: Ptr Word8 -> Int -> IO Vertex+vertexAt vp i = Vertex <$> at 0 <*> at 4 <*> ((,,) <$> at 8 <*> at 12 <*> at 16) <*> at 20 <*> at 24 <*> at 28+  where+    at o = peekByteOff vp (i * vertexSize + o) :: IO Float++-- | A vertex's colour and alpha as a 'Color'.+vertexColor :: Vertex -> Color+vertexColor v = let (r, g, b) = vRgb v in colorRGBA (byte r) (byte g) (byte b) (byte (vA v))+  where+    byte f = clamp 0 255 (round (f * 255))++-- | Every vertex of a frame, in buffer order. The draw buffers are borrowed:+-- read them before the context's next frame.+drawnVertices :: DrawData -> IO [Vertex]+drawnVertices dd = withForeignPtr (drawVertices dd) $ \vp -> mapM (vertexAt vp) [0 .. drawVertexCount dd - 1]++-- | The vertex each of these index-buffer positions names.+indexedVertices :: DrawData -> [Int] -> IO [Vertex]+indexedVertices dd is =+  withForeignPtr (drawVertices dd) $ \vp -> withForeignPtr (drawIndices dd) $ \ip ->+    forM is $ \i -> (peekByteOff ip (i * indexSize) :: IO Word32) >>= vertexAt vp . fromIntegral++-- The index-buffer positions a draw command covers.+cmdIndices :: DrawCmd -> [Int]+cmdIndices c = [fromIntegral (cmdIndexOffset c) .. fromIntegral (cmdIndexOffset c + cmdIndexCount c) - 1]++-- | The vertices the commands drawn from texture @tex@ index, in order.+textureVertices :: Int -> DrawData -> IO [Vertex]+textureVertices tex dd =+  indexedVertices dd (concat [cmdIndices c | c <- drawCmdElems dd, cmdTextureId c == tex])++-- | Every indexed triangle of a frame.+drawTriangles :: DrawData -> IO [(Vertex, Vertex, Vertex)]+drawTriangles dd = triples <$> indexedVertices dd [0 .. drawIndexCount dd - 1]+  where+    triples (a : b : c : rest) = (a, b, c) : triples rest+    triples _ = []++-- | A frame's draw triangles as a multiset, for comparing the pictures of+-- two frames. Each key hashes a triangle's vertices with the texture and+-- clip of the command that draws it, and maps to how many such triangles+-- the frame draws and the part of their bounding box inside that clip. The+-- draw buffers are borrowed: read them before the context's next frame.+trianglePicture :: DrawData -> IO (M.Map Int (Int, Rect))+trianglePicture dd =+  withForeignPtr (drawVertices dd) $ \vp -> withForeignPtr (drawIndices dd) $ \ip ->+    foldM (addCmd vp ip) M.empty (drawCmdElems dd)+  where+    addCmd vp ip acc c = do+      let clip = Rect (cmdClipX c) (cmdClipY c) (cmdClipW c) (cmdClipH c)+          salt = hash (cmdTextureId c, (cmdClipX c, cmdClipY c, cmdClipW c, cmdClipH c))+          start = fromIntegral (cmdIndexOffset c) :: Int+          corner t k = (peekByteOff ip ((start + 3 * t + k) * indexSize) :: IO Word32) >>= vertexAt vp . fromIntegral+          add m t = do+            vs <- mapM (corner t) [0, 1, 2]+            let shown = fromMaybe (Rect 0 0 0 0) (rectIntersect (vertexBounds vs) clip)+                key = foldl' hashVertex salt vs+            pure $! M.insertWith (\(i, r) (j, _) -> (i + j, r)) key (1, shown) m+      foldM add acc [0 .. fromIntegral (cmdIndexCount c) `quot` 3 - 1]+    hashVertex s v =+      let (r, g, b) = vRgb v+       in s `hashWithSalt` vX v `hashWithSalt` vY v `hashWithSalt` r `hashWithSalt` g `hashWithSalt` b+            `hashWithSalt` vA v `hashWithSalt` vU v `hashWithSalt` vV v++vertexBounds :: [Vertex] -> Rect+vertexBounds vs =+  let xs = map vX vs+      ys = map vY vs+   in Rect (minimum xs) (minimum ys) (maximum xs - minimum xs) (maximum ys - minimum ys)+ -- | Decode the quads a frame actually rasterised: one @(rect, color)@ per--- six-index quad, in draw order. Span and arena queries cannot see chrome--- (scroller wells, scrollbar lanes); this can. Every rasterised op in the--- draw arena is emitted as 4 vertices / 6 indices; a command that breaks--- that packing fails loudly here instead of decoding garbage.+-- six-index quad, in draw order. Unlike span and arena queries, this includes+-- widget chrome such as scroller wells and scrollbar lanes. Use only with+-- quad-packed output, such as square-geometry test contexts. Triangle and+-- rounded-shape output is not supported. Commands with counts not divisible by+-- six throw. drawQuads :: DrawData -> IO [(Rect, Color)]-drawQuads dd =-  fmap concat $-    forM (drawCmdElems dd) $ \c -> do-      let ioff = fromIntegral (cmdIndexOffset c)-          icnt = fromIntegral (cmdIndexCount c)-      when (icnt `rem` 6 /= 0) $-        error ("drawQuads: draw command packs " ++ show icnt ++ " indices; not quad-packed")-      sequence-        [ decodeQuad (ioff + q)-        | q <- [0, 6 .. icnt - 1]-        ]+drawQuads dd = do+  forM_ (drawCmdElems dd) $ \c ->+    when (cmdIndexCount c `rem` 6 /= 0) $+      error ("drawQuads: draw command packs " ++ show (cmdIndexCount c) ++ " indices; not quad-packed")+  quads <$> indexedVertices dd (concatMap cmdIndices (drawCmdElems dd))   where-    verts = drawVertices dd-    idxs = drawIndices dd-    peekWord32 :: Ptr Word8 -> IO Word32-    peekWord32 off = allocaBytes 4 $ \tmp -> do-      c_memcpy tmp off 4-      peekByteOff tmp 0-    peekVertex :: Ptr Word8 -> Int -> IO (Float, Float, Float, Float, Float, Float)-    peekVertex vp vi =-      allocaBytes vertexSize $ \tmp -> do-        c_memcpy tmp (vp `plusPtr` (vi * vertexSize)) (fromIntegral vertexSize)-        x <- peekByteOff tmp 0-        y <- peekByteOff tmp 4-        r <- peekByteOff tmp 8-        g <- peekByteOff tmp 12-        b <- peekByteOff tmp 16-        a <- peekByteOff tmp 20-        pure (x, y, r, g, b, a)-    decodeQuad iStart =-      withForeignPtr verts $ \vp ->-        withForeignPtr idxs $ \ip -> do-          vis <--            forM [iStart .. iStart + 3] $ \ii -> do-              vi <- fromIntegral <$> peekWord32 (ip `plusPtr` (ii * indexSize))-              peekVertex vp vi-          case vis of-            [] -> pure (Rect 0 0 0 0, colorRGBA 0 0 0 0)-            (x0, y0, r0, g0, b0, a0) : rest -> do-              let xs = x0 : map (\(x, _, _, _, _, _) -> x) rest-                  ys = y0 : map (\(_, y, _, _, _, _) -> y) rest-                  toW8 f = max 0 (min 255 (round (f * 255)))-              pure-                ( Rect (minimum xs) (minimum ys) (maximum xs - minimum xs) (maximum ys - minimum ys)-                , colorRGBA (toW8 r0) (toW8 g0) (toW8 b0) (toW8 a0)-                )+    -- Each quad's 6 indices are [a, b, c, a, c, d]; corners are a, b, c, d.+    quads vs = case splitAt 6 vs of+      (a : b : c : _ : _ : d : _, rest) -> (vertexBounds [a, b, c, d], vertexColor a) : quads rest+      _ -> [] +-- | Ids and rects of the frame's nodes of one type, in arena order.+nodesOfType :: NodeType -> Context -> IO [(WidgetId, Rect)]+nodesOfType wanted ctx = do+  let na = ctxNodeArena ctx+  n <- arenaCount na+  matching <- filterM (fmap (== wanted) . getNodeType na) [0 .. n - 1]+  forM matching $ \i -> (,) <$> getWidgetId na i <*> getNodeRect na i++-- | Midpoint of a logical rectangle, without clipping it. spanCenter :: Rect -> V2 spanCenter (Rect x y w h) = V2 (x + w / 2) (y + h / 2) +-- | Whether any span contains the text as a substring. hasText :: T.Text -> [(Rect, T.Text, a, b, c)] -> Bool hasText needle = any (\(_, txt, _, _, _) -> needle `T.isInfixOf` txt) @@ -124,9 +222,12 @@ dropSpanMarkers :: T.Text -> T.Text dropSpanMarkers = T.dropWhile (`elem` ['\x01', '\x02', '\x05']) +-- | Trim surrounding whitespace and remove leading internal blank-glyph markers. spanLabel :: T.Text -> T.Text spanLabel txt = dropSpanMarkers (T.strip txt) +-- | Centre of the rightmost nontrivial span with an exact normalised label.+-- Returns 'Nothing' when none matches. findExact :: T.Text -> [DemoSpan] -> Maybe V2 findExact needle spans =   pickRight@@ -136,37 +237,34 @@     , spanLabel txt == needle     ] +-- | Find a table-header centre: a span that is the needle plus padding, or+-- else the rightmost span labelled exactly the needle ('findExact'). Text+-- that only starts with the needle, such as "Name (asc)", never matches.+-- Current tables draw their sort mark as a style flag, not padding, so their+-- headers come from the 'findExact' fallback, and a view with another label+-- of the same text to the right needs a finder of its own. findHeader :: T.Text -> [DemoSpan] -> Maybe V2 findHeader needle spans =-  -- Header spans keep their sort-reserve padding ("Name   " with the arrow-  -- glyph blanked when unsorted), while every other "Name" label is trimmed.-  -- Match the raw, untrimmed text so the header wins over right-aligned kv-  -- values that happen to repeat the column name.   let marked =         [ (x, spanCenter r)         | (r@(Rect x _ w h), txt, _, _, _) <- spans         , w > 1 && h > 1-        , T.isPrefixOf (needle <> " ") (dropSpanMarkers txt)-        ]-      exact =-        [ (x, spanCenter r)-        | (r@(Rect x _ w h), txt, _, _, _) <- spans-        , w > 1 && h > 1-        , spanLabel txt == needle+        , let raw = dropSpanMarkers txt+        , T.strip raw == needle && T.length raw > T.length needle         ]-   in pickRight (if null marked then exact else marked)+   in pickRight marked <|> findExact needle spans +-- | Centre of the rightmost span containing the substring, or 'Nothing'. findRightmost :: T.Text -> [DemoSpan] -> Maybe V2 findRightmost needle spans =   pickRight [(x, spanCenter r) | (r@(Rect x _ _ _), txt, _, _, _) <- spans, needle `T.isInfixOf` txt]  pickRight :: [(Float, V2)] -> Maybe V2 pickRight [] = Nothing-pickRight (p : ps) = Just (go p ps)- where-  go acc [] = snd acc-  go acc@(ax, _) (q@(qx, _) : qs) = go (if qx >= ax then q else acc) qs+-- maximumBy keeps the later of equal elements, so ties choose the rightmost.+pickRight ps = Just (snd (maximumBy (comparing fst) ps)) +-- | Return a located point or throw an IO error with the supplied diagnostic. requireSpan :: String -> Maybe V2 -> IO V2 requireSpan msg = maybe (fail msg) pure @@ -178,6 +276,7 @@ clickPos :: (Input -> IO ()) -> Input -> V2 -> IO () clickPos drawFrame base pos = dragPos drawFrame base pos pos +-- | Locate a named tab from text spans and drive a click. Fails if absent. clickTab :: (Context -> IO [DemoSpan]) -> (Input -> IO ()) -> Context -> Input -> T.Text -> IO () clickTab getSpans drawFrame ctx base name = do   spans <- getSpans ctx@@ -188,187 +287,208 @@ dragPos :: (Input -> IO ()) -> Input -> V2 -> V2 -> IO () dragPos drawFrame base from to = do   let press = pressAt base from-      hold = press {inputMousePressed = False, inputMousePos = to}+      hold = holdAt base to   mapM_ drawFrame [press, hold, releaseAt hold, base, base] +-- | 'clickPairWith' 'MouseLeft'. clickPair :: Input -> V2 -> (Input, Input)-clickPair inp pos =-  let-    press = pressAt inp pos-    release = releaseAt press-   in-    (press, release)+clickPair = clickPairWith MouseLeft +-- | Press and release frames for the button at @pos@, keeping the base+-- input's other fields.+clickPairWith :: MouseButton -> Input -> V2 -> (Input, Input)+clickPairWith b inp pos = let press = pressWith b inp pos in (press, releaseWith b press)++-- | 'clickPairWith' 'MouseRight'. rightClickPair :: Input -> V2 -> (Input, Input)-rightClickPair inp pos =-  let-    press =-      inp-        { inputMousePos = pos-        , inputMouseRightDown = True-        , inputMouseRightPressed = True-        }-    release =-      press-        { inputMouseRightDown = False-        , inputMouseRightPressed = False-        , inputMouseRightReleased = True-        }-   in-    (press, release)+rightClickPair = clickPairWith MouseRight +-- | 'pressWith' 'MouseLeft'. pressAt :: Input -> V2 -> Input-pressAt inp pos =-  inp-    { inputMousePos = pos-    , inputMouseDown = True-    , inputMousePressed = True-    , inputMouseReleased = False-    }+pressAt = pressWith MouseLeft +-- | A frame where the button goes down at @pos@ and is not released.+pressWith :: MouseButton -> Input -> V2 -> Input+pressWith b inp pos =+  applyMouseButton b True inp {inputMousePos = pos, inputButtonsReleased = buttonsDelete b (inputButtonsReleased inp)}++-- | The button still down from an earlier 'pressAt', with the pointer at @pos@.+holdAt :: Input -> V2 -> Input+holdAt inp pos = unpress MouseLeft (pressAt inp pos)++-- | 'releaseWith' 'MouseLeft'. releaseAt :: Input -> Input-releaseAt press =-  press-    { inputMouseDown = False-    , inputMousePressed = False-    , inputMouseReleased = True-    }+releaseAt = releaseWith MouseLeft --- | A single key-down frame.+-- | A frame where the button comes up at the pointer, with no press.+releaseWith :: MouseButton -> Input -> Input+releaseWith b = applyMouseButton b False . unpress b++unpress :: MouseButton -> Input -> Input+unpress b inp = inp {inputButtonsPressed = buttonsDelete b (inputButtonsPressed inp)}++-- | A frame where the key goes down (not an auto-repeat). keyInp :: Key -> Input -> Input-keyInp k inp = inp {inputKeys = inputKeysFromList [k]}+keyInp k inp = inp {inputKeys = ks, inputKeysNew = ks}+  where+    ks = inputKeysFromList [k] +-- | A frame with one auto-repeat of a held key (pressed, but not new).+keyRepeatInp :: Key -> Input -> Input+keyRepeatInp k inp = inp {inputKeys = inputKeysFromList [k], inputKeysNew = mempty}++-- | A frame pressing a chord such as @ctrl <> key \'a\'@, with exactly the+-- chord's modifiers held.+chordInp :: Shortcut -> Input -> Input+chordInp (Shortcut k mods) inp =+  (maybe id (`applyKey` True) k inp {inputKeys = mempty, inputKeysNew = mempty}) {inputModifiers = mods}++-- | A frame releasing a key, which drops it from the held keys.+keyUpInp :: Key -> Input -> Input+keyUpInp k inp = applyKey k False inp {inputKeys = mempty, inputKeysNew = mempty, inputKeysReleased = mempty}+ -- | Step the tab focus to the next focusable. tabInp :: Input -> Input tabInp = keyInp KeyTab +-- | Event-free input with the requested window size and pointer at (-10,-10). withInputOff :: Float -> Float -> Input-withInputOff w h =-  let inp = withInput w h-   in inp {inputMousePos = V2 (-10) (-10)}+withInputOff w h = (withInput w h) {inputMousePos = V2 (-10) (-10)} +-- | Event-free input with logical width/height and elapsed time in seconds. withDelta :: Float -> Float -> Float -> Input-withDelta w h dt =-  let inp = withInput w h-   in inp {inputDeltaTime = dt}+withDelta w h dt = (withInput w h) {inputDeltaTime = dt} +-- | Centre of the response rectangle. Warm up the view before using it as a target. centerOf :: Response -> V2 centerOf = spanCenter . respRect +-- | Run one frame to establish previous geometry. Supply event-free input. warmup :: Context -> Input -> NanoUI a -> IO () warmup ctx inp ui = void (runFrame ctx inp ui) +-- | Run two frames and return the second result, whose responses can use solved+-- geometry from the first. Supply event-free input. warmup2 :: Context -> Input -> NanoUI a -> IO a-warmup2 ctx inp ui = do-  _ <- runFrame ctx inp ui-  (a, _, _, _) <- runFrame ctx inp ui-  pure a+warmup2 ctx inp ui = warmup ctx inp ui >> evalUi ctx inp ui +-- | Two-frame warmup returning the second result and borrowed drawing buffers. warmupDraw :: Context -> Input -> NanoUI a -> IO (a, DrawData)-warmupDraw ctx inp ui = do-  _ <- runFrame ctx inp ui-  (a, _, draw, _) <- runFrame ctx inp ui-  pure (a, draw)+warmupDraw ctx inp ui = (\(a, draw, _) -> (a, draw)) <$> run2Frames ctx inp ui --- | Drive a controlled input the way an application does: pass the value held--- in the test's 'IORef' and store the widget's result for the next frame. Not--- a hook: a hook write makes the frame run the view again without input, and--- the frame then returns that pass's result without its click or change flags.-held :: Ui :> es => IORef a -> (a -> Eff es (r, a)) -> Eff es (r, a)-held ref widget = do-  result <- widget =<< uiIO (readIORef ref)-  uiIO (writeIORef ref (snd result))-  pure result+-- | Warm the view up, then Tab onto its first focusable.+warmupFocused :: Context -> Input -> NanoUI a -> IO ()+warmupFocused ctx inp ui = warmup2 ctx inp ui >> void (runFrame ctx (tabInp inp) ui) +-- | Give @wid@ keyboard focus directly, as focus kept from earlier frames+-- does; the next frame sees it.+setFocus :: Context -> WidgetId -> IO ()+setFocus ctx = writeIORef (ctxFocusId ctx)++-- | Run a widget bound to a 'Var' and pair its result with the post-frame+-- 'Var' value. The read uses 'peekVar', so it adds no rerun of its own; a+-- view that reads the 'Var' before the widget mutates it will still rerun,+-- returning the second pass's result without click or change flags.+held :: Var a -> (Var a -> NanoUI r) -> NanoUI (r, a)+held v widget = (,) <$> widget v <*> peekVar v++-- | Per-frame test metrics: view pass count, resulting 'Damage', and number+-- of follow-up idle frames needed until the context is no longer dirty.+data FrameCost = FrameCost+  { fcPasses :: !Int+  , fcDamage :: !Damage+  , fcFollowUps :: !Int+  }+  deriving (Eq, Show)++-- | Run one frame of @ui@ with @inp@, counting its view passes, then frames+-- with @idle@ until one returns clean. Fails if eight of them do not settle.+frameCost :: Context -> Input -> Input -> NanoUI a -> IO (a, FrameCost)+frameCost ctx inp idle ui = do+  (a, _, dirty) <- runFrame ctx inp ui+  dmg <- takeDamage ctx+  n <- lastFramePasses ctx+  follow <- settle dirty 0+  pure (a, FrameCost n dmg follow)+  where+    settle dirty k+      | not dirty = pure k+      | k >= (8 :: Int) = fail "frameCost: the view never settled"+      | otherwise = do+          (_, _, d) <- runFrame ctx idle ui+          settle d (k + 1)++runClickWith :: MouseButton -> Context -> Input -> NanoUI a -> V2 -> IO a+runClickWith b ctx inp0 ui pos = let (press, release) = clickPairWith b inp0 pos in warmup ctx press ui >> evalUi ctx release ui+ -- | Run a press frame and a release frame at @pos@ ('clickPair'), returning -- the release frame's result. runClick :: Context -> Input -> NanoUI a -> V2 -> IO a-runClick ctx inp0 ui pos = do-  let-    (press, release) = clickPair inp0 pos-  _ <- runFrame ctx press ui-  (a, _, _, _) <- runFrame ctx release ui-  pure a+runClick = runClickWith MouseLeft +-- | 'runClick' with the right button ('rightClickPair'), as opens a context+-- or edit menu.+runRightClick :: Context -> Input -> NanoUI a -> V2 -> IO a+runRightClick = runClickWith MouseRight++-- | Count a failure unless some span contains the substring. assertSpansHas :: HasCallStack => IORef Int -> T.Text -> [(Rect, T.Text, a, b, c)] -> IO () assertSpansHas failed needle spans = assert failed (hasText needle spans) +matchingRects :: (T.Text -> Bool) -> [(Rect, T.Text, a, b, c)] -> [Rect]+matchingRects p spans = [r | (r, txt, _, _, _) <- spans, p txt]++-- | The rect of the first span whose text contains @needle@.+spanRect :: T.Text -> [(Rect, T.Text, a, b, c)] -> Maybe Rect+spanRect needle = listToMaybe . matchingRects (needle `T.isInfixOf`)++-- | The rect of the first span whose text is exactly @lbl@.+spanRectOf :: T.Text -> [(Rect, T.Text, a, b, c)] -> Maybe Rect+spanRectOf lbl = listToMaybe . matchingRects (== lbl)++-- | Whether the first rect contains the second.+covers :: Rect -> Rect -> Bool+covers (Rect cx cy cw ch) (Rect x y w h) =+  cx <= x && cy <= y && cx + cw >= x + w && cy + ch >= y + h++-- | Whether a frame's damage was a clip, and one that covers @rect@.+clipCovers :: Damage -> Rect -> Bool+clipCovers (DamageClip clip) rect = covers clip rect+clipCovers DamageFull _ = False++-- | Whether a frame's damage covers @rect@, the whole window included.+damageCovers :: Damage -> Rect -> Bool+damageCovers DamageFull _ = True+damageCovers dmg rect = clipCovers dmg rect++-- | Y origins of spans whose unmodified text exactly matches the label. spanYOf :: T.Text -> [(Rect, T.Text, a, b, c)] -> [Float]-spanYOf lbl spans = [y | (Rect _ y _ _, txt, _, _, _) <- spans, txt == lbl]+spanYOf lbl = map rectY . matchingRects (== lbl) +-- | X origins of spans whose unmodified text exactly matches the label. spanXOf :: T.Text -> [(Rect, T.Text, a, b, c)] -> [Float]-spanXOf lbl spans = [x | (Rect x _ _ _, txt, _, _, _) <- spans, txt == lbl]--assertScrollGutterPad ::-  HasCallStack-  => IORef Int-  -> Context-  -> WidgetId-  -> Response-  -> Float-  -> Float-  -> IO ()-assertScrollGutterPad failed ctx sid child gutter endPad = do-  mrect <- getPrevRect ctx sid-  case mrect of-    Nothing -> assert failed False-    Just (Rect sx _ sw _) -> do-      let-        Rect cx _ cw _ = respRect child-        contentRight = sx + sw - endPad - gutter-      assert failed (cx + cw >= contentRight - 0.5)-      assert failed (cx + cw <= contentRight + 0.01)+spanXOf lbl = map rectX . matchingRects (== lbl) -assertWheelTitlePinned ::-  HasCallStack-  => IORef Int-  -> Context-  -> Input-  -> NanoUI a-  -> T.Text-  -> T.Text-  -> V2-  -> Maybe Float-  -> IO ()-assertWheelTitlePinned failed ctx inp0 ui title line1 wheelAt mClipMax = do-  spans0 <- collectOverlayTextSpans ctx inp0-  let-    titleYs0 = spanYOf title spans0-    line1Ys0 = spanYOf line1 spans0-  assert failed (not (null titleYs0))-  case line1Ys0 of-    [] -> assert failed False-    b0 : _ -> do-      let-        wheel = inp0 {inputMousePos = wheelAt, inputScroll = V2 0 1}-      _ <- runFrame ctx wheel ui-      spans1 <- collectOverlayTextSpans ctx wheel-      let-        titleYs1 = spanYOf title spans1-        line1Ys1 = spanYOf line1 spans1-      case (titleYs0, titleYs1) of-        (y0 : _, y1 : _) -> assertEq failed y1 y0-        _ -> assert failed False-      case line1Ys1 of-        [] -> pure ()-        b1 : _ -> assertLt failed b1 b0-      case mClipMax of-        Nothing -> pure ()-        Just maxY ->-          assert failed (not (any (\(Rect _ y _ h, _, _, _, _) -> y < 0 || y + h > maxY) spans1))+-- | Run a frame with the pointer at @pos@ and return the resulting 'UiCursorKind'.+cursorOver :: Context -> Input -> NanoUI a -> V2 -> IO UiCursorKind+cursorOver ctx inp ui pos = do+  let hover = inp {inputMousePos = pos}+  _ <- runFrame ctx hover ui+  uiCursorKind ctx hover +-- | Probe candidate y positions at a fixed x, running a frame for each, and+-- return the first input that produces a grab cursor. findGrabHover ::   Context -> NanoUI a -> Input -> Float -> [Float] -> IO (Maybe Input) findGrabHover ctx ui inp0 thumbX = go  where   go [] = pure Nothing   go (y : ys) = do-    let-      hover = inp0 {inputMousePos = V2 thumbX y}-    _ <- runFrame ctx hover ui-    kind <- uiCursorKind ctx hover-    if kind == UiCursorGrab then pure (Just hover) else go ys+    kind <- cursorOver ctx inp0 ui (V2 thumbX y)+    if kind == UiCursorGrab then pure (Just inp0 {inputMousePos = V2 thumbX y}) else go ys +-- | Press and move a resize handle, then run two button-up frames. Returns+-- the window's recorded bounds, or 'Nothing' if its node is absent. dragWindowEdge ::   Context   -> Input@@ -377,87 +497,58 @@   -> V2   -> IO (Maybe Rect) dragWindowEdge ctx inp0 ui grab dest = do-  let-    press = pressAt inp0 grab-  _ <- runFrame ctx press ui-  let-    dragged =-      press-        { inputMousePos = dest-        , inputMousePressed = False-        }-  _ <- runFrame ctx dragged ui-  let-    idle = inp0 {inputMousePos = dest}-  _ <- runFrame ctx idle ui-  (win, _, _, _) <- runFrame ctx idle ui+  runDragFrom ctx inp0 ui grab dest+  win <- warmup2 ctx (inp0 {inputMousePos = dest}) ui   getPrevRect ctx (respId win) +-- | Read UV coordinates of a zero-based vertex. The index must be below+-- 'drawVertexCount' and the borrowed draw buffers must still be valid. vertUv :: DrawData -> Int -> IO (Float, Float)-vertUv dd i =-  withForeignPtr (drawVertices dd) $ \p -> do-    let-      off = i * vertexSize-    u <- peekByteOff p (off + 24) :: IO Float-    v <- peekByteOff p (off + 28) :: IO Float-    pure (u, v)--checkIdleFullDamage ::-  HasCallStack => IORef Int -> Context -> Input -> Input -> NanoUI a -> IO ()-checkIdleFullDamage failed ctx inpAfter inpIdle ui = do-  need <- needsRedraw ctx inpAfter inpIdle-  assert failed need-  _ <- runFrame ctx inpIdle ui-  dmg <- takeDamage ctx-  assert failed (dmg == DamageFull)+vertUv dd i = withForeignPtr (drawVertices dd) $ \vp -> (\v -> (vU v, vV v)) <$> vertexAt vp i --- AlignEnd pins last-glyph ink, so "10" / "1i" / "1." share one right edge.--- Lives here rather than with its test case because the pen and ink helpers--- are internal to the library.-checkLabelAlignEndInk :: IORef Int -> IO ()-checkLabelAlignEndInk failed = do-  let-    gq xoff gw =-      GlyphQuad-        { gqX = xoff-        , gqY = 0-        , gqW = gw-        , gqH = 10-        , gqU0 = 0-        , gqV0 = 0-        , gqU1 = 1-        , gqV1 = 1-        }-    fm =-      (monospaceMetrics 10)-        { fmAdvance = \c -> case c of-            'i' -> 4-            '.' -> 4-            _ -> 10-        , fmGlyph = \c -> case c of-            'i' -> Just (gq 0.5 3)-            '.' -> Just (gq 1 1)-            _ -> Just (gq 1 8)-        }-    boxW = 100-    visualRight txt =-      let (tx, _) = alignedTextPen AlignEnd 0 boxW 0 fm txt-       in tx + textInkEnd fm txt-    r0 = visualRight "10"-    ri = visualRight "1i"-    rd = visualRight "1."-  when (abs (r0 - boxW) > 0.01) $ bump failed-  when (abs (ri - boxW) > 0.01) $ bump failed-  when (abs (rd - boxW) > 0.01) $ bump failed+-- | Run press and held-move frames from one point to another. Leaves the button+-- held; the test supplies the release frame when needed.+runDragFrom :: Context -> Input -> NanoUI a -> V2 -> V2 -> IO ()+runDragFrom ctx inp0 ui grab dest =+  forM_ [pressAt inp0 grab, holdAt inp0 dest] $ \inp -> runFrame ctx inp ui -windowTitleGrab :: Rect -> V2-windowTitleGrab (Rect x0 y0 _ _) = V2 (x0 + 24) (y0 + padT windowPad + 19.5)+-- | Install a wake action on a headless context and return a wait for it.+-- @wait us@ consumes a wake since the last wait, blocking up to @us@+-- microseconds, and returns whether one arrived. Consuming a wake takes the+-- wakes so far ('takeWakes'), as a session loop does after its wait, so the+-- next one signals again. A frame that requests another also wakes the loop,+-- so drain those with @wait 0@ before starting the background job the test+-- waits on.+newWakeSignal :: Context -> IO (Int -> IO Bool)+newWakeSignal ctx = do+  signal <- newEmptyMVar+  setWakeLoop ctx (void (tryPutMVar signal ()))+  pure $ \us -> do+    woke <-+      if us <= 0+        then isJust <$> tryTakeMVar signal+        else isJust <$> timeout us (takeMVar signal)+    when woke (takeWakes ctx)+    pure woke -runDragFrom :: Context -> Input -> NanoUI a -> V2 -> V2 -> IO ()-runDragFrom ctx inp0 ui grab dest = do-  let-    press = pressAt inp0 grab-  _ <- runFrame ctx press ui-  let-    moved = press {inputMousePos = dest, inputMousePressed = False}-  void (runFrame ctx moved ui)+-- | Run @action@ @warmups@ times, then time it over @NANO_PROFILE_ITERATIONS@+-- runs (@runs@ when unset) and print its mean wall time and allocation per+-- run under @name@. The clock stops before the second GC, which only brings+-- the allocation counter current. Needs the RTS's statistics (@+RTS -T@).+measureRuns :: Int -> Int -> String -> IO () -> IO ()+measureRuns warmups runs0 name action = do+  requested <- lookupEnv "NANO_PROFILE_ITERATIONS"+  let runs = max 1 (fromMaybe runs0 (requested >>= readMaybe))+  replicateM_ warmups action+  performGC+  s0 <- getRTSStats+  t0 <- getMonotonicTimeNSec+  replicateM_ runs action+  t1 <- getMonotonicTimeNSec+  performGC+  s1 <- getRTSStats+  let perIter :: Double -> Double+      perIter total = total / fromIntegral runs+  printf "%-34s : %11.6f ms/frame  |  %11.3f KB alloc/frame\n" name+    (perIter (fromIntegral (t1 - t0) / 1e6))+    (perIter (fromIntegral (allocated_bytes s1 - allocated_bytes s0) / 1024))
lib/NanoUI/Testing/Runner.hs view
@@ -1,45 +1,74 @@ -- | Shared runner for the @exitcode-stdio@ integration suites: runs named -- specs against fresh contexts, selecting them by command-line name.+--+-- The program arguments choose what runs:+--+-- * no arguments runs every spec;+-- * an argument that is a spec's full name selects that spec;+-- * any other argument selects every spec whose name starts with it, and+--   one that starts no name stops the run with an error;+-- * @--list@ prints the names the other arguments select, one per line,+--   and runs nothing. module NanoUI.Testing.Runner   ( runTests+  , runChecks+  , check   ) where -import Control.Monad (forM_, when)+import Control.Exception (SomeAsyncException, SomeException, catch, displayException, fromException, throwIO)+import Control.Monad (forM, unless, when) import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.List (isPrefixOf, partition)+import Data.Maybe (isJust) import NanoUI.Testing (Context) import System.Environment (getArgs) import System.IO (hFlush, stdout)  -- | Run the given specs. Each entry is a test name, a context maker, and the--- test body (which receives the context and a shared failure counter). Names--- passed as program arguments select which tests run; with no arguments--- everything runs. A test counts as failed when it incremented the counter.+-- test body (which receives the context and a shared failure counter). The+-- program arguments select which tests run, as the module header describes.+-- A test counts as failed when it incremented the counter or threw. runTests :: [(String, IO Context, Context -> IORef Int -> IO ())] -> IO ()-runTests specs = do-  args <- getArgs-  let-    wantAll = null args-    want name = wantAll || name `elem` args-    names = [name | (name, _, _) <- specs]-    unknown = filter (`notElem` names) args-  when (not (null unknown)) $+runTests specs = runChecks [(name, \failed -> mkCtx >>= \ctx -> run ctx failed) | (name, mkCtx, run) <- specs]++-- | 'runTests' for specs that need no 'Context': each entry is a test name+-- and a body that receives the shared failure counter.+runChecks :: [(String, IORef Int -> IO ())] -> IO ()+runChecks specs = do+  (flags, args) <- partition (== "--list") <$> getArgs+  let names = map fst specs+      selects arg name = arg == name || (arg `notElem` names && arg `isPrefixOf` name)+      unknown = filter (\arg -> not (any (selects arg) names)) args+      chosen = [s | s@(name, _) <- specs, null args || any (`selects` name) args]+  unless (null unknown) $     fail ("Unknown test names: " ++ unwords unknown)-  failed <- newIORef (0 :: Int)-  failedTests <- newIORef (0 :: Int)-  forM_ specs $ \(name, mkCtx, run) ->-    when (want name) $ do-      putStrLn ("RUN: " ++ name)-      hFlush stdout-      before <- readIORef failed-      ctx <- mkCtx-      run ctx failed-      after <- readIORef failed-      when (after > before) $ do-        modifyIORef' failedTests (+ 1)-        putStrLn ("FAIL: " ++ name)-  n <- readIORef failedTests-  if n == 0-    then putStrLn "All tests passed."+  if not (null flags)+    then mapM_ (putStrLn . fst) chosen     else do-      putStrLn $ show n ++ " test(s) failed."-      fail "tests failed"+      failed <- newIORef (0 :: Int)+      results <-+        forM chosen $ \(name, run) -> do+          putStrLn ("RUN: " ++ name)+          hFlush stdout+          before <- readIORef failed+          -- A test that throws fails on its own, and the specs after it still run.+          run failed `catch` \(e :: SomeException) -> do+            when (isJust (fromException @SomeAsyncException e)) (throwIO e)+            putStrLn ("EXCEPTION: " ++ displayException e)+            modifyIORef' failed (+ 1)+          after <- readIORef failed+          when (after > before) $ putStrLn ("FAIL: " ++ name)+          pure (after > before)+      let n = length (filter id results)+      if n == 0+        then putStrLn "All tests passed."+        else do+          putStrLn $ show n ++ " test(s) failed."+          fail "tests failed"++-- | Print a named check as @[PASS] name@ or @[FAIL] name@. A failure+-- increments the counter and returns, so the checks after it still run.+check :: IORef Int -> String -> Bool -> IO ()+check failed name ok+  | ok = putStrLn ("[PASS] " ++ name)+  | otherwise = putStrLn ("[FAIL] " ++ name) >> modifyIORef' failed (+ 1)
+ lib/NanoUI/Testing/Sim.hs view
@@ -0,0 +1,485 @@+{-# LANGUAGE DerivingVia #-}++-- | A simulated user driving a view headlessly, in the style of iced's+-- simulator: find a widget by its text or rect, click it, type, press keys,+-- and check what the next frame shows.+--+-- > runSim ctx failed (withInput 300 200) counterView $ do+-- >   click "+"+-- >   click "+"+-- >   expect "2"+--+-- 'runSim' settles the view first (frames until it asks for no more), so+-- 'respRect's and spans are current. Each action then runs the frames a real+-- event would: 'click' is a press frame and a release frame, 'typeText' one+-- frame. The pointer stays where the last action left it, as a mouse does.+-- One-shot events (presses, keys, text, wheel) last a single frame; held+-- buttons, modifiers and the window size persist.+--+-- Checks ('check', 'checkEq', 'expect') count a failure on the shared+-- counter and carry on ('runSimWith' can make them stop the script instead).+-- Aiming at a 'Target' that is not on screen throws, which the test runner+-- reports as a failure of the whole test.+module NanoUI.Testing.Sim+  ( -- * Running+    Sim+  , runSim+  , runSimWith+  , SimOptions (..)+  , defaultSimOptions+  , simContext+  , onContext+  , simFailures+    -- * Frames+  , frame+  , frameWith+  , settle+  , result+  , wantsFrame+  , modifyInput+  , getInput+  , resize+  , advance+  , afterView+    -- * Pointer+  , Target (..)+  , at+  , targetPoint+  , prevRect+  , moveTo+  , press+  , pressButton+  , release+  , releaseButton+  , click+  , clickWith+  , rightClick+  , doubleClick+  , drag+  , wheel+  , cursorAt+  , pointerCursor+  , hotId+    -- * Keyboard+  , typeText+  , pressKey+  , chord+  , pressTab+  , focusedId+  , focusOn+  , focusRing+    -- * Reading the frame+  , spans+  , findSpan+  , rectOf+  , labelShown+  , textShown+  , expect+  , expectNot+  , frameDamage+  , wouldRedraw+  , wakeTime+  , scrollOffsetOf+  , scrollOffset2DOf+    -- * State+  , readV+  , writeV+    -- * Checks+  , check+  , checkEq+  , checkGt+  , checkLt+  , checkJust+  ) where++import Control.Exception (finally, throwIO)+import Control.Monad (replicateM_, unless, void, when)+import Control.Monad.IO.Class (MonadIO (..))+import Control.Monad.Trans.Reader (ReaderT (..))+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (isJust, listToMaybe)+import Data.String (IsString (..))+import Data.Text qualified as T+import GHC.Stack (HasCallStack, withFrozenCallStack)+import NanoUI hiding (liftIO)+import NanoUI.Backend+import NanoUI.Shortcut (Shortcut)+import NanoUI.Internal.Context (getFocusVisible, getScrollOffset, getScrollOffset2D)+import NanoUI.Testing (getHotId, getPrevRect, needsRedraw)+import NanoUI.Testing.Assert qualified as A+import NanoUI.Testing.Harness (chordInp, keyInp, pressWith, releaseWith, setFocus, spanLabel)++data Env a = Env+  { envCtx :: Context+  , envFailed :: IORef Int+  , envOptions :: SimOptions a+  , envView :: NanoUI a+  , envAfter :: IORef (Maybe (NanoUI ()))+  , envInput :: IORef Input+  , envResult :: IORef (a, Bool)+  }++-- | A scripted session against one view. @a@ is the view's result.+newtype Sim a r = Sim (Env a -> IO r)+  deriving (Functor, Applicative, Monad, MonadFail, MonadIO) via ReaderT (Env a) IO++-- | How 'runSimWith' runs frames and treats a failed check.+data SimOptions a = SimOptions+  { simFrameRunner :: Context -> Input -> NanoUI a -> IO (a, Bool)+  -- ^ Run one frame of the view on this input: the view's result, and+  -- whether the frame asks for another. A backend's own frame function+  -- drives a real window this way.+  , simFailFast :: Bool+  -- ^ Throw at the first failed check, after printing it, instead of+  -- counting it and carrying on.+  }++-- | Headless frames ('runFrame'), and failed checks counted.+defaultSimOptions :: SimOptions a+defaultSimOptions = SimOptions {simFrameRunner = headlessFrame, simFailFast = False}+  where+    headlessFrame ctx inp view = (\(a, _, again) -> (a, again)) <$> runFrame ctx inp view++-- | Settle the view on @input@ (its window size, usually from 'A.withInput'),+-- then run the script. Failures go to the shared counter.+runSim :: Context -> IORef Int -> Input -> NanoUI a -> Sim a r -> IO r+runSim = runSimWith defaultSimOptions++-- | 'runSim' with other frames or fail-fast checks.+runSimWith :: SimOptions a -> Context -> IORef Int -> Input -> NanoUI a -> Sim a r -> IO r+runSimWith opts ctx failed inp view (Sim script) = do+  first <- simFrameRunner opts ctx inp view+  after <- newIORef Nothing+  env <- Env ctx failed opts view after <$> newIORef (clearEphemeral inp) <*> newIORef first+  let Sim settled = settle+  _ <- settled env+  script env++-- | The context the script drives.+simContext :: Sim a Context+simContext = Sim (pure . envCtx)++-- | Run an action on the context, such as a read the script has no helper+-- for.+onContext :: (Context -> IO b) -> Sim a b+onContext f = Sim (f . envCtx)++-- | The shared failure counter, for the assertions of "NanoUI.Testing.Assert".+simFailures :: Sim a (IORef Int)+simFailures = Sim (pure . envFailed)++-- | Run one frame on the current input and return the view's result. The+-- frame's one-shot events are cleared afterwards.+frame :: Sim a a+frame = frameWith id++-- | Run one frame with @f@ applied to the current input for that frame only,+-- then keep its held state (buttons, keys, pointer) and drop its one-shot+-- events.+frameWith :: (Input -> Input) -> Sim a a+frameWith f = Sim $ \env -> do+  inp <- f <$> readIORef (envInput env)+  view <- maybe (envView env) (envView env <*) <$> readIORef (envAfter env)+  (a, again) <- simFrameRunner (envOptions env) (envCtx env) inp view+  writeIORef (envInput env) (clearEphemeral inp)+  writeIORef (envResult env) (a, again)+  pure a++-- | Run frames until the view stops asking for another (at least two, so+-- geometry from the first is used by the second; at most twenty, for a view+-- that animates). Check 'wantsFrame' afterwards to tell the two apart.+settle :: Sim a a+settle = go (0 :: Int)+  where+    go n = do+      a <- frame+      again <- wantsFrame+      if n < 1 || (again && n < 19) then go (n + 1) else pure a++-- | The result of the last frame.+result :: Sim a a+result = Sim (fmap fst . readIORef . envResult)++-- | Whether the last frame asked for another (a redraw, animation, or a+-- change it made that the view must see).+wantsFrame :: Sim a Bool+wantsFrame = Sim (fmap snd . readIORef . envResult)++-- | Change the input that every later frame starts from.+modifyInput :: (Input -> Input) -> Sim a ()+modifyInput f = Sim (\env -> modifyIORef' (envInput env) f)++-- | The input the next frame starts from.+getInput :: Sim a Input+getInput = Sim (readIORef . envInput)++-- | Resize the window and settle.+resize :: Float -> Float -> Sim a a+resize w h = modifyInput (\i -> i {inputWindowSize = Size w h}) >> settle++-- | One frame in which @dt@ seconds pass, as for animations and delays.+advance :: Float -> Sim a a+advance dt = frameWith (\i -> i {inputDeltaTime = dt})++-- | One frame whose view runs @act@ after the script's view, and what @act@+-- returned. Running last, it takes no widget id from the view, so it can+-- aim commands such as 'requestFocus', 'focusNext' or 'runTextCommand' at+-- widgets the view declared.+afterView :: NanoUI b -> Sim a b+afterView act = Sim $ \env -> do+  out <- newIORef Nothing+  writeIORef (envAfter env) (Just (act >>= liftIO . writeIORef out . Just))+  let Sim run = frame+  _ <- run env `finally` writeIORef (envAfter env) Nothing+  readIORef out >>= maybe (throwIO (userError "Sim: the view never reached afterView's action")) pure++-- | Where the pointer is aimed. A string literal is a 'Labelled' target, so+-- @click "Save"@ clicks the text "Save".+data Target+  = -- | This point.+    At V2+  | -- | The rect's centre.+    Within Rect+  | -- | The centre of the widget's rect from the last frame.+    On Response+  | -- | The centre of that widget's rect from the last frame.+    OnWidget WidgetId+  | -- | The centre of the visible text span labelled exactly this, ignoring+    -- surrounding space (popups and menus included; see 'findSpan').+    Labelled T.Text++instance IsString Target where+  fromString = Labelled . T.pack++-- | @'At' ('V2' x y)@.+at :: Float -> Float -> Target+at x y = At (V2 x y)++-- | The point a target aims at, throwing when it is not on screen.+targetPoint :: HasCallStack => Target -> Sim a V2+targetPoint = \case+  At p -> pure p+  Within (Rect x y w h) -> pure (V2 (x + w / 2) (y + h / 2))+  On resp -> targetPoint (Within (respRect resp))+  OnWidget wid -> prevRect wid >>= targetPoint . Within+  Labelled txt -> rectOf txt >>= targetPoint . Within++-- | The widget's rect from the last frame, throwing when it has none.+prevRect :: WidgetId -> Sim a Rect+prevRect wid = onContext (`getPrevRect` wid) >>= maybe (missing ("widget " <> show wid)) pure++missing :: String -> Sim a b+missing what = liftIO (throwIO (userError ("Sim: no " <> what <> " on screen")))++-- | Move the pointer to the target for a frame.+moveTo :: HasCallStack => Target -> Sim a a+moveTo t = do+  p <- targetPoint t+  frameWith (\i -> i {inputMousePos = p})++-- | Press the left button on the target and hold it.+press :: HasCallStack => Target -> Sim a a+press = pressButton MouseLeft++-- | Press @b@ on the target and hold it.+pressButton :: HasCallStack => MouseButton -> Target -> Sim a a+pressButton b t = do+  p <- targetPoint t+  frameWith (\i -> pressWith b i p)++-- | Release the left button where the pointer is.+release :: Sim a a+release = releaseButton MouseLeft++-- | Release @b@ where the pointer is.+releaseButton :: MouseButton -> Sim a a+releaseButton b = frameWith (releaseWith b)++-- | Press and release the left button on the target; the release frame's+-- result.+click :: HasCallStack => Target -> Sim a a+click = clickWith MouseLeft++-- | Press and release @b@ on the target.+clickWith :: HasCallStack => MouseButton -> Target -> Sim a a+clickWith b t = pressButton b t >> releaseButton b++-- | 'clickWith' 'MouseRight', as opens a context menu.+rightClick :: HasCallStack => Target -> Sim a a+rightClick = clickWith MouseRight++-- | Two quick clicks on the target; the second press reports a double click.+doubleClick :: HasCallStack => Target -> Sim a a+doubleClick t = do+  p <- targetPoint t+  void (click (At p))+  void (frameWith (\i -> (pressWith MouseLeft i p) {inputMouseClicks = 2}))+  release++-- | Press on @from@, move to @to@ in @steps@ held frames, and release there.+drag :: HasCallStack => Target -> Target -> Int -> Sim a a+drag from to steps = do+  V2 x0 y0 <- targetPoint from+  V2 x1 y1 <- targetPoint to+  void (press (At (V2 x0 y0)))+  let n = max 1 steps+      step k = let s = fromIntegral k / fromIntegral n in V2 (x0 + (x1 - x0) * s) (y0 + (y1 - y0) * s)+  mapM_ (\k -> frameWith (\i -> i {inputMousePos = step k})) [1 .. n]+  release++-- | Hover the target for a frame, then turn the wheel there by @d@+-- (positive @y@ scrolls down).+wheel :: HasCallStack => Target -> V2 -> Sim a a+wheel t d = moveTo t >> frameWith (\i -> i {inputScroll = d})++-- | The pointer cursor after a frame with the pointer on the target.+cursorAt :: HasCallStack => Target -> Sim a UiCursorKind+cursorAt t = moveTo t >> pointerCursor++-- | The pointer cursor the last frame's layout gives the current input.+pointerCursor :: Sim a UiCursorKind+pointerCursor = getInput >>= onContext . flip uiCursorKind++-- | The widget the pointer is over, which a press would go to ('WidgetId'+-- 0 for none). It lags a pointer move by a frame.+hotId :: Sim a WidgetId+hotId = onContext getHotId++-- | One frame that types @txt@ into whatever has focus.+typeText :: T.Text -> Sim a a+typeText txt = frameWith (\i -> i {inputChars = txt})++-- | One frame pressing @k@ (not an auto-repeat).+pressKey :: Key -> Sim a a+pressKey k = frameWith (keyInp k)++-- | One frame pressing a chord such as @cmdOrCtrl <> key \'z\'@, with exactly+-- its modifiers held for that frame. The key and modifiers are let go+-- afterwards, so the same chord again is a new press, not an auto-repeat.+chord :: Shortcut -> Sim a a+chord s = do+  before <- getInput+  a <- frameWith (chordInp s)+  modifyInput (\i -> i {inputModifiers = inputModifiers before, inputKeysHeld = inputKeysHeld before})+  pure a++-- | Press Tab @n@ times, a frame each, moving focus forward.+pressTab :: Int -> Sim a ()+pressTab n = replicateM_ n (void (pressKey KeyTab))++-- | The widget with keyboard focus.+focusedId :: Sim a WidgetId+focusedId = onContext getFocusId++-- | Give @wid@ keyboard focus directly, as focus kept from earlier frames+-- does; the next frame sees it.+focusOn :: WidgetId -> Sim a ()+focusOn wid = onContext (`setFocus` wid)++-- | Whether the focus ring shows, as it does after keyboard navigation and+-- not after a click.+focusRing :: Sim a Bool+focusRing = onContext getFocusVisible++-- | The text spans of the last frame: the base layer, then overlays.+spans :: Sim a [(Rect, T.Text, Color, Color, Rect)]+spans = Sim $ \env -> do+  inp <- readIORef (envInput env)+  (base, over) <- collectRasterSpans (envCtx env) inp+  pure (base <> over)++-- | The rect of the visible span labelled exactly @txt@ (ignoring+-- surrounding space and blank-glyph markers). When several match, the+-- topmost layer's last one, as the pointer would hit it.+findSpan :: T.Text -> Sim a (Maybe Rect)+findSpan txt = do+  ss <- spans+  pure (listToMaybe (reverse [r | (r@(Rect _ _ w h), t, _, _, _) <- ss, w > 1, h > 1, spanLabel t == txt]))++-- | 'findSpan', throwing when nothing matches.+rectOf :: T.Text -> Sim a Rect+rectOf txt = findSpan txt >>= maybe (missing ("text " <> show txt)) pure++-- | Whether the last frame shows a span labelled exactly @txt@, as+-- 'findSpan' matches.+labelShown :: T.Text -> Sim a Bool+labelShown txt = isJust <$> findSpan txt++-- | Whether some span of the last frame contains @txt@.+textShown :: T.Text -> Sim a Bool+textShown txt = any (\(_, t, _, _, _) -> T.isInfixOf txt t) <$> spans++-- | Check that some span of the last frame contains @txt@.+expect :: HasCallStack => T.Text -> Sim a ()+expect txt = withFrozenCallStack (checkShown ("expected text " <> show txt) =<< textShown txt)++-- | Check that no span of the last frame contains @txt@.+expectNot :: HasCallStack => T.Text -> Sim a ()+expectNot txt = withFrozenCallStack (checkShown ("unexpected text " <> show txt) . not =<< textShown txt)++checkShown :: HasCallStack => String -> Bool -> Sim a ()+checkShown what ok = unless ok $ do+  liftIO (putStrLn what)+  withFrozenCallStack (check False)++-- | The damage of the frames since the last call, which this takes, as a+-- backend does before it paints ('takeDamage').+frameDamage :: Sim a Damage+frameDamage = onContext takeDamage++-- | Whether a frame on the current input changed by @f@ would need drawing,+-- as a backend's loop asks before it runs one ('needsRedraw'). Runs no+-- frame.+wouldRedraw :: (Input -> Input) -> Sim a Bool+wouldRedraw f = getInput >>= \i -> onContext (\ctx -> needsRedraw ctx i (f i))++-- | When the view next wants waking, in monotonic seconds, or 0 for no+-- timed wake ('getWakeAt').+wakeTime :: Sim a Double+wakeTime = onContext getWakeAt++-- | The vertical scroll offset of the scroller @wid@.+scrollOffsetOf :: WidgetId -> Sim a Float+scrollOffsetOf wid = onContext (`getScrollOffset` wid)++-- | Both scroll offsets of the scroller @wid@.+scrollOffset2DOf :: WidgetId -> Sim a V2+scrollOffset2DOf wid = onContext (`getScrollOffset2D` wid)++-- | The value of a 'Var', as the next frame will see it.+readV :: Var v -> Sim a v+readV = liftIO . readVarIO++-- | Write a 'Var' from outside the view, as a worker thread would; the next+-- frame sees the value.+writeV :: Eq v => Var v -> v -> Sim a ()+writeV v = liftIO . writeVarIO v++-- | Count a failure unless the condition holds.+check :: HasCallStack => Bool -> Sim a ()+check ok = counted (\r -> withFrozenCallStack (A.assert r ok))++-- | Count a failure unless the values are equal, printing both.+checkEq :: (HasCallStack, Eq b, Show b) => b -> b -> Sim a ()+checkEq x y = counted (\r -> withFrozenCallStack (A.assertEq r x y))++-- | Count a failure unless the first value is greater.+checkGt :: (HasCallStack, Ord b, Show b) => b -> b -> Sim a ()+checkGt x y = counted (\r -> withFrozenCallStack (A.assertGt r x y))++-- | Count a failure unless the first value is less.+checkLt :: (HasCallStack, Ord b, Show b) => b -> b -> Sim a ()+checkLt x y = counted (\r -> withFrozenCallStack (A.assertLt r x y))++-- Run an assertion on the failure counter, and stop the script if it failed+-- and the session is fail-fast.+counted :: (IORef Int -> IO ()) -> Sim a ()+counted assertion = Sim $ \env -> do+  before <- readIORef (envFailed env)+  assertion (envFailed env)+  after <- readIORef (envFailed env)+  when (simFailFast (envOptions env) && after > before) (throwIO (userError "Sim: a check failed"))++-- | Continue with the value, or count a failure on 'Nothing'.+checkJust :: HasCallStack => Maybe b -> (b -> Sim a ()) -> Sim a ()+checkJust m k = maybe (withFrozenCallStack (check False)) k m
+ lib/NanoUI/Themes.hs view
@@ -0,0 +1,31 @@+-- | Extra built-in theme presets and Base16 palette construction.+--+-- "NanoUI" exports 'NanoUI.defaultTheme', 'NanoUI.defaultLightTheme', and+-- semantic styling modifiers. Import this module for the Tomorrow presets+-- and for generating themes from 16-color Base16 palettes.+module NanoUI.Themes+  ( -- * Presets+    tomorrowNightMinDarkTheme+  , tomorrowMinLightTheme+  , tomorrowMidnightMinDarkTheme++    -- * Base16 palettes+  , Base16 (..)+  , themeFromBase16+  , themeFromBase16Dark+  , themeFromBase16Light+  , base16TomorrowNight+  , base16TomorrowLight+  ) where++import NanoUI.Internal.Style+  ( Base16 (..)+  , base16TomorrowLight+  , base16TomorrowNight+  , themeFromBase16+  , themeFromBase16Dark+  , themeFromBase16Light+  , tomorrowMidnightMinDarkTheme+  , tomorrowMinLightTheme+  , tomorrowNightMinDarkTheme+  )
− lib/NanoUI/Types.hs
@@ -1,365 +0,0 @@-module NanoUI.Types-  ( V2 (..)-  , Rect (..)-  , Size (..)-  , Color (..)-  , colorRGBA-  , colorToWord32-  , colorR-  , colorG-  , colorB-  , colorA-  , colorFromWord32-  , rgbToHsv-  , hsvToRgb-  , clamp-  , clamp01-  , onGrid-  , roundHalfUp-  , lerpColor-  , colorLuminance-  , contrastRatio-  , ImageId (..)-  , rectContains-  , rectNonEmpty-  , rectHit-  , rectUnion-  , rectIntersect-  , rectFullyInside-  , rectOverlapArea-  , rectInflate-  , rectArea-  , Damage (..)-  , DamageBounds (..)-  , defaultDamageSlop-  , sliderDamageSlop-  , haloDamageSlop-  , resolveDamageRect-  , damageIsEmpty-  , v2Add-  , v2Sub-  , PopupAnchor (..)-  , PopupPlacement (..)-  ) where--import Data.Bits (shiftL, shiftR, (.&.), (.|.))-import Data.Word (Word8, Word32)--data V2 = V2-  { v2X :: {-# UNPACK #-} !Float-  , v2Y :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)--data Size = Size-  { sizeW :: {-# UNPACK #-} !Float-  , sizeH :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)--data Rect = Rect-  { rectX :: {-# UNPACK #-} !Float-  , rectY :: {-# UNPACK #-} !Float-  , rectW :: {-# UNPACK #-} !Float-  , rectH :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)--newtype ImageId = ImageId-  { unImageId :: Int-  }-  deriving (Eq, Ord, Show)--newtype Color = Color Word32-  deriving (Eq, Show, Num)--{-# INLINE colorRGBA #-}-colorRGBA :: Word8 -> Word8 -> Word8 -> Word8 -> Color-colorRGBA r g b a =-  Color $-    (word32Of r `shiftL` 24)-      .|. (word32Of g `shiftL` 16)-      .|. (word32Of b `shiftL` 8)-      .|. word32Of a--{-# INLINE colorToWord32 #-}-colorToWord32 :: Color -> Word32-colorToWord32 (Color w) = w--{-# INLINE colorR #-}-colorR :: Color -> Word8-colorR (Color w) = fromIntegral ((w `shiftR` 24) .&. 0xFF)--{-# INLINE colorG #-}-colorG :: Color -> Word8-colorG (Color w) = fromIntegral ((w `shiftR` 16) .&. 0xFF)--{-# INLINE colorB #-}-colorB :: Color -> Word8-colorB (Color w) = fromIntegral ((w `shiftR` 8) .&. 0xFF)--{-# INLINE colorA #-}-colorA :: Color -> Word8-colorA (Color w) = fromIntegral (w .&. 0xFF)--{-# INLINE colorFromWord32 #-}-colorFromWord32 :: Word32 -> Color-colorFromWord32 = Color--{-# INLINE clamp #-}-clamp :: Ord a => a -> a -> a -> a-clamp lo hi x = max lo (min hi x)--{-# INLINE clamp01 #-}-clamp01 :: Float -> Float-clamp01 x = clamp 0 1 x---- | Round a logical coordinate onto the device-pixel grid implied by draw--- scale @s@ (device px = logical * s). Every layer that positions pixels ----- the layout solve, text pens, scroll offsets, paint and glyph rasterization ----- must route its coordinates through this single function (backends through--- 'roundHalfUp'), so geometry can never dephase from text. An identity when--- @s <= 0@ (no scaling).-{-# INLINE onGrid #-}-onGrid :: Float -> Float -> Float-onGrid s v-  | s > 0 = fromIntegral (roundHalfUp (v * s)) / s-  | otherwise = v---- | Round to the nearest integer, ties up: the device-pixel rounding shared by--- 'onGrid' and the backends. Not ties-to-even (@round@): at a fractional scale--- (125%: a 20px row is 25 device px) a column of rows can all sit on half--- pixels, and ties-to-even would alternate them down and up, leaving uneven--- gaps. Compares the exact fractional part rather than @floor (r + 0.5)@,--- whose addition itself rounds: it lifts the float just below 0.5 to 1 and--- odd integers past 2^23 up by one.-{-# INLINE roundHalfUp #-}-roundHalfUp :: Float -> Int-roundHalfUp r =-  let f = floor r-   in if r - fromIntegral f >= 0.5 then f + 1 else f--rgbToHsv :: Color -> (Float, Float, Float)-rgbToHsv c =-  let r = fromIntegral (colorR c) / 255-      g = fromIntegral (colorG c) / 255-      b = fromIntegral (colorB c) / 255-      maxC = max r (max g b)-      minC = min r (min g b)-      delta = maxC - minC-      v = maxC-      s = if maxC <= 0 then 0 else delta / maxC-      rawH-        | delta <= 0 = 0-        | maxC == r =-            let t = (g - b) / delta-             in if t < 0 then 60 * (t + 6) else 60 * t-        | maxC == g = 60 * (((b - r) / delta) + 2)-        | otherwise = 60 * (((r - g) / delta) + 4)-      h = if rawH < 0 then rawH + 360 else rawH-   in (h, s, v)--hsvToRgb :: Float -> Float -> Float -> Color-hsvToRgb h s v =-  let hi = floor (h / 60) :: Int-      f = h / 60 - fromIntegral hi-      p = v * (1 - s)-      q = v * (1 - f * s)-      t = v * (1 - (1 - f) * s)-      (r, g, b) =-        case hi `mod` 6 of-          0 -> (v, t, p)-          1 -> (q, v, p)-          2 -> (p, v, t)-          3 -> (p, q, v)-          4 -> (t, p, v)-          _ -> (v, p, q)-      toCh x = round (clamp01 x * 255) :: Word8-   in colorRGBA (toCh r) (toCh g) (toCh b) 255---- | WCAG 2 relative-luminance contrast. 4.5 is AA for normal text.------ Alpha is ignored, so both colours must be opaque. Passing a translucent--- colour such as 'NanoUI.Style.themeOverlayDim' gives a meaningless ratio;--- composite it over its backdrop first.-contrastRatio :: Color -> Color -> Double-contrastRatio a b =-  let hi = max (colorLuminance a) (colorLuminance b)-      lo = min (colorLuminance a) (colorLuminance b)-   in (hi + 0.05) / (lo + 0.05)--colorLuminance :: Color -> Double-colorLuminance c =-  0.2126 * srgb (colorR c) + 0.7152 * srgb (colorG c) + 0.0722 * srgb (colorB c)--lerpColor :: Color -> Color -> Float -> Color-lerpColor (Color a) (Color b) t =-  let u = clamp01 t-      ch shift =-        round $-          fromIntegral ((a `shiftR` shift) .&. 0xFF) * (1 - u)-            + fromIntegral ((b `shiftR` shift) .&. 0xFF) * u-   in Color-        ( (ch 24 `shiftL` 24)-            .|. (ch 16 `shiftL` 16)-            .|. (ch 8 `shiftL` 8)-            .|. ch 0-        )--srgb :: Word8 -> Double-srgb ch =-  let x = fromIntegral ch / 255-   in if x <= 0.04045 then x / 12.92 else ((x + 0.055) / 1.055) ** 2.4--{-# INLINE word32Of #-}-word32Of :: Word8 -> Word32-word32Of = fromIntegral--{-# INLINE rectContains #-}-rectContains :: Rect -> V2 -> Bool-rectContains (Rect x y w h) (V2 px py) =-  px >= x && px < x + w && py >= y && py < y + h---- | A rect that has actually been laid out (nonzero extent).-{-# INLINE rectNonEmpty #-}-rectNonEmpty :: Rect -> Bool-rectNonEmpty r = rectW r > 0 && rectH r > 0---- | Hit test that ignores rects that have not been laid out yet.-{-# INLINE rectHit #-}-rectHit :: Rect -> V2 -> Bool-rectHit r p = rectNonEmpty r && rectContains r p--{-# INLINE rectUnion #-}-rectUnion :: Rect -> Rect -> Rect-rectUnion (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) =-  let x = min x1 x2-      y = min y1 y2-      xEnd = max (x1 + w1) (x2 + w2)-      yEnd = max (y1 + h1) (y2 + h2)-   in Rect x y (xEnd - x) (yEnd - y)--{-# INLINE rectIntersect #-}-rectIntersect :: Rect -> Rect -> Maybe Rect-rectIntersect (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) =-  let x = max x1 x2-      y = max y1 y2-      xEnd = min (x1 + w1) (x2 + w2)-      yEnd = min (y1 + h1) (y2 + h2)-      w = xEnd - x-      h = yEnd - y-   in if w > 0 && h > 0 then Just (Rect x y w h) else Nothing--{-# INLINE rectFullyInside #-}-rectFullyInside :: Rect -> Rect -> Bool-rectFullyInside (Rect ix iy iw ih) (Rect ox oy ow oh) =-  iw > 0-    && ih > 0-    && ix >= ox-    && iy >= oy-    && ix + iw <= ox + ow-    && iy + ih <= oy + oh--{-# INLINE rectOverlapArea #-}-rectOverlapArea :: Rect -> Rect -> Float-rectOverlapArea a b =-  maybe 0 (\r -> rectW r * rectH r) (rectIntersect a b)--{-# INLINE rectInflate #-}-rectInflate :: Float -> Rect -> Rect-rectInflate pad (Rect x y w h) =-  Rect (x - pad) (y - pad) (w + pad * 2) (h + pad * 2)--{-# INLINE rectArea #-}-rectArea :: Rect -> Float-rectArea (Rect _ _ w h) = w * h---- Full window vs a scissor box around widgets that actually changed (hover, anim).-data Damage-  = DamageFull-  | DamageClip Rect-  deriving (Eq, Show)--{-# INLINE damageIsEmpty #-}-damageIsEmpty :: Damage -> Bool-damageIsEmpty dmg =-  case dmg of-    DamageFull -> False-    DamageClip r -> rectW r <= 0 || rectH r <= 0---- | Invalidation bounding strategy for a widget and its interaction events.-data DamageBounds-  = DamageSelf                              -- ^ Exact layout bounding box Rect-  | DamageInflated {-# UNPACK #-} !Float    -- ^ Layout bounding box inflated by margin (focus rings, shadows, text slop)-  | DamageExact !Rect                       -- ^ Explicit rectangle in window space-  | DamageCustom (Rect -> Rect)             -- ^ Custom transformation on layout bounding box-  | DamageUnion !DamageBounds !DamageBounds -- ^ Combined invalidation bounds-  | DamageNone                              -- ^ No invalidation bounds--instance Show DamageBounds where-  show DamageSelf = "DamageSelf"-  show (DamageInflated f) = "DamageInflated " ++ show f-  show (DamageExact r) = "DamageExact " ++ show r-  show (DamageCustom _) = "DamageCustom <fn>"-  show (DamageUnion a b) = "DamageUnion (" ++ show a ++ ") (" ++ show b ++ ")"-  show DamageNone = "DamageNone"--instance Eq DamageBounds where-  DamageSelf == DamageSelf = True-  DamageInflated a == DamageInflated b = a == b-  DamageExact a == DamageExact b = a == b-  DamageUnion a1 b1 == DamageUnion a2 b2 = a1 == a2 && b1 == b2-  DamageNone == DamageNone = True-  _ == _ = False---- | Standard damage slop for text overhang, focus rings, and border anti-aliasing.-defaultDamageSlop :: Float-defaultDamageSlop = 4.0---- | Damage slop for slider handles that extend past track bounds.-sliderDamageSlop :: Float-sliderDamageSlop = 8.0---- | Damage slop for window resize halos and shadows.-haloDamageSlop :: Float-haloDamageSlop = 12.0---- | Resolve damage bounds against a given layout rect.-resolveDamageRect :: DamageBounds -> Rect -> Rect-resolveDamageRect bounds r =-  case bounds of-    DamageSelf -> r-    DamageInflated pad -> rectInflate pad r-    DamageExact exactR -> exactR-    DamageCustom f -> f r-    DamageUnion a b ->-      -- An empty side (DamageNone, or an unlaid-out rect) contributes-      -- nothing; a plain rect union would stretch the damage to the origin.-      let ra = resolveDamageRect a r-          rb = resolveDamageRect b r-       in if not (rectNonEmpty ra)-            then rb-            else if not (rectNonEmpty rb) then ra else rectUnion ra rb-    DamageNone -> Rect 0 0 0 0--{-# INLINE v2Add #-}-v2Add :: V2 -> V2 -> V2-v2Add (V2 x1 y1) (V2 x2 y2) = V2 (x1 + x2) (y1 + y2)--{-# INLINE v2Sub #-}-v2Sub :: V2 -> V2 -> V2-v2Sub (V2 x1 y1) (V2 x2 y2) = V2 (x1 - x2) (y1 - y2)--data PopupAnchor-  = AnchorPoint !V2-  | AnchorRect !Rect-  deriving (Eq, Show)--data PopupPlacement-  = PlacementBelow-  | PlacementAbove-  | PlacementRight-  | PlacementLeft-  | PlacementAtCursor-  | PlacementAuto-  deriving (Eq, Show)
+ lib/NanoUI/Var.hs view
@@ -0,0 +1,77 @@+-- | Mutable state that persists across frames.+--+-- A 'Var' is a mutable reference passed to stateful widgets: @textInput draft@+-- displays @draft@ and mutates it in place on user input. Read a 'Var' with+-- 'readVar' and update it with 'writeVar' or 'modifyVar'.+--+-- > counter :: NanoUI ()+-- > counter = row $ do+-- >   n <- useVar (0 :: Int)+-- >   whenM (button "-") (modifyVar n (subtract 1))+-- >   label . T.pack . show =<< readVar n+-- >   whenM (button "+") (modifyVar n (+ 1))+--+-- = Creating Vars+--+-- * 'useVar' allocates view-local mutable state keyed by its position among+--   the positional 'Var's of its scope (apart from widget ids), for 'Int',+--   'Double', 'Float', 'Bool', 'Data.Text.Text' and 'NanoUI.SortCol', and enumerations+--   via 'useEnumVar'.+-- * 'newVar' allocates a 'Var' of any type in 'IO' for application-owned+--   state.+-- * 'VarMap' stores one 'Var' per key for dynamic collections.+-- * @'constVar' x@ is a read-only 'Var' that always reads as @x@ and discards+--   writes, useful for inputs driven by derived state whose changes are handled+--   via the primed widget's 'NanoUI.Response'.+--+-- With @OverloadedRecordDot@, @v.field@ focuses a 'Var' on a single field of a+-- single-constructor 'GHC.Generics.Generic' record. 'forEachVar' projects a 'Var' of a list+-- into a 'Var' per element.+--+-- = Rerun semantics+--+-- A view normally runs once per frame. Mutating a 'Var' that was already read+-- earlier in the same pass invalidates the earlier read and triggers a second+-- pass before rendering. Reading a 'Var' after the widget that mutates it+-- avoids the extra pass. Record fields are tracked independently, so reading+-- @m.title@ before a widget mutates @m.name@ also runs in a single pass.+module NanoUI.Var+  ( -- * Vars+    Var+  , constVar+  , newVar+  , useVar+  , useEnumVar+  , VarSlot++    -- * Reading and writing+  , readVar+  , peekVar+  , writeVar+  , modifyVar+  , readVarIO+  , writeVarIO+  , modifyVarIO++    -- * Parts of a value+  , zoomVar+  , zoomVarL++    -- * Lists+  , forEachVar+  , withElemVars+  , VarMap+  , newVarMap+  , varAt+  , dropVar+  , retainVars++    -- * Plain values+  , withValue+  )+where++import NanoUI.Internal.Var+import NanoUI.Internal.Var.List+import NanoUI.Internal.Var.Map+import NanoUI.Internal.Var.Types
− lib/NanoUI/WidgetText.hs
@@ -1,422 +0,0 @@-module NanoUI.WidgetText-  ( intValueText-  , treeEncodeStyle-  , treeDecodeStyle-  , treeDecodeStripe-  , textInputFieldText-  , textInputMinWidth-  , textInputFieldPadY-  , textInputFieldHeight-  , textInputFlagSearch-  , textInputSearchMode-  , textInputFlagSelectable-  , textInputSelectableMode-  , textInputFlagPassword-  , textInputPasswordMode-  , textInputFlagNumeric-  , textInputNumericMode-  , numericStepperW-  , numericTextClip-  , numericStepperRects-  , comboTextClip-  , searchFieldReserveW-  , searchFieldTextClip-  , searchFieldIconRects-  , selectDisplayText-  , selectChevronReserve-  , selectChevronCenterX-  , colorPickerGap-  , colorPickerSvH-  , colorPickerCurrentLabel-  , colorPickerNewLabel-  , colorToHex-  , colorToHexA-  , colorFromHex-  , colorPickerParseHex-  , buttonFlagClose-  , buttonCloseTrailing-  , buttonFlagTab-  , buttonFlagTable-  , buttonFlagMenu-  , buttonFlagMenuBar-  , buttonFlagMask-  , tableStripeEven-  , tableStripeOdd-  , tableSortReserve-  , tableStripeColor-  , stripeColor-  , packTextNodeStyleFull-  , textNodeFontVariant-  , textNodeFontWeight-  , textNodeFontStyle-  , textNodeTextDecoration-  , textNodeStripe-  , tableHeaderLabel-  , tableHeaderDisplayText-  , tableSortMarkOf-  , tableSortBlank-  , isCloseButtonStyle-  , isTabButtonStyle-  , isTableHeaderStyle-  , isMenuItemStyle-  , isMenuBarStyle-  , buttonVisualStyle-  , buttonFlagsFromStyle-  ) where--import Data.Bits ((.&.), (.|.), complement, shiftL, shiftR)-import Data.Char (digitToInt, isHexDigit)-import Data.Maybe (fromMaybe)-import Data.Primitive.SmallArray (SmallArray, indexSmallArray, smallArrayFromList)-import Data.Text (Text)-import qualified Data.Text.Lazy as TL-import qualified Data.Text.Lazy.Builder as TB-import qualified Data.Text.Lazy.Builder.Int as TB-import Data.Word (Word8)-import Numeric (showHex)-import NanoUI.Font (FontMetrics (..), fmLineHeight, widgetContentInset)-import NanoUI.Style (FontStyle (..), FontVariant (..), FontWeight (..), TextDecoration (..), Theme (..), styleBg, themeButton, themePanel, themeWindow)-import NanoUI.Types (Color (..), Rect (..), colorA, colorB, colorG, colorR, colorRGBA, lerpColor)-import qualified Data.Text as T--intValueText :: Int -> Text-intValueText = TL.toStrict . TB.toLazyText . TB.decimal---- | styleIdx: nodeIdx in bits 11+, depth in 0-7, hasKids bit 8, expanded bit 9, stripeOdd bit 10.-treeEncodeStyle :: Int -> Int -> Bool -> Bool -> Bool -> Int-treeEncodeStyle nodeIdx depth hasKids expanded isOdd =-  (nodeIdx `shiftL` 11)-    .|. (if isOdd then 0x400 else 0)-    .|. (if expanded then 0x200 else 0)-    .|. (if hasKids then 0x100 else 0)-    .|. (depth .&. 0xff)--treeDecodeStyle :: Int -> (Int, Int, Bool, Bool)-treeDecodeStyle s =-  ( s `shiftR` 11-  , s .&. 0xff-  , s .&. 0x100 /= 0-  , s .&. 0x200 /= 0-  )--treeDecodeStripe :: Int -> Int-treeDecodeStripe s = if s .&. 0x400 /= 0 then tableStripeOdd else tableStripeEven--textInputMinWidth :: Float-textInputMinWidth = 160--textInputFieldPadY :: FontMetrics -> Float-textInputFieldPadY fm = max 3 (fmAdvance fm ' ' * 1.25)--textInputFieldHeight :: FontMetrics -> Float-textInputFieldHeight fm = fmLineHeight fm + 2 * textInputFieldPadY fm---- | Search-field icon geometry. Returns--- (icon diameter, outer pad, left chrome lead, right chrome tail). The lead/tail--- are the horizontal space the magnifier / clear buttons reserve either side of--- the editable text.-searchFieldChrome :: FontMetrics -> (Float, Float, Float, Float)-searchFieldChrome fm =-  let (ix, _) = widgetContentInset fm-      s = max 12 (min 15 (fmLineHeight fm * 0.8))-      pad = fmAdvance fm ' ' * 0.6-   in (s, ix, ix + s + pad, pad + s + ix)---- | Total horizontal chrome a caption-less search box reserves for its icons.-searchFieldReserveW :: FontMetrics -> Float-searchFieldReserveW fm =-  let (_, _, lead, tailw) = searchFieldChrome fm-   in lead + tailw---- | Region a caption-less search field's editable text may occupy. Excludes the--- magnifier on the left and the clear slot on the right.-searchFieldTextClip :: FontMetrics -> Float -> Float -> Float -> Float -> Rect-searchFieldTextClip fm x y w h =-  let (_, _, lead, tailw) = searchFieldChrome fm-      (_, iy) = widgetContentInset fm-   in Rect (x + lead) (y + iy) (max 0 (w - lead - tailw)) (max 0 (h - 2 * iy))---- | Square slots (magnifier left, clear right) the search icons are drawn in.-searchFieldIconRects :: FontMetrics -> Float -> Float -> Float -> Float -> (Rect, Rect)-searchFieldIconRects fm x y w h =-  let (s, ix, _, _) = searchFieldChrome fm-      cy = y + h / 2-      mag = Rect (x + ix) (cy - s / 2) s s-      clear = Rect (x + w - ix - s) (cy - s / 2) s s-   in (mag, clear)--textInputFieldText :: Text -> Text -> Bool -> Text-textInputFieldText ph value focused =-  let body = value-   in if T.null body && not focused-        then ph-        else body---- | Marks a @NodeTextInput@ as a caption-less search field. Lives in the high--- style bits (like the button flags) so it survives the arena's int storage.-textInputFlagSearch :: Int-textInputFlagSearch = 0x04000000--{-# INLINE textInputSearchMode #-}-textInputSearchMode :: Int -> Bool-textInputSearchMode si = si .&. textInputFlagSearch /= 0---- | Marks a @NodeTextInput@ as a selectable text label: read-only, caption-less,--- chrome-less, sized to its text content, with mouse drag-to-select and copy.-textInputFlagSelectable :: Int-textInputFlagSelectable = 0x10000000--{-# INLINE textInputSelectableMode #-}-textInputSelectableMode :: Int -> Bool-textInputSelectableMode si = si .&. textInputFlagSelectable /= 0---- | Marks a @NodeTextInput@ as a password field: its value is displayed masked--- and is never copied or cut to the clipboard.-textInputFlagPassword :: Int-textInputFlagPassword = 0x20000000--{-# INLINE textInputPasswordMode #-}-textInputPasswordMode :: Int -> Bool-textInputPasswordMode si = si .&. textInputFlagPassword /= 0---- | Marks a @NodeTextInput@ as a numeric field: a caption-less box whose text--- stops short of an up / down stepper at its right edge.-textInputFlagNumeric :: Int-textInputFlagNumeric = 0x40000000--{-# INLINE textInputNumericMode #-}-textInputNumericMode :: Int -> Bool-textInputNumericMode si = si .&. textInputFlagNumeric /= 0---- | Width of a numeric field's stepper column.-numericStepperW :: Float-numericStepperW = 18---- | Region a numeric field's text may occupy: inside the content inset, left--- of the stepper.-numericTextClip :: FontMetrics -> Float -> Float -> Float -> Float -> Rect-numericTextClip fm x y w h =-  let (ix, iy) = widgetContentInset fm-   in Rect (x + ix) (y + iy) (max 0 (w - 2 * ix - numericStepperW)) (max 0 (h - 2 * iy))---- | The up and down halves of a numeric field's stepper.-numericStepperRects :: Float -> Float -> Float -> Float -> (Rect, Rect)-numericStepperRects x y w h =-  let sx = x + w - numericStepperW-      half = h / 2-   in (Rect sx y numericStepperW half, Rect sx (y + half) numericStepperW (h - half))---- | Region a combo box's editable text may occupy: from the left content inset--- to the select chevron reserve on the right.-comboTextClip :: FontMetrics -> Float -> Float -> Float -> Float -> Rect-comboTextClip fm x y w h =-  let (ix, iy) = widgetContentInset fm-   in Rect (x + ix) (y + iy) (max 0 (w - ix - selectChevronReserve)) (max 0 (h - 2 * iy))--selectDisplayText :: Text -> Text -> Text-selectDisplayText lbl opt-  | T.null lbl = opt-  | otherwise = lbl <> ": " <> opt---- Space reserved on the right of a select for the chevron.-selectChevronReserve :: Float-selectChevronReserve = 16--selectChevronCenterX :: Float -> Float -> Float-selectChevronCenterX x w = x + w - selectChevronReserve / 2--colorPickerGap :: Float-colorPickerGap = 4---- Height of a colour picker's field row; the field grows to a square this tall.-colorPickerSvH :: Float-colorPickerSvH = 250--colorPickerCurrentLabel :: Text-colorPickerCurrentLabel = "Current"--colorPickerNewLabel :: Text-colorPickerNewLabel = "New"--colorToHex :: Color -> Text-colorToHex c =-  "#" <> hexByte (colorR c) <> hexByte (colorG c) <> hexByte (colorB c)---- | Eight-digit form for the alpha-aware picker: @#RRGGBBAA@.-colorToHexA :: Color -> Text-colorToHexA c = colorToHex c <> hexByte (colorA c)--hexByte :: Word8 -> Text-hexByte n = indexSmallArray hexBytes (fromIntegral n)---- Each byte's two-character representation is allocated once, shared by--- color-picker labels instead of formatting fresh Strings every frame.-hexBytes :: SmallArray Text-hexBytes =-  smallArrayFromList-    [T.justifyRight 2 '0' (T.pack (showHex n "")) | n <- [0 .. 255 :: Int]]---- | Parse a hex colour, accepting an optional leading @#@ and either 6 or 8--- digits. The fourth component is 'Nothing' for the six-digit form.-colorPickerParseHex :: Text -> Maybe (Word8, Word8, Word8, Maybe Word8)-colorPickerParseHex txt =-  let bare = T.dropWhile (== '#') (T.strip txt)-      pair i = parseHexPair (T.take 2 (T.drop i bare))-      n = T.length bare-   in if n /= 6 && n /= 8-        then Nothing-        else do-          r <- pair 0-          g <- pair 2-          b <- pair 4-          a <- if n == 8 then Just <$> pair 6 else pure Nothing-          pure (r, g, b, a)--colorFromHex :: Text -> Maybe Color-colorFromHex txt = do-  (r, g, b, ma) <- colorPickerParseHex txt-  pure (colorRGBA r g b (fromMaybe 255 ma))--parseHexPair :: Text -> Maybe Word8-parseHexPair t = case T.unpack t of-  [hi, lo]-    | isHexDigit hi && isHexDigit lo -> Just (fromIntegral (digitToInt hi * 16 + digitToInt lo))-  _ -> Nothing--tableStripeEven :: Int-tableStripeEven = 1--tableStripeOdd :: Int-tableStripeOdd = 2--{-# INLINE packTextNodeStyleFull #-}-packTextNodeStyleFull :: FontVariant -> FontWeight -> FontStyle -> TextDecoration -> Int -> Int-packTextNodeStyleFull fvar weight fstyle deco stripe =-  (stripe `shiftL` 4)-    .|. (fromEnum fvar .&. 0x0F)-    .|. ((fromEnum weight .&. 0x0F) `shiftL` 8)-    .|. ((fromEnum fstyle .&. 0x03) `shiftL` 12)-    .|. ((fromEnum deco .&. 0x03) `shiftL` 14)---- | The enum packed in the style bits at @shift@ under @mask@, or @fallback@--- when they hold no constructor.-{-# INLINE decodeStyleEnum #-}-decodeStyleEnum :: forall a. (Bounded a, Enum a) => Int -> Int -> a -> Int -> a-decodeStyleEnum shift mask fallback si =-  let v = (si `shiftR` shift) .&. mask-   in if v >= fromEnum (minBound :: a) && v <= fromEnum (maxBound :: a) then toEnum v else fallback--{-# INLINE textNodeFontVariant #-}-textNodeFontVariant :: Int -> FontVariant-textNodeFontVariant = decodeStyleEnum 0 0x0F FontRegular--{-# INLINE textNodeFontWeight #-}-textNodeFontWeight :: Int -> FontWeight-textNodeFontWeight = decodeStyleEnum 8 0x0F WeightNormal--{-# INLINE textNodeFontStyle #-}-textNodeFontStyle :: Int -> FontStyle-textNodeFontStyle = decodeStyleEnum 12 0x03 FontStyleNormal--{-# INLINE textNodeTextDecoration #-}-textNodeTextDecoration :: Int -> TextDecoration-textNodeTextDecoration = decodeStyleEnum 14 0x03 DecorationNone--{-# INLINE textNodeStripe #-}-textNodeStripe :: Int -> Int-textNodeStripe si = (si `shiftR` 4) .&. 0x0F--{-# INLINE stripeColor #-}-stripeColor :: Theme -> Int -> Maybe Color-stripeColor theme s-  | s == tableStripeEven = Just (lerpColor (styleBg (themePanel theme)) (themeWindow theme) 0.26)-  | s == tableStripeOdd = Just (lerpColor (styleBg (themePanel theme)) (styleBg (themeButton theme)) 0.55)-  | otherwise = Nothing--tableStripeColor :: Theme -> Int -> Maybe Color-tableStripeColor theme si = stripeColor theme (textNodeStripe si)---- | Trailing slot reserved in every header so the sort mark never changes column width.-tableSortReserve :: Text-tableSortReserve = "  ▲"--tableHeaderLabel :: Text -> Text-tableHeaderLabel hdr = hdr <> tableSortReserve---- | Sort direction encoded for a table-header style. Lives in bits 16-17: the--- low nibbles are the font fields, and a mark value of 1 or 2 in bit 0-1 used--- to flip the header's font variant (heading / muted), which blanked the--- arrow glyph.-tableSortMarkOf :: Int -> Int-tableSortMarkOf styleIdx = (styleIdx `shiftR` 16) .&. 0x03---- | Blank reserve slot (spaces only). The sort mark is drawn as a triangle--- over this slot, so the ▲/▼ codepoint never enters measured or laid-out text--- (the pruned UI font does not carry it).-tableSortBlank :: Text-tableSortBlank = T.map (const ' ') tableSortReserve--tableHeaderDisplayText :: Text -> Text-tableHeaderDisplayText txt =-  fromMaybe txt (T.stripSuffix tableSortReserve txt) <> tableSortBlank---- Type flags live in bits 28-31 so visual style and tab index stay in the low bits.-buttonFlagClose :: Int-buttonFlagClose = 0x20000000---- | Visual style of a title-bar close button: its cross sits against the--- box's right edge, so it lines up with the panel padding the way the title--- does on the left.-buttonCloseTrailing :: Int-buttonCloseTrailing = 1--buttonFlagTab :: Int-buttonFlagTab = 0x40000000--buttonFlagTable :: Int-buttonFlagTable = 0x80000000---- Flat menu row / menu-bar entry: transparent at rest, hover highlight, and an--- accent marker on hover. Rendered by 'menuItemVisualStyle'.-buttonFlagMenu :: Int-buttonFlagMenu = 0x10000000---- Flat menu-bar title: same flat/hover/open fill as a menu row, but centered--- text and no hover accent marker (that marker belongs to drop-down rows).-buttonFlagMenuBar :: Int-buttonFlagMenuBar = 0x08000000--buttonFlagMask :: Int-buttonFlagMask = buttonFlagClose .|. buttonFlagTab .|. buttonFlagTable .|. buttonFlagMenu .|. buttonFlagMenuBar--{-# INLINE buttonVisualStyle #-}-buttonVisualStyle :: Int -> Int-buttonVisualStyle si = si .&. complement buttonFlagMask--{-# INLINE buttonFlagsFromStyle #-}-buttonFlagsFromStyle :: Int -> (Bool, Bool, Bool)-buttonFlagsFromStyle si =-  ( si .&. buttonFlagClose /= 0-  , si .&. buttonFlagTab /= 0-  , si .&. buttonFlagTable /= 0-  )--{-# INLINE isCloseButtonStyle #-}-isCloseButtonStyle :: Int -> Bool-isCloseButtonStyle si = si .&. buttonFlagClose /= 0--{-# INLINE isTabButtonStyle #-}-isTabButtonStyle :: Int -> Bool-isTabButtonStyle si = si .&. buttonFlagTab /= 0--{-# INLINE isTableHeaderStyle #-}-isTableHeaderStyle :: Int -> Bool-isTableHeaderStyle si = si .&. buttonFlagTable /= 0--{-# INLINE isMenuItemStyle #-}-isMenuItemStyle :: Int -> Bool-isMenuItemStyle si = si .&. buttonFlagMenu /= 0--{-# INLINE isMenuBarStyle #-}-isMenuBarStyle :: Int -> Bool-isMenuBarStyle si = si .&. buttonFlagMenuBar /= 0
− lib/NanoUI/Widgets/Animate.hs
@@ -1,107 +0,0 @@-module NanoUI.Widgets.Animate-  ( Transition (..)-  , animate-  , animateTo-  , animateToA-  , pulse-  , keepAnimating-  )-where--import Control.Monad (when)-import Data.Maybe (isNothing)-import Effectful (Eff, type (:>))-import NanoUI.Animatable (Animatable (..))-import NanoUI.Animation (SpringParams)-import NanoUI.Context-  ( Ease (..)-  , approxEq-  , easeSameSpec-  , getAnimationValue-  , lookupAnimation-  , setAnimationValue-  , startAnimation-  , startAnimationEaseDelay-  , startSpring-  )-import NanoUI.Monad (Ui, askContext, nextId, scope, uiIO, uiTime, withKey)-import NanoUI.Widgets.Node (HasResponse, respId)---- | How an animated value moves.-data Transition-  = -- | Eased tween: duration and start delay, in seconds.-    Tween !Ease !Float !Float-  | -- | Damped spring; retargets from its current position and velocity.-    Spring !SpringParams---- | Animate from @from@ to @to@. It starts over from @from@ once it has--- finished (a tween completes, a spring settles) or its tween changes, so--- calling it every frame cycles.-animate :: Ui :> es => Transition -> Float -> Float -> Eff es Float-animate transition from to = do-  wid <- nextId-  ctx <- askContext-  uiIO $ do-    case transition of-      Tween ease dur delay -> startAnimationEaseDelay ctx wid from to dur ease delay-      Spring params -> do-        running <- lookupAnimation ctx wid-        when (isNothing running) (setAnimationValue ctx wid from)-        startSpring ctx wid params to-    getAnimationValue ctx wid---- | Animate from the current value toward @target@. An unchanged target keeps--- the running animation; a new one retargets from wherever the value is.-animateTo :: Ui :> es => Transition -> Float -> Eff es Float-animateTo transition target = do-  wid <- nextId-  ctx <- askContext-  uiIO $ do-    case transition of-      Tween ease dur delay -> do-        cur <- getAnimationValue ctx wid-        manim <- lookupAnimation ctx wid-        case manim of-          Just a | easeSameSpec a ease dur delay target -> pure ()-          Nothing | approxEq cur target -> pure ()-          _ -> startAnimationEaseDelay ctx wid cur target dur ease delay-      Spring params -> startSpring ctx wid params target-    getAnimationValue ctx wid---- | 'animateTo' for every component of a composite value.-animateToA :: (Animatable a, Ui :> es) => Transition -> a -> Eff es a-animateToA transition = animateComponents (animateTo transition)---- Component keys are local to one composite value, not its parent widget.-animateComponents ::-  (Animatable a, Ui :> es) => (Float -> Eff es Float) -> a -> Eff es a-animateComponents animateComponent target = scope $ do-  components <--    mapM-      (\(index, value) -> withKey (index :: Int) (animateComponent value))-      (zip [0 ..] (toComponents target))-  pure (fromComponents components)---- | A smoothly oscillating value in @[0,1]@ driven by the real-time clock, with--- the given period in seconds (e.g. @pulse 6@ sweeps once every six seconds).--- The time is captured in 'Double' (see 'NanoUI.Monad.uiTime'), so the sweep--- stays sub-frame smooth even on long-running processes. The value is--- re-evaluated each frame, like 'animate'.-pulse :: Ui :> es => Float -> Eff es Float-pulse periodSec = do-  t <- uiTime-  let-    period = max 0.001 (realToFrac periodSec :: Double)-  pure (realToFrac (0.5 + 0.5 * sin (2 * pi * t / period)) :: Float)---- | Keep a widget animating indefinitely so the frame loop never idles. Widgets--- driven by the wall clock ('pulse', or drawing from 'NanoUI.Monad.uiTime')--- rather than by a frame-counted animation would otherwise stop repainting--- once other animations settle.------ > bar <- progressBar' =<< pulse 6--- > keepAnimating bar-keepAnimating :: (HasResponse r, Ui :> es) => r -> Eff es ()-keepAnimating resp = do-  ctx <- askContext-  uiIO (startAnimation ctx (respId resp) 0 1 1e9)
− lib/NanoUI/Widgets/Behavior.hs
@@ -1,247 +0,0 @@--- | Interaction hooks shared by widgets: 1D drags, drag reordering, arrow-key--- navigation, click-outside and Escape dismissal, and the keyboard focus--- check. Their state lives in the widget store.-module NanoUI.Widgets.Behavior-  ( DragAxis (..)-  , keyedDragHeld-  , useDrag1D-  , useReorder-  , useKeyNav-  , keyboardFocused-  , keyActivated-  , KeyNav (..)-  , useDismissable-  , dragThresholdPx-  )-where--import Control.Monad (when)-import Data.Hashable (Hashable, hash)-import Data.IORef (readIORef)-import Data.List (find)-import Effectful (Eff, type (:>))-import qualified Data.IntMap.Strict as IM-import NanoUI.Context-  ( Context (..)-  , getFocusId-  , getStore-  , intKey-  , isDisabled-  , markEscapeConsumed-  , getMenuPointerGesture-  , pointerBlockedByModal-  , Slot (..)-  , slotKey-  , modifyStore-  )-import NanoUI.Id (WidgetId (..), enterKeyed, hashWidgetId, idContextWidgetId)-import NanoUI.Input-  ( Input (..)-  , Key (..)-  , inputChars-  , inputKeys-  , inputKeysElem-  , inputKeysNull-  , inputMouseDown-  , inputMousePos-  , inputMousePressed-  , inputMouseReleased-  , inputMouseRightPressed-  )-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO)-import NanoUI.Store (WidgetStore (..))-import NanoUI.Types (Rect (..), clamp01, rectHit, v2X, v2Y)-import qualified Data.Text as T---- | Pointer slop in pixels before a held press counts as a drag.-dragThresholdPx :: Float-dragThresholdPx = 8--data DragAxis = DragAxisX | DragAxisY-  deriving (Eq, Show)---- | True when a prior keyed useDrag1D on this path is still held.--- Peeks the keyed first-id without enterKeyed bumping parent siblingId.-keyedDragHeld :: (Hashable k, Ui :> es) => k -> Eff es Bool-keyedDragHeld k = do-  ctx <- askContext-  uiIO $ do-    old <- readIORef (ctxIdContext ctx)-    let wid = idContextWidgetId (snd (enterKeyed (fromIntegral (hash k)) old))-        dragK = slotKey SlotDrag (intKey wid)-    store <- getStore ctx-    pure (IM.findWithDefault 0 dragK (storeInt store) /= 0)---- | Clamped 1D drag. Maps pointer position on 'track' into [lo, hi].-useDrag1D ::-  (Ui :> es) =>-  DragAxis ->-  Float ->-  Float ->-  Float ->-  Rect ->-  Eff es (Float, Bool)-useDrag1D axis lo hi current track = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  let key = intKey wid-      dragK = slotKey SlotDrag key-      trackLen = case axis of-        DragAxisX -> rectW track-        DragAxisY -> rectH track-      origin = case axis of-        DragAxisX -> rectX track-        DragAxisY -> rectY track-      mouse = case axis of-        DragAxisX -> v2X (inputMousePos inp)-        DragAxisY -> v2Y (inputMousePos inp)-      down = inputMouseDown inp-  store <- uiIO (getStore ctx)-  gesture <- uiIO (getMenuPointerGesture ctx)-  let active0 = IM.findWithDefault 0 dragK (storeInt store) /= 0-      hit = rectHit track (inputMousePos inp) && not gesture-      active = down && not gesture && (active0 || hit)-      frac =-        if trackLen <= 0-          then 0-          else clamp01 ((mouse - origin) / trackLen)-      next =-        if active-          then lo + frac * (hi - lo)-          else current-  when (active /= active0) $-    uiIO $-      modifyStore ctx $ \st ->-        st-          { storeInt =-              if active-                then IM.insert dragK 1 (storeInt st)-                else IM.delete dragK (storeInt st)-          }-  pure (next, active)---- | Drag-and-drop reorder of a visible index list.-useReorder ::-  (Ui :> es) =>-  [Int] ->-  [(Int, Rect)] ->-  Eff es ([Int], Maybe Int)-useReorder order items = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  let key = intKey wid-      dragK = slotKey SlotDrag key-      mouse = inputMousePos inp-      down = inputMouseDown inp-      press = inputMousePressed inp-      release = inputMouseReleased inp-      hit =-        find-          (\(_, r) -> rectHit r mouse)-          items-  store <- uiIO (getStore ctx)-  let from0 = IM.findWithDefault (-1) dragK (storeInt store)-      startX = IM.findWithDefault 0 (slotKey SlotDragW key) (storeFloat store)-      dragging = if press then maybe (-1) fst hit else from0-      nextDrag =-        if release || not down-          then -1-          else dragging-      -- Resolve the drop using the held source before clearing it on release.-      moved =-        not press && dragging >= 0 && abs (v2X mouse - startX) > dragThresholdPx-      dropTo = if moved then fmap fst hit else Nothing-      nextOrder =-        case dropTo of-          Just toCol | release -> moveItem order dragging toCol-          _ -> order-  when (nextDrag /= from0 || (press && nextDrag >= 0)) $-    uiIO $-      modifyStore ctx $ \st ->-        st-          { storeInt = IM.insert dragK nextDrag (storeInt st)-          , storeFloat =-              IM.insert-                (slotKey SlotDragW key)-                (if press then v2X mouse else startX)-                (storeFloat st)-          }-  pure (nextOrder, if nextDrag >= 0 then Just nextDrag else Nothing)--moveItem :: [Int] -> Int -> Int -> [Int]-moveItem xs from to-  | from == to = xs-  | otherwise =-      let without = filter (/= from) xs-          (pre, post) = break (== to) without-       in pre ++ from : post--data KeyNav = KeyNav-  { knUp :: !Bool-  , knDown :: !Bool-  , knLeft :: !Bool-  , knRight :: !Bool-  , knEnter :: !Bool-  , knSpace :: !Bool-  }-  deriving (Eq, Show)---- | Focus alone does not grant keyboard input. A retained focus ID must still--- respect disabled state and the modal currently being declared. Unfocused--- controls avoid the store and modal checks entirely.-{-# INLINE keyboardFocused #-}-keyboardFocused :: Ui :> es => WidgetId -> Eff es Bool-keyboardFocused wid-  | hashWidgetId wid == 0 = pure False-  | otherwise = do-      ctx <- askContext-      focus <- uiIO (getFocusId ctx)-      if focus /= wid-        then pure False-        else uiIO $ do-          disabled <- isDisabled ctx wid-          if disabled then pure False else not <$> pointerBlockedByModal ctx---- | Arrow / Enter / Space while 'wid' is focused and eligible for input.-useKeyNav :: (Ui :> es) => WidgetId -> Eff es KeyNav-useKeyNav wid = do-  inp <- askInput-  let keys = inputKeys inp-      none = KeyNav False False False False False False-  if hashWidgetId wid == 0 || (inputKeysNull keys && T.null (inputChars inp))-    then pure none-    else do-      eligible <- keyboardFocused wid-      if not eligible-        then pure none-        else pure KeyNav-          { knUp = inputKeysElem KeyUp keys-          , knDown = inputKeysElem KeyDown keys-          , knLeft = inputKeysElem KeyLeft keys-          , knRight = inputKeysElem KeyRight keys-          , knEnter = inputKeysElem KeyEnter keys-          , knSpace = T.any (== ' ') (inputChars inp)-          }---- | True when Enter or Space was pressed while @wid@ holds focus. Buttons,--- checkboxes, and toggle switches treat this as a click.-{-# INLINE keyActivated #-}-keyActivated :: (Ui :> es) => WidgetId -> Eff es Bool-keyActivated wid = do-  nav <- useKeyNav wid-  pure (knEnter nav || knSpace nav)---- | Escape and click-outside-rect dismiss. Consumes Escape when it fires.-useDismissable :: (Ui :> es) => Rect -> Eff es Bool-useDismissable panel = do-  ctx <- askContext-  inp <- askInput-  let mouse = inputMousePos inp-      inside = rectHit panel mouse-      esc = inputKeysElem KeyEscape (inputKeys inp)-      backdrop = (inputMousePressed inp || inputMouseRightPressed inp) && not inside-      dismissed = esc || backdrop-  when esc $ uiIO (markEscapeConsumed ctx)-  pure dismissed
− lib/NanoUI/Widgets/Button.hs
@@ -1,50 +0,0 @@--- | Push buttons.-module NanoUI.Widgets.Button-  ( button-  , button'-  , buttonWith-  , buttonWith'-  )-where--import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Monad (Ui)-import NanoUI.Style (Layout, defaultLayout)-import NanoUI.Widgets.Combinators (buttonStyledEx)-import NanoUI.Widgets.Node (Response, respClicked)---- | Button with a text label. 'True' on the frame it is clicked, by pointer--- or by Enter or Space while focused.------ @--- whenM (button "Save") saveDocument--- @-{-# INLINE button #-}-button :: Ui :> es => Text -> Eff es Bool-button txt = respClicked <$> button' txt---- | 'button' returning its 'Response', for tooltips, anchored popups, or--- hover state.------ @--- help <- button' "Help"--- tooltip help "Open the manual"--- when (respClicked help) openManual--- @-{-# INLINE button' #-}-button' :: Ui :> es => Text -> Eff es Response-button' = buttonWith' id---- | 'button' with a layout modifier.------ @--- whenM (buttonWith (fixedW 120) "Submit") submitForm--- @-{-# INLINE buttonWith #-}-buttonWith :: Ui :> es => (Layout -> Layout) -> Text -> Eff es Bool-buttonWith f txt = respClicked <$> buttonWith' f txt--{-# INLINE buttonWith' #-}-buttonWith' :: Ui :> es => (Layout -> Layout) -> Text -> Eff es Response-buttonWith' f txt = buttonStyledEx True txt 0 (f defaultLayout) 0
− lib/NanoUI/Widgets/Checkbox.hs
@@ -1,35 +0,0 @@--- | Checkbox control.-module NanoUI.Widgets.Checkbox (checkbox, checkbox') where--import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context (adoptStoreInt, intKey, recordStoreInt, registerFocusable, writeStoreBool)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, nextId, uiIO)-import NanoUI.Store (boolInt, intBool)-import NanoUI.Style (defaultLayout)-import NanoUI.Widgets.Behavior (keyActivated)-import NanoUI.Widgets.Node (Response, addWidget, respClicked, setChanged)---- | Checkbox with a caption. Pass whether it is checked; the result is the--- state after this frame's click or Space/Enter.-{-# INLINE checkbox #-}-checkbox :: Ui :> es => Text -> Bool -> Eff es Bool-checkbox txt checked = snd <$> checkbox' txt checked--checkbox' :: Ui :> es => Text -> Bool -> Eff es (Response, Bool)-checkbox' txt checked = do-  wid <- nextId-  ctx <- askContext-  uiIO $ registerFocusable ctx wid-  let key = intKey wid-  current <- intBool <$> uiIO (adoptStoreInt ctx wid key (boolInt checked))-  resp <- addWidget wid NodeCheckbox txt (if current then 1 else 0) defaultLayout-  keyClick <- keyActivated wid-  let-    clicked = respClicked resp || keyClick-    display = current /= clicked-  uiIO $ do-    writeStoreBool ctx wid display-    recordStoreInt ctx key (boolInt display)-  pure (setChanged clicked resp, display)
− lib/NanoUI/Widgets/Chrome.hs
@@ -1,67 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}---- | Floating overlay chrome: title bars, close buttons.-module NanoUI.Widgets.Chrome-  ( modalTitleBarH-  , titleBarChromeHFor-  , titleBarLayoutFor-  , titleLabelLayoutFor-  , floatMinFor-  , closeButton-  , windowChromeTop-  , windowChromeSepH-  ) where--import Data.Bits ((.|.))-import Effectful (Eff, type (:>))-import NanoUI.WidgetText (buttonCloseTrailing, buttonFlagClose)-import NanoUI.Monad (Ui)-import NanoUI.Style-  ( Layout (..)-  , alignMid-  , defaultLayout-  , fillW-  , fixedH-  , fixedWH-  , gap-  , tight-  )-import NanoUI.Types (clamp)-import NanoUI.Widgets.Combinators (buttonStyled)-import NanoUI.Widgets.Node (Response)--titleBarH :: Float-titleBarH = 28--closeButtonSize :: Float-closeButtonSize = 24--windowChromeTop :: Float-windowChromeTop = 10--modalTitleBarH :: Float-modalTitleBarH = 40--windowChromeSepH :: Float-windowChromeSepH = 1--titleBarChromeHFor :: Float-titleBarChromeHFor = titleBarH + windowChromeTop + windowChromeSepH--titleBarLayoutFor :: Float -> Layout-titleBarLayoutFor barH =-  tight . gap 6 . alignMid . fixedH barH . fillW $ defaultLayout--titleLabelLayoutFor :: Float -> Layout-titleLabelLayoutFor barH =-  (fixedH barH . alignMid . tight) $-    defaultLayout {layoutMinH = barH, layoutMaxH = barH}--floatMinFor :: Float -> Float -> Float-floatMinFor authored avail = clamp 1 avail authored--{-# INLINE closeButton #-}-closeButton :: (Ui :> es) => Eff es Response-closeButton = buttonStyled "" 0 layout (buttonFlagClose .|. buttonCloseTrailing)-  where-    layout = tight . fixedWH closeButtonSize closeButtonSize . alignMid $ defaultLayout
− lib/NanoUI/Widgets/ColorPicker.hs
@@ -1,705 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}---- | Colour picker. The saturation / value field, the hue bar, the alpha bar and--- the Current / New preview are separate 'NodeColorPicker' nodes in one row,--- so each bar is its own focus stop with its own keyboard control.-module NanoUI.Widgets.ColorPicker-  ( ColorPickerPart (..)-  , colorPickerPartOf-  , widgetStoreColor-  , widgetStoreBaseColor-  , colorPickerSvSquare-  , colorPickerPartRect-  , colorPickerPreviewGeom-  , drawColorPickerPart-  , colorPicker-  , colorPicker'-  , colorPickerRGBA-  , colorPickerRGBA'-  )-where--import Control.Monad (forM_, void, when)-import Data.Bits ((.&.))-import Data.IORef (readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Maybe (fromMaybe, isJust)-import Data.Text (Text)-import Data.Word (Word8)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , WidgetStore (..)-  , getMenuPointerGesture-  , getStore-  , intKey-  , recordStoreInt-  , registerFocusable-  , setStore-  , getsOverlay-  , OverlayState (..)-  , modifyStore-  )-import NanoUI.Draw-  ( DrawArena-  , pushQuadGradient-  , pushRect-  , pushRoundedRect-  , pushRoundedStroke-  )-import NanoUI.Font-  ( FontMetrics (..)-  )-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (Input (..), Key (..), inputKeys, inputKeysElem, inputModifiers, inputMouseDown, inputMousePressed, modShift)-import NanoUI.Layout.Arena-  ( NodeArena-  , NodeIdx-  , NodeType (..)-  , getFirstChild-  , getNextSibling-  , getNodeType-  , getParent-  , getRect-  , getStyleIdx-  , getWidgetId-  )-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, withKey)-import NanoUI.Store (Slot (..), slotKey)-import NanoUI.Style-  ( AlignY (..)-  , Direction (..)-  , Layout (..)-  , Padding (..)-  , Sizing (..)-  , Style (..)-  , defaultLayout-  )-import NanoUI.Types-  ( Color (..)-  , Rect (..)-  , clamp-  , clamp01-  , colorA-  , colorB-  , colorFromWord32-  , colorG-  , colorR-  , colorRGBA-  , colorToWord32-  , hsvToRgb-  , rectH-  , rectW-  , rectX-  , rectY-  , rgbToHsv-  )-import NanoUI.WidgetText-  ( colorPickerGap-  , colorPickerParseHex-  , colorPickerSvH-  , colorToHex-  , colorToHexA-  )-import NanoUI.Widgets.Behavior-  ( DragAxis (..)-  , keyboardFocused-  , keyedDragHeld-  , useDrag1D-  )-import NanoUI.Widgets.Node-  ( Response (..)-  , addWidget-  , addWidgetStyled-  , container-  , respRect-  , setChanged-  )-import NanoUI.Widgets.NumericInput (NumericInputConfig (..), defaultNumericInputConfig, numericInputConfigured)-import NanoUI.Widgets.TextEditor (singleLineMode)-import NanoUI.Widgets.TextInput (editTextField)--colorPickerDefaultColor :: Color-colorPickerDefaultColor = colorRGBA 128 128 128 255--colorPickerBarW :: Float-colorPickerBarW = 14--colorPickerSwatchH :: Float-colorPickerSwatchH = 30--colorPickerSwatchW :: Float-colorPickerSwatchW = 80---- Width reserved for the Current / New preview column (label plus swatch).-colorPickerPreviewW :: Float-colorPickerPreviewW = 112---- | The piece of a colour picker a 'NodeColorPicker' node paints, kept in the--- low bits of its style.-data ColorPickerPart = PickerSv | PickerHue | PickerAlpha | PickerPreview-  deriving (Eq, Show, Enum, Bounded)--{-# INLINE colorPickerPartOf #-}-colorPickerPartOf :: Int -> ColorPickerPart-colorPickerPartOf si = toEnum (si .&. 3)--storeColorAt :: WidgetStore -> Int -> Color -> Color-storeColorAt store key fallback =-  colorFromWord32-    ( fromIntegral-        ( IM.findWithDefault-            (fromIntegral (colorToWord32 fallback))-            key-            (storeInt store)-        )-    )--widgetStoreColor :: WidgetStore -> WidgetId -> Color -> Color-widgetStoreColor store wid fallback = storeColorAt store (intKey wid) fallback--widgetStoreBaseColor :: WidgetStore -> WidgetId -> Color -> Color-widgetStoreBaseColor store wid fallback =-  storeColorAt-    store-    (slotKey SlotColorBase (intKey wid))-    (widgetStoreColor store wid fallback)---- RGB cannot tell hue 0 from 360. Keep the slider end the user last set.-widgetStoreHue :: WidgetStore -> WidgetId -> Color -> Float-widgetStoreHue store wid fallback =-  let-    (h0, _, _) = rgbToHsv (widgetStoreColor store wid fallback)-   in-    IM.findWithDefault h0 (intKey wid) (storeFloat store)---- Black collapses S in RGB. Keep the last mouse S/V so the marker does not jitter.-widgetStoreSv :: WidgetStore -> WidgetId -> Color -> (Float, Float)-widgetStoreSv store wid fallback =-  let-    (_, s0, v0) = rgbToHsv (widgetStoreColor store wid fallback)-   in-    fromMaybe (s0, v0) (IM.lookup (intKey wid) (storePoint store))---- | Store the live colour with the hue and S/V it was set through.-putColorState :: Int -> Color -> Float -> (Float, Float) -> WidgetStore -> WidgetStore-putColorState key col hue sv st =-  st-    { storeInt = IM.insert key (fromIntegral (colorToWord32 col)) (storeInt st)-    , storeFloat = IM.insert key hue (storeFloat st)-    , storePoint = IM.insert key sv (storePoint st)-    }--withAlpha :: Word8 -> Color -> Color-withAlpha a c = colorRGBA (colorR c) (colorG c) (colorB c) a---- | The square the saturation / value field fills, centered in its node.-colorPickerSvSquare :: Rect -> Rect-colorPickerSvSquare (Rect x y w h) =-  let s = max 0 (min w h)-   in Rect (x + (w - s) / 2) (y + (h - s) / 2) s s---- | The field node of the picker a part belongs to: the part's sibling that--- paints the saturation / value square. Its widget id keys the picker's state.-pickerSvNode :: NodeArena -> NodeIdx -> IO NodeIdx-pickerSvNode na idx = do-  parent <- getParent na idx-  if parent < 0 then pure idx else getFirstChild na parent >>= go-  where-    go ci-      | ci < 0 = pure idx-      | otherwise = do-          nt <- getNodeType na ci-          si <- getStyleIdx na ci-          if nt == NodeColorPicker && colorPickerPartOf si == PickerSv-            then pure ci-            else getNextSibling na ci >>= go---- | Where the part at @idx@ (laid out at @rect@) draws: the field's square, or--- the part's column cut to the square's height so the bars and the preview--- line up with the field.-colorPickerPartRect :: NodeArena -> NodeIdx -> Rect -> IO Rect-colorPickerPartRect na idx rect@(Rect x _ w _) = do-  si <- getStyleIdx na idx-  case colorPickerPartOf si of-    PickerSv -> pure (colorPickerSvSquare rect)-    _ -> do-      (sx, sy0, sw, sh) <- pickerSvNode na idx >>= getRect na-      let Rect _ sy _ side = colorPickerSvSquare (Rect sx sy0 sw sh)-      pure (Rect x sy w side)---- | The preview column's rows, stacked and centered in its band: the Current--- label's top, its swatch, the New label's top, and its swatch.-colorPickerPreviewGeom :: FontMetrics -> Rect -> (Float, Rect, Float, Rect)-colorPickerPreviewGeom fm (Rect x y w h) =-  let-    labelH = fmLineHeight fm-    swatchW = min colorPickerSwatchW w-    swatchH = clamp 0 colorPickerSwatchH (h - labelH * 2 - colorPickerGap)-    stackH = labelH + swatchH + colorPickerGap + labelH + swatchH-    top = y + max 0 ((h - stackH) / 2)-    currentY = top + labelH-    newLabelY = currentY + swatchH + colorPickerGap-   in-    (top, Rect x currentY swatchW swatchH, newLabelY, Rect x (newLabelY + labelH) swatchW swatchH)---- Wider than the painted bar so the handle is easy to grab.-colorPickerBarHitRect :: Rect -> Rect-colorPickerBarHitRect (Rect x y w h) =-  let-    pad = 2-   in-    Rect (x - pad) y (w + pad * 2) h--drawSvField :: DrawArena -> Rect -> Float -> IO ()-drawSvField da rect hue = do-  let-    white = colorRGBA 255 255 255 255-    hueCol = hsvToRgb hue 1 1-    clear = colorRGBA 0 0 0 0-    black = colorRGBA 0 0 0 255-  -- Horizontal: white to hue. Vertical overlay: fade to black (alpha over).-  pushQuadGradient da rect white hueCol hueCol white-  pushQuadGradient da rect clear clear black black---- Vertical rainbow: each stop band fades into the next.-drawHueBar :: DrawArena -> Rect -> IO ()-drawHueBar da rect =-  let-    stops = (6 :: Int)-    cellH = rectH rect / fromIntegral stops-    stopCol i = hsvToRgb (360 * fromIntegral i / fromIntegral stops) 1 1-   in-    mapM_-      ( \i ->-          let-            cell = Rect (rectX rect) (rectY rect + fromIntegral i * cellH) (rectW rect) cellH-           in-            pushQuadGradient-              da-              cell-              (stopCol i)-              (stopCol i)-              (stopCol (i + 1))-              (stopCol (i + 1))-      )-      [0 .. stops - 1]--drawChecker :: DrawArena -> Rect -> IO ()-drawChecker da (Rect x y w h) = goRows 0-  where-    s = 6 :: Float-    cols = ceiling (max 0 w / s) :: Int-    rows = ceiling (max 0 h / s) :: Int-    -- Nested range folds retain a shared column list under -O2. Explicit-    -- counters keep both loops numeric, without allocating that list.-    goRows !ry = when (ry < rows) $ do-      goCols ry 0-      goRows (ry + 1)-    goCols !ry !cx = when (cx < cols) $ do-      let-        col =-          if even (ry + cx) then colorRGBA 190 190 190 255 else colorRGBA 140 140 140 255-        rx = x + fromIntegral cx * s-        ry' = y + fromIntegral ry * s-        cw = clamp 0 s (x + w - rx)-        ch = clamp 0 s (y + h - ry')-      pushRect da (Rect rx ry' cw ch) col-      goCols ry (cx + 1)--drawAlphaBar :: DrawArena -> Rect -> Color -> IO ()-drawAlphaBar da rect col = do-  drawChecker da rect-  let-    c0 = withAlpha 0 col-    c1 = withAlpha 255 col-  pushQuadGradient da rect c0 c0 c1 c1--drawBarHandle :: DrawArena -> Rect -> Float -> Color -> IO ()-drawBarHandle da bar cy col = do-  let-    w = rectW bar-    x = rectX bar-    h = 4-    handle = Rect (x - 3) (cy - h / 2) (w + 6) h-  pushRoundedRect da handle 2 (colorRGBA 255 255 255 255)-  pushRoundedStroke da handle 2 1 col---- | Paint one part of a picker from its state in the store.-drawColorPickerPart :: NodeArena -> NodeIdx -> FontMetrics -> DrawArena -> WidgetStore -> Style -> Rect -> IO ()-drawColorPickerPart na idx fm da store style rect = do-  si <- getStyleIdx na idx-  owner <- pickerSvNode na idx >>= getWidgetId na-  area <- colorPickerPartRect na idx rect-  let-    newCol = widgetStoreColor store owner colorPickerDefaultColor-    border = styleBorder style-    handleCol = colorRGBA 0 0 0 180-  case colorPickerPartOf si of-    PickerSv -> do-      let-        hue = widgetStoreHue store owner colorPickerDefaultColor-        (sat, val) = widgetStoreSv store owner colorPickerDefaultColor-        marker = 6-        mx = rectX area + sat * rectW area-        my = rectY area + (1 - val) * rectH area-        dot = Rect (mx - marker / 2) (my - marker / 2) marker marker-      drawSvField da area hue-      pushRoundedStroke da area 4 1 border-      pushRoundedRect da dot (marker / 2) (colorRGBA 255 255 255 255)-      pushRoundedStroke da dot (marker / 2) 1 handleCol-    PickerHue -> do-      let hue = widgetStoreHue store owner colorPickerDefaultColor-      drawHueBar da area-      pushRoundedStroke da area 3 1 border-      drawBarHandle da area (rectY area + (hue / 360) * rectH area) handleCol-    PickerAlpha -> do-      drawAlphaBar da area newCol-      pushRoundedStroke da area 3 1 border-      drawBarHandle da area (rectY area + (fromIntegral (colorA newCol) / 255) * rectH area) handleCol-    PickerPreview -> do-      let-        (_, current, _, new) = colorPickerPreviewGeom fm area-        swatch r col = do-          drawChecker da r-          pushRect da r col-          pushRoundedStroke da r 0 1 border-      swatch current (widgetStoreBaseColor store owner colorPickerDefaultColor)-      swatch new newCol--colorPickerLayout :: Layout-colorPickerLayout =-  defaultLayout-    { layoutDirection = Column-    , layoutWidth = Grow 1-    , layoutGap = colorPickerGap-    , layoutPadding = Padding 0 0 0 0-    }---- The field, bars and preview side by side.-colorPickerCanvasLayout :: Layout-colorPickerCanvasLayout =-  colorPickerLayout {layoutDirection = Row}---- The field grows up to a square as tall as the row.-colorPickerSvLayout :: Layout-colorPickerSvLayout =-  defaultLayout-    { layoutWidth = Grow 1-    , layoutHeight = Fixed colorPickerSvH-    , layoutMinW = 60-    , layoutMaxW = colorPickerSvH-    , layoutPadding = Padding 0 0 0 0-    }--colorPickerColumnLayout :: Float -> Layout-colorPickerColumnLayout w =-  colorPickerSvLayout {layoutWidth = Fixed w, layoutMinW = w, layoutMaxW = w}---- A row of channel fields. Children are groups sized by 'percent' so the--- R/G/B(/A) and H/S/V rows share the same column widths.-colorPickerRowLayout :: Layout-colorPickerRowLayout =-  colorPickerLayout {layoutDirection = Row, layoutAlignY = AlignMiddle}---- One channel field: an inline label plus its bare box, taking @pct@ of the row.-colorPickerFieldGroupLayout :: Float -> Layout-colorPickerFieldGroupLayout pct =-  colorPickerLayout-    { layoutDirection = Row-    , layoutWidth = Percent pct-    , layoutAlignY = AlignMiddle-    }--colorPickerFieldLayout :: Layout-colorPickerFieldLayout =-  defaultLayout-    { layoutWidth = Grow 1-    , layoutMinW = 40-    , layoutPadding = Padding 0 0 0 0-    }---- A numeric channel field: room for three digits beside its stepper.-colorPickerChannelLayout :: Layout-colorPickerChannelLayout = colorPickerFieldLayout {layoutMinW = 60}--colorPickerLabelLayout :: Layout-colorPickerLabelLayout =-  defaultLayout {layoutPadding = Padding 0 0 0 0, layoutAlignY = AlignMiddle}---- | RGB colour picker: a saturation/value field, a hue bar, and RGB, HSV and--- hex fields. Pass the current colour; the result is the colour after this--- frame's edits.------ The field and each bar take keyboard focus in turn. On the field the arrow--- keys move the marker (left and right for saturation, up and down for--- value); on a bar they move its handle, and Home and End jump to its ends.--- Shift takes steps ten times larger.-{-# INLINE colorPicker #-}-colorPicker :: Ui :> es => Color -> Eff es Color-colorPicker value = snd <$> colorPickerWith False value--colorPicker' :: Ui :> es => Color -> Eff es (Response, Color)-colorPicker' = colorPickerWith False---- | 'colorPicker' with an alpha bar and an A / @#RRGGBBAA@ field.-{-# INLINE colorPickerRGBA #-}-colorPickerRGBA :: Ui :> es => Color -> Eff es Color-colorPickerRGBA value = snd <$> colorPickerWith True value--colorPickerRGBA' :: Ui :> es => Color -> Eff es (Response, Color)-colorPickerRGBA' = colorPickerWith True---- | The byte fields: label, the channel read, and the channel write.-rgbChannels, rgbaChannels :: [(Text, Color -> Word8, Word8 -> Color -> Color)]-rgbChannels =-  [ ("R", colorR, \v c -> colorRGBA v (colorG c) (colorB c) (colorA c))-  , ("G", colorG, \v c -> colorRGBA (colorR c) v (colorB c) (colorA c))-  , ("B", colorB, \v c -> colorRGBA (colorR c) (colorG c) v (colorA c))-  ]-rgbaChannels = rgbChannels ++ [("A", colorA, \v c -> colorRGBA (colorR c) (colorG c) (colorB c) v)]---- | The HSV fields: label, the largest value, the shown value, and the--- (hue, s, v) a typed value makes.-hsvChannels :: [(Text, Int, (Float, Float, Float) -> Int, Int -> (Float, Float, Float) -> (Float, Float, Float))]-hsvChannels =-  [ ("H", 360, \(h, _, _) -> round h, \n (_, s, v) -> (fromIntegral n, s, v))-  , ("S", 100, \(_, s, _) -> round (s * 100), \n (h, _, v) -> (h, percent n, v))-  , ("V", 100, \(_, _, v) -> round (v * 100), \n (h, s, _) -> (h, s, percent n))-  ]-  where-    percent n = fromIntegral n / 100---- | Widget ids of a picker's parts. The field's id keys the picker's state.-data PickerParts = PickerParts-  { ppSv :: !WidgetId-  , ppHue :: !WidgetId-  , ppAlpha :: !WidgetId-  , ppPreview :: !WidgetId-  }--colorPickerWith ::-  Ui :> es => Bool -> Color -> Eff es (Response, Color)-colorPickerWith showAlpha value = do-  ctx <- askContext-  parts <- PickerParts <$> nextId <*> nextId <*> nextId <*> nextId-  let-    wid = ppSv parts-    key = intKey wid-    pct = 100 / (if showAlpha then 4 else 3)-    readColor = (\st -> widgetStoreColor st wid value) <$> uiIO (getStore ctx)-    writePicker col hue sv = uiIO (modifyStore ctx (putColorState key col hue sv))-    writeColor col =-      let (h, s, v) = rgbToHsv col-       in writePicker col (clamp 0 360 h) (s, v)-    -- Without the alpha bar the colour stays opaque.-    alphaOf c = if showAlpha then colorA c else 255-    part pid p lay = addWidgetStyled pid NodeColorPicker "" 0 lay (fromEnum p)-  uiIO $ do-    adoptColorPickerValue ctx wid value-    mapM_ (registerFocusable ctx) (wid : ppHue parts : [ppAlpha parts | showAlpha])-  (start, final, svResp) <- container NodeContainer colorPickerLayout $ do-    (svResp, hueResp, alphaResp) <--      container NodeContainer colorPickerCanvasLayout $ do-        sv <- part wid PickerSv colorPickerSvLayout-        hue <- part (ppHue parts) PickerHue (colorPickerColumnLayout colorPickerBarW)-        alpha <--          if showAlpha-            then Just <$> part (ppAlpha parts) PickerAlpha (colorPickerColumnLayout colorPickerBarW)-            else pure Nothing-        void (part (ppPreview parts) PickerPreview (colorPickerColumnLayout colorPickerPreviewW))-        pure (sv, hue, alpha)-    start <- colorPickerCanvas parts value svResp hueResp alphaResp-    -- Only the focused field edits, so each row's fields share one store read.-    rgb <- readColor-    _ <- container NodeContainer colorPickerRowLayout $-      forM_ (if showAlpha then rgbaChannels else rgbChannels) $ \(lbl, get, set) -> do-        let shown = fromIntegral (get rgb)-        n <- channelField pct lbl 255 shown-        when (n /= shown) $-          writeColor (set (fromIntegral n) (withAlpha (alphaOf rgb) rgb))-    hsvStore <- uiIO (getStore ctx)-    let-      (s0, v0) = widgetStoreSv hsvStore wid value-      hsv = (widgetStoreHue hsvStore wid value, s0, v0)-      alpha = alphaOf (widgetStoreColor hsvStore wid value)-    _ <- container NodeContainer colorPickerRowLayout $ do-      forM_ hsvChannels $ \(lbl, hi, shown, edit) -> do-        n <- channelField pct lbl hi (shown hsv)-        when (n /= shown hsv) $ do-          let (h, s, v) = edit n hsv-          writePicker (withAlpha alpha (hsvToRgb h s v)) h (s, v)-      when showAlpha $-        void (container NodeContainer (colorPickerFieldGroupLayout pct) (pure ()))-    hex <- readColor-    let hexText = if showAlpha then colorToHexA hex else colorToHex hex-    hexWid <- nextId-    (_, thex, fhex, _) <- editTextField hexWid singleLineMode hexText (Just hexText)-    _ <--      container NodeContainer (colorPickerFieldGroupLayout 100) $-        addWidgetStyled hexWid NodeTextInput "" 0 colorPickerFieldLayout 0-    when (fhex && thex /= hexText) $-      forM_ (colorPickerParseHex thex) $ \(r, g, b, ma) ->-        writeColor (colorRGBA r g b (if showAlpha then fromMaybe (colorA hex) ma else 255))-    final <- readColor-    pure (start, final, svResp)-  uiIO $ recordStoreInt ctx key (fromIntegral (colorToWord32 final))-  pure (setChanged (final /= start) svResp, final)---- | The field and the bars: pointer drags, then arrow keys on whichever part--- holds focus, then committing the "current" swatch when a drag ends or a key--- moved the colour. Returns the colour the frame started with.-colorPickerCanvas :: Ui :> es => PickerParts -> Color -> Response -> Response -> Maybe Response -> Eff es Color-colorPickerCanvas parts initial svResp hueResp alphaResp = do-  ctx <- askContext-  inp <- askInput-  active <- uiIO (readIORef (ctxActiveId ctx))-  blocked <- uiIO (getsOverlay ctx osLastPointerBlocked)-  gesture <- uiIO (getMenuPointerGesture ctx)-  store0 <- uiIO (getStore ctx)-  hueHeld0 <- keyedDragHeld ("hue" :: Text)-  alphaHeld0 <- keyedDragHeld ("alpha" :: Text)-  sHeld0 <- keyedDragHeld ("s" :: Text)-  vHeld0 <- keyedDragHeld ("v" :: Text)-  let-    wid = ppSv parts-    showAlpha = isJust alphaResp-    current0 = widgetStoreColor store0 wid initial-    h0 = widgetStoreHue store0 wid initial-    (s0, v0) = widgetStoreSv store0 wid initial-    svHeld0 = sHeld0 || vHeld0-    empty = Rect 0 0 0 0-    isActive = active == wid-    -- A press lands on whichever part is under the pointer; the picker then-    -- takes the active id over while it drags.-    ownsActive = active `elem` [wid, ppHue parts, ppAlpha parts, ppPreview parts]-    heldByOther =-      inputMouseDown inp-        && not (inputMousePressed inp)-        && hashWidgetId active /= 0-        && not ownsActive-    locked = blocked || heldByOther || gesture-    svSquare = colorPickerSvSquare (respRect svResp)-    band resp = Rect (rectX (respRect resp)) (rectY svSquare) (rectW (respRect resp)) (rectH svSquare)-    svRect = if locked || hueHeld0 || alphaHeld0 then empty else svSquare-    hueRect = if locked || svHeld0 || alphaHeld0 then empty else colorPickerBarHitRect (band hueResp)-    alphaRect =-      case alphaResp of-        Just r | not (locked || svHeld0 || hueHeld0) -> colorPickerBarHitRect (band r)-        _ -> empty-  (sDrag, sA) <- withKey ("s" :: Text) (useDrag1D DragAxisX 0 1 s0 svRect)-  (vDrag, vA) <- withKey ("v" :: Text) (useDrag1D DragAxisY 1 0 v0 svRect)-  let svA = sA || vA-  (hDrag, hA) <--    withKey ("hue" :: Text) (useDrag1D DragAxisY 0 360 h0 (if svA then empty else hueRect))-  (aDrag, aA) <--    withKey-      ("alpha" :: Text)-      (useDrag1D DragAxisY 0 255 (fromIntegral (colorA current0)) (if svA || hA then empty else alphaRect))-  let-    dragging = svA || hA || aA-    nextHue = if hA then hDrag else h0-    nextS = if sA then sDrag else s0-    nextV = if vA then vDrag else v0-    nextA =-      if aA then clamp 0 255 (round aDrag :: Int) else fromIntegral (colorA current0)-    base = hsvToRgb nextHue nextS nextV-    dragged-      | aA && not (svA || hA) = withAlpha (fromIntegral nextA) current0-      | otherwise = withAlpha (if showAlpha then fromIntegral nextA else 255) base-  when (dragging && not isActive) $ uiIO $ writeIORef (ctxActiveId ctx) wid-  when ((not dragging || blocked) && isActive) $-    uiIO $ writeIORef (ctxActiveId ctx) (WidgetId 0)-  when (dragging && (dragged /= current0 || nextHue /= h0 || nextS /= s0 || nextV /= v0)) $-    uiIO $ modifyStore ctx (putColorState (intKey wid) dragged nextHue (nextS, nextV))-  svFocus <- keyboardFocused wid-  hueFocus <- keyboardFocused (ppHue parts)-  alphaFocus <- if showAlpha then keyboardFocused (ppAlpha parts) else pure False-  keyMoved <--    if not (svFocus || hueFocus || alphaFocus)-      then pure False-      else uiIO (applyColorPickerKeys ctx wid initial inp svFocus hueFocus)-  let releasedDrag = (hueHeld0 || alphaHeld0 || svHeld0) && not dragging-  when (releasedDrag || keyMoved) $-    uiIO $ do-      st <- getStore ctx-      commitColorPickerCurrent ctx wid (widgetStoreColor st wid initial)-  pure current0---- | One channel field: an inline label and a numeric box over @0..hi@ that--- shows @value@ while unfocused. Returns the value after this frame's edits.-channelField :: Ui :> es => Float -> Text -> Int -> Int -> Eff es Int-channelField pct label hi value =-  container NodeContainer (colorPickerFieldGroupLayout pct) $ do-    labelWid <- nextId-    void (addWidget labelWid NodeText label 0 colorPickerLabelLayout)-    round-      <$> numericInputConfigured-        defaultNumericInputConfig {nicMin = 0, nicMax = fromIntegral hi, nicLayout = colorPickerChannelLayout}-        (fromIntegral value)---- | Adopt the caller's colour as 'NanoUI.Context.adoptStoreInt' does. A new--- colour also resets the hue, S/V, and the "current" swatch.-adoptColorPickerValue :: Context -> WidgetId -> Color -> IO ()-adoptColorPickerValue ctx wid value = do-  store0 <- getStore ctx-  let-    key = intKey wid-    packed = fromIntegral (colorToWord32 value)-    seenKey = slotKey SlotSeen key-    ints = IM.insert seenKey packed (storeInt store0)-  when (IM.lookup seenKey (storeInt store0) /= Just packed) $-    setStore ctx $-      if IM.lookup key (storeInt store0) == Just packed-        then store0 {storeInt = ints}-        else-          let (h, s, v) = rgbToHsv value-           in putColorState key value (clamp 0 360 h) (s, v) $-                store0 {storeInt = IM.insert (slotKey SlotColorBase key) packed ints}--commitColorPickerCurrent :: Context -> WidgetId -> Color -> IO ()-commitColorPickerCurrent ctx wid col = do-  st <- getStore ctx-  let-    packed = fromIntegral (colorToWord32 col)-    k = slotKey SlotColorBase (intKey wid)-    old = IM.findWithDefault packed k (storeInt st)-  when (old /= packed) $-    setStore ctx (st {storeInt = IM.insert k packed (storeInt st)})---- | Arrow, Home and End keys on the focused part: the field when @svFocus@,--- the hue bar when @hueFocus@, otherwise the alpha bar. Arrows move a part--- the way it is drawn: the marker right for more saturation and up for more--- value, a bar's handle down (or right) towards its bottom end. Returns--- whether the colour moved.-applyColorPickerKeys :: Context -> WidgetId -> Color -> Input -> Bool -> Bool -> IO Bool-applyColorPickerKeys ctx wid fallback inp svFocus hueFocus = do-  store <- getStore ctx-  let-    keys = inputKeys inp-    down k = inputKeysElem k keys-    step = if modShift (inputModifiers inp) then 10 else 1-    along neg pos = (if down pos then 1 else 0) - (if down neg then 1 else 0) :: Float-    dx = along KeyLeft KeyRight-    dy = along KeyUp KeyDown-    current = widgetStoreColor store wid fallback-    h = widgetStoreHue store wid current-    (s, v) = widgetStoreSv store wid current-    a = fromIntegral (colorA current) :: Float-    bar lo hi cur-      | down KeyHome = lo-      | down KeyEnd = hi-      | otherwise = clamp lo hi (cur + (dx + dy) * step)-    (col', h', sv')-      | svFocus =-          let sat = clamp01 (s + dx * step / 100)-              val = clamp01 (v - dy * step / 100)-           in (withAlpha (colorA current) (hsvToRgb h sat val), h, (sat, val))-      | hueFocus =-          let hue = bar 0 360 h-           in (withAlpha (colorA current) (hsvToRgb hue s v), hue, (s, v))-      | otherwise = (withAlpha (round (bar 0 255 a)) current, h, (s, v))-    moved = col' /= current || h' /= h || sv' /= (s, v)-  when moved $-    setStore ctx (putColorState (intKey wid) col' h' sv' store)-  pure moved
− lib/NanoUI/Widgets/Combinators.hs
@@ -1,78 +0,0 @@-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE OverloadedStrings #-}---- | Button and selection helpers shared by the widget modules.-module NanoUI.Widgets.Combinators-  ( buttonStyled-  , buttonStyledEx-  , selectableItem-  , withBoundedIndex-  )-where--import Control.Monad (when)-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context (isDisabled, registerFocusable)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, nextId, uiIO)-import NanoUI.Style (Layout (..))-import NanoUI.Widgets.Behavior (keyActivated)-import NanoUI.Widgets.Node-  ( Response (..)-  , addWidgetStyled-  , setClicked-  )---- | Button with styleIdx for active, sort, badge, or close chrome. Focusable--- and activatable with Enter or Space while focused.-buttonStyled :: (Ui :> es) => Text -> Float -> Layout -> Int -> Eff es Response-buttonStyled = buttonStyledEx True---- | Shared activation path for ordinary buttons, menu items, and header chrome.--- Disabled controls keep their identity and geometry but cannot take focus or--- activate, including through a click queued before they became disabled.-{-# INLINE buttonStyledEx #-}-buttonStyledEx :: (Ui :> es) => Bool -> Text -> Float -> Layout -> Int -> Eff es Response-buttonStyledEx enabled txt value layout styleIdx = do-  wid <- nextId-  ctx <- askContext-  disabled <- uiIO (isDisabled ctx wid)-  let active = enabled && not disabled-  when active $ uiIO (registerFocusable ctx wid)-  resp <- addWidgetStyled wid NodeButton txt value layout styleIdx-  if active-    then do-      keyClick <- keyActivated wid-      pure (if keyClick then setClicked True resp else resp)-    else pure resp-      { rawRespHovered = False-      , rawRespPressed = False-      , rawRespClicked = False-      , rawRespRightPressed = False-      , rawRespRightClicked = False-      }--selectableItem :: (Ui :> es) => NodeType -> Text -> Bool -> Layout -> Int -> Eff es Response-selectableItem nt txt selected layout styleIdx = do-  wid <- nextId-  addWidgetStyled-    wid-    nt-    txt-    (if selected then 1 else 0)-    layout-    styleIdx---- | Run an index-based picker over every value of a bounded enum. Indices--- are offset by @fromEnum minBound@, so enums that do not start at 0 map--- correctly. Meant for small enums: every value becomes an option.-withBoundedIndex ::-  forall a r f.-  (Bounded a, Enum a, Functor f) =>-  (a -> Text) -> a -> ([Text] -> Int -> f (r, Int)) -> f (r, a)-withBoundedIndex encode initial pick =-  fmap (toEnum . (+ lower))-    <$> pick (map encode [minBound .. maxBound]) (fromEnum initial - lower)-  where-    lower = fromEnum (minBound :: a)
lib/NanoUI/Widgets/Combo.hs view
@@ -1,5 +1,3 @@-{-# LANGUAGE OverloadedStrings #-}- -- | Combo box: a search field with a filtered, scrollable suggestion dropdown. -- The per-frame logic is the pure 'comboStep' over a persisted 'ComboState'. module NanoUI.Widgets.Combo@@ -12,40 +10,36 @@   ) where -import Control.Monad (foldM, when, (<$!>))+import Control.Monad (foldM, forM_, mfilter, void, when, (<$!>))+import Data.Foldable (toList) import Data.IORef (writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Maybe (fromMaybe, isJust)+import Data.Hashable (hash)+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe) import Data.Text (Text) import Data.Text qualified as T-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , getStore-  , intKey-  , markDirty-  , markEscapeConsumed-  , modifyStore-  , recordStoreText-  )-import NanoUI.Font (FontMetrics, menuItemRowH)-import NanoUI.Frame.Hit (findNodeByWidgetId)-import NanoUI.Frame.Select (comboDropPickIndex, comboDropRect, comboScrollGeom)-import NanoUI.Id (WidgetId (..))-import NanoUI.Input (Key (..), inputKeys, inputMouseDown, inputMousePos, inputMousePressed, inputScroll)-import NanoUI.Layout.Arena (setOptions)-import NanoUI.Monad (Ui, askContext, askInput, uiIO)-import NanoUI.Store-  ( WidgetStore (..)-  , boolInt-  , Slot (..)-  , slotKey-  )-import NanoUI.Types (Rect (..), V2 (..), clamp, rectContains, rectNonEmpty, v2X, v2Y)-import NanoUI.WidgetText (textInputFlagSearch)-import NanoUI.Widgets.Behavior (keyboardFocused)-import NanoUI.Widgets.Node (Response (..), setChanged)-import NanoUI.Widgets.TextInput (buildTextInput, searchFieldLayout)+import NanoUI.Internal.Context+import NanoUI.Internal.Canvas (drawRect, drawRoundedRect, runCanvasFor, withClip)+import NanoUI.Internal.Derived (ComboMatches (..), comboCache)+import NanoUI.Internal.Font (menuItemRowH)+import NanoUI.Internal.Frame.Hit (findNodeByWidgetId)+import NanoUI.Internal.Frame.Select (comboDropPickIndex, comboDropRect, comboScrollGeom, dropdownPopupRows)+import NanoUI.Internal.Id (WidgetId (..))+import NanoUI.Internal.Input (Input, Key (..), MouseButton (..), Pressable (..), inputMousePos, inputScroll, inputWindowSize)+import NanoUI.Internal.Style (scrollBarThumbColor, scrollBarThumbHoverColor, scrollBarTrackColor, themeInput)+import NanoUI.Internal.Layout.Arena (DirTag (..), setOptions)+import NanoUI.Internal.Layout.ScrollGeometry (ScrollBarLayout (..), onScrollBar, scrollOffsetFromThumb)+import NanoUI.Internal.Monad (NanoUI, askContext, liftIO)+import NanoUI.Internal.Store (fieldCombo, fieldText, insertSlot, lookupSlot, ptrEq, setFieldSelection)+import NanoUI.Internal.Store.Types (ComboState (..))+import NanoUI.Internal.Var (Binding (..), bindVar)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Types (Rect (..), Size (..), V2 (..), clamp, rectContains, rectIntersect, rectNonEmpty, v2X, v2Y)+import NanoUI.Internal.WidgetText (textInputFlagSearch)+import NanoUI.Internal.Widgets.Behavior (keyboardFocused)+import NanoUI.Internal.Widgets.Combinators (readDerived, writeDerived)+import NanoUI.Internal.Widgets.Node (Response (..), dropdownInput, respPressed, setChanged)+import NanoUI.Internal.Widgets.Select (dropdownPopup, paintDropdownRows)+import NanoUI.Internal.Widgets.TextInput (buildTextInput, searchInputLayout)  -- | Maximum suggestion rows the combo dropdown shows at once; Up/Down walk -- the highlight and the wheel scrolls the list through a sliding window.@@ -61,35 +55,29 @@ comboFiltered options q   | T.null q = opts   | otherwise =-      let needle = T.toLower q-        in filter (T.isInfixOf needle . T.toLower) opts+      let needle = T.toCaseFold q+        in filter (T.isInfixOf needle . T.toCaseFold) opts   where-    opts = foldr (:) [] options+    opts = toList options --- | A combo's state between frames.-data ComboState = ComboState-  { csHighlight :: !Int-    -- ^ Highlighted row of the filtered list; -1 for none.-  , csWindow :: !Int-    -- ^ First visible row.-  , csScrollX :: !Float-  , csContentW :: !Float-    -- ^ Widest matching row, measured while focused.-  , csDrag :: !Int-    -- ^ Scrollbar thumb drag: 0 none, 1 vertical, 2 horizontal.-  , csDragOff :: !Float-    -- ^ Pointer offset into the dragged thumb.-  , csCommitted :: !Text-    -- ^ Last committed value.-  , csLive :: !Text-    -- ^ Field text the combo last produced.-  , csFocused :: !Bool-  }-  deriving (Eq, Show)+-- | 'comboFiltered', kept in 'ctxDerivedCache' under the combo's key while the+-- options are the same container and the query the same text. A combo+-- filters its options on every frame, focused or not, and a long list (a+-- font picker's families) would otherwise fold every option each time. The+-- caller's container is compared, not a list made from it, so a vector or+-- sequence hits too.+comboMatches :: Foldable f => Context -> Int -> f Text -> Text -> IO ComboMatches+comboMatches ctx key !opts q =+  readDerived comboCache ctx key >>= \case+    Just m@(ComboMatches o q' _ _) | ptrEq o opts && q' == q -> pure m+    _ -> do+      let m = ComboMatches opts q (comboFiltered opts q) Nothing+      m <$ writeDerived comboCache ctx key m  -- | One frame's inputs to 'comboStep'. data ComboInput = ComboInput   { ciFocused :: !Bool+    -- ^ The field holds keyboard focus, so the dropdown is open.   , ciEdited :: !Bool     -- ^ Typing changed the field text this frame.   , ciText :: !Text@@ -99,19 +87,14 @@   , ciContentW :: !Float     -- ^ Width of the widest matching row.   , ciField :: !Rect-    -- ^ The field's rect; empty before its first layout.-  , ciMetrics :: !FontMetrics-  , ciMouse :: !V2-  , ciPressed :: !Bool-  , ciDown :: !Bool-  , ciScroll :: !V2-  , ciKeyUp :: !Bool-  , ciKeyDown :: !Bool-  , ciEnter :: !Bool-  , ciEscape :: !Bool+    -- ^ The field's rect; empty before its first layout and while the field+    -- is clipped out of view, when no row takes the pointer.+  , ciInput :: !Input+    -- ^ Dropdown-scoped input for the frame.   }+  deriving (Eq, Show) --- | What one frame of the combo decided.+-- | Result of stepping the combo state for one frame. data ComboStep = ComboStep   { stepState :: !ComboState   , stepCommit :: !(Maybe Text)@@ -123,6 +106,7 @@   , stepRedraw :: !Bool     -- ^ Something visible moved.   }+  deriving (Eq, Show)  -- | One frame of the combo: highlight, scrolling, thumb drags, and commits. --@@ -130,7 +114,8 @@ -- changes on Enter (which commits the highlighted row only), on a row click -- (a field text the combo did not produce), or when the field loses focus. -- Escape reverts the live text to the last committed value. Hover--- highlights a row and makes it the Enter target; Up/Down move the highlight.+-- highlights a row and makes it the Enter target; Up/Down move the highlight,+-- and a stationary pointer does not override keyboard highlight until it moves. comboStep :: ComboInput -> ComboState -> ComboStep comboStep ci cs0 =   ComboStep@@ -142,25 +127,30 @@           , csContentW = contentW           , csDrag = dragKind'           , csDragOff = dragOff'+          , csWheelRem = wheelRows - fromIntegral wheelDelta           , csCommitted = fromMaybe committed0 commitText           , csLive = finalText           , csFocused = isFocus+          , csNavPointer = navPointer           }     , stepCommit = if commitPulse then commitText else Nothing     , stepPicked = picked     , stepDismissed = escDismiss     , stepRedraw =-        picked || nav /= 0 || escDismiss || wheelDelta /= 0 || xWheel /= 0+        -- What navigation and the wheel show moves the window, the x offset+        -- or the highlight; a press at the end of the list moves nothing.+        picked || escDismiss           || win /= storedWin || xOff /= storedX || hi' /= storedHi           || dragKind' /= drag0 || commitPulse || csFocused cs0 /= isFocus     }   where     isFocus = ciFocused ci+    inp = ciInput ci     text = ciText ci     displayed = ciRows ci     contentW = ciContentW ci     n = length displayed-    vis = max 1 comboBoxMaxVisible+    vis = comboBoxMaxVisible     storedHi = csHighlight cs0     storedWin = csWindow cs0     storedX = csScrollX cs0@@ -172,8 +162,8 @@     win0 = if ciEdited ci then 0 else storedWin     nav       | not isFocus || n <= 0 = 0 :: Int-      | ciKeyDown ci = 1-      | ciKeyUp ci = -1+      | pressedIn KeyDown inp = 1+      | pressedIn KeyUp inp = -1       | otherwise = 0     hi       | nav == 0 = hi0@@ -187,15 +177,18 @@       | hi >= v + vis = hi - vis + 1       | otherwise = clampWin v     Rect rx ry rw rh = ciField ci-    mouse = ciMouse ci-    dropRect = comboDropRect rx ry rw rh (min vis n) n contentW+    mouse = inputMousePos inp+    dropRect = comboDropRect (inputWindowSize inp) rx ry rw rh (min vis n) n contentW     overDrop = isFocus && rectNonEmpty (ciField ci) && rectContains dropRect mouse     itemH = menuItemRowH-    -- Hover highlights the row under the pointer (and makes it the Enter-    -- target); it never commits by itself. Rows on screen belong to the-    -- previous frame's window, so the hit test maps through storedWin.+    -- Visible rows come from the previous frame's scroll window, so hit-testing+    -- offsets by storedWin.+    navPointer+      | nav /= 0 = Just mouse+      | wheelDelta /= 0 = Nothing+      | otherwise = mfilter (== mouse) (csNavPointer cs0)     hoverIdx-      | overDrop = (storedWin +) <$> comboDropPickIndex dropRect itemH (min vis n) (v2Y mouse)+      | overDrop && isNothing navPointer = (storedWin +) <$> comboDropPickIndex dropRect itemH (min vis n) (v2Y mouse)       | otherwise = Nothing     hiRaw = fromMaybe hi hoverIdx     -- A hover mapped through a stale window can point past a shrunken list:@@ -205,49 +198,47 @@     -- is looking at when a drag starts).     (_, vSb, hSb, usableW) = comboScrollGeom dropRect n vis storedWin storedX contentW     maxOffX = max 0 (contentW - usableW)-    onVThumb = maybe False (\(_, th) -> rectContains th mouse) vSb-    onVTrack = maybe False (\(t, _) -> rectContains t mouse) vSb-    onHThumb = maybe False (\(_, th) -> rectContains th mouse) hSb-    onHTrack = maybe False (\(t, _) -> rectContains t mouse) hSb-    pressed = isFocus && ciPressed ci-    down = isFocus && ciDown ci+    pressed = isFocus && pressedIn MouseLeft inp+    down = isFocus && heldIn MouseLeft inp+    hitBar = maybe (False, False) (\l -> (rectContains (sbTrack l) mouse, rectContains (sbThumb l) mouse))+    (onVTrack, onVThumb) = hitBar vSb+    (onHTrack, onHThumb) = hitBar hSb     startV = pressed && overDrop && onVTrack     startH = pressed && overDrop && not startV && onHTrack-    vThumbR = maybe (Rect 0 0 0 0) snd vSb-    vTrackR = maybe (Rect 0 0 0 0) fst vSb-    hThumbR = maybe (Rect 0 0 0 0) snd hSb-    hTrackR = maybe (Rect 0 0 0 0) fst hSb-    vGrab = if onVThumb then v2Y mouse - rectY vThumbR else rectH vThumbR / 2-    hGrab = if onHThumb then v2X mouse - rectX hThumbR else rectW hThumbR / 2+    grabOff dir onThumb = maybe 0 $ \l ->+      let Rect tx ty tw th = sbThumb l+       in case dir of+            DirColumn -> if onThumb then v2Y mouse - ty else th / 2+            DirRow -> if onThumb then v2X mouse - tx else tw / 2     drag1       | startV = 1       | startH = 2       | down && drag0 /= 0 = drag0       | otherwise = 0+    dragKind' = if down then drag1 else 0+    -- This frame's grab offset: a track press jumps by the one its drag+    -- goes on with.+    dragOff' | startV = grabOff DirColumn onVThumb vSb | startH = grabOff DirRow onHThumb hSb | otherwise = dragOff0     -- Thumb-anchored drags move from the next frame on; track presses jump     -- the window to the click immediately.-    draggingV = down && drag1 == 1 && ((drag0 == 1 && not startV) || (startV && not onVThumb))-    draggingH = down && drag1 == 2 && ((drag0 == 2 && not startH) || (startH && not onHThumb))-    dragWin = clampWin (round ((v2Y mouse - rectY vTrackR - dragOff0) / max 1 (rectH vTrackR - rectH vThumbR) * fromIntegral (n - vis)))-    dragX = clamp 0 maxOffX ((v2X mouse - rectX hTrackR - dragOff0) / max 1 (rectW hTrackR - rectW hThumbR) * maxOffX)-    wheelRows = round (v2Y (ciScroll ci) * comboBoxRowsPerNotch) :: Int-    wheelDelta = if overDrop then wheelRows else 0-    xWheel = if overDrop then v2X (ciScroll ci) * 20 else 0+    dragging kind started onThumb = down && drag1 == kind && ((drag0 == kind && not started) || (started && not onThumb))+    -- Off the dropdown the wheel scrolls something else, and the carried+    -- fraction is dropped.+    wheelRows = if overDrop then v2Y (inputScroll inp) * comboBoxRowsPerNotch + csWheelRem cs0 else 0+    wheelDelta = truncate wheelRows :: Int+    xWheel = if overDrop then v2X (inputScroll inp) * 20 else 0     win-      | draggingV = dragWin+      | dragging 1 startV onVThumb = maybe 0 (\l -> clampWin (round (scrollOffsetFromThumb DirColumn l dragOff' mouse))) vSb       | nav /= 0 = alignWin (win0 + wheelDelta)       | otherwise = clampWin (win0 + wheelDelta)     xOff-      | draggingH = dragX+      | dragging 2 startH onHThumb = maybe 0 (\l -> scrollOffsetFromThumb DirRow l dragOff' mouse) hSb       | otherwise = clamp 0 maxOffX (storedX + xWheel)-    dragKind' = if down then drag1 else 0-    dragOff' | startV = vGrab | startH = hGrab | otherwise = dragOff0     -- Enter commits only an explicitly highlighted row (hover or Up/Down).-    picked = isFocus && n > 0 && hi' >= 0 && ciEnter ci-    pickedText = case drop (max 0 hi') displayed of-      chosen : _ | hi' >= 0 -> chosen-      _ -> text-    escDismiss = isFocus && ciEscape ci+    picked = isFocus && n > 0 && hi' >= 0 && pressedOnceIn KeyEnter inp+    -- Only read when 'picked', so @hi'@ is a row.+    pickedText = fromMaybe text (listToMaybe (drop hi' displayed))+    escDismiss = isFocus && pressedOnceIn KeyEscape inp     -- Commit points: Enter, a row click (the frame-side pick lands as a     -- frame-start text the widget did not produce), and losing focus (which     -- the blur frame after the focus clear detects). Escape is a cancel: it@@ -264,48 +255,68 @@       | escDismiss = committed0       | otherwise = text --- | Combo box: the 'searchField' with a select-style dropdown of options.--- While the field holds focus, the shared select dropdown overlay lists the--- options filtered by the field text (all of them while it is empty). The+-- | Combo box: the 'NanoUI.searchInput' with a select-style dropdown of options.+-- While the field holds focus, a dropdown popup lists the options filtered+-- by the field text (all of them while it is empty). The -- value is free text: options are suggestions, not a closed set. See--- 'comboStep' for when the value commits. Pass the current text; the result is--- the text after this frame, and 'respChanged' on 'comboBox'' marks a commit.+-- 'comboStep' for when the value commits. The 'Var' is mutated on every edit;+-- @respChanged@ on 'comboBox'' fires only when the user commits a value, not+-- when the application writes one. {-# INLINE comboBox #-}-comboBox :: (Foldable f, Ui :> es) => Text -> f Text -> Text -> Eff es Text-comboBox placeholder options value = snd <$> comboBox' placeholder options value+comboBox :: Foldable f => Text -> f Text -> Var Text -> NanoUI ()+comboBox placeholder options v = void (comboBox' placeholder options v) -comboBox' :: (Foldable f, Ui :> es) => Text -> f Text -> Text -> Eff es (Response, Text)-comboBox' placeholder options value = do+-- | 'comboBox' returning its 'Response'. The first argument is the+-- placeholder.+{-# INLINE comboBox' #-}+comboBox' :: Foldable f => Text -> f Text -> Var Text -> NanoUI Response+comboBox' placeholder options v = bindVar RenderFinal v (comboBoxCore placeholder options)++-- | Load the persisted combo state for @key@, defaulting committed and live+-- text to @value@ and @text@.+loadComboState :: WidgetStore -> Int -> Text -> Text -> ComboState+loadComboState store key value text =+  fromMaybe (ComboState (-1) 0 0 0 0 0 0 value text False Nothing) (lookupSlot fieldCombo key store)++-- | Persist @cs@ for @key@, moving the caret to the end when @picked@ is 'True'.+saveComboState :: Int -> Bool -> ComboState -> WidgetStore -> WidgetStore+saveComboState key picked cs =+  (if picked then setFieldEnd key finalText else id)+    . insertSlot fieldCombo key cs+    . insertSlot fieldText key finalText+  where+    finalText = csLive cs++setFieldEnd :: Int -> Text -> WidgetStore -> WidgetStore+setFieldEnd key t = let len = T.length t in setFieldSelection key len len++comboBoxCore :: Foldable f => Text -> f Text -> Text -> NanoUI (Response, Text)+comboBoxCore placeholder options value = do   (resp, text) <--    buildTextInput textInputFlagSearch searchFieldLayout placeholder value Nothing+    buildTextInput textInputFlagSearch searchInputLayout placeholder value Nothing   ctx <- askContext-  inp <- askInput+  inp <- dropdownInput (rawRespId resp)   let wid = rawRespId resp       key = intKey wid-      keys = inputKeys inp   isFocus <- keyboardFocused wid+  -- A field scrolled out of its viewport hangs no list ('settleDropdowns'), so+  -- no row of it takes the pointer.+  shown <- if isFocus then liftIO (maybe True (isJust . rectIntersect (rawRespRect resp)) <$> getPrevClipRect ctx wid) else pure True   -- The dropdown only shows while the field is focused, so an unfocused   -- combo steps with no rows. The matches stay lazy: the option window below   -- forces only its rows, and the count is forced only on frames that store it.-  let matches = comboFiltered options text-      displayed = if isFocus then matches else []-  store <- uiIO (getStore ctx)-  let cs0 =-        ComboState-          { csHighlight = IM.findWithDefault (-1) (slotKey SlotComboHighlight key) (storeInt store)-          , csWindow = IM.findWithDefault 0 (slotKey SlotComboScroll key) (storeInt store)-          , csScrollX = IM.findWithDefault 0 (slotKey SlotComboScrollX key) (storeFloat store)-          , csContentW = IM.findWithDefault 0 (slotKey SlotComboContentW key) (storeFloat store)-          , csDrag = IM.findWithDefault 0 (slotKey SlotComboDrag key) (storeInt store)-          , csDragOff = IM.findWithDefault 0 (slotKey SlotComboDragOff key) (storeFloat store)-          , csCommitted = IM.findWithDefault value (slotKey SlotComboCommitted key) (storeText store)-          , csLive = IM.findWithDefault text (slotKey SlotComboLive key) (storeText store)-          , csFocused = IM.findWithDefault 0 (slotKey SlotComboFocus key) (storeInt store) /= 0-          }-  contentW <- uiIO $-    if isFocus && not (null displayed)-      then foldM (\widest t -> max widest . fst <$!> ctxMeasureText ctx t) 0 displayed-      else pure (csContentW cs0)+  ComboMatches opts query matches cachedW <- liftIO (comboMatches ctx key options text)+  let displayed = if isFocus then matches else []+  store <- liftIO (getStore ctx)+  let cs0 = loadComboState store key value text+  contentW <- liftIO $+    case cachedW of+      Just w | isFocus -> pure w+      _+        | isFocus && not (null displayed) -> do+            w <- foldM (\widest t -> max widest . fst <$!> ctxMeasureText ctx t) 0 displayed+            w <$ writeDerived comboCache ctx key (ComboMatches opts query matches (Just w))+        | otherwise -> pure (csContentW cs0)   let step =         comboStep           ComboInput@@ -314,53 +325,77 @@             , ciText = text             , ciRows = displayed             , ciContentW = contentW-            , ciField = rawRespRect resp-            , ciMetrics = ctxFontMetrics ctx-            , ciMouse = inputMousePos inp-            , ciPressed = inputMousePressed inp-            , ciDown = inputMouseDown inp-            , ciScroll = inputScroll inp-            , ciKeyUp = KeyUp `elem` keys-            , ciKeyDown = KeyDown `elem` keys-            , ciEnter = KeyEnter `elem` keys-            , ciEscape = KeyEscape `elem` keys+            , ciField = if shown then rawRespRect resp else Rect 0 0 0 0+            , ciInput = inp             }           cs0       cs1 = stepState step       finalText = csLive cs1+      win = csWindow cs1+      rows = take comboBoxMaxVisible (drop win matches)+      nRows = length rows+      nMatches = length matches+      mouse = inputMousePos inp+      size@(Size _ winH) = inputWindowSize inp+      Rect rx ry rw rh = rawRespRect resp+      dropRect = comboDropRect size rx ry rw rh nRows nMatches contentW+      geom r = comboScrollGeom r nMatches comboBoxMaxVisible win (csScrollX cs1) contentW+      onLane = let (_, vSb, hSb, _) = geom dropRect in any (\l -> rectContains (sbTrack l) mouse) (catMaybes [vSb, hSb])+      -- A left press on a row, not on a scrollbar lane, picks it, so that+      -- finishing a thumb drag cannot.+      clickRow+        | isFocus && shown && nRows > 0 && pressedIn MouseLeft inp && rectContains dropRect mouse && not onLane =+            comboDropPickIndex dropRect menuItemRowH nRows (v2Y mouse)+        | otherwise = Nothing   when (isFocus || stepRedraw step) $-    uiIO $ do-      let len = T.length finalText-      modifyStore ctx $ \st ->-        let ints =-              IM.insert (slotKey SlotComboHighlight key) (csHighlight cs1) $-                IM.insert (slotKey SlotComboScroll key) (csWindow cs1) $-                  IM.insert (slotKey SlotComboCount key) (length matches) $-                    IM.insert (slotKey SlotComboFocus key) (boolInt (csFocused cs1)) $-                      IM.insert (slotKey SlotComboDrag key) (csDrag cs1) (storeInt st)-         in st-              { storeInt =-                  if stepPicked step-                    then IM.insert (slotKey SlotCursor key) len (IM.insert (slotKey SlotAnchor key) len ints)-                    else ints-              , storeFloat =-                  IM.insert (slotKey SlotComboScrollX key) (csScrollX cs1) $-                    IM.insert (slotKey SlotComboContentW key) (csContentW cs1) $-                      IM.insert (slotKey SlotComboDragOff key) (csDragOff cs1) (storeFloat st)-              , storeText =-                  IM.insert (slotKey SlotComboLive key) finalText $-                    IM.insert (slotKey SlotComboCommitted key) (csCommitted cs1) $-                      IM.insert key finalText (storeText st)-              }+    liftIO $ do+      modifyStore ctx (saveComboState key (stepPicked step) cs1)       when (stepDismissed step) $ do         writeIORef (ctxFocusId ctx) (WidgetId 0)         markEscapeConsumed ctx       when (stepRedraw step) $ markDirty ctx-  -- The dropdown overlay reads its rows from the node's option list: the-  -- visible window of the filtered list. Unfocused combos set it too, since a-  -- click that focuses the field this frame shows the dropdown this frame.-  uiIO $ do-    findNodeByWidgetId ctx wid-      >>= mapM_ (\idx -> setOptions (ctxNodeArena ctx) idx (take comboBoxMaxVisible (drop (csWindow cs1) matches)))-    recordStoreText ctx key finalText-  pure (setChanged (isJust (stepCommit step)) resp, finalText)+  -- A pick puts the row's text in the field and takes focus away, which+  -- closes the dropdown; the next frame finds a text the combo did not+  -- produce, and commits it.+  liftIO . forM_ clickRow $ \i -> do+    let picked = fromMaybe "" (listToMaybe (drop i rows))+    modifyStore ctx (insertSlot fieldText key picked . setFieldEnd key picked)+    writeIORef (ctxFocusId ctx) (WidgetId 0)+    markDirty ctx+  -- The dropdown's text spans read its rows from the node's option list: the+  -- visible window of the filtered list.+  liftIO $ do+    findNodeByWidgetId ctx wid >>= mapM_ (\idx -> setOptions (ctxNodeArena ctx) idx rows)+    recordSlot fieldText ctx key finalText+  -- Focus moves after the view, so a press that focuses the field shows the+  -- dropdown in its own frame here.+  let focusing = not isFocus && pressedIn MouseLeft inp && respPressed resp+  when ((isFocus || focusing) && shown && nRows > 0) $ do+    let dp = DropdownPopup wid (csHighlight cs1 - win) True (csScrollX cs1)+        drag = csDrag cs1+        -- As a scroller's bar: brighter under the pointer or while dragged.+        hot kind l = drag == kind || drag == 0 && onScrollBar mouse l+    void . dropdownPopup wid dp (rectH dropRect) $ \_ dropR ->+      let+        (_, vSb, hSb, _) = geom dropR+        hovered = if rectContains dropR mouse then comboDropPickIndex dropR menuItemRowH nRows (v2Y mouse) else Nothing+        content = hash ((win, dpPicked dp, hovered, csScrollX cs1, drag), (hot 1 <$> vSb, hot 2 <$> hSb, contentW, nMatches, hash rows))+        build cdc rect =+          let+            (inner, vBar, hBar, _) = geom rect+            theme = cdcTheme cdc+            base = themeInput theme+            bar kind l = do+              drawRect (sbTrack l) (scrollBarTrackColor base theme)+              drawRoundedRect (sbThumb l) 3 ((if hot kind l then scrollBarThumbHoverColor else scrollBarThumbColor) base theme)+           in+            runCanvasFor cdc $ do+              withClip inner (paintDropdownRows cdc (dropdownPopupRows (cdcFont cdc) theme winH mouse dp rows rect))+              mapM_ (bar 1) vBar+              mapM_ (bar 2) hBar+       in ((), content, build)+  -- A value the application wrote reaches the field as a text the combo did+  -- not produce, as a row click does, and becomes the committed value; but+  -- it is not the user's commit.+  let appWrote = value /= csLive cs0 && stepCommit step == Just value+  pure (setChanged (isJust (stepCommit step) && not appWrote) resp, finalText)
lib/NanoUI/Widgets/Custom.hs view
@@ -1,28 +1,66 @@-{-# LANGUAGE OverloadedStrings #-}- -- | Custom widgets and the reference widgets built on them. --+-- The widgets provided in this module ('knob', 'toggleSwitch', 'circularProgress',+-- 'progressBar', 'spinner', 'sparkline') serve as reference implementations for+-- custom widgets that users may want to implement themselves. This API is meant+-- to accompany the canvas API ('CanvasM', 'customWidget', 'customWidgetWithId'),+-- demonstrating how 2D vector drawing, layout sizing, gesture hooks ('useDrag2DOn',+-- 'useWheelDeltaOn'), keyboard navigation, and responsive state binding ('bindVar')+-- integrate into cohesive, interactive controls.+-- -- 'customWidget' takes a 'CustomWidgetSpec': a layout, optional measurement,--- drawing that sees hover and press state, an optional content key, a cursor,--- and damage slop.--- 'canvas' is the short form for drawing into a laid-out rectangle with--- 'CanvasM'. 'useDrag2D' and 'useWheelDelta' are gesture hooks for your own--- controls; 'knob' and 'toggleSwitch' show how they fit together.+-- a draw function receiving hover and press state, an optional content key, a+-- cursor, and damage slop.+-- 'canvas' is the short form: it draws into a laid-out rectangle with+-- 'CanvasM' (rects, circles, lines, images, text, "NanoUI.Path" paths, clips+-- and transforms). 'canvasConfigured' adds a content key, a cursor and+-- pointer tracking; 'drawContext' reads the hover, press, and theme state+-- inside 'CanvasM'.+-- 'useDrag2DOn' and 'useWheelDeltaOn' are gesture hooks that take the+-- widget's 'Response'; 'knob' and 'toggleSwitch' show them in use. Each+-- reference widget follows the ordinary @x@, @x'@, @xWith@ and @xWith'@+-- convention: a prime adds the 'Response', and @With@ accepts layout and size. module NanoUI.Widgets.Custom   ( -- * Custom widgets-    CustomWidgetSpec (..)++    -- ** On a Var++    -- | 'bindVar' adapts a pure @a -> NanoUI (Response, a)@ widget to mutate a+    -- 'Var' in place.+    Binding (..)+  , bindVar+  , bindVarBy++    -- ** Specs+  , CustomWidgetSpec (..)+  , KeyClaim (..)   , defaultCustomWidgetSpec   , customWidget   , customWidgetWithId   , contentKey+  , contentKeyOf+  , KeyPart+  , keyPart   , CustomDrawContext (..)   , CustomMeasureFn   , CustomDrawBuild-  , mkCustomDrawContext+  , DrawOp (..)+  , DrawingBuild+  , shiftDrawOp+  , drawing+  , drawingVersioned+  , drawingCached+  , setChanged+  , setClicked+  , setSubmitted     -- * Canvas   , CanvasM-  , runCanvas   , canvas+  , CanvasConfig (..)+  , defaultCanvasConfig+  , canvasConfigured+  , runCanvasFor+  , drawContext   , drawRect   , drawRoundedRect   , drawCircle@@ -35,11 +73,30 @@   , drawLinearGradientV   , drawImage   , drawImageUV+  , ImageDraw (..)+  , imageDraw+  , drawImageWith   , drawText+  , drawTextWith+  , drawTextClipped+  , drawTextClippedWith+  , drawCheckbox+  , checkboxBoxSize+    -- * Paths, clips and transforms++    -- | Build a path with "NanoUI.Path", imported qualified, and fill or+    -- stroke it here, in a colour or a 'NanoUI.Path.Paint'. 'withTransform'+    -- moves, turns and scales what a block draws, and 'withClip' clips it.+  , drawPath+  , drawPathWith+  , drawStrokePath+  , drawStrokePathWith+  , withTransform+  , withClip     -- * Gestures-  , useDrag2D+  , useDrag2DOn   , Drag2D (..)-  , useWheelDelta+  , useWheelDeltaOn     -- * Reference widgets   , knob   , knob'@@ -67,180 +124,35 @@   , sparklineWith'   ) where -import Control.Monad (forM_, void, when)-import Data.IORef (readIORef)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)+import Control.Monad (void, when) import Data.Text qualified as T-import Data.Primitive.SmallArray (SmallArray, emptySmallArray, smallArrayFromList)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , CustomDrawBuild-  , CustomDrawContext (..)-  , CustomMeasureFn-  , adoptStoreFloat-  , adoptStoreInt-  , getFocusId-  , getHotId-  , getStore-  , intKey-  , isDisabled-  , recordStoreFloat-  , recordStoreInt-  , registerCustomCursor-  , registerCustomDamageSlop-  , registerCustomDrawing-  , registerCustomMeasure-  , registerFocusable-  , writeStoreBool-  , writeStoreFloat-  , widgetTheme-  , modifyStore-  , getMenuPointerGesture-  )-import NanoUI.Draw (DrawOp (..))-import NanoUI.Font (FontMetrics)+import Data.Primitive.SmallArray (emptySmallArray)+import NanoUI.Internal.Canvas+import NanoUI.Internal.Context+import NanoUI.Internal.Draw (DrawOp (..), DrawingBuild, shiftDrawOp)+import NanoUI.Internal.Widgets.Drawing (drawing, drawingCached, drawingVersioned)+import Data.Word (Word64)+import Data.Hashable (Hashable, hash) import GHC.Float (castFloatToWord32)-import NanoUI.Id (WidgetId, mix64)-import NanoUI.Input-  ( Input (..)-  , UiCursorKind (..)-  , inputMouseDown-  , inputMousePos-  , inputMousePressed-  , inputScroll-  )-import NanoUI.Layout.Arena (NodeType (NodeDrawing))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, uiTime)-import NanoUI.Store (WidgetStore (..), boolInt, intBool, Slot (..), slotKey)-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Layout-  , defaultLayout-  , fillW-  , fixedH-  , fixedWH-  , styleActiveBg-  , styleBg-  , styleBorder-  , styleHoverBg-  , themeAccent-  , themeButton-  , themePanel-  , themeOnAccent-  , fadeAlpha-  )-import NanoUI.Types-  ( Color-  , ImageId (..)-  , Rect (..)-  , V2 (..)-  , clamp-  , clamp01-  , defaultDamageSlop-  , rectContains-  , v2X-  , v2Y-  )-import NanoUI.Widgets.Behavior (KeyNav (..), keyActivated, useKeyNav)-import NanoUI.Widgets.Node-  ( Response-  , addWidget-  , respClicked-  , respHovered-  , respPressed-  , respRect-  , setChanged-  )-import NanoUI.Widgets.Animate (keepAnimating)---- -------------------------------------------------------------------------------- Canvas Monad--- --------------------------------------------------------------------------------- | Monadic canvas builder that collects 'DrawOp' vector operations efficiently.-newtype CanvasM a = CanvasM { runCanvasM :: ([DrawOp] -> [DrawOp]) -> (a, [DrawOp] -> [DrawOp]) }--instance Functor CanvasM where-  fmap f (CanvasM m) = CanvasM $ \s ->-    case m s of (a, s') -> (f a, s')--instance Applicative CanvasM where-  pure a = CanvasM $ \s -> (a, s)-  CanvasM mf <*> CanvasM mx = CanvasM $ \s ->-    case mf s of-      (f, s1) -> case mx s1 of-        (x, s2) -> (f x, s2)--instance Monad CanvasM where-  CanvasM m >>= f = CanvasM $ \s ->-    case m s of (a, s') -> runCanvasM (f a) s'---- | Compile a 'CanvasM' block into an immutable 'SmallArray DrawOp'.-runCanvas :: CanvasM a -> SmallArray DrawOp-runCanvas (CanvasM m) =-  let (_, diff) = m id-   in smallArrayFromList (diff [])--emitOp :: DrawOp -> CanvasM ()-emitOp op = CanvasM $ \diff -> ((), diff . (op :))---- | Fill a solid rectangle.-drawRect :: Rect -> Color -> CanvasM ()-drawRect r c = emitOp (FillRect r c)---- | Fill a rounded rectangle with given corner radius.-drawRoundedRect :: Rect -> Float -> Color -> CanvasM ()-drawRoundedRect r radius c = emitOp (FillRoundedRect r radius c)---- | Fill a solid circle at center with given radius.-drawCircle :: V2 -> Float -> Color -> CanvasM ()-drawCircle (V2 cx cy) radius c = emitOp (FillCircle cx cy radius c)---- | Stroke a straight segment between two points with thickness.-drawStroke :: V2 -> V2 -> Float -> Color -> CanvasM ()-drawStroke (V2 x0 y0) (V2 x1 y1) thickness c = emitOp (Stroke x0 y0 x1 y1 thickness c)---- | Stroke a rounded rectangle border with given radius and stroke width.-drawStrokeRoundedRect :: Rect -> Float -> Float -> Color -> CanvasM ()-drawStrokeRoundedRect r radius thickness c = emitOp (StrokeRoundedRect r radius thickness c)---- | Stroke a circular outline at center with given radius and stroke width.-drawStrokeCircle :: V2 -> Float -> Float -> Color -> CanvasM ()-drawStrokeCircle (V2 cx cy) radius thickness c = emitOp (StrokeCircle cx cy radius thickness c)---- | Antialiased smooth stroke line between two points.-drawStrokeAA :: V2 -> V2 -> Float -> Color -> CanvasM ()-drawStrokeAA (V2 x0 y0) (V2 x1 y1) thickness c = emitOp (StrokeLineAA x0 y0 x1 y1 thickness c)---- | Four-corner bilinear gradient fill (top-left, top-right, bottom-right, bottom-left).-drawQuadGradient :: Rect -> Color -> Color -> Color -> Color -> CanvasM ()-drawQuadGradient r tl tr br bl = emitOp (FillQuadGradient r tl tr br bl)---- | Horizontal 2-color linear gradient fill (left to right).-drawLinearGradientH :: Rect -> Color -> Color -> CanvasM ()-drawLinearGradientH r leftCol rightCol = emitOp (FillQuadGradient r leftCol rightCol rightCol leftCol)---- | Vertical 2-color linear gradient fill (top to bottom).-drawLinearGradientV :: Rect -> Color -> Color -> CanvasM ()-drawLinearGradientV r topCol botCol = emitOp (FillQuadGradient r topCol topCol botCol botCol)---- | Draw a textured image stretched over given rectangle.-drawImage :: Rect -> ImageId -> Color -> CanvasM ()-drawImage r (ImageId tid) c = emitOp (DrawImageRect r tid 0 0 1 1 c)---- | Draw a sub-region of a textured image with explicit UV texture coordinates.-drawImageUV :: Rect -> ImageId -> Float -> Float -> Float -> Float -> Color -> CanvasM ()-drawImageUV r (ImageId tid) u0 v0 u1 v1 c = emitOp (DrawImageRect r tid u0 v0 u1 v1 c)---- | Draw text positioned at a reference point with horizontal and vertical alignment.-drawText :: V2 -> AlignX -> AlignY -> Text -> Color -> CanvasM ()-drawText (V2 x y) alignX alignY txt col =-  let ax = case alignX of AlignStart -> 0; AlignCenter -> 0.5; AlignEnd -> 1-      ay = case alignY of AlignTop -> 1; AlignMiddle -> 0.5; AlignBottom -> 0; AlignBaseline -> -1-   in emitOp (DrawText x y ax ay txt col)+import NanoUI.Internal.Font (checkboxBoxSize)+import NanoUI.Internal.Id (WidgetId, mix64)+import NanoUI.Internal.Input+import NanoUI.Internal.Layout.Arena (NodeType (NodeDrawing))+import NanoUI.Internal.Monad (NanoUI, askContext, askInput, freshWidget, nextId, liftIO, uiTime, withContext)+import NanoUI.Path qualified as P+import NanoUI.Internal.Store+import NanoUI.Internal.Store.Slots (slotDragPoint, slotDragPress)+import NanoUI.Internal.Style+import NanoUI.Internal.Types+import NanoUI.Internal.Var (Binding (..), bindVar, bindVarBy)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Widgets.Behavior (dragPressLive, leftPress, navStep, useKeyNav)+import NanoUI.Internal.Widgets.Combinators (finishInput, finishToggle, widgetBaseLayout)+import NanoUI.Internal.Widgets.Node+import NanoUI.Internal.Widgets.Animate (wakeAfter)+import NanoUI.Internal.Sensor.Types (Watch (..))+import NanoUI.Internal.Widgets.Sensor (Visibility (..), defaultSensorConfig, watchSensor)+import NanoUI.Internal.Widgets.Custom (customDrawContext)  -- ----------------------------------------------------------------------------- -- Custom Widget Specification@@ -248,123 +160,170 @@  -- | Complete specification for defining a custom widget. data CustomWidgetSpec a = CustomWidgetSpec-  { widgetLayout     :: !Layout-    -- ^ Flex layout constraints (width/height sizing, min/max, alignment, padding).+  { widgetLayout     :: !LayoutModifier+    -- ^ Flex layout modifier applied on top of 'defaultLayout' (with inherited+    -- font defaults): for example, @fixedWH 120 24@.   , widgetMeasure    :: !(Maybe CustomMeasureFn)     -- ^ Optional intrinsic measurement hook for 'Fit' or dynamic sizing.   , widgetDraw       :: !CustomDrawBuild     -- ^ Vector drawing procedure receiving interaction context and layout rect.   , widgetContent    :: !Int     -- ^ Content key: a number that changes whenever 'widgetDraw' would draw-    -- something different from the state it reads (a value, a flag, a model-    -- revision; 'contentKey' hashes numbers into one). A frame whose key,-    -- size, interaction state and metrics are unchanged neither rebuilds the-    -- ops nor repaints the widget (a widget that only moved has its ops-    -- translated), so key a drawing whose ops are expensive to build. The default 0 means no key: the ops are rebuilt every frame and-    -- compared, which repaints correctly whatever the drawing reads but pays-    -- for the rebuild. A stale key draws stale pixels, so derive it from-    -- everything the drawing reads, an animated value included: a key is-    -- believed while the widget animates, as a versioned drawing's version is.-  , widgetCursor     :: !(Maybe (CustomDrawContext -> UiCursorKind))-    -- ^ Optional custom mouse cursor when pointer is over the widget.+    -- something different ('contentKey' hashes numbers into one). If the key,+    -- size, interaction state and metrics are unchanged, the frame skips+    -- rebuilding the ops and repainting. The default 0 means no key: ops are+    -- rebuilt and compared every frame. A stale key draws stale pixels, so+    -- derive it from everything the drawing reads. The key is trusted even+    -- while the widget animates.+  , widgetCursor     :: !(Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind))+    -- ^ Pointer shape over the widget, given the draw context, the widget's+    -- rect and the pointer position, so different parts can show different+    -- shapes. It is also queried during a drag that started on the widget,+    -- so the drag keeps its shape. 'UiCursorDefault' defers to an enclosing+    -- 'NanoUI.withCursorShape', or the arrow.+    --+    -- > widgetCursor = Just $ \_ (Rect x _ w _) (V2 px _) ->+    -- >   if px > x + w - 6 then UiCursorEwResize else UiCursorDefault   , widgetFocusable  :: !Bool     -- ^ Whether this widget accepts tab/keyboard focus.+  , widgetKeys       :: !KeyClaim+    -- ^ Keys the widget handles itself while focused; shortcuts and+    -- 'NanoUI.keyPressed' ignore them. Default 'KeysNavigate'. A terminal or+    -- an editor with its own chords uses 'KeysAll'. A widget that claims Tab+    -- ('KeysAll', or 'KeysOnly' naming it) keeps focus when it is pressed.+    -- Use 'KeysOnly' with "NanoUI.Shortcut" chords for precise ownership,+    -- 'KeysNone' to reserve none, or 'KeysReadOnly' for selectable text.   , widgetDamageSlop :: !Float     -- ^ Padding added to dirty rectangles (for shadows, glow, or drag handles).+  , widgetTrackPointer :: !Bool+    -- ^ Run a frame on every pointer move over the widget, for drawings that+    -- depend on the pointer position. Default 'False': a move runs a frame+    -- only when it crosses onto another widget.   , widgetInteract   :: !(Response -> CustomDrawContext -> Input -> (Response, a))-    -- ^ Interaction hook. It receives the widget's resolved 'Response' (hover,-    -- press, right-click, and clicks including one queued from a previous-    -- frame), the draw context and the input, and returns the final response-    -- and value.+    -- ^ Interaction hook: maps the resolved 'Response', draw context and+    -- input to the final response and value.   }  -- | Default configuration for a custom widget with standard hover/press/click behavior. defaultCustomWidgetSpec :: CustomWidgetSpec () defaultCustomWidgetSpec = CustomWidgetSpec-  { widgetLayout     = defaultLayout+  { widgetLayout     = id   , widgetMeasure    = Nothing   , widgetDraw       = \_ _ -> emptySmallArray   , widgetContent    = 0   , widgetCursor     = Nothing   , widgetFocusable  = False+  , widgetKeys       = KeysNavigate   , widgetDamageSlop = defaultDamageSlop+  , widgetTrackPointer = False   , widgetInteract   = \resp _ _ -> (resp, ())   } +fixedSizeSpec :: (Layout -> Layout) -> Float -> Float -> CustomWidgetSpec ()+fixedSizeSpec f w h =+  defaultCustomWidgetSpec {widgetLayout = fixedWH w h . f, widgetMeasure = Just $ \_ _ -> (w, h)}+ -- | A 'widgetContent' key for a drawing whose output follows these numbers. -- Pass every value the drawing reads; @0@ means "no key", so a hash that lands -- there becomes 1. {-# INLINE contentKey #-} contentKey :: [Float] -> Int-contentKey vs =-  let raw = foldl' (\acc v -> mix64 acc (fromIntegral (castFloatToWord32 v))) 0x9E3779B97F4A7C15 vs+contentKey vs = contentKeyOf [KeyPart (fromIntegral (castFloatToWord32 v)) | v <- vs]++-- | A 'widgetContent' key over 'Hashable' values, mixed in order. Unlike+-- 'contentKey', an 'Int' or 'Double' is hashed whole, not rounded to 'Float'.+--+-- > widgetContent = contentKeyOf [keyPart version, keyPart scrollY, keyPart query, keyPart selected]+{-# INLINE contentKeyOf #-}+contentKeyOf :: [KeyPart] -> Int+contentKeyOf parts =+  let raw = foldl' (\acc (KeyPart v) -> mix64 acc v) 0x9E3779B97F4A7C15 parts       k = fromIntegral raw    in if k == 0 then 1 else k --- | Build the draw context a custom widget sees, resolving hover/press/focus--- state for @wid@ from the ambient context. One policy for state masking.-mkCustomDrawContext :: Context -> FontMetrics -> WidgetId -> IO CustomDrawContext-mkCustomDrawContext ctx fm wid = do-  hot <- getHotId ctx-  active <- readIORef (ctxActiveId ctx)-  customDrawContext ctx fm wid (hot == wid) (active == wid)+-- | One value of a 'contentKeyOf' key, made by 'keyPart'.+newtype KeyPart = KeyPart Word64 --- | Draw context for @wid@ with the given hover and press state; a disabled--- widget is never hovered or pressed.-customDrawContext :: Context -> FontMetrics -> WidgetId -> Bool -> Bool -> IO CustomDrawContext-customDrawContext ctx fm wid hovered pressed = do-  disabled <- isDisabled ctx wid-  focused <- (== wid) <$> getFocusId ctx-  active <- readIORef (ctxActiveId ctx)-  theme <- widgetTheme ctx wid-  pure-    CustomDrawContext-      { cdcHovered = hovered && not disabled-      , cdcPressed = pressed && not disabled-      , cdcFocused = focused-      , cdcActive = active == wid-      , cdcDisabled = disabled-      , cdcTheme = theme-      , cdcFont = fm-      }+-- | Wrap any 'Hashable' value (including lists, 'Maybe', tuples, or custom+-- types deriving 'Hashable') for 'contentKeyOf'.+{-# INLINE keyPart #-}+keyPart :: Hashable a => a -> KeyPart+keyPart = KeyPart . fromIntegral . hash  -- | Instantiates a custom widget using an existing 'WidgetId'.-customWidgetWithId :: (Ui :> es) => WidgetId -> CustomWidgetSpec a -> Eff es (Response, a)+customWidgetWithId :: WidgetId -> CustomWidgetSpec a -> NanoUI (Response, a) customWidgetWithId wid spec = do   ctx <- askContext   inp <- askInput-  uiIO $ do-    when (widgetFocusable spec) $ registerFocusable ctx wid-    mapM_ (registerCustomMeasure ctx wid) (widgetMeasure spec)-    registerCustomDrawing ctx wid (widgetContent spec) (widgetDraw spec)-    mapM_ (registerCustomCursor ctx wid) (widgetCursor spec)-    when (widgetDamageSlop spec > 0) $-      registerCustomDamageSlop ctx wid (widgetDamageSlop spec)-  resp0 <- addWidget wid NodeDrawing T.empty 0 (widgetLayout spec)-  cdc <- uiIO (customDrawContext ctx (ctxFontMetrics ctx) wid (respHovered resp0) (respPressed resp0))+  lay <- widgetBaseLayout defaultLayout (widgetLayout spec)+  when (widgetFocusable spec) $ liftIO (registerFocusable ctx wid)+  resp0 <- addWidget wid NodeDrawing T.empty 0 lay+  -- Registered on the node just added ('NanoUI.Internal.Context.ctxNodeCustom').+  cdc <- liftIO $ do+    case widgetMeasure spec of+      Just fn -> registerCustomMeasure ctx wid fn+      Nothing -> pure ()+    registerCustomEntry ctx wid (specEntry spec)+    customDrawContext ctx (ctxFontMetrics ctx) wid (respHovered resp0) (respPressed resp0)   pure (widgetInteract spec resp0 cdc inp)  -- | Instantiates a custom widget from a 'CustomWidgetSpec'.------ Connects the widget into:--- - The two-pass layout arena (respecting 'widgetMeasure' or layout constraints).--- - Off-heap vector drawing pipeline. Without a 'widgetContent' key the draw---   function runs once a frame and the widget repaints when its ops change, so---   it may read anything; with one, an unchanged key skips both.--- - Interactive hit-testing, focus management, and custom cursor resolution.--- - Accurate damage region tracking with 'widgetDamageSlop'.-customWidget :: (Ui :> es) => CustomWidgetSpec a -> Eff es (Response, a)-customWidget spec = do-  wid <- nextId-  customWidgetWithId wid spec+customWidget :: CustomWidgetSpec a -> NanoUI (Response, a)+customWidget spec = nextId >>= (`customWidgetWithId` spec) --- | Draw into a rectangle sized by the layout modifier. Use 'customWidget'--- when the drawing needs hover or press state.-canvas :: (Ui :> es) => (Layout -> Layout) -> (Rect -> CanvasM ()) -> Eff es Response-canvas f drawAction =+-- | Draw into a rectangle sized by the layout modifier. Curves are flattened+-- for the current display ('runCanvasFor'). Ops are rebuilt and compared+-- every frame; use 'canvasConfigured' for a content key or a cursor.+canvas :: LayoutModifier -> (Rect -> CanvasM ()) -> NanoUI Response+canvas f = canvasConfigured defaultCanvasConfig {canvasLayout = f}++-- | Options for 'canvasConfigured'.+data CanvasConfig = CanvasConfig+  { canvasLayout :: !LayoutModifier+    -- ^ Layout modifier applied on top of 'defaultLayout' (default 'id').+  , canvasContent :: !Int+    -- ^ As 'widgetContent'; build it with 'contentKey' or 'contentKeyOf'.+    -- Default 0 (no key): the drawing runs every frame.+  , canvasTrackPointer :: !Bool+    -- ^ As 'widgetTrackPointer' (default 'False').+  , canvasCursor :: !(Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind))+    -- ^ As 'widgetCursor' (default 'Nothing').+  , canvasFocusable :: !Bool+    -- ^ As 'widgetFocusable' (default 'False'): a Tab stop, focused by a+    -- press too, with the focus ring Tab draws. Read its keys with+    -- 'NanoUI.focusedKeyPressed' or 'NanoUI.useKeyNav' on the response's id.+  , canvasKeys :: !KeyClaim+    -- ^ As 'widgetKeys' (default 'KeysNavigate').+  }++-- | Default layout modifier ('id'), with no content key, cursor or pointer tracking.+defaultCanvasConfig :: CanvasConfig+defaultCanvasConfig =+  CanvasConfig+    { canvasLayout = id+    , canvasContent = 0+    , canvasTrackPointer = False+    , canvasCursor = Nothing+    , canvasFocusable = False+    , canvasKeys = KeysNavigate+    }++-- | 'canvas' with a 'CanvasConfig'. The drawing reads hover, press state and+-- theme with 'drawContext':+--+-- > canvasConfigured defaultCanvasConfig {canvasLayout = fixedWH 120 24, canvasContent = contentKey [level]} $ \r -> do+-- >   cdc <- drawContext+-- >   drawRoundedRect r 4 (if cdcHovered cdc then themeAccent (cdcTheme cdc) else themeMuted (cdcTheme cdc))+canvasConfigured :: CanvasConfig -> (Rect -> CanvasM ()) -> NanoUI Response+canvasConfigured cfg drawAction =   fst <$> customWidget defaultCustomWidgetSpec-    { widgetLayout = f defaultLayout-    , widgetDraw   = \_ rect -> runCanvas (drawAction rect)+    { widgetLayout = canvasLayout cfg+    , widgetContent = canvasContent cfg+    , widgetTrackPointer = canvasTrackPointer cfg+    , widgetCursor = canvasCursor cfg+    , widgetFocusable = canvasFocusable cfg+    , widgetKeys = canvasKeys cfg+    , widgetDraw = \cdc rect -> runCanvasFor cdc (drawAction rect)     }  -- -----------------------------------------------------------------------------@@ -382,240 +341,240 @@   }   deriving (Eq, Show) --- | Tracks pointer dragging across a 2D area (e.g. for color pickers, joysticks, canvas panning).-useDrag2D ::-  (Ui :> es) =>-  Rect ->-  Eff es Drag2D-useDrag2D bounds = do-  wid <- nextId-  ctx <- askContext+-- | A left-button drag that starts with a press on the widget and lasts+-- until release, wherever the pointer goes. For colour pickers, joysticks or+-- panned canvases. The position is clamped to the widget's rect. Only the+-- widget's own press ('respPressed') starts a drag, so nothing starts when+-- the press lands on an overlay, a scrolled-off part, or a disabled widget.+-- Call it every frame, after the widget:+--+-- > (resp, ()) <- customWidget spec+-- > drag <- useDrag2DOn resp+-- > when (dragActive drag) (setPan (dragPosition drag))+useDrag2DOn :: HasResponse r => r -> NanoUI Drag2D+useDrag2DOn r = do+  (wid, ctx) <- freshWidget   inp <- askInput-  -- The drag flag lives in 'storeInt' and the last pointer position in-  -- 'storePoint', both under the widget's drag slot.-  let dragK = slotKey SlotDrag (intKey wid)+  -- The press that started the drag is quiet bookkeeping (it causes no+  -- damage); the last pointer position goes in a point slot. As in+  -- 'useDrag1D', the drag lasts only under that press, so one released while+  -- this hook did not run does not come back.+  let bounds = respRect r+      key = intKey wid       mouse = inputMousePos inp-  store <- uiIO (getStore ctx)-  -- A press that belongs to an open menu's pointer gesture drags nothing.-  gesture <- uiIO (getMenuPointerGesture ctx)-  let active0 = IM.findWithDefault 0 dragK (storeInt store) /= 0-      active = inputMouseDown inp && not gesture && (active0 || (inputMousePressed inp && rectContains bounds mouse))-      (prevX, prevY) = IM.findWithDefault (v2X mouse, v2Y mouse) dragK (storePoint store)-      delta =-        if active && active0-          then V2 (v2X mouse - prevX) (v2Y mouse - prevY)-          else V2 0 0+  store <- liftIO (getStore ctx)+  let held = findSpec slotDragPress 0 key store+  active0 <- liftIO (dragPressLive ctx key store)+  let active = heldIn MouseLeft inp && (active0 || (pressedIn MouseLeft inp && respPressed r))+      prev = findSpec slotDragPoint mouse key store+      delta = if active && active0 then v2Sub mouse prev else V2 0 0       clampedMouse =         V2           (clamp (rectX bounds) (rectX bounds + rectW bounds) (v2X mouse))           (clamp (rectY bounds) (rectY bounds + rectH bounds) (v2Y mouse))-  when (active || active0) $-    uiIO $-      modifyStore ctx $ \st ->-        if active-          then-            st-              { storeInt = IM.insert dragK 1 (storeInt st)-              , storePoint = IM.insert dragK (v2X mouse, v2Y mouse) (storePoint st)-              }-          else-            st-              { storeInt = IM.delete dragK (storeInt st)-              , storePoint = IM.delete dragK (storePoint st)-              }-  pure Drag2D { dragPosition = clampedMouse, dragActive = active, dragDelta = delta }+  when (active || held /= 0) . liftIO $ do+    press <- if active && not active0 then leftPress ctx else pure held+    modifyStore ctx $+      if active+        then insertSpec slotDragPress key press . insertSpec slotDragPoint key mouse+        else deleteSpec slotDragPress key . deleteSpec slotDragPoint key+  pure Drag2D {dragPosition = clampedMouse, dragActive = active, dragDelta = delta} --- | Inspects mouse wheel scroll delta when pointer is hovering over bounds.-useWheelDelta :: (Ui :> es) => Rect -> Eff es (Float, Float)-useWheelDelta bounds = do-  inp <- askInput-  let mouse = inputMousePos inp-  if rectContains bounds mouse-    then pure (v2X (inputScroll inp), v2Y (inputScroll inp))-    else pure (0, 0)+-- | This frame's wheel delta while the widget is hovered ('respHovered').+-- Returns @(0, 0)@ when covered by an overlay, clipped out of view, or disabled.+-- The widget does not take the wheel from a scroller around it: one that can+-- still scroll that way moves by the same notches on the same frame.+useWheelDeltaOn :: HasResponse r => r -> NanoUI (Float, Float)+useWheelDeltaOn r = do+  V2 x y <- inputScroll <$> askInput+  pure (if respHovered r then (x, y) else (0, 0))  -- ----------------------------------------------------------------------------- -- Reference Custom Widgets -- ----------------------------------------------------------------------------- --- | Rotary knob over @[minV, maxV]@, 36 px across. Drag vertically, scroll,--- or use the arrow keys. Pass the current value; the result is the value--- after this frame.+-- | Rotary knob over @[minV, maxV]@ (36 px diameter) backed by a 'Var'.+-- Supports vertical drag, scroll wheel, and arrow keys. In a scroller that+-- can still scroll, the wheel turns the knob and scrolls too+-- ('useWheelDeltaOn'). {-# INLINE knob #-}-knob :: Ui :> es => Float -> Float -> Float -> Eff es Float-knob minV maxV value = snd <$> knobWith' id 36 minV maxV value+knob :: Float -> Float -> Var Float -> NanoUI ()+knob minV maxV v = void (knobWith' id 36 minV maxV v) +-- | 'knob' returning its response. {-# INLINE knob' #-}-knob' :: Ui :> es => Float -> Float -> Float -> Eff es (Response, Float)+knob' :: Float -> Float -> Var Float -> NanoUI Response knob' = knobWith' id 36 --- | 'knob' with a layout modifier and a diameter in pixels.+-- | 'knob' with a layout modifier and diameter. {-# INLINE knobWith #-}-knobWith :: Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Float -> Eff es Float-knobWith f diameter minV maxV value = snd <$> knobWith' f diameter minV maxV value+knobWith :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI ()+knobWith f diameter lo hi v = void (knobWith' f diameter lo hi v) -knobWith' ::-  Ui :> es =>-  (Layout -> Layout) -> Float -> Float -> Float -> Float -> Eff es (Response, Float)-knobWith' f diameter minV maxV value = do-  wid <- nextId-  ctx <- askContext-  let key = intKey wid-  current <- uiIO $ adoptStoreFloat ctx wid key value-  let range = maxV - minV-      frac = if range > 0 then clamp01 ((current - minV) / range) else 0-  (resp, ()) <- customWidgetWithId wid defaultCustomWidgetSpec-    { widgetLayout = fixedWH diameter diameter (f defaultLayout)-    , widgetMeasure = Just $ \_ _ -> (diameter, diameter)-    , widgetCursor = Just (\_ -> UiCursorNsResize)-    , widgetFocusable = True-    , widgetContent = contentKey [frac]-    , widgetDraw = \cdc (Rect x y w h) -> runCanvas $ do-        let cx = x + w / 2-            cy = y + h / 2-            r = min (w / 2) (h / 2) - 2-            theme = cdcTheme cdc-            hover = cdcHovered cdc-            pressed = cdcPressed cdc-            bgCol =-              if pressed-                then styleActiveBg (themeButton theme)-                else if hover-                  then styleHoverBg (themeButton theme)-                  else styleBg (themeButton theme)-            accent = themeAccent theme-            borderCol = styleBorder (themeButton theme)-            angle = (135 + frac * 270) * (pi / 180)-            ix = cx + cos angle * (r * 0.75)-            iy = cy + sin angle * (r * 0.75)-        drawCircle (V2 cx cy) r bgCol-        drawStrokeCircle (V2 cx cy) r 1.5 borderCol-        drawStrokeAA (V2 cx cy) (V2 ix iy) 2.5 accent-    }-  let bounds = respRect resp-  drag <- useDrag2D bounds-  (_scrollX, scrollY) <- useWheelDelta bounds+-- | 'knob' with a layout modifier and a diameter in pixels, returning its+-- response.+{-# INLINE knobWith' #-}+knobWith' :: (Layout -> Layout) -> Float -> Float -> Float -> Var Float -> NanoUI Response+knobWith' f diameter minV maxV v = bindVarBy sameFloat RenderFinal v (knobCore f diameter minV maxV)++knobCore ::+  (Layout -> Layout)+  -> Float+  -> Float+  -> Float+  -> Float+  -> NanoUI (Response, Float)+knobCore f diameter minV maxV value = do+  (wid, ctx) <- freshWidget+  -- NaN never equals itself, so it would be re-adopted, dirtying every frame.+  current <- liftIO $ adoptSlot fieldFloat ctx wid (if isNaN value then minV else value)+  let+    range = maxV - minV+    fracOf x = if range > 0 then clamp01 ((x - minV) / range) else 0+    spec x =+      (fixedSizeSpec f diameter diameter)+        { widgetCursor = Just (\_ _ _ -> UiCursorNsResize)+        , widgetFocusable = True+        , widgetContent = contentKey [fracOf x]+        , widgetDraw = \cdc (Rect bx by bw bh) -> runCanvasFor cdc $ do+            let+              cx = bx + bw / 2+              cy = by + bh / 2+              r = min (bw / 2) (bh / 2) - 2+              button = themeButton (cdcTheme cdc)+              bgCol+                | cdcPressed cdc = styleActiveBg button+                | cdcHovered cdc = styleHoverBg button+                | otherwise = styleBg button+              angle = (135 + fracOf x * 270) * (pi / 180)+              tip = V2 (cx + cos angle * (r * 0.75)) (cy + sin angle * (r * 0.75))+            drawCircle (V2 cx cy) r bgCol+            drawStrokeCircle (V2 cx cy) r 1.5 (styleBorder button)+            drawStrokeAA (V2 cx cy) tip 2.5 (themeAccent (cdcTheme cdc))+        }+  (resp, ()) <- customWidgetWithId wid (spec current)+  drag <- useDrag2DOn resp+  (_, scrollY) <- useWheelDeltaOn resp   nav <- useKeyNav wid-  let isDragging = dragActive drag-      dy = if isDragging then - v2Y (dragDelta drag) else 0-      dScroll = scrollY * 2.0-      dKey =-        (if knRight nav || knUp nav then 1 else 0 :: Int)-          - (if knLeft nav || knDown nav then 1 else 0)-      deltaNorm =-        if range > 0-          then (dy / 120.0) + (dScroll / 60.0) + fromIntegral dKey * 0.05-          else 0-      finalVal =-        if deltaNorm /= 0-          then clamp minV maxV (current + deltaNorm * range)-          else current-  uiIO $ do-    writeStoreFloat ctx wid key finalVal-    recordStoreFloat ctx key finalVal-  pure (setChanged (finalVal /= current) resp, finalVal)+  let+    deltaNorm = -v2Y (dragDelta drag) / 120 + scrollY * 2 / 60 + fromIntegral (navStep nav) * 0.05+    finalVal+      | range > 0 && deltaNorm /= 0 = clamp minV maxV (current + deltaNorm * range)+      | otherwise = current+  -- Re-register the drawing when the value changes so this frame renders the+  -- updated position.+  when (finalVal /= current) $ liftIO (registerCustomEntry ctx wid (specEntry (spec finalVal)))+  finishInput fieldFloat ctx wid current resp finalVal --- | On/off switch. Pass the current state; the result is the state after--- this frame's click or Space/Enter.+-- | Boolean toggle switch backed by a 'Var', toggled by click or Space/Enter. {-# INLINE toggleSwitch #-}-toggleSwitch :: Ui :> es => Bool -> Eff es Bool-toggleSwitch on = snd <$> toggleSwitchWith' id on+toggleSwitch :: Var Bool -> NanoUI ()+toggleSwitch v = void (toggleSwitchWith' id v) +-- | 'toggleSwitch' returning its response. {-# INLINE toggleSwitch' #-}-toggleSwitch' :: Ui :> es => Bool -> Eff es (Response, Bool)+toggleSwitch' :: Var Bool -> NanoUI Response toggleSwitch' = toggleSwitchWith' id  -- | 'toggleSwitch' with a layout modifier. {-# INLINE toggleSwitchWith #-}-toggleSwitchWith :: Ui :> es => (Layout -> Layout) -> Bool -> Eff es Bool-toggleSwitchWith f on = snd <$> toggleSwitchWith' f on+toggleSwitchWith :: (Layout -> Layout) -> Var Bool -> NanoUI ()+toggleSwitchWith f v = void (toggleSwitchWith' f v) -toggleSwitchWith' :: Ui :> es => (Layout -> Layout) -> Bool -> Eff es (Response, Bool)-toggleSwitchWith' f on = do-  wid <- nextId-  ctx <- askContext-  let key = intKey wid-  current <- intBool <$> uiIO (adoptStoreInt ctx wid key (boolInt on))-  let pillW = 44.0-      pillH = 24.0-  (resp, ()) <- customWidgetWithId wid defaultCustomWidgetSpec-    { widgetLayout = fixedWH pillW pillH (f defaultLayout)-    , widgetMeasure = Just $ \_ _ -> (pillW, pillH)-    , widgetCursor = Just (\_ -> UiCursorPointer)-    , widgetFocusable = True-    , widgetContent = contentKey [if current then 1 else 0]-    , widgetDraw = \cdc (Rect x y w h) -> runCanvas $ do-        let theme = cdcTheme cdc-            r = h / 2-            accent = themeAccent theme-            mutedCol = styleBg (themeButton theme)-            bgCol = if current then accent else mutedCol-            thumbR = r - 3-            thumbX = if current then (x + w - r) else (x + r)-            thumbY = y + r-            thumbCol = themeOnAccent theme-        drawRoundedRect (Rect x y w h) r bgCol-        drawStrokeRoundedRect (Rect x y w h) r 1 (styleBorder (themeButton theme))-        drawCircle (V2 thumbX thumbY) thumbR thumbCol-    }-  keyClick <- keyActivated wid-  let clicked = respClicked resp || keyClick-      newVal = current /= clicked-  uiIO $ do-    writeStoreBool ctx wid newVal-    recordStoreInt ctx key (boolInt newVal)-  pure (setChanged clicked resp, newVal)+-- | 'toggleSwitch' with a layout modifier, returning its response.+{-# INLINE toggleSwitchWith' #-}+toggleSwitchWith' :: (Layout -> Layout) -> Var Bool -> NanoUI Response+toggleSwitchWith' f v = bindVar RenderFinal v (toggleSwitchCore f) +toggleSwitchCore ::+  (Layout -> Layout) -> Bool -> NanoUI (Response, Bool)+toggleSwitchCore f on = do+  (wid, ctx) <- freshWidget+  current <- intBool <$> liftIO (adoptSlot fieldInt ctx wid (boolInt on))+  let+    pillW = 44.0+    pillH = 24.0+    spec isOn =+      (fixedSizeSpec f pillW pillH)+        { widgetCursor = Just (\_ _ _ -> UiCursorPointer)+        , widgetFocusable = True+        , widgetKeys = KeysActivate+        , widgetContent = contentKey [if isOn then 1 else 0]+        , widgetDraw = \cdc rect@(Rect x y w h) -> runCanvasFor cdc $ do+            let+              theme = cdcTheme cdc+              r = h / 2+              thumbX = if isOn then x + w - r else x + r+            drawRoundedRect rect r (if isOn then themeAccent theme else styleBg (themeButton theme))+            drawStrokeRoundedRect rect r 1 (styleBorder (themeButton theme))+            drawCircle (V2 thumbX (y + r)) (r - 3) (themeOnAccent theme)+        }+  (resp, ()) <- customWidgetWithId wid (spec current)+  result@(_, value) <- finishToggle ctx wid current resp+  when (value /= current) $ liftIO (registerCustomEntry ctx wid (specEntry (spec value)))+  pure result++{-# INLINE specEntry #-}+specEntry :: CustomWidgetSpec a -> CustomDrawingEntry+specEntry spec =+  CustomDrawingEntry+    (widgetContent spec)+    (widgetDraw spec)+    (widgetCursor spec)+    (widgetDamageSlop spec)+    (widgetTrackPointer spec)+    (widgetKeys spec)+ -- | Progress ring for a fraction in @[0, 1]@, 32 px across. {-# INLINE circularProgress #-}-circularProgress :: Ui :> es => Float -> Eff es ()+circularProgress :: Float -> NanoUI () circularProgress frac = void (circularProgressWith' id 32 frac) -{-# INLINE circularProgress' #-}-circularProgress' :: Ui :> es => Float -> Eff es Response+-- | 'circularProgress' returning its response.+circularProgress' :: Float -> NanoUI Response circularProgress' = circularProgressWith' id 32 --- | 'circularProgress' with a layout modifier and a diameter in pixels.-{-# INLINE circularProgressWith #-}-circularProgressWith :: Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es ()-circularProgressWith f diameter frac = void (circularProgressWith' f diameter frac)+-- | 'circularProgress' with a layout modifier and diameter.+circularProgressWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()+circularProgressWith f diameter = void . circularProgressWith' f diameter -circularProgressWith' :: Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es Response+-- | 'circularProgress' with a layout modifier and a diameter in pixels,+-- returning its response.+circularProgressWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response circularProgressWith' f diameter frac =-  fst <$> customWidget defaultCustomWidgetSpec-    { widgetLayout = fixedWH diameter diameter (f defaultLayout)-    , widgetMeasure = Just $ \_ _ -> (diameter, diameter)-    , widgetContent = contentKey [clamp01 frac]-    , widgetDraw = \cdc (Rect x y w h) -> runCanvas $ do-        let cx = x + w / 2-            cy = y + h / 2+  fst <$> customWidget (fixedSizeSpec f diameter diameter)+    { widgetContent = contentKey [clamp01 frac]+    , widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $ do+        let centre = V2 (x + w / 2) (y + h / 2)             r = min (w / 2) (h / 2) - 2             theme = cdcTheme cdc-            trackCol = styleBorder (themeButton theme)-            accent = themeAccent theme             clampedFrac = clamp01 frac-        drawStrokeCircle (V2 cx cy) r 2.0 trackCol+        drawStrokeCircle centre r 2.0 (styleBorder (themeButton theme))         when (clampedFrac > 0) $-          drawCircle (V2 cx cy) (r * clampedFrac) accent+          drawCircle centre (r * clampedFrac) (themeAccent theme)     } --- | An indeterminate loading indicator: a short accent arc turning over a--- faint ring, 18 px across. It keeps the frame loop running while it is on--- screen and repaints only its own rect.+-- | An indeterminate loading indicator, 18 px across: an accent arc turning+-- over a faint ring. While any of it is on screen it wakes the frame loop+-- for each of its 60 steps a second; scrolled or clipped out of view, it+-- wakes nothing. {-# INLINE spinner #-}-spinner :: Ui :> es => Eff es ()+spinner :: NanoUI () spinner = void (spinnerWith' id 18) -{-# INLINE spinner' #-}-spinner' :: Ui :> es => Eff es Response+-- | 'spinner' returning its response.+spinner' :: NanoUI Response spinner' = spinnerWith' id 18 --- | 'spinner' with a layout modifier and a diameter in pixels.-{-# INLINE spinnerWith #-}-spinnerWith :: Ui :> es => (Layout -> Layout) -> Float -> Eff es ()-spinnerWith f diameter = void (spinnerWith' f diameter)+-- | 'spinner' with a layout modifier and diameter.+spinnerWith :: (Layout -> Layout) -> Float -> NanoUI ()+spinnerWith f = void . spinnerWith' f -spinnerWith' :: Ui :> es => (Layout -> Layout) -> Float -> Eff es Response+-- | 'spinner' with a layout modifier and a diameter in pixels, returning its+-- response. It requests a frame for its next step ('wakeAfter') while any of+-- it is on screen, so it costs 60 frames a second however fast the display+-- refreshes, and none while hidden.+spinnerWith' :: (Layout -> Layout) -> Float -> NanoUI Response spinnerWith' f diameter = do   t <- uiTime   let !d = max 4 diameter@@ -623,66 +582,59 @@       -- frames within a step reuse the ops.       !step = floor (t * 48 / 0.8) `mod` 48 :: Int   resp <--    fst <$> customWidget defaultCustomWidgetSpec-      { widgetLayout = fixedWH d d (f defaultLayout)-      , widgetMeasure = Just $ \_ _ -> (d, d)-      , widgetContent = step + 1-      , widgetDraw = \cdc (Rect x y w h) -> runCanvas $ do+    fst <$> customWidget (fixedSizeSpec f d d)+      { widgetContent = step + 1+      , widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $ do           let theme = cdcTheme cdc               thick = max 1.5 (d / 9)               r = min w h / 2 - thick / 2               cx = x + w / 2               cy = y + h / 2               start = 2 * pi * fromIntegral step / 48-              at a = V2 (cx + r * cos a) (cy + r * sin a)-              segments = 8 :: Int-              sweep = pi / 2           drawStrokeCircle (V2 cx cy) r thick (fadeAlpha (themeAccent theme) 48)-          forM_ [0 .. segments - 1] $ \i -> do-            let a0 = start + sweep * fromIntegral i / fromIntegral segments-                a1 = start + sweep * fromIntegral (i + 1) / fromIntegral segments-            drawStrokeAA (at a0) (at a1) thick (themeAccent theme)+          drawStrokePath (P.arc (V2 cx cy) r start (pi / 2)) thick (themeAccent theme)       }-  keepAnimating resp+  -- The sensor is keyed by the spinner's own id, so it takes no sibling id.+  vis <- withContext $ \ctx -> watchSensor ctx (respId resp) (Watch (respId resp) defaultSensorConfig)+  when (visVisible vis) $+    wakeAfter (max 1.0e-3 (fromIntegral (floor (t * stepsPerSec) + 1 :: Int) / stepsPerSec - t))   pure resp+  where+    stepsPerSec = 48 / 0.8 :: Double  -- | Horizontal progress bar for a fraction in @[0, 1]@. It fills the -- available width at a fixed height. {-# INLINE progressBar #-}-progressBar :: Ui :> es => Float -> Eff es ()+progressBar :: Float -> NanoUI () progressBar frac = void (progressBarWith' id progressBarDefaultHeight frac) -{-# INLINE progressBar' #-}-progressBar' :: Ui :> es => Float -> Eff es Response+-- | 'progressBar' returning its response.+progressBar' :: Float -> NanoUI Response progressBar' = progressBarWith' id progressBarDefaultHeight --- | 'progressBar' with a layout modifier and a bar height in pixels.-{-# INLINE progressBarWith #-}-progressBarWith :: Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es ()-progressBarWith f height frac = void (progressBarWith' f height frac)+-- | 'progressBar' with a layout modifier and height.+progressBarWith :: (Layout -> Layout) -> Float -> Float -> NanoUI ()+progressBarWith f height = void . progressBarWith' f height -progressBarWith' :: Ui :> es => (Layout -> Layout) -> Float -> Float -> Eff es Response+-- | 'progressBar' with a layout modifier and a height in pixels, returning+-- its response.+progressBarWith' :: (Layout -> Layout) -> Float -> Float -> NanoUI Response progressBarWith' f height frac =   let !barH = max 0 height    in fst <$> customWidget defaultCustomWidgetSpec-        { widgetLayout = fillW (fixedH barH (f defaultLayout))+        { widgetLayout = fixedH barH . f . fillW         , widgetMeasure = Just $ \_ _ -> (progressBarDefaultWidth, barH)         , widgetContent = contentKey [clamp01 frac]-        , widgetDraw = \cdc (Rect x y w h) -> runCanvas $ do+        , widgetDraw = \cdc (Rect x y w h) -> runCanvasFor cdc $ do             let theme = cdcTheme cdc-                trackCol = styleBg (themeButton theme)-                borderCol = styleBorder (themeButton theme)-                fillCol = themeAccent theme                 barW = max 0 w                 barH' = max 0 h                 rad = barH' / 2-                clamped = clamp01 frac-                fillWpx = barW * clamped-                fillRad = if barH' <= 0 then 0 else min rad (fillWpx / 2)-            drawRoundedRect (Rect x y barW barH') rad trackCol-            when (clamped > 0 && fillWpx > 0) $-              drawRoundedRect (Rect x y fillWpx barH') fillRad fillCol-            drawStrokeRoundedRect (Rect x y barW barH') rad 1 borderCol+                fillWpx = barW * clamp01 frac+            drawRoundedRect (Rect x y barW barH') rad (styleBg (themeButton theme))+            when (fillWpx > 0) $+              drawRoundedRect (Rect x y fillWpx barH') (min rad (fillWpx / 2)) (themeAccent theme)+            drawStrokeRoundedRect (Rect x y barW barH') rad 1 (styleBorder (themeButton theme))         }  -- | Default height and minimum content width for 'progressBar'.@@ -692,29 +644,26 @@  -- | A small line chart of the values, 80 by 24 px, scaled to their range. {-# INLINE sparkline #-}-sparkline :: Ui :> es => [Float] -> Eff es ()+sparkline :: [Float] -> NanoUI () sparkline values = void (sparklineWith' id 80 24 values) -{-# INLINE sparkline' #-}-sparkline' :: Ui :> es => [Float] -> Eff es Response+-- | 'sparkline' returning its response.+sparkline' :: [Float] -> NanoUI Response sparkline' = sparklineWith' id 80 24 --- | 'sparkline' with a layout modifier and a width and height in pixels.-{-# INLINE sparklineWith #-}-sparklineWith :: Ui :> es => (Layout -> Layout) -> Float -> Float -> [Float] -> Eff es ()-sparklineWith f prefW prefH values = void (sparklineWith' f prefW prefH values)+-- | 'sparkline' with a layout modifier, width and height.+sparklineWith :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI ()+sparklineWith f w h = void . sparklineWith' f w h -sparklineWith' :: Ui :> es => (Layout -> Layout) -> Float -> Float -> [Float] -> Eff es Response+-- | 'sparkline' with a layout modifier and a preferred size, returning its+-- response.+sparklineWith' :: (Layout -> Layout) -> Float -> Float -> [Float] -> NanoUI Response sparklineWith' f prefW prefH values =-  fst <$> customWidget defaultCustomWidgetSpec-    { widgetLayout = fixedWH prefW prefH (f defaultLayout)-    , widgetMeasure = Just $ \_ _ -> (prefW, prefH)-    , widgetContent = contentKey values-    , widgetDraw = \cdc (Rect x y rw rh) -> runCanvas $ do-        let theme = cdcTheme cdc-            accent = themeAccent theme-            bg = styleBg (themePanel theme)-        drawRoundedRect (Rect x y rw rh) 3.0 bg+  fst <$> customWidget (fixedSizeSpec f prefW prefH)+    { widgetContent = contentKey values+    , widgetDraw = \cdc rect@(Rect x y rw rh) -> runCanvasFor cdc $ do+        let accent = themeAccent (cdcTheme cdc)+        drawRoundedRect rect 3.0 (styleBg (themePanel (cdcTheme cdc)))         case values of           [] -> pure ()           [_] -> drawCircle (V2 (x + rw / 2) (y + rh / 2)) 2.0 accent@@ -731,13 +680,6 @@                            (y + rh - pad - ((v - minV) / range) * plotH)                       | (i, v) <- zip [0 :: Int ..] vs                       ]-                drawSegments [] = pure ()-                drawSegments [_] = pure ()-                drawSegments (p1 : p2 : rest) = do-                  drawStrokeAA p1 p2 1.5 accent-                  drawSegments (p2 : rest)-            drawSegments pts-            case pts of-              [] -> pure ()-              _ -> drawCircle (last pts) 2.5 accent+            drawStrokePath (P.polyline pts) 1.5 accent+            drawCircle (last pts) 2.5 accent     }
− lib/NanoUI/Widgets/Display.hs
@@ -1,241 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}---- | Display helpers: styled labels, key/value rows, cards, toolbars, images--- and colour boxes.-module NanoUI.Widgets.Display-  ( heading-  , muted-  , mono-  , danger-  , bold-  , italic-  , underline-  , kv-  , kvMono-  , kvBlock-  , card-  , toolbar-  , image-  , image'-  , freshImageId-  , registerImageRgba-  , svgIcon-  , svgIconWith-  , svgIconWith'-  , loadSvg-  , box-  )-where--import Control.Exception (IOException, try)-import Control.Monad (void)-import Data.ByteString (ByteString)-import Data.ByteString qualified as BS-import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)-import Data.Map.Strict qualified as Map-import Data.Text.Encoding qualified as TE-import Data.Text (Text)-import Data.Text qualified as T-import Effectful (Eff, type (:>))-import NanoUI.Atlas qualified as Atlas-import NanoUI.Context (Context (..), askHostIO, registerImage, setHost)-import NanoUI.Draw (getDrawSnapScale)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, nextId, uiIO, uiTheme)-import NanoUI.Svg (Svg, parseSvg, rasterizeSvg, svgKey, svgMonochrome, svgSize)-import NanoUI.Style-  ( Layout (..)-  , Sizing (..)-  , alignEnd-  , alignMid-  , defaultLayout-  , fillW-  , fontBold-  , fontDanger-  , fontItalic-  , fontMedium-  , fontMono-  , fontMuted-  , fontUnderline-  , gap-  , minW-  , padXY-  , styleFg-  , themePanel-  , tight-  )-import Data.Word (Word32)-import NanoUI.Types (Color (..), ImageId (..), colorRGBA, colorToWord32)-import NanoUI.WidgetText (intValueText)-import NanoUI.Widgets.Layout (labelEx, labelWith, panelWith, row', rowWith)-import NanoUI.Widgets.Node (Response, addWidget, addWidgetStyled)--heading :: Ui :> es => Text -> Eff es ()-heading = labelWith (tight . fontMedium)--muted :: Ui :> es => Text -> Eff es ()-muted = labelWith (fillW . fontMuted)--mono :: Ui :> es => Text -> Eff es ()-mono = labelWith fontMono--danger :: Ui :> es => Text -> Eff es ()-danger = labelWith (fillW . fontDanger)--bold :: Ui :> es => Text -> Eff es ()-bold = labelWith fontBold--italic :: Ui :> es => Text -> Eff es ()-italic = labelWith fontItalic--underline :: Ui :> es => Text -> Eff es ()-underline = labelWith fontUnderline---- | Key/value row: a muted key on the left, the value right-aligned. Trailing--- whitespace in the value is dropped.-kv :: Ui :> es => Text -> Text -> Eff es ()-kv k v =-  row' (tight . gap 12 . alignMid . fillW $ defaultLayout) $ do-    void (labelEx (fontMuted . tight . minW 88 $ defaultLayout) k)-    void (labelEx (tight . fillW . alignEnd $ defaultLayout) (T.stripEnd v))---- | Key/value row with a monospace value.-kvMono :: Ui :> es => Text -> Text -> Eff es ()-kvMono k v =-  row' (tight . gap 12 . alignMid . fillW $ defaultLayout) $ do-    void (labelEx (tight . minW 88 $ defaultLayout) k)-    void (labelEx (tight . fillW . alignEnd . fontMono $ defaultLayout) (T.stripEnd v))---- | Key/value pairs as one monospace block with the keys padded to a column.-kvBlock :: (Foldable f, Ui :> es) => f (Text, Text) -> Eff es ()-kvBlock rows =-  let maxK = foldl' (\acc (k, _) -> max acc (T.length k)) 0 rows-      padK k = T.justifyLeft maxK ' ' k-   in void $-        labelEx-          (tight . gap 0 . fontMono $ defaultLayout)-          (T.concat (foldr (\(k, v) rest -> padK k : "  " : v : "\n" : rest) [] rows))--card :: Ui :> es => Eff es a -> Eff es a-card = panelWith (minW 300 . padXY 12 10 . gap 8 . fillW)--toolbar :: Ui :> es => Eff es a -> Eff es a-toolbar = rowWith (tight . gap 8 . alignMid . fillW)---- | An image registered with the host, sized by the layout modifier.-image :: Ui :> es => (Layout -> Layout) -> ImageId -> Eff es ()-image f iid = void (image' f iid)---- | 'image' with its 'Response', for example to 'NanoUI.keepAnimating' an--- image whose id changes over time.-image' :: Ui :> es => (Layout -> Layout) -> ImageId -> Eff es Response-image' f (ImageId tid) = do-  wid <- nextId-  let-    stored = if tid <= 0 then T.empty else intValueText tid-  addWidget wid NodeImage stored 0 (f defaultLayout)---- | An image id that no registered image uses and no earlier call returned.--- Take one for each image registered while the app runs.-freshImageId :: Ui :> es => Eff es ImageId-freshImageId = do-  ctx <- askContext-  uiIO (Atlas.freshImageId (ctxImageAtlas ctx))---- | Register an RGBA image (4 bytes a pixel, rows top to bottom) under an id--- while the app runs, for 'image' to draw. Returns 'False' when the size or--- pixels are invalid, an image of another size already has the id, or the--- atlas is full. An image of the same size is replaced.-registerImageRgba :: Ui :> es => ImageId -> Int -> Int -> ByteString -> Eff es Bool-registerImageRgba iid w h pixels = do-  ctx <- askContext-  uiIO (registerImage ctx iid w h pixels)---- | Read and parse an SVG file.-loadSvg :: FilePath -> IO (Either String Svg)-loadSvg path = do-  result <- try (BS.readFile path)-  pure $ case result of-    Left (err :: IOException) -> Left (show err)-    Right bytes -> parseSvg (TE.decodeUtf8Lenient bytes)---- | An SVG icon @size@ logical pixels square, drawn in the text colour where--- it is used: a one-colour document (every paint @currentColor@ or--- unspecified) takes the colour as a tint, and a multicoloured one paints--- its @currentColor@ with it.-{-# INLINE svgIcon #-}-svgIcon :: Ui :> es => Float -> Svg -> Eff es ()-svgIcon size = svgIconWith (fixedSquare size)-  where-    fixedSquare n l = l {layoutWidth = Fixed n, layoutHeight = Fixed n}---- | An SVG document sized by the layout modifier: a fixed width and height,--- or else the document's own size. A 'NanoUI.fontColor' in the modifier--- replaces the text colour.-{-# INLINE svgIconWith #-}-svgIconWith :: Ui :> es => (Layout -> Layout) -> Svg -> Eff es ()-svgIconWith f doc = void (svgIconWith' f doc)---- | The document is rasterized once per pixel size and colour, at the--- display's scale, and kept in the image atlas for as long as the app runs.-svgIconWith' :: Ui :> es => (Layout -> Layout) -> Svg -> Eff es Response-svgIconWith' f doc = do-  ctx <- askContext-  theme <- uiTheme-  let lay0 = f defaultLayout-      (docW, docH) = svgSize doc-      fixedOr sizing dflt = case sizing of-        Fixed n -> n-        _ -> dflt-      w = fixedOr (layoutWidth lay0) docW-      h = fixedOr (layoutHeight lay0) docH-      color = maybe (styleFg (themePanel theme)) id (layoutFontColor lay0)-      oneColour = svgMonochrome doc-      white = colorRGBA 255 255 255 255-      lay = lay0 {layoutWidth = Fixed w, layoutHeight = Fixed h, layoutFontColor = Just (if oneColour then color else white)}-  iid <- uiIO $ do-    scale <- getDrawSnapScale (ctxDrawArena ctx)-    let pw = max 1 (ceiling (w * max 1 scale))-        ph = max 1 (ceiling (h * max 1 scale))-        -- A one-colour raster is white and tinted when drawn, so every colour-        -- shares it.-        rasterColor = if oneColour then white else color-        key = (svgKey doc, pw, ph, colorToWord32 rasterColor)-    cache <- svgRasterCache ctx-    known <- Map.lookup key <$> readIORef cache-    case known of-      Just iid -> pure iid-      Nothing -> do-        iid <- Atlas.freshImageId (ctxImageAtlas ctx)-        ok <- registerImage ctx iid pw ph (rasterizeSvg pw ph rasterColor doc)-        if ok-          then atomicModifyIORef' cache (\m -> (Map.insert key iid m, ()))-          else pure ()-        pure (if ok then iid else ImageId 0)-  image' (const lay) iid---- | Rasterized SVG documents by document, pixel size and colour.-newtype SvgRasters = SvgRasters (IORef (Map.Map (Int, Int, Int, Word32) ImageId))--svgRasterCache :: Context -> IO (IORef (Map.Map (Int, Int, Int, Word32) ImageId))-svgRasterCache ctx =-  askHostIO ctx >>= \case-    Just (SvgRasters ref) -> pure ref-    Nothing -> do-      ref <- newIORef Map.empty-      setHost ctx (SvgRasters ref)-      pure ref---- | A solid rectangle sized by the layout modifier.-box :: Ui :> es => (Layout -> Layout) -> Color -> Eff es ()-box f col = do-  wid <- nextId-  void-    ( addWidgetStyled-        wid-        NodeBox-        T.empty-        0-        (f defaultLayout)-        (fromIntegral (colorToWord32 col))-    )
− lib/NanoUI/Widgets/Drawing.hs
@@ -1,65 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Drawing-  ( DrawOp (..)-  , DrawingBuild-  , drawing-  , drawingVersioned-  , drawingCached-  )-where--import Data.Text qualified as T-import Data.Primitive.SmallArray (SmallArray)-import Effectful (Eff, type (:>))-import NanoUI.Context (cachedWidgetLayout, registerDrawing)-import NanoUI.Draw (DrawOp (..), DrawingBuild)-import NanoUI.Layout.Arena (NodeType (NodeDrawing))-import NanoUI.Monad (Ui, askContext, nextId, uiIO)-import NanoUI.Style (Layout, defaultLayout)-import NanoUI.Types (Rect)-import NanoUI.Widgets.Node (Response, addWidget)---- | Vector ops for a laid-out widget. Paint caches ops while width and height--- stay the same, then translates when the widget moves. Unversioned: the cache--- drops while the widget animates because the builder has no content key, and--- a builder that draws something else at the same size neither rebuilds nor--- repaints. Use 'drawingVersioned' for output that changes, or--- 'NanoUI.Widgets.Custom.customWidget' without a key to have every frame--- rebuild and compare.-{-# INLINE drawing #-}-drawing :: Ui :> es => (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> Eff es Response-drawing = drawingVersioned 0---- | Like 'drawing', but the tessellated op cache is keyed by an explicit--- content version. Change the version whenever the builder output changes--- (a model pointer, dirty counter, or content hash): that rebuilds the ops and--- repaints the widget. Frames with the same version replay cached ops without--- rebuilding, even while the widget animates. Version 0 means unversioned, as--- in 'drawing'.-drawingVersioned :: Ui :> es => Int -> (Layout -> Layout) -> (Rect -> SmallArray DrawOp) -> Eff es Response-drawingVersioned version f build = do-  wid <- nextId-  ctx <- askContext-  uiIO (registerDrawing ctx wid version build)-  addWidget wid NodeDrawing T.empty 0 (f defaultLayout)---- | Like 'drawingVersioned', but the layout itself comes from @compute@, which--- only reruns when the envelope, line height, content key, or modifier result--- change.-drawingCached ::-  Ui :> es =>-  Double ->-  Double ->-  Float ->-  Int ->-  (Layout -> Layout) ->-  IO Layout ->-  DrawingBuild ->-  Eff es Response-drawingCached dw dh lh content f compute build = do-  wid <- nextId-  ctx <- askContext-  layout <- uiIO (cachedWidgetLayout ctx wid dw dh lh content (f defaultLayout) compute)-  uiIO (registerDrawing ctx wid content build)-  addWidget wid NodeDrawing T.empty 0 layout
− lib/NanoUI/Widgets/Drop.hs
@@ -1,146 +0,0 @@-{-# LANGUAGE StrictData #-}---- | Operating-system drag and drop.------ 'useDrop' turns the frame's 'NanoUI.Input.DropEvent's into a 'DropTarget'--- for one rectangle. 'dropZone' wraps a panel and does the same for its rect.------ @--- (_, _, target) <- dropZone fillW (label "Drop files here")--- when (dropReceived target) (mapM_ openFile (dropFiles target))--- @-module NanoUI.Widgets.Drop-  ( DropTarget (..)-  , useDrop-  , dropZone-  ) where--import Control.Applicative ((<|>))-import Control.Monad (when)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)-import Data.Foldable (toList)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( getStore-  , intKey-  , modifyStore-  )-import NanoUI.Input-  ( DropEvent (..)-  , DropType (..)-  , inputDrops-  )-import NanoUI.Monad (Ui, askContext, askDefaultLayout, askInput, nextId, uiIO)-import NanoUI.Store-  ( WidgetStore (..)-  , Slot (..)-  , slotKey-  )-import NanoUI.Style (Layout)-import NanoUI.Types (Rect, V2 (..), rectContains)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Widgets.Node (Response, containerResponse, respRect)---- | Per-frame drop state for a single rectangular drop target.-data DropTarget = DropTarget-  { dropHovered :: !Bool-    -- ^ A drag is currently positioned over the target rect.-  , dropReceived :: !Bool-    -- ^ One or more payloads landed on the target this frame.-  , dropFiles :: ![Text]-    -- ^ File paths dropped on the target this frame.-  , dropTexts :: ![Text]-    -- ^ Text snippets dropped on the target this frame.-  , dropPosition :: !(Maybe V2)-    -- ^ Last known drop position in window coordinates, if any.-  }-  deriving (Eq, Show)---- | Compute the drop state for a rectangle from the current frame's drop events.------ Active/hover state persists across frames in the widget store, so a target--- keeps highlighting while the OS drag is stationary. Payload events--- ('DropFile'/'DropText') are one-shot: they are reported exactly on the frame--- they arrive.------ Attribution uses the tracked drag position (the coordinates of the most--- recent 'DropPosition') rather than a payload's own coordinates. SDL--- synthesizes file/text events at the last drag position and reports (0,0)--- when it never observed one, so the position stream is the only reliable--- signal for "which target is this drop over".-useDrop :: Ui :> es => Rect -> Eff es DropTarget-useDrop bounds = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  let key = intKey wid-      activeK = slotKey SlotDrop key-      posK = slotKey SlotDropPos key-  store <- uiIO (getStore ctx)-  let active0 = IM.findWithDefault 0 activeK (storeInt store) /= 0-      lastPos0 = fmap (\(x, y) -> V2 x y) (IM.lookup posK (storePoint store))-      events = toList (inputDrops inp)-      -- A drag is active from 'DropBegin' until 'DropComplete'.-      active1 =-        foldl'-          ( \active ev -> case dropEventType ev of-              DropBegin -> True-              DropComplete -> False-              _ -> active-          )-          active0-          events-      -- Tracked position after each event: only 'DropPosition' moves it and-      -- 'DropComplete' clears it. Payload events leave it unchanged, so a-      -- payload is attributed to the position at that point in the sequence,-      -- not to the frame's final position.-      positions =-        drop 1 $ scanl-          ( \pos ev -> case dropEventType ev of-              DropPosition -> dropEventPos ev <|> pos-              DropComplete -> Nothing-              _ -> pos-          )-          lastPos0-          events-      lastPos1 = last (lastPos0 : positions)-      payloads ty =-        [dropEventData ev | (ev, pos) <- zip events positions, dropEventType ev == ty, posInside bounds pos]-      files = payloads DropFile-      texts = payloads DropText-      hovered = active1 && posInside bounds lastPos1-  when (active1 /= active0 || lastPos1 /= lastPos0) $-    uiIO $-      modifyStore ctx $ \st ->-        st-          { storeInt =-              if active1-                then IM.insert activeK 1 (storeInt st)-                else IM.delete activeK (storeInt st)-          , storePoint =-              maybe-                (IM.delete posK (storePoint st))-                (\(V2 x y) -> IM.insert posK (x, y) (storePoint st))-                lastPos1-          }-  pure-    DropTarget-      { dropHovered = hovered-      , dropReceived = not (null files) || not (null texts)-      , dropFiles = files-      , dropTexts = texts-      , dropPosition = lastPos1-      }--posInside :: Rect -> Maybe V2 -> Bool-posInside bounds = maybe False (rectContains bounds)---- | A panel that is also a drop target. Returns the body's result, the--- panel's 'Response', and the 'DropTarget' for its rect.-dropZone :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es (a, Response, DropTarget)-dropZone f child = do-  base <- askDefaultLayout-  (a, resp) <- containerResponse NodePanel (f base) child-  target <- useDrop (respRect resp)-  pure (a, resp, target)
− lib/NanoUI/Widgets/Layout.hs
@@ -1,361 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Layout-  ( panel-  , panelWith-  , panel'-  , callout-  , calloutWith-  , row-  , rowWith-  , row'-  , column-  , columnWith-  , column'-  , hstack-  , vstack-  , label-  , label'-  , labelWith-  , labelWith'-  , labelEx-  , separator-  , spacer-  , flex-  , scroll-  , scrollWith-  , scroll'-  , scroll2D-  , scroll2DWith-  , scroll2D'-  , scrollArea-  , scrollArea2D-  , scrollConfigured-  , scrollAreaIdConfigured-  , grid-  , gridWith-  , grid'-  , responsive-  , responsiveRowCol-  , center-  )-where--import Control.Monad (void)-import Data.IORef (readIORef)-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context (Context (..), setScrollConfig)-import NanoUI.Frame.Scroll.Geometry-  ( ScrollConfig (..)-  , defaultScrollConfig-  , encodeScrollConfig-  , scrollDefault1D-  )-import NanoUI.Id (WidgetId)-import NanoUI.Layout.Arena-  ( DirTag (..)-  , NodeIdx-  , NodeType (..)-  , addNodeFromLayout-  , getDirection-  , setStyleIdx-  , setWidgetId-  )-import NanoUI.Input (Input (inputWindowSize))-import NanoUI.Monad (Ui, askContext, askDefaultLayout, askInput, nextId, styled, uiIO)-import NanoUI.Style-  ( AlignX (..)-  , Direction (..)-  , Layout (..)-  , Sizing (..)-  , alignMid-  , fillW-  , gap-  , grow-  , padXY-  , panelStyle-  )-import NanoUI.Style qualified as Style-import NanoUI.Types (Color (..), Size (..), lerpColor)-import NanoUI.Widgets.Node-  ( Response-  , addSizingLeafNode-  , addWidget-  , container--  , parentIdx-  , withContainerNode-  )---- =============================================================================--- Internal Ambient Helpers--- =============================================================================--{-# INLINE withDefault #-}-withDefault :: Ui :> es => (Layout -> Eff es a -> Eff es r) -> Eff es a -> Eff es r-withDefault = withDefaultWith id--{-# INLINE withDefaultWith #-}-withDefaultWith :: Ui :> es => (Layout -> Layout) -> (Layout -> Eff es a -> Eff es r) -> Eff es a -> Eff es r-withDefaultWith f c child = do-  base <- askDefaultLayout-  c (f base) child---- =============================================================================--- Panel--- =============================================================================--{-# INLINE panel #-}-panel :: Ui :> es => Eff es a -> Eff es a-panel = withDefault panel'--{-# INLINE panelWith #-}-panelWith :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a-panelWith = (`withDefaultWith` panel')--{-# INLINE panel' #-}-panel' :: Ui :> es => Layout -> Eff es a -> Eff es a-panel' = container NodePanel--{-# INLINE callout #-}-callout :: Ui :> es => Color -> Eff es a -> Eff es a-callout borderCol = calloutWith borderCol id---- | A panel tinted with @col@: a border in it and a faint wash of it over the--- panel colour. The tint applies to the callout's own panel and to panels--- nested in it.-{-# INLINE calloutWith #-}-calloutWith :: Ui :> es => Color -> (Layout -> Layout) -> Eff es a -> Eff es a-calloutWith col f =-  styled-    (\t -> panelStyle (Style.background (lerpColor col (Style.styleBg (Style.themePanel t)) 0.88) . Style.borderColor col) t)-    . panelWith (f . padXY 10 6 . gap 8 . fillW)---- =============================================================================--- Row--- =============================================================================--{-# INLINE row #-}-row :: Ui :> es => Eff es a -> Eff es a-row = withDefault row'--{-# INLINE rowWith #-}-rowWith :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a-rowWith = (`withDefaultWith` row')--{-# INLINE row' #-}-row' :: Ui :> es => Layout -> Eff es a -> Eff es a-row' layout = container NodeContainer (layout {layoutDirection = Row})---- =============================================================================--- Column--- =============================================================================--{-# INLINE column #-}-column :: Ui :> es => Eff es a -> Eff es a-column = withDefault column'--{-# INLINE columnWith #-}-columnWith :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a-columnWith = (`withDefaultWith` column')--{-# INLINE column' #-}-column' :: Ui :> es => Layout -> Eff es a -> Eff es a-column' layout = container NodeContainer (layout {layoutDirection = Column})---- =============================================================================--- Collection stacks--- =============================================================================---- | Run a collection of widgets side by side, as in @hstack (map label names)@.-{-# INLINE hstack #-}-hstack :: (Foldable f, Ui :> es) => f (Eff es ()) -> Eff es ()-hstack = row . sequence_---- | Run a collection of widgets top to bottom.-{-# INLINE vstack #-}-vstack :: (Foldable f, Ui :> es) => f (Eff es ()) -> Eff es ()-vstack = column . sequence_---- =============================================================================--- Grid--- =============================================================================--{-# INLINE grid #-}-grid :: Ui :> es => Int -> Eff es a -> Eff es a-grid n = withDefault (grid' n)--{-# INLINE gridWith #-}-gridWith :: Ui :> es => Int -> (Layout -> Layout) -> Eff es a -> Eff es a-gridWith n f = withDefaultWith f (grid' n)--{-# INLINE grid' #-}-grid' :: Ui :> es => Int -> Layout -> Eff es a -> Eff es a-grid' n layout = container NodeContainer (layout {layoutGridCols = max 1 n})---- =============================================================================--- Responsive--- =============================================================================---- | Choose between two container builders based on window width.-{-# INLINE responsive #-}-responsive :: Ui :> es => Float -> (Eff es a -> Eff es a) -> (Eff es a -> Eff es a) -> Eff es a -> Eff es a-responsive breakpoint wideContainer narrowContainer child = do-  inp <- askInput-  let w = sizeW (inputWindowSize inp)-  if w >= breakpoint then wideContainer child else narrowContainer child---- | A row while the window is at least @breakpoint@ wide, a column below it.-{-# INLINE responsiveRowCol #-}-responsiveRowCol :: Ui :> es => Float -> (Layout -> Layout) -> Eff es a -> Eff es a-responsiveRowCol breakpoint f child = do-  inp <- askInput-  base <- askDefaultLayout-  let w = sizeW (inputWindowSize inp)-      dir = if w >= breakpoint then Row else Column-  container NodeContainer ((f base) {layoutDirection = dir}) child---- | A line of text. Newlines start new lines.-{-# INLINE label #-}-label :: Ui :> es => Text -> Eff es ()-label txt = void (label' txt)---- | 'label' returning its 'Response', for a tooltip or an anchored popup.-{-# INLINE label' #-}-label' :: Ui :> es => Text -> Eff es Response-label' txt = do-  base <- askDefaultLayout-  labelEx base txt---- | 'label' with a layout modifier, for example @labelWith fontMono@.-{-# INLINE labelWith #-}-labelWith :: Ui :> es => (Layout -> Layout) -> Text -> Eff es ()-labelWith f txt = void (labelWith' f txt)--{-# INLINE labelWith' #-}-labelWith' :: Ui :> es => (Layout -> Layout) -> Text -> Eff es Response-labelWith' f txt = do-  base <- askDefaultLayout-  labelEx (f base) txt--{-# INLINE labelEx #-}-labelEx :: Ui :> es => Layout -> Text -> Eff es Response-labelEx layout txt = do-  wid <- nextId-  addWidget wid NodeText txt 0 layout---- | Takes up the remaining space along the parent's direction.-{-# INLINE flex #-}-flex :: Ui :> es => Eff es ()-flex = spacer (Grow 1) Fit---- | A one-pixel rule: horizontal in a column, vertical in a row.-separator :: Ui :> es => Eff es ()-separator = void $ do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    let-      parent = parentIdx stack-    parentDir <--      if parent < 0-        then pure DirColumn-        else getDirection (ctxNodeArena ctx) parent-    let-      (dir, wSiz, hSiz) =-        case parentDir of-          DirColumn -> (Column, Grow 1, Fixed 1)-          DirRow -> (Row, Fixed 1, Grow 1)-    addSizingLeafNode ctx inp wid NodeSeparator dir wSiz hSiz---- | Empty space with the given sizing on each axis.-{-# INLINE spacer #-}-spacer :: Ui :> es => Sizing -> Sizing -> Eff es ()-spacer w h = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  void (uiIO $ addSizingLeafNode ctx inp wid NodeSpacer Row w h)--{-# INLINE scroll #-}-scroll :: Ui :> es => Eff es a -> Eff es a-scroll = withDefault scroll'--{-# INLINE scrollWith #-}-scrollWith :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a-scrollWith = (`withDefaultWith` scroll')--{-# INLINE scroll' #-}-scroll' :: Ui :> es => Layout -> Eff es a -> Eff es a-scroll' layout child =-  snd <$> scrollConfigured (scrollDefault1D (layoutDirection layout)) layout child--{-# INLINE center #-}-center :: Ui :> es => Eff es a -> Eff es a-center = columnWith (grow . alignMid . (\l -> l { layoutAlignX = AlignCenter }))---- | Push a scroll container node, run the child inside it, then pop.-{-# INLINE scrollContainerWith #-}-scrollContainerWith :: Ui :> es => WidgetId -> (NodeIdx -> IO ()) -> Layout -> Eff es a -> Eff es a-scrollContainerWith wid setup layout child = do-  ctx <- askContext-  idx <- uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    idx <- addNodeFromLayout (ctxNodeArena ctx) NodeScrollContainer (parentIdx stack) layout-    setWidgetId (ctxNodeArena ctx) idx wid-    setup idx-    pure idx-  -- Unscoped: a scroll container's children keep their parent's id scope.-  withContainerNode False idx child---- | Style index + context scroll config for a container with a chosen config.-{-# INLINE configureScrollContainer #-}-configureScrollContainer :: Context -> WidgetId -> ScrollConfig -> NodeIdx -> IO ()-configureScrollContainer ctx wid cfg idx = do-  setStyleIdx (ctxNodeArena ctx) idx (encodeScrollConfig cfg)-  setScrollConfig ctx wid cfg---- | 'scrollWith' that also returns the container's widget id, which keys its--- scroll offset.-{-# INLINE scrollArea #-}-scrollArea :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es (WidgetId, a)-scrollArea f child = do-  layout <- f <$> askDefaultLayout-  scrollConfigured (scrollDefault1D (layoutDirection layout)) layout child--{-# INLINE scrollAreaIdConfigured #-}-scrollAreaIdConfigured :: Ui :> es => WidgetId -> Layout -> ScrollConfig -> Eff es a -> Eff es a-scrollAreaIdConfigured wid layout cfg child = do-  ctx <- askContext-  scrollContainerWith wid (configureScrollContainer ctx wid cfg) layout child---- | Scroll container on both axes.-{-# INLINE scroll2D #-}-scroll2D :: Ui :> es => Eff es a -> Eff es a-scroll2D = withDefault scroll2D'--{-# INLINE scroll2DWith #-}-scroll2DWith :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es a-scroll2DWith = (`withDefaultWith` scroll2D')--{-# INLINE scroll2D' #-}-scroll2D' :: Ui :> es => Layout -> Eff es a -> Eff es a-scroll2D' layout child = fmap snd (scrollConfigured defaultScrollConfig layout child)---- | 'scroll2DWith' that also returns the container's widget id.-{-# INLINE scrollArea2D #-}-scrollArea2D :: Ui :> es => (Layout -> Layout) -> Eff es a -> Eff es (WidgetId, a)-scrollArea2D f child = do-  layout <- f <$> askDefaultLayout-  scrollConfigured defaultScrollConfig layout child--{-# INLINE scrollConfigured #-}-scrollConfigured :: Ui :> es => ScrollConfig -> Layout -> Eff es a -> Eff es (WidgetId, a)-scrollConfigured cfg layout child = do-  ctx <- askContext-  wid <- nextId-  r <- scrollContainerWith wid (configureScrollContainer ctx wid cfg) layout child-  pure (wid, r)
− lib/NanoUI/Widgets/Menu.hs
@@ -1,214 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Menu-  ( contextMenu-  , contextMenuArea-  , useContextMenu-  , menuButton-  , menuButton'-  , MenuItem (..)-  , menuItemWith-  , menuItem-  , menuItem'-  , menuItemShortcut-  , menuItemDisabled-  , menuSeparator-  , menuHeader-  )-where--import Control.Monad (void, when)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context (Context (..), getStore, intKey, modifyStore)-import NanoUI.Font (menuItemPadX, menuItemRowH, menuMinW, menuOuterPad, menuSepH, widgetContentInset)-import NanoUI.Input (inputMousePos, inputMouseReleased)-import NanoUI.Monad (Ui, askContext, askDefaultLayout, askInput, nextId, uiIO)-import NanoUI.Store (WidgetStore (..), slotKey, Slot (..))-import NanoUI.Style (Layout (..), Padding (..), defaultLayout, fillW, fixedH, fontMuted, gap, minW, padXY, tight)-import NanoUI.Types (PopupAnchor (..), PopupPlacement (..), V2 (..))-import NanoUI.WidgetText (buttonFlagMenu, buttonFlagMenuBar)-import NanoUI.Widgets.Combinators (buttonStyled)-import NanoUI.Widgets.Layout (columnWith, labelEx, rowWith, separator)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Widgets.Node (HasResponse, Response (..), containerResponse, respClicked, respHovered, respRightClicked)-import NanoUI.Widgets.Popup (PopupConfig (..), popup)---- | A context menu for any widget response, opened by right-clicking it.--- Returns the menu body's result while the menu is open.-contextMenu ::-  (Ui :> es, HasResponse r) =>-  r ->-  Eff es a ->-  Eff es (Maybe a)-contextMenu target child = do-  menu <- useContextMenu-  runContextMenu menu (respRightClicked target) (const child)---- | A container whose right-click opens a context menu. The menu body--- receives the position it was opened at.-contextMenuArea ::-  Ui :> es =>-  (Layout -> Layout) ->-  Eff es a ->-  (V2 -> Eff es b) ->-  Eff es (a, Maybe b)-contextMenuArea f areaContent menuContent = do-  menu <- useContextMenu-  base <- askDefaultLayout-  (areaRes, areaResp) <- containerResponse NodeContainer (f base) areaContent-  (,) areaRes <$> runContextMenu menu (respRightClicked areaResp) menuContent---- | Open the menu at the pointer on a right click, show it while open, and--- close it once a row is picked or it is dismissed.-runContextMenu ::-  Ui :> es =>-  (Bool, V2, V2 -> Eff es (), Eff es ()) ->-  Bool ->-  (V2 -> Eff es a) ->-  Eff es (Maybe a)-runContextMenu (isOpen0, pos0, openAt, close) rightClick child = do-  inp <- askInput-  let mouse = inputMousePos inp-      pos = if rightClick then mouse else pos0-      cfg =-        PopupConfig-          { cfgAnchor = AnchorPoint pos-          , cfgPlacement = PlacementAtCursor-          , cfgDismissable = True-          , cfgOffset = 0-          }-  when rightClick (openAt mouse)-  (popupResp, mBody) <- popup (isOpen0 || rightClick) cfg (columnWith (tight . gap 0) (child pos))-  let picked = respHovered popupResp && inputMouseReleased inp-  when (respClicked popupResp || picked) close-  pure mBody---- | Open state for a context menu you position yourself: whether it is open,--- where it was opened, an action to open it at a point, and one to close it.-useContextMenu ::-  Ui :> es =>-  Eff es (Bool, V2, V2 -> Eff es (), Eff es ())-useContextMenu = do-  wid <- nextId-  ctx <- askContext-  let key = intKey wid-      openK = slotKey SlotMenuOpen key-      posK = slotKey SlotMenuPos key-  store <- uiIO (getStore ctx)-  let isOpen = IM.findWithDefault 0 openK (storeInt store) /= 0-      (px, py) = IM.findWithDefault (0, 0) posK (storePoint store)-      openAt (V2 x y) =-        uiIO $-          modifyStore ctx $ \st ->-            st-              { storeInt = IM.insert openK 1 (storeInt st)-              , storePoint = IM.insert posK (x, y) (storePoint st)-              }-      close = uiIO $ modifyStore ctx $ \st -> st {storeInt = IM.delete openK (storeInt st)}-  pure (isOpen, V2 px py, openAt, close)---- | One context-menu row; the whole row is the button.-data MenuItem = MenuItem-  { menuItemLabel :: !Text-  , menuItemHint :: !(Maybe Text)-    -- ^ Shortcut hint shown after the label, e.g. @Ctrl+S@.-  , menuItemEnabled :: !Bool-    -- ^ Disabled rows are dimmed and cannot be clicked or focused.-  }-  deriving (Eq, Show)---- | Render a menu row, returning its full 'Response'. A disabled row is a--- muted label, not a disabled button: hover tracking does not know a button's--- enabled flag and would still highlight it. Text nodes ignore padding, so the--- label sits in a container that reproduces an enabled row's geometry: the--- 'menuItemRowH' height and 'menuMinW' width, the label inset 'menuItemPadX'--- plus the button's content inset, and the same total horizontal gutter the--- solver reserves for menu buttons. Its response never reports interaction.-menuItemWith :: Ui :> es => MenuItem -> Eff es Response-menuItemWith (MenuItem lbl hint enabled)-  | enabled = buttonStyled text 0 menuRowLayout buttonFlagMenu-  | otherwise = do-      ctx <- askContext-      let (ix, _) = widgetContentInset (ctxFontMetrics ctx)-          padLeft = menuItemPadX + ix-          padRight = max 0 (2 * (menuOuterPad + menuItemPadX) - padLeft)-          rowLayout = (minW menuMinW defaultLayout) {layoutPadding = Padding padLeft padRight 0 0}-      (_, resp) <--        containerResponse NodeContainer rowLayout $-          labelEx (fixedH menuItemRowH . tight . fontMuted $ defaultLayout) text-      pure-        resp-          { rawRespHovered = False-          , rawRespPressed = False-          , rawRespClicked = False-          , rawRespRightPressed = False-          , rawRespRightClicked = False-          }-  where-    text = maybe lbl (\s -> mconcat [lbl, "  ", s]) hint---- | Menu row. 'True' on the frame it is clicked.------ @--- whenM (menuItem "Open...") openFile--- @-{-# INLINE menuItem #-}-menuItem :: Ui :> es => Text -> Eff es Bool-menuItem txt = respClicked <$> menuItem' txt--{-# INLINE menuItem' #-}-menuItem' :: Ui :> es => Text -> Eff es Response-menuItem' txt = menuItemWith (MenuItem txt Nothing True)---- | Menu row with a shortcut hint after the label. The hint is only text;--- handle the key itself elsewhere.------ @--- whenM (menuItemShortcut "Save" "Ctrl+S") saveFile--- @-menuItemShortcut :: Ui :> es => Text -> Text -> Eff es Bool-menuItemShortcut txt hint = respClicked <$> menuItemWith (MenuItem txt (Just hint) True)---- | Dimmed menu row that cannot be clicked.-menuItemDisabled :: Ui :> es => Text -> Eff es ()-menuItemDisabled txt = void (menuItemWith (MenuItem txt Nothing False))---- | Row layout shared by menu items, matching the text-field context menu:--- 28px rows and a 148px minimum menu width (@menuItemRowH@ and @menuMinW@ in--- @NanoUI.Font@).-menuRowLayout :: Layout-menuRowLayout = minW menuMinW . fixedH menuItemRowH . tight . fillW $ defaultLayout---- | Menu-bar title: a flat, label-sized button. @open@ tints the title while--- its drop-down is showing. 'True' on the frame it is clicked.-{-# INLINE menuButton #-}-menuButton :: Ui :> es => Text -> Bool -> Eff es Bool-menuButton txt open = respClicked <$> menuButton' txt open---- | 'menuButton' returning its 'Response', whose rect anchors the drop-down.-menuButton' :: Ui :> es => Text -> Bool -> Eff es Response-menuButton' txt open =-  buttonStyled txt (if open then 1 else 0) menuBarTitleLayout buttonFlagMenuBar--menuBarTitleLayout :: Layout-menuBarTitleLayout = tight $ defaultLayout---- | Separator line inside a context menu, matching the text-field context--- menu painter exactly: a 1px rule inset 'menuItemPadX' from the panel edge--- (the popup already contributes 'menuOuterPad', the row adds the remainder)--- centered in a 'menuSepH' band (@lineY = bandY + h\/2@ via 4.5px vertical--- padding around a zero-height content box). The rule sits in a 'tight'--- column so it stays horizontal ('separator' adapts to its parent's--- direction and would grow vertically inside the padded row) and so the--- default 3px container padding does not inset or stretch it.-menuSeparator :: Ui :> es => Eff es ()-menuSeparator = do-  rowWith (fixedH menuSepH . padXY (menuItemPadX - menuOuterPad) 4.5 . fillW) $-    columnWith (tight . fillW) separator---- | Header / category title inside a context menu.-menuHeader :: Ui :> es => Text -> Eff es ()-menuHeader txt =-  void (labelEx (padXY 6 2 defaultLayout) txt)
− lib/NanoUI/Widgets/Node.hs
@@ -1,430 +0,0 @@-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE OverloadedStrings #-}---- | Widget node construction and interaction responses.-module NanoUI.Widgets.Node-  ( Response (..)-  , HasResponse (..)-  , respId-  , respRect-  , respHovered-  , respPressed-  , respClicked-  , respChanged-  , respSubmitted-  , respRightPressed-  , respRightClicked-  , mkResponse-  , emptyModalResp-  , setClicked-  , setChanged-  , setSubmitted-  , parentIdx-  , container-  , containerResponse-  , withContainerNode-  , floatingPanel-  , addWidget-  , addWidgetStyled-  , addWidgetWithOptions-  , addSizingLeafNode-  , resolveInteraction-  , tagContainer-  )-where--import Control.Monad (when)-import Data.IORef (readIORef, writeIORef)-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , isDisabled-  , pointerBlockedByOverlay-  , OverlayState (..)-  , getsOverlay-  , modifyOverlay-  )-import NanoUI.Id (WidgetId (..), enterScope, hashWidgetId, scopeTag)-import NanoUI.Input-  ( Input (..)-  , inputMouseDown-  , inputMousePos-  , inputMouseReleased-  , inputMouseRightDown-  , inputMouseRightReleased-  )-import NanoUI.Layout.Arena-  ( NodeIdx-  , NodeType (..)-  , addNode-  , addNodeFromLayout-  , rootAttachParent-  , setNodeText-  , setOptions-  , setNodeValue-  , setStyleIdx-  , setWidgetId-  )-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO)-import NanoUI.WidgetText (packTextNodeStyleFull)-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Direction (..)-  , Layout (..)-  , Padding (..)-  , Sizing (..)-  )-import NanoUI.Types (Rect (..), rectContains, rectH, rectHit, rectUnion, rectW)-import NanoUI.Frame.Hit (findNodeByWidgetId, nodeInteractionHit, scrollHitRect)--parentIdx :: [Int] -> Int-parentIdx = \case-  [] -> -1-  (p : _) -> p---- | Anything that carries a widget 'Response' (composite widget results such--- as 'NanoUI.Widgets.Tabs.TabResponse'). The @resp*@ accessors work on all of them.-class HasResponse r where-  toResponse :: r -> Response--instance HasResponse Response where-  {-# INLINE toResponse #-}-  toResponse = id--{-# INLINE respId #-}-respId :: HasResponse r => r -> WidgetId-respId = rawRespId . toResponse--{-# INLINE respRect #-}-respRect :: HasResponse r => r -> Rect-respRect = rawRespRect . toResponse--{-# INLINE respHovered #-}-respHovered :: HasResponse r => r -> Bool-respHovered = rawRespHovered . toResponse--{-# INLINE respPressed #-}-respPressed :: HasResponse r => r -> Bool-respPressed = rawRespPressed . toResponse--{-# INLINE respClicked #-}-respClicked :: HasResponse r => r -> Bool-respClicked = rawRespClicked . toResponse--{-# INLINE respChanged #-}-respChanged :: HasResponse r => r -> Bool-respChanged = rawRespChanged . toResponse--{-# INLINE respSubmitted #-}-respSubmitted :: HasResponse r => r -> Bool-respSubmitted = rawRespSubmitted . toResponse--{-# INLINE respRightPressed #-}-respRightPressed :: HasResponse r => r -> Bool-respRightPressed = rawRespRightPressed . toResponse--{-# INLINE respRightClicked #-}-respRightClicked :: HasResponse r => r -> Bool-respRightClicked = rawRespRightClicked . toResponse--data Response = Response-  { rawRespId :: !WidgetId-  , rawRespRect :: !Rect-  , rawRespHovered :: !Bool-  , rawRespPressed :: !Bool-  , rawRespClicked :: !Bool-  , rawRespChanged :: !Bool-  , rawRespSubmitted :: !Bool-  , rawRespRightPressed :: !Bool-  , rawRespRightClicked :: !Bool-  }-  deriving (Eq, Show)--instance Semigroup Response where-  a <> b =-    Response-      { rawRespId = if rawRespId b == WidgetId 0 then rawRespId a else rawRespId b-      , rawRespRect = unionRespRect (rawRespRect a) (rawRespRect b)-      , rawRespHovered = rawRespHovered a || rawRespHovered b-      , rawRespPressed = rawRespPressed a || rawRespPressed b-      , rawRespClicked = rawRespClicked a || rawRespClicked b-      , rawRespChanged = rawRespChanged a || rawRespChanged b-      , rawRespSubmitted = rawRespSubmitted a || rawRespSubmitted b-      , rawRespRightPressed = rawRespRightPressed a || rawRespRightPressed b-      , rawRespRightClicked = rawRespRightClicked a || rawRespRightClicked b-      }--instance Monoid Response where-  mempty = mkResponse (WidgetId 0) (Rect 0 0 0 0) False False False False--unionRespRect :: Rect -> Rect -> Rect-unionRespRect a b-  | rectW a <= 0 || rectH a <= 0 = b-  | rectW b <= 0 || rectH b <= 0 = a-  | otherwise = rectUnion a b--setClicked :: Bool -> Response -> Response-setClicked c r = r {rawRespClicked = c}--setChanged :: Bool -> Response -> Response-setChanged c r = r {rawRespChanged = c}--setSubmitted :: Bool -> Response -> Response-setSubmitted s r = r {rawRespSubmitted = s}--mkResponse :: WidgetId -> Rect -> Bool -> Bool -> Bool -> Bool -> Response-mkResponse wid rect hovered pressed clicked changed =-  Response-    { rawRespId = wid-    , rawRespRect = rect-    , rawRespHovered = hovered-    , rawRespPressed = pressed-    , rawRespClicked = clicked-    , rawRespChanged = changed-    , rawRespSubmitted = False-    , rawRespRightPressed = False-    , rawRespRightClicked = False-    }--emptyModalResp :: WidgetId -> Response-emptyModalResp wid = mempty {rawRespId = wid}--container :: Ui :> es => NodeType -> Layout -> Eff es a -> Eff es a-container nt layout child = runContainer nt layout Nothing child--containerResponse :: Ui :> es => NodeType -> Layout -> Eff es a -> Eff es (a, Response)-containerResponse nt layout child = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  r <- runContainer nt layout (Just wid) child-  resp <- uiIO (resolveInteraction ctx inp wid)-  pure (r, resp)--runContainer :: Ui :> es => NodeType -> Layout -> Maybe WidgetId -> Eff es a -> Eff es a-runContainer nt layout mWid child = do-  ctx <- askContext-  idx <- uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    idx <- addNodeFromLayout (ctxNodeArena ctx) nt (parentIdx stack) layout-    mapM_ (setWidgetId (ctxNodeArena ctx) idx) mWid-    pure idx-  withContainerNode True idx child---- | Push container node @idx@ (already added under the current parent), run--- @child@ inside it, then pop. @scoped@ also runs the children in a fresh id--- scope; it changes the children's widget ids (and so their store keys), so--- callers pick it explicitly: plain containers scope, scroll containers do not.-withContainerNode :: Ui :> es => Bool -> NodeIdx -> Eff es a -> Eff es a-withContainerNode scoped idx child = do-  ctx <- askContext-  (stack, parentIds) <- uiIO $ do-    stack0 <- readIORef (ctxContainerStack ctx)-    writeIORef (ctxContainerStack ctx) (idx : stack0)-    ids0 <- readIORef (ctxIdContext ctx)-    if scoped-      then do-        let (parentIds, childIds) = enterScope scopeTag ids0-        writeIORef (ctxIdContext ctx) childIds-        pure (stack0, parentIds)-      else pure (stack0, ids0)-  r <- child-  uiIO $ do-    writeIORef (ctxContainerStack ctx) stack-    when scoped $ writeIORef (ctxIdContext ctx) parentIds-  pure r---- | A floating panel (popup, modal, window): its node attaches to the root--- layer and it is the current floating panel while @body@ runs. @addPanel@--- adds the node under the given parent; @enter@ runs once the node is pushed--- (seeding its rect, opening a modal).-floatingPanel ::-  Ui :> es => Bool -> WidgetId -> (Int -> IO NodeIdx) -> IO () -> Eff es a -> Eff es a-floatingPanel scoped wid addPanel enter body = do-  ctx <- askContext-  let arena = ctxNodeArena ctx-  prevFloat <- uiIO (getsOverlay ctx osCurrentFloatingId)-  idx <- uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    idx <- addPanel =<< rootAttachParent arena (parentIdx stack)-    setWidgetId arena idx wid-    pure idx-  r <- withContainerNode scoped idx (uiIO (enter >> modifyOverlay ctx (\os -> os {osCurrentFloatingId = Just wid})) >> body)-  uiIO (modifyOverlay ctx (\os -> os {osCurrentFloatingId = prevFloat}))-  pure r--addSizingLeafNode ::-  Context-  -> Input-  -> WidgetId-  -> NodeType-  -> Direction-  -> Sizing-  -> Sizing-  -> IO Response-addSizingLeafNode ctx inp wid nt dir wSiz hSiz = do-  stack <- readIORef (ctxContainerStack ctx)-  let-    parent = parentIdx stack-  idx <--    addNode-      (ctxNodeArena ctx)-      nt-      parent-      dir-      wSiz-      hSiz-      (Padding 0 0 0 0)-      0-      0-      0-      1e9-      1e9-      0-      AlignStart-      AlignTop-  setWidgetId (ctxNodeArena ctx) idx wid-  resolveInteraction ctx inp wid--{-# INLINE addWidget #-}-addWidget ::-  Ui :> es =>-  WidgetId-  -> NodeType-  -> Text-  -> Float-  -> Layout-  -> Eff es Response-addWidget wid nt txt value layout = addWidgetStyled wid nt txt value layout 0--{-# INLINE addWidgetStyled #-}-addWidgetStyled ::-  Ui :> es =>-  WidgetId-  -> NodeType-  -> Text-  -> Float-  -> Layout-  -> Int-  -> Eff es Response-addWidgetStyled wid nt txt value layout styleIdx = do-  ctx <- askContext-  inp <- askInput-  uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    let-      parent = parentIdx stack-    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout-    setNodeText (ctxNodeArena ctx) idx txt-    setNodeValue (ctxNodeArena ctx) idx value-    let effectiveStyle-          | nt == NodeText = packTextNodeStyleFull (layoutFontVariant layout) (layoutFontWeight layout) (layoutFontStyle layout) (layoutTextDecoration layout) styleIdx-          | otherwise = styleIdx-    setStyleIdx (ctxNodeArena ctx) idx effectiveStyle-    setWidgetId (ctxNodeArena ctx) idx wid-    resolveInteraction ctx inp wid--addWidgetWithOptions ::-  Ui :> es =>-  WidgetId-  -> NodeType-  -> Text-  -> [Text]-  -> Float-  -> Layout-  -> Eff es Response-addWidgetWithOptions wid nt txt opts value layout = do-  ctx <- askContext-  inp <- askInput-  uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    let parent = parentIdx stack-    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout-    setNodeText (ctxNodeArena ctx) idx txt-    setOptions (ctxNodeArena ctx) idx opts-    setNodeValue (ctxNodeArena ctx) idx value-    setStyleIdx (ctxNodeArena ctx) idx 0-    setWidgetId (ctxNodeArena ctx) idx wid-    resolveInteraction ctx inp wid--resolveInteraction :: Context -> Input -> WidgetId -> IO Response-resolveInteraction ctx inp wid = do-  mrect <- scrollHitRect ctx wid-  active <- readIORef (ctxActiveId ctx)-  pending <- readIORef (ctxClickedId ctx)-  let-    mouse = inputMousePos inp-    rect = case mrect of-      Just r -> r-      Nothing -> Rect 0 0 0 0-    canHit = rectHit rect mouse || pending == wid-  if not canHit-    then pure $! mkResponse wid rect False False False False-    else do-      disabled <- isDisabled ctx wid-      blocked <- pointerBlockedByOverlay ctx mouse-      mIdx <- findNodeByWidgetId ctx wid-      let-        hitAt p = case mIdx of-          Nothing -> pure (rectContains rect p)-          Just idx -> nodeInteractionHit ctx idx rect p-        -- Whether the button held in @ref@ went down on this widget. A press-        -- the frame never saw (synthesized input, or one swallowed before it-        -- arrived) leaves the gesture unowned, so nobody is ruled out.-        startedHere ref = readIORef ref >>= maybe (pure True) hitAt-      -- A held button belongs to whatever it went down on. Another widget the-      -- drag passes over is not hovered, so it neither lights up nor reports a-      -- press of its own.-      captured <--        if not (inputMouseDown inp)-          then pure False-          else-            if hashWidgetId active /= 0 && active /= wid-              then pure True-              else not <$> startedHere (ctxPressPos ctx)-      hovered <--        if disabled || blocked || captured-          then pure False-          else hitAt mouse-      let-        pressed = hovered && inputMouseDown inp-        rightPressed = hovered && inputMouseRightDown inp-      -- The click belongs to whatever the press went down on: a release that-      -- drifted here from a neighbouring widget is not this widget's click.-      released <--        if hovered && inputMouseReleased inp-          then startedHere (ctxPressPos ctx)-          else pure False-      rightReleased <--        if hovered && inputMouseRightReleased inp-          then startedHere (ctxRightPressPos ctx)-          else pure False-      when (released && wid == active) $-        writeIORef (ctxReleaseClickedId ctx) wid-      let-        clicked = released || pending == wid-        rightClicked = rightReleased-      pure $!-        Response-          { rawRespId = wid-          , rawRespRect = rect-          , rawRespHovered = hovered-          , rawRespPressed = pressed-          , rawRespClicked = clicked-          , rawRespChanged = False-          , rawRespSubmitted = False-          , rawRespRightPressed = rightPressed-          , rawRespRightClicked = rightClicked-          }---- | Stamp the current container with a widget id (radio/tree group key).-tagContainer :: Ui :> es => WidgetId -> Eff es ()-tagContainer wid = do-  ctx <- askContext-  uiIO $ do-    stack <- readIORef (ctxContainerStack ctx)-    case stack of-      (idx : _) -> setWidgetId (ctxNodeArena ctx) idx wid-      [] -> pure ()
− lib/NanoUI/Widgets/NumericInput.hs
@@ -1,232 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}---- | Numeric field: a text field that only accepts numbers, with an up / down--- stepper, arrow-key steps, and an optional hexadecimal mode.-module NanoUI.Widgets.NumericInput-  ( NumericInputConfig (..)-  , defaultNumericInputConfig-  , numericInput-  , numericInput'-  , numericInputConfigured-  , numericInputConfigured'-  )-where--import Control.Monad (when)-import Data.Char (isDigit, isHexDigit)-import Data.IntMap.Strict qualified as IM-import Data.Maybe (fromMaybe)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Text.Read qualified as TR-import Effectful (Eff, type (:>))-import GHC.Clock (getMonotonicTime)-import NanoUI.Context (getStore, intKey, markDirty, registerFocusable, modifyStore)-import NanoUI.Input (Key (..), inputKeys, inputKeysElem, inputModifiers, inputMouseDown, inputMousePos, inputMousePressed, modShift)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO)-import NanoUI.Store (WidgetStore (..), slotKey, Slot (..))-import NanoUI.Style (Layout (..), Sizing (..), defaultLayout)-import NanoUI.Types (Rect (..), rectContains)-import NanoUI.WidgetText (numericStepperRects, textInputFlagNumeric)-import NanoUI.Widgets.Behavior (keyboardFocused)-import NanoUI.Widgets.Node (Response, addWidgetStyled, respHovered, respRect, setChanged, setSubmitted)-import NanoUI.Widgets.TextEditor (singleLineMode)-import NanoUI.Widgets.TextInput (TextInputState (..), editTextInput, editorTextState, loadTextInputState, saveTextEditor, saveTextInputState)-import Numeric (showFFloat, showHex)---- | How a numeric field reads, shows, and steps its value.-data NumericInputConfig = NumericInputConfig-  { nicMin :: !Double-    -- ^ Smallest value (default: no limit).-  , nicMax :: !Double-    -- ^ Largest value (default: no limit).-  , nicStep :: !Double-    -- ^ What one arrow key or stepper click adds (default 1). Shift steps ten-    -- times as far.-  , nicDecimals :: !Int-    -- ^ Digits after the decimal point, both shown and accepted (default 0).-  , nicHex :: !Bool-    -- ^ Show and accept the value as a whole hexadecimal number (default-    -- 'False'). 'nicDecimals' is ignored in this mode.-  , nicLayout :: !Layout-  }-  deriving (Eq, Show)--defaultNumericInputConfig :: NumericInputConfig-defaultNumericInputConfig =-  NumericInputConfig-    { nicMin = -1 / 0-    , nicMax = 1 / 0-    , nicStep = 1-    , nicDecimals = 0-    , nicHex = False-    , nicLayout = defaultLayout {layoutWidth = Grow 1, layoutMinW = 80}-    }---- | Numeric field over whole numbers. Pass the current value; the result is--- the value after this frame's typing, arrow keys, and stepper clicks.------ Only digits, and a leading minus sign when the range reaches below zero, can--- be typed. Up and Down step the value, Shift steps ten times as far, and--- holding a stepper arrow repeats. Enter, a step, or leaving the field rewrites--- the text as the value, clamped to the range.-{-# INLINE numericInput #-}-numericInput :: Ui :> es => Double -> Eff es Double-numericInput value = snd <$> numericInputConfigured' defaultNumericInputConfig value--{-# INLINE numericInput' #-}-numericInput' :: Ui :> es => Double -> Eff es (Response, Double)-numericInput' = numericInputConfigured' defaultNumericInputConfig---- | 'numericInput' with a range, a step, decimal places, hexadecimal mode, or--- its own layout.------ @--- byte' <- numericInputConfigured defaultNumericInputConfig {nicMin = 0, nicMax = 255, nicHex = True} byte--- @-{-# INLINE numericInputConfigured #-}-numericInputConfigured :: Ui :> es => NumericInputConfig -> Double -> Eff es Double-numericInputConfigured cfg value = snd <$> numericInputConfigured' cfg value--numericInputConfigured' :: Ui :> es => NumericInputConfig -> Double -> Eff es (Response, Double)-numericInputConfigured' cfg value = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  uiIO $ registerFocusable ctx wid-  store <- uiIO (getStore ctx)-  isFocus <- keyboardFocused wid-  let-    key = intKey wid-    given = clampNumber cfg value-    stored = IM.lookup key (storeText store)-    -- Unfocused, the field shows the caller's value; focused, it keeps the-    -- text being typed.-    text0 = if isFocus then fromMaybe (formatNumber cfg given) stored else formatNumber cfg given-    s0 = loadTextInputState store key text0-    lastValue = IM.findWithDefault given key (storeDouble store)-  mEdited <- if isFocus then uiIO (editTextInput ctx singleLineMode inp store key s0) else pure Nothing-  resp <- addWidgetStyled wid NodeTextInput "" 0 (nicLayout cfg) textInputFlagNumeric-  let-    -- An edit that would leave text no number can start with is dropped.-    typed = maybe s0 editorTextState mEdited-    s1 = if acceptsNumberText cfg (tisText typed) then typed else s0-    current-      | isFocus = maybe lastValue (clampNumber cfg) (parseNumber cfg (tisText s1))-      | otherwise = given-    Rect rx ry rw rh = respRect resp-    (upRect, downRect) = numericStepperRects rx ry rw rh-    mouse = inputMousePos inp-    keys = inputKeys inp-    over r dir = if respHovered resp && rectContains r mouse then dir else 0-    pressDir-      | inputMousePressed inp = over upRect 1 + over downRect (-1)-      | otherwise = 0 :: Int-    held0 = IM.findWithDefault 0 (slotKey SlotNumericHeld key) (storeInt store)-    holding =-      held0 /= 0-        && inputMouseDown inp-        && over (if held0 > 0 then upRect else downRect) held0 /= 0-    keyDir-      | not isFocus = 0-      | inputKeysElem KeyUp keys = 1-      | inputKeysElem KeyDown keys = -1-      | otherwise = 0-  now <- if pressDir /= 0 || holding then uiIO getMonotonicTime else pure 0-  let-    repeatAt0 = IM.findWithDefault 0 (slotKey SlotNumericRepeat key) (storeDouble store)-    -- A held arrow repeats after a pause.-    repeatDir = if pressDir == 0 && holding && now >= repeatAt0 then held0 else 0-    dir-      | pressDir /= 0 = pressDir-      | repeatDir /= 0 = repeatDir-      | otherwise = keyDir-    held1-      | pressDir /= 0 = pressDir-      | holding = held0-      | otherwise = 0-    repeatAt1-      | pressDir /= 0 = now + 0.4-      | repeatDir /= 0 = now + 0.06-      | held1 == 0 = 0-      | otherwise = repeatAt0-    scale = if modShift (inputModifiers inp) then 10 else 1-    final-      | dir /= 0 = clampNumber cfg (roundNumber cfg (current + fromIntegral dir * scale * nicStep cfg))-      | otherwise = current-    submitted = isFocus && inputKeysElem KeyEnter keys-    -- A step or Enter rewrites the text as the value, caret at its end.-    s2-      | dir /= 0 || submitted =-          let t = formatNumber cfg final-           in TextInputState t (T.length t) (T.length t)-      | otherwise = s1-    heldK = slotKey SlotNumericHeld key-    repeatK = slotKey SlotNumericRepeat key-    dirty =-      stored /= Just (tisText s2)-        || s2 /= s0-        || IM.lookup key (storeDouble store) /= Just final-        || held1 /= held0-        || repeatAt1 /= repeatAt0-  when dirty $-    uiIO $ do-      -- An accepted edit keeps its undo history; a rejected one or a step-      -- rewrites the text without it.-      let save = case mEdited of-            Just ed | editorTextState ed == s2 -> saveTextEditor key ed-            _ -> saveTextInputState key s2-      modifyStore ctx $ \st0 ->-        let st = save st0-         in st-              { storeInt = (if held1 == 0 then IM.delete heldK else IM.insert heldK held1) (storeInt st)-              , storeDouble = IM.insert key final (IM.insert repeatK repeatAt1 (storeDouble st))-              }-  -- Keep frames coming while an arrow is held so it can repeat.-  when (held1 /= 0) $ uiIO (markDirty ctx)-  pure (setSubmitted submitted (setChanged (final /= value) resp), final)--clampNumber :: NumericInputConfig -> Double -> Double-clampNumber cfg = max (nicMin cfg) . min (nicMax cfg)---- | The value rounded to what the field shows.-roundNumber :: NumericInputConfig -> Double -> Double-roundNumber cfg v-  | nicHex cfg || nicDecimals cfg <= 0 = fromInteger (round v)-  | otherwise = fromInteger (round (v * scale)) / scale-  where-    scale = 10 ^ nicDecimals cfg--formatNumber :: NumericInputConfig -> Double -> Text-formatNumber cfg v-  | nicHex cfg =-      let n = round v :: Integer-       in (if n < 0 then "-" else "") <> T.toUpper (T.pack (showHex (abs n) ""))-  | nicDecimals cfg <= 0 = T.pack (show (round v :: Integer))-  | otherwise = T.pack (showFFloat (Just (nicDecimals cfg)) v "")---- | Whether @t@ can stand in the field mid-edit: an optional minus sign when--- the range reaches below zero, then digits (hexadecimal ones in hex mode),--- and with decimal places, one point followed by at most that many digits.-acceptsNumberText :: NumericInputConfig -> Text -> Bool-acceptsNumberText cfg t =-  signOk && case T.splitOn "." body of-    [whole] -> T.all digit whole-    [whole, frac] -> decimals > 0 && T.all isDigit whole && T.all isDigit frac && T.length frac <= decimals-    _ -> False-  where-    (negative, body) = maybe (False, t) ((,) True) (T.stripPrefix "-" t)-    signOk = not negative || nicMin cfg < 0-    digit = if nicHex cfg then isHexDigit else isDigit-    decimals = if nicHex cfg then 0 else nicDecimals cfg---- | The value the text reads as, once it reads as one.-parseNumber :: NumericInputConfig -> Text -> Maybe Double-parseNumber cfg t-  | nicHex cfg = case TR.signed TR.hexadecimal t of-      Right (n, rest) | T.null rest -> Just (fromInteger n)-      _ -> Nothing-  | otherwise = case TR.signed TR.rational (T.dropWhileEnd (== '.') t) of-      Right (v, rest) | T.null rest -> Just v-      _ -> Nothing
− lib/NanoUI/Widgets/Overlay.hs
@@ -1,179 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Overlay-  ( modal-  , window-  )-where--import Control.Monad (void, when)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)-import Data.Text qualified as T-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , beginModal-  , endModal-  , getPrevRect-  , getStore-  , intKey-  , seedFloatingPanel-  )-import NanoUI.Id (WidgetId)-import NanoUI.Input-  ( inputWindowSize-  )-import NanoUI.Layout.Arena (NodeType (..), addNode)-import NanoUI.Monad-  ( Ui-  , askContext-  , askInput-  , uiIO-  , withKey-  )-import NanoUI.Store (WidgetStore (..), slotKey, Slot (..))-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Direction (..)-  , Padding (..)-  , Sizing (..)-  , grow-  , padB-  , padT-  , tight-  , windowMargin-  , windowPad-  )-import NanoUI.Types (Rect (..), Size (..), rectNonEmpty)-import NanoUI.Widgets.Chrome-  ( closeButton-  , floatMinFor-  , modalTitleBarH-  , titleBarChromeHFor-  , titleBarLayoutFor-  , titleLabelLayoutFor-  )-import NanoUI.Widgets.Popup (floatingOverlay)-import NanoUI.Widgets.Layout-  ( flex-  , labelEx-  , row'-  , scrollWith-  , separator-  )-import NanoUI.Widgets.Node-  ( Response (..)-  , respClicked-  )--data OverlayKind-  = ModalOverlay-  | WindowOverlay-  deriving Eq--modal :: Ui :> es => Bool -> Text -> Eff es a -> Eff es (Response, Maybe a)-modal = overlay ModalOverlay--window :: Ui :> es => Bool -> Text -> Eff es a -> Eff es (Response, Maybe a)-window = overlay WindowOverlay--overlay ::-  Ui :> es =>-  OverlayKind -> Bool -> Text -> Eff es a -> Eff es (Response, Maybe a)-overlay kind open title child = do-  ctx <- askContext-  inp <- askInput-  let-    Size winW winH = inputWindowSize inp-    margin = windowMargin-    availW = max 1 (winW - 2 * margin)-    availH = max 1 (winH - 2 * margin)-    isModal = kind == ModalOverlay-    -- Modals share the window's side padding. The body's scrollbar sits-    -- out in it just inside the panel's edge, that padding from the-    -- content.-    padding = if isModal then windowPad {padB = 12} else windowPad-    barH = if isModal then modalTitleBarH else titleBarChromeHFor-    -- Window body breathing room: one side-pad between the chrome and-    -- the body, matching the window's left/right padding. Modals keep-    -- their own larger gap.-    bodyGap = if isModal then 8 else 10-    minWidth =-      floatMinFor-        (if isModal then 260 else 280)-        availW-    minHeight =-      if isModal-        then 0-        else-          min availH (padT padding + titleBarChromeHFor + bodyGap + padB padding)-    addOverlayNode _ parent =-      addNode-        (ctxNodeArena ctx)-        (if isModal then NodeModal else NodeWindow)-        parent-        Column-        Fit-        Fit-        padding-        bodyGap-        minWidth-        minHeight-        availW-        availH-        0-        AlignStart-        AlignTop-    enter wid = do-      when isModal (beginModal ctx)-      seedFloatingPanel ctx wid-        =<< floatingSeedRect ctx wid isModal minWidth minHeight margin winW winH-    titleLabel = void (labelEx (titleLabelLayoutFor barH) title)-  floatingOverlay open isModal addOverlayNode enter $ do-    close <--      row' (titleBarLayoutFor barH) $ do-        when (not (T.null title)) $-          case kind of-            ModalOverlay -> titleLabel-            WindowOverlay -> withKey title titleLabel-        flex-        withKey ("close" :: Text) closeButton-    when (isModal && not (T.null title)) separator-    r <- scrollWith (tight . grow) child-    when isModal (uiIO (endModal ctx))-    pure (respClicked close, r)--floatingSeedRect ::-  Context-  -> WidgetId-  -> Bool-  -> Float-  -> Float-  -> Float-  -> Float-  -> Float-  -> IO Rect-floatingSeedRect ctx wid isModal minWidth minHeight margin winW winH = do-  mPrev <- getPrevRect ctx wid-  case mPrev of-    Just r | rectNonEmpty r -> pure r-    _ -> do-      store <- getStore ctx-      let-        k = intKey wid-        pos = IM.lookup k (storePoint store)-        sz = IM.lookup (slotKey SlotWinSize k) (storePoint store)-      pure $-        case (pos, sz) of-          (Just (x, y), Just (w, h)) | w > 0 && h > 0 -> Rect x y w h-          (Just (x, y), _) -> Rect x y minWidth (max minHeight 1)-          _ ->-            let-              w = minWidth-              h = max minHeight 1-             in-              if isModal-                then Rect ((winW - w) / 2) ((winH - h) / 2) w h-                else Rect (max 0 (winW - w - margin)) margin w h
lib/NanoUI/Widgets/PaneGrid.hs view
@@ -1,1005 +1,988 @@-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE OverloadedStrings #-}---- | Interactive pane grid with resizable dividers, modelled on iced's--- @PaneGrid@.------ The grid is a binary split tree ('NanoUI.Widgets.SplitPane.GridNode')--- persisted per widget as a "Data.Dynamic" value in the widget store.------ Panes are rendered through the user-provided 'pgViewPane', which receives a--- 'PaneGridCtx' with immediate-mode actions to split, close, maximize, or--- restore the pane. Dividers can be dragged to resize; panes can be grabbed by--- their pick rect and dropped onto another pane (center = swap, edge = split)--- or onto the grid's outer edge to restructure the whole grid at top level;--- arrow keys navigate between panes; @m@/@x@ maximize/close and @Escape@--- restores while the grid is focused.-module NanoUI.Widgets.PaneGrid-  ( GridAxis (..)-  , PaneGridConfig (..)-  , defaultPaneGridConfig-  , PaneGridCtx (..)-  , PaneView (..)-  , PaneGridResponse (..)-  , paneGrid-  ) where--import Control.Monad (forM_, unless, void, when)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Dynamic (fromDynamic, toDyn)-import Data.Hashable (hash)-import Data.IntMap.Strict qualified as IM-import Data.List (find, minimumBy)-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as M-import Data.Maybe (fromMaybe, isJust, listToMaybe)-import Data.Ord (comparing)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Primitive.SmallArray (SmallArray)-import Data.Word (Word64)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , bumpMirror-  , damageWidget-  , getFocusId-  , getFocusVisible-  , getPrevRect-  , getStore-  , intKey-  , markDirty-  , markEscapeConsumed-  , getMenuPointerGesture-  , overlayConsumesQuit-  , registerCustomDrawing-  , registerFocusable-  , setStore-  , modifyStore-  )-import NanoUI.Draw (DrawOp)-import NanoUI.Input-  ( Input (..)-  , Key (..)-  , UiCursorKind (..)-  , inputChars-  , inputKeys-  , inputKeysElem-  , inputMouseDown-  , inputMousePos-  , inputMousePressed-  )-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, withIdFrame, withKey)-import NanoUI.Id (IdContext (..), WidgetId, hashWidgetId)-import NanoUI.Frame.Hit (nodeInteractionHit, scrollHitRect)-import NanoUI.Frame.Input (isInteractiveNode)-import NanoUI.Store-  ( WidgetStore (..)-  , slotKey-  , Slot (..)-  )-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Direction (..)-  , Layout (..)-  , Padding (..)-  , Sizing (..)-  , Style (..)-  , Theme (..)-  , defaultLayout-  , fadeAlpha-  , separatorTrackColor-  )-import NanoUI.Types-  ( DamageBounds (..)-  , Rect (..)-  , V2 (..)-  , lerpColor-  , rectHit-  , rectH-  , rectInflate-  , rectNonEmpty-  , rectW-  , rectX-  , rectY-  , v2X-  , v2Y-  )-import NanoUI.Widgets.Behavior (KeyNav (..), dragThresholdPx, useKeyNav)-import NanoUI.Widgets.Custom-  ( CustomWidgetSpec (..)-  , CustomDrawContext (..)-  , contentKey-  , defaultCustomWidgetSpec-  , customWidget-  , drawRect-  , drawRoundedRect-  , drawStroke-  , drawStrokeRoundedRect-  , drawText-  , runCanvas-  )-import NanoUI.Widgets.Layout (column', row')-import NanoUI.Layout.Arena (NodeType (..), arenaCount, getNodeType, getWidgetId)-import NanoUI.Widgets.Node-  ( container-  , containerResponse-  , tagContainer-  )-import NanoUI.Widgets.SplitPane-  ( DividerInfo (..)-  , GridAxis (..)-  , GridNode (..)-  , clampTreeRatio-  , dropPreview-  , dropTargetForPane-  , layoutNode-  , mainLen-  , mainMins-  , PaneDrop (..)-  , paneExist-  , splitLength-  , subtreeMin-  , topLevelDropTarget-  , treeMovePane-  , treePanes-  , treeRemovePane-  , treeSetRatio-  , treeSize-  , treeSplit-  )---- -------------------------------------------------------------------------------- Public API--- --------------------------------------------------------------------------------- | Configuration for a pane grid. 'pgViewPane' can run arbitrary widget code,--- so the config carries the caller's effect row.-data PaneGridConfig es = PaneGridConfig-  { pgLayout :: !(Layout -> Layout)-    -- ^ Layout modifier for the grid container (default 'id'); pass-    -- @fillW . fillH@ to fill the parent area.-  , pgSpacing :: !Float-    -- ^ Gutter between panes per split level (default 4).-  , pgMinSize :: !Float-    -- ^ Minimum physical size any pane may shrink to (default 40).-  , pgLeeway :: !Float-    -- ^ Extra grab margin on each side of a divider, added to 'pgSpacing' to-    -- form the divider's real layout gutter. The resize cursor and grab work-    -- anywhere in that gutter while only 'pgSpacing' is drawn crisp, so the-    -- interaction space is far wider than the visible line (default 6).-  , pgEdgeBand :: !Float-    -- ^ Thickness of the grid's outer edge that acts as a top-level drop zone-    -- (default 20). Dragging a pane into this band restructures the whole grid-    -- instead of a single pane: the tree is wrapped in a new top-level split-    -- with the dragged pane on that side.-  , pgViewPane :: !(Word64 -> PaneGridCtx es -> Eff es PaneView)-    -- ^ Renders the content of one pane.-  }--defaultPaneGridConfig :: PaneGridConfig es-defaultPaneGridConfig =-  PaneGridConfig-    { pgLayout = id-    , pgSpacing = 4-    , pgMinSize = 40-    , pgLeeway = 6-    , pgEdgeBand = 20-    , pgViewPane = \_ _ -> pure (PaneView "" False Nothing)-    }---- | Actions handed to a pane so it can mutate the grid immediately.-data PaneGridCtx es = PaneGridCtx-  { pgcPaneId :: !Word64-  , pgcRect :: !Rect-    -- ^ Prev-frame screen rect of this pane (zero until it has been laid-    -- out once; the whole grid rect while maximized). Use it to build-    -- 'pvDragPick' handles such as a title-bar sub-rect.-  , pgcMaximized :: !Bool-    -- ^ True when this pane currently fills the whole grid.-  , pgcDragging :: !Bool-    -- ^ True while this pane's drag is armed. Once the drag threshold is-    -- crossed, the pane is omitted from the visible layout until release.-  , pgcDndActive :: !Bool-    -- ^ True while any pane drag-and-drop gesture is in progress.-  , pgcSplit :: !(GridAxis -> Eff es Word64)-    -- ^ Split this pane along the axis; returns the new pane id.-  , pgcClose :: !(Eff es ())-  , pgcMaximize :: !(Eff es ())-  , pgcRestore :: !(Eff es ())-  }---- | What a pane renders to this frame. The pane's content (including any title--- bar / header) is drawn entirely by the caller in 'pgViewPane'; a header is--- purely optional and nothing here depends on one existing.-data PaneView = PaneView-  { pvTitle :: !Text-    -- ^ Label shown (abbreviated to fit) on the compact drag indicator.-  , pvDraggable :: !Bool-    -- ^ Grab the pane anywhere inside its own region to drag-and-drop it. This-    -- is the easy way to reorder panes without drawing a dedicated handle.-    -- Interactive children keep their pointer presses. Pane still needs a-    -- drag only on a sub-region? see 'pvDragPick'.-  , pvDragPick :: !(Maybe Rect)-    -- ^ Optional absolute sub-region (e.g. just a title bar; position it via-    -- 'pgcRect') that also starts a drag. Both handles combine: the pane drags-    -- if the press lands in this rect or (when 'pvDraggable') anywhere in the-    -- pane. 'Nothing' here and 'pvDraggable' 'False' makes the pane immovable.-  }-  deriving (Eq, Show)---- | Outcome of one frame of the grid. The pane list, focus, and maximize--- fields report the state after this pass: actions run by pane content--- ('pgcSplit', 'pgcClose', ...) and the keyboard handling below take effect--- in these values and from the next frame's layout onward.-data PaneGridResponse = PaneGridResponse-  { pgrChanged :: !Bool-    -- ^ Any structural or maximize change happened this frame.-  , pgrPaneCount :: !Int-    -- ^ Number of panes (0 once the last pane has been closed).-  , pgrPanes :: ![Word64]-    -- ^ Live pane ids, depth-first.-  , pgrFocusedPane :: !Word64-    -- ^ Focused pane id, 0 when the grid has no panes.-  , pgrMaximizedPane :: !Word64-    -- ^ Maximized pane id, 0 when none.-  }-  deriving (Eq, Show)---- -------------------------------------------------------------------------------- Internal state--- -------------------------------------------------------------------------------data RenderedPane = RenderedPane-  { rpPaneId :: !Word64-  , rpView :: !PaneView-  , rpControlHit :: !Bool-  }---- | Per-frame shared environment.-data GridEnv es = GridEnv-  { geCtx :: !Context-  , geKey :: !Int-  , gePaneScope :: !IdContext-    -- ^ Pane identity is rooted at the grid widget, independent of split-    -- ancestry so rearranging or temporarily collapsing splits preserves state.-  , geCfg :: !(PaneGridConfig es)-  , geGutter :: !Float-  , geThickness :: !Float-  , geMinSize :: !Float-  , geLeeway :: !Float-  , geRegions :: !(Map Word64 Rect)-    -- ^ Prev-frame pane regions; drives hit testing and 'pgcRect'.-  , geBaseRect :: !Rect-    -- ^ Prev-frame rect of the grid's root container.-  , geTree :: !GridNode-  , geSeed :: !Word64-    -- ^ Next fresh split / pane id ('SlotPaneNext'); strictly monotonic per-    -- grid, so ids are never reused and state keyed by pane id cannot-    -- collide with a closed pane's state.-  , geDrag0 :: !Int-  , geMax :: !Word64-  , geChangedRef :: !(IORef Bool)-  , geMakeCtx :: Word64 -> Rect -> Bool -> PaneGridCtx es-  }---- | Computed drag-and-drop interaction state for one frame.-data DragInfo = DragInfo-  { dgiActive :: !Bool-  , dgiMoved :: !Bool-  , dgiGhost :: !(Maybe Rect)-  , dgiZone :: !(Maybe (Rect, PaneDrop))-  }---- -------------------------------------------------------------------------------- Tree + focus state--- --------------------------------------------------------------------------------- | The grid's split tree persisted in the widget store, if seeded.-lookupTree :: Int -> WidgetStore -> Maybe GridNode-lookupTree k st = IM.lookup k (storeDyn st) >>= fromDynamic---- | A stored pane id that still exists in the tree, else 0.-validPane :: GridNode -> Int -> Word64-validPane t n =-  let p = fromIntegral n-   in if paneExist t p then p else 0---- | Focused pane: a maximized pane wins, then the stored focus if the pane--- still exists, then the first pane in the tree.-resolveFocus :: GridNode -> Word64 -> Word64 -> Word64-resolveFocus tree maxPane focus0-  | maxPane /= 0 = maxPane-  | paneExist tree focus0 = focus0-  | otherwise = fromMaybe 1 (listToMaybe (treePanes tree))---- -------------------------------------------------------------------------------- Entry point--- -------------------------------------------------------------------------------paneGrid :: (Ui :> es) => PaneGridConfig es -> Eff es PaneGridResponse-paneGrid cfg = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  uiIO (registerFocusable ctx wid)-  let key = intKey wid-      gestK = slotKey SlotPaneGest key-      grabK = slotKey SlotPaneGrab key-      focusK = slotKey SlotPaneFocus key-      maxK = slotKey SlotPaneMax key-      seedK = slotKey SlotPaneNext key-      spacing = max 0 (pgSpacing cfg)-      minSize = max 0 (pgMinSize cfg)-      leeway = max 0 (pgLeeway cfg)-      edgeBand = max 0 (pgEdgeBand cfg)-      gutter = spacing + 2 * leeway-  st <- uiIO (getStore ctx)-  (tree0, seed1) <- case lookupTree key st of-    Just t ->-      -- Init seeded the store before the tree existed, so the stored seed-      -- is already above every id in the tree.-      pure (t, fromIntegral (IM.findWithDefault 1 seedK (storeInt st)))-    Nothing -> do-      let seed = max 1 (fromIntegral (IM.findWithDefault 1 seedK (storeInt st)))-          start = Pane seed-      uiIO $-        setStore-          ctx-          ( bumpMirror-              ( st-                  { storeInt = IM.insert seedK (fromIntegral (seed + 1)) (storeInt st)-                  , storeDyn = IM.insert key (toDyn start) (storeDyn st)-                  }-              )-          )-      pure (start, seed + 1)-  mPrev <- uiIO (getPrevRect ctx wid)-  let baseRect = fromMaybe (Rect 0 0 0 0) mPrev-      drag0 = IM.findWithDefault 0 gestK (storeInt st)-      maxPane = validPane tree0 (IM.findWithDefault 0 maxK (storeInt st))-      focus0 = IM.findWithDefault 0 focusK (storeInt st)-      focusedInit = resolveFocus tree0 maxPane (fromIntegral focus0)-      mouse = inputMousePos inp-      (regions, dividers) = layoutNode minSize gutter tree0 baseRect-  changedRef <- uiIO (newIORef False)-  let mGrab = IM.lookup grabK (storePoint st)-      dgi =-        computeDragInfo-          drag0-          (IM.findWithDefault 0 grabK (storeInt st) /= 0)-          DragGeom-            { dgMinSize = minSize-            , dgGutter = gutter-            , dgTree = tree0-            , dgBaseRect = baseRect-            , dgBand = edgeBand-            , dgRegions = regions-            }-          mGrab-          mouse-      dgiShown = dgiActive dgi && dgiMoved dgi && inputMouseDown inp-      -- Keep the committed tree for cancellation and exact drop previews,-      -- but close up the dragged pane's space in the live layout.-      visibleTree = if dgiShown then treeRemovePane (fromIntegral drag0) tree0 else Just tree0-      (visibleRegions, visibleDividers)-        | dgiShown = maybe (M.empty, []) (\t -> layoutNode minSize gutter t baseRect) visibleTree-        | otherwise = (regions, dividers)-      divMap = M.fromList [(diSplitId d, d) | d <- visibleDividers]-      env =-        GridEnv-          { geCtx = ctx-          , geKey = key-          , gePaneScope = IdContext (hashWidgetId wid) 0-          , geCfg = cfg-          , geGutter = gutter-          , geThickness = spacing-          , geMinSize = minSize-          , geLeeway = leeway-          , geRegions = visibleRegions-          , geBaseRect = baseRect-          , geTree = tree0-          , geSeed = seed1-          , geDrag0 = drag0-          , geMax = maxPane-          , geChangedRef = changedRef-          , geMakeCtx = \pid rect dragging ->-              PaneGridCtx-                { pgcPaneId = pid-                , pgcRect = rect-                , pgcMaximized = maxPane == pid-                , pgcDragging = dragging-                , pgcDndActive = dgiMoved dgi-                , pgcSplit = \axis -> splitPane env pid axis-                , pgcClose = closePane env pid-                , pgcMaximize = maximizePane env pid-                , pgcRestore = restorePane env-                }-          }--  -- Root container. Tagged so its solved rect resolves via getPrevRect for-  -- next frame's geometry.-  container NodeContainer (gridRootLayout minSize (pgLayout cfg)) $ do-    tagContainer wid-    if maxPane /= 0-      then void (renderMaxPane env maxPane)-      else do-        rendered <- maybe (pure []) (renderNode env divMap) visibleTree-        runGestures env dividers rendered dgi-        when (dgiShown && rectNonEmpty baseRect) $-          drawDragOverlay env wid rendered (dgiGhost dgi) (fmap fst (dgiZone dgi))-        -- Keyboard focus also rings the focused pane, so the arrow keys show-        -- where they moved; the grid's own ring says the grid holds focus.-        ringPane <- uiIO ((&&) <$> getFocusVisible ctx <*> ((== wid) <$> getFocusId ctx))-        when (ringPane && not dgiShown) $-          forM_ (M.lookup focusedInit visibleRegions) $ \r ->-            uiIO $ registerCustomDrawing ctx wid (contentKey [1, rectX r, rectY r, rectW r, rectH r]) $ \cdc _ ->-              runCanvas (drawStrokeRoundedRect (rectInflate (-2) r) 2 1.5 (themeAccent (cdcTheme cdc)))--  -- Keyboard navigation for the focused grid. Escape restores a maximized-  -- pane unless something earlier in the pass already consumed it (e.g. a-  -- dismissable popup inside a pane); the grid then claims the key so-  -- neither a nested overlay nor the app also acts on it.-  focusedNow <- uiIO (getFocusId ctx)-  when (focusedNow == wid) $ do-    nav <- useKeyNav wid-    let ch = inputChars inp-        cur = focusedInit-    when (knLeft nav) $ moveFocus env cur (-1, 0)-    when (knRight nav) $ moveFocus env cur (1, 0)-    when (knUp nav) $ moveFocus env cur (0, -1)-    when (knDown nav) $ moveFocus env cur (0, 1)-    when (knLeft nav || knRight nav || knUp nav || knDown nav) $-      uiIO (damageWidget ctx wid (DamageInflated 0))-    when (T.any (== 'm') ch) $ maximizePane env cur-    when (T.any (== 'x') ch) $ closePane env cur-    when (inputKeysElem KeyEscape (inputKeys inp)) $ do-      taken <- uiIO (overlayConsumesQuit ctx inp)-      unless taken $ do-        restorePane env-        uiIO (markEscapeConsumed ctx)--  changed <- uiIO (readIORef changedRef)-  stEnd <- uiIO (getStore ctx)-  let treeEnd = lookupTree key stEnd-      maxEnd = maybe 0 (\t -> validPane t (IM.findWithDefault 0 maxK (storeInt stEnd))) treeEnd-      focusEnd =-        maybe-          0-          (\t -> resolveFocus t maxEnd (fromIntegral (IM.findWithDefault 0 focusK (storeInt stEnd))))-          treeEnd-  pure-    PaneGridResponse-      { pgrChanged = changed-      , pgrPaneCount = maybe 0 treeSize treeEnd-      , pgrPanes = maybe [] treePanes treeEnd-      , pgrFocusedPane = focusEnd-      , pgrMaximizedPane = maxEnd-      }---- -------------------------------------------------------------------------------- Layout helpers--- -------------------------------------------------------------------------------gridRootLayout :: Float -> (Layout -> Layout) -> Layout-gridRootLayout minSize f =-  f-    defaultLayout-      { layoutDirection = Column-      , layoutGap = 0-      , layoutPadding = Padding 0 0 0 0-      , layoutWidth = Grow 1-      , layoutHeight = Grow 1-      , layoutMinW = minSize-      , layoutMinH = minSize-      }--sizingLay :: Sizing -> Sizing -> Layout-sizingLay wSiz hSiz =-  defaultLayout-    { layoutDirection = Column-    , layoutPadding = Padding 0 0 0 0-    , layoutGap = 0-    , layoutWidth = wSiz-    , layoutHeight = hSiz-    }---- | Zero-gap, zero-padding, grow-to-fill layout.-fillLay :: Layout-fillLay = sizingLay (Grow 1) (Grow 1)---- | A-side sizing for a split: fixed percent along the main axis. The B side--- grows into the remainder.-splitSideLay :: GridAxis -> Float -> Layout-splitSideLay AxisV p = sizingLay (Percent p) (Grow 1)-splitSideLay AxisH p = sizingLay (Grow 1) (Percent p)--minSized :: Layout -> Float -> Float -> Layout-minSized l minW_ minH_ = l {layoutMinW = minW_, layoutMinH = minH_}---- | The pane content wrapper: fills its cell, never below one minimum pane.-paneLay :: Float -> Layout-paneLay m = minSized fillLay m m---- Percent of the main-axis extent for side A, after min clamping.-splitPct :: Float -> Float -> Float -> Float -> Float -> Float-splitPct spacing avail minA minB ratio-  | avail <= 0 = 50-  | otherwise = splitLength spacing avail minA minB ratio / avail * 100---- -------------------------------------------------------------------------------- Rendering--- -------------------------------------------------------------------------------renderMaxPane :: (Ui :> es) => GridEnv es -> Word64 -> Eff es [RenderedPane]-renderMaxPane env pid =-  renderPane env pid (geBaseRect env) (paneLay (geMinSize env)) False---- | Enter a pane's grid-relative identity scope while leaving the split tree's--- layout scopes intact. Consume one sibling just as 'withKey' does.-withPaneKey :: (Ui :> es) => GridEnv es -> Word64 -> Eff es a -> Eff es a-withPaneKey env pid =-  withIdFrame (\parent -> (parent {siblingId = siblingId parent + 1}, gePaneScope env)) . withKey pid---- | Render one pane's content via 'pgViewPane' under the pane's stable key.-renderPane ::-  (Ui :> es) =>-  GridEnv es ->-  Word64 ->-  Rect ->-  Layout ->-  Bool ->-  Eff es [RenderedPane]-renderPane env pid rect lay dragging =-  withPaneKey env pid $ do-    inp <- askInput-    let ctx = geCtx env-        arena = ctxNodeArena ctx-    start <- uiIO (arenaCount arena)-    let ctxt = geMakeCtx env pid rect dragging-    (view, _) <- containerResponse NodeContainer lay (pgViewPane (geCfg env) pid ctxt)-    -- Press ownership must be checked against previous solved child rects:-    -- ctxActiveId is only finalized after this frame's UI has been built.-    controlHit <--      if not (inputMousePressed inp)-        then pure False-        else uiIO $ do-          end <- arenaCount arena-          let hitFrom idx-                | idx >= end = pure False-                | otherwise = do-                    nt <- getNodeType arena idx-                    hit <--                      if isInteractiveNode nt-                        then do-                          child <- getWidgetId arena idx-                          r <- scrollHitRect ctx child-                          maybe (pure False) (\childRect -> nodeInteractionHit ctx idx childRect (inputMousePos inp)) r-                        else pure False-                    if hit then pure True else hitFrom (idx + 1)-          hitFrom start-    pure [RenderedPane pid view controlHit]--renderNode ::-  (Ui :> es) =>-  GridEnv es ->-  Map Word64 DividerInfo ->-  GridNode ->-  Eff es [RenderedPane]-renderNode env dividers = \case-  Pane pid ->-    renderPane env pid (paneRect env pid) (paneLay (geMinSize env)) (draggingPane env pid)-  Split sid0 ax _ a b ->-    withKey sid0 $ do-      let (wa, ha) = subtreeMin (geMinSize env) (geGutter env) a-          (wb, hb) = subtreeMin (geMinSize env) (geGutter env) b-          mDiv = M.lookup sid0 dividers-          avail = maybe 0 (mainLen ax . diRegion) mDiv-          (mA, mB) = mainMins ax (wa, ha) (wb, hb)-          pct = splitPct (geGutter env) avail mA mB (maybe 0.5 diRatio mDiv)-          aLay = minSized (splitSideLay ax pct) wa ha-          bLay = minSized fillLay wb hb-          inner = do-            a' <- container NodeContainer aLay (renderNode env dividers a)-            dividerWidget env ax-            b' <- container NodeContainer bLay (renderNode env dividers b)-            pure (a' <> b')-      case ax of-        AxisV -> row' fillLay inner-        AxisH -> column' fillLay inner---- | Prev-frame rect of a pane; zero until the pane has been laid out once.-paneRect :: GridEnv es -> Word64 -> Rect-paneRect env pid = fromMaybe (Rect 0 0 0 0) (M.lookup pid (geRegions env))---- | Is this the pane being drag-and-dropped? A resize gesture (negative id)--- wraps to a huge 'Word64' and never matches a pane id.-draggingPane :: GridEnv es -> Word64 -> Bool-draggingPane env pid = fromIntegral (geDrag0 env) == pid---- | The divider: a 'NodeDrawing' spanning the full gutter (visible thickness--- plus the invisible grab halo on each side). Its widget rect covers the whole--- gutter, so the resize cursor and grab apply across the halo; the gutter is--- drawn as a faint rail with the crisp 'geThickness' strip in the middle, so--- the whole interaction space reads as one divider.-dividerWidget :: (Ui :> es) => GridEnv es -> GridAxis -> Eff es ()-dividerWidget env axis = do-  void $-    customWidget-      defaultCustomWidgetSpec-        { widgetLayout = dLay-        , widgetContent = contentKey [if axis == AxisV then 1 else 2, geThickness env, geLeeway env]-        , widgetDraw = \cdc rect -> drawDivider cdc rect axis (geThickness env) (geLeeway env)-        , widgetCursor = Just (const (if axis == AxisV then UiCursorEwResize else UiCursorNsResize))-        }-  where-    dLay = case axis of-      AxisV -> sizingLay (Fixed (geGutter env)) (Grow 1)-      AxisH -> sizingLay (Grow 1) (Fixed (geGutter env))--drawDivider :: CustomDrawContext -> Rect -> GridAxis -> Float -> Float -> SmallArray DrawOp-drawDivider cdc rect axis thickness leeway =-  runCanvas $ do-    let theme = cdcTheme cdc-        panel = themePanel theme-        rail = lerpColor (styleBg panel) (themeSeparator theme) 0.12-        track = separatorTrackColor panel theme-        trackRect = case axis of-          AxisV -> Rect (rectX rect + leeway) (rectY rect) thickness (rectH rect)-          AxisH -> Rect (rectX rect) (rectY rect + leeway) (rectW rect) thickness-    drawRect rect rail-    drawRect trackRect track-    when (cdcHovered cdc || cdcPressed cdc) $ do-      -- Full accent while grabbed; a calmer tint while merely hovering.-      let line-            | cdcPressed cdc = themeAccent theme-            | otherwise = lerpColor (themeAccent theme) (styleBg panel) 0.45-      case axis of-        AxisV ->-          let cx = rectX rect + rectW rect / 2-           in drawStroke (V2 cx (rectY rect)) (V2 cx (rectY rect + rectH rect)) 2 line-        AxisH ->-          let cy = rectY rect + rectH rect / 2-           in drawStroke (V2 (rectX rect) cy) (V2 (rectX rect + rectW rect) cy) 2 line---- | Drag ghost + drop-zone highlight, drawn on top of the grid via a custom--- drawing registered on the grid's root container. Registering on the--- container (instead of adding a flex sibling) keeps the overlay out of the--- layout, so it never squeezes the panes and is clipped to the full grid rect.-drawDragOverlay ::-  (Ui :> es) =>-  GridEnv es ->-  WidgetId ->-  [RenderedPane] ->-  Maybe Rect ->-  Maybe Rect ->-  Eff es ()-drawDragOverlay env wid rendered ghost zone = do-  st <- uiIO (getStore (geCtx env))-  let ctx = geCtx env-      dragPane = fromIntegral (geDrag0 env)-      cached = IM.lookup (slotKey SlotPaneGrab (geKey env)) (storeDyn st) >>= fromDynamic-      title = maybe (fromMaybe "" cached) pvTitle (fmap rpView (find ((== dragPane) . rpPaneId) rendered))-      rectKey = maybe [0, 0, 0, 0, 0] (\(Rect x y w h) -> [1, x, y, w, h])-      key = contentKey (2 : fromIntegral (hash title) : rectKey ghost ++ rectKey zone)-  uiIO $-    registerCustomDrawing ctx wid key (\cdc _ -> drawOverlay (cdcTheme cdc) title ghost zone)---- | A compact, translucent drag indicator leaves the full-size drop preview--- visible. The indicator is offset from the pointer so it cannot obscure aim.-drawOverlay :: Theme -> Text -> Maybe Rect -> Maybe Rect -> SmallArray DrawOp-drawOverlay theme title ghost zone =-  runCanvas $ do-    let accent = themeAccent theme-        win = themeFloatingWindow theme-        panelFill = fadeAlpha accent 48-        panelBorder = fadeAlpha accent 128-        previewFill = fadeAlpha accent 32-        shortTitle = if T.length title > 12 then T.take 11 title <> "…" else title-    forM_ ghost $ \gr -> do-      drawRoundedRect gr 2 panelFill-      drawStrokeRoundedRect gr 2 2 panelBorder-      when (not (T.null title)) $-        drawText (V2 (rectX gr + 6) (rectY gr + 6)) AlignStart AlignTop shortTitle (fadeAlpha (styleFg win) 160)-    forM_ zone $ \zr -> do-      drawRoundedRect zr 2 previewFill-      drawStrokeRoundedRect (rectInflate (-1) zr) 2 2 accent---- -------------------------------------------------------------------------------- Gestures--- --------------------------------------------------------------------------------- | Grid geometry 'computeDragInfo' needs for the current frame.-data DragGeom = DragGeom-  { dgMinSize :: !Float-    -- ^ Per-pane size floor used by the preview layout.-  , dgGutter :: !Float-    -- ^ Layout gutter between panes ('pgSpacing' + 2 * 'pgLeeway').-  , dgTree :: !GridNode-    -- ^ Current split tree.-  , dgBaseRect :: !Rect-    -- ^ Prev-frame rect of the grid's root container.-  , dgBand :: !Float-    -- ^ Thickness of the grid's outer top-level drop band.-  , dgRegions :: !(Map Word64 Rect)-    -- ^ Prev-frame pane regions.-  }---- | Pure drag-and-drop geometry for the current frame. Geometry is computed--- for as long as the gesture id is armed (not just while the button is held),--- so the drop zone is still resolvable on the frame the button is released.--- 'dgBaseRect' is the grid's own rect: its outer band (thickness 'dgBand') is--- a top-level drop zone, and the pointer there restructures the whole grid;--- otherwise the pane under the pointer is the target. Every candidate is--- resolved through 'dropPreview', which simulates the drop and lays the tree--- back out with the grid's real 'dgGutter' and 'dgMinSize', so the--- highlighted rect is the exact region the pane lands in even when removing--- it reshapes the rest of a mixed-split grid.-computeDragInfo :: Int -> Bool -> DragGeom -> Maybe (Float, Float) -> V2 -> DragInfo-computeDragInfo drag0 latched geom mGrab mouse-  | drag0 <= 0 = DragInfo False False Nothing Nothing-  | otherwise =-      let DragGeom{dgMinSize = minSize, dgGutter = gutter, dgTree = tree, dgBaseRect = baseRect, dgBand = band, dgRegions = regions} = geom-          pid = fromIntegral drag0-          mFrom = M.lookup pid regions-          (gx, gy) = fromMaybe (0, 0) mGrab-          moved = latched || case mFrom of-            Just (Rect px py _ _) ->-              let vx = v2X mouse - (px + gx)-                  vy = v2Y mouse - (py + gy)-               in vx * vx + vy * vy > dragThresholdPx * dragThresholdPx-            Nothing -> False-          ghost = case mFrom of-            Just _-              | moved -> Just (Rect (v2X mouse + 12) (v2Y mouse + 12) 112 28)-            _ -> Nothing-          targetRegions = maybe M.empty (\t -> fst (layoutNode minSize gutter t baseRect)) (treeRemovePane pid tree)-          under =-            [ (q, r)-            | (q, r) <- M.toList targetRegions-            , q /= pid-            , rectHit r mouse-            ]-          zone = case topLevelDropTarget band baseRect mouse of-            Just dt -> dropPreview minSize gutter tree pid baseRect dt-            Nothing -> case under of-              (q, r) : _ ->-                let dt = dropTargetForPane r mouse q-                 in dropPreview minSize gutter tree pid baseRect dt-              [] -> Nothing-       in DragInfo True moved ghost zone---- | Apply resize / drag transitions, writing to the widget store.-runGestures ::-  (Ui :> es) =>-  GridEnv es ->-  [DividerInfo] ->-  [RenderedPane] ->-  DragInfo ->-  Eff es ()-runGestures env dividers rendered dgi = do-  ctx <- askContext-  inp <- askInput-  let regions = geRegions env-      mouse = inputMousePos inp-      press = inputMousePressed inp-      down = inputMouseDown inp-      drag0 = geDrag0 env-      busy = drag0 /= 0-      -- diBand already spans spacing + both leeway margins. Inflating it-      -- again steals presses from the neighboring pane, especially headers.-      hitDiv =-        find-          (\d -> rectHit (diBand d) mouse)-          dividers-      -- The pane whose pick rect (or, when 'pvDraggable', whole region) is-      -- under the pointer.-      pickHit =-        listToMaybe-          [ p-          | pane <- rendered-          , let p = rpPaneId pane-                v = rpView pane-          , maybe False (`rectHit` mouse) (pvDragPick v)-              || (pvDraggable v && maybe False (`rectHit` mouse) (M.lookup p regions))-          ]-      gestK = slotKey SlotPaneGest (geKey env)-      grabK = slotKey SlotPaneGrab (geKey env)-  menu <- uiIO (getMenuPointerGesture ctx)-  -- A press arms the gesture slot (negative split id for a resize, pane id-  -- for a drag) together with its start state in one store write. The resize-  -- start keeps the divider's ratio and the pointer's main-axis coordinate so-  -- drag frames move the divider by delta instead of snapping it to the-  -- pointer; the drag start keeps the title and the grab offset (mouse - pane-  -- origin) for the drag threshold.-  when (press && not busy && not menu && not (any rpControlHit rendered)) $ do-    case hitDiv of-      Just d ->-        storeWrite env True $ \st -> st-          { storeInt = IM.insert gestK (negate (fromIntegral (diSplitId d))) (storeInt st)-          , storePoint = IM.insert (slotKey SlotPaneResize (geKey env)) (diRatio d, mouseMain d mouse) (storePoint st)-          }-      Nothing ->-        forM_ pickHit $ \pid -> do-          let title = maybe "" (pvTitle . rpView) (find ((== pid) . rpPaneId) rendered)-              (gx, gy) = maybe (0, 0) (\(Rect px py _ _) -> (v2X mouse - px, v2Y mouse - py)) (M.lookup pid regions)-          storeWrite env True $ \st -> st-            { storeDyn = IM.insert grabK (toDyn title) (storeDyn st)-            , storeInt = IM.insert gestK (fromIntegral pid) (IM.delete grabK (storeInt st))-            , storePoint = IM.insert grabK (gx, gy) (storePoint st)-            }-  when (drag0 < 0 && down) $ do-    let sid = fromIntegral (negate drag0)-    forM_ (find ((== sid) . diSplitId) dividers) $ \d -> do-      st <- uiIO (getStore ctx)-      let (ratio0, main0) =-            IM.findWithDefault (diRatio d, mouseMain d mouse) (slotKey SlotPaneResize (geKey env)) (storePoint st)-          -- The ratio shares out the region minus the divider gutter.-          usable = mainLen (diAxis d) (diRegion d) - geGutter env-          r0 =-            if usable <= 0-              then ratio0-              else ratio0 + (mouseMain d mouse - main0) / usable-          r' = clampTreeRatio (geTree env) sid (diRegion d) (geGutter env) (geMinSize env) r0-       in putTree env (Just (treeSetRatio sid r' (geTree env)))-  when (drag0 < 0 && not down) $ writeGest env 0-  -- Keep the loop at the display cadence while a pane is being dragged: the-  -- ghost follows the pointer, and without a dirty flag the debug HUD's slow-  -- refresh paces the whole frame (4 fps). Window / scroll / resize drags mark-  -- dirty every frame for the same reason.-  when (drag0 > 0 && down) $ uiIO (markDirty ctx)-  when (drag0 > 0 && down && dgiMoved dgi) $-    storeWrite env False $ \st -> st {storeInt = IM.insert (slotKey SlotPaneGrab (geKey env)) 1 (storeInt st)}-  -- A drop clears the gesture and, when it moved the pane, stores the new-  -- tree, seed and focus in the same write.-  when (drag0 > 0 && not down) $ do-    let moved = fromIntegral drag0-        dropped-          | dgiMoved dgi = dgiZone dgi >>= \(_, dt) -> treeMovePane moved (geSeed env) dt (geTree env)-          | otherwise = Nothing-    storeWrite env True $ \st -> case dropped of-      Nothing -> st {storeInt = IM.delete gestK (storeInt st)}-      Just t' ->-        st-          { storeDyn = IM.insert (geKey env) (toDyn t') (storeDyn st)-          , storeInt =-              IM.insert (slotKey SlotPaneNext (geKey env)) (fromIntegral (geSeed env + 1)) $-                IM.insert (slotKey SlotPaneFocus (geKey env)) (fromIntegral moved) $-                  IM.delete gestK (storeInt st)-          }-    when (isJust dropped) (markChanged env)--mouseMain :: DividerInfo -> V2 -> Float-mouseMain d mouse = case diAxis d of-  AxisV -> v2X mouse-  AxisH -> v2Y mouse---- -------------------------------------------------------------------------------- Keyboard navigation--- -------------------------------------------------------------------------------moveFocus ::-  (Ui :> es) =>-  GridEnv es ->-  Word64 ->-  (Float, Float) ->-  Eff es ()-moveFocus env cur dir =-  case neighborPane (geRegions env) cur dir of-    Just pid -> putPaneSlot False SlotPaneFocus env pid-    Nothing -> pure ()--neighborPane :: Map Word64 Rect -> Word64 -> (Float, Float) -> Maybe Word64-neighborPane regions cur (dx, dy) =-  case M.lookup cur regions of-    Nothing -> Nothing-    Just curR ->-      let (cx, cy) = centerOf curR-          scored =-            [ (pid, s)-            | (pid, r) <- M.toList regions-            , pid /= cur-            , rectNonEmpty r-            , let (px, py) = centerOf r-                  vx = px - cx-                  vy = py - cy-                  dotv = vx * dx + vy * dy-            , dotv > 0-            , let s = abs (vx * dy - vy * dx) / dotv-            ]-       in case scored of-            [] -> Nothing-            _ -> Just (fst (minimumBy (comparing snd) scored))--centerOf :: Rect -> (Float, Float)-centerOf r = (rectX r + rectW r / 2, rectY r + rectH r / 2)---- -------------------------------------------------------------------------------- Store mutation helpers--- -------------------------------------------------------------------------------splitPane :: (Ui :> es) => GridEnv es -> Word64 -> GridAxis -> Eff es Word64-splitPane env pid axis = do-  let splitId = geSeed env-      newPane = geSeed env + 1-  putTree env (Just (treeSplit pid splitId axis False newPane (geTree env)))-  putSeed env (geSeed env + 2)-  putPaneSlot False SlotPaneFocus env newPane-  pure newPane--closePane :: (Ui :> es) => GridEnv es -> Word64 -> Eff es ()-closePane env pid =-  case treeRemovePane pid (geTree env) of-    Nothing -> putTree env Nothing-    Just t' -> do-      putTree env (Just t')-      when (geMax env == pid) (putPaneSlot True SlotPaneMax env 0)--maximizePane :: (Ui :> es) => GridEnv es -> Word64 -> Eff es ()-maximizePane env pid = do-  let v = if geMax env == pid then 0 else pid-  putPaneSlot True SlotPaneMax env v-  -- Maximizing hides the dividers and every other pane, so an armed drag or-  -- resize gesture could never complete; cancel it instead of leaking it.-  when (v /= 0) (writeGest env 0)--restorePane :: (Ui :> es) => GridEnv es -> Eff es ()-restorePane env = putPaneSlot True SlotPaneMax env 0---- | One store round-trip. @mirror@ bumps the mirror generation so the--- running frame rebuilds its UI and layout with the new value (see--- 'NanoUI.Frame'); the store write itself wakes the renderer.-storeWrite ::-  (Ui :> es) =>-  GridEnv es ->-  Bool ->-  (WidgetStore -> WidgetStore) ->-  Eff es ()-storeWrite env mirror f =-  uiIO $ modifyStore (geCtx env) ((if mirror then bumpMirror else id) . f)---- | Flag 'pgrChanged' for this frame.-markChanged :: (Ui :> es) => GridEnv es -> Eff es ()-markChanged env = uiIO (writeIORef (geChangedRef env) True)---- | Structural change (mirror + 'pgrChanged'): store the tree, or remove it--- entirely when the last pane was closed. The pane-id seed keeps counting--- across a removal, so the re-seeded pane gets a fresh id and state keyed by--- pane id never collides with a closed pane's state.-putTree :: (Ui :> es) => GridEnv es -> Maybe GridNode -> Eff es ()-putTree env mTree = do-  storeWrite env True $ \st ->-    st {storeDyn = maybe (IM.delete k) (IM.insert k . toDyn) mTree (storeDyn st)}-  markChanged env-  where-    k = geKey env---- | Gesture slot: 0 none, positive = dragged pane id, negative = resized--- split id.-writeGest :: (Ui :> es) => GridEnv es -> Int -> Eff es ()-writeGest env n =-  storeWrite env True $ \st ->-    st-      { storeInt =-          if n == 0-            then IM.delete (slotKey SlotPaneGest (geKey env)) (storeInt st)-            else IM.insert (slotKey SlotPaneGest (geKey env)) n (storeInt st)-      }---- | Write a pane-id slot (maximized or focused pane) when it differs,--- bumping the mirror; @structural@ also flags 'pgrChanged'.-putPaneSlot :: (Ui :> es) => Bool -> Slot -> GridEnv es -> Word64 -> Eff es ()-putPaneSlot structural slot env v = do-  let k = slotKey slot (geKey env)-      n = fromIntegral v-  st <- uiIO (getStore (geCtx env))-  when (IM.findWithDefault 0 k (storeInt st) /= n) $ do-    storeWrite env True (\st' -> st' {storeInt = IM.insert k n (storeInt st')})-    when structural (markChanged env)---- | Advance the next-id seed ('SlotPaneNext').-putSeed :: (Ui :> es) => GridEnv es -> Word64 -> Eff es ()-putSeed env v =-  storeWrite env False $ \st ->-    st {storeInt = IM.insert (slotKey SlotPaneNext (geKey env)) (fromIntegral v) (storeInt st)}+-- | Interactive pane grid with resizable dividers, modeled on iced's+-- @PaneGrid@. The layout is a binary split tree ('GridNode') kept in the+-- widget store.+--+-- 'pgViewPane' renders each pane and receives a 'PaneGridCtx' with actions+-- to split, close, maximize or restore it. Drag a divider to resize. Drag a+-- pane by its handle ('paneDragHandle') onto another pane (center swaps,+-- edge splits) or onto the grid's outer edge (new top-level split). While+-- the grid has focus, arrow keys move between panes, @m@ maximizes, @x@+-- closes and Escape restores. 'pgrTree' reads the tree back and 'pgTree'+-- replaces it.+--+-- During a drag the grid is laid out as the drop would leave it, with the+-- landing slot empty and highlighted. Releasing commits exactly that tree.+-- Releasing outside the grid cancels the drag.+--+-- For external sources, 'pgrDropTarget' reports a destination and preview+-- rectangle. The application resolves target priority and calls+-- 'commitPaneDrop' only when it chooses to create a pane.+module NanoUI.Widgets.PaneGrid+  ( -- * Split tree model+    GridAxis (..)+  , CenterDropMode (..)+  , GridNode (..)+  , PaneTree (..)+  , validateGridTree+  , treePanes+  , treeRemovePane+  , treeSplit+  , treeAddTab+  , treeSelectTab++    -- * Configuration and pane context+  , PaneGridConfig (..)+  , defaultPaneGridConfig+  , PaneGridCtx (pgcPaneId, pgcRect, pgcMaximized, pgcInTabs, pgcDragging, pgcDndActive, pgcSplit, pgcClose, pgcMaximize, pgcRestore)+  , PaneView (..)+  , PaneGridResponse (..)++    -- * External drag and drop+  , PaneEdge (..)+  , PaneDropLocation (..)+  , PaneGridDrop+  , pgdLocation+  , pgdRect+  , pgdPane+  , commitPaneDrop++    -- * Widgets+  , paneGrid+  , paneDragHandle+  ) where++import Control.Monad (foldM, forM, forM_, unless, void, when)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Hashable (hash)+import Data.List (find)+import Data.Set qualified as S+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as M+import Data.Maybe (fromMaybe, isJust, listToMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word64)+import NanoUI.Internal.Context+import NanoUI.Internal.Font (FontMetrics (..), buttonPadding)+import NanoUI.Internal.Input+import NanoUI.Internal.Monad (NanoUI, askContext, askInput, damageWidgetNow, focusedWidget, freshWidget, lastRect, releaseFocus, liftIO, takeEscape, uiTheme, whenM, withIdFrame, withKey)+import NanoUI.Internal.Id (IdContext (..), WidgetId, hashWidgetId, scopeIdContext)+import NanoUI.Internal.Var (bindVarOn, requestRerun)+import NanoUI.Internal.Var.Types (Var)+import NanoUI.Internal.Layout.ScrollGeometry (padContentClip)+import NanoUI.Internal.Shortcut qualified as Shortcut+import NanoUI.Internal.Store (fieldGrid, insertSlot, lookupSlot)+import NanoUI.Internal.Store.Types (GridState (..), Gesture (..))+import NanoUI.Internal.Style+import NanoUI.Internal.Types+import NanoUI.Internal.Widgets.Behavior (KeyNav (..), dragPressLive, pastDragThreshold, recordDragPress, useKeyNav)+import NanoUI.Internal.Widgets.Cursor (withCursorShape)+import NanoUI.Widgets.Custom+import NanoUI.Internal.Widgets.Button (buttonWith')+import NanoUI.Internal.Widgets.Display (box)+import NanoUI.Internal.Widgets.Layout (column', columnWith, labelWith, row', rowWith, rowWith', separator)+import NanoUI.Internal.Layout.Arena (NodeType (..), arenaCount)+import NanoUI.Internal.Widgets.Node+import NanoUI.Internal.Widgets.Shortcut (shortcutOnce)+import NanoUI.Internal.Widgets.SplitPane++-- -----------------------------------------------------------------------------+-- Public API+-- -----------------------------------------------------------------------------++-- | Ownership mode for the split tree. 'InitialTree' seeds widget-internal+-- state on first mount; 'ControlledTree' reads the tree from a 'Var' each pass+-- and mutates it in place when panes change. In either mode 'Nothing'+-- represents an empty workspace, including after the last pane is closed.+data PaneTree = InitialTree !(Maybe GridNode) | ControlledTree !(Var (Maybe GridNode))++-- | Validate a persisted/application-built tree before using it. Pane and split+-- ids share one namespace; ratios must be finite and between zero and one.+-- 'paneGrid' also validates any tree it adopts and throws an 'IOError'+-- ('userError') from the view for an invalid one, which ends the session+-- unless the view catches it ('NanoUI.Monad.catchView'). Validate a tree+-- that comes from a file or the user with this first.+validateGridTree :: GridNode -> Either String ()+validateGridTree tree = void (walk S.empty tree)+  where+    insertId seen ident+      | ident == 0 || ident >= 2 ^ (63 :: Int) = Left "pane grid: ids must be in [1, 2^63)"+      | S.member ident seen = Left "pane grid: duplicate pane or split id"+      | otherwise = Right (S.insert ident seen)+    walk seen (Pane ident) = insertId seen ident+    walk seen (PaneTabs gid pids active)+      | null pids = Left "pane grid: tab group must not be empty"+      | notElem active pids = Left "pane grid: active tab must belong to its tab group"+      | otherwise = do+          s1 <- insertId seen gid+          foldM insertId s1 pids+    walk seen (Split ident _ ratio left right) = do+      next <- insertId seen ident+      if isNaN ratio || isInfinite ratio || ratio < 0 || ratio > 1+        then Left "pane grid: ratio must be finite and in [0, 1]"+        else walk next left >>= (`walk` right)++-- | Configuration for a pane grid.+data PaneGridConfig = PaneGridConfig+  { pgLayout :: !(Layout -> Layout)+    -- ^ Layout modifier for the grid container (default 'id'); pass+    -- @fillW . fillH@ to fill the parent area.+  , pgSpacing :: !Float+    -- ^ Gutter between panes per split level (default 4).+  , pgMinSize :: !Float+    -- ^ Minimum size in logical pixels any pane may shrink to (default 40).+  , pgLeeway :: !Float+    -- ^ Extra grab margin on each side of a divider (default 6). The divider's+    -- gutter is 'pgSpacing' plus this margin on both sides. The whole gutter+    -- grabs and shows the resize cursor; only 'pgSpacing' is drawn solid.+  , pgEdgeBand :: !Float+    -- ^ Width of the drop zone along the grid's outer edge (default 20). A+    -- drop there wraps the tree in a new top-level split with the dragged+    -- pane on that side.+  , pgPreserveDragSize :: !Bool+    -- ^ Keep the dragged pane's size along its old parent split's axis,+    -- swapping width and height when the drop changes orientation, within the+    -- available space and minimum sizes (default 'False': the target splits+    -- evenly). Center swaps are unaffected.+  , pgFixedPanes :: !(Word64 -> Bool)+    -- ^ Panes that keep their size when the grid is resized (default+    -- @const False@). A pinned pane keeps its extent along its parent split's+    -- axis and the other side absorbs the change. It still yields to its+    -- neighbor's minimum, and its divider can still be dragged. Only that one+    -- split is pinned: a pinned sidebar keeps its width, but its row's height+    -- still follows the grid.+  , pgTree :: !PaneTree+    -- ^ 'InitialTree' seeds internally owned state once. 'ControlledTree'+    -- keeps the arrangement in a 'Var': the grid mutates it on each edit, and a+    -- tree written to it replaces the arrangement, restores a maximized pane+    -- and cancels any gesture on the old one. Both modes permit an empty grid.+    --+    -- Allocate @arrangement <- newVar (Just startLayout)@ during setup, then:+    --+    -- > resp <- paneGrid cfg {pgTree = ControlledTree arrangement}+    -- > whenM (button "Reset layout") (writeVar arrangement (Just startLayout))+    --+    -- Closing the last pane leaves the grid empty until the caller supplies+    -- another controlled tree or changes the grid's widget identity.+    --+    -- Pane and split ids are the caller's: unique within the tree, from 1 to+    -- below @2^63@ (0 means "none"). Panes the grid creates later get higher+    -- ids. Ratios apply from the first frame, and pinned panes keep the size+    -- their ratio gives them:+    --+    -- > pgTree = InitialTree (Just (Split 3 AxisV 0.25 (Pane 1) (Pane 2)))+  , pgDividerColor :: !(Maybe Color)+    -- ^ The color of the gutters between panes (default 'Nothing': a faint+    -- tint of the panel color with a line down the middle from+    -- 'themeSeparator'). The hover and drag highlight is drawn over it.+  , pgFocusable :: !Bool+    -- ^ Whether the grid is a Tab stop whose arrow, @m@, @x@ and Escape keys+    -- act on its panes (default 'True'). Turn it off when pane content needs+    -- those keys.+  , pgCenterDrop :: !CenterDropMode+    -- ^ Whether dropping a pane onto the center of another swaps them+    -- ('CenterSwap', the default) or merges them into a native 'PaneTabs' stack+    -- ('CenterTab').+  , pgTabTitle :: !(Word64 -> Text)+    -- ^ Title shown on native 'PaneTabs' headers for a pane id (default+    -- @"Pane <id>"@), and used as the pane label when dragging from a tab.+  , pgViewTab :: !(Maybe (Word64 -> Bool -> NanoUI ()))+    -- ^ Optional custom renderer for one tab's label area in a 'PaneTabs' strip,+    -- given the pane id and whether it is the active tab. When 'Nothing'+    -- (default), renders 'pgTabTitle' truncated in the middle.+  , pgClosableTabs :: !Bool+    -- ^ Whether native 'PaneTabs' headers include a close button (default 'True').+  , pgViewPane :: !(Word64 -> PaneGridCtx -> NanoUI PaneView)+    -- ^ Renders the content of one pane. Each pane is sized by its split ratio+    -- regardless of content size, clipping overflow.+  }++-- | Default spacing and drag margins with empty pane bodies. Set 'pgViewPane'+-- to render application content and 'pgLayout' to constrain the grid.+defaultPaneGridConfig :: PaneGridConfig+defaultPaneGridConfig =+  PaneGridConfig+    { pgLayout = id+    , pgSpacing = 4+    , pgMinSize = 40+    , pgLeeway = 6+    , pgEdgeBand = 20+    , pgPreserveDragSize = False+    , pgFixedPanes = const False+    , pgTree = InitialTree (Just (Pane 1))+    , pgDividerColor = Nothing+    , pgFocusable = True+    , pgCenterDrop = CenterSwap+    , pgTabTitle = \pid -> "Pane " <> T.pack (show pid)+    , pgViewTab = Nothing+    , pgClosableTabs = True+    , pgViewPane = \_ _ -> pure (PaneView "" False)+    }++-- | Per-pane context and callbacks passed to 'pgViewPane'.+data PaneGridCtx = PaneGridCtx+  { pgcPaneId :: !Word64+  , pgcRect :: !Rect+    -- ^ This pane's screen rect from the previous frame. Zero until laid+    -- out, the grid's content rect while maximized, and the previewed rect+    -- during a drop.+  , pgcMaximized :: !Bool+    -- ^ True when this pane currently fills the whole grid.+  , pgcInTabs :: !Bool+    -- ^ True when this pane is rendered inside a native 'PaneTabs' stack, so+    -- 'pgViewPane' can omit its own title bar and avoid duplicate headers.+  , pgcDragging :: !Bool+    -- ^ True while this pane's drag is armed. Once past the drag threshold,+    -- the pane is not rendered until release.+  , pgcDndActive :: !Bool+    -- ^ True while any pane drag-and-drop gesture is in progress.+  , pgcSplit :: !(GridAxis -> NanoUI Word64)+    -- ^ Split this pane along the axis; returns the new pane id.+  , pgcClose :: !(NanoUI ())+    -- ^ Close this pane; its sibling takes its space.+  , pgcMaximize :: !(NanoUI ())+    -- ^ Make this pane fill the grid, or restore it if it already does.+  , pgcRestore :: !(NanoUI ())+    -- ^ Restore the maximized pane, if any, to its place in the grid.+  , pgcHandle :: !(IORef (Maybe Rect))+    -- ^ Where the pane's 'paneDragHandle' was laid out last frame.+  }++-- | How a pane can be dragged this frame. 'pgViewPane' draws all of the+-- pane's content, including any title bar.+data PaneView = PaneView+  { pvTitle :: !Text+    -- ^ Label shown (abbreviated to fit) on the compact drag indicator.+  , pvDraggable :: !Bool+    -- ^ A press anywhere in the pane not taken by an interactive child or a+    -- scrollbar starts a drag. Without it, only a press on the pane's+    -- 'paneDragHandle' does, and a pane with neither cannot be moved.+  }+  deriving (Eq, Show)++-- | The grid's state after this frame, including pane actions and keys+-- handled during it. The layout reflects them from the next frame.+data PaneGridResponse = PaneGridResponse+  { pgrChanged :: !Bool+    -- ^ Any structural or maximize change happened this frame, including+    -- each step of a divider drag.+  , pgrCommitted :: !Bool+    -- ^ The split tree changed and nothing is being dragged: a divider or a+    -- pane was let go after moving, or a split or close ran. The time to+    -- save 'pgrTree'. Not set for a maximize or restore, which leave the+    -- tree as it is, nor for a tree the caller passed in 'pgTree'.+  , pgrTree :: !(Maybe GridNode)+    -- ^ The split tree, 'Nothing' once the last pane has been closed.+  , pgrPaneCount :: !Int+    -- ^ Number of panes (0 once the last pane has been closed).+  , pgrPanes :: ![Word64]+    -- ^ Live pane ids, depth-first.+  , pgrFocusedPane :: !Word64+    -- ^ Focused pane id, 0 when the grid has no panes.+  , pgrMaximizedPane :: !Word64+    -- ^ Maximized pane id, 0 when none.+  , pgrDropTarget :: !(Maybe PaneGridDrop)+    -- ^ Destination at the pointer, independent of any drag. Pane edges yield+    -- 'BesidePane', outer grid margins yield 'OutsideGrid', and pane centers+    -- yield 'IntoTabs' when 'pgCenterDrop' is 'CenterTab' (or 'Nothing' when+    -- 'CenterSwap'). Gutters, covered/clipped areas, maximization, and internal+    -- gestures yield 'Nothing'. Resolve target priority before calling+    -- 'commitPaneDrop'.+  }+  deriving (Eq, Show)++-- | The side of a pane, or of the whole grid, that a new pane goes on.+data PaneEdge = PaneLeft | PaneRight | PaneAbove | PaneBelow+  deriving (Eq, Show)++-- | Split beside one pane, merge into a pane's tab group, or split around the+-- whole grid.+data PaneDropLocation+  = BesidePane !Word64 !PaneEdge+  | IntoTabs !Word64+  | OutsideGrid !PaneEdge+  deriving (Eq, Show)++-- | A destination and its proposed new pane rectangle. Querying it neither+-- paints a preview nor changes the grid. Keep it within the current context;+-- commits reject an already-used target or a changed grid snapshot.+data PaneGridDrop = PaneGridDrop !PaneDropLocation Rect !Word64 !WidgetId !GridState GridNode+  deriving (Eq, Show)++-- | Where the new pane would go: beside a pane, into a pane's tab group, or+-- around the whole grid.+pgdLocation :: PaneGridDrop -> PaneDropLocation+pgdLocation (PaneGridDrop location _ _ _ _ _) = location++-- | Preview rectangle in window coordinates, laid out only when read.+pgdRect :: PaneGridDrop -> Rect+pgdRect (PaneGridDrop _ rect _ _ _ _) = rect++-- | Pane under the pointer, also at outer edges; use it to reject destinations.+pgdPane :: PaneGridDrop -> Word64+pgdPane (PaneGridDrop _ _ pane _ _ _) = pane++-- | Insert and focus a fresh pane at an accepted destination. Returns its id+-- and the committed tree, or Nothing if the grid changed since the target+-- was obtained. The application decides when to call this (normally on+-- DragReleased), assigns the content, and saves the returned tree if controlled.+-- The earlier 'PaneGridResponse' remains a pre-commit snapshot.+commitPaneDrop :: PaneGridDrop -> NanoUI (Maybe (Word64, GridNode))+commitPaneDrop (PaneGridDrop _ _ _ wid expected tree) = do+  ctx <- askContext+  let key = intKey wid+      pane = gsSeed expected + 1+  current <- lookupSlot fieldGrid key <$> liftIO (getStore ctx)+  if current /= Just expected+    then pure Nothing+    else do+      liftIO . modifyStore ctx . insertSlot fieldGrid key $+        expected {gsTree = Just tree, gsSeed = pane + 1, gsFocus = pane}+      pure (Just (pane, tree))++-- -----------------------------------------------------------------------------+-- Internal state+-- -----------------------------------------------------------------------------++data RenderedPane = RenderedPane+  { rpPaneId :: !Word64+  , rpView :: !PaneView+  , rpControlHit :: !Bool+  , rpHandle :: !(Maybe Rect)+  , rpIsTab :: !Bool+  }++-- | Per-frame shared environment.+data GridEnv = GridEnv+  { geCtx :: !Context+  , geKey :: !Int+  , gePaneScope :: !IdContext+    -- ^ Pane ids are rooted at the grid, not the split tree, so rearranging+    -- splits keeps pane state.+  , geCfg :: !PaneGridConfig+  , geGutter :: !Float+  , geMinSize :: !Float+  , geRegions :: !(Map Word64 Rect)+    -- ^ Prev-frame pane regions; drives hit testing and 'pgcRect'.+  , geState :: !GridState+    -- ^ The state this frame was built from.+  , geLifted :: !Bool+    -- ^ The dragged pane is lifted out: not rendered, and its slot left+    -- empty in a drop preview.+  , geMaxPane :: !Word64+  , geDragMoved :: !Bool+  }++-- -----------------------------------------------------------------------------+-- Tree + focus state+-- -----------------------------------------------------------------------------++-- | The maximized pane (0 = none) and the focused pane of a state over its+-- tree. A stored pane id counts while the pane still exists; a maximized pane+-- has the focus, and with no stored focus the first pane does.+paneFocus :: GridNode -> GridState -> (Word64, Word64)+paneFocus tree g = (maxPane, focus)+  where+    maxPane = if paneExist tree (gsMax g) then gsMax g else 0+    focus+      | maxPane /= 0 = maxPane+      | paneExist tree (gsFocus g) = gsFocus g+      | otherwise = fromMaybe 1 (listToMaybe (treePanes tree))++-- -----------------------------------------------------------------------------+-- Entry point+-- -----------------------------------------------------------------------------++-- | Stateful split-pane workspace with draggable tabs and dividers. Keep its+-- widget identity stable; pane callbacks receive actions for splits, closes,+-- and maximization through 'PaneGridCtx'.+paneGrid :: PaneGridConfig -> NanoUI PaneGridResponse+paneGrid cfg = case pgTree cfg of+  InitialTree t -> paneGridCore cfg False t+  -- The grid draws the tree it was given, so a change shows on a rerun.+  ControlledTree v -> bindVarOn Conservative pgrTree v (paneGridCore cfg True)++paneGridCore :: PaneGridConfig -> Bool -> Maybe GridNode -> NanoUI PaneGridResponse+paneGridCore cfg controlled given = do+  (wid, ctx) <- freshWidget+  inp <- askInput+  -- If Tab focus was turned off, drop any focus the grid still holds.+  if pgFocusable cfg then liftIO (registerFocusable ctx wid) else releaseFocus wid+  let key = intKey wid+      spacing = max 0 (pgSpacing cfg)+      minSize = max 0 (pgMinSize cfg)+      leeway = max 0 (pgLeeway cfg)+      edgeBand = max 0 (pgEdgeBand cfg)+      gutter = spacing + 2 * leeway+  store0 <- liftIO (getStore ctx)+  let stored = lookupSlot fieldGrid key store0+  -- A gesture lasts only under the press it started with ('runGestures'),+  -- so one whose release the grid did not see is over.+  live <- case stored of+    Just s | gsGesture s /= NoGesture -> liftIO (dragPressLive ctx key store0)+    _ -> pure True+  let adopt+        | controlled = maybe True ((/= given) . gsTree) stored+        | otherwise = maybe True (const False) stored+  when adopt $ forM_ given $ \t ->+    either (liftIO . fail) pure (validateGridTree t)+  Rect ox oy ow oh <- fromMaybe (Rect 0 0 0 0) <$> lastRect wid+  let lay = pgLayout cfg (paneLay minSize)+      -- The panes share the grid's content box, inside its padding.+      baseRect = padContentClip ox oy ow oh (layoutPadding lay)+      st = fromMaybe (GridState Nothing 1 0 0 Nothing NoGesture) stored+      -- An adopted tree replaces the old one whole: neither its maximized+      -- pane nor its gesture carries over.+      started+        | adopt = st {gsTree = given, gsSeed = max (gsSeed st) (maybe 1 ((+ 1) . treeMaxId) given), gsMax = 0, gsGesture = NoGesture}+        | not live = st {gsGesture = NoGesture}+        | otherwise = st+      curSpan = (rectW baseRect, rectH baseRect)+      -- On a size change, re-ratio pinned panes' splits before layout. A move+      -- or a first fit needs no reflow.+      reflow tree0 = case gsSpan started of+        Just (pw, ph)+          | (pw, ph) /= curSpan+          , any (pgFixedPanes cfg) (treePanes tree0) ->+              reflowFixed (pgFixedPanes cfg) minSize gutter (baseRect {rectW = pw, rectH = ph}) baseRect tree0+        _ -> tree0+      arrangement = reflow <$> gsTree started+      gs = started {gsTree = arrangement, gsSpan = Just curSpan}+  when (Just gs /= stored) $ liftIO (modifyStore ctx (insertSlot fieldGrid key gs))+  let (maxPane, focused) = maybe (0, 0) (`paneFocus` gs) arrangement+      mouse = inputMousePos inp+      (regions, dividers) = maybe (M.empty, []) (\t -> layoutNode minSize gutter t baseRect) arrangement+      -- Drop geometry, computed while the drag is armed so the release frame+      -- can still resolve it. The target is the outer edge band, else the+      -- pane nearest the pointer, else nothing outside the grid. Hit tests+      -- use the grid without the dragged pane, not the on-screen preview, so+      -- showing the preview cannot change the target. 'dropPreviewTreeSized'+      -- lays out the result of the drop.+      (dragMoved, dragZone, remaining) = case (arrangement, gsGesture gs) of+        (Just tree, Drag pid press moved0 _) ->+          let mFrom = M.lookup pid regions+              moved = moved0 || pastDragThreshold press mouse+              rest = treeRemovePane pid tree+              targetRegions = maybe M.empty (\t -> fst (layoutNode minSize gutter t baseRect)) rest+              preview = dropPreviewTreeSized (if pgPreserveDragSize cfg then mFrom else Nothing) minSize gutter tree pid (gsSeed gs) baseRect+              zone = case topLevelDropTarget edgeBand baseRect mouse of+                Just dt -> preview dt+                Nothing+                  | rectContains baseRect mouse ->+                      nearestPane targetRegions mouse >>= \(q, r) -> preview (dropTargetForPaneWith (pgCenterDrop cfg) r mouse q)+                  | otherwise -> Nothing+           in (moved, zone, rest)+        _ -> (False, Nothing, Nothing)+      lifted = dragMoved && heldIn MouseLeft inp+      -- The store keeps the committed tree so a drag can be canceled. The+      -- screen shows the post-drop tree with an empty slot, or the tree+      -- without the dragged pane when there is no target.+      (visibleTree, (visibleRegions, visibleDividers))+        | not lifted = (arrangement, (regions, dividers))+        | Just dp <- dragZone = (Just (dpTree dp), (dpRegions dp, dpDividers dp))+        | otherwise = (remaining, maybe (M.empty, []) (\t -> layoutNode minSize gutter t baseRect) remaining)+      env =+        GridEnv+          { geCtx = ctx+          , geKey = key+          , gePaneScope = scopeIdContext (hashWidgetId wid)+          , geCfg = cfg+          , geGutter = gutter+          , geMinSize = minSize+          , geRegions = visibleRegions+          , geState = gs+          , geLifted = lifted+          , geMaxPane = maxPane+          , geDragMoved = dragMoved+          }++  -- Tagged so next frame reads the grid's rect.+  container NodeContainer lay $ do+    tagContainer wid+    if maxPane /= 0+      then void (renderPane env False maxPane baseRect)+      else do+        rendered <- maybe (pure []) (\t -> renderNode env (M.fromList [(diSplitId d, d) | d <- visibleDividers]) t (buildMinTree (geMinSize env) (geGutter env) t)) visibleTree+        runGestures wid env dividers rendered dragMoved dragZone+        -- The indicator follows the pointer on the grid's own drawing, which+        -- nothing else damages, so the grid repaints while a pane is lifted.+        when (lifted && rectNonEmpty baseRect) $ do+          drawDragOverlay env wid mouse (dpRect <$> dragZone)+          damageWidgetNow wid DamageSelf+        -- Draw an inner focus ring on the active pane in addition to the+        -- grid's outer focus ring.+        ringPane <- liftIO ((&&) <$> getFocusVisible ctx <*> ((== wid) <$> getFocusId ctx))+        when (ringPane && not lifted) $+          forM_ (M.lookup focused visibleRegions) $ \r ->+            liftIO $ registerCustomDrawing ctx wid (contentKey [1, rectX r, rectY r, rectW r, rectH r]) $ \cdc _ ->+              runCanvasFor cdc (drawStrokeRoundedRect (rectInflate (-2) r) 2 1.5 (themeAccent (cdcTheme cdc)))++  when (pgFocusable cfg) $ handleGridKeys wid env maxPane focused+  end <- fromMaybe gs . lookupSlot fieldGrid key <$> liftIO (getStore ctx)+  dropTarget <- liftIO (resolveExternalDrop env wid baseRect mouse end)+  let (maxEnd, focusEnd) = maybe (0, 0) (`paneFocus` end) (gsTree end)+      -- A divider drag moves the tree on the frames it is held, so the frame+      -- that lets it go compares with the ratio it was pressed at.+      resized = case gsGesture gs of+        Resize sid ratio0 _ -> (treeSetRatio sid ratio0 <$> gsTree gs) /= gsTree gs+        _ -> False+  pure+    PaneGridResponse+      { pgrChanged = gsTree end /= gsTree gs || gsMax end /= gsMax gs+      , pgrCommitted = gsGesture end == NoGesture && (gsTree end /= gsTree gs || resized)+      , pgrTree = gsTree end+      , pgrPaneCount = maybe 0 treeSize (gsTree end)+      , pgrPanes = maybe [] treePanes (gsTree end)+      , pgrFocusedPane = focusEnd+      , pgrMaximizedPane = maxEnd+      , pgrDropTarget = dropTarget+      }++-- | Keys for the focused grid. Escape restores a maximized pane and is+-- consumed, unless something earlier (such as a popup in a pane) took it+-- or it closes a menu or dropdown ('takeEscape'). With no pane maximized,+-- Escape is left for others.+handleGridKeys :: WidgetId -> GridEnv -> Word64 -> Word64 -> NanoUI ()+handleGridKeys wid env maxPane focused = do+  focusedNow <- focusedWidget+  when (focusedNow == wid) $ do+    nav <- useKeyNav wid+    forM_ [(knLeft, (-1, 0)), (knRight, (1, 0)), (knUp, (0, -1)), (knDown, (0, 1))] $+      \(k, dir) -> when (k nav) (moveFocus env focused dir)+    when (knLeft nav || knRight nav || knUp nav || knDown nav) $+      damageWidgetNow wid (DamageInflated 0)+    -- Unmodified letters, taken as a 'shortcutOnce': a shortcut declared+    -- earlier for the same key keeps it from the grid, and the grid keeps it+    -- from one declared later.+    whenM (shortcutOnce (Shortcut.key 'm')) (maximizePane env focused)+    whenM (shortcutOnce (Shortcut.key 'x')) (closePane env focused)+    when (maxPane /= 0) $ whenM takeEscape (restorePane env)++-- | External drop target over the grid when no internal gesture is active.+resolveExternalDrop ::+  GridEnv -> WidgetId -> Rect -> V2 -> GridState -> IO (Maybe PaneGridDrop)+resolveExternalDrop env wid baseRect mouse end = do+  let ctx = geCtx env+      gs = geState env+      edgeBand = max 0 (pgEdgeBand (geCfg env))+  reachable <- pointerReachable ctx wid mouse+  pure $+    if not reachable+      || gsGesture gs /= NoGesture+      || gsGesture end /= NoGesture+      || geMaxPane env /= 0+      || gsMax end /= 0+      || gsTree end /= gsTree gs+      || not (rectContains baseRect mouse)+      then Nothing+      else do+        tree <- gsTree gs+        (q, r) <- find (\(_, r) -> rectContains r mouse) (M.toList (geRegions env))+        let seed = gsSeed end+            np = seed + 1+            edge AxisV True = PaneLeft+            edge AxisV False = PaneRight+            edge AxisH True = PaneAbove+            edge AxisH False = PaneBelow+        (location, proposed) <- case fromMaybe (dropTargetForPaneWith (pgCenterDrop (geCfg env)) r mouse q) (topLevelDropTarget edgeBand baseRect mouse) of+          DropSplit p ax onA -> Just (BesidePane p (edge ax onA), treeSplit p seed ax onA np tree)+          DropTab p mIdx -> Just (IntoTabs p, treeAddTab p seed mIdx np tree)+          DropTop ax onA -> Just (OutsideGrid (edge ax onA), splitBeside seed ax onA np tree)+          DropSwap _ -> Nothing+        let rect = M.findWithDefault (Rect 0 0 0 0) np (fst (layoutNode (geMinSize env) (geGutter env) proposed baseRect))+        pure (PaneGridDrop location rect q wid end proposed)++-- | A row, laid out like 'rowWith', that drags its pane: a press on it not+-- taken by a control inside it starts a drag, and the pointer shows a grab+-- cursor over it. Wrap a pane's title bar in it:+--+-- > paneDragHandle pctx (fillW . alignMiddle) $ do+-- >   label title+-- >   flex+-- >   whenM (button "Close") (pgcClose pctx)+paneDragHandle :: PaneGridCtx -> (Layout -> Layout) -> NanoUI a -> NanoUI a+paneDragHandle pctx f body = withCursorShape UiCursorGrab $ do+  (a, handle) <- rowWith' f body+  liftIO (writeIORef (pgcHandle pctx) (Just (respRect handle)))+  pure a++-- -----------------------------------------------------------------------------+-- Layout helpers+-- -----------------------------------------------------------------------------++-- | @s@ along the axis's main direction, growing across it, with no gap or+-- padding.+axisLay :: GridAxis -> Sizing -> Layout+axisLay ax s = tight . gap 0 $ case ax of+  AxisV -> defaultLayout {layoutWidth = s, layoutHeight = Grow 1}+  AxisH -> defaultLayout {layoutWidth = Grow 1, layoutHeight = s}++fillLay :: Layout+fillLay = axisLay AxisV (Grow 1)++-- | The pane content wrapper: fills its cell, never below one minimum pane.+paneLay :: Float -> Layout+paneLay m = minW m (minH m fillLay)++-- -----------------------------------------------------------------------------+-- Rendering+-- -----------------------------------------------------------------------------++-- | Enter a pane's grid-relative id scope. Like 'withKey', it takes no+-- sibling position, so panes coming and going never move a later sibling's id.+withPaneKey :: GridEnv -> Word64 -> NanoUI a -> NanoUI a+withPaneKey env pid =+  withIdFrame (\parent -> (parent, gePaneScope env)) . withKey pid++-- | Whether a left press landed on an enabled interactive child declared at or+-- after arena index @start@, using previous-frame bounds.+hitChildControl :: Context -> Input -> Int -> IO Bool+hitChildControl ctx inp start+  | not (pressedIn MouseLeft inp) = pure False+  | otherwise = arenaCount (ctxNodeArena ctx) >>= anyControlHitInRange ctx (inputMousePos inp) start++-- | Render one pane's content via 'pgViewPane' under the pane's stable key.+renderPane ::+  GridEnv ->+  Bool ->+  Word64 ->+  Rect ->+  NanoUI [RenderedPane]+renderPane env inTabs pid rect =+  withPaneKey env pid $ do+    inp <- askInput+    let ctx = geCtx env+    start <- liftIO (arenaCount (ctxNodeArena ctx))+    handleRef <- liftIO (newIORef Nothing)+    let ctxt =+          PaneGridCtx+            { pgcPaneId = pid+            , pgcRect = rect+            , pgcMaximized = geMaxPane env == pid+            , pgcInTabs = inTabs+            , pgcDragging = draggingPane env pid+            , pgcDndActive = geDragMoved env+            , pgcSplit = splitPane env pid+            , pgcClose = closePane env pid+            , pgcMaximize = maximizePane env pid+            , pgcRestore = restorePane env+            , pgcHandle = handleRef+            }+    view <- clipContainer (paneLay (geMinSize env)) (pgViewPane (geCfg env) pid ctxt)+    controlHit <- liftIO (hitChildControl ctx inp start)+    handleRect0 <- liftIO (readIORef handleRef)+    let handleRect = handleRect0 >>= rectIntersect rect+    pure [RenderedPane pid view controlHit handleRect False]++renderTabStrip :: GridEnv -> Rect -> [Word64] -> Word64 -> NanoUI ([RenderedPane], Float)+renderTabStrip env fullR pids active = do+  inp <- askInput+  th <- uiTheme+  let ctx = geCtx env+      arena = ctxNodeArena ctx+      fm = ctxFontMetrics ctx+      (_, padY) = buttonPadding fm+      defaultTabH = fromIntegral (max 24 (ceiling (fmLineHeight fm + padY) :: Int))+      closeSz = fromIntegral (max 16 (round (fmLineHeight fm) :: Int))+      maxLabelW = max 96 (fmLineHeight fm * 8)+      maxTabW = maxLabelW + closeSz + 28+  (tabs, stripResp) <- rowWith' (minH defaultTabH . tight . gap 0 . fillW) $+    forM pids $ \pid ->+      withKey ("tab" :: Text, pid) $ do+        let isActive = pid == active+            title = pgTabTitle (geCfg env) pid+            closable = pgClosableTabs (geCfg env)+        withCursorShape UiCursorPointer $ do+          (controlHit, tabArea) <- mouseArea (minH defaultTabH . maxW maxTabW) $+            columnWith (tight . gap 0 . fillH) $ do+              start <- liftIO (arenaCount arena)+              rowWith (padXY 8 2 . gap 6 . itemsCenter . fillH) $ do+                case pgViewTab (geCfg env) of+                  Just viewTab -> viewTab pid isActive+                  Nothing ->+                    labelWith+                      ( tight+                          . maxW maxLabelW+                          . ellipsisMiddle+                          . (if isActive then fontSemiBold else fontMuted)+                      )+                      title+                when closable $ do+                  closeR <- buttonWith' (fixedWH closeSz closeSz . tight . fontMuted) "\215"+                  when (respClicked closeR) (closePane env pid)+              hit <- liftIO (hitChildControl ctx inp start)+              box (fixedH 2 . fillW) (if isActive then themeAccent th else colorTransparent)+              pure hit+          let clippedTab =+                if rectNonEmpty fullR+                  then rectIntersect fullR (respRect tabArea)+                  else Just (respRect tabArea)+          pure (RenderedPane pid (PaneView title False) controlHit clippedTab True)+  let stripH = rectH (respRect stripResp)+      usedH = if stripH > 0 then stripH else defaultTabH+  pure (tabs, usedH)++renderNode ::+  GridEnv ->+  Map Word64 DividerInfo ->+  GridNode ->+  MinTree ->+  NanoUI [RenderedPane]+renderNode env dividers node mt = case node of+  Pane pid+    -- The lifted pane's landing slot in a drop preview: an empty cell of the+    -- pane's size, which the drop-zone highlight fills.+    | geLifted env && draggingPane env pid ->+        [] <$ container NodeContainer (paneLay (geMinSize env)) (pure ())+    -- Its prev-frame rect, zero until the pane has been laid out once.+    | otherwise ->+        renderPane env False pid (M.findWithDefault (Rect 0 0 0 0) pid (geRegions env))+  PaneTabs gid pids active ->+    withKey gid $+      clipContainer (paneLay (geMinSize env)) $ do+        let fullR = M.findWithDefault (Rect 0 0 0 0) active (geRegions env)+        (tabRendered, stripH) <- renderTabStrip env fullR pids active+        separator+        let tabBarH = stripH + 1+            bodyR =+              Rect+                (rectX fullR)+                (rectY fullR + min (rectH fullR) tabBarH)+                (rectW fullR)+                (max 0 (rectH fullR - tabBarH))+        bodyRendered <-+          if geLifted env && draggingPane env active+            then [] <$ container NodeContainer fillLay (pure ())+            else renderPane env True active bodyR+        pure (tabRendered <> bodyRendered)+  Split sid ax ratio a b ->+    withKey sid $ do+      let (ma, mb) = splitMinChildren (geMinSize env) (geGutter env) a b mt+          (wa, ha) = minTreeDims ma+          (wb, hb) = minTreeDims mb+          mDiv = M.lookup sid dividers+          avail = maybe 0 (mainLen ax . diRegion) mDiv+          -- The A side's extent after 'layoutNode' clamped it.+          dA = maybe 0 (\d -> dividerLength (geGutter env) d ratio) mDiv+          pinA = pinnedSide (pgFixedPanes (geCfg env)) a+          pinB = pinnedSide (pgFixedPanes (geCfg env)) b+          -- A zero weight would not grow at all.+          weight w = axisLay ax (Grow (max 1.0e-3 w))+          (aSide, bSide)+            -- Not laid out yet (first frame or new split): split the space by+            -- the ratio.+            | avail <= 0 = (weight (clamp01 ratio), weight (1 - clamp01 ratio))+            -- A percent for A, the rest for B, so both follow a resize.+            | pinA == pinB = (axisLay ax (Percent (dA / avail * 100)), fillLay)+            -- A pinned side keeps its pixel length; 'reflowFixed' updates the+            -- ratio next frame.+            | pinA = (axisLay ax (Fixed (max 0 dA)), fillLay)+            | otherwise = (fillLay, axisLay ax (Fixed (max 0 (avail - dA - geGutter env))))+      (if ax == AxisV then row' else column') fillLay $ do+        a' <- container NodeContainer (minW wa (minH ha aSide)) (renderNode env dividers a ma)+        dividerWidget env ax+        b' <- container NodeContainer (minW wb (minH hb bSide)) (renderNode env dividers b mb)+        pure (a' <> b')++draggingPane :: GridEnv -> Word64 -> Bool+draggingPane env pid = case gsGesture (geState env) of+  Drag p _ _ _ -> p == pid+  _ -> False++-- | The divider: a drawing that covers the whole gutter, so all of it grabs.+-- Painted as a faint rail with a solid 'pgSpacing' strip in the middle.+dividerWidget :: GridEnv -> GridAxis -> NanoUI ()+dividerWidget env axis =+  void $+    customWidget+      defaultCustomWidgetSpec+        { widgetLayout = const (axisLay axis (Fixed (geGutter env)))+        , widgetContent = contentKeyOf [keyPart (axis == AxisV), keyPart thickness, keyPart leeway, keyPart (colorToWord32 <$> color)]+        , widgetDraw = \cdc rect -> runCanvasFor cdc $ do+            let theme = cdcTheme cdc+                panel = themePanel theme+                -- The gutter as a vertical one; its center line as a+                -- zero-width rect down it.+                Rect x y w h = alongAxis axis rect+                Rect lx ly lw lh = alongAxis axis (Rect (x + w / 2) y 0 h)+                -- Full accent while grabbed; a calmer tint while merely hovering.+                line+                  | cdcPressed cdc = themeAccent theme+                  | otherwise = lerpColor (themeAccent theme) (fromMaybe (styleBg panel) color) 0.45+            case color of+              Just c -> drawRect rect c+              Nothing -> do+                drawRect rect (lerpColor (styleBg panel) (themeSeparator theme) 0.12)+                drawRect (alongAxis axis (Rect (x + leeway) y thickness h)) (scrollBarTrackColor panel theme)+            when (cdcHovered cdc || cdcPressed cdc) $+              drawStroke (V2 lx ly) (V2 (lx + lw) (ly + lh)) 2 line+        , widgetCursor = Just (\_ _ _ -> if axis == AxisV then UiCursorEwResize else UiCursorNsResize)+        }+  where+    thickness = max 0 (pgSpacing (geCfg env))+    leeway = max 0 (pgLeeway (geCfg env))+    color = pgDividerColor (geCfg env)++-- | The drag indicator and drop-zone highlight, drawn over the grid by its+-- root container so they stay out of the layout. The indicator is small,+-- translucent and offset from the pointer so the preview stays visible.+drawDragOverlay :: GridEnv -> WidgetId -> V2 -> Maybe Rect -> NanoUI ()+drawDragOverlay env wid (V2 mx my) zone =+  liftIO $ registerCustomDrawing (geCtx env) wid key $ \cdc _ -> runCanvasFor cdc $ do+    let theme = cdcTheme cdc+        accent = themeAccent theme+        shortTitle = if T.length title > 12 then T.take 11 title <> "…" else title+    drawRoundedRect ghost 2 (fadeAlpha accent 48)+    drawStrokeRoundedRect ghost 2 2 (fadeAlpha accent 128)+    unless (T.null title) $+      drawText (V2 (mx + 18) (my + 18)) AlignStart AlignTop shortTitle (fadeAlpha (styleFg (themeFloatingWindow theme)) 160)+    forM_ zone $ \zr -> do+      drawRoundedRect zr 2 (fadeAlpha accent 32)+      drawStrokeRoundedRect (rectInflate (-1) zr) 2 2 accent+  where+    title = case gsGesture (geState env) of+      Drag _ _ _ t -> t+      _ -> ""+    ghost = Rect (mx + 12) (my + 12) 112 28+    key = contentKey (2 : fromIntegral (hash title) : mx : my : maybe [0, 0, 0, 0, 0] (\(Rect x y w h) -> [1, x, y, w, h]) zone)++-- -----------------------------------------------------------------------------+-- Gestures+-- -----------------------------------------------------------------------------++-- | Arm, run and finish the resize and drag gestures.+runGestures ::+  WidgetId ->+  GridEnv ->+  [DividerInfo] ->+  [RenderedPane] ->+  Bool ->+  Maybe DropPreview ->+  NanoUI ()+runGestures wid env dividers rendered moved zone = do+  inp <- askInput+  let mouse = inputMousePos inp+  reachable <- liftIO (pointerReachable (geCtx env) wid mouse)+  -- A press that grabbed a scrollbar, before the view ran, is the bar's.+  barDrag <- liftIO (getsInteraction (geCtx env) (isJust . isScrollDrag))+  let down = heldIn MouseLeft inp+      setGesture rerun g = void (updateGrid env rerun (\s -> s {gsGesture = g}))+      -- A gesture keeps the press it starts with, for 'paneGridCore' to end+      -- it once that press is gone.+      start g = do+        liftIO (recordDragPress (geCtx env) (geKey env))+        setGesture True g+      -- diBand already includes the leeway; inflating it would steal presses+      -- from neighbouring panes.+      hitDiv = find (\d -> rectContains (diBand d) mouse) dividers+      -- The pane whose handle, tab header, or (when 'pvDraggable') whole+      -- region is under the pointer. Handles and tab headers are already+      -- clipped to their enclosing cell.+      pickHit = flip find rendered $ \pane ->+        any (`rectContains` mouse) (rpHandle pane)+          || (pvDraggable (rpView pane) && any (`rectContains` mouse) (M.lookup (rpPaneId pane) (geRegions env)))+  when (pressedIn MouseLeft inp && reachable && not barDrag+      && gsGesture (geState env) == NoGesture && not (any rpControlHit rendered)) $+    case (hitDiv, pickHit) of+      -- From the ratio the divider is drawn at, which the panes' minima may+      -- have clamped, so it moves with the pointer from the start.+      (Just d, _) -> start (Resize (diSplitId d) (clampRatio (geGutter env) d (diRatio d)) (mouseMain (diAxis d) mouse))+      (_, Just pane) -> do+        liftIO (recordDragPress (geCtx env) (geKey env))+        let pid = rpPaneId pane+            rawTitle = pvTitle (rpView pane)+            dragTitle = if T.null rawTitle then pgTabTitle (geCfg env) pid else rawTitle+            g = Drag pid mouse False dragTitle+        void . updateGrid env True $ \s ->+          if rpIsTab pane+            then s {gsTree = treeSelectTab pid <$> gsTree s, gsFocus = pid, gsGesture = g}+            else s {gsGesture = g}+      _ -> pure ()+  case gsGesture (geState env) of+    NoGesture -> pure ()+    Resize sid ratio0 main0+      | down ->+          forM_ (find ((== sid) . diSplitId) dividers) $ \d -> do+            -- The ratio shares out the region minus the divider gutter.+            let usable = mainLen (diAxis d) (diRegion d) - geGutter env+                r0 = if usable <= 0 then ratio0 else ratio0 + (mouseMain (diAxis d) mouse - main0) / usable+            void . updateGrid env True $ \s ->+              s {gsTree = treeSetRatio sid (clampRatio (geGutter env) d r0) <$> gsTree s}+      | otherwise -> setGesture True NoGesture+    Drag pid press moved0 title+      -- The indicator follows the pointer, whose moves bring their own+      -- frames; a still, held pointer needs none.+      | down -> when (moved && not moved0) $ setGesture False (Drag pid press True title)+      -- One write clears the gesture and stores the previewed tree, which+      -- was built with this frame's seed.+      | otherwise ->+          void . updateGrid env True $ \s -> case zone of+            Just dp | moved -> s {gsGesture = NoGesture, gsTree = Just (dpTree dp), gsSeed = max (gsSeed s) (gsSeed (geState env) + 1), gsFocus = pid}+            _ -> s {gsGesture = NoGesture}++mouseMain :: GridAxis -> V2 -> Float+mouseMain AxisV = v2X+mouseMain AxisH = v2Y++-- -----------------------------------------------------------------------------+-- Keyboard navigation+-- -----------------------------------------------------------------------------++moveFocus :: GridEnv -> Word64 -> (Float, Float) -> NanoUI ()+moveFocus env cur dir =+  forM_ (neighborPane (geRegions env) cur dir) $ \p -> updateGrid env True (\s -> s {gsFocus = p})++-- | The pane nearest the line from @cur@'s center in direction @(dx, dy)@.+neighborPane :: Map Word64 Rect -> Word64 -> (Float, Float) -> Maybe Word64+neighborPane regions cur (dx, dy) = do+  (cx, cy) <- centerOf <$> M.lookup cur regions+  let score r =+        let (px, py) = centerOf r+            vx = px - cx+            vy = py - cy+            dotv = vx * dx + vy * dy+         in if dotv > 0 then Just (abs (vx * dy - vy * dx) / dotv) else Nothing+  fst <$> bestPane score (M.delete cur regions)++centerOf :: Rect -> (Float, Float)+centerOf r = (rectX r + rectW r / 2, rectY r + rectH r / 2)++-- -----------------------------------------------------------------------------+-- Store mutation helpers+-- -----------------------------------------------------------------------------++-- | Update the grid's stored state and return it. With @rerun@, the+-- running frame rebuilds its view from the new state, and the rebuild's+-- diffs repaint what moved. A no-op update leaves the store untouched.+updateGrid :: GridEnv -> Bool -> (GridState -> GridState) -> NanoUI GridState+updateGrid env rerun f = liftIO $ do+  let ctx = geCtx env+  st <- getStore ctx+  let old = fromMaybe (geState env) (lookupSlot fieldGrid (geKey env) st)+      new = f old+  when (new /= old) $ do+    setStore ctx (insertSlot fieldGrid (geKey env) new st)+    when rerun (requestRerun ctx)+  pure new++-- | Split a pane, focusing and returning the new one.+splitPane :: GridEnv -> Word64 -> GridAxis -> NanoUI Word64+splitPane env pid axis =+  fmap gsFocus . updateGrid env True $ \s ->+    let seed = gsSeed s+     in s {gsTree = treeSplit pid seed axis False (seed + 1) <$> gsTree s, gsSeed = seed + 2, gsFocus = seed + 1}++closePane :: GridEnv -> Word64 -> NanoUI ()+closePane env pid =+  void . updateGrid env True $ \s ->+    s {gsTree = gsTree s >>= treeRemovePane pid, gsMax = if gsMax s == pid then 0 else gsMax s, gsGesture = NoGesture}++-- | Maximizing hides the dividers and every other pane, so an armed drag or+-- resize gesture could never complete; cancel it instead of leaking it.+maximizePane :: GridEnv -> Word64 -> NanoUI ()+maximizePane env pid =+  void . updateGrid env True $ \s ->+    if gsMax s == pid then s {gsMax = 0} else s {gsMax = pid, gsGesture = NoGesture}++restorePane :: GridEnv -> NanoUI ()+restorePane env = void (updateGrid env True (\s -> s {gsMax = 0}))
− lib/NanoUI/Widgets/Popup.hs
@@ -1,211 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Popup-  ( PopupAnchor (..)-  , PopupPlacement (..)-  , PopupConfig (..)-  , defaultPopupConfig-  , popup-  , popupWith-  , floatingOverlay-  , tooltipWidget-  , tooltipAt-  , tooltip-  , withTooltip-  )-where--import Control.Monad (void)-import Data.IORef (modifyIORef')-import Data.Maybe (fromMaybe)-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , getPrevRect-  , registerPopupConfig-  , seedFloatingPanel-  )-import NanoUI.Id (WidgetId, enterScope, scopeTag)-import NanoUI.Input (inputMousePos)-import NanoUI.Layout.Arena (NodeIdx, NodeType (..), addNode)-import NanoUI.Monad-  ( Ui-  , askContext-  , askDefaultLayout-  , askInput-  , nextId-  , uiIO-  )-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Layout (..)-  , Padding (..)-  , defaultLayout-  , tight-  )-import NanoUI.Types-  ( PopupAnchor (..)-  , PopupPlacement (..)-  , Rect (..)-  , rectHit-  , rectNonEmpty-  )-import NanoUI.Widgets.Behavior (useDismissable)-import NanoUI.Widgets.Layout (label)-import NanoUI.Widgets.Node-  ( HasResponse-  , Response (..)-  , containerResponse-  , emptyModalResp-  , floatingPanel-  , mkResponse-  , respHovered-  , respRect-  )--data PopupConfig = PopupConfig-  { cfgAnchor :: !PopupAnchor-  , cfgPlacement :: !PopupPlacement-  , cfgDismissable :: !Bool-  , cfgOffset :: !Float-  }-  deriving (Eq, Show)--defaultPopupConfig :: PopupAnchor -> PopupConfig-defaultPopupConfig anchor =-  PopupConfig-    { cfgAnchor = anchor-    , cfgPlacement = PlacementAuto-    , cfgDismissable = True-    , cfgOffset = 4-    }---- | A floating panel placed by the config, shown while @open@. Returns the--- body's result while open. The 'Response' reports a dismissal (Escape, or a--- click outside when 'cfgDismissable') as a click.-popup ::-  Ui :> es =>-  Bool ->-  PopupConfig ->-  Eff es a ->-  Eff es (Response, Maybe a)-popup open cfg child = popupWith open cfg id child---- | 'popup' with a modifier applied to its tight default layout.-popupWith ::-  Ui :> es =>-  Bool ->-  PopupConfig ->-  (Layout -> Layout) ->-  Eff es a ->-  Eff es (Response, Maybe a)-popupWith open cfg f child = do-  ctx <- askContext-  let-    layout = f (tight defaultLayout)-    addPopupNode wid parent = do-      registerPopupConfig ctx wid (cfgAnchor cfg) (cfgPlacement cfg) (cfgOffset cfg)-      addNode-        (ctxNodeArena ctx)-        NodePopup-        parent-        (layoutDirection layout)-        (layoutWidth layout)-        (layoutHeight layout)-        (Padding 6 6 6 6)-        4-        0-        0-        1e9-        1e9-        0-        AlignStart-        AlignTop-    seedFromPrev wid = getPrevRect ctx wid >>= mapM_ (seedFloatingPanel ctx wid)-  floatingOverlay open (cfgDismissable cfg) addPopupNode seedFromPrev ((,) False <$> child)---- | The floating panel behind popups, modals and windows, shown while @open@--- with its body in its own id scope. @addPanel@ and @enter@ are those of--- 'floatingPanel', given the panel's id. The body returns whether it closed--- the panel along with its result. The 'Response' reports a dismissal (the--- body's close, Escape, or a click outside when @dismissable@) as a click. A--- closed panel still consumes its id scope, so the ids of later siblings do--- not shift when it opens.-floatingOverlay ::-  Ui :> es =>-  Bool ->-  Bool ->-  (WidgetId -> Int -> IO NodeIdx) ->-  (WidgetId -> IO ()) ->-  Eff es (Bool, a) ->-  Eff es (Response, Maybe a)-floatingOverlay open dismissable addPanel enter body = do-  wid <- nextId-  ctx <- askContext-  if not open-    then do-      uiIO (modifyIORef' (ctxIdContext ctx) (fst . enterScope scopeTag))-      pure (emptyModalResp wid, Nothing)-    else do-      inp <- askInput-      (closed, r) <- floatingPanel True wid (addPanel wid) (enter wid) body-      panel <- fromMaybe (Rect 0 0 0 0) <$> uiIO (getPrevRect ctx wid)-      outside <--        if dismissable && rectNonEmpty panel-          then useDismissable panel-          else pure False-      let dismissed = closed || outside-      pure-        ( mkResponse wid panel (rectHit panel (inputMousePos inp)) False dismissed dismissed-        , Just r-        )---- | Attach a rich tooltip widget to any target response, displayed on hover.-tooltipWidget ::-  (Ui :> es, HasResponse r) =>-  r ->-  Eff es a ->-  Eff es (Maybe a)-tooltipWidget target child =-  snd <$> popup (respHovered target) cfg child-  where-    cfg = (defaultPopupConfig (AnchorRect (respRect target))) {cfgPlacement = PlacementBelow, cfgDismissable = False}---- | Attach a rich tooltip widget to an inner UI computation.-withTooltip ::-  Ui :> es =>-  Eff es a ->-  Eff es b ->-  Eff es (a, Maybe b)-withTooltip mainChild tipChild = do-  base <- askDefaultLayout-  (res, contResp) <- containerResponse NodeContainer (tight base) mainChild-  mTip <- tooltipWidget contResp tipChild-  pure (res, mTip)---- | 'tooltip' with a placement.-tooltipAt ::-  (Ui :> es, HasResponse r) =>-  PopupPlacement ->-  r ->-  Text ->-  Eff es ()-tooltipAt placement target txt =-  void (popup (respHovered target) cfg (label txt))-  where-    cfg = (defaultPopupConfig (AnchorRect (respRect target))) {cfgPlacement = placement, cfgDismissable = False}---- | Text shown below a widget while the pointer is over it.------ @--- save <- button' "Save"--- tooltip save "Write the file to disk"--- @-tooltip ::-  (Ui :> es, HasResponse r) =>-  r ->-  Text ->-  Eff es ()-tooltip = tooltipAt PlacementBelow
− lib/NanoUI/Widgets/Radio.hs
@@ -1,105 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Radio-  ( radio-  , radio'-  , boundedRadio-  , boundedRadio'-  , enumRadio-  , enumRadio'-  )-where--import Control.Monad (foldM)-import Data.Foldable (toList)-import Data.Hashable (hash)-import Data.Text (Text)-import Data.Text qualified as T-import Effectful (Eff, type (:>))-import NanoUI.Context (adoptStoreInt, intKey, recordStoreInt, registerFocusable, writeStoreInt)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, nextId, uiIO, withKey)-import NanoUI.Style (Layout, defaultLayout, fillW, gap, tight)-import NanoUI.Types (clamp)-import NanoUI.Widgets.Behavior (KeyNav (..), useKeyNav)-import NanoUI.Widgets.Combinators (selectableItem, withBoundedIndex)-import NanoUI.Widgets.Layout (column')-import NanoUI.Widgets.Node-  ( Response (..)-  , setChanged-  , tagContainer-  )--radioLay :: Layout-radioLay = tight (fillW defaultLayout)--radioGroupLay :: Layout-radioGroupLay = tight (gap 4 (fillW defaultLayout))--radioSalt :: Int-radioSalt = hash ("radio" :: Text)---- | A column of radio buttons over @options@ in fold order. Pass the selected--- index; the result is the index after this frame's click or arrow keys.-{-# INLINE radio #-}-radio :: (Foldable f, Ui :> es) => f Text -> Int -> Eff es Int-radio options index = snd <$> radio' options index--radio' ::-  (Foldable f, Ui :> es) => f Text -> Int -> Eff es (Response, Int)-radio' options index =-  withKey radioSalt $ do-    gid <- nextId-    ctx <- askContext-    let-      opts = case toList options of-        [] -> [""]-        xs -> xs-      !len = length opts-      !key = intKey gid-    stored <- uiIO $ adoptStoreInt ctx gid key (clamp 0 (len - 1) index)-    let !sel = clamp 0 (len - 1) stored-    uiIO $ registerFocusable ctx gid-    nav <- useKeyNav gid-    let-      !navDelta =-        (if knDown nav || knRight nav then 1 else 0 :: Int)-          - (if knUp nav || knLeft nav then 1 else 0)-      !selNav = if navDelta == 0 then sel else clamp 0 (len - 1) (sel + navDelta)-    column' radioGroupLay $ do-      tagContainer gid-      (combinedResp, clickedIdx) <- addRadioOptions selNav opts-      let !finalSel = if clickedIdx >= 0 then clickedIdx else selNav-      uiIO $ do-        writeStoreInt ctx gid key finalSel-        recordStoreInt ctx key finalSel-      -- Compare with the caller's index, as 'NanoUI.Widgets.Select' does, so a-      -- selection stored between frames still reports a change.-      pure (setChanged (finalSel /= clamp 0 (len - 1) index) combinedResp, finalSel)---- Use the ordinary widget path for every option, including singleton groups.--- It owns IDs, node construction, and scroll-aware interaction geometry.-addRadioOptions :: Ui :> es => Int -> [Text] -> Eff es (Response, Int)-addRadioOptions sel opts = foldM addOption (mempty, -1) (zip [0 ..] opts)- where-  addOption (!acc, !clickedIdx) (i, txt) = do-    r <- selectableItem NodeRadio txt (sel == i) radioLay i-    let-      clickedIdx' = if rawRespClicked r && clickedIdx < 0 then i else clickedIdx-    pure (acc <> r, clickedIdx')---- | Radio buttons for every value of a bounded enum, labelled by @encode@.-{-# INLINE boundedRadio #-}-boundedRadio :: (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es a-boundedRadio encode value = snd <$> boundedRadio' encode value--boundedRadio' :: (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es (Response, a)-boundedRadio' encode value = withBoundedIndex encode value radio'---- | 'boundedRadio' labelled with 'show'.-{-# INLINE enumRadio #-}-enumRadio :: (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es a-enumRadio = boundedRadio (T.pack . show)--enumRadio' :: (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es (Response, a)-enumRadio' = boundedRadio' (T.pack . show)
lib/NanoUI/Widgets/RichText.hs view
@@ -1,334 +1,700 @@ -- | Paragraphs of mixed-style text and links. module NanoUI.Widgets.RichText-  ( Inline+  ( -- * Inline pieces+    Inline   , inlineText   , inlineWith   , restyle   , strong   , emphasis   , inlineCode+  , inlineBackground+  , inlineTooltip   , hyperlink++    -- * Paragraphs   , richText   , richText'   , richTextWith   , richTextWith'+  , selectableRichText+  , selectableRichText'+  , selectableRichTextWith+  , selectableRichTextWith'   ) where -import Control.Monad (unless)+import Control.Applicative ((<|>))+import Control.Monad (filterM, forM_, foldM, unless, when) import Data.Hashable (hashWithSalt)-import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.IntMap.Strict qualified as IM-import Data.List (dropWhileEnd, groupBy)-import Data.Maybe (fromMaybe, isJust)-import Data.Primitive.SmallArray (SmallArray, indexSmallArray, smallArrayFromList)-import Data.String (IsString (..))+import Data.List (groupBy)+import Data.Map.Strict qualified as M+import Data.Maybe (fromMaybe, isJust, listToMaybe)+import Data.Primitive.PrimArray (indexPrimArray, sizeofPrimArray)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray, smallArrayFromList) import Data.Text (Text) import Data.Text qualified as T-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , askHostIO-  , intKey-  , setHost-  , registerCustomCursor-  , registerCustomDrawing-  , registerCustomMeasure-  )-import NanoUI.Draw (DrawOp (..), TextFont (..))-import NanoUI.Font (FontMetrics (..), lineWidthIO)-import NanoUI.Frame.Node (resolveTextFont)-import NanoUI.Input (Input (..), UiCursorKind (..))-import NanoUI.Layout.Arena (NodeType (NodeDrawing))-import NanoUI.Monad (Ui, askContext, askDefaultLayout, askInput, nextId, uiIO, uiTheme)-import NanoUI.Style-  ( FontVariant (..)-  , Layout (..)-  , TextDecoration (..)-  , Theme (..)-  , fontBold-  , fontItalic-  , fontMono-  , styleFg-  )-import NanoUI.Types (Color (..), Rect (..), V2 (..))-import NanoUI.Widgets.Node (Response, addWidget, respClicked, respHovered, respRect)---- | A piece of a paragraph: text in one style, and the hyperlink it follows when--- it is one. A string literal is 'plain' text.-data Inline = Inline !Text (Layout -> Layout) !(Maybe Text)--instance IsString Inline where-  fromString = inlineText . T.pack---- | Text in the paragraph's own style.-inlineText :: Text -> Inline-inlineText txt = Inline txt id Nothing+import NanoUI.Internal.Context+import NanoUI.Internal.Host qualified as Host+import NanoUI.Internal.RichText.Types+import NanoUI.Internal.Draw (DrawOp (..), TextFont (..))+import NanoUI.Internal.Font (FontMetrics (..), ShapedText (..), prepareFontMetrics, selectionSpans, textDecorationMetrics, textIndexAtX)+import NanoUI.Internal.Font qualified as Font+import NanoUI.Internal.Frame.Node (resolveTextFont)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Input (Input (..), MouseButton (MouseLeft), UiCursorKind (..), heldIn, inputMousePos, pressedIn, releasedIn)+import NanoUI.Internal.Layout.Arena (NodeType (NodeDrawing), lookupNodeByKey)+import NanoUI.Internal.Store (eqByPtr, ptrEq, fieldRichSelection, findSlot, insertSlot)+import NanoUI.Internal.Monad (NanoUI, askDefaultLayout, askInput, freshWidget, liftIO, requestFocus, uiTheme, withKey)+import NanoUI.Internal.Style hiding (Flow (..))+import NanoUI.Internal.TextCluster (clusterLength)+import NanoUI.Internal.Types (Color (..), Rect (..), V2 (..), rectContains)+import NanoUI.Internal.Widgets.Node (Response (..), addWidget, respClicked, respHovered, respRect)+import NanoUI.Internal.Widgets.Popup (tooltip)+import NanoUI.Internal.Widgets.Behavior (keyboardFocused)+import NanoUI.Internal.Widgets.TextInput (cursorAtOffset, cursorOffset, fieldTextCommands)+import NanoUI.Widgets.TextBuffer qualified as TB+import NanoUI.Widgets.TextEditor (Editor (..), EditorMode (..), editorSelection, emptyHistory, multiLineMode, runCommandIO)+import System.IO.Unsafe (unsafeDupablePerformIO)  -- | Text styled by font modifiers (@fontBold@, @fontSize 20@, -- @fontColor red . fontUnderline@), applied over the paragraph's layout. inlineWith :: (Layout -> Layout) -> Text -> Inline-inlineWith f txt = Inline txt f Nothing+inlineWith f txt = Inline txt (InlineCustom f) Nothing Nothing Nothing  -- | Add font modifiers to a piece, a hyperlink included. restyle :: (Layout -> Layout) -> Inline -> Inline-restyle f (Inline txt style target) = Inline txt (f . style) target+restyle f (Inline txt style target bg tip) = Inline txt (InlineCustom (f . applyInlineStyle style)) target bg tip  -- | Bold text. strong :: Text -> Inline-strong = inlineWith fontBold+strong txt = Inline txt InlineBold Nothing Nothing Nothing  -- | Italic text. emphasis :: Text -> Inline-emphasis = inlineWith fontItalic+emphasis txt = Inline txt InlineItalic Nothing Nothing Nothing  -- | Monospaced text. inlineCode :: Text -> Inline-inlineCode = inlineWith fontMono+inlineCode txt = Inline txt InlineMono Nothing Nothing Nothing --- | @hyperlink target label@: text in the theme's link colour, underlined while--- hovered, whose click the paragraph reports as @target@.+-- | Paint a colour behind a piece, the full line-box height, e.g. a+-- highlight or an inline code tint. Leading and trailing spaces on each line+-- are left bare.+--+-- > richText ["Run ", inlineBackground codeTint (inlineCode "cabal build"), " first."]+inlineBackground :: Color -> Inline -> Inline+inlineBackground c (Inline txt style target _ tip) = Inline txt style target (Just c) tip++-- | Attach hover tooltip text to any 'Inline' piece (code run, text, or link).+inlineTooltip :: Text -> Inline -> Inline+inlineTooltip tip (Inline txt style target bg _) = Inline txt style target bg (Just tip)++-- | @hyperlink target label@: text styled with the theme's link colour and+-- underlined on hover. Clicking the link returns @Just target@ from 'richText'. hyperlink :: Text -> Text -> Inline-hyperlink target label = Inline label id (Just target)+hyperlink target label = Inline label InlinePlain (Just target) Nothing Nothing +applyInlineStyle :: InlineStyle -> Layout -> Layout+applyInlineStyle = \case+  InlinePlain -> id+  InlineBold -> fontBold+  InlineItalic -> fontItalic+  InlineMono -> fontMono+  InlineCustom f -> f+ -- | A paragraph of pieces, wrapped at its width. Returns the target of the -- hyperlink clicked this frame.-richText :: Ui :> es => [Inline] -> Eff es (Maybe Text)+richText :: [Inline] -> NanoUI (Maybe Text) richText = richTextWith id  -- | 'richText' with a layout modifier, whose font choices are the default--- for every piece.-richTextWith :: Ui :> es => (Layout -> Layout) -> [Inline] -> Eff es (Maybe Text)-richTextWith f pieces = snd <$> richTextWith' f pieces--richText' :: Ui :> es => [Inline] -> Eff es (Response, Maybe Text)-richText' = richTextWith' id+-- for every piece. Horizontal alignment applies per line: with 'alignEnd'+-- every line ends at the right edge.+richTextWith :: (Layout -> Layout) -> [Inline] -> NanoUI (Maybe Text)+richTextWith f = fmap snd . richTextWith' f --- A resolved piece: its font, colour, line metrics and hyperlink.-data Run = Run-  { runFont :: !TextFont-  , runColor :: !Color-  , runLineHeight :: !Float-  , runAscent :: !Float-  , runTarget :: !(Maybe Text)-  }+-- | 'richTextWith' with read-only mouse selection and the standard text+-- commands for selecting and copying text. Link clicks still return their+-- destination.+selectableRichTextWith :: (Layout -> Layout) -> [Inline] -> NanoUI (Maybe Text)+selectableRichTextWith f = fmap snd . selectableRichTextWith' f -data TokenKind = Word | Space | Break-  deriving (Eq)+-- | A selectable paragraph at its default layout.+selectableRichText :: [Inline] -> NanoUI (Maybe Text)+selectableRichText = selectableRichTextWith id --- A word, a run of spaces or a line break, with its width in its piece's font.-data Token = Token-  { _tokenText :: !Text-  , tokenRun :: !Int-  , tokenKind :: !TokenKind-  , tokenWidth :: !Float-  }+-- | 'selectableRichText' with its response, for focus and geometry.+selectableRichText' :: [Inline] -> NanoUI (Response, Maybe Text)+selectableRichText' = selectableRichTextWith' id --- A laid-out line: its top, height and baseline offset, and its tokens with--- their x positions.-data Line = Line-  { lineTop :: !Float-  , lineHeight :: !Float-  , lineAscent :: !Float-  , lineWidth :: !Float-  , lineTokens :: ![(Float, Token)]-  }+-- | 'selectableRichTextWith' with its response.+selectableRichTextWith' :: (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)+selectableRichTextWith' = richTextWithMode' True --- A paragraph's measured pieces and its lines at the width it last had,--- kept between frames while its pieces, fonts and colours stay the same.-data Paragraph = Paragraph-  { paraKey :: !Int-  , paraRuns :: !(SmallArray Run)-  , paraTokens :: ![Token]-  , paraEmptyLine :: !(Float, Float)-  , paraNatural :: (Float, Float)-  , paraWidth :: !Float-  , paraLines :: [Line]-  }+-- | 'richText' returning the paragraph response and a link target clicked+-- this frame, or 'Nothing' when no link was activated.+richText' :: [Inline] -> NanoUI (Response, Maybe Text)+richText' = richTextWith' id -newtype Paragraphs = Paragraphs (IORef (IM.IntMap Paragraph))+-- | 'richTextWith' returning the paragraph response and optional clicked link target.+richTextWith' :: (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)+richTextWith' = richTextWithMode' False -richTextWith' :: Ui :> es => (Layout -> Layout) -> [Inline] -> Eff es (Response, Maybe Text)-richTextWith' f pieces = do-  ctx <- askContext+richTextWithMode' :: Bool -> (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)+richTextWithMode' selectable f pieces = do+  (wid, ctx) <- freshWidget   inp <- askInput   base <- f <$> askDefaultLayout   theme <- uiTheme-  wid <- nextId-  let styled = [(txt, pieceFont l, pieceColor theme l target, target) | Inline txt style target <- pieces, let l = style base]-  cacheRef <--    uiIO $-      askHostIO ctx >>= \case-        Just (Paragraphs ref) -> pure ref-        Nothing -> do-          ref <- newIORef IM.empty-          setHost ctx (Paragraphs ref)-          pure ref-  gen <- uiIO (readIORef (ctxMetricGen ctx))-  let key =-        foldl'-          ( \h (txt, TextFont size variant weight fstyle deco, Color rgba, target) ->-              h `hashWithSalt` txt `hashWithSalt` size `hashWithSalt` fromEnum variant-                `hashWithSalt` fromEnum weight `hashWithSalt` fromEnum fstyle `hashWithSalt` fromEnum deco-                `hashWithSalt` rgba `hashWithSalt` target-          )-          gen-          styled-  cached <- uiIO (IM.lookup (intKey wid) <$> readIORef cacheRef)+  let !baseSize = ctxFontSize ctx+      !align = layoutAlignX base+  Paragraphs cacheRef <- liftIO $ Host.hostOrInit (ctxParagraphs ctx) (Paragraphs <$> newIORef (ParagraphCache 0 paragraphBound IM.empty))+  gen <- liftIO (readIORef (ctxMetricGen ctx))+  cached <- liftIO ((\(ParagraphCache _ _ m) -> IM.lookup (intKey wid) m) <$> readIORef cacheRef)+  sameInputs <- case cached of+    Nothing -> pure False+    Just para -> liftIO $ do+      Inputs pieces0 base0 theme0 gen0 selectable0 <- readIORef (paraInputs para)+      pure (ptrEq pieces pieces0 && gen == gen0 && eqByPtr base base0 && eqByPtr theme theme0 && selectable == selectable0)+  let !key = case cached of+        Just para | sameInputs -> paraKey para+        _ -> hashPieces baseSize base theme align gen selectable pieces   para0 <- case cached of-    Just para | paraKey para == key -> pure para-    _ -> uiIO $ do-      resolved <- mapM (measurePiece ctx) (zip [0 ..] styled)+    Just para | paraKey para == key ->+      liftIO (para <$ unless sameInputs (writeIORef (paraInputs para) (Inputs pieces base theme gen selectable)))+    _ -> liftIO $ do+      let styled =+            [ (piece, pieceFont baseSize l, pieceColor theme l target, layoutTextBreak l)+            | piece@(Inline _ style target _ _) <- pieces+            , let l = applyInlineStyle style base+            ]+          plainInput = T.concat [txt | Inline txt _ _ _ _ <- pieces]+          starts = scanl (+) 0 [T.length txt | Inline txt _ _ _ _ <- pieces]+      resolved <- mapM (measurePiece ctx) (zip3 [0 ..] starts styled)       let runs = smallArrayFromList (map fst resolved)           tokens = concatMap snd resolved           emptyLine = case resolved of             (run, _) : _ -> (runLineHeight run, runAscent run)             [] -> (fmLineHeight (ctxFontMetrics ctx), fmAscent (ctxFontMetrics ctx))-      pure (Paragraph key runs tokens emptyLine (lineBoxes (layoutLines runs emptyLine 1e9 tokens)) (-1) [])+          hasGlyphs = any (\(_, _, _, brk) -> brk == BreakAnywhere) styled+          tooltipRuns =+            [ (runIdx, tip)+            | runIdx <- [0 .. sizeofSmallArray runs - 1]+            , Just tip <- [runTooltip (indexSmallArray runs runIdx)]+            ]+          hasInteractive =+            not (null tooltipRuns)+              || any (\runIdx -> isJust (runTarget (indexSmallArray runs runIdx))) [0 .. sizeofSmallArray runs - 1]+      measured <- newIORef Unmeasured+      inputsRef <- newIORef (Inputs pieces base theme gen selectable)+      pure+        ( Paragraph+            key+            inputsRef+            runs+            tokens+            emptyLine+            (lineBoxes (layoutLines runs emptyLine AlignStart 1e9 tokens))+            (-1)+            []+            []+            tooltipRuns+            hasInteractive+            hasGlyphs+            measured+            (if selectable then plainInput else T.empty)+            (TB.fromText plainInput)+        )+  -- Forced, so selection sync compares this address rather than a selector thunk.+  let !plain = paraText para0+  when (selectable && not (T.null plain)) (liftIO (registerFocusable ctx wid))   resp <- addWidget wid NodeDrawing T.empty 0 base   let Rect rx ry rw _ = respRect resp       runs = paraRuns para0-      layoutAt width = layoutLines runs (paraEmptyLine para0) width (paraTokens para0)+      layoutAt width = layoutLines runs (paraEmptyLine para0) align width (paraTokens para0)       para         | paraWidth para0 == rw = para0-        | otherwise = para0 {paraWidth = rw, paraLines = layoutAt rw}+        | otherwise =+            let ls = layoutAt rw+                inter = if paraHasInteractive para0 then interactivePieces runs ls else []+             in para0 {paraWidth = rw, paraLines = ls, paraInteractive = inter}       linesAt width         | width == paraWidth para = paraLines para         | otherwise = layoutAt width-      V2 mx my = inputMousePos inp-      hoveredRun-        | not (respHovered resp) = Nothing-        | otherwise =-            case [ tokenRun tok-                 | line <- paraLines para-                 , my >= ry + lineTop line && my < ry + lineTop line + lineHeight line-                 , (x, tok) <- lineTokens line-                 , tokenKind tok /= Break-                 , mx >= rx + x && mx < rx + x + tokenWidth tok-                 , isJust (runTarget (indexSmallArray runs (tokenRun tok)))-                 ] of-              run : _ -> Just run-              [] -> Nothing-      -- Words are drawn one by one, so a decoration is drawn once across a-      -- piece's words on a line and the spaces between them.-      draw _cdc (Rect x0 y0 w _) =-        smallArrayFromList $-          concat-            [ [ DrawTextStyled (x0 + x) (lineY line run) ((runFont run) {textFontDecoration = DecorationNone}) txt (runColor run)-              | (x, Token txt runIdx Word _) <- lineTokens line-              , let run = indexSmallArray runs runIdx-              ]-                ++ concat-                  [ [FillRect (Rect (x0 + x1) (y + offset) (x2 - x1) thick) (runColor run) | offset <- decorationOffsets deco run]-                  | group <- groupBy (\(_, a) (_, b) -> tokenRun a == tokenRun b) (lineTokens line)-                  , let trimmed = dropWhileEnd isSpaceToken (dropWhile isSpaceToken group)-                  , (x1, first) : _ <- [trimmed]-                  , let runIdx = tokenRun first-                        run = indexSmallArray runs runIdx-                        deco = decorationOf runIdx-                        (lastX, lastTok) = last trimmed-                        x2 = lastX + tokenWidth lastTok-                        y = lineY line run-                        thick = max 1 (0.06 * runLineHeight run)-                  , deco /= DecorationNone-                  ]-            | line <- linesAt w-            ]-        where-          lineY line run = y0 + lineTop line + lineAscent line - runAscent run-          isSpaceToken (_, tok) = tokenKind tok == Space-      decorationOf runIdx-        | Just runIdx == hoveredRun = underlined (textFontDecoration (runFont (indexSmallArray runs runIdx)))-        | otherwise = textFontDecoration (runFont (indexSmallArray runs runIdx))-      -- Where underline and strikethrough sit below a line box's top, as-      -- styled labels draw them.-      decorationOffsets deco run =-        let lh = runLineHeight run-            under = runAscent run + max 1 (0.1 * lh)-            strike = runAscent run * 0.65-         in case deco of-              DecorationUnderline -> [under]-              DecorationStrikethrough -> [strike]-              DecorationUnderlineStrike -> [under, strike]-              DecorationNone -> []-      drawKey = key `hashWithSalt` fromMaybe (-1) hoveredRun-  uiIO $ do+  focused <- if selectable then keyboardFocused wid else pure False+  (selection, dragReleased) <-+    if selectable+      then do+        (current, dragged) <- updateSelection ctx inp wid resp focused plain (paraBuffer para0) (paraLines para)+        -- Drawn only while focused, as a text field's selection goes when+        -- the field loses focus.+        pure (if focused then Just current else Nothing, dragged)+      else pure (Nothing, False)+  let mouse = inputMousePos inp+      interPieces = paraInteractive para+      hovered = respHovered resp && paraHasInteractive para+      hoveredRun = if hovered then linkRunAt runs rx ry interPieces mouse else Nothing+      draw = drawParagraph runs (paraHasGlyphs para) theme hoveredRun selection linesAt+      drawKey = key `hashWithSalt` fromMaybe (-1) hoveredRun `hashWithSalt` fmap (\s -> (selectionStart s, selectionEnd s)) selection+  liftIO $ do+    -- A move onto or off a link or tooltipped run inside the hovered paragraph+    -- changes no hot widget, so each interactive piece registers a hover zone.+    when hovered $+      forM_ interPieces $ \(InteractivePiece _ x y w h) ->+        registerHoverZone ctx False (Rect (rx + x) (ry + y) w h)     unless (paraWidth para0 == rw && fmap paraKey cached == Just key) $-      modifyIORef' cacheRef $ \m ->-        -- Paragraphs no longer drawn are dropped all at once past a bound.-        IM.insert (intKey wid) para (if IM.size m > 4096 then IM.empty else m)+      cacheParagraph ctx cacheRef wid (isJust cached) para     registerCustomMeasure ctx wid $ \_ (availW, _) ->-      if availW >= 1e9 then paraNatural para else lineBoxes (linesAt availW)-    registerCustomDrawing ctx wid (if drawKey == 0 then 1 else drawKey) draw-    registerCustomCursor ctx wid (const (if isJust hoveredRun then UiCursorPointer else UiCursorDefault))-  let clicked-        | respClicked resp = hoveredRun >>= runTarget . indexSmallArray runs-        | otherwise = Nothing+      if availW >= 1e9 then paraNatural para else measureAt (paraMeasured para) (lineBoxes . linesAt) availW+    registerCustomEntry ctx wid $+      CustomDrawingEntry+        (if drawKey == 0 then 1 else drawKey)+        draw+        (Just (\_ _ _ -> if isJust hoveredRun then UiCursorPointer else if selectable then UiCursorText else UiCursorDefault))+        0+        False+        (if selectable then KeysReadOnly else KeysNone)+  forM_ (paraTooltipRuns para) $ \(runIdx, tip) ->+    withKey ("rt-tip" :: Text, runIdx) $ do+      let runRects =+            [ Rect (rx + x) (ry + y) w h+            | InteractivePiece ri x y w h <- interPieces+            , ri == runIdx+            ]+          mTargetRect = listToMaybe [r | r <- runRects, rectContains r mouse] <|> listToMaybe runRects+      forM_ mTargetRect $ \pieceR ->+        tooltip (resp {rawRespRect = pieceR}) tip+  clicked <-+    if respClicked resp && not dragReleased && paraHasInteractive para+      then do+        -- The press must have gone down on the link too; its point stays+        -- recorded through the release frame.+        presses <- liftIO (readIORef (ctxPressPos ctx))+        pure $+          if maybe True ((== hoveredRun) . linkRunAt runs rx ry interPieces . ppPos) (M.lookup MouseLeft presses)+            then hoveredRun >>= runTarget . indexSmallArray runs+            else Nothing+      else pure Nothing   pure (resp, clicked)   where-    underlined DecorationStrikethrough = DecorationUnderlineStrike-    underlined DecorationNone = DecorationUnderline-    underlined deco = deco     lineBoxes lines' = (maximum (0 : map lineWidth lines'), sum (map lineHeight lines')) --- | The font a piece's layout chooses.-pieceFont :: Layout -> TextFont-pieceFont l = TextFont (layoutFontSize l) (layoutFontVariant l) (layoutFontWeight l) (layoutFontStyle l) (layoutTextDecoration l)+-- | Hash a paragraph's pieces directly against the base layout and theme+-- without allocating intermediate 'Layout' or 'TextFont' records on cache hits.+hashPieces :: Float -> Layout -> Theme -> AlignX -> Int -> Bool -> [Inline] -> Int+hashPieces !baseSize base theme align !gen !selectable = go h0+  where+    !h0 = gen `hashWithSalt` fromEnum align `hashWithSalt` selectable+    !baseResolvedSize = resolveFontSize baseSize (layoutFontSize base)+    !baseVariant = fromEnum (layoutFontVariant base)+    !baseWeight = fromEnum (layoutFontWeight base)+    !baseStyle = fromEnum (layoutFontStyle base)+    !baseDeco = fromEnum (layoutTextDecoration base)+    !baseTab = layoutFontTabular base+    !baseBrk = fromEnum (layoutTextBreak base)+    !baseToneCol = textToneColor theme (layoutFontTone base)+    !baseFontColor = layoutFontColor base+    !linkCol = themeLink theme+    go !h [] = h+    go !h (Inline txt style target bg tip : rest) =+      let !h' = case style of+            InlineCustom f ->+              let l = f base+                  TextFont size variant weight fstyle deco tabular = pieceFont baseSize l+                  Color rgba = pieceColor theme l target+               in hashOne h txt size (fromEnum variant) (fromEnum weight) (fromEnum fstyle) (fromEnum deco) tabular rgba target bg tip (fromEnum (layoutTextBreak l))+            _ ->+              let !variant = case style of InlineMono -> fromEnum FontMono; _ -> baseVariant+                  !weight = case style of InlineBold -> fromEnum WeightBold; _ -> baseWeight+                  !fstyle = case style of InlineItalic -> fromEnum FontStyleItalic; _ -> baseStyle+                  Color rgba = case baseFontColor of+                    Just c -> c+                    Nothing -> if isJust target then linkCol else baseToneCol+               in hashOne h txt baseResolvedSize variant weight fstyle baseDeco baseTab rgba target bg tip baseBrk+       in go h' rest+    {-# INLINE hashOne #-}+    hashOne !h txt !size !variant !weight !fstyle !deco !tabular !rgba target bg tip !brk =+      let !bgHash = case bg of+            Nothing -> h `hashWithSalt` (0 :: Int)+            Just (Color c) -> h `hashWithSalt` (1 :: Int) `hashWithSalt` c+       in bgHash `hashWithSalt` txt `hashWithSalt` size `hashWithSalt` variant+            `hashWithSalt` weight `hashWithSalt` fstyle `hashWithSalt` deco+            `hashWithSalt` tabular `hashWithSalt` rgba `hashWithSalt` target+            `hashWithSalt` tip `hashWithSalt` brk +interactivePieces :: SmallArray Run -> [Line] -> [InteractivePiece]+interactivePieces runs ls =+  [ InteractivePiece runIdx x1 (lineTop line) (x2 - x1) (lineHeight line)+  | line <- ls+  , (run, runIdx, x1, x2) <- pieceSpans runs line+  , isJust (runTarget run) || isJust (runTooltip run)+  ]++linkRunAt :: SmallArray Run -> Float -> Float -> [InteractivePiece] -> V2 -> Maybe Int+linkRunAt runs !rx !ry pieces (V2 px py) = go pieces+  where+    !lx = px - rx+    !ly = py - ry+    go [] = Nothing+    go (InteractivePiece runIdx x y w h : rest)+      | lx >= x && lx < x + w && ly >= y && ly < y + h && isJust (runTarget (indexSmallArray runs runIdx)) =+          Just runIdx+      | otherwise = go rest++-- | Words are drawn separately, so backgrounds and decorations are drawn once+-- per piece per line, spanning the inner spaces. Backgrounds go underneath.+drawParagraph ::+  SmallArray Run ->+  Bool ->+  Theme ->+  Maybe Int ->+  Maybe RichSelection ->+  (Float -> [Line]) ->+  CustomDrawContext ->+  Rect ->+  SmallArray DrawOp+drawParagraph runs hasGlyphs theme hoveredRun selection linesAt _cdc (Rect x0 y0 w _) =+  smallArrayFromList $+    concatMap lineOps (linesAt w)+  where+    selected = selection >>= selectionOffsets+    lineOps line =+      let spans = pieceSpans runs line+          highlights = maybe [] (\(lo, hi) -> selectionOps x0 y0 line lo hi (themeSelection theme)) selected+          glyphDraw =+            if hasGlyphs+              then [(x, runIdx, T.concat [tokenText tok | (_, tok) <- group]) | group@((x, Token _ runIdx _ _ _ _) : _) <- glyphGroups line]+              else []+       in [ FillRect (Rect (x0 + x1) (y0 + lineTop line) (x2 - x1) (lineHeight line)) bg+          | (run, _, x1, x2) <- spans+          , Just bg <- [runBackground run]+          ]+            ++ highlights+            ++ [ DrawTextStyled (x0 + x) (lineY line run) ((runFont run) {textFontDecoration = DecorationNone}) txt (runColor run)+               | (x, runIdx, txt) <-+                   [(x, runIdx, txt) | (x, Token txt runIdx Word _ _ _) <- lineTokens line]+                     ++ glyphDraw+               , let run = indexSmallArray runs runIdx+               ]+            ++ [ FillRect (Rect (x0 + x1) (lineY line run + offset) (x2 - x1) thick) (runColor run)+               | (run, runIdx, x1, x2) <- spans+               , let deco = decorationOf runIdx+                     (thick, under, strike) = textDecorationMetrics (runLineHeight run) (runAscent run)+               , deco /= DecorationNone+               , offset <- decorationOffsets deco under strike+               ]+    lineY line run = y0 + lineTop line + lineAscent line - runAscent run+    glyphGroups line =+      groupBy joinsGlyphs [(x, tok) | (x, tok) <- lineTokens line, tokenKind tok == Glyph || tokenKind tok == GlyphSpace]+    decorationOf runIdx =+      (if Just runIdx == hoveredRun then addUnderline else id)+        (textFontDecoration (runFont (indexSmallArray runs runIdx)))+    decorationOffsets deco under strike =+      case deco of+        DecorationUnderline -> [under]+        DecorationStrikethrough -> [strike]+        DecorationUnderlineStrike -> [under, strike]+        DecorationNone -> []++-- | Each piece's stretch of a line without the spaces at its ends: its run,+-- the run's index, and its left and right edges. Computed in a single scan+-- without intermediate grouping lists.+pieceSpans :: SmallArray Run -> Line -> [(Run, Int, Float, Float)]+pieceSpans runs line = go (lineTokens line)+  where+    isSpaceTok tok = tokenKind tok == Space || tokenKind tok == GlyphSpace+    go [] = []+    go ((x, tok) : rest) = scanRun (tokenRun tok) (if isSpaceTok tok then (-1) else x) (if isSpaceTok tok then 0 else x + tokenWidth tok) rest+    scanRun !ri !startX !endX toks = case toks of+      (x, tok) : rest | tokenRun tok == ri ->+        if isSpaceTok tok+          then scanRun ri startX endX rest+          else scanRun ri (if startX < 0 then x else startX) (x + tokenWidth tok) rest+      _ ->+        let tailSpans = go toks+         in if startX < 0 then tailSpans else (indexSmallArray runs ri, ri, startX, endX) : tailSpans++-- | Whether two placed tokens belong to the same piece.+joinsGlyphs :: (Float, Token) -> (Float, Token) -> Bool+joinsGlyphs (_, a) (_, b) = tokenRun a == tokenRun b++-- | Store @para@ under @wid@, pruning entries neither drawn last frame nor yet+-- this frame once the cache grows past its bound.+cacheParagraph :: Context -> IORef ParagraphCache -> WidgetId -> Bool -> Paragraph -> IO ()+cacheParagraph ctx cacheRef wid hadEntry para = do+  ParagraphCache n bound m <- readIORef cacheRef+  let n' = if hadEntry then n else n + 1+  writeIORef cacheRef+    =<< if n' <= bound+      then pure $! ParagraphCache n' bound (IM.insert (intKey wid) para m)+      else do+        prev <- getsDamage ctx (pfRects . dsPrev)+        -- A paragraph declared this pass has registered its custom drawing.+        let declared k = maybe (pure False) (fmap isJust . lookupCustomDrawingAt ctx) =<< lookupNodeByKey (ctxNodeArena ctx) k+        live <- filterM (\(k, _) -> if IM.member k prev then pure True else declared k) (IM.toAscList m)+        let kept = IM.insert (intKey wid) para (IM.fromDistinctAscList live)+            size = IM.size kept+        pure $! ParagraphCache size (max paragraphBound (2 * size)) kept++-- | Keep the paragraph's selection in document coordinates, so it survives+-- rewrapping when the widget's width changes.+updateSelection :: Context -> Input -> WidgetId -> Response -> Bool -> Text -> TB.TextBuffer -> [Line] -> NanoUI (RichSelection, Bool)+updateSelection ctx inp wid resp focused plain buffer lines' = do+  let key = intKey wid+      initial = RichSelection plain (TB.Cursor 0 0) (TB.Cursor 0 0) False False 0 0+  !stored <- liftIO (findSlot fieldRichSelection initial key <$> getStore ctx)+  let synced = syncSelection plain stored+  commands <- if focused then liftIO (fieldTextCommands ctx readOnlyMode inp) else pure []+  afterKeys <-+    if null commands+      then pure synced+      else do+        editor <- liftIO (foldM (flip (runCommandIO ctx readOnlyMode)) (selectionEditor buffer synced) commands)+        let (a, c) = editorSelection editor+        pure (selectionIn plain a c (selectionDragging synced) (selectionMoved synced))+  let mouse = inputMousePos inp+      press = pressedIn MouseLeft inp && respHovered resp+      held = heldIn MouseLeft inp+      released = releasedIn MouseLeft inp+      (next, dragReleased)+        | press =+            let pos = pointAt plain lines' (respRect resp) mouse+             in (selectionAt plain pos pos held False, False)+        | selectionDragging afterKeys && (held || released) =+            let pos = pointAt plain lines' (respRect resp) mouse+                dragAnchor = (selectionAnchor afterKeys, anchorOffset afterKeys)+                didMove = selectionMoved afterKeys || fst pos /= fst dragAnchor+             in (selectionAt plain dragAnchor pos held (didMove && held), released && didMove)+        -- A drag that ended elsewhere stops; an idle pass keeps the stored+        -- selection object, so it writes nothing.+        | selectionDragging afterKeys = (afterKeys {selectionDragging = False, selectionMoved = False}, False)+        | otherwise = (afterKeys, False)+  when press (requestFocus wid)+  unless (ptrEq stored next) $+    liftIO (modifyStore ctx (insertSlot fieldRichSelection key next))+  pure (next, dragReleased)++readOnlyMode :: EditorMode+readOnlyMode = multiLineMode {modeEditable = False}++-- | The stored selection over the paragraph's current text. Changed text+-- keeps the selection's offsets, clamped to its length, without building a+-- text buffer.+syncSelection :: Text -> RichSelection -> RichSelection+syncSelection plain previous+  | ptrEq (selectionText previous) plain = previous+  -- A rebuilt paragraph has equal text at a new address: adopt it once, so+  -- later passes compare by pointer rather than by content.+  | selectionText previous == plain = previous {selectionText = plain}+  | otherwise =+      let clamped o = let o' = min (T.length plain) o in (cursorAtOffset plain o', o')+          cursorOff = if selectionCursor previous < selectionAnchor previous then selectionStart previous else selectionEnd previous+       in selectionAt plain (clamped (anchorOffset previous)) (clamped cursorOff) False False++selectionEditor :: TB.TextBuffer -> RichSelection -> Editor+selectionEditor buffer selection =+  Editor (TB.withCursor (selectionCursor selection) buffer) (selectionAnchor selection) emptyHistory++-- | A selection between two positions whose document offsets are known, so+-- drawing reads them rather than walking the text each pass.+selectionAt :: Text -> (TB.Cursor, Int) -> (TB.Cursor, Int) -> Bool -> Bool -> RichSelection+selectionAt txt (anchor, a) (cursor, c) dragging moved =+  RichSelection txt anchor cursor dragging moved (min a c) (max a c)++-- | 'selectionAt' for positions a text command left, which carry no offset.+selectionIn :: Text -> TB.Cursor -> TB.Cursor -> Bool -> Bool -> RichSelection+selectionIn txt anchor cursor = selectionAt txt (anchor, cursorOffset txt anchor) (cursor, cursorOffset txt cursor)++-- | The anchor's document offset: whichever end of the range it is.+anchorOffset :: RichSelection -> Int+anchorOffset s = if selectionAnchor s <= selectionCursor s then selectionStart s else selectionEnd s++selectionOffsets :: RichSelection -> Maybe (Int, Int)+selectionOffsets s+  | selectionStart s == selectionEnd s = Nothing+  | otherwise = Just (selectionStart s, selectionEnd s)++-- | Highlight the selected range of each token using its per-run 'FontMetrics'.+selectionOps :: Float -> Float -> Line -> Int -> Int -> Color -> [DrawOp]+selectionOps x0 y0 line lo hi color = concatMap drawToken (lineTokens line)+  where+    drawToken (x, tok) =+      let Token txt _ kind w start fm = tok+          end = start + T.length txt+          a = max lo start+          b = min hi end+       in if b <= a+            then []+            else+              [ FillRect+                  (Rect (x0 + x + sx) (y0 + lineTop line) (ex - sx) (lineHeight line))+                  color+              | (sx, ex) <-+                  -- A token that may break anywhere is one cluster, as wide+                  -- as the shaped line draws it.+                  if kind == Glyph || kind == GlyphSpace then [(0, w)] else selectionSpans fm txt (a - start) (b - start)+              ]++-- | The position under a point, and its document offset.+pointAt :: Text -> [Line] -> Rect -> V2 -> (TB.Cursor, Int)+pointAt plain lines' (Rect rx ry _ _) (V2 px py) =+  let line = lineAtY (py - ry) lines'+      offset = max 0 (min (T.length plain) (tokenIndexAtX line (px - rx)))+   in (cursorAtOffset plain offset, offset)++lineAtY :: Float -> [Line] -> Line+lineAtY y = go+  where+    go [] = Line 0 0 0 0 0 []+    go (line : rest)+      | null rest || y < lineTop line + lineHeight line = line+      | otherwise = go rest++tokenIndexAtX :: Line -> Float -> Int+tokenIndexAtX line x = go (lineTokens line)+  where+    go [] = lineStart line+    go ((tokenX, tok) : rest)+      | x <= tokenX = tokenStart tok+      | null rest && x >= tokenX + tokenWidth tok = tokenStart tok + T.length (tokenText tok)+      | x <= tokenX + tokenWidth tok = indexWithin tokenX tok+      | otherwise = go rest+    indexWithin tokenX tok =+      let txt = tokenText tok+          kind = tokenKind tok+       in tokenStart tok+            + if kind == Glyph || kind == GlyphSpace+              then (if x - tokenX < tokenWidth tok / 2 then 0 else T.length txt)+              else textIndexAtX (tokenMetrics tok) txt (x - tokenX)++-- | @measureAt ref extentAt width@ is @extentAt width@, reused from @ref@+-- when it holds the extent at that width, and otherwise computed and left+-- there. A paragraph keeps its reference while its pieces stay the same, so+-- the solver's check of last frame's layout, which measures the paragraph+-- again at the width it offered then, costs nothing even when that width is a+-- cap the paragraph stays under, and its second measure at a new width reuses+-- the first. Only the extent is kept, never the lines. Reading and writing+-- the reference from pure code is safe because @extentAt@ is a pure function+-- of the width for those pieces: the reference only decides what is shared.+measureAt :: IORef Measured -> (Float -> (Float, Float)) -> Float -> (Float, Float)+measureAt ref extentAt width = unsafeDupablePerformIO $ do+  kept <- readIORef ref+  case kept of+    Measured w ew eh | w == width -> pure (ew, eh)+    _ -> case extentAt width of+      (!ew, !eh) -> (ew, eh) <$ writeIORef ref (Measured width ew eh)+{-# NOINLINE measureAt #-}++-- | Cache size at which stale paragraphs are first pruned.+paragraphBound :: Int+paragraphBound = 4096++-- | Extract 'TextFont' from a 'Layout', resolving relative 'fontSizeScale'+-- factors against @baseSize@. Colour-only variants resolve to the regular face+-- in 'resolveTextFont'.+pieceFont :: Float -> Layout -> TextFont+pieceFont baseSize l =+  TextFont+    (resolveFontSize baseSize (layoutFontSize l))+    (layoutFontVariant l)+    (layoutFontWeight l)+    (layoutFontStyle l)+    (layoutTextDecoration l)+    (layoutFontTabular l)+ -- | A piece's colour: its own, else the link colour for a link, else its--- font variant's colour.+-- colour for its tone and face, as for a label. pieceColor :: Theme -> Layout -> Maybe Text -> Color pieceColor theme l target =-  let variantColor = case layoutFontVariant l of-        FontHeading -> themeAccent theme-        FontMuted -> themeMuted theme-        FontDanger -> themeRed theme-        _ -> styleFg (themePanel theme)-   in fromMaybe (maybe variantColor (const (themeLink theme)) target) (layoutFontColor l)+  let toneCol = textToneColor theme (layoutFontTone l)+   in fromMaybe (maybe toneCol (const (themeLink theme)) target) (layoutFontColor l) --- | A piece's line metrics and its tokens measured in its font.-measurePiece :: Context -> (Int, (Text, TextFont, Color, Maybe Text)) -> IO (Run, [Token])-measurePiece ctx (i, (txt, font, color, target)) = do+-- | A piece's line metrics and its tokens measured in its font. A piece that+-- may break anywhere is measured a character cluster at a time.+measurePiece :: Context -> (Int, Int, (Inline, TextFont, Color, TextBreak)) -> IO (Run, [Token])+measurePiece ctx (i, start, (Inline txt _ target bg tip, font, color, brk)) = do   (fm, _) <- resolveTextFont ctx font-  tokens <- mapM (measure fm) (T.groupBy (\a b -> kindOf a == kindOf b && kindOf a /= Break) txt)-  pure (Run font color (fmLineHeight fm) (fmAscent fm) target, tokens)+  let anywhere = brk == BreakAnywhere+      parts+        | anywhere = clusters txt+        | otherwise = T.groupBy (\a b -> kindOf False a == kindOf False b && kindOf False a /= Break) txt+  wholeMetrics <- if anywhere then prepareFontMetrics fm txt else pure fm+  -- A cluster is as wide as its share of the shaped piece, as the line+  -- holding it is drawn: alone it would miss the kerning, the fallback font+  -- and a mark drawn over the letter before it.+  let carets = if anywhere then stCarets <$> fmShape wholeMetrics txt else Nothing+  tokens <- reverse . snd <$> foldM (measure fm anywhere wholeMetrics carets) (start, []) parts+  pure (Run font color (fmLineHeight fm) (fmAscent fm) target bg tip, tokens)   where-    kindOf c+    kindOf anywhere c       | c == '\n' = Break+      | anywhere && (c == ' ' || c == '\t') = GlyphSpace+      | anywhere = Glyph       | c == ' ' || c == '\t' = Space       | otherwise = Word-    measure fm part = do-      let kind = kindOf (T.head part)-      w <- if kind == Break then pure 0 else lineWidthIO fm part-      pure (Token part i kind w)+    measure fm anywhere wholeMetrics carets (at, acc) part = do+      let kind = kindOf anywhere (T.head part)+      prepared <- if anywhere then pure wholeMetrics else prepareFontMetrics fm part+      let w = case carets of+            _ | kind == Break -> 0+            Just cs+              | let i0 = at - start+                    i1 = i0 + T.length part+                    lenCs = sizeofPrimArray cs+              , i0 >= 0 && i1 < lenCs ->+                  abs (indexPrimArray cs i1 - indexPrimArray cs i0)+            _ -> Font.lineWidth prepared part+          token = Token part i kind w at prepared+      pure (at + T.length part, token : acc) --- | Greedy lines at @width@: a break goes between words only at spaces or--- line breaks, spaces at a wrap are dropped, and a word wider than the line--- takes a line of its own.-layoutLines :: SmallArray Run -> (Float, Float) -> Float -> [Token] -> [Line]-layoutLines runs (emptyH, emptyAscent) width = go 0 [] 0 [] True+-- | Text split into user-perceived characters ('clusterLength'), closely+-- enough for wrapping.+clusters :: Text -> [Text]+clusters t = case clusterLength t of+  0 -> []+  n -> T.take n t : clusters (T.drop n t)++-- | Greedy line breaking at @width@, aligned by @align@. Breaks only at+-- spaces or newlines, drops spaces at a wrap, and gives an overlong word its+-- own line.+layoutLines :: SmallArray Run -> (Float, Float) -> AlignX -> Float -> [Token] -> [Line]+layoutLines runs (emptyH, emptyAscent) align width = go 0 0 [] 0 []   where     -- @placed@ holds the line's tokens in reverse, @pending@ the spaces since-    -- its last word; @fresh@ whether the line starts after a wrap.-    go top placed x pending fresh toks = case toks of-      [] -> [finish top placed x]+    -- its last word. A wrapped line starts at its first word, so it has none.+    go top start placed x pending toks = case toks of+      [] -> [finish start top placed x]       tok : rest -> case tokenKind tok of-        Break -> let line = finish top placed x in line : go (top + lineHeight line) [] 0 [] False rest-        Space -> go top placed x (tok : pending) fresh rest+        Break ->+          let line = finish start top placed x+              nextStart = tokenStart tok + T.length (tokenText tok)+           in line : go (top + lineHeight line) nextStart [] 0 [] rest+        Space -> go top start placed x (tok : pending) rest+        Glyph -> placeGroup top start placed x pending [tok] rest+        GlyphSpace -> placeGroup top start placed x pending [tok] rest         Word ->           let (word, rest') = span (\t -> tokenKind t == Word) toks-              wordW = sum (map tokenWidth word)-              spaceW = if null placed && fresh then 0 else sum (map tokenWidth pending)-           in if not (null placed) && x + spaceW + wordW > width-                then-                  let line = finish top placed x-                   in line : go (top + lineHeight line) [] 0 [] True toks-                else-                  let (placed', x') = foldl' place (placed, x) (if null placed && fresh then [] else reverse pending)-                      (placed'', x'') = foldl' place (placed', x') word-                   in go top placed'' x'' [] False rest'+           in placeGroup top start placed x pending word rest'+    placeGroup top start placed x pending group rest+      | not (null placed) && x + spaceW + groupW > width =+          let line = finish start top placed x+           in line : go (top + lineHeight line) firstStart [] 0 [] (group ++ rest)+      | otherwise =+          let (placed', x') = foldl' place (placed, x) (reverse pending)+              (placed'', x'') = foldl' place (placed', x') group+           in go top start placed'' x'' [] rest+      where+        groupW = sum (map tokenWidth group)+        spaceW = sum (map tokenWidth pending)+        firstStart = maybe start tokenStart (listToMaybe group)     place (acc, x) tok = ((x, tok) : acc, x + tokenWidth tok)-    finish top placed x =-      let toks = reverse placed+    finish start top placed x =+      -- An overlong word's line starts at the left edge, as with+      -- 'AlignStart', rather than before it.+      let shift = max 0 (width - x) * alignXFraction align+          toks = reverse (if shift == 0 then placed else [(tx + shift, tok) | (tx, tok) <- placed])           metrics = [indexSmallArray runs (tokenRun tok) | (_, tok) <- toks]           (h, ascent) = case metrics of             [] -> (emptyH, emptyAscent)@@ -336,4 +702,4 @@               let ascent' = maximum (map runAscent metrics)                   descent = maximum [runLineHeight r - runAscent r | r <- metrics]                in (ascent' + descent, ascent')-       in Line top h ascent x toks+       in Line start top h ascent x toks
− lib/NanoUI/Widgets/Select.hs
@@ -1,116 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}---- | Dropdown select.-module NanoUI.Widgets.Select-  ( select-  , select'-  , selectWith-  , selectWith'-  , boundedSelect-  , boundedSelect'-  , enumSelect-  , enumSelect'-  )-where--import Control.Monad (forM_, when)-import Data.IORef (writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)-import Data.Text qualified as T-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , adoptStoreInt-  , getStore-  , intKey-  , recordStoreInt-  , registerFocusable-  , modifyStore-  )-import NanoUI.Font (menuItemRowH)-import NanoUI.Frame.Select (selectDropPickIndex, selectDropRect)-import NanoUI.Input (inputMousePos, inputMousePressed, inputMouseReleased)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO)-import NanoUI.Store (WidgetStore (..), isSelectOpen, setSelectOpen)-import NanoUI.Style (Layout, defaultLayout)-import NanoUI.Types (Rect (..), clamp, rectContains, rectHit, rectNonEmpty, v2Y)-import NanoUI.Widgets.Combinators (withBoundedIndex)-import NanoUI.Widgets.Node (Response, addWidgetWithOptions, respRect, setChanged)---- | Dropdown over @options@ in fold order. Pass the selected index; the result--- is the index after this frame's pick.-{-# INLINE select #-}-select :: (Foldable f, Ui :> es) => f Text -> Int -> Eff es Int-select options index = snd <$> selectWith' id options index--{-# INLINE select' #-}-select' :: (Foldable f, Ui :> es) => f Text -> Int -> Eff es (Response, Int)-select' = selectWith' id---- | 'select' with a layout modifier.-{-# INLINE selectWith #-}-selectWith :: (Foldable f, Ui :> es) => (Layout -> Layout) -> f Text -> Int -> Eff es Int-selectWith f options index = snd <$> selectWith' f options index--selectWith' ::-  (Foldable f, Ui :> es) =>-  (Layout -> Layout) ->-  f Text ->-  Int ->-  Eff es (Response, Int)-selectWith' f options index = do-  wid <- nextId-  ctx <- askContext-  uiIO $ registerFocusable ctx wid-  let-    opts = case foldr (:) [] options of-      [] -> [""]-      xs -> xs-    n = length opts-    key = intKey wid-  stored <- uiIO $ adoptStoreInt ctx wid key (clamp 0 (n - 1) index)-  store0 <- uiIO (getStore ctx)-  let-    current = clamp 0 (n - 1) stored-    open = isSelectOpen store0 key-  resp <- addWidgetWithOptions wid NodeSelect "" opts 0 (f defaultLayout)-  inp <- askInput-  let-    rect@(Rect rx ry rw rh) = respRect resp-    mouse = inputMousePos inp-    dropRect = selectDropRect rx ry rw rh n-    picked-      | open && rectNonEmpty rect && rectContains dropRect mouse && inputMouseReleased inp =-          selectDropPickIndex dropRect menuItemRowH n (v2Y mouse)-      | otherwise = Nothing-    finalIdx = maybe current (clamp 0 (n - 1)) picked-  -- Opening, closing or picking changes the store, which wakes the loop.-  uiIO $ do-    when (rectHit rect mouse && inputMousePressed inp) $ do-      modifyStore ctx (\st -> setSelectOpen st key (not open))-      writeIORef (ctxFocusId ctx) wid-    forM_ picked $ \i -> do-      modifyStore ctx (\st -> setSelectOpen (st {storeInt = IM.insert key i (storeInt st)}) key False)-      writeIORef (ctxFocusId ctx) wid-    recordStoreInt ctx key finalIdx-  -- Compare with the caller's index, not 'current': a dropdown or keyboard-  -- pick lands in the store between frames and must still report a change.-  pure (setChanged (finalIdx /= clamp 0 (n - 1) index) resp, finalIdx)---- | Select over every value of a bounded enum, labelled by @encode@.-{-# INLINE boundedSelect #-}-boundedSelect :: (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es a-boundedSelect encode value = snd <$> boundedSelect' encode value--boundedSelect' :: (Bounded a, Enum a, Ui :> es) => (a -> Text) -> a -> Eff es (Response, a)-boundedSelect' encode value = withBoundedIndex encode value select'---- | 'boundedSelect' labelled with 'show'.-{-# INLINE enumSelect #-}-enumSelect :: (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es a-enumSelect = boundedSelect (T.pack . show)--enumSelect' :: (Bounded a, Enum a, Show a, Ui :> es) => a -> Eff es (Response, a)-enumSelect' = boundedSelect' (T.pack . show)
− lib/NanoUI/Widgets/Slider.hs
@@ -1,101 +0,0 @@--- | Horizontal slider control.-module NanoUI.Widgets.Slider-  ( slider-  , slider'-  , sliderWith-  , sliderWith'-  )-where--import Control.Monad (when)-import Data.IORef (readIORef, writeIORef)-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , adoptStoreFloat-  , intKey-  , recordStoreFloat-  , registerFocusable-  , writeStoreFloat-  , getsOverlay-  , OverlayState (..)-  )-import NanoUI.Font (sliderHandleSlack, sliderTrackBounds)-import NanoUI.Frame.Hit (scrollHitRect)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (inputMouseDown, inputMousePressed)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, withKey)-import NanoUI.Style (Layout, defaultLayout, fillW)-import NanoUI.Types (Rect (..), clamp)-import NanoUI.Widgets.Behavior (DragAxis (..), KeyNav (..), useDrag1D, useKeyNav)-import NanoUI.Widgets.Node (Response, addWidget, setChanged)---- | Slider over @[minV, maxV]@ that fills the available width. Pass the--- current value; the result is the value after this frame's drag or arrow--- keys.-{-# INLINE slider #-}-slider :: Ui :> es => Float -> Float -> Float -> Eff es Float-slider minV maxV value = snd <$> sliderWith' id minV maxV value--{-# INLINE slider' #-}-slider' :: Ui :> es => Float -> Float -> Float -> Eff es (Response, Float)-slider' = sliderWith' id---- | 'slider' with a layout modifier.------ @--- volume' <- sliderWith (fixedW 200) 0 100 volume--- @-{-# INLINE sliderWith #-}-sliderWith :: Ui :> es => (Layout -> Layout) -> Float -> Float -> Float -> Eff es Float-sliderWith f minV maxV value = snd <$> sliderWith' f minV maxV value--sliderWith' ::-  Ui :> es =>-  (Layout -> Layout) -> Float -> Float -> Float -> Eff es (Response, Float)-sliderWith' f minV maxV value = do-  wid <- nextId-  ctx <- askContext-  inp <- askInput-  uiIO $ registerFocusable ctx wid-  let key = intKey wid-  current <- uiIO $ adoptStoreFloat ctx wid key value-  let-    frac = if maxV > minV then (current - minV) / (maxV - minV) else 0-  resp <- addWidget wid NodeSlider "" frac (f (fillW defaultLayout))-  active <- uiIO (readIORef (ctxActiveId ctx))-  blocked <- uiIO (getsOverlay ctx osLastPointerBlocked)-  mrect <- uiIO (scrollHitRect ctx wid)-  let-    isActive = active == wid-    heldByOther =-      inputMouseDown inp-        && not (inputMousePressed inp)-        && hashWidgetId active /= 0-        && not isActive-    track0 =-      case mrect of-        Just (Rect x y w h) ->-          let tr = sliderTrackBounds x y w h-           in Rect (rectX tr) (rectY tr - sliderHandleSlack) (rectW tr) (rectH tr + 2 * sliderHandleSlack)-        Nothing -> Rect 0 0 0 0-    track = if blocked || heldByOther then Rect 0 0 0 0 else track0-  (dragged, dragging) <- withKey ("drag" :: Text) (useDrag1D DragAxisX minV maxV current track)-  when (dragging && not isActive) $ uiIO $ writeIORef (ctxActiveId ctx) wid-  when ((not dragging || blocked) && isActive) $-    uiIO $ writeIORef (ctxActiveId ctx) (WidgetId 0)-  nav <- useKeyNav wid-  let-    range = maxV - minV-    step = if range > 0 then range / 100 else 0-    navStep =-      (if knRight nav || knUp nav then 1 else 0 :: Int)-        - (if knLeft nav || knDown nav then 1 else 0)-    baseVal = if dragging then dragged else current-    finalVal = clamp minV maxV (baseVal + fromIntegral navStep * step)-  uiIO $ do-    writeStoreFloat ctx wid key finalVal-    recordStoreFloat ctx key finalVal-  pure (setChanged (finalVal /= current) resp, finalVal)
− lib/NanoUI/Widgets/SplitPane.hs
@@ -1,328 +0,0 @@-{-# LANGUAGE LambdaCase #-}---- | Pure pane-grid tree model and geometry, modelled on iced's @PaneGrid@.------ A 'GridNode' is a binary split tree of panes. Each split stores an axis--- ('AxisV' = vertical divider splitting width, 'AxisH' = horizontal divider--- splitting height), a ratio in @[0,1]@ for the first (A) side, and the two--- child subtrees. Every pane and split has a globally unique 'Word64' id so--- pane state can be keyed by pane id regardless of position in the tree.------ All functions here are pure; the interactive wrapper in--- "NanoUI.Widgets.PaneGrid" persists a 'GridNode' as a "Data.Dynamic" value--- in the widget store.-module NanoUI.Widgets.SplitPane-  ( GridAxis (..)-  , GridNode (..)-  , PaneDrop (..)-  , treePanes-  , treeSize-  , paneExist-  , subtreeMin-  , mainMins-  , mainLen-  , splitLength-  , layoutNode-  , DividerInfo (..)-  , treeSplit-  , treeSetRatio-  , treeRemovePane-  , treeMovePane-  , clampTreeRatio-  , dropPreview-  , dropTargetForPane-  , topLevelDropTarget-  ) where--import Control.Applicative ((<|>))-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as M-import Data.Word (Word64)-import NanoUI.Types (Rect (..), V2 (..), clamp, clamp01, rectH, rectNonEmpty, rectW, rectX, rectY)---- | Divider orientation. 'AxisV' draws a vertical divider (panes left/right),--- 'AxisH' draws a horizontal divider (panes stacked top/bottom).-data GridAxis = AxisV | AxisH-  deriving (Eq, Ord, Show, Enum, Bounded)---- | Binary split tree node. Pane and split ids share one monotonic counter.--- Positional (non-record) so the multi-constructor type keeps total fields.-data GridNode-  = Split-      !Word64-      -- ^ Split id.-      !GridAxis-      -- ^ Orientation of the divider.-      !Float-      -- ^ Ratio in @[0,1]@ for the A side.-      !GridNode-      -- ^ Left / top subtree.-      !GridNode-      -- ^ Right / bottom subtree.-  | Pane-      !Word64-      -- ^ Pane id.-  deriving (Eq, Show)---- | Result of dropping a dragged pane on a target pane.-data PaneDrop-  = DropSwap Word64-      -- ^ Drop on the center of the pane: the two panes swap places.-  | DropSplit Word64 GridAxis Bool-      -- ^ Drop near an edge: the target pane splits along the axis and the-      -- dragged pane moves into the new child. 'True' puts the dragged pane on-      -- the A (left/top) side, 'False' on the B (right/bottom) side.-  | DropTop GridAxis Bool-      -- ^ Drop on the outer edge of the whole grid: the entire tree is wrapped-      -- in a new top-level split and the dragged pane takes one side, so the-      -- rest of the grid collapses onto the other. 'True' puts the dragged-      -- pane on the A (left/top) side, 'False' on the B (right/bottom) side.-  deriving (Eq, Show)---- | Fold a tree bottom-up: @onPane@ for each pane id, @onSplit@ for each--- split (id, axis, ratio) with its already-folded A and B sides. The sides--- are passed lazily, so a short-circuiting @onSplit@ stops early.-foldGrid :: (Word64 -> r) -> (Word64 -> GridAxis -> Float -> r -> r -> r) -> GridNode -> r-foldGrid onPane onSplit = go-  where-    go (Pane pid) = onPane pid-    go (Split sid axis ratio a b) = onSplit sid axis ratio (go a) (go b)---- | Pane ids in the tree (depth-first, A then B).-treePanes :: GridNode -> [Word64]-treePanes = foldGrid pure (\_ _ _ a b -> a <> b)---- | Number of panes.-treeSize :: GridNode -> Int-treeSize = foldGrid (const 1) (\_ _ _ a b -> a + b)---- | Does a pane with the given id exist?-paneExist :: GridNode -> Word64 -> Bool-paneExist t p = foldGrid (== p) (\_ _ _ a b -> a || b) t---- | Minimum (width, height) that must be reserved for a subtree under a--- 'minSize' per-pane floor and 'spacing' between every split level.-subtreeMin :: Float -> Float -> GridNode -> (Float, Float)-subtreeMin minSize spacing = \case-  Pane _ -> (minSize, minSize)-  Split _ axis _ a b ->-    let (wa, ha) = subtreeMin minSize spacing a-        (wb, hb) = subtreeMin minSize spacing b-     in case axis of-          AxisV -> (wa + spacing + wb, max ha hb)-          AxisH -> (max wa wb, ha + spacing + hb)---- | Extent of a region along a split's main axis.-mainLen :: GridAxis -> Rect -> Float-mainLen AxisV = rectW-mainLen AxisH = rectH---- | The subtree minima that apply along a split's main axis: widths for--- 'AxisV' (panes left/right), heights for 'AxisH' (panes stacked).-mainMins :: GridAxis -> (Float, Float) -> (Float, Float) -> (Float, Float)-mainMins AxisV (wa, _) (wb, _) = (wa, wb)-mainMins AxisH (_, ha) (_, hb) = (ha, hb)---- | A-side extent for a split along its main axis, honouring the subtree--- minima. The ratio shares out the extent left after the gutter between the--- sides, so a 0.5 split gives both sides the same length. Falls back to the--- raw share when the region is too small to satisfy both minima.-splitLength :: Float -> Float -> Float -> Float -> Float -> Float-splitLength spacing avail minA minB ratio-  | avail <= 0 = 0-  | lo <= hi = clamp lo hi share-  | otherwise = clamp 0 avail share-  where-    share = ratio * max 0 (avail - spacing)-    lo = minA-    hi = avail - spacing - minB---- | Carve a region at offset @d@ along the main axis into (A, B, divider band).-splitBounds :: GridAxis -> Float -> Rect -> Float -> (Rect, Rect, Rect)-splitBounds AxisV spacing r d =-  let avail = rectW r-   in ( r {rectW = d}-      , r {rectX = rectX r + d + spacing, rectW = avail - d - spacing}-      , Rect (rectX r + d) (rectY r) spacing (rectH r)-      )-splitBounds AxisH spacing r d =-  let avail = rectH r-   in ( r {rectH = d}-      , r {rectY = rectY r + d + spacing, rectH = avail - d - spacing}-      , Rect (rectX r) (rectY r + d) (rectW r) spacing-      )---- | Per-split divider information: the split's own region (where the ratio--- applies), the exact spacing band, and the axis / ratio / id.-data DividerInfo = DividerInfo-  { diSplitId :: {-# UNPACK #-} !Word64-  , diAxis :: !GridAxis-  , diRegion :: !Rect-  , diBand :: !Rect-  , diRatio :: {-# UNPACK #-} !Float-  }-  deriving (Eq, Show)---- | Lay out a tree into per-pane regions and divider bands within 'Rect'.--- Dividers are reported parent-before-child so dragging a divider resizes its--- immediate subtrees relative to the same region.-layoutNode :: Float -> Float -> GridNode -> Rect -> (Map Word64 Rect, [DividerInfo])-layoutNode minSize spacing sp r =-  case sp of-    Pane pid -> (M.singleton pid r, [])-    Split sid axis ratio0 a b ->-      let (wa, ha) = subtreeMin minSize spacing a-          (wb, hb) = subtreeMin minSize spacing b-          (mA, mB) = mainMins axis (wa, ha) (wb, hb)-          (rA, rB, band) = splitBounds axis spacing r (splitLength spacing (mainLen axis r) mA mB ratio0)-          self = DividerInfo sid axis r band ratio0-          (regionsA, divsA) = layoutNode minSize spacing a rA-          (regionsB, divsB) = layoutNode minSize spacing b rB-       in (M.union regionsA regionsB, self : divsA <> divsB)---- | Split the pane (first arg) along the axis with a 0.5 ratio, inserting the--- new pane. 'newOnA' places the new pane on the A (left/top) side of the new--- split; 'False' puts it on the B (right/bottom) side. Returns the updated--- tree (unchanged if the pane does not exist).-treeSplit :: Word64 -> Word64 -> GridAxis -> Bool -> Word64 -> GridNode -> GridNode-treeSplit targetPaneId splitId axis newOnA newPaneId = foldGrid onPane Split-  where-    onPane p-      | p /= targetPaneId = Pane p-      | newOnA = Split splitId axis 0.5 (Pane newPaneId) (Pane p)-      | otherwise = Split splitId axis 0.5 (Pane p) (Pane newPaneId)---- | Set the raw ratio of a split (clamped to @[0,1]@).-treeSetRatio :: Word64 -> Float -> GridNode -> GridNode-treeSetRatio splitId r =-  foldGrid Pane (\sid ax r0 -> Split sid ax (if sid == splitId then clamp01 r else r0))---- | Remove a pane. The sibling subtree absorbs its space. @Nothing@ if the--- pane does not exist or removing it would empty the tree.-treeRemovePane :: Word64 -> GridNode -> Maybe GridNode-treeRemovePane pid = foldGrid onPane onSplit-  where-    onPane p = if p == pid then Nothing else Just (Pane p)-    onSplit sid ax r0 ma mb = case (ma, mb) of-      (Just a, Just b) -> Just (Split sid ax r0 a b)-      (Nothing, b) -> b-      (a, Nothing) -> a---- | Swap two panes by id (content follows the pane id).-treeSwapPanes :: Word64 -> Word64 -> GridNode -> GridNode-treeSwapPanes a b = foldGrid (\p -> Pane (if p == a then b else if p == b then a else p)) Split---- | Move a pane onto a drop target. Center drops swap the two panes; edge--- drops split the target pane with the given fresh split id and move the--- dragged pane into the new child; top-level drops wrap the whole tree in a--- new root split with the dragged pane on one side.-treeMovePane :: Word64 -> Word64 -> PaneDrop -> GridNode -> Maybe GridNode-treeMovePane moved splitId dt tree-  | not (paneExist tree moved) = Nothing-  | otherwise =-      case dt of-        DropSwap tgt-          | tgt == moved -> Nothing-          | not (paneExist tree tgt) -> Nothing-          | otherwise -> Just (treeSwapPanes moved tgt tree)-        DropSplit tgt axis onA-          | tgt == moved -> Nothing-          | not (paneExist tree tgt) -> Nothing-          | otherwise -> do-              t' <- treeRemovePane moved tree-              Just (treeSplit tgt splitId axis onA moved t')-        DropTop axis onA-          | treeSize tree <= 1 -> Nothing-          | otherwise -> do-              t' <- treeRemovePane moved tree-              Just-                ( if onA-                    then Split splitId axis 0.5 (Pane moved) t'-                    else Split splitId axis 0.5 t' (Pane moved)-                )---- | Find the split node with a given id (or 'Nothing').-findSplitNode :: GridNode -> Word64 -> Maybe GridNode-findSplitNode (Pane _) _ = Nothing-findSplitNode s@(Split sid0 _ _ a b) target-  | sid0 == target = Just s-  | otherwise = findSplitNode a target <|> findSplitNode b target---- | Clamp a proposed ratio for a split so both subtrees keep at least their--- minimum size within the given region.-clampTreeRatio :: GridNode -> Word64 -> Rect -> Float -> Float -> Float -> Float-clampTreeRatio tree splitId region spacing minSize r0 =-  case findSplitNode tree splitId of-    Nothing -> r0-    Just (Pane _) -> r0-    Just (Split _ ax _ a b) ->-      let avail = mainLen ax region-          usable = avail - spacing-       in if usable <= 0-            then r0-            else-              let (wa, ha) = subtreeMin minSize spacing a-                  (wb, hb) = subtreeMin minSize spacing b-                  (mA, mB) = mainMins ax (wa, ha) (wb, hb)-               in splitLength spacing avail mA mB r0 / usable---- | Which drop zone a pointer falls into for a target pane rect.-data EdgeZone = ZoneCenter | ZoneLeft | ZoneRight | ZoneTop | ZoneBottom---- | Classify a drop point into a zone of the target pane.-edgeZone :: Rect -> V2 -> EdgeZone-edgeZone r (V2 mx my)-  | not (rectNonEmpty r) = ZoneCenter-  | tx < 0.25 = ZoneLeft-  | tx > 0.75 = ZoneRight-  | ty < 0.25 = ZoneTop-  | ty > 0.75 = ZoneBottom-  | otherwise = ZoneCenter-  where-    tx = (mx - rectX r) / rectW r-    ty = (my - rectY r) / rectH r---- | Classify a drop point on a target pane into the 'PaneDrop' the drop--- performs: the pane's center swaps the two panes, an edge zone splits the--- target along that edge's axis with the dragged pane on the near side.-dropTargetForPane :: Rect -> V2 -> Word64 -> PaneDrop-dropTargetForPane r mouse tgt =-  case edgeZone r mouse of-    ZoneCenter -> DropSwap tgt-    ZoneLeft -> DropSplit tgt AxisV True-    ZoneRight -> DropSplit tgt AxisV False-    ZoneTop -> DropSplit tgt AxisH True-    ZoneBottom -> DropSplit tgt AxisH False---- | Classify a drop point against the grid's outer boundary. If the pointer--- sits within @band@ px of a grid edge, return the 'DropTop' target for that--- edge; otherwise 'Nothing'. Checked before pane-level drops so the outermost--- edge always restructures the whole grid.-topLevelDropTarget :: Float -> Rect -> V2 -> Maybe PaneDrop-topLevelDropTarget band r@(Rect l t w h) (V2 x y)-  | not (rectNonEmpty r) = Nothing-  | x <= l + band = Just (DropTop AxisV True)-  | x >= l + w - band = Just (DropTop AxisV False)-  | y <= t + band = Just (DropTop AxisH True)-  | y >= t + h - band = Just (DropTop AxisH False)-  | otherwise = Nothing---- | Drop preview for a drop target: the rect to highlight and the--- 'PaneDrop' the drop performs. The highlight is found by simulating the--- drop ('treeMovePane' with a throwaway split id) and laying the resulting--- tree out ('layoutNode') into the grid rect, so it is exactly the region the--- dragged pane will occupy after the drop, accounting for the restructuring--- that removing the pane causes (its parent split collapses and sibling--- subtrees expand) and for 'spacing' and min-size floors. Estimating the rect--- from the target's pre-drop bounds goes wrong wherever mixed 'AxisV' /--- 'AxisH' splits make those two layouts diverge. @spacing@ must be the gutter--- actually laid out between panes: 'NanoUI.Widgets.PaneGrid' passes--- @pgSpacing + 2 * pgLeeway@, not @pgSpacing@, or the preview regions drift--- from the on-screen layout. 'Nothing' when the drop cannot be performed--- (unknown pane ids, 'DropTop' on a single-pane grid).-dropPreview :: Float -> Float -> GridNode -> Word64 -> Rect -> PaneDrop -> Maybe (Rect, PaneDrop)-dropPreview minSize spacing tree moved baseRect dt = do-  t' <- treeMovePane moved 0 dt tree-  let (regions, _) = layoutNode minSize spacing t' baseRect-  r <- M.lookup moved regions-  pure (r, dt)
− lib/NanoUI/Widgets/Table.hs
@@ -1,692 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Table-  ( SortDir (..)-  , SortCol (..)-  , ColSize (..)-  , TableConfig (..)-  , TableResponse (..)-  , defaultTableConfig-  , table-  , tableWith-  , tableConfigured-  , simpleTable-  , useTableSort-  , tableHiddenIndices-  , sortRows-  , Colonnade-  , Headed (..)-  , headed-  , headless-  )-where--import Colonnade (Colonnade, Headed (..), headed, headless)-import Colonnade.Encode qualified as Encode-import Control.Monad (forM, forM_, unless, void, when)-import Control.Monad.ST (runST)-import Data.Char (isDigit)-import Data.Foldable (toList)-import Data.IntSet (IntSet)-import Data.IntSet qualified as IS-import Data.List (sortOn)-import Data.Maybe (fromMaybe, isJust, listToMaybe)-import Data.Ord (Down (..))-import Data.Text (Text)-import Data.Text qualified as T-import Data.Primitive.PrimArray (PrimArray, generatePrimArray, indexPrimArray, newPrimArray, primArrayFromList, readPrimArray, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)-import Data.Primitive.SmallArray (SmallArray, indexSmallArray, mapSmallArray', newSmallArray, sizeofSmallArray, smallArrayFromList, unsafeFreezeSmallArray, writeSmallArray)-import Data.Primitive.Types (Prim)-import Data.Vector qualified as V-import Effectful (Eff, type (:>))-import qualified Data.IntMap.Strict as IM-import NanoUI.Context (Context (..), getPrevRect, getScrollOffset2D, getStore, intKey, linkScrollAxes, setStore, modifyStore)-import NanoUI.Hooks (useInt)-import NanoUI.Font (ScrollBarSlot (..), scrollBarGutter, tableCellInset, lineWidthIO)-import NanoUI.Input (Input (..), inputMouseDown, inputMousePos, inputMousePressed, inputMouseReleased)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, withKey)-import NanoUI.Store (WidgetStore (..), Slot (..), slotKey)-import NanoUI.Style (AlignX (..), AlignY (..), Direction (..), FontVariant (..), Layout (..), Padding (..), Sizing (..), defaultLayout, fillH, fillW, tight)-import Data.Bits ((.|.), shiftL)-import NanoUI.Types (Rect (..), clamp, rectH, rectW, rectY, v2X, V2 (..), rectContains)-import NanoUI.WidgetText (buttonFlagTable, tableHeaderLabel, tableSortReserve)-import NanoUI.Widgets.Behavior (dragThresholdPx, useReorder)-import NanoUI.Widgets.Combinators (buttonStyled)-import NanoUI.Widgets.Layout (column', panel', row', scrollAreaIdConfigured, separator, spacer)-import NanoUI.Frame.Scroll.Geometry (ScrollConfig (..), ScrollPolicy (..), scrollHorizontalHidden, scrollVerticalAuto, scrollVerticalHidden)-import NanoUI.Widgets.Node-  ( HasResponse (..)-  , Response (..)-  , rawRespRect-  , respClicked-  , respRightClicked-  , setChanged-  , setClicked-  , tagContainer-  , addWidgetStyled-  )---- | True if the first n column sizes contain ColStretch.-{-# INLINE tableStretchN #-}-tableStretchN :: Int -> [ColSize] -> Bool-tableStretchN n = any (== ColStretch) . take n---- | Columns fill the table width when one stretches or the table grows.-tableFillInner :: Bool -> Layout -> Bool-tableFillInner hasStretch outer =-  hasStretch-    || case layoutWidth outer of-      Grow _ -> True-      _ -> False--data SortDir = SortAsc | SortDesc-  deriving (Eq, Show, Enum, Bounded)--data SortCol = SortCol {sortColIndex :: !Int, sortColDir :: !SortDir}-  deriving (Eq, Show)--data ColSize = ColContent | ColStretch | ColFixed Float-  deriving (Eq, Show)--data TableConfig = TableConfig-  { tableFreezeCols :: {-# UNPACK #-} !Int-  , tableFreezeRows :: {-# UNPACK #-} !Int-  , tableColSizes :: ![ColSize]-  , tableHidden :: !IntSet-  }-  deriving (Eq, Show)--defaultTableConfig :: TableConfig-defaultTableConfig = TableConfig 0 0 [] IS.empty--data TableResponse = TableResponse-  { tableWidgetResponse :: !Response-  , tableSort :: !SortCol-  , tableColOrder :: ![Int]-  , tableHiddenCols :: !IntSet-  }-  deriving (Eq, Show)--instance HasResponse TableResponse where-  {-# INLINE toResponse #-}-  toResponse = tableWidgetResponse--tableHiddenIndices :: TableResponse -> [Int]-tableHiddenIndices = IS.toAscList . tableHiddenCols--packSort :: SortCol -> Int-packSort (SortCol c SortAsc) = c * 2-packSort (SortCol c SortDesc) = c * 2 + 1--unpackSort :: Int -> SortCol-unpackSort n = SortCol (n `div` 2) (if odd n then SortDesc else SortAsc)--clampSortCol :: Int -> SortCol -> SortCol-clampSortCol n (SortCol idx dir) = SortCol (clamp 0 (max 0 (n - 1)) idx) dir---- Sort mark in bits 16-17 (see tableSortMarkOf): the low nibbles are the--- font fields and a mark of 1 or 2 in bit 0-1 flips the header's font--- variant, which blanks the arrow glyph.-sortMarkStyle :: SortCol -> Int -> Int-sortMarkStyle sort idx-  | sortColIndex sort /= idx = 0-  | sortColDir sort == SortDesc = 2 `shiftL` 16-  | otherwise = 1 `shiftL` 16--sortRows :: Foldable f => Colonnade Headed row Text -> SortCol -> f row -> [row]-sortRows cols sort inputRows =-  let rows = toList inputRows-      n = V.length (Encode.getColonnade cols)-      idx = sortColIndex (clampSortCol n sort)-      enc = maybe (const T.empty) Encode.oneColonnadeEncode (Encode.getColonnade cols V.!? idx)-   in case sortColDir sort of-        SortAsc -> sortOn enc rows-        SortDesc -> sortOn (Down . enc) rows--columnCount :: Colonnade Headed row Text -> Int-columnCount = V.length . Encode.getColonnade--isNumericCell :: Text -> Bool-isNumericCell txt =-  let s = T.strip txt-      digits = case T.uncons s of-        Just (c, rest) | c == '-' || c == '+' -> rest-        _ -> s-   in not (T.null digits) && T.all isDigit digits---- | Content width and numeric flag of each column, measured once over the--- encoded rows.-columnMetrics :: Context -> V.Vector Text -> SmallArray (V.Vector Text) -> IO (PrimArray Float, SmallArray Bool)-columnMetrics ctx hdrs encoded = do-  let fm = ctxFontMetrics ctx-      mono = ctxMonoFontMetrics ctx-      cellPadX = 2 * tableCellInset-      count = V.length hdrs-      nRows = sizeofSmallArray encoded-      cell r c = indexSmallArray encoded r V.! c-  widths <- newPrimArray count-  numeric <- newSmallArray count False-  forM_ [0 .. count - 1] $ \c -> do-    hdrW <- (+ cellPadX) <$> lineWidthIO fm (hdrs V.! c <> tableSortReserve)-    let numericFrom !r = r >= nRows || (isNumericCell (cell r c) && numericFrom (r + 1))-        isNum = nRows > 0 && numericFrom 0-        font = if isNum then mono else fm-        widest !r !w-          | r >= nRows = pure w-          | otherwise = do-              width <- lineWidthIO font (cell r c)-              widest (r + 1) (max w (width + cellPadX))-    cellW <- widest 0 minColW-    writePrimArray widths c (if nRows == 0 then hdrW else max hdrW cellW)-    writeSmallArray numeric c isNum-  (,) <$> unsafeFreezePrimArray widths <*> unsafeFreezeSmallArray numeric--nextSortCol :: Int -> SortCol -> Int -> SortCol-nextSortCol n cur clicked =-  let clamped = clampSortCol n cur-   in if clicked == sortColIndex clamped-        then SortCol clicked (case sortColDir clamped of SortAsc -> SortDesc; SortDesc -> SortAsc)-        else SortCol clicked SortAsc--useTableSort :: Ui :> es => SortCol -> Eff es (SortCol, SortCol -> Eff es ())-useTableSort initial = do-  (packed, setPacked) <- useInt (packSort initial)-  pure (unpackSort packed, setPacked . packSort)---- | Header pointer gesture on column @i@, stored as one Int in the drag slot:--- 0 idle, @-(1000 + i)@ resizing, @-(2000 + i)@ dragging to reorder.-data HeaderDrag = HeaderIdle | HeaderResize !Int | HeaderReorder !Int-  deriving (Eq)--packHeaderDrag :: HeaderDrag -> Int-packHeaderDrag = \case-  HeaderIdle -> 0-  HeaderResize i -> -(1000 + i)-  HeaderReorder i -> -(2000 + i)--unpackHeaderDrag :: Int -> HeaderDrag-unpackHeaderDrag n-  | n <= -2000 = HeaderReorder (-2000 - n)-  | n <= -1000 = HeaderResize (-1000 - n)-  | otherwise = HeaderIdle---- Metadata is indexed by original column id after reordering/hiding. Keep--- it indexed throughout layout, rather than walking a list for each cell.-{-# INLINE primAt #-}-primAt :: Prim a => PrimArray a -> Int -> a -> a-primAt xs i fallback = if i >= 0 && i < sizeofPrimArray xs then indexPrimArray xs i else fallback--{-# INLINE smallAt #-}-smallAt :: SmallArray a -> Int -> a -> a-smallAt xs i fallback = if i >= 0 && i < sizeofSmallArray xs then indexSmallArray xs i else fallback--resolvedWidth :: SmallArray ColSize -> PrimArray Float -> PrimArray Float -> Int -> Float-resolvedWidth sizes contentWs stored i =-  let contentW = max minColW (primAt contentWs i minColW)-      saved = primAt stored i 0-   in case smallAt sizes i ColContent of-        ColStretch -> if saved > contentW then saved else contentW-        ColFixed f ->-          let base = max minColW f-           in if saved > 0 then max base saved else base-        ColContent -> if saved > 0 then max contentW saved else contentW---- Width floor a column cannot shrink under: its declared fixed width, else--- its content minimum. Shared by colSizing and the resize-drag clamp so a--- dragged or stored width never wraps the cell text.-colFloor :: SmallArray ColSize -> PrimArray Float -> Int -> Float-colFloor sizes contentWs i = case smallAt sizes i ColContent of-  ColFixed f -> max minColW f-  _ -> max minColW (primAt contentWs i minColW)--colSizing :: Bool -> Bool -> SmallArray ColSize -> PrimArray Float -> PrimArray Float -> Int -> Sizing-colSizing fillInner hasStretch sizes contentWs stored i =-  let saved = primAt stored i 0-      floorW = colFloor sizes contentWs i-   in case smallAt sizes i ColContent of-        ColFixed _ -> Fixed (max floorW saved)-        ColStretch-          | saved > 0 -> Fixed (max floorW saved)-          | fillInner -> Grow 1-          | otherwise -> Fixed floorW-        ColContent-          | saved > 0 -> Fixed (max floorW saved)-          | fillInner && not hasStretch -> Grow 1-          | otherwise -> Fixed floorW--colBoxLayout :: Sizing -> Float -> Layout-colBoxLayout sizing minCol =-  let base =-        tight $-          defaultLayout-            { layoutGap = 0-            , layoutMinW = minCol-            , -- Columns stretch to the row height so every cell's background-              -- and borders span the full row even when one cell wraps.-              layoutHeight = Grow 1-            }-    in case sizing of-        Fixed w -> base {layoutWidth = Fixed w, layoutMaxW = w}-        Grow g -> base {layoutWidth = Grow g}-        _ -> base {layoutWidth = Fit}---- | Sortable table with resizable, reorderable columns. @key@ tells tables in--- one scope apart, and the columns are a colonnade over @row@. Pass the--- current sort; the 'TableResponse' carries the sort after this frame's--- header clicks, along with the column order and hidden columns.-{-# INLINE table #-}-table :: (Foldable f, Ui :> es) => Text -> Colonnade Headed row Text -> f row -> SortCol -> Eff es TableResponse-table = tableConfigured defaultTableConfig id---- | 'table' with a layout modifier.-{-# INLINE tableWith #-}-tableWith :: (Foldable f, Ui :> es) => (Layout -> Layout) -> Text -> Colonnade Headed row Text -> f row -> SortCol -> Eff es TableResponse-tableWith = tableConfigured defaultTableConfig---- | A table of text rows under the given headers.-simpleTable :: (Foldable f, Ui :> es) => [Text] -> f [Text] -> Eff es TableResponse-simpleTable headers rows = do-  let cols = mconcat [headed h (\r -> smallAt r i "") | (i, h) <- zip [0 ..] headers]-      indexedRows = map smallArrayFromList (toList rows)-  table "simple" cols indexedRows (SortCol 0 SortAsc)---- | 'tableWith' with column sizes, frozen rows and columns, and initially--- hidden columns.-tableConfigured ::-  (Foldable f, Ui :> es) =>-  TableConfig ->-  (Layout -> Layout) ->-  Text ->-  Colonnade Headed row Text ->-  f row ->-  SortCol ->-  Eff es TableResponse-tableConfigured cfg f key cols inputRows curSort =-  withKey ("table:" <> key) $ do-    let outerLayout = f (tight . fillW $ defaultLayout {layoutGap = 0})-    stateWid <- nextId-    vWid <- nextId-    hWid <- nextId-    tableWid <- nextId-    let n = columnCount cols-        sort0 = clampSortCol n curSort-        stateKey = intKey stateWid-        hdrs = Encode.header id cols-        -- Each row is encoded once and shared by measuring, sorting and the-        -- cells; the sort orders row indices.-        encoded = smallArrayFromList [Encode.row id cols r | r <- toList inputRows]-    ctx <- askContext-    inp <- askInput-    st0 <- uiIO (getStore ctx)-    (!contentWs, !numeric) <- uiIO (columnMetrics ctx hdrs encoded)-    let sizes = smallArrayFromList (tableColSizes cfg)-        order0 = normalizeOrder n (IM.findWithDefault [0 .. n - 1] stateKey (storeIntList st0))-        hidden0 = IM.findWithDefault (tableHidden cfg) stateKey (storeIntSet st0)-        widths0 = take n (IM.findWithDefault [] stateKey (storeFloatList st0) ++ repeat 0)-        drag0 = unpackHeaderDrag (IM.findWithDefault 0 (slotKey SlotDrag stateKey) (storeInt st0))-        dragX0 = IM.findWithDefault 0 stateKey (storeFloat st0)-        dragW0 = IM.findWithDefault 0 (slotKey SlotDragW stateKey) (storeFloat st0)-        mx = v2X (inputMousePos inp)-        -- A drag cannot push a column under its colFloor: the column reserved-        -- that much space for its text, and going under it wraps the cell and-        -- drags the whole row taller.-        widths1 = case drag0 of-          HeaderResize c-            | inputMouseDown inp ->-                setAt c (max (colFloor sizes contentWs c) (dragW0 + mx - dragX0)) widths0-          _ -> widths0-    when (widths1 /= widths0) $ uiIO $-      modifyStore ctx (\st -> st {storeFloatList = IM.insert stateKey widths1 (storeFloatList st)})-    let hasStretch = tableStretchN n (tableColSizes cfg)-        indexedWidths = primArrayFromList widths1-        vis = filter (`IS.notMember` hidden0) order0-        freezeN = clamp 0 (length vis) (tableFreezeCols cfg)-        frozenIdx = take freezeN vis-        unfrozenIdx = drop freezeN vis-        nRows = sizeofSmallArray encoded-        sorted =-          sortIndices-            (sortColDir sort0)-            (mapSmallArray' (\cells -> fromMaybe T.empty (cells V.!? sortColIndex sort0)) encoded)-        pinnedN = min nRows (max 0 (tableFreezeRows cfg))-        scrollN = nRows - pinnedN-        rowMinH = 28-        fillInner = tableFillInner hasStretch outerLayout-        mins = generatePrimArray n (resolvedWidth sizes contentWs indexedWidths)-        colBoxes = smallArrayFromList [colBoxLayout (colSizing fillInner hasStretch sizes contentWs indexedWidths i) (primAt mins i minColW) | i <- [0 .. n - 1]]-        colBox i = smallAt colBoxes i (tight defaultLayout)-        resolvedW i = primAt mins i minColW-        cellLayouts = smallArrayFromList $ flip map [0 .. n - 1] $ \i ->-          (tight defaultLayout)-              { layoutWidth = Grow 1-              , layoutHeight = Grow 1-              , layoutAlignX = if smallAt numeric i False then AlignEnd else AlignStart-              , layoutAlignY = AlignMiddle-              , layoutMinH = rowMinH-              , layoutFontVariant = if smallAt numeric i False then FontMono else FontRegular-              }-        cellLayout i = smallAt cellLayouts i (tight defaultLayout)-        -- Cell @i@ of display row @ri@, which shows encoded row @r@.-        renderCell ri r i = do-          wid <- nextId-          void (addWidgetStyled wid NodeText (indexSmallArray encoded r V.! i) 0 (cellLayout i) (if even ri then 1 else 2))-        rowCells rowLay idxs colLays ri =-          gridColumnsLay rowLay idxs colLays [renderCell ri (indexPrimArray sorted ri) i | i <- idxs]-        paneRoot =-          (if fillInner then tight . fillW . fillH else tight . fillH) defaultLayout-        minSum idxs = sum (map (layoutMinW . colBox) idxs) + fromIntegral (max 0 (length idxs - 1))-        vLay fill =-          let base = tight . fillH $ defaultLayout {layoutGap = 0}-           in if fill then fillW base else base-        hRowLay = defaultLayout {layoutDirection = Row, layoutPadding = Padding 0 0 0 0, layoutGap = 0}-        paneLay fill idxs =-          let base = tight $ defaultLayout {layoutGap = 0, layoutHeight = Grow 1}-           in if fill then fillW (fillH base) else base {layoutWidth = Fit, layoutMinW = minSum idxs}-        gridRowLay idxs =-          (if fillInner then fillW else id) (tight $ defaultLayout {layoutGap = 0, layoutMinW = minSum idxs})-        -- Header row, its rule, the pinned rows and their rule: the same in both-        -- panes.-        headerBlock idxs = do-          hs <- row' (gridRowLay idxs) $-            forM (zip [0 :: Int ..] idxs) $ \(k, i) -> do-              when (k > 0) $ void separator-              withKey i $-                column' (colBox i) $-                  buttonStyled (tableHeaderLabel (fromMaybe T.empty (hdrs V.!? i))) (if sortColIndex sort0 == i then 1 else 0) (cellLayout i) (sortMarkStyle sort0 i .|. buttonFlagTable)-          void separator-          let !rowLay = gridRowLay idxs-              !colLays = map colBox idxs-          forM_ [0 .. pinnedN - 1] $ \ri ->-            withKey ("pin" :: Text, ri) $ do-              when (ri > 0) $ void separator-              rowCells rowLay idxs colLays ri-          when (pinnedN > 0 && scrollN > 0) $ void separator-          pure hs-        bodyBlock idxs = do-          (lo, hi) <--            if scrollN == 0-              then pure (0, -1)-              else uiIO $ do-                V2 _ scrollY <- getScrollOffset2D ctx vWid-                viewH <- maybe (rowMinH * 8) rectH <$> getPrevRect ctx vWid-                pure (listClipper scrollN scrollY viewH rowMinH)-          let !rowLay = gridRowLay idxs-              !colLays = map colBox idxs-              topH = fromIntegral lo * rowMinH-              botH = fromIntegral (max 0 (scrollN - hi - 1)) * rowMinH-          column' rowLay $ do-            when (topH > 0) $ void (spacer Fit (Fixed topH))-            forM_ [lo .. hi] $ \rowIdx ->-              withKey rowIdx $ do-                when (rowIdx > 0) $ void separator-                rowCells rowLay idxs colLays (rowIdx + pinnedN)-            when (botH > 0) $ void (spacer Fit (Fixed botH))-        frozenPane =-          column' (paneLay False frozenIdx) $ do-            hs <- headerBlock frozenIdx-            scrollAreaIdConfigured-              vWid-              (vLay False)-              (if null unfrozenIdx then scrollVerticalAuto else scrollVerticalHidden)-              (bodyBlock frozenIdx)-            pure hs-        unfrozenPane = do-          -- The body scroller has no padding, so its whole lane is gutter.-          let vGutter = scrollBarGutter ScrollBarList 0-              idxs = unfrozenIdx-          mPrevV <- uiIO (getPrevRect ctx vWid)-          let totalH = fromIntegral scrollN * rowMinH-              -- Prev-frame decision, one frame behind the body scroller's live 2D-              -- gutter: on the frame the vertical bar first appears (or vanishes)-              -- the header spacer disagrees with the body's reserved lane for one-              -- frame. The horizontal side dodges this class of lag by owning its-              -- bar inside the body scroller; the vertical lane cannot do that-              -- because the header must narrow by exactly the lane width at build-              -- time, and the body's live v-gutter is only known after this-              -- frame's solve. Known, accepted one-frame misalignment.-              hasVertBar = maybe (totalH > 100) (\r -> totalH > rectH r) mPrevV-          column' (paneLay fillInner idxs) $ do-            hs <--              row' (tight . (if fillInner then fillW else id) $ defaultLayout {layoutGap = 0}) $ do-                hs' <--                  scrollAreaIdConfigured-                    hWid-                    ( if fillInner-                        then fillW hRowLay-                        else hRowLay {layoutMinW = minSum idxs}-                    )-                    -- The header scroller is chrome-less: it follows the body's-                    -- horizontal offset (linkScrollAxes below) and clips the header-                    -- row at the pane edge. The horizontal scrollbar itself belongs-                    -- to the body scroller so it spans the full table width at the-                    -- table's bottom edge instead of sitting under the header.-                    scrollHorizontalHidden-                    (column' (gridRowLay idxs) (headerBlock idxs))-                when hasVertBar $ void (spacer (Fixed vGutter) Fit)-                pure hs'-            uiIO (linkScrollAxes ctx vWid hWid)-            -- The body owns both bars: the vertical one on the right, and the-            -- horizontal one at the bottom of the table. Its live 2D gutter logic-            -- reserves the lane exactly while the columns overflow, so the bar-            -- cannot flicker the way the prev-frame header lane did.-            scrollAreaIdConfigured-              vWid-              (vLay fillInner)-              (ScrollConfig ScrollAuto ScrollAuto True False)-              (bodyBlock idxs)-            pure hs-    column' outerLayout $ do-      showAllResp <--        if IS.null hidden0-          then pure Nothing-          else fmap Just $-            buttonStyled "Show all columns" 0 (tight . fillW $ defaultLayout) 0-      headerPairs <--        panel' paneRoot $ do-          tagContainer tableWid-          row' (paneRoot {layoutGap = 0}) $ do-            frozenHs <--              if null frozenIdx-                then pure []-                else zip frozenIdx <$> frozenPane-            when (not (null frozenIdx) && not (null unfrozenIdx)) $ void separator-            unfrozenHs <--              if null unfrozenIdx then pure [] else zip unfrozenIdx <$> unfrozenPane-            pure (frozenHs ++ unfrozenHs)-      mBodyRect <- uiIO (getPrevRect ctx vWid)-      let mouse = inputMousePos inp-          edgePad = 4-          -- Resize grab zone spans the header band plus the body scroller: a-          -- column boundary is resizable anywhere down the table, not just on-          -- the header cell. The bottom anchor is the body scroller's rect-          -- (prev frame: readable at build time). The resize cursor-          -- (Frame.Cursor.tableColResizeCursorKind) locates the same scroller-          -- structurally and uses its current-frame rect, so the grab zone and-          -- the cursor zone are the same rect and cannot drift apart. First-          -- frame (no prev rect yet): header band only.-          hdrSpans =-            [ (rectY rr, rectY rr + rectH rr)-            | (_, r) <- headerPairs-            , let rr = rawRespRect r-            ]-          (edgeTop, edgeBot) = case hdrSpans of-            [] -> (0, 0)-            _ ->-              ( minimum (map fst hdrSpans)-              , maybe (maximum (map snd hdrSpans)) (\(Rect _ by _ bh) -> by + bh) mBodyRect-              )-          edgeCol = headerEdgeHit edgePad edgeTop edgeBot headerPairs mouse-          hoverCol = listToMaybe [i | (i, r) <- headerPairs, rectContains (rawRespRect r) mouse]-          headerRects = [(i, rawRespRect r) | (i, r) <- headerPairs]-          (isResize, isReorder) = case drag0 of-            HeaderResize _ -> (True, False)-            HeaderReorder _ -> (False, True)-            HeaderIdle -> (False, False)-          resizing = isResize && inputMouseDown inp-      (vis', mReorder) <--        withKey ("reorder" :: Text) $-          useReorder vis (if resizing || isJust edgeCol then [] else headerRects)-      let dragged = isReorder && abs (mx - dragX0) > dragThresholdPx-          pressResize = inputMousePressed inp && isJust edgeCol-          pressReorder = inputMousePressed inp && edgeCol == Nothing && isJust hoverCol-          nextDrag-            | pressResize = maybe HeaderIdle HeaderResize edgeCol-            | pressReorder = maybe HeaderIdle HeaderReorder hoverCol-            | inputMouseReleased inp || not (inputMouseDown inp) = HeaderIdle-            | otherwise = drag0-          nextDragX-            | pressResize || pressReorder = mx-            | nextDrag == HeaderIdle = 0-            | otherwise = dragX0-          nextDragW-            | pressResize = maybe 0 headerW edgeCol-            | nextDrag == HeaderIdle = 0-            | otherwise = dragW0-          headerW i = maybe (resolvedW i) (\r -> let w = rectW (rawRespRect r) in if w > 0 then w else resolvedW i) (lookup i headerPairs)-          nextOrder = if vis' /= vis then rebuildOrder hidden0 vis' order0 else order0-          -- respRightClicked, not a bare release: a right press that went down-          -- elsewhere and came up over a header must not hide that column.-          hideClicked = [i | (i, r) <- headerPairs, respRightClicked r, drag0 == HeaderIdle]-          nextHidden = case showAllResp of-            Just r | respClicked r -> IS.empty-            _ -> case hideClicked of-              (i : _) | IS.size hidden0 + 1 < n -> IS.insert i hidden0-              _ -> hidden0-          sortClick =-            if dragged || isJust mReorder || vis' /= vis || isResize-              then Nothing-              else-                if isJust edgeCol && (inputMouseDown inp || inputMouseReleased inp)-                  then Nothing-                  else listToMaybe [i | (i, r) <- headerPairs, respClicked r]-          nextSort = maybe sort0 (nextSortCol n sort0) sortClick-          hasChanged = nextSort /= sort0 || nextOrder /= order0 || nextHidden /= hidden0 || widths1 /= widths0-          widgetResp =-            setChanged hasChanged $-              setClicked (hasChanged && isJust sortClick) (mconcat (map snd headerPairs ++ maybe [] pure showAllResp))-      -- Compare the five slots, not the whole store: rewriting the store only-      -- when a slot moved keeps an idle table from diffing every map each frame.-      uiIO $ do-        st <- getStore ctx-        let dragCode = packHeaderDrag nextDrag-            dragK = slotKey SlotDrag stateKey-            dragWK = slotKey SlotDragW stateKey-            unchanged =-              IM.lookup stateKey (storeIntList st) == Just nextOrder-                && IM.lookup stateKey (storeIntSet st) == Just nextHidden-                && IM.lookup dragK (storeInt st) == Just dragCode-                && IM.lookup stateKey (storeFloat st) == Just nextDragX-                && IM.lookup dragWK (storeFloat st) == Just nextDragW-        unless unchanged $-          setStore-            ctx-            st-              { storeIntList = IM.insert stateKey nextOrder (storeIntList st)-              , storeIntSet = IM.insert stateKey nextHidden (storeIntSet st)-              , storeInt = IM.insert dragK dragCode (storeInt st)-              , storeFloat =-                  IM.insert stateKey nextDragX $-                    IM.insert dragWK nextDragW (storeFloat st)-              }-      pure (TableResponse widgetResp nextSort nextOrder nextHidden)---- | One row of cells with custom row layout.-gridColumnsLay :: (Ui :> es) => Layout -> [Int] -> [Layout] -> [Eff es ()] -> Eff es ()-gridColumnsLay lay keys layouts cells =-  void (row' lay (go True keys layouts cells))- where-  -- Walk in lockstep without allocating zip tuples and indices per cell.-  go first (key : moreKeys) (layout : moreLayouts) (cell : moreCells) = do-    when (not first) $ void separator-    void (withKey key (column' layout cell))-    go False moreKeys moreLayouts moreCells-  go _ _ _ _ = pure ()---- | Indices of @keys@ stably sorted by key: a bottom-up merge sort between--- two index buffers.-sortIndices :: SortDir -> SmallArray Text -> PrimArray Int-sortIndices dir keys = runST $ do-  let n = sizeofSmallArray keys-      before l r = case compare (indexSmallArray keys l) (indexSmallArray keys r) of-        LT -> dir == SortAsc-        GT -> dir == SortDesc-        EQ -> True-  start <- newPrimArray n-  let fill !i = when (i < n) (writePrimArray start i i >> fill (i + 1))-  fill 0-  spare <- newPrimArray n-  let pass !src !dst !width-        | width >= n = unsafeFreezePrimArray src-        | otherwise = do-            let mergeFrom !lo = when (lo < n) $ do-                  let !mid = min n (lo + width)-                      !hi = min n (lo + 2 * width)-                      takeLeft !i !j !k = readPrimArray src i >>= writePrimArray dst k >> go (i + 1) j (k + 1)-                      takeRight !i !j !k = readPrimArray src j >>= writePrimArray dst k >> go i (j + 1) (k + 1)-                      go !i !j !k-                        | k >= hi = pure ()-                        | i >= mid = takeRight i j k-                        | j >= hi = takeLeft i j k-                        | otherwise = do-                            l <- readPrimArray src i-                            r <- readPrimArray src j-                            if before l r then takeLeft i j k else takeRight i j k-                  go lo mid lo-                  mergeFrom hi-            mergeFrom 0-            pass dst src (2 * width)-  pass start spare 1---- | First and last visible item index for a uniform-height list, or--- @(0, -1)@ when nothing is visible.-{-# INLINE listClipper #-}-listClipper :: Int -> Float -> Float -> Float -> (Int, Int)-listClipper itemCount scrollOff viewH itemH-  | itemCount <= 0 || itemH <= 0 || viewH <= 0 = (0, -1)-  | otherwise =-      let firstVis = max 0 (floor (scrollOff / itemH))-          lastVis = min (itemCount - 1) (floor ((scrollOff + viewH - 1) / itemH))-       in if lastVis < firstVis then (0, -1) else (firstVis, lastVis)--setAt :: Int -> a -> [a] -> [a]-setAt i x xs-  | i < 0 = xs-  | otherwise = case splitAt i xs of-      (before, _ : after) -> before ++ x : after-      (_, []) -> xs--normalizeOrder :: Int -> [Int] -> [Int]-normalizeOrder n stored =-  let valid = filter (\i -> i >= 0 && i < n) stored-      seen = IS.fromList valid-   in valid ++ [i | i <- [0 .. n - 1], not (IS.member i seen)]--rebuildOrder :: IntSet -> [Int] -> [Int] -> [Int]-rebuildOrder hidden newVis old =-  let go [] vs = vs-      go (i : is) vs-        | IS.member i hidden = i : go is vs-        | otherwise = case vs of-            (v : vs') -> v : go is vs'-            [] -> i : is-   in go old newVis--minColW :: Float-minColW = 40---- | Hit-test a column resize edge. The grab zone spans the whole column--- height (header top to body bottom), so a column can be resized by its--- boundary line anywhere down the table, not just on the header cell.-headerEdgeHit :: Float -> Float -> Float -> [(Int, Response)] -> V2 -> Maybe Int-headerEdgeHit pad yTop yBot cols mouse =-  listToMaybe-    [ i-    | (i, r) <- cols-    , let Rect x y w h = rawRespRect r-    , w > 0 && h > 0-    , let mx = v2X mouse-          my = v2Y mouse-    , my >= min y yTop && my <= max (y + h) yBot-    , abs (mx - (x + w)) <= pad-    ]
− lib/NanoUI/Widgets/Tabs.hs
@@ -1,426 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}--module NanoUI.Widgets.Tabs-  ( Tab (..), TabStyle (..), TabOrientation (..), TabResponse (..)-  , TabsConfig (..), defaultTabsConfig-  , tab, closableTab-  , tabs, tabs', tabsConfigured, tabsConfigured'-  , tabBar, tabBar', tabBarConfigured, tabBarConfigured'-  )-where--import Control.Monad (forM_, when)-import Data.Bits ((.|.))-import Data.List (find)-import qualified Data.IntMap.Strict as IM-import Data.Maybe (isJust, listToMaybe)-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , getPrevRect-  , getScrollOffset-  , getStore-  , intKey-  , markDirty-  , resolveScrollStep-  , setScrollOffset-  , setStore-  , currentTheme-  )-import NanoUI.Frame.Hit (findNodeByWidgetId)-import NanoUI.Frame.Scroll.Geometry (scrollAxisRange, scrollBare, scrollHorizontalHidden)-import NanoUI.Id (WidgetId)-import NanoUI.Input (inputMousePos, inputScroll)-import NanoUI.Layout.Arena (setNodeValue)-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, withKey)-import NanoUI.Store (WidgetStore (storeFloat), slotKey, Slot (..))-import NanoUI.Style-  ( AlignX (..)-  , AlignY (..)-  , Direction (..)-  , Layout (..)-  , Padding (..)-  , Sizing (..)-  , defaultLayout-  , fillW-  , grow-  , themeMuted-  , tight-  )-import NanoUI.Types (Rect (..), clamp, rectContains, rectW, v2Y)-import NanoUI.WidgetText (buttonFlagClose, buttonFlagTab)-import NanoUI.Widgets.Combinators (buttonStyledEx)-import NanoUI.Widgets.Layout (column', columnWith, row', rowWith, scrollAreaIdConfigured)-import NanoUI.Widgets.Node-  ( HasResponse (..)-  , Response (..)-  , respClicked-  , respId-  , respRect-  , setChanged-  , setClicked-  , tagContainer-  )--data TabStyle = TabUnderline | TabPill | TabSegmented | TabContained-  deriving (Eq, Show, Enum, Bounded)--data TabOrientation = TabTop | TabBottom | TabLeft | TabRight-  deriving (Eq, Show, Enum, Bounded)---- | Header look and placement for 'tabsConfigured' and 'tabBarConfigured'.-data TabsConfig = TabsConfig-  { tabsStyle :: !TabStyle-  , tabsOrientation :: !TabOrientation-  }-  deriving (Eq, Show)---- | Underlined headers along the top.-defaultTabsConfig :: TabsConfig-defaultTabsConfig = TabsConfig TabUnderline TabTop--data Tab a body = Tab-  { tabKey :: !a-  , tabTitle :: !Text-  , tabClosable :: !Bool-  , tabDisabled :: !Bool-  , tabBadge :: !(Maybe Text)-  , tabBody :: !body-  }--data TabResponse a = TabResponse-  { tabResponse :: !Response-  , tabClosed :: !(Maybe a)-  , tabActive :: !a-  }-  deriving (Eq, Show)--instance HasResponse (TabResponse a) where-  {-# INLINE toResponse #-}-  toResponse = tabResponse--tab :: a -> Text -> body -> Tab a body-tab key title body = Tab key title False False Nothing body--closableTab :: a -> Text -> body -> Tab a body-closableTab key title body = Tab key title True False Nothing body---- | Header chrome height: one source for the strip bar, the scroller, and--- the paging arrows so they cannot drift apart.-tabHeaderH :: Float-tabHeaderH = 28---- | One rendered header, shared by selection, close handling, and scrolling.-data Header a = Header-  { headerKey :: !a-  , headerResponse :: !Response-  , headerClosed :: !Bool-  }--tabStrip ::-  (Eq a, Ui :> es) =>-  TabsConfig ->-  a ->-  [Tab a body] ->-  Maybe (a -> Eff es ()) ->-  Eff es (TabResponse a, a)-tabStrip (TabsConfig style orient) cur tabList mRenderBody = do-  ctx <- askContext-  groupId <- nextId-  let vertical = orient == TabLeft || orient == TabRight-      h = tabHeaderH-      styleVal = fromEnum style-      hdrLay =-        defaultLayout-          { layoutHeight = Fixed h-          , layoutPadding = Padding 8 8 4 4-          , layoutAlignX = AlignCenter-          , layoutAlignY = AlignMiddle-          , layoutGap = 4-          }-      barLay =-        if vertical-          then defaultLayout {layoutDirection = Column, layoutWidth = Fit, layoutHeight = Grow 1, layoutGap = 2, layoutPadding = Padding 2 2 2 2}-          else-            defaultLayout-              { layoutDirection = Row-              , layoutWidth = Grow 1-              , layoutHeight = Fixed (h + 4)-              , layoutGap = if style == TabSegmented then 0 else 4-              , layoutPadding = if style == TabContained then Padding 0 0 2 0 else Padding 0 0 0 0-              }-  let headerBar =-        if vertical-          then column' barLay $ do-            tagContainer groupId-            (tabResp, nextTab, _) <- renderHeaders ctx hdrLay styleVal cur (zip [0 :: Int ..] tabList)-            pure (tabResp, nextTab)-          else row' barLay $ do-            tagContainer groupId-            renderScrollableHeaders ctx style hdrLay barLay groupId cur tabList-  case mRenderBody of-    Nothing -> headerBar-    Just bodyRender ->-      let shell layout = layout $ do-            (tabResp, nextTab) <- headerBar-            bodyRender nextTab-            pure (tabResp, nextTab)-       in if vertical-            then shell (rowWith (tight . fillW . grow))-            else shell (columnWith (tight . fillW))---- | Horizontal headers that page with chevron buttons when they overflow.--- While the labels fit, the strip renders exactly as before (no scroll--- container, no well). Once they overflow, the headers move into a 1D--- hidden, bare 'scrollHorizontalHidden' container so the framework owns the--- clip, the offset store, the damage, and the wheel: a bare scroller paints--- no well, so the headers look exactly as they did before they could--- scroll, and the hidden policy keeps the scrollbar away while the wheel--- (both the left+right axis, applied by the framework, and up/down notches,--- mapped here because a tab bar is horizontal) still pages the same offset.--- The strip only adds the two buttons. The scroller grows between the--- buttons, so the right arrow sits on the bar's far edge instead of--- trailing the last tab.-renderScrollableHeaders ::-  (Eq a, Ui :> es) =>-  Context ->-  TabStyle ->-  Layout ->-  Layout ->-  WidgetId ->-  a ->-  [Tab a body] ->-  Eff es (TabResponse a, a)-renderScrollableHeaders ctx style hdrLay barLay groupId cur tabList = do-  scrollWid <- withKey ("tab-scroller" :: Text) nextId-  let h = tabHeaderH-      styleVal = fromEnum style-      barPad = layoutPadding barLay-      arrowW = 26-      leftGlyph = "\8249"-      rightGlyph = "\8250"-      innerLay =-        defaultLayout-          { layoutDirection = Row-          , layoutWidth = Fit-          , layoutHeight = Fixed h-          , layoutGap = layoutGap barLay-          , layoutPadding = Padding 0 0 0 0-          }-      scrollerLay =-        defaultLayout-          { layoutDirection = Row-          , layoutWidth = Grow 1-          , layoutHeight = Fixed h-          , layoutPadding = Padding 0 0 0 0-          }-      -- Hidden + bare: the scroller owns the clip, offset, wheel, and damage-      -- but paints nothing (no well, no scrollbar), so the headers look-      -- exactly as they did before the strip could scroll.-      scrollerCfg = scrollHorizontalHidden {scrollBare = True}-      rangeKey = slotKey SlotScrollContent (intKey scrollWid)-      renderInner =-        withKey ("tab-strip" :: Text) $-          row' innerLay (renderHeaders ctx hdrLay styleVal cur (zip [0 :: Int ..] tabList))-  -- The reachable range cached last frame decides whether the strip needs the-  -- scroller at all. Cached as a float so a pure scroll frame keeps its clip-  -- damage (see `onlyScrollFloatsChanged` in NanoUI.Damage).-  store <- uiIO (getStore ctx)-  let maxOffPrev = max 0 (IM.findWithDefault 0 rangeKey (storeFloat store))-      overflow = maxOffPrev > 0.5-  off <- uiIO (getScrollOffset ctx scrollWid)-  wheelStep <- uiIO (resolveScrollStep ctx scrollWid)-  mBar <- uiIO (getPrevRect ctx groupId)-  mScr <- uiIO (getPrevRect ctx scrollWid)-  inp <- askInput-  let overBar = maybe False (\r -> rectContains r (inputMousePos inp)) mBar-      notches = if overBar then round (v2Y (inputScroll inp)) else 0 :: Int-      canLeft = overflow && off > 0.5-  leftResp <--    if overflow-      then Just <$> withKey ("tab-arrow-left" :: Text) (arrowButton ctx hdrLay arrowW h (not canLeft) leftGlyph)-      else pure Nothing-  (tabResp, nextTab, resps) <--    if overflow-      then scrollAreaIdConfigured scrollWid scrollerLay scrollerCfg renderInner-      else renderInner-  let-    (viewX, viewW) =-      if overflow-        then maybe (0, 0) (\r -> (rectX r, rectW r)) mScr-        else-          case mBar of-            Just r ->-              ( rectX r + padL barPad-              , max 0 (rectW r - padL barPad - padR barPad)-              )-            Nothing -> (0, 0)-    maxRight = maximum (0 : [rectX r + rectW r | header <- resps, let r = respRect (headerResponse header)])-    contentW = maxRight - viewX + (if overflow then off else 0)-    -- The first overflow frame has no scroller rect yet (mScr is Nothing);-    -- keep the last cached range instead of measuring against a phantom-    -- viewport, so nothing pages or clamps wildly and the cache never-    -- flip-flops the scroller away.-    maxOff = case (overflow, mScr) of-      (True, Nothing) -> maxOffPrev-      _ -> scrollAxisRange contentW viewW 0-    page = max 1 (viewW * 0.9)-    canRight = overflow && off < maxOff - 0.5-  rightResp <--    if overflow-      then Just <$> withKey ("tab-arrow-right" :: Text) (arrowButton ctx hdrLay arrowW h (not canRight) rightGlyph)-      else pure Nothing-  uiIO (cacheScrollRange ctx rangeKey maxOff)-  -- One final offset per frame. The paged result folds the arrow pages, the-  -- wheel notches, and the end clamp (a stale offset that outlived a wider-  -- bar); the active-follow wins over it so a programmatically changed tab-  -- always lands in view.-  let pagedOff-        | maybe False respClicked leftResp, canLeft = max 0 (off - page)-        | maybe False respClicked rightResp, canRight = min maxOff (off + page)-        | overflow, notches /= 0, maxOff > 0 =-            clamp 0 maxOff (off + fromIntegral notches * wheelStep)-        | overflow, off > maxOff + 0.5 = maxOff-        | otherwise = off-      finalOff-        | overflow-        , nextTab /= cur-        , Just header <- find ((== nextTab) . headerKey) resps-        , let hr = respRect (headerResponse header) =-            if rectX hr < viewX-              then max 0 (off - (viewX - rectX hr))-              else-                if rectX hr + rectW hr > viewX + viewW-                  then min maxOff (off + (rectX hr + rectW hr - viewX - viewW))-                  else pagedOff-        | otherwise = pagedOff-  when (finalOff /= off) $-    uiIO (setScrollOffset ctx scrollWid finalOff)-  pure (tabResp, nextTab)---- | Remember the scroller's reachable range for the next frame's arrow--- visibility. Sub-pixel churn is ignored so a parked strip never dirties.-cacheScrollRange :: Context -> Int -> Float -> IO ()-cacheScrollRange ctx key v = do-  st <- getStore ctx-  let prev = IM.findWithDefault 0 key (storeFloat st)-  when (abs (prev - v) > 0.5) $-    setStore ctx (st {storeFloat = IM.insert key v (storeFloat st)})---- | A prettier thin chevron button for the strip. Disabled ends paint the--- glyph in the muted fg instead of dropping the button, so the row width does--- not jump as you page to either end.-arrowButton :: (Ui :> es) => Context -> Layout -> Float -> Float -> Bool -> Text -> Eff es Response-arrowButton ctx hdrLay arrowW barH muted glyph = do-  theme <- uiIO (currentTheme ctx)-  let lay =-        hdrLay-          { layoutWidth = Fixed arrowW-          , layoutHeight = Fixed barH-          , layoutFontColor = if muted then Just (themeMuted theme) else Nothing-          }-  buttonStyledEx (not muted) glyph 0 lay 0--renderHeaders ::-  (Eq a, Ui :> es) =>-  Context ->-  Layout ->-  Int ->-  a ->-  [(Int, Tab a body)] ->-  Eff es (TabResponse a, a, [Header a])-renderHeaders ctx hdrLay styleVal cur indexed = do-  resps <- mapM (\(i, t) -> withKey i (renderSingleHeader hdrLay (styleVal + 4 * i) cur t)) indexed-  let clickedKeys = [headerKey h | h <- resps, respClicked (headerResponse h), not (headerClosed h)]-      closedKey = headerKey <$> find headerClosed resps-      nextTab = case clickedKeys of-        (k : _) -> k-        [] -> cur-      hasChanged = nextTab /= cur-      hasClicked = not (null clickedKeys)-      overallResp =-        TabResponse-          { tabResponse = setChanged hasChanged (setClicked hasClicked (foldMap headerResponse resps))-          , tabClosed = closedKey-          , tabActive = nextTab-          }-  when (hasChanged || isJust closedKey) $ uiIO (markDirty ctx)-  when hasChanged $ uiIO (syncTabHeaderActive ctx nextTab resps)-  pure (overallResp, nextTab, resps)--renderSingleHeader ::-  (Eq a, Ui :> es) =>-  Layout ->-  Int ->-  a ->-  Tab a body ->-  Eff es (Header a)-renderSingleHeader hdrLay packedStyle cur t = do-  let isActive = tabKey t == cur-      headerText = maybe (tabTitle t) (\b -> mconcat [tabTitle t, " (", b, ")"]) (tabBadge t)-      tabStyle = packedStyle .|. buttonFlagTab-      headerButton = buttonStyledEx (not (tabDisabled t))-  if tabClosable t-    then do-      (tabResp, closed) <- rowWith tight $ do-        resp <- headerButton headerText (if isActive then 1 else 0) hdrLay tabStyle-        closeResp <- headerButton "\215" 0 (hdrLay {layoutPadding = Padding 2 4 4 4}) buttonFlagClose-        pure (resp, respClicked closeResp)-      pure (Header (tabKey t) tabResp closed)-    else do-      resp <- headerButton headerText (if isActive then 1 else 0) hdrLay tabStyle-      pure (Header (tabKey t) resp False)--syncTabHeaderActive :: Eq a => Context -> a -> [Header a] -> IO ()-syncTabHeaderActive ctx active resps =-  forM_ resps $ \(Header k r _) -> do-    mIdx <- findNodeByWidgetId ctx (respId r)-    case mIdx of-      Just i -> setNodeValue (ctxNodeArena ctx) i (if k == active then 1 else 0)-      Nothing -> pure ()---- | Tab headers and the active tab's body. Pass the active key; the result is--- the active key after this frame's clicks or arrow keys. Only the active--- tab's body runs.-{-# INLINE tabs #-}-tabs :: (Foldable f, Eq a, Ui :> es) => a -> f (Tab a (Eff es ())) -> Eff es a-tabs = tabsConfigured defaultTabsConfig---- | 'tabs' returning the 'TabResponse', which also reports a closed tab.-{-# INLINE tabs' #-}-tabs' :: (Foldable f, Eq a, Ui :> es) => a -> f (Tab a (Eff es ())) -> Eff es (TabResponse a)-tabs' = tabsConfigured' defaultTabsConfig---- | 'tabs' with a header style and placement.-tabsConfigured :: (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a (Eff es ())) -> Eff es a-tabsConfigured cfg active inputTabs =-  let ts = foldr (:) [] inputTabs-   in snd <$> tabStrip cfg active ts (Just (renderBody ts))--tabsConfigured' :: (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a (Eff es ())) -> Eff es (TabResponse a)-tabsConfigured' cfg active inputTabs =-  let ts = foldr (:) [] inputTabs-   in fst <$> tabStrip cfg active ts (Just (renderBody ts))---- | Tab headers only; the caller renders the body.-{-# INLINE tabBar #-}-tabBar :: (Foldable f, Eq a, Ui :> es) => a -> f (Tab a body) -> Eff es a-tabBar = tabBarConfigured defaultTabsConfig--{-# INLINE tabBar' #-}-tabBar' :: (Foldable f, Eq a, Ui :> es) => a -> f (Tab a body) -> Eff es (TabResponse a)-tabBar' = tabBarConfigured' defaultTabsConfig--tabBarConfigured :: (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a body) -> Eff es a-tabBarConfigured cfg active ts = snd <$> tabStrip cfg active (foldr (:) [] ts) Nothing--tabBarConfigured' :: (Foldable f, Eq a, Ui :> es) => TabsConfig -> a -> f (Tab a body) -> Eff es (TabResponse a)-tabBarConfigured' cfg active ts = fst <$> tabStrip cfg active (foldr (:) [] ts) Nothing--renderBody :: (Eq a, Ui :> es) => [Tab a (Eff es ())] -> a -> Eff es ()-renderBody ts activeKey =-  columnWith (tight . fillW) $-    case find ((== activeKey) . tabKey) ts of-      Just selected -> tabBody selected-      Nothing -> maybe (pure ()) tabBody (listToMaybe ts)
lib/NanoUI/Widgets/TextArea.hs view
@@ -1,5 +1,3 @@-{-# LANGUAGE BangPatterns #-}- -- | The multi-line text area widget and its state: the document buffer, -- caret and selection, viewport, and commands run against it. module NanoUI.Widgets.TextArea@@ -8,347 +6,17 @@   , initTextAreaState   , setTextAreaViewport   , setTextAreaSelection+  , runTextAreaCommand     -- * Widget   , textArea   , textArea'   , textAreaWith   , textAreaWith'+  , textAreaDocument+  , textAreaDocument'+  , textAreaDocumentWith+  , textAreaDocumentWith'   , textAreaLayout-  , loadTextAreaState-  , loadTextAreaStateWithBuffer-  , saveTextAreaState-  , textAreaEditor-  , runTextAreaCommand-  , applyTextAreaCommand   ) where -import Control.Monad (foldM, when)-import Data.Dynamic (fromDynamic, toDyn)-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.IntMap.Strict as IM-import Effectful (Eff, type (:>))-import NanoUI.Context-  ( Context (..)-  , damageWidget-  , getStore-  , intKey-  , markDirty-  , registerFocusable-  , setStore-  , setTextInputDrag-  , modifyStore-  )-import NanoUI.Font (fmLineHeight)-import NanoUI.Id (WidgetId)-import NanoUI.Input-  ( Input (..)-  , inputChars-  , inputKeys-  , inputKeysNull-  )-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO)-import NanoUI.Store-  ( WidgetStore (..)-  , slotKey-  , Slot (..)-  )-import NanoUI.Style (FontStyle (..), FontVariant (..), FontWeight (..), Layout (..), Sizing (..), defaultLayout)-import NanoUI.Types (DamageBounds (..), clamp)-import NanoUI.Widgets.Behavior (keyboardFocused)-import NanoUI.Widgets.Node (Response, addWidget, setChanged)-import qualified NanoUI.Widgets.TextBuffer as TB-import NanoUI.Widgets.TextEditor-  ( Editor (..)-  , EditHistory-  , TextCommand (..)-  , inputTextCommands-  , editorModeCode-  , emptyHistory-  , multiLineMode-  , runCommand-  , runCommandIO-  , sealHistory-  )--data TextAreaState = TextAreaState-  { buffer :: !TB.TextBuffer-  , selectionAnchor :: !TB.Cursor-  , scrollOffset :: !(Double, Double)-  , viewportSize :: !(Double, Double)-  , lineHeight :: !Double-  , history :: !EditHistory-  }-  deriving (Show)--initTextAreaState :: T.Text -> TextAreaState-initTextAreaState initial =-  TextAreaState-    { buffer = TB.fromText initial-    , selectionAnchor = TB.Cursor 0 0-    , scrollOffset = (0.0, 0.0)-    , viewportSize = (0.0, 0.0)-    , lineHeight = 16.0-    , history = emptyHistory-    }--setTextAreaViewport :: (Double, Double) -> Double -> TextAreaState -> TextAreaState-setTextAreaViewport vp lh state =-  state {viewportSize = vp, lineHeight = lh}--cursorOf :: TextAreaState -> TB.Cursor-cursorOf state = TB.getCursor (buffer state)--setTextAreaSelection :: TB.Cursor -> TB.Cursor -> TextAreaState -> TextAreaState-setTextAreaSelection anchor cursor state =-  let buf =-        let b = TB.withCursor cursor (buffer state)-         in b {TB.preferredCol = TB.cursorCol cursor}-   in ensureCaretVisible state {buffer = buf, selectionAnchor = anchor}--textAreaEditor :: TextAreaState -> Editor-textAreaEditor state = Editor (buffer state) (selectionAnchor state) (history state)--withEditor :: TextAreaState -> Editor -> TextAreaState-withEditor state ed =-  ensureCaretVisible state {buffer = editorBuffer ed, selectionAnchor = editorAnchor ed, history = editorHistory ed}---- | Run a command that needs no clipboard, keeping the caret in view.-runTextAreaCommand :: TextCommand -> TextAreaState -> TextAreaState-runTextAreaCommand cmd state = withEditor state (runCommand multiLineMode cmd (textAreaEditor state))--ensureCaretVisible :: TextAreaState -> TextAreaState-ensureCaretVisible state =-  let TB.Cursor r _ = TB.getCursor (buffer state)-      lh = lineHeight state-      vh = snd (viewportSize state)-      (sx, sy) = scrollOffset state-      caretY = fromIntegral r * lh-      caretH = lh-      contentH = fromIntegral (TB.getLineCount (buffer state)) * lh-      maxSy = max 0 (contentH - vh)-      sy'-        | vh <= 0 = 0-        | caretY < sy = caretY-        | caretY + caretH > sy + vh = caretY + caretH - vh-        | otherwise = sy-  in state {scrollOffset = (sx, clamp 0 maxSy sy')}------------------------------------------------------------------------------------- Widget-----------------------------------------------------------------------------------textAreaLayout :: Layout-textAreaLayout =-  defaultLayout-    { layoutWidth = Grow 1-    , layoutMinW = 200-    , layoutHeight = Fixed 140-    }---- | Multi-line text editor. Pass the current text; the result is the text--- after this frame's edits. Pair it with a 'label' when a caption is wanted.-{-# INLINE textArea #-}-textArea :: Ui :> es => Text -> Eff es Text-textArea value = snd <$> textAreaWith' id value--{-# INLINE textArea' #-}-textArea' :: Ui :> es => Text -> Eff es (Response, Text)-textArea' = textAreaWith' id---- | 'textArea' with a modifier applied to 'textAreaLayout', for example--- 'grow' to fill the parent.-{-# INLINE textAreaWith #-}-textAreaWith :: Ui :> es => (Layout -> Layout) -> Text -> Eff es Text-textAreaWith f value = snd <$> textAreaWith' f value--textAreaWith' :: Ui :> es => (Layout -> Layout) -> Text -> Eff es (Response, Text)-textAreaWith' f value = do-  wid <- nextId-  ctx <- askContext-  uiIO $ registerFocusable ctx wid-  inp <- askInput-  store0 <- uiIO (getStore ctx)-  let layout = f textAreaLayout-      key = intKey wid-      seenKey = slotKey SlotSeen key-      contentCacheKey = slotKey SlotTextAreaContentFont key-      changedSlotKey = slotKey SlotTextAreaChanged key-      texts0 = storeText store0-      replaced = IM.lookup key texts0 /= Just value-  -- Adopt the caller's text the way 'adoptStoreText' does. A replaced document-  -- orphans any cached buffer or content size for the key. Seed the scroll-  -- slot too: the wheel and drag paths write offsets through-  -- setScrollOffset2D, which only updates the text area's slot once it exists.-  -- Its undo history, recorded against the old text, goes with them.-  when (IM.lookup seenKey texts0 /= Just value) $-    uiIO $ setStore ctx-      store0-        { storeText = IM.insert seenKey value (IM.insert key value texts0)-        , storePoint = IM.insertWith (\_ old -> old) (slotKey SlotTextAreaScroll key) (0, 0) (storePoint store0)-        , storeFloat = if replaced then IM.delete contentCacheKey (storeFloat store0) else storeFloat store0-        , storeDyn =-            if replaced-              then IM.delete (slotKey SlotTextHistory key) (IM.delete (slotKey SlotTextAreaBuffer key) (storeDyn store0))-              else storeDyn store0-        , storeInt = IM.insert (slotKey SlotTextMode key) (editorModeCode multiLineMode) (storeInt store0)-        }-  store <- uiIO (getStore ctx)-  let current = IM.findWithDefault value key (storeText store)-      -- Set by commands run outside the frame ('applyTextAreaCommand') whose-      -- edits carry no keys or chars; folded into 'changed' so the caller-      -- gets its respChanged pulse, then cleared in the state write below.-      menuPulse = IM.member changedSlotKey (storeInt store)-  isFocus <- keyboardFocused wid-  (newText, stateChanged) <--    if isFocus-      then do-        editFm <--          if layoutFontSize layout <= 0-            then pure (ctxFontMetrics ctx)-            else fst <$> uiIO (ctxResolveFont ctx (layoutFontSize layout) WeightNormal FontStyleNormal FontRegular)-        let oldState = loadTextAreaState store key value-            s1 = setTextAreaViewport (viewportSize oldState) (realToFrac (fmLineHeight editFm)) oldState-            hadInput = not (T.null (inputChars inp)) || not (inputKeysNull (inputKeys inp))-        newState <- uiIO $ do-          when hadInput $ setTextInputDrag ctx Nothing-          case inputTextCommands multiLineMode inp of-            [] -> pure s1-            cmds -> withEditor s1 <$> foldM (flip (runCommandIO ctx multiLineMode)) (textAreaEditor s1) cmds-        let newText-              -- Commands only come from keys or chars, so idle focused frames-              -- skip the O(document) 'TB.toText' and stop at the cheap-              -- cursor/scroll checks.-              | hadInput || changed = TB.toText (buffer newState)-              | otherwise = current-            changed =-              cursorOf newState /= cursorOf oldState-                || selectionAnchor newState /= selectionAnchor oldState-                || scrollOffset newState /= scrollOffset oldState-                || menuPulse-                || (hadInput && newText /= current)-        -- Saving writes the new text and its buffer together; drop only the-        -- content size measured for the old text, and the menu pulse. The-        -- store damage is keyed on slots, not the widget, so damage the widget-        -- itself: a selection-only change (Ctrl+A) would otherwise repaint-        -- nothing until the next frame.-        when changed $-          uiIO $ do-            damageWidget ctx wid DamageSelf-            modifyStore ctx $ \st0 ->-              let st = saveTextAreaState key newText newState st0-               in st-                    { storeText = IM.insert seenKey newText (storeText st)-                    , storeInt = IM.delete changedSlotKey (storeInt st)-                    , storeFloat = IM.delete contentCacheKey (storeFloat st)-                    }-        pure (newText, changed)-      else do-        -- A command run on the unfocused area ('applyTextAreaCommand') still-        -- pulses this frame's respChanged, once.-        when menuPulse $-          uiIO $ modifyStore ctx $ \st -> st {storeInt = IM.delete changedSlotKey (storeInt st)}-        pure (current, menuPulse)-  resp <- addWidget wid NodeTextArea "" 0 layout-  pure (setChanged stateChanged resp, newText)--loadTextAreaState :: WidgetStore -> Int -> Text -> TextAreaState-loadTextAreaState store key initial =-  let text = IM.findWithDefault initial key (storeText store)-      -- The buffer cache is written together with storeText by-      -- saveTextAreaState, so a present entry is always the buffer for the-      -- stored text; no (O(document)) re-comparison is needed.-      cachedBuffer :: Maybe TB.TextBuffer =-        IM.lookup (slotKey SlotTextAreaBuffer key) (storeDyn store) >>= fromDynamic-      buf0 = case cachedBuffer of-        Just cached -> cached-        Nothing -> TB.fromText text-   in loadTextAreaStateWithBuffer store key buf0---- | 'loadTextAreaState' with the buffer already resolved (the paint path--- ensures the buffer cache and hands it straight through, avoiding a second--- store lookup).-loadTextAreaStateWithBuffer :: WidgetStore -> Int -> TB.TextBuffer -> TextAreaState-loadTextAreaStateWithBuffer store key buf0 =-  let row = IM.findWithDefault 0 (slotKey SlotTextAreaRow key) (storeInt store)-      col = IM.findWithDefault 0 (slotKey SlotTextAreaCol key) (storeInt store)-      anchorRow = IM.findWithDefault row (slotKey SlotTextAreaAnchorRow key) (storeInt store)-      anchorCol = IM.findWithDefault col (slotKey SlotTextAreaAnchorCol key) (storeInt store)-      pref = IM.findWithDefault col (slotKey SlotTextAreaPrefCol key) (storeInt store)-      scroll =-        let (sx, sy) =-              IM.findWithDefault (0, 0) (slotKey SlotTextAreaScroll key) (storePoint store)-         in (realToFrac sx, realToFrac sy)-      viewport =-        let (vw, vh) =-              IM.findWithDefault (200, 96) (slotKey SlotTextAreaViewport key) (storePoint store)-         in (realToFrac vw, realToFrac vh)-      buf =-        let b = TB.withCursor (TB.Cursor row col) buf0-         in b {TB.preferredCol = pref}-      anchor = TB.getCursor (TB.withCursor (TB.Cursor anchorRow anchorCol) buf0)-      -- Replacing the document drops its history, so the recorded text is-      -- always the current one here.-      hist = case IM.lookup (slotKey SlotTextHistory key) (storeDyn store) >>= fromDynamic of-        Just (_ :: Text, h) -> h-        Nothing -> emptyHistory-   in TextAreaState-        { buffer = buf-        , selectionAnchor = anchor-        , scrollOffset = scroll-        , viewportSize = viewport-        , lineHeight = 16-        , history = hist-        }---- | Store the editor state with its text. Callers pass the text because they--- usually have it already, and 'TB.toText' joins the whole document.-saveTextAreaState :: Int -> Text -> TextAreaState -> WidgetStore -> WidgetStore-saveTextAreaState key text state store =-  let TB.Cursor row col = TB.getCursor (buffer state)-      TB.Cursor anchorRow anchorCol = selectionAnchor state-   in store-        { storeText = IM.insert key text (storeText store)-        , storeDyn =-            IM.insert (slotKey SlotTextAreaBuffer key) (toDyn (buffer state)) $-              IM.insert (slotKey SlotTextHistory key) (toDyn (text, history state)) (storeDyn store)-        , storeInt =-            IM.insert (slotKey SlotTextAreaRow key) row $-              IM.insert (slotKey SlotTextAreaCol key) col $-                IM.insert (slotKey SlotTextAreaPrefCol key) (TB.preferredCol (buffer state)) $-                  IM.insert (slotKey SlotTextAreaAnchorRow key) anchorRow $-                    IM.insert (slotKey SlotTextAreaAnchorCol key) anchorCol (storeInt store)-        , storePoint =-            IM.insert (slotKey SlotTextAreaScroll key) (realToFrac sx, realToFrac sy) $-              IM.insert (slotKey SlotTextAreaViewport key) (realToFrac vw, realToFrac vh) (storePoint store)-        }-  where-    (sx, sy) = scrollOffset state-    (vw, vh) = viewportSize state---- | Run a command on a text area outside its frame (a context menu row, an--- app's Edit menu). A change to the text pulses 'respChanged' on the area's--- next frame.-applyTextAreaCommand :: Context -> WidgetId -> TextCommand -> IO ()-applyTextAreaCommand ctx wid cmd = do-  store <- getStore ctx-  let key = intKey wid-      text = IM.findWithDefault "" key (storeText store)-      s0 = loadTextAreaState store key text-  s1 <- withEditor s0 <$> runCommandIO ctx multiLineMode cmd (textAreaEditor s0 {history = sealHistory (history s0)})-  let newText = TB.toText (buffer s1)-      saved = saveTextAreaState key newText s1 store-  -- A changed text also drops the content size measured for the old one.-  setStore ctx $-    if newText == text-      then saved-      else-        saved-          { storeInt = IM.insert (slotKey SlotTextAreaChanged key) 1 (storeInt saved)-          , storeFloat = IM.delete (slotKey SlotTextAreaContentFont key) (storeFloat saved)-          }-  -- Store damage is keyed on slots, not the widget: damage the widget so a-  -- selection-only command (Select All) repaints this frame.-  damageWidget ctx wid DamageSelf-  markDirty ctx+import NanoUI.Internal.Widgets.TextArea
lib/NanoUI/Widgets/TextBuffer.hs view
@@ -1,5 +1,3 @@-{-# LANGUAGE BangPatterns #-}- -- | A text document as a finger tree of lines with a cursor. Every change is -- a 'TextEdit': replace the text at a position with other text. An edit -- touches only the lines it spans, so edits, cursor moves and line lookups@@ -14,7 +12,10 @@     -- * Construction & Conversion   , empty   , fromText+  , fromLines   , toText+  , splitLines+  , joinLines   , toLines   , lineAt @@ -23,6 +24,7 @@   , getLineCount   , withCursor   , clampCursor+  , snapToCluster   , changedLines   , markLinesSeen @@ -54,8 +56,8 @@  import Control.Monad (when) import Control.Monad.ST (runST)-import Data.Char (isPrint, isSpace)-import Data.Foldable (toList)+import Data.Char (isControl, isSpace)+import Data.Foldable (foldlM, toList) import Data.Maybe (fromMaybe) import Data.Sequence (Seq) import Data.Sequence qualified as Seq@@ -63,6 +65,8 @@ import Data.Text qualified as T import Data.Text.Array qualified as A import Data.Text.Internal (Text (..))+import NanoUI.Internal.TextCluster (clusterLength, prevClusterStart)+import NanoUI.Internal.Types (clamp)  -- | Zero-indexed logical (row, column) position in the buffer. Fields are -- row then column, so the derived 'Ord' is document order.@@ -77,8 +81,7 @@   { bufferLines :: !(Seq Text)   , bufferCursor :: {-# UNPACK #-} !Cursor   , preferredCol :: {-# UNPACK #-} !Int-  -- ^ The column vertical motion aims for, kept while moving through-  -- shorter lines.+  -- ^ Target column preserved across vertical motion through shorter lines.   , bufferSeenHead :: {-# UNPACK #-} !Int   , bufferSeenTail :: {-# UNPACK #-} !Int   -- ^ Lines at the start and the end that no edit has touched since@@ -103,25 +106,45 @@  -- | Construct a TextBuffer from raw Text. Cursor is always (0, 0). fromText :: Text -> TextBuffer-fromText t = TextBuffer (Seq.fromList (T.splitOn "\n" t)) (Cursor 0 0) 0 0 0+fromText = fromLines . splitLines +-- | A buffer over lines already split, at (0, 0), with every line unseen.+-- The lines are as 'splitLines' makes them: at least one, none holding a+-- newline.+fromLines :: Seq Text -> TextBuffer+fromLines lns+  | Seq.null lns = empty+  | otherwise = TextBuffer lns (Cursor 0 0) 0 0 0++-- | The lines of a text, without their newlines. There is always at least one.+-- A Windows line end (@\\r\\n@) is one newline, so 'joinLines' gives the text+-- back with @\\n@ line ends.+splitLines :: Text -> Seq Text+splitLines t = Seq.fromList [fromMaybe l (T.stripSuffix "\r" l) | l <- T.splitOn "\n" t]+ -- | All lines joined with newlines, copied once into a new text. toText :: TextBuffer -> Text-toText buf =-  let lns = bufferLines buf-      !total = foldl' (\acc (Text _ _ len) -> acc + len + 1) (-1) lns-   in if total <= 0-        then T.empty-        else runST $ do+toText = joinLines . bufferLines++-- | Lines joined with newlines, copied once into a new text. A single line+-- is returned as it is.+joinLines :: Seq Text -> Text+joinLines lns = case lns of+  Seq.Empty -> T.empty+  line Seq.:<| Seq.Empty -> line+  _ ->+    let !total = foldl' (\acc (Text _ _ len) -> acc + len + 1) (-1) lns+     in runST $ do           dest <- A.new total-          let copyLine (Text arr start len) next !off = do+          let copyLine !off (Text arr start len) = do                 A.copyI len dest off arr start                 when (off + len < total) $ A.unsafeWrite dest (off + len) 10-                next (off + len + 1)-          foldr copyLine (\_ -> pure ()) lns 0+                pure (off + len + 1)+          _ <- foldlM copyLine 0 lns           frozen <- A.unsafeFreeze dest           pure (Text frozen 0 total) +-- | Lines in document order without newline separators. Allocates the list spine. toLines :: TextBuffer -> [Text] toLines = toList . bufferLines @@ -129,9 +152,11 @@ lineAt :: Int -> TextBuffer -> Text lineAt row buf = fromMaybe T.empty (Seq.lookup row (bufferLines buf)) +-- | Current zero-based row and character column. getCursor :: TextBuffer -> Cursor getCursor = bufferCursor +-- | Line count in O(1), including the one empty line of an empty buffer. getLineCount :: TextBuffer -> Int getLineCount = Seq.length . bufferLines @@ -149,10 +174,25 @@ -- | The nearest position inside the document. clampCursor :: TextBuffer -> Cursor -> Cursor clampCursor buf (Cursor row col) =-  let !r = max 0 (min (getLineCount buf - 1) row)-      !c = max 0 (min (T.length (lineAt r buf)) col)+  let !r = clamp 0 (getLineCount buf - 1) row+      !c = clamp 0 (T.length (lineAt r buf)) col    in Cursor r c +-- | 'clampCursor', then back to the start of the user-perceived character+-- the position falls inside ('clusterLength'). Use it for a position that+-- comes from outside the editing commands, such as a caret kept across a+-- replaced document or a selection set by the application: there it can+-- land between a letter and its accent or inside an emoji sequence, and an+-- insert would split the character. The editing commands themselves stop+-- inside a cluster on purpose (Backspace removes a vowel sign alone), so+-- they keep 'clampCursor'.+snapToCluster :: TextBuffer -> Cursor -> Cursor+snapToCluster buf cur =+  let Cursor r c = clampCursor buf cur+      line = lineAt r buf+      p = prevClusterStart line c+   in if c <= 0 || p + clusterLength (T.drop p line) <= c then Cursor r c else Cursor r p+ -- | Move to a position, clamped into the document, without changing text. withCursor :: Cursor -> TextBuffer -> TextBuffer withCursor cur buf =@@ -163,27 +203,37 @@ -- Navigation -------------------------------------------------------------------------------- +-- | Move one user-perceived character left ('clusterLength': a flag, an+-- emoji sequence or a letter with its marks), crossing to the preceding line+-- at column zero. Stops at the document start. moveLeft :: TextBuffer -> TextBuffer moveLeft buf = withCursor (positionLeft buf (getCursor buf)) buf +-- | Move one user-perceived character right, crossing to the next line at+-- line end. Stops at the document end. moveRight :: TextBuffer -> TextBuffer moveRight buf = withCursor (positionRight buf (getCursor buf)) buf  positionLeft :: TextBuffer -> Cursor -> Cursor positionLeft buf (Cursor row col)-  | col > 0 = Cursor row (col - 1)+  -- Walk back to the start of the cluster immediately before the caret.+  | col > 0 = Cursor row (prevClusterStart (lineAt row buf) col)   | row > 0 = Cursor (row - 1) (T.length (lineAt (row - 1) buf))   | otherwise = Cursor 0 0  positionRight :: TextBuffer -> Cursor -> Cursor positionRight buf (Cursor row col)-  | col < T.length (lineAt row buf) = Cursor row (col + 1)+  | col < T.length line = Cursor row (col + clusterLength (T.drop col line))   | row + 1 < getLineCount buf = Cursor (row + 1) 0   | otherwise = Cursor row col+  where+    line = lineAt row buf +-- | Move up one row, retaining the preferred column and clamping to line length. moveUp :: TextBuffer -> TextBuffer moveUp = moveByRow (-1) +-- | Move down one row, retaining the preferred column and clamping to line length. moveDown :: TextBuffer -> TextBuffer moveDown = moveByRow 1 @@ -193,17 +243,21 @@       goal = preferredCol buf    in buf {bufferCursor = clampCursor buf (Cursor (row + d) goal)} +-- | Move to column zero of the current line. moveToBOL :: TextBuffer -> TextBuffer moveToBOL buf = withCursor (Cursor (cursorRow (getCursor buf)) 0) buf +-- | Move just past the last character of the current line. moveToEOL :: TextBuffer -> TextBuffer moveToEOL buf =   let row = cursorRow (getCursor buf)    in withCursor (Cursor row (T.length (lineAt row buf))) buf +-- | Move to the document start, resetting the preferred column. moveToTop :: TextBuffer -> TextBuffer moveToTop = withCursor (Cursor 0 0) +-- | Move to the document end, resetting the preferred column. moveToBottom :: TextBuffer -> TextBuffer moveToBottom buf = withCursor (documentEnd buf) buf @@ -238,10 +292,10 @@ -- Edits -------------------------------------------------------------------------------- --- | Apply an edit and leave the cursor after the inserted text. The removed--- text decides how far the edit reaches, so an edit recorded against this--- document (or undone from one) is applied without reading the text it--- removes.+-- | Apply an edit and leave the cursor after the inserted text. The span to+-- replace is computed from the length and line breaks of 'editRemoved' rather+-- than inspecting the buffer, so recorded and inverted edits apply without+-- reading the removed text. applyEdit :: TextEdit -> TextBuffer -> TextBuffer applyEdit (TextEdit at removed inserted) buf =   let Cursor row col = clampCursor buf at@@ -267,7 +321,7 @@     0 -> Cursor row (col + T.length txt)     breaks -> Cursor (row + breaks) (T.length (T.takeWhileEnd (/= '\n') txt)) --- | The edit that takes the document back.+-- | Swap 'editRemoved' and 'editInserted' to produce the inverse edit. invertEdit :: TextEdit -> TextEdit invertEdit (TextEdit at removed inserted) = TextEdit at inserted removed @@ -277,18 +331,24 @@   let (lo, hi) = selectionRange (clampCursor buf a) (clampCursor buf b)    in TextEdit lo (textRange lo hi buf) inserted --- | Text as it can enter the document: printable characters, tabs and line--- breaks, with Windows line ends folded.+-- | Text as it can enter the document: every character but the control+-- characters, tabs and line breaks aside, with Windows (@\\r\\n@) and classic+-- Mac (@\\r@) line ends made newlines. Format characters (joiners, bidi+-- marks), private-use characters and those the base library's Unicode tables+-- predate stay. insertableText :: Text -> Text-insertableText = T.filter (\c -> isPrint c || c == '\t' || c == '\n') . T.replace "\r\n" "\n"+insertableText = T.filter (\c -> not (isControl c) || c == '\t' || c == '\n') . T.replace "\r" "\n" . T.replace "\r\n" "\n"  -------------------------------------------------------------------------------- -- Selection -------------------------------------------------------------------------------- +-- | Order two selection endpoints from earlier to later without clamping them. selectionRange :: Cursor -> Cursor -> (Cursor, Cursor) selectionRange a b = (min a b, max a b) +-- | Text between clamped, ordered endpoints. Selection is half-open and+-- includes newline separators crossed by the range. selectedText :: Cursor -> Cursor -> TextBuffer -> Text selectedText a b buf =   let (lo, hi) = selectionRange (clampCursor buf a) (clampCursor buf b)@@ -303,6 +363,7 @@       let middle = toList (Seq.take (hiRow - loRow - 1) (Seq.drop (loRow + 1) (bufferLines buf)))        in T.intercalate "\n" (T.drop loCol (lineAt loRow buf) : middle ++ [T.take hiCol (lineAt hiRow buf)]) +-- | Position immediately after the final character of the last line. documentEnd :: TextBuffer -> Cursor documentEnd buf =   let row = getLineCount buf - 1
lib/NanoUI/Widgets/TextCommand.hs view
@@ -8,7 +8,7 @@ import Data.Text (Text) import NanoUI.Widgets.TextBuffer (Cursor) --- | Where a motion takes the cursor.+-- | Cursor movement unit and direction. data TextMotion   = CharLeft   | CharRight@@ -20,10 +20,13 @@   | LineDown   | DocumentStart   | DocumentEnd-  deriving (Eq, Show, Enum, Bounded)+  deriving (Eq, Ord, Show, Enum, Bounded) --- | Something done to a text field. Commands that change text are undoable--- and replace the selection where one exists.+-- The book's Text Editing chapter includes this declaration.+-- ANCHOR: text_command+-- | Editing, navigation, selection, history, and clipboard operations on a+-- text field. Mutating commands record an undo step and replace any active+-- selection. data TextCommand   = -- | Replace the selection with text (typing, a snippet).     InsertText !Text@@ -31,6 +34,8 @@     -- @Delete CharLeft@ is Backspace, @Delete WordRight@ Ctrl+Delete.     Delete !TextMotion   | -- | Move the cursor, extending the selection when the flag is set.+    -- Without it, 'CharLeft' and 'CharRight' over a selection go to its start+    -- and its end.     Move !TextMotion !Bool   | SelectAll   | -- | Select from the first position (the anchor) to the second (the@@ -46,4 +51,5 @@   | Copy   | Paste   deriving (Eq, Show)+-- ANCHOR_END: text_command 
− lib/NanoUI/Widgets/TextCommon.hs
@@ -1,64 +0,0 @@-{-# LANGUAGE BangPatterns #-}--module NanoUI.Widgets.TextCommon-  ( -- * Character classes and word boundaries-    TextCharClass (..)-  , textCharClass-  , textWordBounds-    -- * Selection and caret helpers-  , textSelectionForClick-  , textSelectionForDrag-  , selectionCaretGeom-  ) where--import Data.Char (isAlphaNum, isSpace)-import Data.Text (Text)-import qualified Data.Text as T-import NanoUI.Types (clamp)---- | Character classification for double-click word selection.-data TextCharClass = TextWord | TextSpace | TextOther-  deriving (Eq)--textCharClass :: Char -> TextCharClass-textCharClass c-  | isAlphaNum c || c == '_' = TextWord-  | isSpace c = TextSpace-  | otherwise = TextOther---- | Find the word bounds around a character position in text.-textWordBounds :: Text -> Int -> (Int, Int)-textWordBounds text raw-  | T.null text = (0, 0)-  | otherwise =-      -- Split once: repeatedly indexing UTF-8 text makes long-word selection-      -- quadratic. The clamped index guarantees a non-empty suffix.-      let i = clamp 0 (T.length text - 1) raw-          (before, after) = T.splitAt i text-          sameClass = (== textCharClass (T.head after)) . textCharClass-       in ( i - T.length (T.takeWhileEnd sameClass before)-          , i + T.length (T.takeWhile sameClass after)-          )---- | Calculate selection span for single/double/triple click.-textSelectionForClick :: Text -> Int -> Int -> (Int, Int)-textSelectionForClick value idx clicks-  | clicks >= 3 = (0, T.length value)-  | clicks == 2 = textWordBounds value idx-  | otherwise = (idx, idx)---- | Calculate selection span when dragging mouse across text.-textSelectionForDrag :: Text -> Int -> Int -> Int -> (Int, Int)-textSelectionForDrag value anchor idx clicks-  | clicks >= 3 = (0, T.length value)-  | clicks == 2 =-      let (a0, a1) = textWordBounds value anchor-          (c0, c1) = textWordBounds value idx-       in (min a0 c0, max a1 c1)-  | otherwise = (anchor, idx)---- | Shared caret geometry (caretX, caretY, caretH).-{-# INLINE selectionCaretGeom #-}-selectionCaretGeom :: Float -> Float -> Float -> Float -> (Float, Float, Float)-selectionCaretGeom originX originY pw lineH =-  (originX + pw, originY + 1, max 4 (lineH - 2))
+ lib/NanoUI/Widgets/TextDocument.hs view
@@ -0,0 +1,30 @@+-- | The text a text area edits, kept as its lines. A text area takes a+-- document and returns the document after the frame's edits: an edit+-- replaces the lines it touches and shares the rest, so a keystroke costs+-- the lines it changed, not the length of the document. Join the lines into+-- one @Text@ with 'documentText' only when the whole text is wanted, such as+-- when saving.+--+-- Programs edit a document the same way: 'replaceDocumentRange' and+-- 'editDocument' change only the lines they touch, and 'documentBuffer' and+-- 'bufferDocument' move between a document and a+-- "NanoUI.Widgets.TextBuffer" in O(1) for searching or moving through it.+module NanoUI.Widgets.TextDocument+  ( TextDocument+  , textDocument+  , emptyDocument+  , documentText+  , documentLines+  , documentLine+  , documentLineCount+  , sameDocument++    -- * Editing+  , documentRange+  , replaceDocumentRange+  , editDocument+  , documentBuffer+  , bufferDocument+  ) where++import NanoUI.Internal.Widgets.TextDocument
lib/NanoUI/Widgets/TextEditor.hs view
@@ -10,8 +10,6 @@   , EditorMode (..)   , singleLineMode   , multiLineMode-  , editorModeCode-  , editorModeFromCode   , editorFromBuffer   , editorSelection   , hasSelection@@ -31,53 +29,25 @@   , canRedo   ) where -import Control.Monad (void, when)-import Data.Bits ((.&.), (.|.))-import Data.Char (isPrint, isSpace, toLower)+import Control.Monad (unless, void, when)+import Data.Char (isControl, isMark, isSpace, toLower) import Data.Text qualified as T import Data.Text.Short qualified as TS-import NanoUI.Context (Context (..))-import NanoUI.Input (Input (..), Key (..), Modifiers (..))+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.TextEditor.Types+import NanoUI.Internal.Input (Input (..), Key (..), Modifiers (..), chordModifiers, inputKeysElem, isCommandKey, modJump, modMacCommand, modPrimary, noModifiers, onMac) import NanoUI.Widgets.TextBuffer (Cursor (..), TextBuffer, TextEdit (..)) import NanoUI.Widgets.TextCommand (TextCommand (..), TextMotion (..)) import NanoUI.Widgets.TextBuffer qualified as TB --- | How a field lets its document be changed.-data EditorMode = EditorMode-  { modeMultiLine :: !Bool-  , modeEditable :: !Bool-  -- ^ Off for selectable labels: only motion, selection and copy apply.-  , modeCopyable :: !Bool-  -- ^ Off for passwords: nothing reaches the clipboard.-  }-  deriving (Eq, Show)-+-- | Editable, copyable text without newline insertion. singleLineMode :: EditorMode singleLineMode = EditorMode {modeMultiLine = False, modeEditable = True, modeCopyable = True} +-- | Editable, copyable text with multiline commands enabled. multiLineMode :: EditorMode multiLineMode = singleLineMode {modeMultiLine = True} --- | A mode as a store integer, so a command sent to a widget id between--- frames knows what kind of field it edits.-editorModeCode :: EditorMode -> Int-editorModeCode m =-  8-    .|. (if modeMultiLine m then 1 else 0)-    .|. (if modeEditable m then 0 else 2)-    .|. (if modeCopyable m then 0 else 4)--editorModeFromCode :: Int -> Maybe EditorMode-editorModeFromCode code-  | code .&. 8 == 0 = Nothing-  | otherwise =-      Just-        EditorMode-          { modeMultiLine = code .&. 1 /= 0-          , modeEditable = code .&. 2 == 0-          , modeCopyable = code .&. 4 == 0-          }- -- | A document with its selection (the cursor is the buffer's, the anchor -- the other end) and history. data Editor = Editor@@ -87,6 +57,7 @@   }   deriving (Show) +-- | Start an editor with no selection or history at the buffer's current cursor. editorFromBuffer :: TextBuffer -> Editor editorFromBuffer buf = Editor buf (TB.getCursor buf) emptyHistory @@ -94,6 +65,7 @@ editorSelection :: Editor -> (Cursor, Cursor) editorSelection ed = (editorAnchor ed, TB.getCursor (editorBuffer ed)) +-- | Whether the selection anchor differs from the buffer cursor. hasSelection :: Editor -> Bool hasSelection ed = editorAnchor ed /= TB.getCursor (editorBuffer ed) @@ -101,40 +73,7 @@ -- History -------------------------------------------------------------------------------- --- | What started a group of edits, which decides what may join it.-data EditKind = EditTyping | EditDeleting | EditOther-  deriving (Eq, Show)---- | An edit as history keeps it. Undo steps live for the life of a field and--- are rarely replayed, so their texts are compact copies: they cost two--- words less than a 'T.Text', and never keep alive the larger text a slice--- was cut from.-data StoredEdit = StoredEdit !Cursor !TS.ShortText !TS.ShortText-  deriving (Eq, Show)---- | Edits undone and redone as one step.-data EditGroup = EditGroup-  { groupKind :: !EditKind-  , groupEdits :: ![StoredEdit]-  -- ^ Newest first.-  , groupBefore :: !(Cursor, Cursor)-  -- ^ Anchor and cursor before the first edit.-  , groupAfter :: !(Cursor, Cursor)-  -- ^ Anchor and cursor after the last edit.-  }-  deriving (Eq, Show)--data EditHistory = EditHistory-  { historyUndo :: ![EditGroup]-  , historyRedo :: ![EditGroup]-  , historyDepth :: !Int-  -- ^ Length of 'historyUndo'.-  , historyOpen :: !Bool-  -- ^ Whether the next edit may join the newest group. Undo, redo, cursor-  -- moves and commands from outside the field close it.-  }-  deriving (Eq, Show)-+-- | No undo/redo steps and no open edit group. emptyHistory :: EditHistory emptyHistory = EditHistory [] [] 0 False @@ -142,9 +81,11 @@ sealHistory :: EditHistory -> EditHistory sealHistory h = h {historyOpen = False} +-- | Whether at least one edit group can be undone. canUndo :: EditHistory -> Bool canUndo = not . null . historyUndo +-- | Whether at least one undone group can be reapplied. canRedo :: EditHistory -> Bool canRedo = not . null . historyRedo @@ -152,6 +93,36 @@ maxHistoryDepth :: Int maxHistoryDepth = 500 +-- | Maximum individual edits merged into one undo group.+maxGroupEdits :: Int+maxGroupEdits = 256++-- | Approximate UTF-8 byte budget for stored undo history per field.+maxHistoryBytes :: Int+maxHistoryBytes = 4 * 1024 * 1024++editBytes :: StoredEdit -> Int+editBytes (StoredEdit _ rm ins) = TS.length rm + TS.length ins++groupBytes :: EditGroup -> Int+groupBytes g = foldl' (\acc e -> acc + editBytes e) 0 (groupEdits g)++-- | Trim undo groups to both 'maxHistoryDepth' and 'maxHistoryBytes', always+-- retaining the most recent group so a single large edit can still be undone.+trimUndoGroups :: [EditGroup] -> ([EditGroup], Int)+trimUndoGroups [] = ([], 0)+trimUndoGroups (newest : rest) =+  let (keptRest, n) = go (groupBytes newest) 1 rest+      kept = newest : keptRest+   in length kept `seq` (kept, n)+  where+    go !_ !n [] = ([], n)+    go !bytes !n (g : gs)+      | n >= maxHistoryDepth || bytes + gb > maxHistoryBytes = ([], n)+      | otherwise = let (tailGs, totalN) = go (bytes + gb) (n + 1) gs in (g : tailGs, totalN)+      where+        gb = groupBytes g+ -- | Record an edit. Typing joins the group before it while the selection is -- where that group left it, until a new word starts; consecutive deletes -- join the same way. Anything else starts a group. Recording clears redo.@@ -164,16 +135,21 @@     _ ->       let depth' = depth + 1           group = EditGroup kind [stored] before after-       in if depth' > maxHistoryDepth + 50-            then EditHistory (take maxHistoryDepth (group : undos)) [] maxHistoryDepth True+       in if depth' > maxHistoryDepth + 50 || editBytes stored > 65536+            then+              let (kept, n) = trimUndoGroups (group : undos)+               in EditHistory kept [] n True             else EditHistory (group : undos) [] depth' True   where-    stored = StoredEdit (editAt edit) (TS.fromText (editRemoved edit)) (TS.fromText (editInserted edit))+    -- Built now, so the list keeps the compact copies and not the edit,+    -- whose texts are slices of the whole line.+    !stored = StoredEdit (editAt edit) (TS.fromText (editRemoved edit)) (TS.fromText (editInserted edit))     joins g =       open         && kind /= EditOther         && groupKind g == kind         && groupAfter g == before+        && null (drop (maxGroupEdits - 1) (groupEdits g))         && (kind /= EditTyping || not (startsWord g))     -- A letter typed after a space starts a new undo step.     startsWord g = case (groupEdits g, T.uncons (editInserted edit)) of@@ -192,52 +168,49 @@     InsertText raw       | modeEditable mode ->           let txt = singleLine raw-              kind-                | T.length txt == 1 && txt /= "\n" = EditTyping-                | otherwise = EditOther-           in if T.null txt && not (hasSelection ed) then ed else replaceSelection kind txt+           in replaceSelection (if T.length txt == 1 && txt /= "\n" then EditTyping else EditOther) txt     Delete motion       | modeEditable mode ->           if hasSelection ed             then replaceSelection EditDeleting T.empty-            else-              let target = motionTarget motion-               in if target == cursor-                    then ed-                    else edit EditDeleting (TB.replaceEdit T.empty cursor target buf)+            else edit EditDeleting (TB.replaceEdit T.empty cursor (motionTarget motion) buf)+    Move motion False+      -- Left and Right without Shift collapse a selection onto its start+      -- and end, as every platform's text field does.+      | hasSelection ed, motion == CharLeft || motion == CharRight ->+          let end = (if motion == CharLeft then min else max) anchor cursor+           in Editor (TB.withCursor end buf) end (sealHistory hist)     Move motion extend ->       let moved = moveBuffer motion        in Editor moved (if extend then anchor else TB.getCursor moved) (sealHistory hist)-    SelectAll ->-      let end = TB.documentEnd buf-       in Editor (TB.withCursor end buf) (Cursor 0 0) (sealHistory hist)+    SelectAll -> runCommand mode (Select (Cursor 0 0) (TB.documentEnd buf)) ed     Select a c ->-      Editor (TB.withCursor c buf) (TB.clampCursor buf a) (sealHistory hist)+      Editor (TB.withCursor (TB.snapToCluster buf c) buf) (TB.snapToCluster buf a) (sealHistory hist)     Replace a b txt       | modeEditable mode -> edit EditOther (TB.replaceEdit (singleLine txt) a b buf)-    ReplaceAll txt-      | modeEditable mode ->-          edit EditOther (TB.replaceEdit (singleLine txt) (Cursor 0 0) (TB.documentEnd buf) buf)-    Undo -> case historyUndo hist of-      g : rest ->-        let buf' = foldl (\b e -> TB.applyEdit (TB.invertEdit (replayed e)) b) buf (groupEdits g)-            (a, c) = groupBefore g-         in Editor (TB.withCursor c buf') a hist {historyUndo = rest, historyRedo = g : historyRedo hist, historyDepth = historyDepth hist - 1, historyOpen = False}-      [] -> ed-    Redo -> case historyRedo hist of-      g : rest ->-        let buf' = foldr (TB.applyEdit . replayed) buf (groupEdits g)-            (a, c) = groupAfter g-         in Editor (TB.withCursor c buf') a hist {historyUndo = g : historyUndo hist, historyRedo = rest, historyDepth = historyDepth hist + 1, historyOpen = False}-      [] -> ed+    ReplaceAll txt -> runCommand mode (Replace (Cursor 0 0) (TB.documentEnd buf) txt) ed+    Undo+      | g : rest <- historyUndo hist ->+          restore (groupBefore g) (foldl' (\b e -> TB.applyEdit (TB.invertEdit (replayed e)) b) buf (groupEdits g)) $+            hist {historyUndo = rest, historyRedo = g : historyRedo hist, historyDepth = historyDepth hist - 1}+    Redo+      | g : rest <- historyRedo hist ->+          restore (groupAfter g) (foldr (TB.applyEdit . replayed) buf (groupEdits g)) $+            hist {historyUndo = g : historyUndo hist, historyRedo = rest, historyDepth = historyDepth hist + 1}     _ -> ed   where     cursor = TB.getCursor buf+    restore (a, c) buf' h = Editor (TB.withCursor c buf') a h {historyOpen = False}     replayed (StoredEdit at removed inserted) = TextEdit at (TS.toText removed) (TS.toText inserted)     singleLine = (if modeMultiLine mode then id else T.filter (/= '\n')) . TB.insertableText     replaceSelection kind txt = edit kind (TB.replaceEdit txt anchor cursor buf)+    -- An edit that changes nothing records no step, but typing over a+    -- selection with the same text still leaves the caret after it.     edit kind e-      | editRemoved e == editInserted e = ed+      | editRemoved e == editInserted e =+          if T.null (editInserted e)+            then ed+            else let end = TB.getCursor (TB.applyEdit e buf) in Editor (TB.withCursor end buf) end hist       | otherwise =       let buf' = TB.applyEdit e buf           end = TB.getCursor buf'@@ -246,6 +219,13 @@       -- Deleting to the end of a line from its end takes the line break, so       -- Ctrl+K keeps making progress.       LineEnd | T.length (TB.lineAt (cursorRow cursor) buf) == cursorCol cursor -> TB.getCursor (TB.moveRight buf)+      -- Backspace takes a combining mark off the letter it sits on, as text+      -- fields do, so a mistyped vowel sign or accent costs only itself. A+      -- variation selector or an emoji keycap still goes with its character.+      CharLeft+        | Just (_, c) <- T.unsnoc (T.take (cursorCol cursor) (TB.lineAt (cursorRow cursor) buf))+        , isMark c && c /= '\x20E3' && not (c >= '\xFE00' && c <= '\xFE0F') && not (c >= '\xE0100' && c <= '\xE01EF') ->+            cursor {cursorCol = cursorCol cursor - 1}       motion -> TB.getCursor (moveBuffer motion)     moveBuffer = \case       CharLeft -> TB.moveLeft buf@@ -266,15 +246,13 @@   case cmd of     Copy -> ed <$ copySelection     Cut-      | modeEditable mode && modeCopyable mode -> do+      | modeEditable mode && modeCopyable mode+      , hasSelection ed || not (modeMultiLine mode) -> do           copySelection           pure (runCommand mode (Delete CharRight) (if hasSelection ed then ed else runCommand mode SelectAll ed))-      | otherwise -> pure ed     Paste-      | modeEditable mode -> do-          clip <- ctxClipboardGet ctx-          pure (maybe ed (\txt -> runCommand mode (InsertText txt) ed) clip)-      | otherwise -> pure ed+      | modeEditable mode ->+          maybe ed (\txt -> runCommand mode (InsertText txt) ed) <$> ctxClipboardGet ctx     _ -> pure (runCommand mode cmd ed)   where     -- Copy without a selection takes the whole field.@@ -282,66 +260,90 @@       let (a, c) = editorSelection ed           buf = editorBuffer ed           txt = if a /= c then TB.selectedText a c buf else TB.toText buf-      when (not (T.null txt)) $ void (ctxClipboardSet ctx txt)+      unless (T.null txt) $ void (ctxClipboardSet ctx txt) --- | The command a key runs. Ctrl or Alt turns character and deletion keys--- into word motions, and Shift extends the selection.+-- | The command a key runs, following iced's bindings. 'modJump' (Option on+-- macOS, Ctrl elsewhere) makes motions and deletions work by word, and+-- Home/End in a multi-line field go to the document's ends. Command on+-- macOS, or Ctrl+Shift with Backspace/Delete elsewhere, goes to the line's+-- ends. Shift extends the selection. With 'modPrimary': A select all, C/X/V+-- copy/cut/paste, Z undo, Shift+Z or Y redo. On macOS, Ctrl alone gives the+-- Emacs keys: A/E line start/end, B/F move, H/D delete, K/U delete to line+-- end/start. keyCommand :: EditorMode -> Modifiers -> Key -> Maybe TextCommand keyCommand mode mods key =   case key of-    KeyBackspace -> Just (Delete (if word then WordLeft else CharLeft))-    KeyDelete -> Just (Delete (if word then WordRight else CharRight))-    KeyLeft -> move (if word then WordLeft else CharLeft)-    KeyRight -> move (if word then WordRight else CharRight)-    KeyHome -> move (if modCtrl mods && multi then DocumentStart else LineStart)-    KeyEnd -> move (if modCtrl mods && multi then DocumentEnd else LineEnd)-    KeyUp | multi && not word -> move LineUp-    KeyDown | multi && not word -> move LineDown-    KeyEnter | multi && not word -> Just (InsertText "\n")+    KeyBackspace -> Just (Delete (widen LineStart WordLeft CharLeft))+    KeyDelete -> Just (Delete (widen LineEnd WordRight CharRight))+    KeyLeft -> move (reach LineStart WordLeft CharLeft)+    KeyRight -> move (reach LineEnd WordRight CharRight)+    KeyHome -> move (if jump && multi then DocumentStart else LineStart)+    KeyEnd -> move (if jump && multi then DocumentEnd else LineEnd)+    -- Leave Ctrl/Alt with Enter or a vertical arrow to shortcuts.+    KeyUp | multi && not chorded -> move LineUp+    KeyDown | multi && not chorded -> move LineDown+    KeyEnter | multi && not chorded -> Just (InsertText "\n")+    KeyChar c+      | onMac && mods == noModifiers {modCtrl = True} -> emacsCommand c+      | chordModifiers mods -> chordCommand mods c     _ -> Nothing   where     multi = modeMultiLine mode-    word = modCtrl mods || modAlt mods+    jump = modJump mods+    chorded = modCtrl mods || modAlt mods || modSuper mods+    -- Extent of an arrow or deletion; 'widen' adds Ctrl+Shift deletions to+    -- the line's ends off macOS.+    reach line word char+      | modMacCommand mods = line+      | jump = word+      | otherwise = char+    widen line word char+      | modPrimary mods && modShift mods = line+      | otherwise = reach line word char     move m = Just (Move m (modShift mods)) --- | This frame's typing and keys as commands, typed characters first. Ctrl--- turns characters into shortcuts. Ctrl with Alt is AltGr on many layouts, so--- its characters are typed like plain ones.+-- | This frame's typing and keys as commands, typed characters first.+-- Characters typed under modifiers that make their key a command+-- ('isCommandKey': Ctrl, or Alt alone, outside macOS) are dropped, since+-- those keystrokes arrive as key commands or go to shortcuts. Ctrl+Alt is+-- AltGr on many layouts, and Option types on macOS, so their characters are+-- typed normally. X11 and Wayland report AltGr as Alt alone, so Alt alone+-- drops only its key's own character: the @f@ of Alt+F, but not the \@ of+-- AltGr+Q on a German layout. inputTextCommands :: EditorMode -> Input -> [TextCommand]-inputTextCommands mode inp = T.foldr char keys (inputChars inp)+inputTextCommands mode inp =+  let typed = T.filter keepChar (inputChars inp)+   in [InsertText typed | not (T.null typed)] ++ keys   where     mods = inputModifiers inp-    shortcut = modCtrl mods && not (modAlt mods)-    char c rest-      | shortcut = maybe rest (: rest) (ctrlCharCommand mode mods c)-      | isPrint c = InsertText (T.singleton c) : rest-      | otherwise = rest+    keepChar c =+      not (isControl c) && not (isCommandKey mods (KeyChar c) && (modCtrl mods || modSuper mods || ownKey c))+    -- The key's press can end the frame before its text, so the key is+    -- looked for among those held or released.+    ownKey c = any (inputKeysElem (KeyChar (toLower c))) [inputKeysHeld inp, inputKeysReleased inp]     keys = foldr (\k rest -> maybe rest (: rest) (keyCommand mode mods k)) [] (inputKeys inp) --- | The command a character typed with Ctrl runs. Letters may arrive as the--- letter or as their control code.-ctrlCharCommand :: EditorMode -> Modifiers -> Char -> Maybe TextCommand-ctrlCharCommand mode mods c =+chordCommand :: Modifiers -> Char -> Maybe TextCommand+chordCommand mods c =   case toLower c of     'a' -> Just SelectAll     'c' -> Just Copy     'x' -> Just Cut     'v' -> Just Paste-    'z' | modShift mods || c == 'Z' -> Just Redo+    'z' | modShift mods -> Just Redo     'z' -> Just Undo     'y' -> Just Redo-    'k' | multi -> Just (Delete LineEnd)-    'u' | multi -> Just (Delete LineStart)-    'e' | multi -> Just (Move LineEnd False)-    '\x01' -> Just SelectAll-    '\x03' -> Just Copy-    '\x18' -> Just Cut-    '\x16' -> Just Paste-    '\x1a' -> Just Undo-    '\x19' -> Just Redo-    '\v' | multi -> Just (Delete LineEnd)-    '\NAK' | multi -> Just (Delete LineStart)-    '\ENQ' | multi -> Just (Move LineEnd False)     _ -> Nothing-  where-    multi = modeMultiLine mode++-- | Emacs-style Ctrl bindings, used on macOS.+emacsCommand :: Char -> Maybe TextCommand+emacsCommand = \case+  'a' -> Just (Move LineStart False)+  'e' -> Just (Move LineEnd False)+  'b' -> Just (Move CharLeft False)+  'f' -> Just (Move CharRight False)+  'h' -> Just (Delete CharLeft)+  'd' -> Just (Delete CharRight)+  'k' -> Just (Delete LineEnd)+  'u' -> Just (Delete LineStart)+  _ -> Nothing
lib/NanoUI/Widgets/TextField.hs view
@@ -4,94 +4,31 @@   ( runTextCommand   , textCanUndo   , textCanRedo-  , applyTextFieldCommand-  , textFieldMode-  , textFieldHistory   ) where -import Data.Dynamic (fromDynamic)-import Data.IORef (writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)-import Effectful (Eff, type (:>))-import NanoUI.Context (Context (..), WidgetStore (..), getStore, intKey, setTextInputMenu)-import NanoUI.Frame.Hit (findNodeByWidgetId)-import NanoUI.Id (WidgetId)-import NanoUI.Layout.Arena (NodeType (..), getNodeType, getStyleIdx)-import NanoUI.Monad (Ui, askContext, uiIO)-import NanoUI.Store (slotKey, Slot (..))-import NanoUI.Widgets.TextArea (applyTextAreaCommand)-import NanoUI.Widgets.TextEditor-  ( EditHistory-  , EditorMode (..)-  , TextCommand-  , canRedo-  , canUndo-  , editorModeFromCode-  , emptyHistory-  , multiLineMode-  )-import NanoUI.Widgets.TextInput (applyTextInputCommand, textInputMode)+import NanoUI.Internal.Frame.TextEdit (applyTextFieldCommand, textFieldEditor)+import NanoUI.Internal.Id (WidgetId)+import NanoUI.Internal.Monad (NanoUI, withContext)+import NanoUI.Widgets.TextEditor (EditHistory, Editor (..), TextCommand, canRedo, canUndo)  -- | Run a command on the text field (text input, search field, text area) -- with this id, as if its keys were pressed: @runTextCommand (respId resp) -- Undo@. The field takes keyboard focus, and its next frame returns the -- changed text and a 'NanoUI.respChanged' pulse. An id that is not a text -- field is ignored.-runTextCommand :: Ui :> es => WidgetId -> TextCommand -> Eff es ()-runTextCommand wid cmd = do-  ctx <- askContext-  uiIO (applyTextFieldCommand ctx wid cmd)+runTextCommand :: WidgetId -> TextCommand -> NanoUI ()+runTextCommand wid cmd = withContext (\ctx -> applyTextFieldCommand ctx wid cmd)  -- | Whether 'NanoUI.Widgets.TextCommand.Undo' would change the field, for -- enabling a menu item.-textCanUndo :: Ui :> es => WidgetId -> Eff es Bool-textCanUndo wid = do-  ctx <- askContext-  uiIO (canUndo <$> textFieldHistory ctx wid)+textCanUndo :: WidgetId -> NanoUI Bool+textCanUndo = fieldHistory canUndo  -- | Whether 'NanoUI.Widgets.TextCommand.Redo' would change the field, for -- enabling a menu item.-textCanRedo :: Ui :> es => WidgetId -> Eff es Bool-textCanRedo wid = do-  ctx <- askContext-  uiIO (canRedo <$> textFieldHistory ctx wid)---- | Run a command on the field with this id and focus it: the command comes--- from a menu or button that may not be over the field, and the caret,--- selection highlight and next keystroke belong to the field it edited.-applyTextFieldCommand :: Context -> WidgetId -> TextCommand -> IO ()-applyTextFieldCommand ctx wid cmd =-  textFieldMode ctx wid >>= \case-    Just mode -> do-      if modeMultiLine mode-        then applyTextAreaCommand ctx wid cmd-        else applyTextInputCommand ctx wid mode cmd-      writeIORef (ctxFocusId ctx) wid-      setTextInputMenu ctx Nothing-    Nothing -> pure ()---- | How the field with this id edits: from its node when it has one this--- frame, or from what it recorded the last time it was declared.-textFieldMode :: Context -> WidgetId -> IO (Maybe EditorMode)-textFieldMode ctx wid =-  findNodeByWidgetId ctx wid >>= \case-    Just idx ->-      getNodeType (ctxNodeArena ctx) idx >>= \case-        NodeTextInput -> Just . textInputMode <$> getStyleIdx (ctxNodeArena ctx) idx-        NodeTextArea -> pure (Just multiLineMode)-        _ -> pure Nothing-    Nothing -> do-      store <- getStore ctx-      pure (IM.lookup (slotKey SlotTextMode (intKey wid)) (storeInt store) >>= editorModeFromCode)+textCanRedo :: WidgetId -> NanoUI Bool+textCanRedo = fieldHistory canRedo --- | The undo history of the field with this id, empty when it has none.-textFieldHistory :: Context -> WidgetId -> IO EditHistory-textFieldHistory ctx wid = do-  store <- getStore ctx-  let key = intKey wid-      stored = IM.lookup (slotKey SlotTextHistory key) (storeDyn store)-      text = IM.findWithDefault "" key (storeText store)-  pure $ case stored >>= fromDynamic of-    Just (recorded, h) | recorded == (text :: Text) -> h-    _ -> emptyHistory+fieldHistory :: (EditHistory -> Bool) -> WidgetId -> NanoUI Bool+fieldHistory test wid = withContext $ \ctx ->+  maybe False (\(_, ed, _) -> test (editorHistory ed)) <$> textFieldEditor ctx wid
− lib/NanoUI/Widgets/TextInput.hs
@@ -1,413 +0,0 @@--- | Single-line text fields: editable inputs, debounced search fields, and--- selectable read-only labels, plus the key handling they share.-module NanoUI.Widgets.TextInput-  ( TextInputState (..)-  , loadTextInputState-  , saveTextInputState-  , textInputLayout-  , searchFieldLayout-  , textInputEditor-  , editorTextState-  , saveTextEditor-  , editTextInput-  , textInputMode-  , applyTextInputCommand-    -- * Text fields-  , TextInputConfig (..)-  , defaultTextInputConfig-  , textInput-  , textInput'-  , textInputConfigured-  , textInputConfigured'-  , SearchFieldConfig (..)-  , defaultSearchFieldConfig-  , searchField-  , searchField'-  , searchFieldConfigured-  , searchFieldConfigured'-  , buildTextInput-  , editTextField-    -- * Selectable text-  , selectableText-  , selectableText'-  , selectableTextWith-  , selectableTextWith'-  )-where--import Control.Monad (foldM, void, when)-import Data.Bits ((.|.))-import Data.IntMap.Strict qualified as IM-import Data.Dynamic (fromDynamic, toDyn)-import Data.Maybe (fromMaybe, isNothing)-import Data.Text (Text)-import Data.Text qualified as T-import Effectful (Eff, type (:>))-import GHC.Clock (getMonotonicTime)-import NanoUI.Context-  ( Context (..)-  , adoptStoreText-  , getStore-  , intKey-  , markDirty-  , recordStoreText-  , registerFocusable-  , setStore-  , modifyStore-  )-import NanoUI.Id (WidgetId)-import NanoUI.Input-  ( Input (..)-  , Key (..)-  , inputKeys-  )-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Monad (Ui, askContext, askDefaultLayout, askInput, nextId, uiIO)-import NanoUI.Store (WidgetStore (..), Slot (..), slotKey)-import NanoUI.Style (Layout (..), Sizing (..), defaultLayout)-import NanoUI.WidgetText (packTextNodeStyleFull, textInputFlagPassword, textInputFlagSearch, textInputFlagSelectable, textInputPasswordMode, textInputSelectableMode)-import NanoUI.Widgets.Behavior (keyboardFocused)-import NanoUI.Widgets.Node (Response (..), addWidgetStyled, setChanged, setSubmitted)-import NanoUI.Widgets.TextBuffer qualified as TB-import NanoUI.Widgets.TextEditor-  ( Editor (..)-  , EditorMode (..)-  , TextCommand (..)-  , inputTextCommands-  , editorModeCode-  , emptyHistory-  , runCommandIO-  , sealHistory-  , singleLineMode-  )--textInputLayout :: Layout-textInputLayout =-  defaultLayout-    { layoutWidth = Grow 1-    , layoutMinW = 160-    }---- | Layout for a caption-less search field. Grows to fill, keeps a little more--- room for the embedded magnifier / clear chrome than a plain text input.-searchFieldLayout :: Layout-searchFieldLayout =-  defaultLayout-    { layoutWidth = Grow 1-    , layoutMinW = 180-    }--data TextInputState = TextInputState-  { tisText :: !Text-  , tisCursor :: !Int-  , tisAnchor :: !Int-  }-  deriving (Eq, Show)---- | A field's cursor and anchor for @text@; the cursor defaults to the end--- and the anchor to the cursor. Both are clamped to the text, which can have--- been replaced from outside the field with a shorter one.-loadTextInputState :: WidgetStore -> Int -> Text -> TextInputState-loadTextInputState store key text =-  let len = T.length text-      cursor = min len (IM.findWithDefault len (slotKey SlotCursor key) (storeInt store))-      anchor = min len (IM.findWithDefault cursor (slotKey SlotAnchor key) (storeInt store))-   in TextInputState text cursor anchor--saveTextInputState :: Int -> TextInputState -> WidgetStore -> WidgetStore-saveTextInputState key s store =-  store-    { storeText = IM.insert key (tisText s) (storeText store)-    , storeInt =-        IM.insert (slotKey SlotCursor key) (tisCursor s) $-          IM.insert (slotKey SlotAnchor key) (tisAnchor s) (storeInt store)-    }---- | The editor for a field's state, with the undo history stored for it. A--- history recorded against other text (the caller replaced the value) is--- dropped.-textInputEditor :: WidgetStore -> Int -> TextInputState -> Editor-textInputEditor store key s =-  let buf = TB.withCursor (TB.Cursor 0 (tisCursor s)) (TB.fromText (tisText s))-      history = case IM.lookup (slotKey SlotTextHistory key) (storeDyn store) >>= fromDynamic of-        Just (text, h) | text == tisText s -> h-        _ -> emptyHistory-   in Editor buf (TB.clampCursor buf (TB.Cursor 0 (tisAnchor s))) history--editorTextState :: Editor -> TextInputState-editorTextState ed =-  let buf = editorBuffer ed-   in TextInputState (TB.toText buf) (TB.cursorCol (TB.getCursor buf)) (TB.cursorCol (editorAnchor ed))---- | Store an editor's text, selection and history.-saveTextEditor :: Int -> Editor -> WidgetStore -> WidgetStore-saveTextEditor key ed store =-  let s = editorTextState ed-      saved = saveTextInputState key s store-   in saved {storeDyn = IM.insert (slotKey SlotTextHistory key) (toDyn (tisText s, editorHistory ed)) (storeDyn saved)}---- | Run this frame's commands on a field, or 'Nothing' when it had none.-editTextInput :: Context -> EditorMode -> Input -> WidgetStore -> Int -> TextInputState -> IO (Maybe Editor)-editTextInput ctx mode inp store key s0 =-  case inputTextCommands mode inp of-    [] -> pure Nothing-    cmds -> Just <$> foldM (flip (runCommandIO ctx mode)) (textInputEditor store key s0) cmds---- | The editor mode of a single-line field with these style flags.-textInputMode :: Int -> EditorMode-textInputMode si =-  singleLineMode-    { modeEditable = not (textInputSelectableMode si)-    , modeCopyable = not (textInputPasswordMode si)-    }---- | Run a command on a single-line field outside its frame (a context menu--- row, an app's Edit menu). A change to the text pulses 'respChanged' on the--- field's next frame.-applyTextInputCommand :: Context -> WidgetId -> EditorMode -> TextCommand -> IO ()-applyTextInputCommand ctx wid mode cmd = do-  store <- getStore ctx-  let-    key = intKey wid-    s0 = loadTextInputState store key (IM.findWithDefault "" key (storeText store))-  let ed0 = textInputEditor store key s0-  ed <- runCommandIO ctx mode cmd ed0 {editorHistory = sealHistory (editorHistory ed0)}-  let s1 = editorTextState ed-      saved = saveTextEditor key ed store-  setStore ctx $-    if tisText s1 /= tisText s0-      then saved {storeInt = IM.insert (slotKey SlotTextAreaChanged key) 1 (storeInt saved)}-      else saved-  markDirty ctx---- -------------------------------------------------------------------------------- Text fields--- -------------------------------------------------------------------------------data TextInputConfig = TextInputConfig-  { ticPlaceholder :: !Text-  , ticPassword :: !Bool-  , ticLayout :: !Layout-  }-  deriving (Eq, Show)--defaultTextInputConfig :: TextInputConfig-defaultTextInputConfig =-  TextInputConfig-    { ticPlaceholder = ""-    , ticPassword = False-    , ticLayout = textInputLayout-    }---- | Single-line text field. Pass the current text; the result is the text--- after this frame's typing, pastes, and menu edits.-{-# INLINE textInput #-}-textInput :: Ui :> es => Text -> Eff es Text-textInput value = snd <$> textInputConfigured' defaultTextInputConfig value--{-# INLINE textInput' #-}-textInput' :: Ui :> es => Text -> Eff es (Response, Text)-textInput' = textInputConfigured' defaultTextInputConfig---- | 'textInput' with a placeholder, password masking, or its own layout.------ @--- secret' <- textInputConfigured defaultTextInputConfig {ticPassword = True} secret--- @-{-# INLINE textInputConfigured #-}-textInputConfigured :: Ui :> es => TextInputConfig -> Text -> Eff es Text-textInputConfigured cfg value = snd <$> textInputConfigured' cfg value--textInputConfigured' :: Ui :> es => TextInputConfig -> Text -> Eff es (Response, Text)-textInputConfigured' cfg value =-  buildTextInput-    (if ticPassword cfg then textInputFlagPassword else 0)-    (ticLayout cfg)-    (ticPlaceholder cfg)-    value-    Nothing---- | One frame of a single-line field's text state: load the text (seeding--- @initial@ on first use) with its cursor and anchor, run the editor while--- focused, and save any change. While unfocused, @unfocusedText@ (when given)--- replaces the stored text, so a field that mirrors another value follows it.--- Returns the text before and after this frame, whether it is focused, and--- whether a command run from outside the frame changed it.-editTextField :: Ui :> es => WidgetId -> EditorMode -> Text -> Maybe Text -> Eff es (Text, Text, Bool, Bool)-editTextField wid mode initial unfocusedText = do-  ctx <- askContext-  uiIO $ registerFocusable ctx wid-  inp <- askInput-  store <- uiIO (getStore ctx)-  let-    key = intKey wid-    modeKey = slotKey SlotTextMode key-    pulseKey = slotKey SlotTextAreaChanged key-    stored = IM.lookup key (storeText store)-    s0 = loadTextInputState store key (fromMaybe initial stored)-    pulse = IM.member pulseKey (storeInt store)-  when (isNothing stored || IM.lookup modeKey (storeInt store) /= Just (editorModeCode mode) || pulse) $-    uiIO $ modifyStore ctx $ \st -> st-      { storeText = if isNothing stored then IM.insert key initial (storeText st) else storeText st-      , storeInt = IM.delete pulseKey (IM.insert modeKey (editorModeCode mode) (storeInt st))-      }-  isFocus <- keyboardFocused wid-  mEdited <- if isFocus then uiIO (editTextInput ctx mode inp store key s0) else pure Nothing-  let s1 = case mEdited of-        Just ed -> editorTextState ed-        Nothing -> maybe s0 (\t -> s0 {tisText = t}) unfocusedText-  when (s1 /= s0) $-    uiIO $ modifyStore ctx (maybe (saveTextInputState key s1) (saveTextEditor key) mEdited)-  pure (tisText s0, tisText s1, isFocus, pulse)---- | Shared single-line field builder. The caller's @value@ is adopted as by--- 'NanoUI.Context.adoptStoreText'. @styleIdx@ may carry the search or password--- flag on a @NodeTextInput@; when @mDebounceMs@ is present the returned change--- pulse is delayed until the text has been idle for that long (immediate for--- clear clicks).-buildTextInput ::-  Ui :> es =>-  Int ->-  Layout ->-  Text ->-  Text ->-  Maybe Float ->-  Eff es (Response, Text)-buildTextInput styleIdx layout placeholder value mDebounceMs = do-  wid <- nextId-  ctx <- askContext-  let key = intKey wid-  _ <- uiIO $ adoptStoreText ctx wid key value-  -- Both modes are constants, so an idle field allocates no mode record.-  let mode = if textInputPasswordMode styleIdx then singleLineMode {modeCopyable = False} else singleLineMode-  (oldText, newText, isFocus, pulse) <- editTextField wid mode value Nothing-  uiIO $ recordStoreText ctx key newText-  inp <- askInput-  let submitted = isFocus && KeyEnter `elem` inputKeys inp-      edited = pulse || newText /= oldText-  changed <- case mDebounceMs of-    Nothing -> pure edited-    Just ms -> uiIO (debounceSearchChanged ctx key isFocus edited ms)-  resp <- addWidgetStyled wid NodeTextInput placeholder 0 layout styleIdx-  pure (setSubmitted submitted (setChanged changed resp), newText)---- | Debounced change pulse for a search field. Fires when the text differs from--- the last committed query and either the field is empty, lost focus, or has--- been idle for @ms@ (trailing edge). Field text lives under @key@; the last--- committed query under 'SlotSearchCommitted'.-debounceSearchChanged :: Context -> Int -> Bool -> Bool -> Float -> IO Bool-debounceSearchChanged ctx key focused rawChanged ms = do-  store <- getStore ctx-  let-    committedKey = slotKey SlotSearchCommitted key-    ageKey = slotKey SlotSearchAge key-    fieldText = IM.findWithDefault "" key (storeText store)-    committedMissing = not (IM.member committedKey (storeText store))-    committed = IM.findWithDefault fieldText committedKey (storeText store)-    dirty = fieldText /= committed-    needClock = rawChanged || dirty-  now <- if needClock then getMonotonicTime else pure 0-  let-    -- Debounce timing stays in Double: wall-clock seconds as Float lose-    -- resolution at long uptimes (~125 ms at 12 days), which would shift-    -- (or skip) the trailing-edge window.-    lastEdit = IM.findWithDefault now ageKey (storeDouble store)-    deadline = realToFrac ms :: Double-    idleMs = (now - lastEdit) * 1000-    commit =-      not rawChanged-        && dirty-        && (T.null fieldText || not focused || idleMs >= deadline)-  when (rawChanged || commit || committedMissing) $-    modifyStore ctx $ \st ->-      st-        { storeText =-            if commit || committedMissing-              then IM.insert committedKey fieldText (storeText st)-              else storeText st-        , storeDouble =-            if rawChanged || commit-              then IM.insert ageKey now (storeDouble st)-              else storeDouble st-        }-  pure commit---- | Search field: a caption-less 'NodeTextInput' with an embedded magnifier and--- clear button. The label acts as the placeholder. Change pulses are debounced--- (trailing edge); clearing with the embedded button fires immediately.-data SearchFieldConfig = SearchFieldConfig-  { sfcPlaceholder :: !Text-  , sfcDebounceMs :: !Float-  , sfcLayout :: !Layout-  }-  deriving (Eq, Show)--defaultSearchFieldConfig :: SearchFieldConfig-defaultSearchFieldConfig =-  SearchFieldConfig-    { sfcPlaceholder = "Search…"-    , sfcDebounceMs = 300-    , sfcLayout = searchFieldLayout-    }---- | Search box with a magnifier and a clear button; the first argument is the--- placeholder. Pass the current text; the result is the text after this--- frame. 'respChanged' on 'searchField'' is debounced: it fires once typing--- pauses, or at once when the field is cleared.-{-# INLINE searchField #-}-searchField :: Ui :> es => Text -> Text -> Eff es Text-searchField placeholder value = snd <$> searchField' placeholder value--{-# INLINE searchField' #-}-searchField' :: Ui :> es => Text -> Text -> Eff es (Response, Text)-searchField' placeholder =-  searchFieldConfigured' (defaultSearchFieldConfig {sfcPlaceholder = placeholder})--{-# INLINE searchFieldConfigured #-}-searchFieldConfigured :: Ui :> es => SearchFieldConfig -> Text -> Eff es Text-searchFieldConfigured cfg value = snd <$> searchFieldConfigured' cfg value--searchFieldConfigured' ::-  Ui :> es => SearchFieldConfig -> Text -> Eff es (Response, Text)-searchFieldConfigured' cfg value =-  buildTextInput-    textInputFlagSearch-    (sfcLayout cfg)-    (sfcPlaceholder cfg)-    value-    (Just (sfcDebounceMs cfg))---- -------------------------------------------------------------------------------- Selectable text--- --------------------------------------------------------------------------------- | Read-only text that can be selected with the mouse and copied with Ctrl+C.-{-# INLINE selectableText #-}-selectableText :: Ui :> es => Text -> Eff es ()-selectableText = selectableTextWith id--{-# INLINE selectableText' #-}-selectableText' :: Ui :> es => Text -> Eff es Response-selectableText' = selectableTextWith' id--{-# INLINE selectableTextWith #-}-selectableTextWith :: Ui :> es => (Layout -> Layout) -> Text -> Eff es ()-selectableTextWith f txt = void (selectableTextWith' f txt)--selectableTextWith' :: Ui :> es => (Layout -> Layout) -> Text -> Eff es Response-selectableTextWith' f txt = do-  layout <- f <$> askDefaultLayout-  wid <- nextId-  ctx <- askContext-  -- The caller owns the text; the editor only moves the selection.-  _ <- uiIO $ adoptStoreText ctx wid (intKey wid) txt-  _ <- editTextField wid singleLineMode {modeEditable = False} txt Nothing-  let styleIdx =-        textInputFlagSelectable-          .|. packTextNodeStyleFull-                (layoutFontVariant layout)-                (layoutFontWeight layout)-                (layoutFontStyle layout)-                (layoutTextDecoration layout)-                0-  addWidgetStyled wid NodeTextInput txt 0 layout styleIdx
− lib/NanoUI/Widgets/Tree.hs
@@ -1,175 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{-# LANGUAGE BangPatterns #-}--module NanoUI.Widgets.Tree (TreeItem (..), tree, tree') where--import Control.Applicative ((<|>))-import Control.Monad (when)-import Data.IORef (writeIORef)-import Data.Foldable (fold, toList)-import Data.Maybe (fromMaybe)-import Data.Text (Text)-import Data.Primitive.SmallArray (SmallArray, indexSmallArray, mapSmallArray', sizeofSmallArray, smallArrayFromList)-import Effectful (Eff, type (:>))-import qualified Data.IntMap.Strict as IM-import qualified Data.IntSet as IS-import NanoUI.Context (Context (..), adoptStoreInt, getFocusId, getStore, intKey, recordStoreInt, registerFocusable, setStore, writeStoreInt, modifyStore)-import NanoUI.Font (treeChevronRect)-import NanoUI.Frame.Hit (scrollHitRect)-import NanoUI.Id (WidgetId (..), hashWidgetId)-import NanoUI.Input (inputMousePos)-import NanoUI.Layout.Arena (NodeType (..))-import NanoUI.Store (WidgetStore (..))-import NanoUI.Monad (Ui, askContext, askInput, nextId, uiIO, withKey)-import NanoUI.Style (defaultLayout, fillW, gap, tight)-import NanoUI.Types (Rect (..), clamp, rectContains)-import NanoUI.WidgetText (treeEncodeStyle)-import NanoUI.Widgets.Behavior (KeyNav (..), useKeyNav)-import NanoUI.Widgets.Combinators (selectableItem)-import NanoUI.Widgets.Layout (columnWith)-import NanoUI.Widgets.Node (Response (..), setChanged, tagContainer)--data TreeItem = TreeItem {treeItemLabel :: !Text, treeItemChildren :: ![TreeItem]}-  deriving (Eq, Show)---- | A visible row: pre-order node index, depth, whether it has children, label.-type TreeRow = (Int, Int, Bool, Text)---- | Nodes in a subtree, its root included.-subtreeSize :: TreeItem -> Int-subtreeSize item = 1 + forestSize (treeItemChildren item)--forestSize :: [TreeItem] -> Int-forestSize = foldl' (\acc x -> acc + subtreeSize x) 0---- | Visible rows in pre-order, skipping the children of collapsed nodes. One--- pass: rows come out in order, and a subtree hands the next pre-order index--- to the continuation that lists its later siblings.-visibleRows :: IS.IntSet -> [TreeItem] -> SmallArray TreeRow-visibleRows expanded items = smallArrayFromList (go 0 0 items (const []))-  where-    go !idx !_ [] k = k idx-    go !idx !depth (item@(TreeItem lbl kids) : rest) k =-      let hasKids = not (null kids)-       in (idx, depth, hasKids, lbl)-            : if hasKids && IS.member idx expanded-              then go (idx + 1) (depth + 1) kids (\next -> go next depth rest k)-              else go (idx + subtreeSize item) depth rest k---- | Pre-order indices of every node that has children (the default expansion).-parentIndices :: [TreeItem] -> IS.IntSet-parentIndices items = snd (go 0 items IS.empty)-  where-    go !idx [] acc = (idx, acc)-    go !idx (TreeItem _ kids : rest) acc-      | null kids = go (idx + 1) rest acc-      | otherwise = case go (idx + 1) kids (IS.insert idx acc) of-          (next, acc') -> go next rest acc'--treeKeyNav ::-  KeyNav ->-  SmallArray TreeRow ->-  SmallArray Response ->-  WidgetId ->-  Int ->-  IS.IntSet ->-  (Int, IS.IntSet, Maybe WidgetId)-treeKeyNav nav rows resps focus selected expanded-  | hashWidgetId focus == 0 || not moving = (selected, expanded, Nothing)-  | otherwise = case [pos | pos <- [0 .. n - 1], widAt pos == focus] of-      pos : _ -> step pos (indexSmallArray rows pos)-      [] -> (selected, expanded, Nothing)- where-  moving = knUp nav || knDown nav || knLeft nav || knRight nav || knEnter nav || knSpace nav-  n = sizeofSmallArray rows-  widAt i = rawRespId (indexSmallArray resps i)-  idxAt i = let (idx, _, _, _) = indexSmallArray rows i in idx-  wantToggle = knEnter nav || knSpace nav-  parentPosition pos depth = go (pos - 1)-    where-      go i-        | i < 0 = Nothing-        | otherwise =-            let (_, d, _, _) = indexSmallArray rows i-             in if d < depth then Just i else go (i - 1)-  step pos (nodeIdx, depth, hasKids, _)-    | knDown nav, pos + 1 < n = let p = pos + 1 in (idxAt p, expanded, Just (widAt p))-    | knUp nav, pos > 0 = let p = pos - 1 in (idxAt p, expanded, Just (widAt p))-    | wantToggle, hasKids = (selected, toggle nodeIdx expanded, Nothing)-    | knRight nav, hasKids, not (IS.member nodeIdx expanded) = (selected, IS.insert nodeIdx expanded, Nothing)-    | knLeft nav, hasKids, IS.member nodeIdx expanded = (selected, IS.delete nodeIdx expanded, Nothing)-    | knLeft nav, depth > 0 =-        case parentPosition pos depth of-          Just p -> (idxAt p, expanded, Just (widAt p))-          Nothing -> (nodeIdx, expanded, Nothing)-    | otherwise = (selected, expanded, Nothing)--toggle :: Int -> IS.IntSet -> IS.IntSet-toggle idx s = if IS.member idx s then IS.delete idx s else IS.insert idx s--treeRow :: (Ui :> es) => Int -> TreeRow -> Int -> IS.IntSet -> Eff es (Response, Maybe Int, Maybe IS.IntSet)-treeRow rowIdx (nodeIdx, depth, hasKids, lbl) selectedIdx expandedSet = do-  ctx <- askContext-  inp <- askInput-  let expanded = IS.member nodeIdx expandedSet-      selected = selectedIdx == nodeIdx-      isOdd = odd rowIdx-  resp <- selectableItem NodeTree lbl selected (tight . fillW $ defaultLayout) (treeEncodeStyle nodeIdx depth hasKids expanded isOdd)-  uiIO $ registerFocusable ctx (rawRespId resp)-  if not (rawRespClicked resp)-    then pure (resp, Nothing, Nothing)-    else uiIO $ do-      mrect <- scrollHitRect ctx (rawRespId resp)-      let mouse = inputMousePos inp-          onChevron = case mrect of-            Just rect@(Rect x y w h) ->-              rectContains (treeChevronRect (ctxFontMetrics ctx) x y w h depth) mouse-                && rectContains rect mouse-            _ -> False-      if hasKids && onChevron-        then pure (setChanged False resp, Nothing, Just (toggle nodeIdx expandedSet))-        else pure (setChanged (not selected) resp, Just nodeIdx, Nothing)---- | Collapsible tree. Rows are numbered in pre-order; pass the selected row--- and the result is the selection after this frame's click or arrow keys.--- Expansion is kept by the widget. @key@ distinguishes trees in one scope.-{-# INLINE tree #-}-tree :: (Foldable f, Ui :> es) => Text -> f TreeItem -> Int -> Eff es Int-tree key items index = snd <$> tree' key items index--tree' :: (Foldable f, Ui :> es) => Text -> f TreeItem -> Int -> Eff es (Response, Int)-tree' key inputItems index =-  withKey ("tree:" <> key) $ do-    groupId <- nextId-    ctx <- askContext-    let items = toList inputItems-        groupKey = intKey groupId-        total = forestSize items-        clamped = if total <= 0 then 0 else clamp 0 (total - 1) index-    selected <- uiIO $ adoptStoreInt ctx groupId groupKey clamped-    st <- uiIO (getStore ctx)-    expandedSet <- case IM.lookup groupKey (storeIntSet st) of-      Just expanded -> pure expanded-      Nothing -> do-        let initial = parentIndices items-        uiIO $ setStore ctx (st {storeIntSet = IM.insert groupKey initial (storeIntSet st)})-        pure initial-    let rows = visibleRows expandedSet items-    columnWith (tight . gap 0 . fillW) $ do-      tagContainer groupId-      results <--        smallArrayFromList-          <$> sequence [withKey i (treeRow rowIdx row selected expandedSet) | rowIdx <- [0 .. sizeofSmallArray rows - 1], let row@(i, _, _, _) = indexSmallArray rows rowIdx]-      let resps = mapSmallArray' (\(r, _, _) -> r) results-          afterClickSel = fromMaybe selected (foldr (\(_, idx, _) rest -> idx <|> rest) Nothing results)-          afterClickExp = fromMaybe expandedSet (foldr (\(_, _, s) rest -> s <|> rest) Nothing results)-      focus <- uiIO (getFocusId ctx)-      nav <- useKeyNav focus-      let (keySel, keyExp, mFocus) = treeKeyNav nav rows resps focus afterClickSel afterClickExp-      uiIO $ do-        writeStoreInt ctx groupId groupKey keySel-        recordStoreInt ctx groupKey keySel-      when (keyExp /= expandedSet) $ uiIO $-        modifyStore ctx (\st' -> st' {storeIntSet = IM.insert groupKey keyExp (storeIntSet st')})-      maybe (pure ()) (\wid -> uiIO $ writeIORef (ctxFocusId ctx) wid) mFocus-      pure (setChanged (keySel /= selected) (fold resps), keySel)
nano-ui.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.4 name:               nano-ui-version:            0.1.0.1+version:            0.2.0.0 synopsis:           Immediate-mode GUI toolkit for Haskell description:     Widgets, layout, and input handling for immediate-mode interfaces. A view@@ -10,12 +10,21 @@ license-file:       LICENSE author:             goolord maintainer:         zacharyachurchill@gmail.com+homepage:           https://github.com/goolord/nano-ui+bug-reports:        https://github.com/goolord/nano-ui/issues category:           Graphics build-type:         Simple+tested-with:        GHC ==9.10.3 || ==9.14.1 extra-doc-files:     CHANGELOG.md+    GUIDE.md     README.md +source-repository head+    type:     git+    location: https://github.com/goolord/nano-ui.git+    subdir:   packages/nano-ui+ common extensions     default-language: GHC2024     default-extensions:@@ -34,143 +43,210 @@     ghc-options: -rtsopts -threaded "-with-rtsopts=-A8m -H64m -K128m -T"  common warnings-  ghc-options:-    -Wall-    -Wextra-    -Wcompat-    -Widentities-    -Wincomplete-record-updates-    -Wincomplete-uni-patterns-    -Wmissing-export-lists-    -Wmissing-home-modules-    -Wpartial-fields-    -Wredundant-constraints+    ghc-options:+        -Wall+        -Wextra+        -Wcompat+        -Widentities+        -Wincomplete-record-updates+        -Wincomplete-uni-patterns+        -Wmissing-export-lists+        -Wmissing-home-modules+        -Wpartial-fields+        -Wredundant-constraints+        -Wunused-packages --- Tests, benchmarks and executables build against the library and also--- reject dependencies they never import.+-- Tests, benchmarks and executables build against the library. common downstream     import:           extensions     import:           warnings-    ghc-options:      -Wunused-packages     build-depends:-        base ^>=4.22.0.0,+        base >=4.20 && <4.23,         nano-ui  library     import:           extensions     import:           warnings+    -- The public API is every exposed module outside NanoUI.Internal. The+    -- exposed NanoUI.Internal modules are for backends, tests and tools that+    -- need more than the API, and change without notice.     exposed-modules:         NanoUI-        NanoUI.Context-        NanoUI.Context.Types-        NanoUI.Debug-        NanoUI.Id+        NanoUI.Adornment+        NanoUI.Backend+        NanoUI.Bidi+        NanoUI.Chrome+        NanoUI.Effectful         NanoUI.Input-        NanoUI.Layout.Arena-        NanoUI.Layout.Solve         NanoUI.Monad-        NanoUI.Emit+        NanoUI.Path+        NanoUI.Runner+        NanoUI.Runner.Windows+        NanoUI.Shader.Raw+        NanoUI.Shortcut+        NanoUI.Svg         NanoUI.Testing         NanoUI.Testing.Assert         NanoUI.Testing.Harness         NanoUI.Testing.Runner+        NanoUI.Testing.Sim+        NanoUI.Themes+        NanoUI.Var+        NanoUI.Widgets.Combo+        NanoUI.Widgets.Custom+        NanoUI.Widgets.PaneGrid+        NanoUI.Widgets.RichText+        NanoUI.Widgets.TextArea         NanoUI.Widgets.TextBuffer         NanoUI.Widgets.TextCommand+        NanoUI.Widgets.TextDocument         NanoUI.Widgets.TextEditor         NanoUI.Widgets.TextField-        NanoUI.Widgets.TextArea-        NanoUI.Widgets.Combo-        NanoUI.Widgets.Custom-        NanoUI.Widgets.RichText-        NanoUI.Widgets.PaneGrid-        NanoUI.Widgets.SplitPane-        NanoUI.Store-        NanoUI.Frame.Hit-        NanoUI.Frame.TextEdit-        NanoUI.Frame.Window-        NanoUI.Runner-        NanoUI.Bidi-        NanoUI.SIMD-        NanoUI.Svg+        NanoUI.Internal.Canvas+        NanoUI.Internal.Context+        NanoUI.Internal.Context.Types+        NanoUI.Internal.Debug+        NanoUI.Internal.Frame.Hit+        NanoUI.Internal.Frame.TextArea+        NanoUI.Internal.Frame.Window+        NanoUI.Internal.Id+        NanoUI.Internal.Id.Cursor+        NanoUI.Internal.Image+        NanoUI.Internal.Input+        NanoUI.Internal.Layout.Arena+        NanoUI.Internal.Layout.Solve+        NanoUI.Internal.Monad+        NanoUI.Internal.Path+        NanoUI.Internal.RichText.Types+        NanoUI.Internal.Shader+        NanoUI.Internal.SIMD+        NanoUI.Internal.Store+        NanoUI.Internal.Store.Types+        NanoUI.Internal.Uniforms+        NanoUI.Internal.Var+        NanoUI.Internal.Var.Cell+        NanoUI.Internal.Var.Generic+        NanoUI.Internal.Var.Types+        NanoUI.Internal.Widgets.Custom+        NanoUI.Internal.Widgets.SplitPane+        NanoUI.Internal.Widgets.TextArea+        NanoUI.Internal.Widgets.TextDocument     other-modules:-        NanoUI.Animatable-        NanoUI.Animation-        NanoUI.Atlas-        NanoUI.Compact-        NanoUI.Context.Animation-        NanoUI.Context.Core-        NanoUI.Context.Drawing-        NanoUI.Context.Overlay-        NanoUI.Context.Scroll-        NanoUI.Damage-        NanoUI.Draw-        NanoUI.Font-        NanoUI.Hooks-        NanoUI.Frame-        NanoUI.Frame.Cursor-        NanoUI.Draw.Arena-        NanoUI.Draw.Shapes-        NanoUI.Draw.Text-        NanoUI.Draw.Types-        NanoUI.Frame.Input-        NanoUI.Frame.Chrome-        NanoUI.Frame.Focus-        NanoUI.Frame.Paint-        NanoUI.Frame.Paint.Types-        NanoUI.Frame.Paint.Widgets-        NanoUI.Frame.Redraw-        NanoUI.Frame.Scroll-        NanoUI.Frame.Scroll.Geometry-        NanoUI.Frame.Select-        NanoUI.Frame.Node-        NanoUI.Frame.Overlay-        NanoUI.Frame.Spans-        NanoUI.Frame.SpanArena-        NanoUI.Frame.TextArea-        NanoUI.Frame.TextArea.Content-        NanoUI.Frame.TextArea.Geometry-        NanoUI.Frame.TextEdit.Menu-        NanoUI.Frame.TextInput-        NanoUI.Style-        NanoUI.Types-        NanoUI.WidgetText-        NanoUI.Widgets.Node-        NanoUI.Widgets.Chrome-        NanoUI.Widgets.Layout-        NanoUI.Widgets.Tabs-        NanoUI.Widgets.Radio-        NanoUI.Widgets.Tree-        NanoUI.Widgets.ColorPicker-        NanoUI.Widgets.Drawing-        NanoUI.Widgets.TextInput-        NanoUI.Widgets.NumericInput-        NanoUI.Widgets.TextCommon-        NanoUI.Widgets.Animate-        NanoUI.Widgets.Overlay-        NanoUI.Widgets.Popup-        NanoUI.Widgets.Menu-        NanoUI.Widgets.Table-        NanoUI.Widgets.Behavior-        NanoUI.Widgets.Combinators-        NanoUI.Widgets.Drop-        NanoUI.Widgets.Button-        NanoUI.Widgets.Checkbox-        NanoUI.Widgets.Display-        NanoUI.Widgets.Select-        NanoUI.Widgets.Slider+        NanoUI.Internal.Monad.Core+        NanoUI.Internal.Monad.Explain+        NanoUI.Internal.Monad.Focus+        NanoUI.Internal.Monad.Scroll+        NanoUI.Internal.Equality+        NanoUI.Internal.Var.List+        NanoUI.Internal.Var.Map+        NanoUI.Internal.Derived+        NanoUI.Internal.Resource+        NanoUI.Internal.Host+        NanoUI.Internal.BackendSession+        NanoUI.Internal.NativeWindow.Types+        NanoUI.Internal.Sensor.Types+        NanoUI.Internal.TextEditor.Types+        NanoUI.Internal.TextCluster+        NanoUI.Internal.Animatable+        NanoUI.Internal.Animation+        NanoUI.Internal.Atlas+        NanoUI.Internal.Compact+        NanoUI.Internal.Context.Animation+        NanoUI.Internal.Context.Core+        NanoUI.Internal.Context.Drawing+        NanoUI.Internal.Context.Overlay+        NanoUI.Internal.Context.Scroll+        NanoUI.Internal.Damage+        NanoUI.Internal.Draw+        NanoUI.Internal.EffectDriver+        NanoUI.Internal.Font+        NanoUI.Internal.Font.Types+        NanoUI.Internal.GenCache+        NanoUI.Internal.Metrics+        NanoUI.Internal.Frame+        NanoUI.Internal.Frame.Cursor+        NanoUI.Internal.Draw.Arena+        NanoUI.Internal.Draw.Shapes+        NanoUI.Internal.Draw.Types+        NanoUI.Internal.Frame.Input+        NanoUI.Internal.Frame.Chrome+        NanoUI.Internal.Frame.Explain+        NanoUI.Internal.Frame.Paint+        NanoUI.Internal.Frame.Paint.Widgets+        NanoUI.Internal.Frame.Scroll+        NanoUI.Internal.Layout.ScrollGeometry+        NanoUI.Internal.Frame.Select+        NanoUI.Internal.Frame.Node+        NanoUI.Internal.Frame.Spans+        NanoUI.Internal.Frame.SpanArena+        NanoUI.Internal.Frame.TextEdit+        NanoUI.Internal.Frame.TextInput+        NanoUI.Internal.Layout.Arena.Cache+        NanoUI.Internal.Layout.Arena.Query+        NanoUI.Internal.Layout.Arena.Types+        NanoUI.Internal.Layout.Solve.Flex+        NanoUI.Internal.Layout.Solve.Measure+        NanoUI.Internal.Layout.Solve.Position+        NanoUI.Internal.Style+        NanoUI.Internal.Style.Layout+        NanoUI.Internal.Style.Presets+        NanoUI.Internal.Style.Theme+        NanoUI.Internal.StyleBits+        NanoUI.Internal.GridNode+        NanoUI.Internal.Store.Slots+        NanoUI.Internal.Types+        NanoUI.Internal.WidgetText+        NanoUI.Internal.Widgets.Node+        NanoUI.Internal.Widgets.Caption+        NanoUI.Internal.Widgets.Layout+        NanoUI.Internal.Widgets.Tabs+        NanoUI.Internal.Widgets.Radio+        NanoUI.Internal.Widgets.Tree+        NanoUI.Internal.Widgets.ColorPicker+        NanoUI.Internal.Widgets.Cursor+        NanoUI.Internal.Widgets.Drawing+        NanoUI.Internal.Widgets.TextInput+        NanoUI.Internal.Widgets.NumericInput+        NanoUI.Internal.Widgets.Animate+        NanoUI.Internal.Widgets.Overlay+        NanoUI.Internal.Widgets.Popup+        NanoUI.Internal.Widgets.Menu+        NanoUI.Internal.Widgets.Table+        NanoUI.Internal.Widgets.Behavior+        NanoUI.Internal.Widgets.Combinators+        NanoUI.Internal.Widgets.Drop+        NanoUI.Internal.Widgets.Adornment+        NanoUI.Internal.Widgets.Button+        NanoUI.Internal.Widgets.Checkbox+        NanoUI.Internal.Widgets.Disclosure+        NanoUI.Internal.Widgets.Display+        NanoUI.Internal.Widgets.Select+        NanoUI.Internal.Widgets.Slider+        NanoUI.Internal.Widgets.Image+        NanoUI.Internal.Widgets.Sensor+        NanoUI.Internal.Widgets.Shader+        NanoUI.Internal.Shortcut+        NanoUI.Internal.Widgets.Shortcut+        NanoUI.Internal.NativeWindow+        NanoUI.Internal.ChildWindow+        NanoUI.Internal.Tasks     build-depends:-        base ^>=4.22.0.0,+        base >=4.20 && <4.23,         bytestring ^>=0.12,         colonnade ^>=1.2,-        containers ^>=0.8,-        effectful-core ^>=2.6,+        containers >=0.7 && <0.9,+        effectful-core >=2.6 && <2.8,+        exceptions ^>=0.10,         ghc-compact ^>=0.1,         hashable ^>=1.5,-        hashtables ^>=1.4,-        hexml ^>=0.3.5,+        monad-control ^>=1.0,+        nano-svg ^>=0.2,         primitive ^>=0.9,         text ^>=2.1,         text-short ^>=0.1.6,+        transformers ^>=0.6,+        transformers-base ^>=0.4,+        unliftio-core ^>=0.2,         unordered-containers ^>=0.2,         vector ^>=0.13     hs-source-dirs:   lib@@ -190,32 +266,61 @@     main-is:          NanoUI/TextBufferSpec.hs     build-depends:         hspec ^>=2.11,+        QuickCheck >=2.15 && <2.19,         text ^>=2.1     hs-source-dirs:   test +-- Compiles NanoUI.Internal.StyleBits from the library's source (it imports+-- only base) and checks that the style-index fields of each node type are+-- disjoint and fit in 64 bits.+test-suite style-bits-spec+    import:           extensions+    import:           warnings+    type:             exitcode-stdio-1.0+    main-is:          StyleBitsSpec.hs+    other-modules:    NanoUI.Internal.StyleBits+    ghc-options:      -Wunused-packages+    build-depends:+        base >=4.20 && <4.23+    hs-source-dirs:   test/style-bits lib+ test-suite nano-ui-test     import:           downstream     import:           test-rts-options     type:             exitcode-stdio-1.0+    -- Every module of this suite starts with {-# OPTIONS_GHC -O0 #-}. At -O1+    -- the simplifier inlines the library's views into every test view: about+    -- 280 s to compile at -j1, against 20 s at -O0. (-O0 in ghc-options+    -- would do the same, but cabal check warns about it.)     main-is:          Main.hs     other-modules:-        Cases+        BackendApi+        Spec+        TestSupport         Cases.Animation         Cases.Atlas         Cases.Combo         Cases.Damage+        Cases.DamageProps+        Cases.SimFuzz+        Cases.ApiSmoke         Cases.Demo         Cases.Grid         Cases.HostDraw         Cases.Keyboard         Cases.Cache+        Cases.LayoutReuse+        Cases.LayoutProps         Cases.Runner         Cases.RichText         Cases.SIMD+        Cases.Shader         Cases.Shaping         Cases.Styling         Cases.Svg+        Cases.Adornment         Cases.State+        Cases.Passes         Cases.Table         Cases.Modal         Cases.NoThunks@@ -225,16 +330,41 @@         Cases.TextInput         Cases.NumericInput         Cases.ContextMenu+        Cases.PointerOwnership         Cases.PointerRelease         Cases.CustomWidget         Cases.Tooltip+        Cases.ViewApi+        Cases.PaneGrid+        Cases.Labels+        Cases.Reorder         Cases.Window+        Cases.WidgetIdIndex+        Cases.Paths+        Cases.LayoutFlow+        Cases.Images+        Cases.Focus+        Cases.TooltipDelay+        Cases.Visibility+        Cases.Cursors+        Cases.Explain+        Cases.Shortcut+        Cases.Ime+        Cases.PointerExtra+        Cases.Theming+        Cases.NativeWindow+        Cases.Tasks     build-depends:-        bytestring,-        containers,-        effectful ^>=2.6,-        nothunks,+        bytestring ^>=0.12,+        containers >=0.7 && <0.9,+        directory ^>=1.3,+        effectful >=2.6 && <2.8,+        hashable ^>=1.5,+        filepath ^>=1.5,+        nothunks ^>=0.3,         primitive ^>=0.9,+        QuickCheck >=2.15 && <2.19,+        vector ^>=0.13,         text ^>=2.1     hs-source-dirs:   test/integration @@ -244,6 +374,7 @@     main-is:          Profile.hs     hs-source-dirs:   examples     build-depends:+        bytestring ^>=0.12,         primitive ^>=0.9,         text ^>=2.1 @@ -256,5 +387,9 @@     main-is:          Inspection.hs     ghc-options:      -fplugin=Test.Inspection.Plugin     build-depends:-        inspection-testing+        containers >=0.7 && <0.9,+        inspection-testing ^>=0.6,+        primitive ^>=0.9,+        vector ^>=0.13,+        text ^>=2.1     hs-source-dirs:   test/inspection
test/NanoUI/TextBufferSpec.hs view
@@ -1,21 +1,26 @@ module Main (main) where +import Control.Monad (forM_) import Data.Text qualified as T-import NanoUI.Frame.TextEdit (textWordBounds)-import NanoUI.Input (Input (..), Key (..), Modifiers (..), emptyInput, inputKeysFromList)+import NanoUI.Internal.Frame.TextArea (textWordBounds)+import NanoUI.Input (Input (..), Key (..), Modifiers (..), emptyInput, inputKeysFromList, primaryModifiers)+import NanoUI.Internal.Input (onMac) import NanoUI.Widgets.TextArea as TA import NanoUI.Widgets.TextBuffer as TB+import NanoUI.Widgets.TextDocument qualified as TD+import NanoUI.Internal.Store (ptrEq) import NanoUI.Widgets.TextEditor as TE import Test.Hspec+import Test.Hspec.QuickCheck (modifyMaxSuccess, prop)+import Test.QuickCheck (Arbitrary (..), Gen, Property, choose, property, conjoin, counterexample, elements, frequency, listOf, oneof, vectorOf, (.&&.), (===))  main :: IO ()-main = hspec spec--noMods :: Modifiers-noMods = Modifiers False False False+main = hspec (spec >> editModelSpec) -ctrlMods :: Modifiers-ctrlMods = Modifiers False True False+noMods, ctrlMods, altMods :: Modifiers+noMods = Modifiers False False False False+ctrlMods = Modifiers False True False False+altMods = Modifiers False False True False  -- | One frame's typed text and keys, with modifiers held. frameInput :: Modifiers -> T.Text -> [Key] -> Input@@ -27,9 +32,13 @@ typeArea mods chars keys s =   foldl' (flip TA.runTextAreaCommand) s (TE.inputTextCommands TE.multiLineMode (frameInput mods chars keys)) +-- | A text area's text and caret.+areaText :: TA.TextAreaState -> (T.Text, TB.Cursor)+areaText s = (TB.toText (TA.tasBuffer s), TB.getCursor (TA.tasBuffer s))+ -- | Run commands on a buffer.-edit :: TE.EditorMode -> [TE.TextCommand] -> TB.TextBuffer -> TB.TextBuffer-edit mode cmds buf = TE.editorBuffer (foldl' (flip (TE.runCommand mode)) (TE.editorFromBuffer buf) cmds)+edit :: [TE.TextCommand] -> TB.TextBuffer -> TB.TextBuffer+edit cmds buf = TE.editorBuffer (foldl' (flip (TE.runCommand TE.multiLineMode)) (TE.editorFromBuffer buf) cmds)  spec :: Spec spec = do@@ -40,238 +49,438 @@       map (`TB.lineAt` b) [-1, 0, 1, 2, 3, maxBound]         `shouldBe` ["", "α\tβ", "猫", "", "", ""] -    it-      "replaces a backwards selection across Unicode lines and places the caret after the insertion" $ do-      let-        b = TB.fromText "αβ\n猫犬\nend"-        start = TB.Cursor 0 1-        end = TB.Cursor 1 1-        replaced = edit TE.multiLineMode [TE.Select end start, TE.InsertText "🙂\nλ"] b-        deleted = edit TE.multiLineMode [TE.Select end start, TE.Delete TE.CharLeft] b-      TB.selectedText end start b `shouldBe` "β\n猫"-      TB.toText replaced `shouldBe` "α🙂\nλ犬\nend"-      TB.getCursor replaced `shouldBe` TB.Cursor 1 1-      TB.toText deleted `shouldBe` "α犬\nend"-      TB.getCursor deleted `shouldBe` start--    it "roundtrips a trailing newline through fromText/toText" $ do+    it "splits and joins lines, reading Windows line ends and pasting classic Mac ones" $ do       TB.toText (TB.fromText "a\n") `shouldBe` "a\n"       TB.toLines (TB.fromText "a\n") `shouldBe` ["a", ""]--    it "inserts a tab that text-zipper would otherwise drop" $ do-      let-        b = edit TE.multiLineMode [TE.InsertText "\t"] TB.empty-      TB.toText b `shouldBe` "\t"-      TB.getCursor b `shouldBe` TB.Cursor 0 1+      mapM_+        (\t -> TB.joinLines (TB.splitLines t) `shouldBe` t)+        ["", "\n", "\n\n", "a", "a\n", "\nλ", "α\n\n猫🙂\n", "one\ntwo\nthree"]+      TB.toLines (TB.fromText "one\r\ntwo\r\n") `shouldBe` ["one", "two", ""]+      TB.toText (TB.fromText "one\r\ntwo") `shouldBe` "one\ntwo"+      TB.insertableText "a\rb\r\nc" `shouldBe` "a\nb\nc" -    it "inserts Unicode, tabs, and newlines while filtering control characters" $ do+    it "leaves the expected text and caret after each edit" $ do       let-        b = edit TE.multiLineMode [TE.InsertText "α\t\n猫\x01"] (TB.withCursor (TB.Cursor 0 1) (TB.fromText "ab"))-      TB.toLines b `shouldBe` ["aα\t", "猫b"]-      TB.getCursor b `shouldBe` TB.Cursor 1 1+        uni = TB.fromText "αβ\n猫犬\nend"+        backwards = TE.Select (TB.Cursor 1 1) (TB.Cursor 0 1)+        atEnd = TB.moveToEOL . TB.fromText+      TB.selectedText (TB.Cursor 1 1) (TB.Cursor 0 1) uni `shouldBe` "β\n猫"+      forM_+        [ ("replace a backwards selection", [backwards, TE.InsertText "🙂\nλ"], uni, "α🙂\nλ犬\nend", Just (TB.Cursor 1 1))+        , ("delete a backwards selection", [backwards, TE.Delete TE.CharLeft], uni, "α犬\nend", Just (TB.Cursor 0 1))+        , -- text-zipper would drop the tab.+          ("insert a tab", [TE.InsertText "\t"], TB.empty, "\t", Just (TB.Cursor 0 1))+        , ( "filter control characters"+          , [TE.InsertText "α\t\n猫\x01"]+          , TB.withCursor (TB.Cursor 0 1) (TB.fromText "ab")+          , "aα\t\n猫b"+          , Just (TB.Cursor 1 1)+          )+        , ("delete a word left with its trailing space", [TE.Delete TE.WordLeft], atEnd "foo ", "", Nothing)+        , ("delete the previous word", [TE.Delete TE.WordLeft], atEnd "foo bar", "foo ", Nothing)+        , ("join lines at a line start", [TE.Delete TE.WordLeft], TB.moveDown (TB.fromText "foo\nbar"), "bar", Nothing)+        , ("delete a word right", [TE.Delete TE.WordRight], TB.fromText "foo bar", " bar", Nothing)+        , ("delete to the line end", [TE.Delete TE.LineEnd], TB.moveRight (TB.fromText "hello"), "h", Nothing)+        , ("delete to the line start", [TE.Delete TE.LineStart], atEnd "hello", "", Nothing)+        , -- Whole flags, emoji sequences and combining marks; Backspace takes a+          -- combining mark off its letter, and a variation selector or keycap+          -- with its character.+          ("delete a skin-toned emoji", [TE.Delete TE.CharLeft], atEnd "a👍🏽", "a", Nothing)+        , ("delete a flag", [TE.Delete TE.CharRight], TB.fromText "🇺🇸🇫🇷", "🇫🇷", Nothing)+        , ("delete a vowel sign", [TE.Delete TE.CharLeft], atEnd "a\x0915\x093F", "a\x0915", Nothing)+        , ("delete a combining accent", [TE.Delete TE.CharLeft], atEnd "e\x0301", "e", Nothing)+        , ("delete a variation sequence", [TE.Delete TE.CharLeft], atEnd "a\x2764\xFE0F", "a", Nothing)+        , ("delete a keycap", [TE.Delete TE.CharLeft], atEnd "a#\xFE0F\x20E3", "a", Nothing)+        , ("delete an accented letter", [TE.Delete TE.CharRight], TB.fromText "e\x0301x", "x", Nothing)+        ]+        $ \(name, cmds, b, txt, cursor) -> do+          let b' = edit cmds b+          (name :: String, TB.toText b') `shouldBe` (name, txt)+          forM_ cursor $ \c -> (name, TB.getCursor b') `shouldBe` (name, c) -    it "empty insertion preserves the preferred column on a short line" $ do-      let-        b = TB.moveDown (TB.withCursor (TB.Cursor 0 4) (TB.fromText "12345\nx\n12345"))-      TB.getCursor (TB.moveDown (edit TE.multiLineMode [TE.InsertText ""] b)) `shouldBe` TB.Cursor 2 4+    it "keeps joiners, bidi marks and private-use characters that are typed or pasted" $ do+      let kept = "👩\x200D💻 \x200C \x200F \xE0A0"+      TB.insertableText kept `shouldBe` kept+      TE.inputTextCommands TE.multiLineMode (frameInput noMods "\x200C\x7F" [])+        `shouldBe` [TE.InsertText "\x200C"] -    it-      "clamps vertical motion at document boundaries without losing the preferred column" $ do+    it "moves by grapheme and keeps the preferred column through short lines and document ends" $ do       let+        atEnd = TB.moveToEOL . TB.fromText         top = TB.withCursor (TB.Cursor 0 3) (TB.fromText "abcd\nx\n猫猫猫猫")         bottom = TB.moveDown (TB.moveDown top)-      TB.getCursor (TB.moveUp top) `shouldBe` TB.Cursor 0 3-      TB.getCursor bottom `shouldBe` TB.Cursor 2 3-      TB.getCursor (TB.moveDown bottom) `shouldBe` TB.Cursor 2 3-      TB.getCursor (TB.moveUp (TB.moveUp bottom)) `shouldBe` TB.Cursor 0 3-      TB.getCursor (TB.moveDown TB.empty) `shouldBe` TB.Cursor 0 0-      -- Moving through a shorter line snaps the column and restores it after.-      let         short = TB.withCursor (TB.Cursor 0 4) (TB.fromText "12345\n12\n12345")-      TB.getCursor (TB.moveDown short) `shouldBe` TB.Cursor 1 2-      TB.getCursor (TB.moveDown (TB.moveDown short)) `shouldBe` TB.Cursor 2 4-      TB.getCursor (TB.moveUp (TB.moveDown (TB.moveDown short))) `shouldBe` TB.Cursor 1 2--    it "finds the document end independently of the current cursor" $ do-      TB.documentEnd (TB.fromText "α\n猫🙂") `shouldBe` TB.Cursor 1 2-      TB.documentEnd (TB.fromText "α\n") `shouldBe` TB.Cursor 1 0-      TB.documentEnd TB.empty `shouldBe` TB.Cursor 0 0--    it "deleting a word left eats trailing whitespace then the previous word" $ do+        cursors = map TB.getCursor+      cursors [TB.moveLeft (atEnd "a🇺🇸"), TB.moveLeft (atEnd "a👩\x200D💻"), TB.moveRight (TB.fromText "e\x0301x")]+        `shouldBe` [TB.Cursor 0 1, TB.Cursor 0 1, TB.Cursor 0 2]+      forM_ ["a🇺🇸🇫🇷x", "US🇺🇸🇫🇷🇺", "a😀\x200D👩\x200D👧b", "\x200Dx", "e\x0301\n👍🏽y"] $ \sample -> do+        let buf = TB.fromText sample+            endCur = TB.documentEnd buf+            traceBounds targetCur step s0 =+              let cur = TB.getCursor s0+               in cur : if cur == targetCur then [] else traceBounds targetCur step (step s0)+            fwd = traceBounds endCur TB.moveRight buf+            bwd = reverse (traceBounds (TB.Cursor 0 0) TB.moveLeft (TB.withCursor endCur buf))+        (sample, bwd) `shouldBe` (sample, fwd)+      cursors [TB.moveUp top, bottom, TB.moveDown bottom, TB.moveUp (TB.moveUp bottom), TB.moveDown TB.empty]+        `shouldBe` [TB.Cursor 0 3, TB.Cursor 2 3, TB.Cursor 2 3, TB.Cursor 0 3, TB.Cursor 0 0]+      cursors [TB.moveDown short, TB.moveDown (TB.moveDown short), TB.moveUp (TB.moveDown (TB.moveDown short))]+        `shouldBe` [TB.Cursor 1 2, TB.Cursor 2 4, TB.Cursor 1 2]+      -- An empty insertion keeps the preferred column too.       let-        deleteWordLeft = TB.toText . edit TE.multiLineMode [TE.Delete TE.WordLeft] . TB.moveToEOL . TB.fromText-      deleteWordLeft "foo " `shouldBe` ""-      deleteWordLeft "foo bar" `shouldBe` "foo "+        b = TB.moveDown (TB.withCursor (TB.Cursor 0 4) (TB.fromText "12345\nx\n12345"))+      TB.getCursor (TB.moveDown (edit [TE.InsertText ""] b)) `shouldBe` TB.Cursor 2 4+      map TB.documentEnd [TB.fromText "α\n猫🙂", TB.fromText "α\n", TB.empty]+        `shouldBe` [TB.Cursor 1 2, TB.Cursor 1 0, TB.Cursor 0 0] -    it "deleting a word left joins lines at beginning of line" $ do+  describe "NanoUI.Widgets.TextDocument and edits" $ do+    it "replaces a range, reads one back, and shares untouched lines" $ do       let-        b = edit TE.multiLineMode [TE.Delete TE.WordLeft] (TB.moveToBOL (TB.moveDown (TB.fromText "foo\nbar")))-      TB.toText b `shouldBe` "bar"--    it "deleting a word right deletes the word after the cursor" $ do-      TB.toText (edit TE.multiLineMode [TE.Delete TE.WordRight] (TB.fromText "foo bar")) `shouldBe` " bar"--    it "deleting to the line end or start removes the rest of the line on either side" $ do-      TB.toText (edit TE.multiLineMode [TE.Delete TE.LineEnd] (TB.moveRight (TB.fromText "hello"))) `shouldBe` "h"-      TB.toText (edit TE.multiLineMode [TE.Delete TE.LineStart] (TB.moveToEOL (TB.fromText "hello"))) `shouldBe` ""+        doc0 = TD.textDocument "one\ntwo\nthree\nfour"+        doc1 = TD.replaceDocumentRange (TB.Cursor 2 5) (TB.Cursor 1 1) "W\nX" doc0+      TD.documentText doc1 `shouldBe` "one\ntW\nX\nfour"+      TD.documentRange (TB.Cursor 0 1) (TB.Cursor 1 2) doc1 `shouldBe` "ne\ntW"+      -- Forced first, so the comparison sees values rather than thunks.+      let shared row = let !a = TD.documentLine row doc0; !b = TD.documentLine row doc1 in ptrEq a b+      map shared [0, 3] `shouldBe` [True, True] -  describe "NanoUI.Widgets.TextBuffer edits" $ do-    it "applies an edit across lines and inverts it back" $ do+    it "applies and inverts a recorded edit, on documents and buffers" $ do       let+        doc0 = TD.textDocument "alpha\nbeta"+        e = TB.replaceEdit "B" (TB.Cursor 1 0) (TB.Cursor 1 1) (TD.documentBuffer doc0)+        doc1 = TD.editDocument e doc0+      TD.documentText doc1 `shouldBe` "alpha\nBeta"+      TD.editDocument (TB.invertEdit e) doc1 `shouldBe` doc0+      TD.bufferDocument (TD.documentBuffer doc1) `shouldBe` doc1+      let         b0 = TB.fromText "αβ\n猫犬\nend"-        e = TB.replaceEdit "🙂\nλ\nμ" (TB.Cursor 0 1) (TB.Cursor 2 1) b0-        b1 = TB.applyEdit e b0-      TB.editRemoved e `shouldBe` "β\n猫犬\ne"-      TB.toText b1 `shouldBe` "α🙂\nλ\nμnd"-      TB.getCursor b1 `shouldBe` TB.Cursor 2 1-      TB.toText (TB.applyEdit (TB.invertEdit e) b1) `shouldBe` "αβ\n猫犬\nend"+        across = TB.replaceEdit "🙂\nλ\nμ" (TB.Cursor 0 1) (TB.Cursor 2 1) b0+        b1 = TB.applyEdit across b0+      TB.editRemoved across `shouldBe` "β\n猫犬\ne"+      (TB.toText b1, TB.getCursor b1) `shouldBe` ("α🙂\nλ\nμnd", TB.Cursor 2 1)+      TB.toText (TB.applyEdit (TB.invertEdit across) b1) `shouldBe` "αβ\n猫犬\nend"      it "edits the middle of a long document locally" $ do       let         doc = T.intercalate "\n" [T.pack (show i) | i <- [1 .. 20000 :: Int]]-        b0 = TB.fromText doc         insertAt b i = let at = TB.Cursor (5000 + i) 0 in TB.applyEdit (TB.replaceEdit "x\n" at at b) b-        edited = foldl' insertAt b0 [1 .. 500 :: Int]-      TB.getLineCount edited `shouldBe` 20500-      TB.lineAt 5002 edited `shouldBe` "x"+        edited = foldl' insertAt (TB.fromText doc) [1 .. 500 :: Int]+      (TB.getLineCount edited, TB.lineAt 5002 edited) `shouldBe` (20500, "x")    describe "NanoUI.Widgets.TextEditor" $ do     let       run mode = foldl' (flip (TE.runCommand mode))+      line = TE.runCommand TE.singleLineMode       typeText mode t ed = run mode ed [TE.InsertText (T.singleton c) | c <- T.unpack t]       single = TE.editorFromBuffer TB.empty       text = TB.toText . TE.editorBuffer--    it "undoes typing a word at a time and redoes it" $ do-      let-        typed = typeText TE.singleLineMode "hello world" single-        once = TE.runCommand TE.singleLineMode TE.Undo typed-        twice = TE.runCommand TE.singleLineMode TE.Undo once-      text typed `shouldBe` "hello world"-      text once `shouldBe` "hello "-      text twice `shouldBe` ""-      text (run TE.singleLineMode twice [TE.Redo, TE.Redo]) `shouldBe` "hello world"-      TB.getCursor (TE.editorBuffer once) `shouldBe` TB.Cursor 0 6+      depth = TE.historyDepth . TE.editorHistory      it "joins a run of deletes into one step and restores the selection it replaced" $ do       let-        typed = typeText TE.singleLineMode "abcdef" single-        deleted = run TE.singleLineMode typed (replicate 3 (TE.Delete TE.CharLeft))-        selected = TE.runCommand TE.singleLineMode (TE.Select (TB.Cursor 0 1) (TB.Cursor 0 3)) deleted-        replaced = TE.runCommand TE.singleLineMode (TE.InsertText "Z") selected-        undone = TE.runCommand TE.singleLineMode TE.Undo replaced-      text deleted `shouldBe` "abc"-      text (TE.runCommand TE.singleLineMode TE.Undo deleted) `shouldBe` "abcdef"-      text replaced `shouldBe` "aZ"-      text undone `shouldBe` "abc"+        deleted = run TE.singleLineMode (typeText TE.singleLineMode "abcdef" single) (replicate 3 backspace)+        backspace = TE.Delete TE.CharLeft+        replaced = run TE.singleLineMode deleted [TE.Select (TB.Cursor 0 1) (TB.Cursor 0 3), TE.InsertText "Z"]+        undone = line TE.Undo replaced+      map text [deleted, line TE.Undo deleted, replaced, undone] `shouldBe` ["abc", "abcdef", "aZ", "abc"]       TE.editorSelection undone `shouldBe` (TB.Cursor 0 1, TB.Cursor 0 3)      it "drops redo after a new edit and ignores no-op commands" $ do       let-        typed = typeText TE.singleLineMode "ab" single-        undone = TE.runCommand TE.singleLineMode TE.Undo typed-        retyped = TE.runCommand TE.singleLineMode (TE.InsertText "c") undone-      TE.canRedo (TE.editorHistory undone) `shouldBe` True-      TE.canRedo (TE.editorHistory retyped) `shouldBe` False-      TE.historyDepth (TE.editorHistory (TE.runCommand TE.singleLineMode (TE.Delete TE.CharLeft) single)) `shouldBe` 0-      text (TE.runCommand TE.singleLineMode (TE.ReplaceAll "c") retyped) `shouldBe` "c"-      TE.historyDepth (TE.editorHistory (TE.runCommand TE.singleLineMode (TE.ReplaceAll "c") retyped))-        `shouldBe` TE.historyDepth (TE.editorHistory retyped)+        undone = line TE.Undo (typeText TE.singleLineMode "ab" single)+        retyped = line (TE.InsertText "c") undone+      map (TE.canRedo . TE.editorHistory) [undone, retyped] `shouldBe` [True, False]+      depth (line (TE.Delete TE.CharLeft) single) `shouldBe` 0+      text (line (TE.ReplaceAll "c") retyped) `shouldBe` "c"+      depth (line (TE.ReplaceAll "c") retyped) `shouldBe` depth retyped +    it "collapses the selection when typing over it with the same text" $ do+      let+        selected = line (TE.Select (TB.Cursor 0 0) (TB.Cursor 0 1)) (typeText TE.singleLineMode "abc" single)+        retyped = typeText TE.singleLineMode "ab" selected+      (text retyped, TE.hasSelection retyped) `shouldBe` ("abbc", False)++    it "Left and Right without Shift land on a selection's start and end" $ do+      let+        typed = typeText TE.singleLineMode "hello" single+        selected = line TE.SelectAll typed+        backwards = line (TE.Select (TB.Cursor 0 4) (TB.Cursor 0 1)) typed+        moved m extend = TE.editorSelection . line (TE.Move m extend)+      moved TE.CharLeft False selected `shouldBe` (TB.Cursor 0 0, TB.Cursor 0 0)+      moved TE.CharRight False backwards `shouldBe` (TB.Cursor 0 4, TB.Cursor 0 4)+      moved TE.CharLeft True selected `shouldBe` (TB.Cursor 0 0, TB.Cursor 0 4)+     it "keeps line breaks out of single-line fields and bounds history depth" $ do-      text (TE.runCommand TE.singleLineMode (TE.InsertText "a\nb") single) `shouldBe` "ab"+      text (line (TE.InsertText "a\nb") single) `shouldBe` "ab"       text (TE.runCommand TE.multiLineMode (TE.InsertText "a\r\nb") single) `shouldBe` "a\nb"       let-        edits = run TE.multiLineMode single (concat (replicate 1000 [TE.InsertText "\n"]))-      TE.historyDepth (TE.editorHistory edits) `shouldSatisfy` (<= 550)+        edits = run TE.multiLineMode single (replicate 1000 (TE.InsertText "\n"))+      depth edits `shouldSatisfy` (<= 550)       text (run TE.multiLineMode edits (replicate 2000 TE.Undo)) `shouldSatisfy` (\t -> T.length t >= 450)      it "undoes a large paste in one step without copying the document per keystroke" $ do       let         doc = T.intercalate "\n" (replicate 50000 "some line of text")         pasted = TE.runCommand TE.multiLineMode (TE.InsertText doc) single-        typed = typeText TE.multiLineMode "tail" pasted-        back = run TE.multiLineMode typed [TE.Undo, TE.Undo]+        back = run TE.multiLineMode (typeText TE.multiLineMode "tail" pasted) [TE.Undo, TE.Undo]       text back `shouldBe` ""       text (run TE.multiLineMode back [TE.Redo, TE.Redo]) `shouldBe` doc <> "tail"    describe "NanoUI.Widgets.TextArea" $ do-    it "Ctrl+Z undoes and Ctrl+Shift+Z redoes" $ do-      let-        s0 = TA.initTextAreaState ""-        typed = foldl' (\s c -> typeArea noMods (T.singleton c) [] s) s0 ("one two" :: String)-        undone = typeArea ctrlMods "z" [] typed-        redone = typeArea (Modifiers True True False) "z" [] undone-      TB.toText (TA.buffer undone) `shouldBe` "one "-      TB.toText (TA.buffer redone) `shouldBe` "one two"+    let+      start = TA.initTextAreaState+      atEnd = typeArea noMods "" [KeyEnd] . start+      foo = atEnd "foo bar"+      (wordMods, otherMods) = if onMac then (altMods, ctrlMods) else (ctrlMods, altMods)+      lineMods = if onMac then Modifiers False False False True else Modifiers True True False False+      at = TB.Cursor 0+      mac a b = if onMac then a else b -    it "Ctrl+Alt types characters (AltGr) while Ctrl alone runs shortcuts" $ do-      let-        s0 = typeArea noMods "" [KeyEnd] (TA.initTextAreaState "ab")-        altGr = Modifiers False True True-      TB.toText (TA.buffer (typeArea altGr "@€" [] s0)) `shouldBe` "ab@€"-      TE.inputTextCommands TE.singleLineMode (frameInput altGr "@" [])-        `shouldBe` [TE.InsertText "@"]-      TE.inputTextCommands TE.singleLineMode (frameInput ctrlMods "a" [KeyLeft])-        `shouldBe` [TE.SelectAll, TE.Move TE.WordLeft False]+    it "maps keys and typed text to edits by platform" $+      forM_+        [ -- The word modifier edits and moves by word, the other of Ctrl and Alt by character.+          ("word delete", typeArea wordMods "" [KeyDelete] (start "foo bar"), (" bar", at 0))+        , ("word right", typeArea wordMods "" [KeyRight] (start "foo bar"), ("foo bar", at 3))+        , ("word left", typeArea wordMods "" [KeyLeft] (atEnd "foo"), ("foo", at 0))+        , ("character delete", typeArea otherMods "" [KeyDelete] (start "foo bar"), ("oo bar", at 0))+        , ("character right", typeArea otherMods "" [KeyRight] (start "foo bar"), ("foo bar", at 1))+        , ("character left", typeArea otherMods "" [KeyLeft] (atEnd "foo"), ("foo", at 2))+        , -- Command, or elsewhere Ctrl+Shift, edits and moves to the line's ends.+          ("line delete", typeArea lineMods "" [KeyBackspace] (atEnd "foo bar\nbaz"), ("\nbaz", at 0))+        , ("Ctrl+Left", typeArea (mac lineMods ctrlMods) "" [KeyLeft] foo, ("foo bar", at (mac 0 4)))+        , -- Ctrl alone moves and deletes as in Emacs on macOS, and is no command elsewhere.+          ("Ctrl+A", typeArea ctrlMods "" [KeyChar 'a'] foo, ("foo bar", at (mac 0 7)))+        , ("Ctrl+B", typeArea ctrlMods "" [KeyChar 'b'] foo, ("foo bar", at (mac 6 7)))+        , ("Ctrl+H", typeArea ctrlMods "" [KeyChar 'h'] foo, (mac "foo ba" "foo bar", at (mac 6 7)))+        , ("Ctrl+U", typeArea ctrlMods "" [KeyChar 'u'] foo, (mac "" "foo bar", at (mac 0 7)))+        , -- Backspace at the end of a line read with Windows line ends deletes its last character.+          ("CRLF backspace", typeArea noMods "" [KeyBackspace] (atEnd "one\r\ntwo"), ("on\ntwo", at 2))+        ]+        $ \(name, s, want) -> (name :: String, areaText s) `shouldBe` (name, want) -    it-      "typing and Enter replace a backwards multiline selection and collapse its anchor" $ do+    it "selects all with Ctrl+A or Ctrl+a (Command on macOS), and reads chords from keys" $ do+      forM_ [KeyChar 'a', KeyChar 'A'] $ \k -> do+        let s = typeArea primaryModifiers "" [k] foo+        (TA.tasSelectionAnchor s, TB.getCursor (TA.tasBuffer s)) `shouldBe` (at 0, at 7)+      -- Chords come from key events; characters typed with Ctrl held are ignored.+      TE.inputTextCommands TE.singleLineMode (frameInput primaryModifiers "z\x1a" [KeyChar 'z', KeyChar 'y'])+        `shouldBe` [TE.Undo, TE.Redo]++    it "typing and Enter replace a backwards multiline selection and collapse its anchor" $ do       let-        selected =-          TA.setTextAreaSelection (TB.Cursor 1 1) (TB.Cursor 0 1) $-            TA.initTextAreaState "abc\ndef"+        selected = TA.setTextAreaSelection (TB.Cursor 1 1) (TB.Cursor 0 1) (TA.initTextAreaState "abc\ndef")         typed = typeArea noMods "λ" [] selected         entered = typeArea noMods "" [KeyEnter] selected-      TB.toText (TA.buffer typed) `shouldBe` "aλef"-      TB.getCursor (TA.buffer typed) `shouldBe` TB.Cursor 0 2-      TA.selectionAnchor typed `shouldBe` TB.Cursor 0 2-      TB.toText (TA.buffer entered) `shouldBe` "a\nef"-      TB.getCursor (TA.buffer entered) `shouldBe` TB.Cursor 1 0-      TA.selectionAnchor entered `shouldBe` TB.Cursor 1 0+      (areaText typed, TA.tasSelectionAnchor typed) `shouldBe` (("aλef", TB.Cursor 0 2), TB.Cursor 0 2)+      (areaText entered, TA.tasSelectionAnchor entered) `shouldBe` (("a\nef", TB.Cursor 1 0), TB.Cursor 1 0) -    it "Ctrl and Alt edit and move by word" $ do-      let-        s0 = TA.initTextAreaState "foo bar"-      mapM_-        ( \mods -> do-            let-              deleted = typeArea mods "" [KeyDelete] s0-              right = typeArea mods "" [KeyRight] s0-              left = typeArea mods "" [KeyLeft] right-            TB.toText (TA.buffer deleted) `shouldBe` " bar"-            TB.getCursor (TA.buffer right) `shouldBe` TB.Cursor 0 3-            TB.getCursor (TA.buffer left) `shouldBe` TB.Cursor 0 0-        )-        [ctrlMods, Modifiers False False True]+    it "clamps a selection past the document's end and scrolls the caret into view" $ do+      let s = TA.setTextAreaSelection (TB.Cursor 9 9) (TB.Cursor 9 9) (TA.initTextAreaState "ab")+      (TA.tasSelectionAnchor s, TB.getCursor (TA.tasBuffer s)) `shouldBe` (TB.Cursor 0 2, TB.Cursor 0 2)+      let s0 = TA.setTextAreaViewport (80, 16) 16 (TA.initTextAreaState "a\nb")+      TA.tasScrollOffset (typeArea noMods "" [KeyDown] s0) `shouldBe` (0, 16) -    it "scrolls the caret into a one-line viewport" $ do-      let-        s0 =-          TA.setTextAreaViewport (80, 16) 16 $-            TA.initTextAreaState "a\nb"-        s1 = typeArea noMods "" [KeyDown] s0-      TA.scrollOffset s1 `shouldBe` (0, 16)+  describe "text word selection" $+    it "groups Unicode words, whitespace and punctuation, keeps marks in words, and clamps" $ do+      map (textWordBounds "αβ_猫  🙂!?") [0 .. 8]+        `shouldBe` replicate 4 (0, 4) ++ replicate 2 (4, 6) ++ replicate 3 (6, 9)+      forM_+        [ ("नमस्ते जी", 0, (0, 6))+        , ("cafe\x0301 au lait", 4, (0, 5))+        , ("می\x200Cخواهم", 0, (0, 8))+        , ("", 10, (0, 0))+        , ("one two", -10, (0, 3))+        , ("one two", 100, (4, 7))+        , (T.replicate 10000 "猫", 5000, (0, 10000))+        ]+        $ \(t, i :: Int, want) -> (T.take 20 t, i, textWordBounds t i) `shouldBe` (T.take 20 t, i, want) -    it "Ctrl+A and Ctrl+a both select all" $ do-      let-        s0 = TA.initTextAreaState "hello"-        atEnd = typeArea noMods "" [KeyEnd] s0-        fromLower = typeArea ctrlMods "a" [] atEnd-        fromUpper = typeArea ctrlMods "A" [] atEnd-      TB.getCursor (TA.buffer fromLower) `shouldBe` TB.Cursor 0 5-      TA.selectionAnchor fromLower `shouldBe` TB.Cursor 0 0-      TB.getCursor (TA.buffer fromUpper) `shouldBe` TB.Cursor 0 5-      TA.selectionAnchor fromUpper `shouldBe` TB.Cursor 0 0+  describe "cluster movement" $+    it "steps left symmetrically with right across combining marks, ZWJ chains, flags, and long lines" $+      forM_+        [ "abc"+        , "cafe\x0301x"+        , "a\x200Db\x200Dc"+        , "a\x200D\n"+        , "\x1F1FA\x1F1F8\x1F1EC\x1F1E7"+        , T.replicate 200 "a" <> "e\x0301\x0302"+        ]+        $ \t -> do+          let walkRight b =+                let b' = TB.moveRight b+                 in if TB.getCursor b' == TB.getCursor b then [TB.getCursor b] else TB.getCursor b : walkRight b'+              walkLeft b =+                let b' = TB.moveLeft b+                 in if TB.getCursor b' == TB.getCursor b then [TB.getCursor b] else TB.getCursor b : walkLeft b'+              start0 = TB.fromText t+              fwd = walkRight start0+              atEndBuf = TB.withCursor (last fwd) start0+              bwd = reverse (walkLeft atEndBuf)+          bwd `shouldBe` fwd -  describe "text word selection" $ do-    it "groups Unicode words, whitespace and punctuation by character index" $ do-      let-        text = "αβ_猫  🙂!?"-      map (textWordBounds text) [0 .. 8]-        `shouldBe` replicate 4 (0, 4) ++ replicate 2 (4, 6) ++ replicate 3 (6, 9)-    it "clamps clicks outside the text and handles empty text" $ do-      textWordBounds "" 10 `shouldBe` (0, 0)-      textWordBounds "one two" (-10) `shouldBe` (0, 3)-      textWordBounds "one two" 100 `shouldBe` (4, 7)-      textWordBounds (T.replicate 10000 "猫") 5000 `shouldBe` (0, 10000)+  describe "snapToCluster" $+    it "lands on the start of the character it falls inside" $+      forM_+        [ ("cafe\x0301x", 4, 3)+        , ("cafe\x0301x", 5, 5)+        , ("a\x1F468\x200D\x1F469\&b", 3, 1)+        , ("\x1F1FA\x1F1F8\x1F1EC\x1F1E7", 1, 0)+        , ("\x1F1FA\x1F1F8\x1F1EC\x1F1E7", 3, 2)+        , ("abc", 2, 2)+        , ("abc", 9, 3)+        ]+        $ \(t, col, want) ->+          (t, col, TB.cursorCol (TB.snapToCluster (TB.fromText t) (TB.Cursor 0 col))) `shouldBe` (t, col, want)++-- | Pieces of text the random edits insert: ASCII, spaces, combining marks,+-- ZWJ emoji, a skin-toned emoji, flags, CJK and line breaks.+pieces :: [T.Text]+pieces =+  ["a", "xyz", " ", "  ", "e\x0301", "\x0915\x093F", "\x1F469\x200D\x1F4BB", "\x1F44D\x1F3FD", "\x1F1FA\x1F1F8", "\x732B\x72AC", "\n", "a\nb", "foo bar", "\n\n"]++-- | A text built from 'pieces'.+genText :: Gen T.Text+genText = T.concat <$> listOf (elements pieces)++-- | A position that may lie past the document's end, which commands clamp.+genCursor :: Gen TB.Cursor+genCursor = TB.Cursor <$> choose (-1, 6) <*> choose (-1, 12)++-- | One edit a user or an app makes on a multiline field.+newtype Step = Step TE.TextCommand+  deriving (Show)++instance Arbitrary Step where+  arbitrary =+    Step+      <$> frequency+        [ (6, TE.InsertText <$> elements pieces)+        , (4, TE.Delete <$> elements [TE.CharLeft, TE.CharRight, TE.WordLeft, TE.WordRight, TE.LineStart, TE.LineEnd])+        , (3, TE.Move <$> elements [minBound .. maxBound] <*> arbitrary)+        , (2, TE.Select <$> genCursor <*> genCursor)+        , (1, pure TE.SelectAll)+        , (1, TE.Replace <$> genCursor <*> genCursor <*> elements pieces)+        , (2, pure TE.Undo)+        , (1, pure TE.Redo)+        ]++-- | A starting document and the edits made on it.+data Session = Session T.Text [Step]+  deriving (Show)++instance Arbitrary Session where+  arbitrary = Session <$> genText <*> (choose (0, 60) >>= (`vectorOf` arbitrary))+  shrink (Session t steps) = [Session t s | s <- shrinkList steps]+    where+      shrinkList xs = [take i xs <> drop (i + 1) xs | i <- [0 .. length xs - 1]]++-- | The character offset of a position in a text whose lines are @lns@.+offsetOf :: [T.Text] -> TB.Cursor -> Int+offsetOf lns (TB.Cursor r c) = sum [T.length l + 1 | l <- take r lns] + c++-- | Whether the editor's caret and anchor lie inside its document.+insideDocument :: TE.Editor -> Bool+insideDocument ed =+  let buf = TE.editorBuffer ed+      ok (TB.Cursor r c) = r >= 0 && r < TB.getLineCount buf && c >= 0 && c <= T.length (TB.lineAt r buf)+      (a, cur) = TE.editorSelection ed+   in ok a && ok cur++-- | The editor's text, and its selection as ordered character offsets.+flat :: TE.Editor -> (T.Text, Int, Int)+flat ed =+  let buf = TE.editorBuffer ed+      lns = TB.toLines buf+      (a, c) = TE.editorSelection ed+      (lo, hi) = TB.selectionRange a c+   in (TB.toText buf, offsetOf lns lo, offsetOf lns hi)++-- | The caret's character offset.+caretOffset :: TE.Editor -> Int+caretOffset ed = let buf = TE.editorBuffer ed in offsetOf (TB.toLines buf) (TB.getCursor buf)++runMulti :: TE.TextCommand -> TE.Editor -> TE.Editor+runMulti = TE.runCommand TE.multiLineMode++-- | What one step must do, checked against the editor before and after it:+-- an insert replaces the selection with the text and leaves the caret after+-- it; a delete removes the selection, or else a run of text that ends (to+-- the left) or starts (to the right) at the caret; an undo that a redo+-- follows, or the reverse, gives the text back.+stepModel :: TE.TextCommand -> TE.Editor -> TE.Editor -> Property+stepModel cmd prev next =+  let (old, lo, hi) = flat prev+      new = TB.toText (TE.editorBuffer next)+      caret = caretOffset next+      selected = lo /= hi+      splice a b ins = T.take a old <> ins <> T.drop b old+      leftOf = T.take lo old+   in counterexample (show (cmd, old, lo, hi, new, caret)) $ case cmd of+        TE.InsertText t -> new === splice lo hi t .&&. caret === lo + T.length t+        TE.Delete _+          | selected -> new === splice lo hi "" .&&. caret === lo+        TE.Delete m+          | m `elem` [TE.CharLeft, TE.WordLeft, TE.LineStart] ->+              counterexample "left delete" $+                caret <= lo .&&. new === T.take caret old <> T.drop lo old+          | otherwise ->+              counterexample "right delete" $+                caret === lo .&&. T.isPrefixOf leftOf new .&&. T.isSuffixOf (T.drop lo new) old+        TE.Undo+          | TE.canUndo (TE.editorHistory prev) ->+              TB.toText (TE.editorBuffer (runMulti TE.Redo next)) === old+        TE.Redo+          | TE.canRedo (TE.editorHistory prev) ->+              TB.toText (TE.editorBuffer (runMulti TE.Undo next)) === old+        _ | cmd `elem` [TE.Undo, TE.Redo] -> new === old+        TE.Move _ _ -> new === old+        TE.Select _ _ -> new === old+        TE.SelectAll -> new === old+        _ -> property True++-- | Undo until there is nothing left to undo, and the texts on the way.+undoAll :: TE.Editor -> [T.Text]+undoAll ed+  | TE.canUndo (TE.editorHistory ed) = let ed' = runMulti TE.Undo ed in TB.toText (TE.editorBuffer ed') : undoAll ed'+  | otherwise = []++-- | Random edit sessions against a plain 'T.Text' model, the history, and+-- recorded edits.+editModelSpec :: Spec+editModelSpec = describe "random edits" $ modifyMaxSuccess (max 300) $ do+  prop "match a text model, keep the caret in the document, and undo to the start" $ \(Session t0 steps) ->+    let ed0 = TE.editorFromBuffer (TB.fromText t0)+        trace = scanl (\ed (Step cmd) -> runMulti cmd ed) ed0 steps+        final = last trace+        stepChecks =+          [ counterexample "caret outside the document" (insideDocument ed') .&&. stepModel cmd ed ed'+          | (Step cmd, ed, ed') <- zip3 steps trace (drop 1 trace)+          ]+        seen = map (TB.toText . TE.editorBuffer) trace+        undone = undoAll final+        n = length undone+        start = iterate (runMulti TE.Undo) final !! n+        -- As many redos as undos: steps undone before the session ended+        -- stay on the redo stack past the final text.+        redone = iterate (runMulti TE.Redo) start !! n+     in conjoin stepChecks+          .&&. counterexample "undo reached a text the session never had" (all (`elem` seen) undone)+          .&&. counterexample "undo all" (TB.toText (TE.editorBuffer start) === t0)+          .&&. counterexample "redo what was undone" (TB.toText (TE.editorBuffer redone) === TB.toText (TE.editorBuffer final))+          .&&. counterexample "caret after undo and redo" (insideDocument start .&&. insideDocument redone)++  prop "apply and invert a replace edit between any two positions" $+    \(Session t0 _) -> do+      a <- genCursor+      b <- genCursor+      ins <- oneof [elements pieces, genText]+      let buf = TB.fromText t0+          e = TB.replaceEdit ins a b buf+          applied = TB.applyEdit e buf+          lns = TB.toLines buf+          (lo, hi) = TB.selectionRange (TB.clampCursor buf a) (TB.clampCursor buf b)+          (olo, ohi) = (offsetOf lns lo, offsetOf lns hi)+      pure $+        TB.editRemoved e === T.take (ohi - olo) (T.drop olo t0)+          .&&. TB.toText applied === T.take olo t0 <> ins <> T.drop ohi t0+          .&&. TB.toText (TB.applyEdit (TB.invertEdit e) applied) === t0
test/inspection/Inspection.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE TemplateHaskell #-}  -- | Compile-time optimization invariants for nano-ui's hot-path coding@@ -9,14 +10,65 @@   ( main   , solidQuadProbe   , gradientQuadProbe-  ) where+  , cornerQuadProbe+  , storeWriteProbe+  , storeWriteByHand+  , storeReadProbe+  , storeReadByHand+  , specWriteProbe+  , specWriteByHand+  , specReadProbe+  , specReadByHand+  , channelProbe+  , channelByHand+  , commandReadProbe+  , commandWriteProbe+  , canvasProbe+  , canvasByHand+  , focusGetProbe+  , focusGetByHand+  , focusSetProbe+  , focusSetByHand+  , focusDotProbe+  , luminanceProbe+  , inputInteractedProbe+  , everyStyleProbe+  )+where +import Data.IntMap.Strict qualified as IM+import Data.Text (Text)+import Data.Functor.Identity (Identity (..))+import Data.Primitive.SmallArray (SmallArray) import Data.Word (Word32, Word8)+import Data.Vector.Unboxed qualified as U+import Data.Vector.Unboxed.Mutable qualified as UM+import GHC.Exts (RealWorld)+import GHC.Float (castFloatToWord32, castWord32ToFloat) import Foreign.Ptr (Ptr)+import GHC.Generics (Generic)  import Test.Inspection -import NanoUI.SIMD qualified as SIMD+import NanoUI.Internal.SIMD qualified as SIMD+import NanoUI.Internal.Store+import NanoUI.Internal.Var.Types (Var, fieldLens)+import NanoUI+  ( Animatable (..)+  , Color+  , CustomDrawContext+  , Rect (..)+  , Style+  , Theme+  , V2 (..)+  , colorLuminance+  , drawCircle+  , drawRect+  , everyStyle+  )+import NanoUI.Widgets.Custom (runCanvasFor)+import NanoUI.Backend (Input, fmSnapScale, inputInteracted)+import NanoUI.Testing (DrawCmd (..), DrawOp, Layer (..))  main :: IO () main = putStrLn "inspection invariants hold"@@ -34,6 +86,7 @@     (x, 0, 0, 1) (0, x, 0, 1) (0, 0, x, 1) (x, x, x, 1) base  inspect $ 'solidQuadProbe `doesNotUse` 'SIMD.pokeQuadSIMD+inspect $ 'solidQuadProbe `doesNotUse` 'SIMD.pokeQuadCornersSIMD inspect $ 'solidQuadProbe `doesNotUse` 'SIMD.pokeVertexSIMD inspect $ hasNoTypeClasses 'solidQuadProbe inspect $ 'solidQuadProbe `hasNoType` ''[]@@ -46,3 +99,174 @@ inspect $ 'gradientQuadProbe `doesNotUse` 'SIMD.pokeVertexSIMD inspect $ hasNoTypeClasses 'gradientQuadProbe inspect $ 'gradientQuadProbe `hasNoType` ''(,,,)++-- The rotated image quad writer, which takes each corner explicitly.+cornerQuadProbe :: Ptr Word8 -> Ptr Word8 -> Int -> Float -> Word32 -> IO ()+cornerQuadProbe vp ip offset x base =+  SIMD.pokeQuadCornersSIMD vp offset ip offset x 0 x x 0 x 0 0 0 0 1 1 x x x 1 base++inspect $ 'cornerQuadProbe `doesNotUse` 'SIMD.pokeQuadCornersSIMD+inspect $ 'cornerQuadProbe `doesNotUse` 'SIMD.pokeVertexSIMD+inspect $ hasNoTypeClasses 'cornerQuadProbe+inspect $ 'cornerQuadProbe `hasNoType` ''(,)++-- The store's slot functions take the map they work on as a 'Field'. They+-- must compile to the record code they stand for, with no 'Field' left, so+-- that a composition of writes still builds the store once.+storeWriteProbe :: Int -> Int -> Text -> WidgetStore -> WidgetStore+storeWriteProbe k cursor txt =+  insertSlot fieldText k txt+    . insertSlot fieldInt (slotKey SlotCursor k) cursor+    . deleteSlot fieldInt (slotKey SlotAnchor k)++storeWriteByHand :: Int -> Int -> Text -> WidgetStore -> WidgetStore+storeWriteByHand k cursor txt st0 =+  let st1 = st0 {storeInt = IM.delete (slotKey SlotAnchor k) (storeInt st0)}+      st2 = st1 {storeInt = IM.insert (slotKey SlotCursor k) cursor (storeInt st1)}+   in st2 {storeText = IM.insert k txt (storeText st2)}++storeReadProbe :: Int -> WidgetStore -> (Int, Bool, Maybe Float)+storeReadProbe k st =+  (findSlot fieldInt 7 (slotKey SlotCursor k) st, flagSlot k st, lookupSlot fieldFloat k st)++storeReadByHand :: Int -> WidgetStore -> (Int, Bool, Maybe Float)+storeReadByHand k st =+  ( IM.findWithDefault 7 (slotKey SlotCursor k) (storeInt st)+  , IM.findWithDefault 0 k (storeInt st) /= 0+  , IM.lookup k (storeFloat st)+  )++inspect $ 'storeWriteProbe === 'storeWriteByHand+inspect $ 'storeReadProbe === 'storeReadByHand+inspect $ 'storeWriteProbe `hasNoType` ''Field+inspect $ 'storeReadProbe `hasNoType` ''Field++-- A 'SlotSpec' compiles to the slot code it names, plus its encoding: float+-- bits in a quiet slot, and an int read as a flag.+specWriteProbe :: Int -> Int -> Float -> WidgetStore -> WidgetStore+specWriteProbe k cursor x =+  insertSpec (slotSpec SlotCursor fieldInt) k cursor+    . insertSpec (floatBitsSpec (slotSpec SlotScrollCross fieldQuiet)) k x+    . deleteSpec (slotSpec SlotAnchor fieldInt) k++specWriteByHand :: Int -> Int -> Float -> WidgetStore -> WidgetStore+specWriteByHand k cursor x =+  insertSlot fieldInt (slotKey SlotCursor k) cursor+    . insertSlot fieldQuiet (slotKey SlotScrollCross k) (fromIntegral (castFloatToWord32 x))+    . deleteSlot fieldInt (slotKey SlotAnchor k)++specReadProbe :: Int -> WidgetStore -> (Int, Maybe Float, Bool)+specReadProbe k st =+  ( findSpec (slotSpec SlotCursor fieldInt) 7 k st+  , lookupSpec (floatBitsSpec (slotSpec SlotScrollCross fieldQuiet)) k st+  , findSpec (encodedSpec intBool boolInt (slotSpec SlotMenuOpen fieldInt)) False k st+  )++specReadByHand :: Int -> WidgetStore -> (Int, Maybe Float, Bool)+specReadByHand k st =+  ( findSlot fieldInt 7 (slotKey SlotCursor k) st+  , castWord32ToFloat . fromIntegral <$> lookupSlot fieldQuiet (slotKey SlotScrollCross k) st+  , intBool (findSlot fieldInt 0 (slotKey SlotMenuOpen k) st)+  )++inspect $ 'specWriteProbe === 'specWriteByHand+inspect $ 'specReadProbe === 'specReadByHand+inspect $ 'specWriteProbe `hasNoType` ''SlotSpec+inspect $ 'specReadProbe `hasNoType` ''SlotSpec++-- Direct channel traversal must specialize to scalar arithmetic, including+-- when the channel values and the transform are supplied at runtime.+channelProbe :: Float -> V2 -> V2+channelProbe delta = runIdentity . traverseChannels (\_ x -> Identity (x + delta))++channelByHand :: Float -> V2 -> V2+channelByHand delta (V2 x y) = V2 (x + delta) (y + delta)++inspect $ 'channelProbe === 'channelByHand+inspect $ hasNoTypeClasses 'channelProbe+inspect $ 'channelProbe `hasNoType` ''[]++commandReadProbe :: U.Vector DrawCmd -> Int -> Float+commandReadProbe cmds i =+  let+    cmd = U.unsafeIndex cmds i+   in+    cmdClipX cmd + cmdClipY cmd + cmdClipW cmd + cmdClipH cmd++commandWriteProbe ::+  UM.MVector RealWorld DrawCmd -> Int -> Float -> Word32 -> IO ()+commandWriteProbe cmds i x count = UM.unsafeWrite cmds i (DrawCmd x x x x i count count LayerContent 0)++inspect $ hasNoTypeClasses 'commandReadProbe+inspect $ hasNoTypeClasses 'commandWriteProbe+inspect $ 'commandReadProbe `doesNotUse` 'U.fromURepr+inspect $ 'commandWriteProbe `doesNotUse` 'U.toURepr++-- A block with no curves and no draw-context use must build neither the+-- curve tolerance nor the context, and must not allocate an intermediate list.+canvasProbe :: CustomDrawContext -> Float -> Color -> SmallArray DrawOp+canvasProbe cdc x color = runCanvasFor cdc $ do+  drawRect (Rect x 2 3 4) color+  drawCircle (V2 5 x) 6 color++canvasByHand :: CustomDrawContext -> Float -> Color -> SmallArray DrawOp+canvasByHand _ x color = runCanvasFor (error "unused cdc") $ do+  drawRect (Rect x 2 3 4) color+  drawCircle (V2 5 x) 6 color++inspect $ 'canvasProbe === 'canvasByHand+inspect $ 'canvasProbe `doesNotUse` 'fmSnapScale+inspect $ 'canvasProbe `hasNoType` ''[]++-- Var field focus: the Generic path search must leave no generic+-- representation or class dictionary behind, so reading and replacing a+-- nested field compile to a selector and a record update.+data FocusInner = FocusInner {innerItems :: ![Int], innerNext :: !Int}+  deriving (Eq, Generic)++data FocusOuter = FocusOuter {outerInner :: !FocusInner, outerTitle :: !Text, outerCount :: !Int}+  deriving (Eq, Generic)++focusGetProbe :: FocusOuter -> [Int]+focusGetProbe = fst (fieldLens @"innerItems") . fst (fieldLens @"outerInner")++focusGetByHand :: FocusOuter -> [Int]+focusGetByHand o = innerItems (outerInner o)++focusSetProbe :: [Int] -> FocusOuter -> FocusOuter+focusSetProbe xs o = snd (fieldLens @"outerInner") (snd (fieldLens @"innerItems") xs (outerInner o)) o++focusSetByHand :: [Int] -> FocusOuter -> FocusOuter+focusSetByHand xs o = o {outerInner = (outerInner o) {innerItems = xs}}++-- The dot itself, on a Var.+focusDotProbe :: Var FocusOuter -> Var [Int]+focusDotProbe v = v.outerInner.innerItems++inspect $ 'focusGetProbe === 'focusGetByHand+inspect $ 'focusSetProbe === 'focusSetByHand+inspect $ hasNoGenerics 'focusGetProbe+inspect $ hasNoGenerics 'focusSetProbe+inspect $ hasNoGenerics 'focusDotProbe+inspect $ hasNoTypeClasses 'focusDotProbe++-- colorLuminance must use the precomputed sRGB LUT with no floating-point pow.+luminanceProbe :: Color -> Double+luminanceProbe = colorLuminance++inspect $ 'luminanceProbe `doesNotUse` '(**)+inspect $ hasNoTypeClasses 'luminanceProbe++-- inputInteracted must compare fields directly without building intermediate lists.+inputInteractedProbe :: Input -> Input -> Bool+inputInteractedProbe = inputInteracted++inspect $ 'inputInteractedProbe `hasNoType` ''[]+inspect $ hasNoTypeClasses 'inputInteractedProbe++-- everyStyle must map Theme fields directly without intermediate function lists.+everyStyleProbe :: (Style -> Style) -> Theme -> Theme+everyStyleProbe = everyStyle++inspect $ 'everyStyleProbe `hasNoType` ''[]+inspect $ hasNoTypeClasses 'everyStyleProbe
+ test/integration/BackendApi.hs view
@@ -0,0 +1,41 @@+{-# OPTIONS_GHC -O0 #-}+-- A minimal backend must compile using only the supported public surface.+module BackendApi (backendApiCheck) where++import Control.Monad (unless)+import NanoUI (label)+import NanoUI.Backend+import NanoUI.Runner++backendApiCheck :: IO ()+backendApiCheck = do+  ctx <- newPixelContext+  (_, drawing, _) <- runFrame ctx emptyInput (label "backend")+  unless (drawCmdCount drawing > 0) (fail "label drew no commands")+  _ <- takeDamage ctx+  _ <- takeDamagePieces ctx+  _ <- collectRasterSpans ctx emptyInput+  debug <- newDebugSampler+  let driver = SessionDriver+        { sdPollEvents = pure [()]+        , sdWaitEvents = \_ -> pure [()]+        , sdPacedWait = Nothing+        , sdApplyEvent = const+        , sdIsButtonEdge = const False+        , sdIsSessionQuit = const True+        , sdSyncDisplay = \c i -> pure (c, i)+        , sdDebug = debug+        , sdContinuous = False+        , sdVsyncOff = False+        , sdPacingMs = 16+        , sdPresentPaces = pure False+        , sdAlignSec = 0+        , sdShouldDraw = \c before now anim refresh -> shouldRedrawFrame c before now anim False refresh+        , sdDraw = \c i _ -> do+            (_, _, dirty) <- runFrame c i (label "backend")+            pure dirty+        , sdOnCursor = \_ _ -> pure ()+        , sdShouldQuit = const False+        , sdWindows = Nothing+        }+  runSessionLoop driver ctx emptyInput
− test/integration/Cases.hs
@@ -1,857 +0,0 @@-module Cases-  ( runAspectLayoutTest-  , runCheckboxInitialTest-  , runDrawingTest-  , runEmbedStateTest-  , runEmptyFrameTest-  , runFitMutedWidthTest-  , runGrowSplitTest-  , runHostSlotTest-  , runHoverDamageTest-  , runIdKeyedListTest-  , runKvMultilineHeightTest-  , runImageTest-  , runImageSwapDamageTest-  , runLabelAlignEndTest-  , runLayoutReuseTest-  , runDeepNestingTest-  , runPanelPaintsTest-  , runPaneGridMixedDragTest-  , runPaneGridClippedControlTest-  , runPercentGapShrinkTest-  , runPointerCursorTest-  , runReduceClickTest-  , runReduceMessagesTest-  , runResponsiveWrapTest-  , runSliderFillWidthTest-  , runWidgetNoStringEmitTest-  , runSearchFieldClearTest-  , runSearchFieldDebounceTest-  ) where--import Control.Monad (forM_, void, when)-import Control.Concurrent (threadDelay)-import Data.ByteString qualified as BS-import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Map.Strict qualified as M-import Data.Text qualified as T-import Data.Word (Word64)-import Effectful (liftIO)-import Effectful.State.Static.Local (State, evalState, get, modify)-import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Emit qualified as Emit-import NanoUI.Layout.Arena-  ( NodeType (..)-  , arenaArrays-  , foldNodesM-  , getNodeType-  , getNodeValue-  , tagNodeType-  , treeFirstChild-  , treeNextSibling-  , writeTagEnum-  , writeTree-  )-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt, runClickReduce, withInput)-import NanoUI.Testing.Harness-  ( centerOf-  , checkLabelAlignEndInk-  , clickPair-  , held-  , spanXOf-  , spanYOf-  , tabInp-  , vertUv-  , warmup2-  , warmupDraw-  , withInputOff-  )-import NanoUI.Widgets.SplitPane-  ( GridNode (..)-  , PaneDrop (..)-  , dropPreview-  , dropTargetForPane-  , layoutNode-  , topLevelDropTarget-  )--runIdKeyedListTest :: Context -> IORef Int -> IO ()-runIdKeyedListTest ctx failed = do-  let inp = withInput 200 200-      keyedIds :: [String] -> IO ([WidgetId], [FrameMsg], DrawData, Bool)-      keyedIds keys = runFrame ctx inp (column (mapM (\k -> keyed k nextId) keys))-      idFor :: String -> [String] -> [WidgetId] -> Maybe WidgetId-      idFor key keys ids = lookup key (zip keys ids)-  (idsA, _, _, _) <- keyedIds ["a", "b", "c"]-  (idsPrep, _, _, _) <- keyedIds ["x", "a", "b", "c"]-  (idsApp, _, _, _) <- keyedIds ["a", "b", "c", "y"]-  (idsRev, _, _, _) <- keyedIds ["c", "b", "a"]-  case idsA of-    [a, b, c] -> assert failed (a /= b && b /= c && a /= c)-    _ -> assert failed False-  assertEq failed (idFor "a" ["a", "b", "c"] idsA) (idFor "a" ["x", "a", "b", "c"] idsPrep)-  assertEq failed (idFor "b" ["a", "b", "c"] idsA) (idFor "b" ["a", "b", "c", "y"] idsApp)-  assertEq failed (idFor "c" ["a", "b", "c"] idsA) (idFor "c" ["c", "b", "a"] idsRev)--runFitMutedWidthTest :: Context -> IORef Int -> IO ()-runFitMutedWidthTest ctx failed = do-  let inp = withInput 400 100-      ui = columnWith tight (muted "HelloFitMuted")-  _ <- runFrame ctx inp ui-  spans <- collectTextSpans ctx-  case [w | (Rect _ _ w _, t, _, _, _) <- spans, "HelloFitMuted" `T.isInfixOf` t] of-    (w : _) -> assertGt failed w 8-    _ -> assert failed False---- | Phase 5A: text and resize changes must invalidate the cached-layout path.-runLayoutReuseTest :: Context -> IORef Int -> IO ()-runLayoutReuseTest ctx failed = do-  let inp = withInput 400 300-      ui1 =-        columnWith (tight . gap 4 . fillW) $ do-          void (label "alpha")-          void (button "beta")-          void (label "gamma delta epsilon")-  _ <- runFrame ctx inp ui1-  -- Frame 2 takes the cached-layout path (same descriptor).-  _ <- runFrame ctx inp ui1-  s1 <- collectTextSpans ctx-  -- Text change invalidates the cached descriptor.-  let ui2 =-        columnWith (tight . gap 4 . fillW) $ do-          void (label "alpha changed")-          void (button "beta")-          void (label "gamma delta epsilon")-  _ <- runFrame ctx inp ui2-  s2 <- collectTextSpans ctx-  assert failed (s2 /= s1)-  -- Width change must not serve the cached placement for width-dependent-  -- (wrapping) layout.-  let wrapUi =-        columnWith (tight . fillW) $-          label "the quick brown fox jumps over the lazy dog repeatedly"-  _ <- runFrame ctx (withInput 600 200) wrapUi-  sw0 <- collectTextSpans ctx-  _ <- runFrame ctx (withInput 180 200) wrapUi-  sw1 <- collectTextSpans ctx-  assert failed (sw1 /= sw0)---- | Nesting deeper than the initial snapshot-level capacity must still lay--- out correctly (the level array grows on demand).-runDeepNestingTest :: Context -> IORef Int -> IO ()-runDeepNestingTest ctx failed = do-  let nest :: Int -> NanoUI ()-      nest 0 = void (label "deep")-      nest k = column (nest (k - 1))-  _ <- runFrame ctx (withInput 300 300) (nest 320)-  spans <- collectTextSpans ctx-  assert failed (any (\(_, t, _, _, _) -> t == "deep") spans)---- | A responsive row stacks its children below the breakpoint and keeps them--- side by side above it.-runResponsiveWrapTest :: Context -> IORef Int -> IO ()-runResponsiveWrapTest ctx failed = do-  let ui = responsiveRowCol 720 (tight . gap 8 . fillW) $ do-        columnWith (tight . gap 8 . fillW) (card (void (label "LeftTop")) >> card (void (label "LeftBot")))-        card (void (label "Right"))-  _ <- warmup2 ctx (withInput 520 800) ui-  narrow <- collectTextSpans ctx-  case (spanYOf "Right" narrow, spanYOf "LeftBot" narrow) of-    ([ry], [ly]) -> assertGt failed ry (ly + 1)-    _ -> assert failed False-  _ <- warmup2 ctx (withInput 1200 800) ui-  wide <- collectTextSpans ctx-  case (spanXOf "Right" wide, spanXOf "LeftTop" wide) of-    ([rx], [lx]) -> assertGt failed rx (lx + 1)-    _ -> assert failed False--runDrawingTest :: Context -> IORef Int -> IO ()-runDrawingTest ctx failed = do-  let ui =-        drawing (fixedWH 80 40) $ \r ->-          pure-            ( Stroke-                (rectX r)-                (rectY r + rectH r * 0.5)-                (rectX r + rectW r)-                (rectY r + rectH r * 0.5)-                2-                (colorRGBA 255 0 0 255)-            )-      inp = withInput 200 80-  (_, _, draw, _) <- runFrame ctx inp ui-  assert failed (drawIndexCount draw >= 6 && not (drawCmdNull draw))-  (_, _, draw2, _) <- runFrame ctx inp ui-  assert failed (drawIndexCount draw2 >= 6 && not (drawCmdNull draw2))--runPointerCursorTest :: Context -> IORef Int -> IO ()-runPointerCursorTest ctx failed = do-  let inp0 = withInput 200 100-      ui = column $ do-        btn <- button' "Click"-        (cb, _) <- checkbox' "Feature" False-        pure (btn, cb)-      wantAt inp = runFrame ctx inp ui >> pointerCursorWanted ctx inp-  (btn, cb) <- warmup2 ctx inp0 ui-  onButton <- wantAt (inp0 {inputMousePos = centerOf btn})-  assert failed onButton-  offWidgets <- wantAt (inp0 {inputMousePos = V2 (-1) (-1)})-  assert failed (not offWidgets)-  let hoverBox = inp0 {inputMousePos = centerOf cb}-  onBox <- wantAt hoverBox-  assert failed onBox-  pressBox <- wantAt (hoverBox {inputMouseDown = True, inputMousePressed = True, inputMouseReleased = False})-  assert failed pressBox---- A frame whose UI adds no widgets is an empty frame, not a read of a node--- that was never added: presses, wheel input, redraw and cursor queries all--- run on the empty arena. Node 0 starts out as a container that is its own--- child, so any read of it recurses without end. Widgets added on the next--- frame still lay out.-runEmptyFrameTest :: Context -> IORef Int -> IO ()-runEmptyFrameTest ctx failed = do-  arrays <- arenaArrays (ctxNodeArena ctx)-  writeTagEnum arrays 0 tagNodeType NodeContainer-  writeTree arrays 0 treeFirstChild 0-  writeTree arrays 0 treeNextSibling (-1)-  let inp0 = (withInput 320 200) {inputMousePos = V2 40 40}-      press = inp0 {inputMouseDown = True, inputMousePressed = True, inputScroll = V2 0 1}-      ui = row $ do-        wid <- currentId-        image (fixedWH 40 24) (ImageId 0)-        pure wid-  _ <- runFrame ctx inp0 (pure ())-  _ <- runFrame ctx press (pure ())-  _ <- needsRedraw ctx inp0 (inp0 {inputMousePos = V2 60 60})-  _ <- uiCursorKind ctx inp0-  _ <- runFrame ctx inp0 ui-  (wid, _, _, _) <- runFrame ctx inp0 ui-  mRect <- getPrevRect ctx wid-  assert failed (maybe False (\(Rect _ _ w h) -> abs (w - 40) <= 0.5 && abs (h - 24) <= 0.5) mRect)---- Switching an image to another id repaints the image, and only the image:--- frames swapped inside a page must neither leave a stale frame on screen nor--- repaint the whole page.-runImageSwapDamageTest :: Context -> IORef Int -> IO ()-runImageSwapDamageTest ctx failed = do-  let px a = BS.pack (concat (replicate 16 [a, 0, 0, 255]))-  ok1 <- registerImage ctx (ImageId 1) 4 4 (px 60)-  ok2 <- registerImage ctx (ImageId 2) 4 4 (px 120)-  assert failed (ok1 && ok2)-  frameRef <- newIORef (ImageId 1)-  let inp0 = withInputOff 320 200-      ui = fmap snd $-        scrollArea (padAll 10 . grow) $-          column $ do-            label "frames"-            wid <- currentId-            image (fixedWH 40 24) =<< uiIO (readIORef frameRef)-            pure wid-  wid <- warmup2 ctx inp0 ui-  _ <- takeDamage ctx-  writeIORef frameRef (ImageId 2)-  _ <- runFrame ctx inp0 ui-  dmg <- takeDamage ctx-  mRect <- getPrevRect ctx wid-  case (dmg, mRect) of-    (DamageClip (Rect dx dy dw dh), Just (Rect ix iy iw ih)) -> do-      assert failed (dx <= ix && dy <= iy && dx + dw >= ix + iw && dy + dh >= iy + ih)-      assert failed (dw * dh < 320 * 200 / 4)-    _ -> assert failed False--runImageTest :: Context -> IORef Int -> IO ()-runImageTest ctx failed = do-  let px a b c = BS.pack (concat (replicate 16 [a, b, c, 255]))-  ok1 <- registerImage ctx (ImageId 1) 4 4 (px 255 0 0)-  ok7 <- registerImage ctx (ImageId 7) 4 4 (px 0 0 255)-  assert failed (ok1 && ok7)-  let inp0 = withInput 320 200-      imgLayout = fixedWH 40 24-      ui = row $ do-        image imgLayout (ImageId 1)-        wid <- currentId-        image imgLayout (ImageId 7)-        pure wid-  (wid, drawData) <- warmupDraw ctx inp0 ui-  mRect <- getPrevRect ctx wid-  case mRect of-    Just (Rect _ _ w h) -> assert failed (abs (w - 40) <= 0.5 && abs (h - 24) <= 0.5)-    Nothing -> assert failed False-  let texCmds = filter (\c -> cmdTextureId c == atlasTextureId) (drawCmdElems drawData)-  assertEq failed (length texCmds) 1-  assert failed (any (\c -> cmdIndexCount c == 12) texCmds)-  (u0, _) <- vertUv drawData 0-  (u4, _) <- vertUv drawData 4-  assert failed (abs (u0 - u4) >= 1e-6)-  -- Fresh ids start above the registered ones and never repeat.-  ((fresh1, fresh2), _, _, _) <- runFrame ctx inp0 ((,) <$> freshImageId <*> freshImageId)-  assertEq failed (map unImageId [fresh1, fresh2]) [8, 9]-  let missing = image imgLayout (ImageId 0)-  _ <- runFrame ctx inp0 missing-  (_, _, missingData, _) <- runFrame ctx inp0 missing-  assert failed (not (any (\c -> cmdTextureId c == atlasTextureId) (drawCmdElems missingData)))---- | Hover enter and press repaint only the button, and pointer motion inside--- an already-hovered button does not request a redraw.-runHoverDamageTest :: Context -> IORef Int -> IO ()-runHoverDamageTest ctx failed = do-  let ui = column (button' "OK")-      inp0 = withInputOff 240 80-      assertSmall dmg = case dmg of-        DamageFull -> assert failed False-        DamageClip (Rect _ _ w h) -> assert failed (w * h < 240 * 80 * 0.5)-  _ <- runFrame ctx inp0 ui-  d0 <- takeDamage ctx-  assertEq failed d0 DamageFull-  (resp, _, _, _) <- runFrame ctx inp0 ui-  let V2 cx cy = centerOf resp-      inp1 = inp0 {inputMousePos = V2 cx cy}-      inp2 = inp0 {inputMousePos = V2 (cx + 1) cy}-  needEnter <- needsRedraw ctx inp0 inp1-  assert failed needEnter-  _ <- runFrame ctx inp1 ui-  assertSmall =<< takeDamage ctx-  let drain = inp1 {inputDeltaTime = 1}-  _ <- runFrame ctx drain ui-  needStay <- needsRedraw ctx drain inp2-  assert failed (not needStay)-  let inpClick = inp1 {inputMouseDown = True, inputMousePressed = True}-  needClick <- needsRedraw ctx drain inpClick-  assert failed needClick-  _ <- runFrame ctx inpClick ui-  assertSmall =<< takeDamage ctx----- | An unclicked checkbox must keep rendering its initial value; the frame's--- post-UI value sync must not reset it to unchecked when no state is stored.-runCheckboxInitialTest :: Context -> IORef Int -> IO ()-runCheckboxInitialTest ctx failed = do-  checkedRef <- newIORef True-  let inp0 = withInput 200 100-      ui = column (held checkedRef (checkbox' "Opt"))-  (resp, _) <- warmup2 ctx inp0 ui-  assertCheckboxNodeValue failed ctx 1-  let Rect rx ry _ _ = respRect resp-      (press, release) = clickPair inp0 (V2 (rx + 1) (ry + 0.5))-  _ <- runFrame ctx press ui-  ((_, checked), _, _, _) <- runFrame ctx release ui-  assert failed (not checked)-  assertCheckboxNodeValue failed ctx 0-  -- The toggled value persists on an idle frame.-  ((_, idle), _, _, _) <- runFrame ctx inp0 ui-  assert failed (not idle)-  _ <- runFrame ctx press ui-  ((_, checked2), _, _, _) <- runFrame ctx release ui-  assert failed checked2-  assertCheckboxNodeValue failed ctx 1--assertCheckboxNodeValue :: IORef Int -> Context -> Float -> IO ()-assertCheckboxNodeValue failed ctx expected = do-  let na = ctxNodeArena ctx-  vals <- foldNodesM na (\acc i -> do-    nt <- getNodeType na i-    if nt == NodeCheckbox then (: acc) <$> getNodeValue na i else pure acc) []-  case vals of-    [v] -> assertEq failed v expected-    vs -> assert failed (vs == [expected])--runSliderFillWidthTest :: Context -> IORef Int -> IO ()-runSliderFillWidthTest ctx failed = do-  let inp0 = withInput 400 120-      ui = columnWith fillW (slider' 0 100 0)-  (resp, _) <- warmup2 ctx inp0 ui-  let Rect rx ry rw rh = respRect resp-  assertGt failed rw 300-  let track = sliderTrackBounds rx ry rw rh-      endDrag = V2 (rectX track + rectW track - 2) (rectY track + rectH track / 2)-  ((_, val), _, _, _) <- runFrame ctx (inp0 {inputMousePos = endDrag, inputMouseDown = True, inputMousePressed = True}) ui-  assertGt failed val 90---- | Percent children size against the row width, and flex like CSS: two 50%--- columns plus a gap must give back the overflow so the pair lands exactly on--- the row width (equal halves, no spill past the row's right edge).-runPercentGapShrinkTest :: Context -> IORef Int -> IO ()-runPercentGapShrinkTest ctx failed = do-  let quarters = rowWith (fixedW 200 . tight . gap 0) $ do-        a <- labelWith' (percent 25 . tight) "A"-        b <- labelWith' (percent 75 . tight) "B"-        pure (a, b)-  (qa, qb) <- warmup2 ctx (withInput 200 80) quarters-  assert failed (abs (rectW (respRect qa) - 50) <= 1 && abs (rectW (respRect qb) - 150) <= 1)-  let inp = withInput 300 80-      ui = rowWith (fixedW 206 . tight . gap 6) $ do-        a <- labelWith' (percent 50 . tight) "A"-        b <- labelWith' (percent 50 . tight) "B"-        pure (a, b)-  (a, b) <- warmup2 ctx inp ui-  let Rect xa _ wa _ = respRect a-      Rect xb _ wb _ = respRect b-  assert failed (abs (wa - 100) <= 0.5 && abs (wb - 100) <= 0.5)-  assert failed (abs (xb - (xa + wa + 6)) <= 0.5)---- | Grow children split the free space by factor with a min-content floor--- (fixed-width rows, 12px per char in this context):------ * equal split: two fillW labels with unequal text come out equal when both---   fit their share;--- * content floor: a child whose content needs more than its share takes---   exactly its content width and the sibling re-shares what is left;--- * lock cascade: locking the largest child shrinks the share pool, which---   must lock the middle child on a later sweep (one sweep would give it 55);--- * the vertical axis splits the same way. Its spacers keep a non-zero width---   because prev-rect tracking skips zero-area rects.-runGrowSplitTest :: Context -> IORef Int -> IO ()-runGrowSplitTest ctx failed = do-  let growLabel l txt = respId <$> labelWith' (fillW . l . tight) txt-      growSpacer = currentId <* spacer (Fixed 10) (Grow 1)-      cases :: [(Input, Rect -> Float, NanoUI [WidgetId], [Float])]-      cases =-        [ ( withInput 210 40-          , rectW-          , rowWith (fixedW 210 . tight . gap 0) $-              sequence [growLabel id "A", growLabel id "AAAAA"]-          , [105, 105]-          )-        , ( withInput 200 40-          , rectW-          , rowWith (fixedW 200 . tight . gap 0) $-              sequence [growLabel id "A", growLabel id (T.replicate 15 "A")]-          , [20, 180]-          )-        , ( withInput 240 40-          , rectW-          , rowWith (fixedW 240 . tight . gap 0) $-              sequence [growLabel (minW 12) "A", growLabel (minW 60) "A", growLabel (minW 130) "A"]-          , [50, 60, 130]-          )-        , ( withInput 60 200-          , rectH-          , columnWith (fixedH 200 . tight . gap 0) $-              sequence [growSpacer, growSpacer]-          , [100, 100]-          )-        ]-  forM_ cases $ \(inp, size, ui, want) -> do-    ids <- warmup2 ctx inp ui-    got <- mapM (fmap (maybe 0 size) . getPrevRect ctx) ids-    assertEq failed (length got) (length want)-    forM_ (zip got want) $ \(g, w) -> assert failed (abs (g - w) <= 0.5)--runLabelAlignEndTest :: Context -> IORef Int -> IO ()-runLabelAlignEndTest ctx failed = do-  let-    fm = ctxFontMetrics ctx-    tw = fmAdvance fm ' ' * 2-    boxW = tw + 4-    inp = emptyInput {inputWindowSize = Size (boxW + 8) 8}-    ui =-      rowWith (fixedW boxW . tight . gap 0) $-        labelWith' (fillW . alignEnd . tight) "ab"-  _ <- runFrame ctx inp ui-  (lab, _, _, _) <- runFrame ctx inp ui-  spans <- collectTextSpans ctx-  let-    Rect bx _ bw _ = respRect lab-    hits = [r | (r, txt, _, _, _) <- spans, T.isInfixOf (T.pack "ab") txt]-  case hits of-    [] -> assert failed False-    Rect x _ w _ : _ -> do-      assert failed (abs ((x + w) - (bx + bw)) <= 0.6)-      assert failed (abs (w - tw) <= 0.6)-  checkLabelAlignEndInk failed--runAspectLayoutTest :: Context -> IORef Int -> IO ()-runAspectLayoutTest ctx failed = do-  let inp = withInput 320 240-      ui = columnWith (fixedW 160 . tight) (labelWith' (fixedAspectW 160 2 . tight) "X")-  resp <- warmup2 ctx inp ui-  let Rect _ _ w h = respRect resp-  assert failed (abs (w - 160) <= 1 && abs (h - 80) <= 1)--runHostSlotTest :: Context -> IORef Int -> IO ()-runHostSlotTest ctx failed = do-  let inp = withInput 80 80-      hostUiString = do-        _ <- column (pure ())-        askHost @String-      hostUiInt = do-        _ <- column (pure ())-        askHost @Int-  (miss, _, _, _) <- runFrame ctx inp hostUiString-  setHost ctx ("ok" :: String)-  setHost ctx (1 :: Int)-  (hitS, _, _, _) <- runFrame ctx inp hostUiString-  (hitI, _, _, _) <- runFrame ctx inp hostUiInt-  assert failed (miss == Nothing && hitS == Just "ok" && hitI == Just 1)-  _ <- compactHost ctx ([0 .. 9999] :: [Int])-  let compactUi = do-        _ <- column (pure ())-        askCompact @[Int]-  (got, _, _, _) <- runFrame ctx inp compactUi-  case got of-    Just xs | length xs == 10000 && last xs == 9999 -> pure ()-    _ -> assert failed False--runEmbedStateTest :: Context -> IORef Int -> IO ()-runEmbedStateTest ctx failed = do-  let ui :: Eff '[Ui, State Int, IOE] Int-      ui = do-        _ <- column (pure ())-        modify (+ (1 :: Int))-        modify (+ (1 :: Int))-        get-  (n, _, _, _) <- runFrameEff (runEff . evalState (0 :: Int)) ctx (withInput 80 80) ui-  assertEq failed n 2--data CounterMsg = Inc | Dec-  deriving (Eq, Show)--data Counter = Counter {counterN :: Int}-  deriving (Eq, Show)--updateCounter :: CounterMsg -> Counter -> Counter-updateCounter Inc m = m {counterN = counterN m + 1}-updateCounter Dec m = m {counterN = counterN m - 1}--runReduceMessagesTest :: Context -> IORef Int -> IO ()-runReduceMessagesTest ctx failed = do-  let inp = withInput 80 80-      model0 = Counter 0-      view _ =-        column $-          Emit.emit Inc >> Emit.emit Dec >> Emit.emit Inc >> Emit.emit ("noise" :: String)-  ((), model1, msgs, _, dirty) <- runFrameReduce updateCounter ctx inp model0 view-  assert failed (msgs == [Inc, Dec, Inc] && model1 == Counter 1 && dirty)-  -- Messages that cancel out leave the model unchanged and not dirty.-  let identity _ = column (Emit.emit Inc >> Emit.emit Dec)-  ((), model2, msgs2, _, dirty2) <- runFrameReduce updateCounter ctx inp model0 identity-  assert failed (msgs2 == [Inc, Dec] && model2 == Counter 0 && not dirty2)--runReduceClickTest :: Context -> IORef Int -> IO ()-runReduceClickTest ctx failed = do-  let inp0 = withInput 240 120-      view m = do-        resp <- button' "Go"-        when (respClicked resp) (Emit.emit Inc)-        label (T.pack (show (counterN m)))-        pure resp-  _ <- runFrameReduce updateCounter ctx inp0 (Counter 0) view-  (resp, model0, _, _, _) <- runFrameReduce updateCounter ctx inp0 (Counter 0) view-  assertEq failed model0 (Counter 0)-  (modelR, msgs, dirty) <- runClickReduce updateCounter ctx inp0 (Counter 0) view (centerOf resp)-  assert failed (msgs == [Inc] && modelR == Counter 1 && dirty)-  (_, model1, _, _, _) <- runFrameReduce updateCounter ctx inp0 modelR view-  assertEq failed model1 (Counter 1)--runWidgetNoStringEmitTest :: Context -> IORef Int -> IO ()-runWidgetNoStringEmitTest ctx failed = do-  let inp0 = withInput 240 120-  (resp, _, _, _) <- runFrame ctx inp0 (button' "Go")-  let (press, release) = clickPair inp0 (centerOf resp)-  _ <- runFrame ctx press (button "Go")-  (clicked, msgs, _, _) <- runFrame ctx release (button "Go")-  assert failed clicked-  assert failed (null msgs)--runPanelPaintsTest :: Context -> IORef Int -> IO ()-runPanelPaintsTest ctx failed = do-  let inp = withInput 200 200-      fat = padAll 16 . fillW-  (_, _, colDraw, _) <- runFrame ctx inp (columnWith fat (label "x"))-  (_, _, panDraw, _) <- runFrame ctx inp (panelWith fat (label "x"))-  assertGt failed (drawVertexCount panDraw) (drawVertexCount colDraw)---- | Drag-drop previews must come from simulating the post-drop layout, not--- from halving the target's pre-drop rect: in a grid mixing 'AxisV' and--- 'AxisH' splits, dropping first removes the dragged pane, which collapses--- its parent split and re-flows the sibling subtrees, so the naive highlight--- lands at the wrong position and size.-runPaneGridMixedDragTest :: Context -> IORef Int -> IO ()-runPaneGridMixedDragTest ctx failed = do-  -- Model level: vertical root split with a horizontal split inside the right-  -- branch: pane 1 left, panes 2 (top right) and 3 (bottom right).-  let minSize = 40-      gutter = 4-      base = Rect 0 0 600 400-      tree0 = Split 100 AxisV 0.5 (Pane 1) (Split 101 AxisH 0.5 (Pane 2) (Pane 3))-      regions0 = fst (layoutNode minSize gutter tree0 base)-      r2 = regions0 M.! 2-      r3 = regions0 M.! 3-      preview dt = dropPreview minSize gutter tree0 1 base dt-  assertEq failed regions0 $-    M.fromList-      [ (1, Rect 0 0 298 400)-      , (2, Rect 302 0 298 198)-      , (3, Rect 302 202 298 198)-      ]-  -- Cross-axis edge drop on the bottom-right pane: removing pane 1 collapses-  -- the root split, so the right branch re-flows to the whole grid and pane 1-  -- lands in its bottom-right corner, not in a half of the target's old rect-  -- (which would be Rect 302 301 298 99).-  let dtA = dropTargetForPane r3 (V2 (rectX r3 + rectW r3 / 2) (rectY r3 + rectH r3 * 0.9)) 3-  assertEq failed dtA (DropSplit 3 AxisH False)-  assertEq failed (preview dtA) (Just (Rect 0 303 600 97, DropSplit 3 AxisH False))-  -- Edge drop on the top-right pane.-  let dtB = dropTargetForPane r2 (V2 (rectX r2 + rectW r2 * 0.9) (rectY r2 + rectH r2 / 2)) 2-  assertEq failed dtB (DropSplit 2 AxisV False)-  assertEq failed (preview dtB) (Just (Rect 302 0 298 198, DropSplit 2 AxisV False))-  -- Center drop swaps; the preview is the target's exact region.-  let dtC = dropTargetForPane r2 (V2 (rectX r2 + rectW r2 / 2) (rectY r2 + rectH r2 / 2)) 2-  assertEq failed dtC (DropSwap 2)-  assertEq failed (preview dtC) (Just (Rect 302 0 298 198, DropSwap 2))-  -- Top-level edge drops restructure the whole grid.-  assertEq failed (topLevelDropTarget 20 base (V2 5 200)) (Just (DropTop AxisV True))-  assertEq failed (topLevelDropTarget 20 base (V2 300 200)) Nothing-  let dtD = DropTop AxisV True-  assertEq failed (preview dtD) (Just (Rect 0 0 298 400, DropTop AxisV True))--  -- Widget level: build the same mixed grid through a live paneGrid, drag the-  -- left pane onto the bottom-right pane's lower edge, and check the drop-  -- lands it below that pane (tree order of the restructured grid).-  rects <- newIORef IM.empty-  closeRects <- newIORef IM.empty-  stateUpdates <- newIORef IM.empty-  paneStates <- newIORef IM.empty-  step <- newIORef (0 :: Int)-  nbRef <- newIORef (0 :: Word64)-  let inp0 = withInput 600 400-      cfg =-        defaultPaneGridConfig-          { pgLayout = fillW . fillH-          , pgMinSize = 40-          , pgSpacing = 4-          , pgViewPane = \pid pctx -> do-              liftIO (modifyIORef' rects (IM.insert (fromIntegral pid) (pgcRect pctx)))-              (value, setValue) <- useInt 0-              marker <- nextId-              updates <- liftIO (readIORef stateUpdates)-              case IM.lookup (fromIntegral pid) updates of-                Nothing -> pure ()-                Just n -> do-                  setValue n-                  liftIO (modifyIORef' stateUpdates (IM.delete (fromIntegral pid)))-              liftIO (modifyIORef' paneStates (IM.insert (fromIntegral pid) (marker, value)))-              s <- liftIO (readIORef step)-              case s of-                0 -> do-                  nb <- pgcSplit pctx AxisV-                  liftIO $ do-                    writeIORef nbRef nb-                    writeIORef step 1-                1 -> do-                  nb <- liftIO (readIORef nbRef)-                  when (pid == nb) $ do-                    _ <- pgcSplit pctx AxisH-                    liftIO (writeIORef step 2)-                _ -> pure ()-              close <- button' "x"-              liftIO (modifyIORef' closeRects (IM.insert (fromIntegral pid) (respRect close)))-              when (respClicked close) (pgcClose pctx)-              pure (PaneView "P" True Nothing)-          }-      ui = paneGrid cfg-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  (pgr0, _, _, _) <- runFrame ctx inp0 ui-  case pgrPanes pgr0 of-    [pa, pb, pc] -> do-      let expectedValues = IM.fromList [(fromIntegral p, fromIntegral p + 100) | p <- [pa, pb, pc]]-      writeIORef stateUpdates expectedValues-      _ <- warmup2 ctx inp0 ui-      initialStates <- readIORef paneStates-      assertEq failed (IM.map snd initialStates) expectedValues-      rs <- readIORef rects-      case (IM.lookup (fromIntegral pa) rs, IM.lookup (fromIntegral pc) rs) of-        (Just ra, Just rc) -> do-          -- Inside the header, only 2px from the divider: the gutter's-          -- leeway must not extend into this pane and steal the drag.-          let grab = V2 (rectX ra + rectW ra - 2) (rectY ra + 12)-              -- 30px above the grid's bottom edge: inside the pane's bottom-              -- drop zone but clear of the 20px top-level band.-              dest = V2 (rectX rc + rectW rc / 2) (rectY rc + rectH rc - 30)-              ps = IM.elems rs-              gx = minimum (map rectX ps)-              gy = minimum (map rectY ps)-              gw = maximum (map (\r -> rectX r + rectW r) ps) - gx-              gh = maximum (map (\r -> rectY r + rectH r) ps) - gy-          -- The order assert below cannot tell a pane-level split from a-          -- top-level band drop ([pb, pc, pa] either way), so pin the pointer-          -- to the pane-split path first.-          assert failed (topLevelDropTarget 20 (Rect gx gy gw gh) dest == Nothing)-          let press =-                inp0-                  { inputMousePos = grab-                  , inputMouseDown = True-                  , inputMousePressed = True-                  , inputMouseReleased = False-                  }-              hold = press {inputMousePos = dest, inputMousePressed = False}-              release = hold {inputMouseDown = False, inputMouseReleased = True}-          _ <- runFrame ctx press ui-          writeIORef rects IM.empty-          writeIORef paneStates IM.empty-          _ <- runFrame ctx hold ui-          during <- readIORef rects-          duringStates <- readIORef paneStates-          assertEq failed duringStates (IM.delete (fromIntegral pa) initialStates)-          assert failed (not (IM.member (fromIntegral pa) during))-          assertEq failed (IM.size during) 2-          assert failed (all ((== gw) . rectW) (IM.elems during))-          -- Crossing back over the original grab point must not make the-          -- pane reappear or collapse the drag back into a click.-          writeIORef rects IM.empty-          _ <- runFrame ctx (hold {inputMousePos = grab}) ui-          returned <- readIORef rects-          assert failed (not (IM.member (fromIntegral pa) returned))-          -- Releasing outside the grid restores the committed layout.-          (cancelled, _, _, _) <- runFrame ctx (release {inputMousePos = V2 (-20) (-20)}) ui-          assertEq failed (pgrPanes cancelled) [pa, pb, pc]-          writeIORef rects IM.empty-          _ <- warmup2 ctx inp0 ui-          restored <- readIORef rects-          assertEq failed restored rs-          restoredStates <- readIORef paneStates-          assertEq failed restoredStates initialStates-          _ <- runFrame ctx press ui-          _ <- runFrame ctx hold ui-          (pgr1, _, _, _) <- runFrame ctx release ui-          assertEq failed (pgrPanes pgr1) [pb, pc, pa]-          _ <- warmup2 ctx inp0 ui-          droppedStates <- readIORef paneStates-          assertEq failed droppedStates initialStates-          buttons <- readIORef closeRects-          case IM.lookup (fromIntegral pa) buttons of-            Nothing -> assert failed False-            Just closeRect -> do-              let closePos = V2 (rectX closeRect + rectW closeRect / 2) (rectY closeRect + rectH closeRect / 2)-                  closePress = press {inputMousePos = closePos}-                  closeHold = hold {inputMousePos = V2 (v2X closePos + 60) (v2Y closePos + 40)}-              _ <- runFrame ctx closePress ui-              writeIORef rects IM.empty-              _ <- runFrame ctx closeHold ui-              duringClose <- readIORef rects-              assertEq failed (IM.size duringClose) 3-              (closed, _, _, _) <- runFrame ctx (release {inputMousePos = closePos}) ui-              assertEq failed (pgrPanes closed) [pb, pc]-        _ -> assert failed False-    _ -> assert failed False----- A button scrolled above its viewport can geometrically overlap the header,--- but its invisible rectangle must not claim the header's drag press.-runPaneGridClippedControlTest :: Context -> IORef Int -> IO ()-runPaneGridClippedControlTest ctx failed = do-  rendered <- newIORef False-  geometry <- newIORef Nothing-  let inp0 = withInput 300 240-      ui = paneGrid defaultPaneGridConfig-        { pgLayout = fillW . fillH-        , pgViewPane = \_ _ -> do-            liftIO (writeIORef rendered True)-            header <- labelWith' (fixedH 40 . fillW . tight) "Header"-            (sid, target) <- scrollArea (fixedH 120 . fillW . tight) $-              columnWith tight $ do-                b <- button' "Scrolled control"-                mapM_ (\_ -> void (label "Scroll content")) [1 .. 20 :: Int]-                pure b-            liftIO (writeIORef geometry (Just (respId header, sid, respId target)))-            pure (PaneView "Panel" True Nothing)-        }-  _ <- warmup2 ctx inp0 ui-  ids <- readIORef geometry-  case ids of-    Nothing -> assert failed False-    Just (headerId, sid, targetId) -> do-      headerRect <- getPrevRect ctx headerId-      targetRect <- getPrevRect ctx targetId-      case (headerRect, targetRect) of-        (Just hr, Just br) -> do-          -- Place the button's invisible center exactly in the header.-          let headerY = rectY hr + rectH hr / 2-          setScrollOffset ctx sid (rectY br + rectH br / 2 - headerY)-          _ <- warmup2 ctx inp0 ui-          hiddenRect <- getPrevRect ctx targetId-          case hiddenRect of-            Nothing -> assert failed False-            Just r -> do-              let grab = V2 (rectX r + rectW r / 2) (rectY r + rectH r / 2)-                  press = inp0 {inputMousePos = grab, inputMouseDown = True, inputMousePressed = True}-                  hold = press {inputMousePressed = False, inputMousePos = V2 (v2X grab + 30) (v2Y grab)}-              assert failed (rectContains hr grab)-              _ <- runFrame ctx press ui-              writeIORef rendered False-              _ <- runFrame ctx hold ui-              stillRendered <- readIORef rendered-              assert failed (not stillRendered)-        _ -> assert failed False---- Clicking the embedded clear (×) must empty the field, keep focus, and fire an--- immediate (non-debounced) change pulse.-runSearchFieldClearTest :: Context -> IORef Int -> IO ()-runSearchFieldClearTest ctx failed = do-  queryRef <- newIORef "hello world"-  let inp0 = withInput 320 100-      ui = column (held queryRef (searchField' "Search…"))-  (resp, _) <- warmup2 ctx inp0 ui-  let Rect bx by bw bh = respRect resp-      cy = by + bh / 2-      scanClear x-        | x < bx = pure Nothing-        | otherwise = do-            let probe = inp0 {inputMousePos = V2 x cy}-            _ <- runFrame ctx probe ui-            kind <- uiCursorKind ctx probe-            if kind == UiCursorPointer then pure (Just x) else scanClear (x - 2)-  mcx <- scanClear (bx + bw - 6)-  case mcx of-    Nothing -> assert failed False-    Just cx -> do-      let press = inp0 {inputMousePos = V2 cx cy, inputMouseDown = True, inputMousePressed = True, inputMouseReleased = False}-      _ <- runFrame ctx press ui-      ((r1, t1), _, _, _) <- runFrame ctx inp0 ui-      assertEq failed t1 ""-      assert failed (respChanged r1)-      ((r2, _), _, _, _) <- runFrame ctx inp0 ui-      assert failed (not (respChanged r2))---- Typing is echoed immediately but the change pulse only fires after the text--- has been idle for the configured debounce window.-runSearchFieldDebounceTest :: Context -> IORef Int -> IO ()-runSearchFieldDebounceTest ctx failed = do-  queryRef <- newIORef ""-  let inp0 = withInput 320 100-      ui = column (held queryRef (searchFieldConfigured' (defaultSearchFieldConfig {sfcDebounceMs = 40})))-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  ((rA, tA), _, _, _) <- runFrame ctx (inp0 {inputChars = "a"}) ui-  assertEq failed tA "a"-  assert failed (not (respChanged rA))-  ((rB, tB), _, _, _) <- runFrame ctx (inp0 {inputChars = "b"}) ui-  assertEq failed tB "ab"-  assert failed (not (respChanged rB))-  threadDelay 80000-  ((rC, tC), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed tC "ab"-  assert failed (respChanged rC)-  threadDelay 50000-  ((rD, _), _, _, _) <- runFrame ctx inp0 ui-  assert failed (not (respChanged rD))--runKvMultilineHeightTest :: Context -> IORef Int -> IO ()-runKvMultilineHeightTest ctx failed = do-  let-    inp0 = withInput 320 400-    ui = column $ do-      card $ do-        kv "Notes" "Line 1\nLine 2\nLine 3\nLine 4\nLine 5"-        kv "Tree" "0"-  _ <- warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  case (spanYOf "Line 5" spans, spanYOf "Tree" spans) of-    ([line5Y], [treeY]) ->-      assert failed (treeY > line5Y)-    _ -> assert failed False
+ test/integration/Cases/Adornment.hs view
@@ -0,0 +1,271 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Adornment (tests) where++import Spec+import Data.Text (Text)+import Data.Text qualified as T+import NanoUI.Adornment qualified as A+import NanoUI.Internal.Context (Context (..), getFocusables)+import NanoUI.Internal.Layout.Arena (flowChildrenInOrder, getNodeRect, lookupNodeByWidgetId)+import NanoUI.Testing.Sim+  ( Target (..)+  , check+  , checkEq+  , click+  , focusedId+  , hotId+  , moveTo+  , pointerCursor+  , rectOf+  , result+  , runSim+  , typeText+  )++tests :: [Spec]+tests =+  [ spec "adorned-field" runAdornedFieldTest+  , spec "adorned-button" runAdornedButtonTest+  , spec "adornment-ids" runAdornmentIdsTest+  , spec "adorned-views" runAdornedViewsTest+  , spec "adorned-field-control" runAdornedFieldControlTest+  , spec "adornment-keyboard-inert" runAdornmentKeyboardInertTest+  , spec "adornment-clip" runAdornmentClipTest+  ]++squareIcon :: Svg+squareIcon = either error id (parseSvg "<svg viewBox='0 0 24 24'><rect x='2' y='2' width='20' height='20'/></svg>")++-- | The rects of a widget's adornments, leading then trailing, each side in+-- the order it was given. Each side is a row inside the widget.+adornmentRects :: Context -> Response -> IO [Rect]+adornmentRects ctx resp = do+  let na = ctxNodeArena ctx+      rowsOf = flowChildrenInOrder na+  lookupNodeByWidgetId na (respId resp) >>= \case+    Nothing -> pure []+    Just idx -> rowsOf idx >>= fmap concat . mapM (rowsOf >=> mapM (getNodeRect na))++rightOf :: Rect -> Float+rightOf (Rect x _ w _) = x + w++-- | The clip rects of the spans whose text is @txt@.+spanClips :: Text -> [(Rect, Text, a, b, Rect)] -> [Rect]+spanClips txt spans = [clip | (_, t, _, _, clip) <- spans, t == txt]++-- | A config with these adornments and a fixed width.+adornedInput :: Float -> A.Adornments -> TextInputConfig+adornedInput w adornments =+  defaultTextInputConfig {ticAdornments = adornments, ticLayout = fixedW w}++-- | A field lays an icon and an affix out inside its box, its text between them. A+-- press on the icon, or left of a plain field's text, puts the caret at the start.+runAdornedFieldTest :: Context -> IORef Int -> IO ()+runAdornedFieldTest ctx failed = do+  let inp0 = withInput 400 200+      cfg = adornedInput 240 (A.leading (A.iconSized 16 squareIcon) <> A.trailing (A.affix "kg"))+      ui = column ((,) <$> withValue "12" (textInputConfigured' cfg) <*> withValue "12" textInput')+      typed i = evalUi ctx inp0 {inputChars = "3"} ui >>= assertEq failed "312" . snd . i+  ((resp, _), (plain, _)) <- warmup2 ctx inp0 ui+  spans <- collectTextSpans ctx+  [iconR@(Rect _ _ iw ih), unitR] <- adornmentRects ctx resp+  let field = respRect resp+  [(valueR, valueClip)] <- pure [(r, clip) | (r, "12", _, _, clip) <- spans, covers field r]+  Just unitSpan <- pure (spanRectOf "kg" spans)+  assertEq failed (16, 16) (iw, ih)+  assert failed (covers field iconR && covers field unitR)+  assert failed (abs (v2Y (spanCenter iconR) - v2Y (spanCenter field)) <= 1)+  -- The text starts past the icon and its clip stops short of the affix.+  assert failed (rectX valueR >= rightOf iconR + 1 && rightOf valueClip <= rectX unitR)+  assert failed (rectX unitSpan >= rightOf valueR && rightOf unitSpan <= rightOf field)+  _ <- runClick ctx inp0 ui (spanCenter iconR)+  typed fst+  let Rect x y _ h = respRect plain+  _ <- runClick ctx inp0 ui (V2 (x + 2) (y + h / 2))+  typed snd++-- | A button centres its icon and label as one group in the label's colour, and a+-- press on the icon is the button's. A control adornment clicks alone, even pressed+-- and released in one frame. A content button sizes and clicks as a button does,+-- and a button inside its content is display.+runAdornedButtonTest :: Context -> IORef Int -> IO ()+runAdornedButtonTest ctx failed = do+  theme <- getThemeIO ctx+  removes <- newIORef (0 :: Int)+  inner <- newIORef False+  let inp0 = withInputOff 400 300+      remove = A.trailing (A.control (whenM (buttonWith tight "x") (liftIO (modifyIORef' removes (+ 1)))))+      ui = column $ do+        -- Side by side, so both heights snap from the same y.+        (a, d) <- row ((,) <$> iconButton' squareIcon "Save" <*> button' "Save")+        b <- buttonConfigured' defaultButtonConfig {bcAdornments = A.trailing (A.iconSized 16 squareIcon)} "Next"+        c <- iconButton' squareIcon ""+        chip <- buttonConfigured' defaultButtonConfig {bcAdornments = remove} "Chip"+        (content, plain) <- row ((,) <$> buttonContent' (label "Keep") <*> button' "Keep")+        nested <- buttonContent' (whenM (button "inner") (liftIO (writeIORef inner True)))+        pure [a, b, c, d, chip, content, plain, nested]+  ([a, b, c, d, _, content, plain, nested], draw) <- warmupDraw ctx inp0 ui+  spans <- collectTextSpans ctx+  [iconA] <- adornmentRects ctx a+  [iconB] <- adornmentRects ctx b+  [iconC] <- adornmentRects ctx c+  let labelIn resp lbl = [r | (r, txt, _, _, _) <- spans, txt == lbl, covers (respRect resp) r]+      iconInk (r, col) = col == styleFg (themeButton theme) && covers (rectInflate 1 iconA) r+      tinted' dd = any iconInk <$> drawQuads dd+      -- Whether a click at @p@ clicks the view's @i@th button.+      clicks i p = respClicked . (!! i) <$> runClick ctx inp0 ui p+      ra@(Rect ax _ aw ah) = respRect a+      size r = (rectW (respRect r), rectH (respRect r))+  [labelA] <- pure (labelIn a "Save")+  [labelB] <- pure (labelIn b "Next")+  [keepR] <- pure (labelIn content "Keep")+  Just xR <- pure (spanRectOf "x" spans)+  Just chipR <- pure (spanRectOf "Chip" spans)+  assert failed (covers ra iconA && rectX labelA >= rightOf iconA + 4)+  assert failed (abs ((rectX iconA - ax) - (ax + aw - rightOf labelA)) <= 2)+  assert failed (aw > rectW (respRect d))+  assertEq failed (rectH (respRect d)) ah+  assert failed (rightOf labelB + 4 <= rectX iconB && rightOf iconB <= rightOf (respRect b))+  assert failed (abs (rectW (respRect c) - rectH (respRect c)) <= 1 && covers (respRect c) iconC)+  assertEq failed (size plain) (size content)+  tinted' draw >>= assert failed+  (_, hoverDraw, _) <- runFrame ctx inp0 {inputMousePos = centerOf a} ui+  tinted' hoverDraw >>= assert failed+  clicks 0 (spanCenter iconA) >>= assert failed+  let both = buttonsFromList [MouseLeft]+      tap = inp0 {inputMousePos = spanCenter xR, inputButtonsPressed = both, inputButtonsReleased = both}+  (tapped, _, _) <- runFrame ctx tap ui+  assert failed (not (respClicked (tapped !! 4)))+  clicks 4 (spanCenter xR) >>= assert failed . not+  readIORef removes >>= assertEq failed 2+  clicks 4 (spanCenter chipR) >>= assert failed+  readIORef removes >>= assertEq failed 2+  clicks 5 (spanCenter keepR) >>= assert failed+  clicks 7 (centerOf nested) >>= assert failed+  readIORef inner >>= assert failed . not++-- | Adornments take no ids from a widget's siblings.+runAdornmentIdsTest :: Context -> IORef Int -> IO ()+runAdornmentIdsTest ctx failed = do+  let ui adorned = column $ do+        _ <- if adorned then iconButton' squareIcon "A" else button' "A"+        let adornments = if adorned then A.leading (A.icon squareIcon) <> A.trailing (A.affix "kg") else mempty+        _ <- textInputConfigured' defaultTextInputConfig {ticAdornments = adornments} (constVar "")+        currentId+  plain <- warmup2 ctx (withInputOff 400 300) (ui False)+  assertEq failed plain =<< warmup2 ctx (withInputOff 400 300) (ui True)++-- | Any view adorns either side, in order and clear of the text, its label in the+-- adornment colour; a press on a button's spinner is the button's.+runAdornedViewsTest :: Context -> IORef Int -> IO ()+runAdornedViewsTest ctx failed = do+  theme <- getThemeIO ctx+  let inp0 = withInput 400 200+      value = T.replicate 60 "9"+      spinning = A.view (void (spinnerWith' id 14))+      sides = [A.leading (A.iconSized 16 squareIcon), A.leading (A.affix "$"), A.trailing spinning]+      cfg = adornedInput 260 (mconcat sides <> A.trailing (A.view (label "ok")))+      ui = column $ do+        (field, _) <- withValue value (textInputConfigured' cfg)+        (,) field <$> buttonConfigured' defaultButtonConfig {bcAdornments = A.leading spinning} "Saving"+  (field, saving) <- warmup2 ctx inp0 ui+  spans <- collectTextSpans ctx+  [iconR, dollarR, spinR, okR] <- adornmentRects ctx field+  [savingSpin] <- adornmentRects ctx saving+  [clip] <- pure (spanClips value spans)+  [okFg] <- pure [fg | (_, "ok", fg, _, _) <- spans]+  Just labelR <- pure (spanRectOf "Saving" spans)+  assert failed (all (covers (respRect field)) [iconR, dollarR, spinR, okR])+  assert failed (rightOf iconR < rectX dollarR && rightOf spinR < rectX okR)+  assert failed (rightOf dollarR <= rectX clip && rightOf clip <= rectX spinR)+  assertEq failed (14, 14) (rectW spinR, rectH spinR)+  assertEq failed (lerpColor (styleFg (themeInput theme)) (styleBg (themeInput theme)) 0.45) okFg+  assert failed (covers (respRect saving) savingSpin && rightOf savingSpin + 4 <= rectX labelR)+  (_, saving') <- runClick ctx inp0 ui (spanCenter savingSpin)+  assert failed (respClicked saving')++-- | A control in a field takes the pointer (a disabled one leaves it to the field) and+-- a press on it blurs another field; in the focused field Show clicks, the field+-- keeping focus and caret, unclicked and unhovered.+runAdornedFieldControlTest :: Context -> IORef Int -> IO ()+runAdornedFieldControlTest ctx failed = do+  showClicks <- newIORef (0 :: Int)+  let showButton = whenM (buttonWith tight "Show") (liftIO (modifyIORef' showClicks (+ 1)))+      offButton = A.leading (A.control (disabledWhen True (void (buttonWith tight "Off"))))+      cfg = (adornedInput 260 (offButton <> A.trailing (A.control showButton))) {ticPassword = True}+      ui = column ((,) <$> withValue "ab" (textInputConfigured' cfg) <*> withValue "bb" textInput')+  runSim ctx failed (withInputOff 400 200) ui $ do+    ((field, _), (other, _)) <- result+    showR <- rectOf "Show"+    _ <- click (On other) >> click "Show"+    checkEq (WidgetId 0) =<< focusedId+    -- Focus the field with the caret at the end of its text.+    _ <- click (At (V2 (rectX showR - 20) (v2Y (spanCenter showR))))+    checkEq (respId field) =<< focusedId+    ((hovered, _), _) <- moveTo "Show" >> moveTo "Show" >> moveTo "Show"+    check (not (respHovered hovered))+    checkEq UiCursorPointer =<< pointerCursor+    ((clicked, _), _) <- click "Show"+    check (not (respClicked clicked))+    checkEq 2 =<< liftIO (readIORef showClicks)+    checkEq (respId field) =<< focusedId+    checkEq "abc" . snd . fst =<< typeText "c"+    _ <- moveTo "Off" >> moveTo "Off"+    checkEq (respId field) =<< hotId+    checkEq UiCursorText =<< pointerCursor++-- | Display content neither enters tab order nor requests the input method, even focused.+runAdornmentKeyboardInertTest :: Context -> IORef Int -> IO ()+runAdornmentKeyboardInertTest ctx failed = do+  clicks <- newIORef (0 :: Int)+  childId <- newIORef (WidgetId 0)+  let inp = withInputOff 600 300+      decorative = do+        whenM (button "Display only") (liftIO (modifyIORef' clicks (+ 1)))+        (field, _) <- withValue "Decoration" textInput'+        liftIO (writeIORef childId (respId field))+      ui = column $ do+        outer <- buttonContent' decorative+        adorned <- buttonConfigured' defaultButtonConfig {bcAdornments = A.trailing (A.view decorative)} "Adorned"+        after <- button' "After"+        pure [outer, adorned, after]+  resps <- warmup2 ctx inp ui+  assertEq failed (map respId resps) =<< getFocusables ctx+  forM_ (resps ++ take 1 resps) $ \expected -> do+    _ <- runFrame ctx (tabInp inp) ui+    assertEq failed (respId expected) =<< getFocusId ctx+    void (runFrame ctx (keyInp KeyEnter inp) ui)+  assertEq failed 0 =<< readIORef clicks+  setFocus ctx =<< readIORef childId+  _ <- runFrame ctx inp ui+  assertEq failed Nothing =<< textInputArea ctx++-- | Text is clipped to its room: a value short of its affix (a longer one later+-- narrows it) or a search field's clear button, an affix at its button's edge.+runAdornmentClipTest :: Context -> IORef Int -> IO ()+runAdornmentClipTest ctx failed = do+  let inp0 = withInputOff 400 200+      value = T.replicate 60 "9"+      clipped c ui txt = do+        r <- warmup2 c inp0 (column ui)+        spans <- collectTextSpans c+        [clip] <- pure (spanClips txt spans)+        pure (r, clip, spans)+      withUnit unit = do+        let field = textInputConfigured' (adornedInput 200 (A.trailing (A.affix unit))) (constVar value)+        (_, clip, spans) <- clipped ctx field value+        Just unitR <- pure (spanRectOf unit spans)+        assert failed (rightOf clip <= rectX unitR)+        pure (rightOf clip, rectX unitR)+  (shortClip, kg) <- withUnit "kg"+  (longClip, kilograms) <- withUnit "kilograms"+  assert failed (kilograms < kg && longClip < shortClip)+  let search = defaultSearchInputConfig {sicLayout = fixedW 200}+  searching <- newContext+  (field, clip, _) <- clipped searching (fst <$> withValue value (searchInputConfigured' search)) value+  assert failed (rightOf clip + 15 <= rightOf (respRect field))+  weighing <- newContext+  let weigh =+        defaultButtonConfig {bcLayout = fixedW 60, bcAdornments = A.trailing (A.affix "kilograms")}+  (weighed, kgClip, _) <- clipped weighing (buttonConfigured' weigh "Weigh") "kilograms"+  assert failed (covers (respRect weighed) kgClip)
test/integration/Cases/Animation.hs view
@@ -1,208 +1,259 @@-module Cases.Animation-  ( runAnimationBezierTest-  , runButtonHoverAnimTest-  , runAnimationDamageTest-  , runAnimationSettleTest-  , runAnimationSpringDtTest-  , runAnimationSpringRetargetTest-  , runAnimationStaggerTest-  , runCompositeAnimationIsolationTest-  , runSpinnerTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Animation (tests) where +import Spec import Control.Concurrent (threadDelay)-import Control.Monad (forM_, replicateM, replicateM_, void)-import Data.IORef (IORef)+import Data.Primitive.SmallArray (smallArrayFromList) import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert)-import NanoUI.Testing.Harness (clickPair, drawQuads, withDelta)---- A started animation requests redraws, settles on its target, and then--- leaves the context idle and clean.-runAnimationSettleTest :: Context -> IORef Int -> IO ()-runAnimationSettleTest ctx failed = do-  let inp = withDelta 100 100 0.1-      wid = WidgetId 99-  _ <- runFrame ctx inp (label "settle")-  startAnimation ctx wid 0 1 0.25-  need <- needsRedraw ctx inp inp-  assert failed need-  replicateM_ 4 (runFrame ctx inp (label "settle"))-  val <- getAnimationValue ctx wid-  assert failed (abs (val - 1) <= 0.01)-  live <- anyAnimating ctx-  assert failed (not live)-  needAfter <- needsRedraw ctx inp inp-  assert failed (not needAfter)-  (_, _, _, dirty) <- runFrame ctx inp (label "settle")-  assert failed (not dirty)+import GHC.Clock (getMonotonicTime) -runAnimationDamageTest :: Context -> IORef Int -> IO ()-runAnimationDamageTest _ failed = do-  ctx <- newContext-  let idleInp = withDelta 200 100 0-      idle = label "anim"-      tweenInp = idleInp {inputDeltaTime = 0.05}-      ui = do-        t <- animateTo (Tween EaseLinear 0.4 0) 1-        void (spacer (Fixed (20 + 80 * t)) Fit)-        label "anim"-      hasMove dmg = case dmg of-        DamageFull -> True-        DamageClip r -> rectW r > 0 && rectH r > 0-  _ <- runFrame ctx idleInp idle-  _ <- runFrame ctx idleInp idle-  dIdle <- takeDamage ctx-  assert failed (dIdle /= DamageFull)-  _ <- runFrame ctx tweenInp ui-  dMid <- takeDamage ctx-  assert failed (hasMove dMid)-  ctx2 <- newContext-  let fastInp = idleInp {inputDeltaTime = 0.5}-      uiFast = do-        t <- animateTo (Tween EaseLinear 0.2 0) 1-        void (spacer (Fixed (20 + 80 * t)) Fit)-        label "anim"-  _ <- runFrame ctx2 idleInp idle-  _ <- runFrame ctx2 idleInp idle-  _ <- runFrame ctx2 fastInp uiFast-  dFast <- takeDamage ctx2-  assert failed (hasMove dFast)+tests :: [Spec]+tests =+  [ spec "animation-values" runAnimationValuesTest+  , spec "animate-to-stays-settled" runAnimateToStaysSettledTest+  , spec "animation-damage" runAnimationDamageTest+  , spec "composite-animation-isolation" runCompositeAnimationIsolationTest+  , spec "button-animation" runButtonHoverAnimTest+  , spec "animated-drawings" runSpinnerTest+  , spec "animation-left-out" runAnimationLeftOutTest+  , spec "spinner-out-of-view" runSpinnerOutOfViewTest+  , spec "wake-after" runWakeAfterTest+  ] --- A delayed tween holds its start value until the delay elapses and then--- eases from there; declarative tweens stagger the same way per key.-runAnimationStaggerTest :: Context -> IORef Int -> IO ()-runAnimationStaggerTest ctx failed = do-  let inp = withDelta 200 100 0.02-      wid = WidgetId 202-      slow = inp {inputDeltaTime = 0.1}-  startAnimationEaseDelay ctx wid 0 1 0.2 EaseLinear 0.15-  _ <- runFrame ctx slow (label "delay")-  v0 <- getAnimationValue ctx wid-  assert failed (abs v0 <= 0.01)-  live0 <- anyAnimating ctx-  assert failed live0-  _ <- runFrame ctx slow (label "delay")-  v1 <- getAnimationValue ctx wid-  assert failed (abs (v1 - 0.25) <= 0.03)-  let ui = do+-- | Tweens, delays and springs reach their values and let the loop sleep. A+-- fast spring at a low frame rate stays in range (a fixed 1/30 s step sent+-- it to NaN), and one toward 1500 lands (integrating its absolute position+-- froze it short, running for good). A retargeted spring carries on.+runAnimationValuesTest :: Context -> IORef Int -> IO ()+runAnimationValuesTest ctx failed = do+  let near tol want v = abs (v - want) <= tol+      frames n dt = replicateM_ n (runFrame ctx (withDelta 200 100 dt) (label "anim"))+      value = getAnimationValue ctx+  forM_ [(presetBouncy {springMass = 0.05}, 60), (SpringParams 2000 150 1, 30)] $ \(params, hz) -> do+    setAnimationValue ctx (WidgetId 404) 0+    startSpring ctx (WidgetId 404) params 1+    vals <- replicateM 120 (frames 1 (1 / hz) >> value (WidgetId 404))+    assert failed (all (\v -> v >= -0.5 && v <= 1.5) vals)+    assert failed . not =<< anyAnimating ctx+    assertEq failed 1 (last vals)+  let far = animateTo (Spring presetSmooth) 1500 <* label "far"+  replicateM_ 600 (runFrame ctx (withDelta 200 100 (1 / 60)) far)+  assert failed . not =<< anyAnimating ctx+  assertEq failed 1500 =<< evalUi ctx (withDelta 200 100 (1 / 60)) far+  let inp = withDelta 200 100 0.1+  startAnimation ctx (WidgetId 99) 0 1 0.25+  assert failed =<< needsRedraw ctx inp inp+  frames 4 0.1+  assert failed . near 0.01 1 =<< value (WidgetId 99)+  assert failed . not =<< anyAnimating ctx+  assert failed . not =<< needsRedraw ctx inp inp+  assert failed . not . (\(_, _, dirty) -> dirty) =<< runFrame ctx inp (label "anim")+  startAnimationEaseDelay ctx (WidgetId 202) 0 1 0.2 EaseLinear 0.15+  frames 1 0.1+  assert failed . near 0.01 0 =<< value (WidgetId 202)+  assert failed =<< anyAnimating ctx+  frames 1 0.1+  assert failed . near 0.03 0.25 =<< value (WidgetId 202)+  let staggered = do         _ <- withKey ("lead" :: String) (animateTo (Tween EaseLinear 0.4 0) 1)-        t <- withKey ("trail" :: String) (animateTo (Tween EaseLinear 0.4 0.08) 1)-        label (T.pack ("t=" ++ show t))-      trailVal = do-        spans <- collectTextSpans ctx-        let shown = [txt | (_, txt, _, _, _) <- spans]-            tagged = [T.drop 2 txt | txt <- shown, "t=" `T.isPrefixOf` txt]-        case tagged of-          (raw : _) -> case reads (T.unpack raw) of-            [(n, "")] -> pure (n :: Float)-            _ -> assert failed False >> pure 0-          _ -> assert failed False >> pure 0-  replicateM_ 3 (runFrame ctx inp ui)-  early <- trailVal-  assert failed (early <= 0.01)-  replicateM_ 10 (runFrame ctx inp ui)-  late <- trailVal-  assert failed (late >= 0.15)--runAnimationBezierTest :: Context -> IORef Int -> IO ()-runAnimationBezierTest _ failed = do-  let lin = applyEase (EaseCubicBezier 0 0 1 1) 0.5-      out = applyEase (EaseCubicBezier 0 0 0.58 1) 0.5-  assert failed (abs (lin - 0.5) <= 0.01)-  assert failed (out > 0.5)-  assert failed (abs (applyEase EaseInQuad 0.5 - 0.25) <= 0.01)-  assert failed (abs (applyEase (EaseCubicBezier 0.33 0 0.2 1) 0) <= 0.001)-  assert failed (abs (applyEase (EaseCubicBezier 0.33 0 0.2 1) 1 - 1) <= 0.001)--runAnimationSpringRetargetTest :: Context -> IORef Int -> IO ()-runAnimationSpringRetargetTest ctx failed = do-  let inp = withDelta 100 100 0.02-      wid = WidgetId 402-  startSpring ctx wid presetBouncy 1-  replicateM_ 5 (runFrame ctx inp (label "retarget"))-  v1 <- getAnimationValue ctx wid+        withKey ("trail" :: String) (animateTo (Tween EaseLinear 0.4 0.08) 1) <* label "trail"+  replicateM_ 2 (runFrame ctx (withDelta 200 100 0.02) staggered)+  assert failed . (<= 0.01) =<< evalUi ctx (withDelta 200 100 0.02) staggered+  replicateM_ 9 (runFrame ctx (withDelta 200 100 0.02) staggered)+  assert failed . (>= 0.15) =<< evalUi ctx (withDelta 200 100 0.02) staggered+  startSpring ctx (WidgetId 402) presetBouncy 1+  frames 5 0.02+  v1 <- value (WidgetId 402)   assert failed (v1 >= 0.02 && v1 <= 0.98)-  startSpring ctx wid presetBouncy 0-  v2 <- getAnimationValue ctx wid-  assert failed (abs (v2 - v1) <= 0.02)-  live <- anyAnimating ctx-  assert failed live+  startSpring ctx (WidgetId 402) presetBouncy 0+  assert failed . near 0.02 v1 =<< value (WidgetId 402)+  assert failed =<< anyAnimating ctx+  startSpring ctx (WidgetId 403) presetStiff 1+  frames 1 2+  v <- value (WidgetId 403)+  assert failed (not (isNaN v || isInfinite v || v < 0 || v > 1.5)) -runAnimationSpringDtTest :: Context -> IORef Int -> IO ()-runAnimationSpringDtTest ctx failed = do-  let inp = withDelta 100 100 2-      wid = WidgetId 403-  startSpring ctx wid presetStiff 1-  _ <- runFrame ctx inp (label "dt")-  val <- getAnimationValue ctx wid-  assert failed (not (isNaN val || isInfinite val || val < 0 || val > 1.5))+-- | A settled 'animateTo' value with no node holds its target while read+-- (resting values were once dropped after 300 rectless frames), comes back+-- settled after a short skip, and starts over after a long one.+runAnimateToStaysSettledTest :: Context -> IORef Int -> IO ()+runAnimateToStaysSettledTest ctx failed = do+  let inp = withDelta 200 100 0.05+      fade = withKey ("fade" :: String) (animateTo (Tween EaseLinear 0.2 0) 1)+      ui shown = (if shown then fade else pure 0) <* label "rest"+      near v x = abs (x - v) <= 0.001+  replicateM_ 10 (runFrame ctx inp (ui True))+  assert failed . not =<< anyAnimating ctx+  assert failed . all (near 1) =<< replicateM 400 (evalUi ctx inp (ui True))+  assert failed . not =<< anyAnimating ctx+  assert failed . not =<< needsRedraw ctx inp inp+  replicateM_ 10 (runFrame ctx inp (ui False))+  assert failed . near 1 =<< evalUi ctx inp (ui True)+  replicateM_ 700 (runFrame ctx inp (ui False))+  assert failed . near 0 =<< evalUi ctx inp (ui True) --- Each composite animation owns a scope; component indices alone are not--- unique when two vectors animate side by side in the same parent. Tweens--- and springs both settle and stop requesting redraws.+-- | A tween moving a label repaints its old and new rects, also one that+-- starts and ends in a frame.+runAnimationDamageTest :: Context -> IORef Int -> IO ()+runAnimationDamageTest ctx0 failed = do+  ctx1 <- newContext+  forM_ [(ctx0, 0.4, 0.05), (ctx1, 0.2, 0.5)] $ \(ctx, dur, dt) -> do+    let inp = withDelta 200 100 dt+        ui target = do+          t <- animateTo (Tween EaseLinear dur 0) target+          row (spacer (Fixed (20 + 80 * t)) Fit >> label' "anim")+    lbl <- respId <$> warmup2 ctx inp (ui 0)+    assert failed . (/= DamageFull) =<< takeDamage ctx+    -- The frame that starts the tween, then one it moves the label on.+    _ <- runFrame ctx inp (ui 1)+    assertJustM failed (getPrevRect ctx lbl) $ \old -> do+      _ <- runFrame ctx inp (ui 1)+      dmg <- takeDamage ctx+      assertJustM failed (getPrevRect ctx lbl) $ \new -> do+        assertGt failed (rectX new) (rectX old)+        assert failed (damageCovers dmg old && damageCovers dmg new)++-- | Easing curves hit their ends and bend the right way, colour channels+-- clamp, and two vectors animating side by side keep their own channels+-- (indices alone collide), settling under tweens and springs. runCompositeAnimationIsolationTest :: Context -> IORef Int -> IO ()-runCompositeAnimationIsolationTest _ failed =+runCompositeAnimationIsolationTest _ failed = do+  let out = EaseCubicBezier 0 0 0.58 1+      snappy = EaseCubicBezier 0.33 0 0.2 1+  assert failed (abs (applyEase (EaseCubicBezier 0 0 1 1) 0.5 - 0.5) <= 0.01 && applyEase out 0.5 > 0.5)+  assert failed (abs (applyEase EaseInQuad 0.5 - 0.25) <= 0.01)+  assert failed (abs (applyEase snappy 0) <= 0.001 && abs (applyEase snappy 1 - 1) <= 0.001)+  let color = colorRGBA 17 80 190 255+  assertEq failed ([0, 1], V2 3 5) (traverseChannels (\i x -> ([i], x + fromIntegral i)) (V2 3 4))+  assertEq failed ([0, 1, 2, 3], color) (traverseChannels (\i x -> ([i], x)) color)+  let clamped = snd (traverseChannels (\i _ -> ([i], if i == 0 then -1 else 2)) color)+  assertEq failed (colorRGBA 0 255 255 255) clamped   forM_ [animateToA (Tween EaseLinear 0.2 0), animateToA (Spring presetSmooth)] $ \animateVector -> do     ctx <- newContext     let inp = withDelta 200 100 0.05         ui = do           a <- animateVector (V2 1 2)           b <- animateVector (V2 (-1) (-2))-          label (T.pack (show (a, b)))-          pure (a, b)+          (a, b) <$ label (T.pack (show (a, b)))     replicateM_ 80 (runFrame ctx inp ui)-    ((V2 ax ay, V2 bx by), _, _, _) <- runFrame ctx inp ui-    assert failed (abs (ax - 1) < 0.05 && abs (ay - 2) < 0.05)-    assert failed (abs (bx + 1) < 0.05 && abs (by + 2) < 0.05)-    live <- anyAnimating ctx-    assert failed (not live)-    need <- needsRedraw ctx inp inp-    assert failed (not need)+    (V2 ax ay, V2 bx by) <- evalUi ctx inp ui+    assert failed (all ((< 0.05) . abs) [ax - 1, ay - 2, bx + 1, by + 2])+    assert failed . not =<< anyAnimating ctx+    assert failed . not =<< needsRedraw ctx inp inp --- Hovering a button eases its highlight in without dipping, and a press and--- release over it leaves the hover animation fully on.+-- | A button's hover eases in without dipping and stays on through a click.+-- A 'keepAnimating' lease is not the widget's value: a spring on the key+-- starts from the resting value, and a set keeps the lease and repaints. runButtonHoverAnimTest :: Context -> IORef Int -> IO () runButtonHoverAnimTest ctx failed = do   let inp0 = withDelta 200 100 0.016       ui = column (button "Hover")   _ <- runFrame ctx inp0 ui-  let inp1 = inp0 {inputMousePos = V2 10 10}-  vals <- replicateM 5 (runFrame ctx inp1 ui >> getHotId ctx >>= getAnimationValue ctx)-  let decreases = any (uncurry (\a b -> b + 0.001 < a)) (zip vals (drop 1 vals))-  assert failed (not decreases)+  vals <- replicateM 5 $ runFrame ctx inp0 {inputMousePos = V2 10 10} ui >> getHotId ctx >>= getAnimationValue ctx+  assert failed (and (zipWith (\a b -> b + 0.001 >= a) vals (drop 1 vals)))   assert failed (last vals >= 0.4)-  let (press, release) = clickPair inp0 (V2 10 10)-  _ <- runFrame ctx press ui-  _ <- runFrame ctx release ui+  _ <- runClick ctx inp0 ui (V2 10 10)   hot <- getHotId ctx-  val <- getAnimationValue ctx hot   assert failed (hashWidgetId hot /= 0)-  assert failed (val >= 0.99)+  assert failed . (>= 0.99) =<< getAnimationValue ctx hot+  leased <- newContext+  let inp = withDelta 200 100 0.05+      hover = inp {inputMousePos = V2 10 10}+      kept = column (button' "Go" >>= \b -> b <$ keepAnimating b)+  _ <- runFrame leased inp kept+  wid <- respId . last <$> replicateM 10 (evalUi leased hover kept)+  assertEq failed 1 =<< getAnimationValue leased wid+  startSpring leased wid presetSmooth 0.5+  assert failed . (> 0.99) =<< getAnimationValue leased wid+  replicateM_ 60 (runFrame leased hover kept)+  assertEq failed 0.5 =<< getAnimationValue leased wid+  setAnimationValue leased wid 0+  assertEq failed 0 =<< getAnimationValue leased wid+  assert failed =<< anyAnimating leased+  assert failed =<< needsRedraw leased hover hover --- A spinner keeps the loop drawing, repaints only around itself, and turns.+-- | A spinner wakes the loop for its next step (60 a second), repaints only+-- around itself, and turns.+-- An unversioned drawing rebuilds on the frame its animation ends, which+-- once replayed the last animated frame's ops for good. runSpinnerTest :: Context -> IORef Int -> IO () runSpinnerTest ctx failed = do-  theme <- getTheme ctx+  theme <- getThemeIO ctx   let inp = withDelta 400 300 0.016       ui = column $ do         label "Loading a long label so the window has more than the spinner"-        spinner'+        spinnerWith' id 18+      arc qs = [q | (q, c) <- qs, c == themeAccent theme]   _ <- runFrame ctx inp ui-  (resp, _, draw0, _) <- runFrame ctx inp ui-  _ <- takeDamage ctx-  need <- needsRedraw ctx inp inp-  assert failed need+  (resp, draw0, _) <- runFrame ctx inp ui+  now <- getMonotonicTime+  wake <- getWakeAt ctx+  assert failed (wake > 0 && wake - now <= 1 / 60 + 2.0e-3)   quads0 <- drawQuads draw0-  assert failed (any ((== themeAccent theme) . snd) quads0)+  assert failed (not (null (arc quads0)))   threadDelay 60000-  (_, _, draw1, _) <- runFrame ctx inp ui-  dmg <- takeDamage ctx-  case dmg of+  (_, draw1, _) <- runFrame ctx inp ui+  takeDamage ctx >>= \case     DamageClip r -> assert failed (rectW r < 80 && rectH r < 80 && rectIntersect r (respRect resp) /= Nothing)     DamageFull -> assert failed False-  quads1 <- drawQuads draw1-  let arc qs = [q | (q, c) <- qs, c == themeAccent theme]-  assert failed (arc quads0 /= arc quads1)+  assert failed . (arc quads0 /=) . arc =<< drawQuads draw1+  ended <- newContext+  let running = colorRGBA 255 0 0 255+      stopped = colorRGBA 0 0 255 255+      square on = column $ do+        d <- drawing (fixedWH 40 40) (\r -> smallArrayFromList [FillRect r (if on then running else stopped)])+        when on (keepAnimating d)+  replicateM_ 3 (runFrame ended inp (square True))+  (_, draw, _) <- runFrame ended inp (square False)+  quads <- map snd <$> drawQuads draw+  assert failed (stopped `elem` quads && running `notElem` quads)++-- | An animation the view stops building stops drawing frames and runs again+-- when shown: a spinner's step wakes, and a long tween or undamped spring+-- behind a tab switch, which once drew for minutes or for good.+runAnimationLeftOutTest :: Context -> IORef Int -> IO ()+runAnimationLeftOutTest _ failed = do+  let tweenAndSpring = do+        _ <- animate (Tween EaseLinear 120 0) 0 1+        _ <- animateTo (Spring (SpringParams 180 0 1)) 1+        label "moving"+      loading = column (label "Loading" >> spinner)+  forM_ [(loading, column (label "Loaded")), (tweenAndSpring, label "other")] $ \(shown, other) -> do+    ctx <- newContext+    let inp = withDelta 400 300 0.016+        -- Drawing more frames: an animation, or a wake for a spinner's step.+        alive c = (||) <$> anyAnimating c <*> ((> 0) <$> getWakeAt c)+    replicateM_ 5 (runFrame ctx inp shown)+    assert failed =<< alive ctx+    _ <- runFrame ctx inp other+    _ <- runFrame ctx inp other+    assert failed . not =<< alive ctx+    assert failed . not =<< needsRedraw ctx inp inp+    _ <- runFrame ctx inp shown+    _ <- runFrame ctx inp shown+    assert failed =<< alive ctx++-- | A spinner scrolled out of its scroll area's view wakes nothing.+runSpinnerOutOfViewTest :: Context -> IORef Int -> IO ()+runSpinnerOutOfViewTest ctx failed = do+  let inp = withDelta 400 300 0.016+      ui = column $ void $ scrollWith (fixedH 60) $ column $ do+        spacer (Fixed 10) (Fixed 400)+        spinner+  replicateM_ 4 (runFrame ctx inp ui)+  assertEq failed 0 =<< getWakeAt ctx+  assert failed . not =<< anyAnimating ctx++-- | 'wakeAfter' schedules one frame, the earliest request winning.+runWakeAfterTest :: Context -> IORef Int -> IO ()+runWakeAfterTest ctx failed = do+  let inp = withDelta 200 100 0.016+      wakeWithin ui lo hi = do+        t <- getMonotonicTime+        _ <- runFrame ctx inp ui+        at <- getWakeAt ctx+        assert failed (at > t + lo && at < t + hi)+  wakeWithin (label "tick" >> wakeAfter 5) 4.5 6+  wakeWithin (wakeAfter 5 >> wakeAfter 1 >> wakeAfter 3 >> label "tick") 0.5 2+  _ <- runFrame ctx inp (label "tick")+  assertEq failed 0 =<< getWakeAt ctx
+ test/integration/Cases/ApiSmoke.hs view
@@ -0,0 +1,104 @@+{-# OPTIONS_GHC -O0 #-}+-- | Every widget and container the "NanoUI" facade exports that no other+-- test calls, run once in a view: it settles without an exception and lays+-- out a node of its own, or, for a tooltip, hovering its target asks for+-- the wake that opens it.+--+-- The list was the facade's lowercase exports that no test under+-- @packages/*/test@ names. The rest of that list are not widgets: layout+-- and style modifiers ('alignStart', the border, font and padding+-- setters), colours and themes, input predicates ('inputMouseDown',+-- 'keyActivated'), queries ('uiTime', 'uiFontSize'), scroll commands+-- ('scrollTo'), 'loadSvg' (a file read) and the clipboard calls, which+-- need a backend's clipboard.+module Cases.ApiSmoke (tests) where++import Spec+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (arenaCount)+import NanoUI.Testing.Sim qualified as Sim++tests :: [Spec]+tests =+  [spec "api-smoke" runApiSmokeTest]++data Fruit = Apple | Pear | Plum+  deriving (Eq, Show, Bounded, Enum)++-- | Each widget, named, and whether it is a tooltip on the button "target".+widgets :: IO [(String, Bool, NanoUI ())]+widgets = do+  fruit <- newVar Pear+  flag <- newVar False+  sortCol <- newVar (SortCol 0 SortAsc)+  doc <- newVar (textDocument "one\ntwo")+  icon <- either fail pure (parseSvg "<svg viewBox='0 0 24 24'><rect x='2' y='2' width='20' height='20'/></svg>")+  let show' = T.pack . show+      target = button' "target"+      cols = headed "Name" fst <> headed "Value" snd+  pure+    [ ("enumSelectBy", False, enumSelectBy show' fruit)+    , ("enumSelectBy'", False, void (enumSelectBy' show' fruit))+    , ("enumTabBarBy", False, enumTabBarBy show' fruit)+    , ("enumTabBarByConfigured", False, enumTabBarByConfigured defaultTabsConfig show' fruit)+    , ("enumTabsBy", False, enumTabsBy show' fruit (label . show'))+    , ("enumTabsByConfigured", False, enumTabsByConfigured defaultTabsConfig show' fruit (label . show'))+    , ("buttonContentWith", False, void (buttonContentWith id (label "content")))+    , ("buttonContentWith'", False, void (buttonContentWith' id (label "content")))+    , ("callout", False, callout (colorRGBA 200 40 40 255) (label "note"))+    , ("calloutWith", False, calloutWith (colorRGBA 200 40 40 255) fillW (label "note"))+    , ("captionButton", False, void (captionButton defaultCaptionConfig GlyphClose))+    , ("captionButtonsConfigured", False, void (captionButtonsConfigured defaultCaptionConfig False))+    , ("checkboxWith'", False, void (checkboxWith' fillW "check" flag))+    , ("drawingCached", False, void (drawingCached 40 20 12 0 id (pure (fixedWH 40 20 defaultLayout)) (\r -> pure (FillRect r (colorRGBA 0 0 255 255)))))+    , ("dropZone", False, void (dropZone (fixedWH 80 40) (label "drop")))+    , ("enumRadio", False, enumRadio fruit)+    , ("enumRadio'", False, void (enumRadio' fruit))+    , ("enumSelect", False, enumSelect fruit)+    , ("enumSelect'", False, void (enumSelect' fruit))+    , ("enumTabBar", False, enumTabBar fruit)+    , ("enumTabs", False, enumTabs fruit (label . show'))+    , ("calloutTone", False, calloutTone Warning (label "warn"))+    , ("selectableRow", False, void (selectableRow True (label "row")))+    , ("collapsing", False, collapsing "More" flag (label "inside"))+    , ("clipBox", False, clipBox (fixedWH 80 40) (label "clipped"))+    , ("kvBlock", False, kvBlock [("key", "value"), ("longer key", "v")])+    , ("menuButtonWith", False, void (menuButtonWith id "File" False))+    , ("menuButtonWith'", False, void (menuButtonWith' id "File" True))+    , ("rowWith'", False, void (rowWith' fillW (label "in a row")))+    , ("scroll2D", False, scroll2D (label "scrolled"))+    , ("selectableText'", False, void (selectableText' "selectable"))+    , ("selectableTextWith'", False, void (selectableTextWith' fillW "selectable"))+    , ("svgIconConfigured'", False, void (svgIconConfigured' defaultImageConfig {icLayout = fixedWH 24 24} icon))+    , ("svgIconWith'", False, void (svgIconWith' (fixedWH 24 24) icon))+    , ("table'", False, void (table' "t" cols [("a" :: T.Text, "1" :: T.Text), ("b", "2")] sortCol))+    , ("textAreaDocumentWith", False, textAreaDocumentWith (fixedWH 200 80) doc)+    , ("textAreaDocumentWith'", False, void (textAreaDocumentWith' (fixedWH 200 80) doc))+    , ("toggleButtonWith", False, toggleButtonWith id Accent "toggle" flag)+    , ("toggleButtonWith'", False, void (toggleButtonWith' id Success "toggle" flag))+    , ("tooltipAt", True, target >>= \t -> tooltipAt PlacementBelow t "tip")+    , ("tooltipWidget", True, target >>= \t -> void (tooltipWidget t (label "tip")))+    , ("windowFrame", False, windowFrame (defaultWindowFrame (colorRGBA 90 90 90 255)) (label "framed"))+    ]++-- | Each widget alone in a column lays out more nodes than the empty+-- column does. A tooltip opens after a delay on the monotonic clock, so for+-- the tooltips the check is that hovering the target asks for a timed wake+-- to open it.+runApiSmokeTest :: Context -> IORef Int -> IO ()+runApiSmokeTest _ failed = do+  ws <- widgets+  bare <- newContext+  Sim.runSim bare failed (withInput 400 300) (column (pure ())) (pure ())+  empty <- arenaCount (ctxNodeArena bare)+  forM_ ws $ \(name, hover, widget) -> do+    ctx <- newContext+    Sim.runSim ctx failed (withInput 400 300) (column widget) $+      if hover+        then do+          _ <- Sim.moveTo "target"+          Sim.checkEq (name, True) . (name,) . (> 0) =<< Sim.wakeTime+        else do+          nodes <- Sim.onContext (arenaCount . ctxNodeArena)+          Sim.checkEq (name, True) (name, nodes > empty)
test/integration/Cases/Atlas.hs view
@@ -1,60 +1,148 @@-module Cases.Atlas (runAtlasGrowthTest) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Atlas (tests) where -import Control.Monad (forM_)+import Spec import Data.ByteString qualified as BS-import Data.IORef (IORef)-import Foreign.ForeignPtr (withForeignPtr)+import Data.Word (Word8)+import Foreign.ForeignPtr (ForeignPtr, withForeignPtr) import Foreign.Marshal.Array (peekArray) import Foreign.Ptr (plusPtr)-import NanoUI (ImageId (..))-import NanoUI.Context (lookupImageUv)-import NanoUI.Testing (Context, atlasSnapshot, newContext, registerImage)-import NanoUI.Testing.Assert (assert, assertEq)+import NanoUI.Internal.Context (lookupImageUv) +tests :: [Spec]+tests =+  [ spec "atlas-growth" runAtlasGrowthTest+  , spec "atlas-changes" runAtlasChangesTest+  , spec "atlas-release" runAtlasReleaseTest+  ]++-- | Register a @w@ x @h@ image whose every byte is @v@.+insert :: Context -> Int -> Int -> Int -> Word8 -> IO Bool+insert ctx tid w h v = registerImage ctx (ImageId tid) w h (BS.replicate (w * h * 4) v)++solid :: Int -> BS.ByteString+solid v = BS.replicate 4 (fromIntegral v)++snapshot :: Context -> IO (Int, Int, ForeignPtr Word8, Int)+snapshot ctx = atlasSnapshot ctx >>= maybe (fail "missing atlas snapshot") pure++-- | The atlas pixel at @x@, @y@.+pixelAt :: Context -> Int -> Int -> IO BS.ByteString+pixelAt ctx x y = do+  (w, _, fp, _) <- snapshot ctx+  withForeignPtr fp $ \ptr -> BS.pack <$> peekArray 4 (ptr `plusPtr` ((y * w + x) * 4))++-- | An image's top-left and bottom-right pixel in the atlas.+corners :: Context -> Int -> IO (Maybe ((Int, Int), (Int, Int)))+corners ctx tid = do+  (w, h, _, _) <- snapshot ctx+  let at u v = (round (u * fromIntegral w), round (v * fromIntegral h))+  fmap (\(u0, v0, u1, v1) -> (at u0 v0, at u1 v1)) <$> lookupImageUv ctx (ImageId tid)++origin :: Context -> Int -> IO (Maybe (Int, Int))+origin ctx tid = fmap fst <$> corners ctx tid++-- | Growing and new shelves keep pixels; a same-size update stays put, and a+-- new size or an image no shelf holds is refused. Narrow images use the+-- allowed width rather than one strip. runAtlasGrowthTest :: Context -> IORef Int -> IO () runAtlasGrowthTest ctx failed = do-  let-    red = BS.pack [255, 0, 0, 255]-    blue = BS.pack [0, 0, 255, 255]-    pixels w h color = BS.concat (replicate (w * h) color)-    insert tid w h color = registerImage ctx (ImageId tid) w h (pixels w h color)-    checkPixel tid expected = do-      snapshot <- atlasSnapshot ctx >>= maybe (fail "missing atlas snapshot") pure-      uv <- lookupImageUv ctx (ImageId tid) >>= maybe (fail "missing image UV") pure-      let-        (w, h, fp, _) = snapshot-        (u0, v0, u1, v1) = uv-        xs = [round (u0 * fromIntegral w), round (u1 * fromIntegral w) - 1]-        ys = [round (v0 * fromIntegral h), round (v1 * fromIntegral h) - 1]-      forM_ [(x, y) | x <- xs, y <- ys] $ \(x, y) -> do-        actual <- withForeignPtr fp $ \ptr -> BS.pack <$> peekArray 4 (ptr `plusPtr` ((y * w + x) * 4))-        assertEq failed actual expected-  insert 1 2 2 red >>= assert failed+  let (red, blue) = (BS.pack [255, 0, 0, 255], BS.pack [0, 0, 255, 255])+      paint tid w h px = registerImage ctx (ImageId tid) w h (BS.concat (replicate (w * h) px))+      checkPixel tid want = corners ctx tid >>= maybe (fail "missing image UV") (\((x0, y0), (x1, y1)) ->+        forM_ [(x, y) | x <- [x0, x1 - 1], y <- [y0, y1 - 1]] $ \(x, y) -> pixelAt ctx x y >>= assertEq failed want)+  paint 1 2 2 red >>= assert failed   initialUv <- lookupImageUv ctx (ImageId 1)-  -- A wider image grows the atlas; wrapping another image starts a new shelf.-  insert 2 300 3 blue >>= assert failed-  insert 3 400 1 red >>= assert failed+  assert failed . and =<< sequence [paint 2 300 3 blue, paint 3 400 1 red]   grownUv <- lookupImageUv ctx (ImageId 1)   assert failed (initialUv /= grownUv)-  checkPixel 1 red-  checkPixel 2 blue-  checkPixel 3 red-  -- Same-size updates retain their location and change only their pixels.-  insert 1 2 2 blue >>= assert failed+  mapM_ (uncurry checkPixel) [(1, red), (2, blue), (3, red)]+  paint 1 2 2 blue >>= assert failed   lookupImageUv ctx (ImageId 1) >>= assertEq failed grownUv-  checkPixel 1 blue-  checkPixel 2 blue+  mapM_ (uncurry checkPixel) [(1, blue), (2, blue)]   before <- atlasSnapshot ctx-  insert 1 3 2 red >>= assert failed . not+  paint 1 3 2 red >>= assert failed . not   atlasSnapshot ctx >>= assertEq failed before--  -- Width growth cannot rescue this insertion: neither the current shelf nor-  -- a new shelf can accommodate it within the atlas's maximum dimensions.   full <- newContext-  registerImage full (ImageId 1) 1 3000 (BS.replicate (3000 * 4) 255)-    >>= assert failed+  insert full 1 1 3000 255 >>= assert failed   fullBefore <- atlasSnapshot full-  registerImage full (ImageId 2) 4094 1100 (BS.replicate (4094 * 1100 * 4) 0)-    >>= assert failed . not+  insert full 2 4094 1100 0 >>= assert failed . not   atlasSnapshot full >>= assertEq failed fullBefore   lookupImageUv full (ImageId 2) >>= assertEq failed Nothing+  wide <- newContext+  let go n = insert wide n 100 100 9 >>= \ok -> if ok && n <= 1000 then go (n + 1) else pure n+  placed <- go 1+  assertGt failed placed 900++-- | A texture of the atlas uploads only what was written since, unless the+-- atlas grew or the writes are too far back to know.+runAtlasChangesTest :: Context -> IORef Int -> IO ()+runAtlasChangesTest ctx failed = do+  let put tid w h = insert ctx tid w h 7 >>= assert failed+      upload since want = (fmap (\(_, _, _, gen, u) -> (gen, u)) <$> atlasChanges ctx since) >>= assertEq failed want+  upload 0 Nothing+  put 1 8 8+  -- A texture that holds nothing takes the whole atlas.+  upload 0 (Just (1, AtlasWhole))+  upload 1 Nothing+  -- Pixels written in place, and a new image that fits, are rects.+  put 1 8 8+  upload 1 (Just (2, AtlasRegions [(1, 1, 8, 8)]))+  put 2 4 4+  upload 1 (Just (3, AtlasRegions [(10, 1, 4, 4), (1, 1, 8, 8)]))+  upload 2 (Just (3, AtlasRegions [(10, 1, 4, 4)]))+  -- An image wider than the atlas grows it: the texture must be remade.+  put 3 300 2+  upload 3 (Just (4, AtlasWhole))+  upload 4 Nothing+  -- Past what the log keeps, the writes are not known.+  replicateM_ 200 (put 2 4 4)+  upload 4 (Just (204, AtlasWhole))+  upload 203 (Just (204, AtlasRegions [(10, 1, 4, 4)]))++-- | A released slot goes to the next image that fits, padding cleared, and+-- merges back whole once a split-off image goes too; ids are not reused.+-- Releasing an image on screen repaints it as the placeholder.+runAtlasReleaseTest :: Context -> IORef Int -> IO ()+runAtlasReleaseTest ctx failed = do+  mapM_ (\(tid, w, v) -> insert ctx tid w w v >>= assert failed) [(1, 8, 200), (2, 4, 100)]+  Just (x, y) <- origin ctx 1+  sizeBefore <- (\(w, h, _, _) -> (w, h)) <$> snapshot ctx+  releaseImage ctx (ImageId 1)+  lookupImageUv ctx (ImageId 1) >>= assertEq failed Nothing+  insert ctx 3 6 6 50 >>= assert failed+  origin ctx 3 >>= assertEq failed (Just (x, y))+  (\(w, h, _, _) -> (w, h)) <$> snapshot ctx >>= assertEq failed sizeBefore+  forM_ [(x + 6, y), (x + 6, y + 5), (x, y + 6), (x + 6, y + 6)] $ \(px, py) -> pixelAt ctx px py >>= assertEq failed (solid 0)+  pixelAt ctx (x + 5) (y + 5) >>= assertEq failed (solid 50)+  (\(_, _, _, g) -> g) <$> snapshot ctx >>= atlasChanges ctx . subtract 1+    >>= assertEq failed (Just (AtlasRegions [(x - 1, y - 1, 8, 8)])) . fmap (\(_, _, _, _, u) -> u)+  -- The leftover strip is too thin for a 4x4 image, so it goes on a shelf.+  insert ctx 4 4 4 60 >>= assert failed+  origin ctx 4 >>= assert failed . (/= Just (x, y))+  releaseImage ctx (ImageId 4)+  fresh <- evalUi ctx (withInput 100 100) freshImageId+  assert failed (fresh > ImageId 4)+  merged <- newContext+  insert merged 1 100 100 9 >>= assert failed+  first <- origin merged 1+  releaseImage merged (ImageId 1)+  forM_ [(2, 60, 100, 3), (4, 99, 99, 5)] $ \(small, w, h, large) -> do+    insert merged small w h 9 >>= assert failed+    releaseImage merged (ImageId small)+    insert merged large 100 100 9 >>= assert failed+    origin merged large >>= assertEq failed first+    releaseImage merged (ImageId large)+  shown <- newContext+  let inp = withInput 200 100+      ui = image (fixedWH 20 20) (ImageId 1)+  insert shown 1 2 2 255 >>= assert failed+  replicateM_ 3 (runFrame shown inp ui)+  assert failed . (/= DamageFull) =<< takeDamage shown+  clearDirty shown+  releaseImage shown (ImageId 7)+  assert failed . not =<< isDirty shown+  releaseImage shown (ImageId 1)+  assert failed =<< isDirty shown+  _ <- runFrame shown inp ui+  assertEq failed DamageFull =<< takeDamage shown
test/integration/Cases/Cache.hs view
@@ -1,28 +1,91 @@-module Cases.Cache-  ( runMetricCacheInvalidationTest-  , runWidgetPlacementCacheTest-  , runLayoutPaintStateTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Cache (tests) where -import Control.Monad (forM_, void)+import Spec import Control.Exception (evaluate)+import Data.Bits (shiftL) import Data.ByteString qualified as BS-import Data.IORef (IORef, readIORef, writeIORef) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Ptr (castPtr)-import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Layout.Arena-  ( NodeType (..), addNodeFromLayout, getRect, setNodeText, setNodeValue+import Data.Text qualified as T+import Data.Primitive.SmallArray (smallArrayFromList)+import NanoUI.Internal.Context (Context (..), registerCustomDrawing)+import NanoUI.Internal.Layout.Arena+  ( addNodeFromLayout, getNodeRect, setNodeText   , setStyleIdx, setWidgetId   )-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt)-import NanoUI.Testing.Harness (withInputOff)+import NanoUI.Internal.Store (ptrEq) import System.Mem.StableName (makeStableName) --- Copy the mutable draw buffers before another frame can reuse them. Counts--- alone cannot detect stale geometry, colors or translated text.+tests :: [Spec]+tests =+  [ spec "metric-cache-invalidation" runMetricCacheInvalidationTest+  , spec "widget-placement-cache" runWidgetPlacementCacheTest+  , spec "draw-reuse" runDrawReuseTest+  , spec "draw-reuse-continuous" runContinuousDrawReuseTest+  , spec "wrap-width-bounds" runWrapBoundsTest+  , spec "wrap-and-truncate" runWrapTruncateTest+  ]++-- | Wrapping keeps indentation and inner runs of spaces; breaks and cuts keep+-- marks, joined emoji and flags whole; a cut never overflows, dropping the+-- dots when only a first character fits.+runWrapTruncateTest :: Context -> IORef Int -> IO ()+runWrapTruncateTest ctx failed = do+  let flags = "\x1F1FA\x1F1F8\x1F1EB\x1F1F7"+      england = "\x1F3F4\xE0067\xE0062\xE0065\xE006E\xE0067\xE007F"+      narrowDots = (monospaceMetrics 10) {fmAdvance = \case 'W' -> 14; '.' -> 4; ' ' -> 5; _ -> 10}+  forM_+    [ (1, "    let x  = 1   in  x + 1  ", 14, ["    let x  = 1", "in  x + 1"])+    , (1, "    a  b  c", 6, ["    a", "b  c"])+    , (10, "ae\x0301\&b", 20, ["a", "e\x0301", "b"])+    , (10, "\x1F469\x200D\x1F4BBx", 20, ["\x1F469\x200D\x1F4BB", "x"])+    , (10, flags, 30, ["\x1F1FA\x1F1F8", "\x1F1EB\x1F1F7"])+    , (10, "a" <> england, 30, ["a", england])+    ]+    $ \(k, txt, w, want) ->+      assertEq failed want =<< wrapTextLinesIO (\t -> pure (k * fromIntegral (T.length t))) txt w+  forM_+    [ (monospaceMetrics 10, 55, "ae\x0301\&bcd", "a...")+    , (monospaceMetrics 10, 65, flags <> "xyz", "\x1F1FA\x1F1F8...")+    , (narrowDots, 16, "Wide", "W")+    , (narrowDots, 36, "Wide", "Wi...")+    ]+    $ \(fm, w, txt, want) -> assertEq failed want =<< evalUi ctx (withInput 100 100) (truncateTextUi fm w txt)++-- | A wrap holds for every width from its widest line up to its break width,+-- since the wrap cache hands it out for all of them.+runWrapBoundsTest :: Context -> IORef Int -> IO ()+runWrapBoundsTest _ failed = do+  let charW :: Char -> Float+      charW c = case c of+        ' ' -> 3+        'i' -> 2+        'l' -> 2.5+        'm' -> 9+        'W' -> 11+        _ -> 5 + fromIntegral (fromEnum c `mod` 3)+      lineW t = pure (sum (map charW (T.unpack t)))+      texts =+        [ "the quick brown fox jumps over the lazy dog"+        , "a supercalifragilisticexpialidocious word among small ones"+        , "two\n\nparagraphs, the second with Wide Words mmm www"+        , "nospacesatalljustonelongrunoflettersWWWmmm"+        , "  leading and  double spaced  words  "+        , "    indented    code  = aligned   -- and a comment"+        , "cafe\x0301 nai\x0308ve e\x0301\&e\x0301\&e\x0301\&e\x0301 \x0928\x092E\x0938\x094D\x0924\x0947 \x1F469\x200D\x1F4BB\x1F469\x200D\x1F4BB"+        ]+  forM_ texts $ \txt -> forM_ [1, 3 .. 320 :: Float] $ \w -> do+    r <- wrapTextIO lineW txt w+    let hi = min (wrBreakW r) (w + 400)+        probes = filter (\v -> v > 0 && v >= wrFitW r && v < wrBreakW r) [wrFitW r, w, (wrFitW r + hi) / 2, hi - 0.01]+    assert failed (wrFitW r <= w && w < wrBreakW r)+    forM_ probes $ \v -> do+      again <- wrapTextLinesIO lineW txt v+      assertEq failed (txt, w, v, wrLines r) (txt, w, v, again)++-- | A copy of the draw buffers, taken before another frame reuses them:+-- counts alone cannot see stale geometry, colours or translated text. snapshotDraw :: DrawData -> IO (BS.ByteString, BS.ByteString, [DrawCmd]) snapshotDraw draw = do   vertices <- withForeignPtr (drawVertices draw) $ \p ->@@ -31,13 +94,19 @@     BS.packCStringLen (castPtr p, drawIndexCount draw * indexSize)   pure (vertices, indices, drawCmdElems draw) +-- | One frame of @ui@, and a copy of what it drew.+drawnBy :: Context -> Input -> NanoUI a -> IO (BS.ByteString, BS.ByteString, [DrawCmd])+drawnBy c inp ui = runFrame c inp ui >>= \(_, dd, _) -> snapshotDraw dd++-- | Contexts derived with other measures share their parent's caches yet lay+-- out with their own (an incremented revision would collide on returning);+-- each font modifier draws as a fresh context does; a new size repaints. runMetricCacheInvalidationTest :: Context -> IORef Int -> IO () runMetricCacheInvalidationTest ctx failed = do   let inp = withInputOff 400 300       width c = do         void $ runFrame c inp (button "ABC")-        (_, _, w, _) <- getRect (ctxNodeArena c) 0-        pure w+        rectW <$> getNodeRect (ctxNodeArena c) 0       a = withMeasureText ctx (\_ -> pure (200, 20))       b = withMeasureText ctx (\_ -> pure (80, 12))   original <- width ctx@@ -45,34 +114,33 @@   wb <- width b   assertGt failed wa original   assertGt failed wa wb-  -- Both variants derive from the same parent and share mutable caches. An-  -- incremented pure Int revision would collide here; returning to A matters.   assertEq failed wa =<< width a   assertEq failed original =<< width ctx--  -- Each supported pure modifier must invalidate both layout and placement.   forM_     [ (\c -> withFontMetrics c (monospaceMetrics 24), void (button "ABC"))-    , (\c -> withMonoFontMetrics c (monospaceMetrics 24), void (labelWith fontMono "ABC"))-    , (\c -> withFontResolver c (\_ _ _ _ -> pure (monospaceMetrics 24, False))-            (\_ _ _ _ _ -> pure (200, 24)), void (labelWith (fontSize 24) "ABC"))-    ] $ \(configure, ui) -> do+    , (\c -> withMonoFontMetrics c (monospaceMetrics 24), labelWith fontMono "ABC")+    , ( \c -> withFontResolver c (\_ _ _ _ -> pure (monospaceMetrics 24, False)) (\_ _ _ _ _ -> pure (200, 24))+      , labelWith (fontSize 24) "ABC"+      )+    ]+    $ \(configure, ui) -> do       warm <- newContext       void $ runFrame warm inp ui       let configured = configure warm-      (_, _, draw, _) <- runFrame configured inp ui-      actual <- snapshotDraw draw+      actual <- drawnBy configured inp ui       spans <- collectTextSpans configured       fresh <- configure <$> newContext-      (_, _, coldDraw, _) <- runFrame fresh inp ui-      expected <- snapshotDraw coldDraw-      assertEq failed actual expected+      assertEq failed actual =<< drawnBy fresh inp ui       assertEq failed spans =<< collectTextSpans fresh+  sized <- newContext+  _ <- warmup2 sized inp (label "ABC")+  _ <- runFrame (withFontSize sized 24) inp (label "ABC")+  assertEq failed DamageFull =<< takeDamage sized --- A table header's width and style stay fixed while alignment and its parent--- origin change independently. This exercises the placement cache's key.+-- | A table header of fixed width and style, at an alignment and parent+-- origin that change independently, as keys the placement cache. header :: Context -> AlignX -> Float -> Float -> NanoUI ()-header ctx ax x y = uiIO $ do+header ctx ax x y = liftIO $ do   let na = ctxNodeArena ctx   parent <- addNodeFromLayout na NodeContainer (-1) $     (fixedWH 320 160 defaultLayout) {layoutPadding = Padding x 0 y 0}@@ -80,60 +148,143 @@     (fixedWH 200 30 defaultLayout) {layoutAlignX = ax}   setWidgetId na i (WidgetId 123)   setNodeText na i "Header"-  setStyleIdx na i 0x80000000+  -- ButtonTable = 3 in bits 24-27 (SB.buttonKind).+  setStyleIdx na i (3 `shiftL` 24) +-- | At each snap scale a new alignment places afresh, and a moved parent+-- reuses the text cache yet draws as a cold placement. runWidgetPlacementCacheTest :: Context -> IORef Int -> IO ()-runWidgetPlacementCacheTest _ctx failed =+runWidgetPlacementCacheTest _ failed =   forM_ [1, 1.5, 2] $ \scale -> do-    base <- newContext-    let ctx = withFontMetrics base ((monospaceMetrics 12) {fmSnapScale = scale})+    let scaled c = withFontMetrics c ((monospaceMetrics 12) {fmSnapScale = scale})         inp = withInputOff 400 300+        drawn c ax x y = drawnBy c inp (header c ax x y)+    ctx <- scaled <$> newContext+    fresh <- scaled <$> newContext     void $ runFrame ctx inp (header ctx AlignStart 0 0)     start <- collectTextSpans ctx-    (_, _, draw, _) <- runFrame ctx inp (header ctx AlignEnd 0 0)-    aligned <- snapshotDraw draw-    end <- collectTextSpans ctx-    assert failed (start /= end)-    freshBase <- newContext-    let fresh = withFontMetrics freshBase ((monospaceMetrics 12) {fmSnapScale = scale})-    (_, _, expectedDraw, _) <- runFrame fresh inp (header fresh AlignEnd 0 0)-    assertEq failed aligned =<< snapshotDraw expectedDraw--    cache <- readIORef (ctxWidgetTextCache ctx) >>= evaluate >>= makeStableName+    aligned <- drawn ctx AlignEnd 0 0+    assert failed . (start /=) =<< collectTextSpans ctx+    assertEq failed aligned =<< drawn fresh AlignEnd 0 0+    let cacheName = readIORef (ctxWidgetTextCache ctx) >>= evaluate >>= makeStableName+    cache <- cacheName     forM_ [(0.25, 0.5), (9.75, 3.25), (0, 0)] $ \(x, y) -> do-      (_, _, movedDraw, _) <- runFrame ctx inp (header ctx AlignEnd x y)-      moved <- snapshotDraw movedDraw-      cache' <- readIORef (ctxWidgetTextCache ctx) >>= evaluate >>= makeStableName-      assert failed (cache == cache')-      -- Force a fresh placement at the same origin and compare actual bytes.+      moved <- drawn ctx AlignEnd x y+      assert failed . (cache ==) =<< cacheName       clearMeasureCache fresh-      (_, _, coldDraw, _) <- runFrame fresh inp (header fresh AlignEnd x y)-      assertEq failed moved =<< snapshotDraw coldDraw+      assertEq failed moved =<< drawn fresh AlignEnd x y -runLayoutPaintStateTest :: Context -> IORef Int -> IO ()-runLayoutPaintStateTest ctx failed = do+-- | A full undamaged frame of unchanged view output returns the last draw+-- data itself; paint-state changes still draw. Container drawings, reuse+-- off, the layout overlay and clip frames always paint.+runDrawReuseTest :: Context -> IORef Int -> IO ()+runDrawReuseTest ctx failed = do+  let px = BS.replicate (4 * 4 * 4) 200+  assert failed . and =<< mapM (\i -> registerImage ctx (ImageId i) 4 4 px) [1, 2]   let inp = withInputOff 400 300-      ui value color = do-        column $ do-          box (fixedWH 30 30) color-          uiIO $ do-            let na = ctxNodeArena ctx-            i <- addNodeFromLayout na NodeSlider 0 (fixedWH 200 30 defaultLayout)-            setWidgetId na i (WidgetId 123)-            setNodeText na i ""-            setNodeValue na i value-          void (labelWith (fontColor color) "paint only")       red = colorRGBA 255 0 0 255       blue = colorRGBA 0 0 255 255-  (_, _, firstDraw, _) <- runFrame ctx inp (ui 0.2 red)-  first <- snapshotDraw firstDraw-  cache <- readIORef (ctxLayoutCache ctx) >>= evaluate >>= makeStableName-  (_, _, changedDraw, _) <- runFrame ctx inp (ui 0.8 blue)-  changed <- snapshotDraw changedDraw-  cache' <- readIORef (ctxLayoutCache ctx) >>= evaluate >>= makeStableName-  assert failed (cache == cache')-  assert failed (first /= changed)-  -- A cache hit must preserve this frame's slider value and paint colors.-  writeIORef (ctxLayoutCache ctx) Nothing-  (_, _, coldDraw, _) <- runFrame ctx inp (ui 0.8 blue)-  assertEq failed changed =<< snapshotDraw coldDraw+      ui (boxColor, value, fontCol, iid, opacity, stray) = column $ do+        box (fixedWH 30 30) boxColor+        void (snd <$> withValue value (slider 0 1))+        labelWith (fontColor fontCol) "paint only"+        imageConfigured defaultImageConfig {icLayout = fixedWH 20 20, icOpacity = opacity} (ImageId iid)+        liftIO $ do+          let na = ctxNodeArena ctx+          i <- addNodeFromLayout na NodeContainer 0 (fixedWH 40 40 defaultLayout)+          setWidgetId na i (WidgetId 777)+          when (stray > 0) $+            registerCustomDrawing ctx (WidgetId 777) 0 $ \_ r ->+              smallArrayFromList [FillRect r (colorRGBA stray 0 0 255)]+      base = (red, 0.2, red, 1, 1, 0)+      -- The case returns the field itself: a selector thunk from fmap would+      -- make two reads of one draw data unequal under 'ptrEq' unoptimised.+      frame s = runFrame ctx inp (ui s) >>= \(_, dd, _) -> pure dd+      -- Two frames of @s@ after @from@: the first draws @s@, and the second+      -- returns the first's draw data when @reused@.+      check from s reused = do+        before <- frame from >>= snapshotDraw+        d1 <- frame s+        d2 <- frame s+        assertEq failed reused (ptrEq d1 d2)+        now <- snapshotDraw d2+        assert failed (s == from || now /= before)+  replicateM_ 2 (frame base)+  forM_+    [ (base, base, True)+    , (base, (blue, 0.2, red, 1, 1, 0), True)+    , (base, (red, 0.8, red, 1, 1, 0), True)+    , (base, (red, 0.2, blue, 1, 1, 0), True)+    , (base, (red, 0.2, red, 2, 1, 0), True)+    , (base, (red, 0.2, red, 1, 0.5, 0), True)+    , (base, (red, 0.2, red, 1, 1, 100), False)+    , ((red, 0.2, red, 1, 1, 100), (red, 0.2, red, 1, 1, 200), False)+    ]+    $ \(from, s, reused) -> check from s reused+  forM_+    [ (setDrawReuse ctx False, setDrawReuse ctx True)+    , (setExplainLayout ctx True, setExplainLayout ctx False)+    , (writeIORef (ctxPaintFull ctx) False, writeIORef (ctxPaintFull ctx) True)+    ]+    $ \(off, on) -> off >> check base base False >> on+  check base base True++-- | In a continuous session not reading damage (as the SDL runner), each+-- frame draws what a never-reusing context draws: hovers, focus, animation+-- steps and wheel notches paint, settled frames reuse.+runContinuousDrawReuseTest :: Context -> IORef Int -> IO ()+runContinuousDrawReuseTest ctx failed = do+  ref <- newContext+  setDrawReuse ref False+  lastDraw <- newIORef Nothing+  let off = (withInputOff 300 200) {inputDeltaTime = 0.016}+      ui (barTo, gapTo) = column $ do+        b <- buttonWith' (fixedWH 60 20) "a"+        -- A drawing of an animated value: no node value or style holds it.+        v <- withKey ("bar" :: String) (animateTo (Tween EaseLinear 0.2 0) barTo)+        void (progressBarWith' (fixedW 100) 12 v)+        -- An animated gap moves the widget below it.+        g <- withKey ("gap" :: String) (animateTo (Tween EaseLinear 0.2 0) gapTo)+        spacer (Fixed 4) (Fixed (4 + 30 * g))+        void (buttonWith' (fixedWH 40 20) "b")+        void $ scrollWith (fixedWH 100 40) $ column $ forM_ [1 .. 10 :: Int] $ \i -> label (T.pack (show i))+        pure b+      frame c inp target = do+        writeIORef (ctxDamageWanted c) False+        (b, dd, _) <- runFrame c inp (ui target)+        writeIORef (ctxDamageWanted c) True+        pure (b, dd)+      -- One frame on both contexts: its response, whether it reused the+      -- last draw, and whether it draws something else.+      step inp target = do+        (b, dd) <- frame ctx inp target+        now <- snapshotDraw dd+        assertEq failed now . snd =<< (traverse snapshotDraw =<< frame ref inp target)+        prev <- readIORef lastDraw+        writeIORef lastDraw (Just (dd, now))+        pure $ case prev of+          Just (lastDd, lastNow) -> (b, ptrEq dd lastDd, now /= lastNow)+          Nothing -> (b, False, True)+      steps n inp target = replicateM n (step inp target)+      reused (_, r, _) = r+      repainted (_, r, changed) = not r && changed+      -- The first frame after a change paints it, and the last has settled.+      paintsThenSettles xs = case (xs, reverse xs) of+        (first : _, final : _) -> repainted first && reused final+        _ -> False+      -- The frame that starts an animation still draws its start; each after+      -- paints a step, and the settled value is reused.+      animates inp target = do+        moving <- steps 6 inp target+        assert failed (not (any reused moving) && all repainted (drop 1 moving))+        assert failed . all reused . drop 16 =<< steps 20 inp target+  settle <- steps 4 off (0, 0)+  let hover = off {inputMousePos = case reverse settle of (b, _, _) : _ -> centerOf b; [] -> V2 0 0}+  assert failed . all reused =<< steps 3 off (0, 0)+  assert failed . paintsThenSettles =<< steps 12 hover (0, 0)+  assert failed . paintsThenSettles =<< ((:) <$> step (tabInp hover) (0, 0) <*> steps 12 hover (0, 0))+  animates hover (1, 0)+  animates hover (1, 1)+  let wheel = off {inputMousePos = V2 30 120, inputScroll = V2 0 (-1)}+  assert failed . all repainted =<< steps 3 wheel (1, 1)+  assert failed . paintsThenSettles =<< steps 12 wheel {inputScroll = V2 0 0} (1, 1)
test/integration/Cases/Combo.hs view
@@ -1,240 +1,241 @@-module Cases.Combo-  ( runComboBlurCommitTest-  , runComboEscapeRevertTest-  , runComboFilterTest-  , runComboHoverHighlightTest-  , runComboKeyboardPickTest-  , runComboMousePickTest-  , runComboScrollbarDragTest-  , runComboWheelScrollTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Combo (tests) where -import Data.IORef (IORef, newIORef)+import Spec import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness (clickPair, hasText, held, keyInp, tabInp, warmup2)+import NanoUI.Internal.Input (onMac)+import NanoUI.Shortcut+import NanoUI.Testing.Sim +tests :: [Spec]+tests =+  [ spec "combo-pick-and-commit" runComboPickTest+  , spec "dropdown-placement" runDropdownPlacementTest+  , spec "dropdown-scrolled-away" runDropdownScrolledAwayTest+  , spec "combo-escape-owned" runComboEscapeOwnedTest+  , simSpec "combo-scrollbar-drag" 320 300 (withValue "" (comboBox' "Fonts" (famOpts 12))) comboScrollbarDrag+  , simSpec "combo-track-press-holds" 320 300 (withValue "" (comboBox' "Fonts" (famOpts 100))) comboTrackHolds+  , simSpec "combo-wheel" 200 360 (withValue "" (comboBox' "Fonts" (famOpts 20 ++ [longOpt]))) comboWheel+  ]+ comboOpts :: [T.Text]-comboOpts = ["Alpha Sans", "Beta Serif", "Gamma Mono", "Delta Round"]+comboOpts = ["Alpha Sans", "Beta Serif", "Gamma Mono", "Delta Round", "Straße Sans"] --- Enough options to overflow the dropdown's visible window (8 rows). Names--- are zero-padded so no name is a substring of another.-comboLongOpts :: [T.Text]-comboLongOpts =-  [ "Fam " <> (if i < 10 then "0" else "") <> T.pack (show i)-  | i <- [1 .. 12 :: Int]+-- | Options numbered with zero padding, so no name is a substring of another.+famOpts :: Int -> [T.Text]+famOpts n = ["Fam " <> (if i < 10 then "0" else "") <> T.pack (show i) | i <- [1 .. n]]++longOpt :: T.Text+longOpt = "A Very Long Font Family Name That Overflows"++type Combo = (Response, T.Text)++-- | Whether the frame committed, and the text.+commitOf :: Combo -> (Bool, T.Text)+commitOf (r, t) = (respChanged r, t)++-- | Each script drives a fresh combo over 'comboOpts' holding its text in+-- the 'Var' it is given.+pickCases :: [(T.Text, Var T.Text -> Sim Combo ())]+pickCases =+  [ -- Typing filters the list, folding case so "STRASSE" finds "Straße",+    -- and never picks anything on its own: Enter with no highlight leaves+    -- the typed text alone.+    ("", \_ -> focused >> typeText "ga" >> expect "Gamma Mono" >> expectNot "Alpha Sans" >> enterLeaves "ga")+  , ("", \_ -> focused >> typeText "STRASSE" >> expect "Straße Sans" >> expectNot "Beta Serif")+  , -- Down from nothing highlights the first row and Enter commits the+    -- highlight.+    ( ""+    , \_ -> do+        _ <- focused >> pressKey KeyDown >> pressKey KeyDown+        enterCommits (True, "Beta Serif")+        expect "Beta Serif"+    )+  , -- A click on a row commits it and blurs the field, which closes the list.+    ( ""+    , \_ -> do+        checkEq (True, "Beta Serif") . commitOf =<< (focused >> click "Beta Serif")+        checkEq (WidgetId 0) =<< focusedId+        expectNot "Alpha Sans"+    )+  , -- Hovering a row highlights it, with the pointer cursor and the hover+    -- background, but commits nothing. The arrows then move the highlight+    -- from it, a pointer that has not moved does not pull it back, and Enter+    -- commits the row the keys reached.+    ( ""+    , \_ -> do+        _ <- focused >> moveTo "Beta Serif"+        checkEq (False, "") . commitOf =<< frame+        checkEq UiCursorPointer =<< pointerCursor+        ss <- spans+        let bgFor needle = [bg | (_, txt, _, bg, _) <- ss, needle `T.isInfixOf` txt]+        check (length (bgFor "Beta Serif") == 1 && bgFor "Beta Serif" /= bgFor "Alpha Sans")+        _ <- pressKey KeyDown >> frame+        enterCommits (True, "Gamma Mono")+    )+  , -- Unfocused, the combo is a search field showing its value, with no+    -- list. Escape cancels an edit: the text reverts to the last commit with+    -- no commit pulse, and the field blurs, closing the list.+    ( "Inter"+    , \_ -> do+        expect "Inter" >> expectNot "Alpha Sans"+        _ <- focused >> typeText "No"+        checkEq (False, "Inter") . commitOf =<< pressKey KeyEscape+        checkEq (WidgetId 0) =<< focusedId+        expectNot "Alpha Sans"+    )+  , -- Typing edits the text without committing, word-wise keys+    -- (Ctrl+Backspace, Option+Backspace on macOS) work as in a text input,+    -- and the frame after a blur commits the text.+    ( ""+    , \_ -> do+        checkEq [(False, "N"), (False, "No")] . map commitOf =<< (focused >> mapM typeText ["N", "o"])+        _ <- typeText " bar" >> chord ((if onMac then alt else ctrl) <> key KeyBackspace)+        checkEq (False, "No ") . commitOf =<< frame+        _ <- pressKey KeyBackspace >> press (At (V2 310 5))+        checkEq [(True, "No"), (False, "No")] . map commitOf =<< sequence [release, frame]+    )+  , -- A value the application writes after a commit shows, but is no commit.+    ( ""+    , \ref -> do+        check . respChanged . fst =<< (focused >> pressKey KeyDown >> pressKey KeyEnter)+        writeV ref "Reset"+        checkEq (False, "Reset") . commitOf =<< frame+    )   ]+  where+    focused = pressKey KeyTab >> settle+    enterCommits want = checkEq want . commitOf =<< pressKey KeyEnter+    enterLeaves txt = checkEq txt . snd =<< pressKey KeyEnter --- Typing filters the suggestion list case-insensitively and never selects--- anything on its own: Enter with no highlight leaves the typed text alone.-runComboFilterTest :: Context -> IORef Int -> IO ()-runComboFilterTest ctx failed = do-  textRef <- newIORef ""-  let inp0 = withInput 320 100-      ui = held textRef (comboBox' "Font" comboOpts)-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (inp0 {inputChars = "ga"}) ui-  overlays <- collectOverlayTextSpans ctx inp0-  assert failed (hasText "Gamma Mono" overlays)-  assert failed (not (hasText "Alpha Sans" overlays))-  ((_, t), _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) ui-  assertEq failed t "ga"+runComboPickTest :: Context -> IORef Int -> IO ()+runComboPickTest _ failed =+  forM_ pickCases $ \(initial, script) -> do+    ctx <- newContext+    ref <- newVar initial+    runSim ctx failed (withInput 320 200) (column (held ref (comboBox' "Font" comboOpts))) (script ref) --- Up/Down move the keyboard highlight (Down from nothing selects the first--- row), and Enter commits it.-runComboKeyboardPickTest :: Context -> IORef Int -> IO ()-runComboKeyboardPickTest ctx failed = do-  let inp0 = withInput 320 100-      ui = comboBox' "Font" comboOpts ""-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (keyInp KeyDown inp0) ui-  _ <- runFrame ctx (keyInp KeyDown inp0) ui-  ((r, t), _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) ui-  assert failed (respChanged r)-  assertEq failed t "Beta Serif"-  spans <- collectTextSpans ctx-  assert failed (hasText "Beta Serif" spans)+-- | A select and a combo box over @opts@, each with its value as the+-- option's text: the select on the second option, the combo empty.+dropdowns :: [(T.Text, [T.Text] -> NanoUI (Response, T.Text))]+dropdowns =+  [ ("select", \opts -> fmap (opts !!) <$> withValue 1 (select' opts))+  , ("combo", \opts -> withValue "" (comboBox' "Font" opts))+  ] --- Clicking a suggestion row commits its option text.-runComboMousePickTest :: Context -> IORef Int -> IO ()-runComboMousePickTest ctx failed = do-  let inp0 = withInput 320 200-      ui = comboBox' "Font" comboOpts ""-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx inp0 ui-  overlays <- collectOverlayTextSpans ctx inp0-  case [r | (r, txt, _, _, _) <- overlays, "Beta Serif" `T.isInfixOf` txt] of-    (rowRect : _) -> do-      let cx = rectX rowRect + rectW rowRect / 2-          cy = rectY rowRect + rectH rowRect / 2-          (press, release) = clickPair inp0 (V2 cx cy)-      _ <- runFrame ctx press ui-      ((r, t), _, _, _) <- runFrame ctx release ui-      assert failed (respChanged r)-      assertEq failed t "Beta Serif"-      -- Picking defocuses the field: the dropdown is visible exactly while-      -- focused, so the menu disappears with the pick.-      focus <- getFocusId ctx-      assertEq failed focus (WidgetId 0)-      overlaysClosed <- collectOverlayTextSpans ctx release-      assert failed (not (hasText "Alpha Sans" overlaysClosed))-    _ -> assert failed False+-- | A dropdown near the floatingWindow's bottom opens above its field, where it+-- fits, and a click there picks the row under it. One that fits on neither+-- side is not slid back over the field, so the click that opens it picks+-- nothing.+runDropdownPlacementTest :: Context -> IORef Int -> IO ()+runDropdownPlacementTest _ failed =+  forM_ dropdowns $ \(name, field) -> do+    let below n opts = column (replicateM_ n (label "line") >> field opts)+    flips <- newContext+    runSim flips failed (withInput 320 200) (below 6 comboOpts) $ do+      (resp, _) <- click . On . fst =<< result+      alpha <- rectOf "Alpha Sans"+      checkEq (name, True) (name, rectY alpha + rectH alpha <= rectY (respRect resp))+      checkEq (name, "Alpha Sans") . (name,) . snd =<< click (Within alpha)+    tall <- newContext+    runSim tall failed (withInput 320 300) (below 4 (famOpts 12)) $ do+      (resp, before) <- result+      checkEq (name, before) . (name,) . snd =<< click (On resp)+      checkEq (name, True) . (name,) =<< labelShown "Fam 01" --- Hovering a suggestion row highlights it (hover paint, becomes the Enter--- target) but never commits by itself; Enter then commits the hovered row.-runComboHoverHighlightTest :: Context -> IORef Int -> IO ()-runComboHoverHighlightTest ctx failed = do-  let inp0 = withInput 320 200-      ui = comboBox' "Font" comboOpts ""-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx inp0 ui-  overlays <- collectOverlayTextSpans ctx inp0-  case [r | (r, txt, _, _, _) <- overlays, "Delta Round" `T.isInfixOf` txt] of-    (rowRect : _) -> do-      let hover =-            inp0-              { inputMousePos = V2 (rectX rowRect + rectW rowRect / 2) (rectY rowRect + rectH rowRect / 2)-              }-      _ <- runFrame ctx hover ui-      -- Hover alone must not commit anything.-      ((r0, t0), _, _, _) <- runFrame ctx hover ui-      assert failed (not (respChanged r0) && T.null t0)-      -- Menu rows show the pointer cursor while hovered.-      ptr <- cursorKindIs ctx hover UiCursorPointer-      assert failed ptr-      -- The hovered row carries the hover background, the others do not.-      overlaysHover <- collectOverlayTextSpans ctx hover-      let bgFor needle = [bg | (_, txt, _, bg, _) <- overlaysHover, needle `T.isInfixOf` txt]-      case (bgFor "Delta Round", bgFor "Alpha Sans") of-        ([dBg], [aBg]) -> assert failed (dBg /= aBg)-        _ -> assert failed False-      -- Enter commits the hovered row.-      ((r1, t1), _, _, _) <- runFrame ctx (keyInp KeyEnter hover) ui-      assert failed (respChanged r1)-      assertEq failed t1 "Delta Round"-    _ -> assert failed False+-- | A dropdown goes with its field when the field scrolls out of view. Held+-- open while the field scrolls just past the top, where the dropdown would+-- still lie in the window, it is not drawn, and neither a release where its+-- row would be nor Enter picks anything.+runDropdownScrolledAwayTest :: Context -> IORef Int -> IO ()+runDropdownScrolledAwayTest _ failed =+  forM_ dropdowns $ \(name, field) -> do+    ctx <- newContext+    let page = field comboOpts <* replicateM_ 30 (label "line")+    runSim ctx failed (withInput 320 300) (column (label "toolbar" >> scrollArea (fixedWH 300 120) page)) $ do+      (sid, (resp, before)) <- result+      V2 cx cy <- press (On resp) >> frame >> (spanCenter <$> rectOf "Gamma Mono")+      let past = rectH (respRect resp) + 20+          picked = checkEq (name, before) . (name,) . snd . snd+      onContext (\c -> setScrollOffsetIO c sid past)+      _ <- frame >> frame+      checkEq (name, False) . (name,) =<< labelShown "Gamma Mono"+      picked =<< (moveTo (At (V2 cx (cy - past))) >> release)+      picked =<< pressKey KeyEnter --- Dragging the vertical scrollbar thumb scrolls the list, and releasing the--- drag over a row must not commit it.-runComboScrollbarDragTest :: Context -> IORef Int -> IO ()-runComboScrollbarDragTest ctx failed = do-  let inp0 = withInput 320 300-      ui = comboBox' "Fonts" comboLongOpts ""-  (resp, _) <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx inp0 ui-  overlays0 <- collectOverlayTextSpans ctx inp0-  assert failed (hasText "Fam 01" overlays0)+-- | Escape on a focused combo showing its list cancels the combo and nothing+-- else, wherever another Escape consumer is declared: a popup's dismiss, a+-- shortcut or a key listener, before it or after it, leaves it alone. So do+-- the listeners while the Escape is held, repeating, and on its release.+runComboEscapeOwnedTest :: Context -> IORef Int -> IO ()+runComboEscapeOwnedTest _ failed =+  forM_ [(w, b) | w <- ["popup", "shortcut", "keyPressed", "keyReleased", "keyHeld"], b <- [True, False]] $+    \(which, before) -> do+      ctx <- newContext+      fired <- newIORef False+      popupOpen <- newVar True+      let listen k = whenM (k KeyEscape) (liftIO (writeIORef fired True))+          other :: NanoUI ()+          other = case which of+            "popup" -> popup popupOpen (defaultPopupConfig (AnchorPoint (V2 300 180))) (label "Panel")+            "shortcut" -> whenM (shortcut (key KeyEscape)) (liftIO (writeIORef fired True))+            "keyPressed" -> listen keyPressed+            "keyReleased" -> listen keyReleased+            _ -> listen keyHeld+          ui = column (when before other >> withValue "" (comboBox' "Font" comboOpts) <* unless before other)+      runSim ctx failed (withInput 320 200) ui $ do+        _ <- pressKey KeyTab >> typeText "a" >> frameWith (chordInp (key KeyEscape))+        _ <- frameWith (keyRepeatInp KeyEscape) >> frameWith (keyUpInp KeyEscape)+        acted <- (||) <$> liftIO (readIORef fired) <*> (not <$> readV popupOpen)+        checkEq (which :: T.Text, before, False) (which, before, acted)+        checkEq (WidgetId 0) =<< focusedId++-- | Dragging the list's scrollbar thumb scrolls it, and releasing the drag+-- over a row commits nothing.+comboScrollbarDrag :: Sim Combo ()+comboScrollbarDrag = do+  (resp, _) <- pressKey KeyTab >> settle+  expect "Fam 01"+  -- The list opens 4 px below the field, its 10 px scrollbar lane at its+  -- right, the thumb at the lane's top.   let Rect rx ry rw rh = respRect resp-      -- Mirrors the overlay geometry: gap 4, item 28, lane 10 wide, rows-      -- flush at the drop rect's top (no outer margin).-      dropY = ry + rh + 4       trackX = rx + rw - 5-      press = inp0 {inputMousePos = V2 trackX (dropY + 200), inputMouseDown = True, inputMousePressed = True}-  _ <- runFrame ctx press ui-  _ <- runFrame ctx press {inputMousePressed = False} ui-  -- Release over a row position (bottom of the list): must not pick.-  let release = press {inputMouseDown = False, inputMouseReleased = True}-  ((r, t), _, _, _) <- runFrame ctx release ui-  assert failed (T.null t && not (respChanged r))-  overlays1 <- collectOverlayTextSpans ctx inp0-  assert failed (not (hasText "Fam 01" overlays1))-  assert failed (hasText "Fam 12" overlays1)---- Typing edits the live text without committing, word-wise editing keys--- (Ctrl+Backspace) work like in the plain text input, and losing focus--- commits the text.-runComboBlurCommitTest :: Context -> IORef Int -> IO ()-runComboBlurCommitTest ctx failed = do-  textRef <- newIORef ""-  let inp0 = withInput 320 200-      ui = column (held textRef (comboBox' "Font" comboOpts))-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  ((rA, tA), _, _, _) <- runFrame ctx (inp0 {inputChars = "N"}) ui-  assertEq failed tA "N"-  assert failed (not (respChanged rA))-  ((rB, tB), _, _, _) <- runFrame ctx (inp0 {inputChars = "o"}) ui-  assertEq failed tB "No"-  assert failed (not (respChanged rB))-  _ <- runFrame ctx (inp0 {inputChars = " bar"}) ui-  _ <- runFrame ctx (inp0 {inputKeys = inputKeysFromList [KeyBackspace], inputModifiers = Modifiers False True False}) ui-  ((rW, tW), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed tW "No "-  assert failed (not (respChanged rW))-  _ <- runFrame ctx (keyInp KeyBackspace inp0) ui-  -- Click far away: focus clears after the UI pass, and the frame after the-  -- blur commits the typed text.-  let away = inp0 {inputMousePos = V2 310 5, inputMouseDown = True, inputMousePressed = True}-  _ <- runFrame ctx away ui-  ((rC, tC), _, _, _) <- runFrame ctx inp0 {inputMouseReleased = True} ui-  assertEq failed tC "No"-  assert failed (respChanged rC)-  ((rD, _), _, _, _) <- runFrame ctx inp0 ui-  assert failed (not (respChanged rD))+      dropY = ry + rh + 4+  checkEq (False, "") . commitOf =<< drag (At (V2 trackX (dropY + 10))) (At (V2 trackX (dropY + 200))) 1+  expectNot "Fam 01" >> expect "Fam 12" --- Unfocused, the combo is just a search field: the value is visible and no--- dropdown overlay exists. Escape cancels an edit: the live text reverts to--- the last committed value without a commit pulse, and the dropdown closes.-runComboEscapeRevertTest :: Context -> IORef Int -> IO ()-runComboEscapeRevertTest ctx failed = do-  textRef <- newIORef "Inter"-  let inp0 = withInput 320 200-      ui = held textRef (comboBox' "Font" comboOpts)-  (r0, t0) <- warmup2 ctx inp0 ui-  assertEq failed t0 "Inter"-  assert failed (not (respChanged r0))-  overlays0 <- collectOverlayTextSpans ctx inp0-  assert failed (not (hasText "Alpha Sans" overlays0))-  spans0 <- collectTextSpans ctx-  assert failed (hasText "Inter" spans0)-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (inp0 {inputChars = "No"}) ui-  ((r, t), _, _, _) <- runFrame ctx (keyInp KeyEscape inp0) ui-  assert failed (not (respChanged r))-  assertEq failed t "Inter"-  focus <- getFocusId ctx-  assertEq failed focus (WidgetId 0)-  overlays <- collectOverlayTextSpans ctx inp0-  assert failed (not (hasText "Alpha Sans" overlays))+-- | A press on the scrollbar track below the thumb jumps the list there, and+-- holding the button still keeps the list where the jump put it.+comboTrackHolds :: Sim Combo ()+comboTrackHolds = do+  (resp, _) <- pressKey KeyTab >> settle+  -- The list opens 4 px below the field, its scrollbar lane at its right.+  let Rect rx ry rw rh = respRect resp+      rows = (\ss -> [spanLabel t | (_, t, _, _, _) <- ss, "Fam " `T.isPrefixOf` spanLabel t]) <$> spans+  jumped <- press (At (V2 (rx + rw - 5) (ry + rh + 4 + 120))) >> rows+  check ("Fam 01" `notElem` jumped)+  checkEq jumped =<< (frame >> rows) --- The wheel scrolls the suggestion list while the pointer is over the open--- dropdown: a horizontal wheel shifts rows that overflow the dropdown width--- (clamped), and a vertical notch slides the window past the first rows.-runComboWheelScrollTest :: Context -> IORef Int -> IO ()-runComboWheelScrollTest ctx failed = do-  let inp0 = withInput 200 260-      long = "A Very Long Font Family Name That Overflows"-      ui = comboBox' "Fonts" (comboLongOpts ++ [long]) ""-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx inp0 ui-  overlays0 <- collectOverlayTextSpans ctx inp0-  assert failed (hasText "Fam 01" overlays0)-  assert failed (not (hasText "Fam 09" overlays0))-  case [r | (r, txt, _, _, _) <- overlays0, "Fam 01" `T.isInfixOf` txt] of-    (rowRect : _) -> do-      let overList = inp0 {inputMousePos = V2 (rectX rowRect + 4) (rectY rowRect + rectH rowRect / 2)}-      _ <- runFrame ctx overList ui-      _ <- runFrame ctx overList {inputScroll = V2 5 0} ui-      overlaysX <- collectOverlayTextSpans ctx overList-      case [r | (r, txt, _, _, _) <- overlaysX, "Fam 01" `T.isInfixOf` txt] of-        (after : _) -> assert failed (rectX after < rectX rowRect - 50)-        _ -> assert failed False-      -- The x-shift is clamped: a huge wheel does not push rows out of reach.-      _ <- runFrame ctx overList {inputScroll = V2 1000 0} ui-      overlaysClamped <- collectOverlayTextSpans ctx overList-      assert failed (hasText "Fam 01" overlaysClamped)-      _ <- runFrame ctx overList {inputScroll = V2 0 1} ui-      overlays1 <- collectOverlayTextSpans ctx overList-      -- One wheel notch scrolls three rows past "Fam 01".-      assert failed (not (hasText "Fam 01" overlays1))-      assert failed (hasText "Fam 04" overlays1)-      assert failed (hasText "Fam 11" overlays1)-    _ -> assert failed False+-- | The wheel over the open list scrolls it: a notch three rows, and a+-- trackpad's eighths of a notch add up to as much. A horizontal wheel shifts+-- rows that overflow the list's width, clamped so a huge one keeps them in+-- reach. Scrolled to its end, a wheel moves nothing and asks for no frame.+comboWheel :: Sim Combo ()+comboWheel = do+  _ <- pressKey KeyTab >> settle+  expect "Fam 01" >> expectNot "Fam 09"+  Rect x0 y0 _ h0 <- rectOf "Fam 01"+  let over = At (V2 (x0 + 4) (y0 + h0 / 2))+  _ <- wheel over (V2 0 1)+  expectNot "Fam 01" >> expect "Fam 04" >> expect "Fam 11"+  replicateM_ 8 (frameWith (\i -> i {inputScroll = V2 0 0.125}))+  expectNot "Fam 06" >> expect "Fam 07"+  before <- rectOf "Fam 07"+  _ <- frameWith (\i -> i {inputScroll = V2 5 0})+  checkLt 50 . (rectX before -) . rectX =<< rectOf "Fam 07"+  _ <- frameWith (\i -> i {inputScroll = V2 1000 0})+  expect "Fam 07"+  _ <- frameWith (\i -> i {inputScroll = V2 0 10}) >> frame+  _ <- frameWith (\i -> i {inputScroll = V2 0 1})+  check . not =<< wantsFrame+  expect "Fam 20"
test/integration/Cases/ContextMenu.hs view
@@ -1,134 +1,190 @@-module Cases.ContextMenu-  ( runContextMenuOpenTest-  , runContextMenuScrollPosTest-  , runContextMenuDisabledRowTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.ContextMenu (tests) where -import Control.Monad (void)-import Data.IORef (IORef)+import Spec+import Data.IntMap.Strict qualified as IM+import Data.Maybe (isJust, listToMaybe) import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, evalUi, withInput)-import NanoUI.Testing.Harness (centerOf, clickPair, rightClickPair, spanCenter, warmup2)+import NanoUI.Testing.Sim +tests :: [Spec]+tests =+  [ simSpec "context-menu-open" 640 480 menuUi contextMenuOpen+  , simSpec "overlay-scroll-pos" 200 200 scrolledUi overlayScrollPos+  , simSpec "context-menu-rows" 640 480 rowsUi contextMenuRows+  , simSpec "context-menu-taller-than-window" 400 300 tallUi contextMenuTall+  , simSpec "menu-button-popup-toggle" 400 300 dropDownUi menuButtonToggle+  , spec "popup-point-flip" runPopupPointFlipTest+  , spec "popup-anchor-moved" runPopupAnchorMovedTest+  ]++-- | Right-click the target and let the menu appear.+openOn :: Target -> Sim a ()+openOn t = rightClick t >> void settle+ menuUi :: NanoUI (Response, Maybe (Response, Response)) menuUi = column $ do   btn <- button' "Target Button"-  mInside <- contextMenu btn $ do-    cut <- menuItem' "Cut"-    copy <- menuItem' "Copy"-    pure (cut, copy)+  mInside <- contextMenu btn ((,) <$> menuItem' "Cut" <*> menuItem' "Copy")   pure (btn, mInside) -openMenu :: Context -> IORef Int -> Input -> IO (Response, Maybe (Response, Response))-openMenu ctx failed inp0 = do-  (btnWarm, _) <- warmup2 ctx inp0 menuUi-  let (inpRightDown, inpRightUp) = rightClickPair inp0 (centerOf btnWarm)-  ((btnDown, _), _, _, _) <- runFrame ctx inpRightDown menuUi-  assert failed (not (respRightClicked btnDown))-  ((btnUp, mInside), _, _, _) <- runFrame ctx inpRightUp menuUi-  pure (btnUp, mInside)+-- | A right click opens the menu on its release; a left click or a right+-- press outside dismisses it.+contextMenuOpen :: Sim (Response, Maybe (Response, Response)) ()+contextMenuOpen = do+  checkEq False . isJust . snd =<< result+  (down, _) <- pressButton MouseRight "Target Button"+  check (not (respRightClicked down))+  (up, inside) <- releaseButton MouseRight+  check (respRightClicked up && isJust inside)+  checkEq False . isJust . snd =<< click (At (V2 500 400))+  openOn "Target Button"+  _ <- pressButton MouseRight (At (V2 500 400))+  checkEq False . isJust . snd =<< releaseButton MouseRight -runContextMenuOpenTest :: Context -> IORef Int -> IO ()-runContextMenuOpenTest ctx failed = do-  let inp0 = withInput 640 480-  (btn0, mInside0) <- evalUi ctx inp0 menuUi-  assert failed (not (respRightClicked btn0))-  assert failed (case mInside0 of Nothing -> True; _ -> False)+scrolledUi :: NanoUI (WidgetId, (Response, Maybe Bool))+scrolledUi = scrollArea (fillW . fixedH 80) $ column $ do+  replicateM_ 40 (label "pad line")+  btn <- button' "Target"+  tooltipConfigured defaultTooltipConfig {tooltipDelay = 0} btn "Scrolled tip"+  cut <- contextMenu btn (menuItem "Scroll Cut")+  replicateM_ 12 (label "tail line")+  pure (btn, cut) -  (btnClicked, mInsideOpen) <- openMenu ctx failed inp0-  assert failed (respRightClicked btnClicked)-  assert failed (case mInsideOpen of Just _ -> True; Nothing -> False)-  -- A left click outside dismisses the menu.-  let (pressOut, releaseOut) = clickPair inp0 (V2 500 400)-  _ <- runFrame ctx pressOut menuUi-  ((_, mAfterClick), _, _, _) <- runFrame ctx releaseOut menuUi-  assert failed (case mAfterClick of Nothing -> True; Just _ -> False)-  -- So does a right press outside.-  _ <- openMenu ctx failed inp0-  let inpRightOut = fst (rightClickPair inp0 (V2 500 400))-  _ <- runFrame ctx inpRightOut menuUi-  ((_, mAfterRight), _, _, _) <- runFrame ctx inp0 menuUi-  assert failed (case mAfterRight of Nothing -> True; Just _ -> False)+-- | A tooltip and a menu on a button in a scrolled area appear where it is+-- drawn, not at its unscrolled layout position: the tip under the button,+-- the menu at the pointer. Picking a row closes the menu.+overlayScrollPos :: Sim (WidgetId, (Response, Maybe Bool)) ()+overlayScrollPos = do+  (sid, _) <- result+  -- Wheel a notch at a time until the button shows with room below it.+  let intoView n = do+        Rect _ sy _ sh <- prevRect sid+        Rect _ by _ bh <- respRect . fst . snd <$> result+        unless (n == (0 :: Int) || (by >= sy + 4 && by + bh + 16 <= sy + sh)) $+          wheel (OnWidget sid) (V2 0 1) >> settle >> intoView (n - 1)+  intoView 200+  (_, (btn, _)) <- result+  off <- scrollOffsetOf sid+  checkGt off 0+  let p = centerOf btn+      bottom = rectY (respRect btn) + rectH (respRect btn)+  -- Hover first: any press closes the tip.+  _ <- moveTo (At p) >> settle+  tipY <- rectY <$> rectOf "Scrolled tip"+  check (abs (tipY - bottom) <= 16)+  check (abs (tipY - bottom) < abs (tipY - (bottom + off)))+  openOn (At p)+  cut <- rectOf "Scroll Cut"+  check (abs (rectY cut - v2Y p) <= 16)+  check (abs (rectY cut - v2Y p) < abs (rectY cut - (rectY (respRect btn) + off)))+  checkEq (Just True) . snd . snd =<< click (Within cut)+  _ <- frame+  expectNot "Scroll Cut" -runContextMenuScrollPosTest :: Context -> IORef Int -> IO ()-runContextMenuScrollPosTest ctx failed = do-  let inp0 = withInput 200 200-      ui =-        scrollArea (fillW . fixedH 80) $-          column $ do-            mapM_ (\_ -> void (label "pad line")) [(1 :: Int) .. 40]-            btn <- button' "Menu Target"-            cut <- contextMenu btn (menuItem "Scroll Cut")-            mapM_ (\_ -> void (label "tail line")) [(1 :: Int) .. 12]-            pure (btn, cut)-  (sid, _) <- warmup2 ctx inp0 ui-  mScroll <- getPrevRect ctx sid-  case mScroll of-    Nothing -> assert failed False-    Just scrollRect@(Rect _ sy _ sh) -> do-      let hover = inp0 {inputMousePos = spanCenter scrollRect}-          wheel = hover {inputScroll = V2 0 1}-          inView btn =-            let y = rectY (respRect btn)-                h = rectH (respRect btn)-             in y >= sy + 4 && y + h + 8 <= sy + sh-          pump = do-            before <- getScrollOffset ctx sid-            _ <- runFrame ctx wheel ui-            after <- getScrollOffset ctx sid-            ((_, (btn, _)), _, _, _) <- runFrame ctx hover ui-            if inView btn || after <= before then pure (after, btn) else pump-      (off, btn1) <- pump-      assert failed (off > 0)-      let clickPos = centerOf btn1-          layoutY = rectY (respRect btn1) + off-          (inpRightDown, inpRightUp) = rightClickPair inp0 clickPos-      _ <- runFrame ctx inpRightDown ui-      _ <- runFrame ctx inpRightUp ui-      spans <- collectOverlayTextSpans ctx inpRightUp-      let hits =-            [ r-            | (r, txt, _, _, _) <- spans-            , "Scroll Cut" `T.isInfixOf` txt-            ]-      case hits of-        [] -> assert failed False-        (r : _) -> do-          let menuY = rectY r-              pick = V2 (rectX r + rectW r / 2) (rectY r + rectH r / 2)-          assert failed (abs (menuY - v2Y clickPos) <= 16)-          assert failed (abs (menuY - v2Y clickPos) < abs (menuY - layoutY))-          let (press, release) = clickPair inp0 pick-          _ <- runFrame ctx press ui-          ((_, (_, picked)), _, _, _) <- runFrame ctx release ui-          assert failed (picked == Just True)-          _ <- runFrame ctx inp0 ui-          spansAfter <- collectOverlayTextSpans ctx inp0-          assert failed (not (any (\(_, txt, _, _, _) -> "Scroll Cut" `T.isInfixOf` txt) spansAfter))+rowsUi :: NanoUI Response+rowsUi = column $ do+  btn <- button' "Target Button"+  _ <- contextMenu btn $ do+    menuHeader "Row Header"+    _ <- menuItem "Row Cut"+    menuItemDisabled "Row Paste"+    _ <- menuItem "Row Undo"+    menuSeparator+    menuItem "Row Redo"+  pure btn --- | A disabled row lines up with the enabled rows around it: its label starts--- at the same x and it takes the same row height.-runContextMenuDisabledRowTest :: Context -> IORef Int -> IO ()-runContextMenuDisabledRowTest ctx failed = do-  let inp0 = withInput 640 480-      ui = column $ do-        btn <- button' "Target Button"-        _ <- contextMenu btn $ do-          _ <- menuItem "Row Cut"-          menuItemDisabled "Row Paste"-          menuItem "Row Undo"-        pure (btn, ())-  (btnWarm, _) <- warmup2 ctx inp0 ui-  let (inpRightDown, inpRightUp) = rightClickPair inp0 (centerOf btnWarm)-  _ <- runFrame ctx inpRightDown ui-  _ <- runFrame ctx inpRightUp ui-  _ <- runFrame ctx inp0 ui-  spans <- collectOverlayTextSpans ctx inp0-  let find t = [r | (r, txt, _, _, _) <- spans, txt == t]-  case (find "Row Cut", find "Row Paste", find "Row Undo") of-    ([cut], [paste], [undo]) -> do-      assert failed (abs (rectX paste - rectX cut) < 0.5)-      assert failed (abs ((rectY paste - rectY cut) - (rectY undo - rectY paste)) < 0.5)-    _ -> assert failed False+-- | A disabled row lines up with the enabled rows around it. A click on a+-- header, a disabled row or a separator keeps the menu open, and a click on+-- a row closes it.+contextMenuRows :: Sim Response ()+contextMenuRows = do+  openOn "Target Button"+  [header, cut, paste, undo, redo] <- mapM rectOf ["Row Header", "Row Cut", "Row Paste", "Row Undo", "Row Redo"]+  check (abs (rectX paste - rectX cut) < 0.5)+  check (abs ((rectY paste - rectY cut) - (rectY undo - rectY paste)) < 0.5)+  let stillOpenAfter t = do+        openOn "Target Button"+        _ <- click t+        _ <- frame+        labelShown "Row Redo"+  check =<< stillOpenAfter (Within header)+  check =<< stillOpenAfter (Within paste)+  check =<< stillOpenAfter (At (V2 (rectX redo + 2) ((rectY undo + rectH undo + rectY redo) / 2)))+  check . not =<< stillOpenAfter (Within cut)++tallUi :: NanoUI (Response, Maybe Bool)+tallUi = column $ do+  btn <- button' "Target Button"+  lastPicked <- contextMenu btn (last <$> mapM (\i -> menuItem (T.pack ("Recent " <> show i))) [1 .. 40 :: Int])+  pure (btn, lastPicked)++-- | A menu taller than the window stays inside it and scrolls, so its last+-- row can be reached and picked.+contextMenuTall :: Sim (Response, Maybe Bool) ()+contextMenuTall = do+  openOn "Target Button"+  first <- rectOf "Recent 1"+  replicateM_ 20 (wheel (Within first) (V2 0 3))+  _ <- frame+  lastRow <- rectOf "Recent 40"+  check (rectY lastRow + rectH lastRow <= 300)+  checkEq (Just True) . snd =<< click (Within lastRow)++-- | A menu title toggling its drop-down on 'respClicked'. Returns the title+-- and whether the drop-down was open going into the frame.+dropDownUi :: NanoUI (Response, Bool)+dropDownUi = column $ do+  openVar <- useVar False+  open <- readVar openVar+  btn <- menuButton' "File" open+  when (respClicked btn) (writeVar openVar (not open))+  let cfg = (defaultPopupConfig (AnchorRect (respRect btn))) {popupPlacement = PlacementBelow, popupOffset = 0}+  (popR, _) <- popup' (constVar open) cfg (menuItem "New")+  when (respClicked popR) (writeVar openVar False)+  pure (btn, open)++-- | Clicking the title of an open drop-down closes it: the press on the title+-- is not a press outside the popup, which would close it for the release to+-- open it again. A click elsewhere still closes it.+menuButtonToggle :: Sim (Response, Bool) ()+menuButtonToggle = do+  title <- On . fst <$> result+  opens <- mapM (\t -> click t >> snd <$> settle) [title, title, title, At (V2 380 280)]+  checkEq [True, False, True, False] opens++-- | A popup placed before or after a point flips to the other side when it+-- would run off the window there and fits on the other side, and it always+-- stays within the window margin.+runPopupPointFlipTest :: Context -> IORef Int -> IO ()+runPopupPointFlipTest _ failed = do+  -- A 100 by 80 popup in an 800 wide window, with a margin of 14.+  let place winH px py = computePopupPosition 800 winH 14 100 80 (AnchorPoint (V2 px py))+  assertEq failed (snd (place 600 400 30 PlacementAbove 4)) 34+  assertEq failed (fst (place 600 30 300 PlacementLeft 4)) 34+  assertEq failed (snd (place 600 400 590 PlacementBelow 20)) 490+  -- Neither side has room: it keeps within the margin rather than flipping.+  assertEq failed (snd (place 200 400 110 PlacementBelow 20)) (200 - 80 - 14)++-- | A popup anchored to a button follows it when a label beside the button+-- grows on a frame nothing else follows up: that frame asks for the one that+-- places the popup at the button's new rect.+runPopupAnchorMovedTest :: Context -> IORef Int -> IO ()+runPopupAnchorMovedTest ctx failed = do+  status <- newIORef ("Loading" :: T.Text)+  let ui = do+        r <- row (liftIO (readIORef status) >>= label >> button' "Filter")+        popup (constVar True) (defaultPopupConfig (AnchorRect (respRect r))) {popupDismissable = False} (label "menu")+        pure r+      popupX = maybe 0 rectX . listToMaybe . IM.elems <$> liftIO (floatingPanelRects ctx)+  runSim ctx failed (withInputOff 640 300) ui $ do+    before <- result+    x0 <- popupX+    liftIO (writeIORef status "Loaded 1,234 items")+    _ <- frame+    check =<< wantsFrame+    after <- settle+    check . not =<< wantsFrame+    x1 <- popupX+    checkGt (rectX (respRect after)) (rectX (respRect before))+    checkEq (rectX (respRect after) - rectX (respRect before)) (x1 - x0)
+ test/integration/Cases/Cursors.hs view
@@ -0,0 +1,182 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Cursors (tests) where++import Spec+import Data.Maybe (fromMaybe, isNothing)+import Data.Text qualified as T+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "cursor-shapes" runCursorShapesTest+  , spec "cursor-shape-ids-layout" runCursorShapeIdsLayoutTest+  , spec "cursor-shape-repeated-pass" runCursorShapeRepeatedPassTest+  , simSpec "cursor-drag-owner" 640 480 dragOwnerUi cursorDragOwner+  ]++-- | A plain drawing: a node with no cursor of its own.+plainArea :: Float -> Float -> NanoUI Response+plainArea w h = drawing (fixedWH w h) (const mempty)++-- | The cursor for the pointer at @p@, from the last frame's solve.+cursorNow :: V2 -> Sim a UiCursorKind+cursorNow p = getInput >>= \i -> onContext (`uiCursorKind` i {inputMousePos = p})++-- | Views that return points, and the cursor each point shows.+shapeCases :: [(NanoUI [V2], [UiCursorKind])]+shapeCases =+  [ -- The innermost scope wins, even when it sets the default arrow. Widgets+    -- keep their own cursors, and a disabled one, having none, shows the+    -- scope's. The scope covers container gaps, and nothing outside it.+    ( row $ do+        rs <- withCursorShape UiCursorMove . columnWith (gap 12) $ sequence+          [ a 30+          , s UiCursorCrosshair (a 30)+          , s UiCursorAllScroll (s UiCursorCell (a 30))+          , s UiCursorDefault (a 30)+          , button' "Press"+          , fst <$> withValue "text" textInput'+          , s UiCursorNotAllowed (disabledWhen True (button' "Delete"))+          , s UiCursorNotAllowed (disabledWhen True (fst <$> withValue "name" textInput'))+          ]+        outside <- a 30+        let Rect bx by _ bh = respRect (rs !! 4)+        pure (map centerOf (rs <> [outside]) <> [V2 (bx + 4) (by + bh + 6)])+    , [ UiCursorMove, UiCursorCrosshair, UiCursorCell, UiCursorDefault, UiCursorPointer, UiCursorText+      , UiCursorNotAllowed, UiCursorNotAllowed, UiCursorDefault, UiCursorMove+      ]+    )+  , -- The shape follows the topmost node: a pinned one, or a later layer.+    (corners <$> col [s UiCursorCrosshair pinned, a 120], [UiCursorCrosshair, UiCursorDefault])+  , (corners <$> col [pinned, s UiCursorCrosshair (a 120)], [UiCursorDefault, UiCursorCrosshair])+  , ( corners <$> layersWith tight (sequence [s UiCursorMove pinned, s UiCursorHelp (a 120), a 60])+    , [UiCursorMove, UiCursorHelp, UiCursorDefault]+    )+  , -- A scoped widget scrolled out of the viewport shows no shape where it+    -- would be.+    ( ends . respRect <$> column (scrollWith (fixedH 100 . fixedW 200) clipped)+    , [UiCursorMove, UiCursorDefault]+    )+  , -- A floating panel over a scope hides its shape. A scope in a window body+    -- applies to its widgets, not the title bar.+    ( column $ do+        (w, inner) <- floatingWindow' (constVar True) "Tools" ((,) <$> label' "Body" <*> s UiCursorCrosshair (a 80))+        d@(Rect dx dy dw dh) <- respRect <$> s UiCursorMove (plainArea 620 380)+        wr@(Rect wx wy ww _) <- rectNow w+        let inset = [V2 x y | x <- [dx + 12, dx + dw - 12], y <- [dy + 12, dy + dh - 12]]+        pure $ case (inner, filter (not . rectContains (rectInflate 8 wr)) inset) of+          (Just (body, scoped), bare : _) | rectContains d (centerOf body) ->+            [bare, centerOf body, centerOf scoped, V2 (wx + ww / 2) (wy + 12)]+          _ -> []+    , [UiCursorMove, UiCursorDefault, UiCursorCrosshair, UiCursorDefault]+    )+  , -- A scope much smaller than the page, whose nodes alone are tested for+    -- the pointer, shows on itself and in a window declared in it, and not on+    -- the list beside it, its labels or the gaps between its rows.+    ( row $ do+        labels <- columnWith (gap 6) . forM [1 .. 30 :: Int] $ \i ->+          row (label' (T.pack ("row " <> show i)) <* plainArea 60 8)+        (area, w) <- s UiCursorCrosshair $+          (,) <$> plainArea 80 60 <*> (fst <$> floatingWindow' (constVar True) "Tools" (label "Body"))+        wr <- rectNow w+        pure $ case [respRect r | r <- labels, isNothing (rectIntersect (rectInflate 8 wr) (respRect r))] of+          l1 : Rect x y _ h : _ -> [spanCenter l1, V2 (x + 2) (y + h + 3), centerOf area, spanCenter wr]+          _ -> []+    , [UiCursorDefault, UiCursorDefault, UiCursorCrosshair, UiCursorCrosshair]+    )+  , -- With a modal open only scopes inside it apply, and a popup in the modal+    -- covers a scope beneath it.+    (modalCase False, [UiCursorMove])+  , (modalCase True, [UiCursorDefault, UiCursorDefault, UiCursorCrosshair])+  ]+  where+    modalCase open = do+      Rect px py _ _ <- respRect <$> s UiCursorMove (plainArea 620 460)+      (_, inner) <- modal' (constVar open) "Dialog" $ do+        area <- s UiCursorCrosshair (a 120)+        let Rect ax ay aw _ = respRect area+            anchor = AnchorPoint (V2 (ax + aw / 2) (ay + 10))+            cfg = (defaultPopupConfig anchor) {popupPlacement = PlacementBelow, popupDismissable = False}+        (area,) . snd <$> popup' (constVar True) cfg (plainArea 60 30)+      let corner = V2 (px + 8) (py + 8)+          apart area = not (rectContains (rectInflate 8 (respRect area)) corner)+      pure . (corner :) $ case inner of+        Just (area, Just body) | apart area && rectContains (respRect area) (centerOf body) ->+          centerOf body : corners [area]+        _ -> []+    rectNow r = askContext >>= \ctx -> liftIO (fromMaybe (Rect 0 0 0 0) <$> getPrevRect ctx (respId r))+    s = withCursorShape+    a = plainArea 200+    pinned = drawing (pinAt 20 20 . fixedWH 60 40) (const mempty)+    col = columnWith (tight . gap 0) . sequence+    corners = map ((\(Rect x y w h) -> V2 (x + w - 10) (y + h - 10)) . respRect)+    clipped = column (plainArea 150 40 >> s UiCursorMove (plainArea 150 80))+    ends (Rect x y w h) = [V2 (x + w / 2) (y + 4), V2 (x + w / 2) (y + h - 4)]++runCursorShapesTest :: Context -> IORef Int -> IO ()+runCursorShapesTest _ failed = forM_ shapeCases $ \(ui, wants) -> do+  ctx <- newContext+  runSim ctx failed (withInputOff 640 600) ui (checkEq wants =<< mapM (cursorAt . At) =<< result)++-- | A scope takes no id and adds no node, so widget ids, state and layout are+-- unchanged. Its shape shows over its node, even read from the solved arena+-- without running a frame, and a frame without the scope drops it.+runCursorShapeIdsLayoutTest :: Context -> IORef Int -> IO ()+runCursorShapeIdsLayoutTest ctx failed = do+  scoped <- newIORef False+  let ui = row $ do+        on <- liftIO (readIORef scoped)+        a <- (if on then withCursorShape UiCursorHelp else id) (plainArea 60 30)+        nVar <- useVar (0 :: Int)+        n <- readVar nVar+        b <- button' "b"+        when (respClicked b) (writeVar nVar (n + 1))+        pure (a, b, n)+      snapshot = do+        (a, b, n) <- result+        rects <- onContext arenaRects+        pure (respId a, respId b, respRect a, respRect b, rects, n)+      setScoped on = liftIO (writeIORef scoped on) >> settle+  runSim ctx failed (withInputOff 640 480) ui $ do+    _ <- click "b"+    before <- snapshot+    (a, _, _) <- setScoped True+    checkEq before =<< snapshot+    checkEq UiCursorHelp =<< cursorNow (centerOf a)+    checkEq UiCursorHelp =<< cursorAt (On a)+    _ <- setScoped False+    checkEq UiCursorDefault =<< cursorAt (On a)++-- | Only scopes from the frame's last view pass count.+runCursorShapeRepeatedPassTest :: Context -> IORef Int -> IO ()+runCursorShapeRepeatedPassTest ctx failed = do+  let inp = withInputOff 640 480+      ui = do+        nVar <- useVar (0 :: Int)+        n <- readVar nVar+        when (n == 0) (writeVar nVar 1)+        d <- column ((if n == 0 then withCursorShape UiCursorMove else id) (plainArea 120 80))+        pure (d, n)+  (d, n) <- evalUi ctx inp ui+  assertEq failed 1 n+  assertJustM failed (getPrevRect ctx (respId d)) $ \r ->+    uiCursorKind ctx inp {inputMousePos = spanCenter r} >>= assertEq failed UiCursorDefault++dragOwnerUi :: NanoUI [Response]+dragOwnerUi = row $ do+  s <- withValue 5 (slider' 0 10)+  f <- withValue "text" textInput'+  g <- withValue "more" textInput'+  b <- button' "Go"+  pure [fst s, fst f, fst g, b]++-- | A drag keeps its owner's cursor over other fields (a slider's grabbing+-- hand, a field's I-beam) and lights up no button it crosses.+cursorDragOwner :: Sim [Response] ()+cursorDragOwner = do+  [s, f, g, b] <- result+  let dragOver from to = (press (On from) >> cursorAt (On to)) <* release+  checkEq UiCursorGrabbing =<< dragOver s f+  checkEq UiCursorText =<< dragOver f g+  _ <- press (On s) >> moveTo (On b)+  check . (/= respId b) =<< hotId
test/integration/Cases/CustomWidget.hs view
@@ -1,312 +1,206 @@-module Cases.CustomWidget-  ( runCustomWidgetMeasureTest-  , runCustomWidgetCursorTest-  , runCustomWidgetInteractionTest-  , runCustomWidgetQueuedClickTest-  , runCustomWidgetContentDamageTest-  , runCustomWidgetContentKeyTest-  , runReferenceKnobTest-  , runDropTargetTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.CustomWidget (tests) where -import Control.Monad (forM_, void)-import Data.IORef (IORef, writeIORef)+import Spec import Data.Primitive.SmallArray qualified as SA-import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Testing-  ( UiCursorKind (..)-  , cursorKindIs-  , newContext-  , runFrame-  , takeDamage-  )-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness (centerOf, clickPair, drawQuads, warmup2, withInputOff)+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..))+import NanoUI.Testing.Sim --- | Verifies custom intrinsic layout measurement via widgetMeasure hook, and--- that the measurement reverts once the hook is gone.-runCustomWidgetMeasureTest :: Context -> IORef Int -> IO ()-runCustomWidgetMeasureTest ctx failed = do-  let inp = withInput 400 400-      ui measure = column $ do-        fst <$> customWidget defaultCustomWidgetSpec-          { widgetMeasure = measure-          , widgetLayout = defaultLayout-          }-  resp <- warmup2 ctx inp (ui (Just $ \_ _ -> (160, 48)))-  let r = respRect resp-  assert failed (rectW r == 160 && rectH r == 48)-  plain <- warmup2 ctx inp (ui Nothing)-  let Rect _ _ pw ph = respRect plain-  assertEq failed (pw, ph) (32, 32)+tests :: [Spec]+tests =+  [ spec "custom-widget-measure" runCustomWidgetMeasureTest+  , spec "custom-widget-pointer" runCustomWidgetPointerTest+  , spec "custom-widget-content" runCustomWidgetContentTest+  , spec "drop-target" runDropTargetTest+  , spec "canvas-text-clipped" runCanvasTextClippedTest+  ] --- | Verifies dynamic cursor resolution on custom widgets.-runCustomWidgetCursorTest :: Context -> IORef Int -> IO ()-runCustomWidgetCursorTest ctx failed = do-  let inp0 = withInput 300 300-      ui = column $ do-        fst <$> customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 80 defaultLayout-          , widgetCursor = Just (\_ -> UiCursorNsResize)-          }-  resp <- warmup2 ctx inp0 ui-  let Rect rx ry rw rh = respRect resp-      hoverInp = inp0 { inputMousePos = centerOf resp }-  _ <- runFrame ctx hoverInp ui-  hoverOk <- cursorKindIs ctx hoverInp UiCursorNsResize-  assert failed hoverOk+red, blue :: Color+red = colorRGBA 255 0 0 255+blue = colorRGBA 0 0 255 255 -  let outInp = inp0 { inputMousePos = V2 (rx + rw + 50) (ry + rh + 50) }-  _ <- runFrame ctx outInp ui-  outOk <- cursorKindIs ctx outInp UiCursorNsResize-  assert failed (not outOk)+-- | A custom widget of this layout, content key and drawing.+custom :: (Layout -> Layout) -> Int -> CustomDrawBuild -> NanoUI Response+custom f key draw =+  fst <$> customWidget defaultCustomWidgetSpec {widgetLayout = f, widgetContent = key, widgetDraw = draw} --- | Verifies interaction state propagation (hover, press, click) and CustomDrawContext.-runCustomWidgetInteractionTest :: Context -> IORef Int -> IO ()-runCustomWidgetInteractionTest ctx failed = do-  let inp0 = withInput 300 300-      ui = column $ do-        customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 40 defaultLayout-          , widgetInteract = \resp cdc _ -> (resp, (cdcHovered cdc, cdcPressed cdc))-          }-  (resp0, _) <- warmup2 ctx inp0 ui-  let pos = centerOf resp0-      (pressInp, releaseInp) = clickPair inp0 pos+-- | A label, then an 80x40 custom widget with this content key and drawing.+afterLabel :: Int -> CustomDrawBuild -> NanoUI Response+afterLabel key draw = column (label "Other" >> custom (fixedWH 80 40) key draw) -  _ <- runFrame ctx pressInp ui-  ((respClick, (hovered, pressed)), _, _, _) <- runFrame ctx releaseInp ui-  assert failed (respClicked respClick)-  assert failed hovered-  assert failed (not pressed)+-- | Draw a rect of the colour.+filled :: Color -> CustomDrawBuild+filled c cdc r = runCanvasFor cdc (drawRect r c) --- | A click the frame queued for a widget whose pointer hit missed still--- reaches custom widgets (regression: their default interaction rebuilt the--- click from hover and release alone, dropping the queued click).-runCustomWidgetQueuedClickTest :: Context -> IORef Int -> IO ()-runCustomWidgetQueuedClickTest ctx failed = do-  let inp0 = (withInput 300 300) {inputMousePos = V2 290 290}-      ui = column $ do-        fromCanvas <- canvas (fixedWH 80 40) (\_ -> pure ())-        fromSpec <- fst <$> customWidget defaultCustomWidgetSpec {widgetLayout = fixedWH 80 40 defaultLayout}-        pure [fromCanvas, fromSpec]-  warm <- warmup2 ctx inp0 ui+-- | Run a frame and decode the quads it drew.+frameQuads :: Context -> Input -> NanoUI a -> IO [(Rect, Color)]+frameQuads ctx inp ui = runFrame ctx inp ui >>= \(_, draw, _) -> drawQuads draw++-- | 'widgetMeasure' sizes a widget and the containers sized from it, as a+-- fresh solve does, even with the arena unchanged. A progress bar takes the+-- caller's width mode.+runCustomWidgetMeasureTest :: Context -> IORef Int -> IO ()+runCustomWidgetMeasureTest ctx failed = do+  let inp = withInput 400 400+      measured m = fst <$> customWidget defaultCustomWidgetSpec {widgetMeasure = m, widgetLayout = id}+      sizeOf ui = (\(Rect _ _ w h) -> (w, h)) . respRect <$> warmup2 ctx inp ui+  mapM (sizeOf . column . measured) [Just (\_ _ -> (160, 48)), Nothing, Just (\_ _ -> (160, 48))]+    >>= assertEq failed [(160, 48), (32, 32), (160, 48)]+  -- The inner column takes its width from the widget, and the label after+  -- it in the row sits where that width ends.+  let parent w = column . row $ column (measured (Just (\_ _ -> (w, 48)))) <* label "after"+  fresh <- newContext+  _ <- sizeOf (parent 120) >> sameAsFreshSolve failed fresh ctx inp (parent 240)+  sizeOf (parent 240) >>= assertEq failed 240 . fst+  let bar f = rowWith (fixedW 300 . tight) (progressBarWith' f 12 0.3)+  (fullW, _) <- sizeOf (bar id)+  sizeOf (bar (percent 50)) >>= assertEq failed (fullW / 2, 12)++-- | 'widgetCursor' (kept through a drag off the widget), 'widgetInteract',+-- a queued post-layout click, and the reference knob, which a pinned button+-- covers for drags and the wheel ('useDrag2DOn' uses the response).+runCustomWidgetPointerTest :: Context -> IORef Int -> IO ()+runCustomWidgetPointerTest ctx failed = do+  let inp = withInput 300 300+      edged = withCursorShape UiCursorHidden . column $ fst <$> customWidget defaultCustomWidgetSpec+        { widgetLayout = fixedWH 80 80+        , widgetCursor = Just $ \_ (Rect x _ w _) (V2 px _) -> if px > x + w - 10 then UiCursorEwResize else UiCursorDefault+        }+  runSim ctx failed inp edged $ do+    Rect rx ry rw rh <- respRect <$> result+    let onEdge = At (V2 (rx + rw - 4) (ry + rh / 2))+        away = At (V2 (rx + rw + 50) (ry + rh + 50))+    checkEq UiCursorEwResize =<< cursorAt onEdge+    checkEq UiCursorHidden =<< cursorAt (Within (Rect rx ry rw rh))+    _ <- press onEdge+    checkEq UiCursorEwResize =<< cursorAt away+    _ <- release+    checkEq UiCursorDefault =<< cursorAt away+  let interacting = column $ customWidget defaultCustomWidgetSpec+        { widgetLayout = fixedWH 80 40+        , widgetInteract = \resp cdc _ -> (resp, (cdcHovered cdc, cdcPressed cdc))+        }+  runSim ctx failed inp interacting $ do+    (resp, (hovered, pressed)) <- click . On . fst =<< result+    check (respClicked resp && hovered && not pressed)+  let queued = column $ (\a b -> [a, b]) <$> canvas (fixedWH 80 40) (\_ -> pure ()) <*> custom (fixedWH 80 40) 0 (\_ _ -> mempty)+      away = inp {inputMousePos = V2 290 290}+  warm <- warmup2 ctx away queued   forM_ (zip [0 :: Int ..] warm) $ \(i, resp0) -> do     writeIORef (ctxClickedId ctx) (respId resp0)-    (resps, _, _, _) <- runFrame ctx inp0 ui-    assert failed (map respClicked resps == [j == i | j <- [0 .. length resps - 1]])---- | A custom widget whose drawing reads state from outside the spec repaints--- when that state changes, though its rect and hover/press state stay the--- same (regression: its ops were cached on those alone, so a table header--- kept drawing its sort arrow after another column took the sort, and the--- frame damaged nothing).-runCustomWidgetContentDamageTest :: Context -> IORef Int -> IO ()-runCustomWidgetContentDamageTest ctx failed = do-  let inp = withInputOff 400 300-      red = colorRGBA 255 0 0 255-      blue = colorRGBA 0 0 255 255-      ui on = column $ do-        label "Other"-        fst <$> customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 40 defaultLayout-          , widgetDraw = \_ r -> runCanvas (drawRect r (if on then red else blue))-          }-  resp <- warmup2 ctx inp (ui False)-  _ <- takeDamage ctx-  (_, _, draw, _) <- runFrame ctx inp (ui True)-  dmg <- takeDamage ctx-  case dmg of-    DamageClip clip -> assert failed (coversRect clip (respRect resp))-    DamageFull -> assert failed False-  quads <- drawQuads draw-  assert failed (any ((== red) . snd) quads)-  assert failed (not (any ((== blue) . snd) quads))-  -- The built-in progress bar captures its fraction the same way.-  let bar frac = column (progressBar' frac)-  barResp <- warmup2 ctx inp (bar 0.2)-  _ <- takeDamage ctx-  _ <- runFrame ctx inp (bar 0.8)-  barDmg <- takeDamage ctx-  case barDmg of-    DamageClip clip -> assert failed (coversRect clip (respRect barResp))-    DamageFull -> assert failed False+    resps <- evalUi ctx away queued+    assertEq failed [j == i | j <- [0 .. length resps - 1]] (map respClicked resps)+  value <- newVar (0 :: Float)+  let covered = columnWith tight (fst <$> held value (knobWith' id 60 0 100) <* buttonWith' (pinAt 0 0 . fixedWH 30 60) "x")+  runSim ctx failed (withInputOff 300 300) covered $ do+    Rect kx ky _ kh <- respRect <$> result+    let moved how p = writeV value 50 >> how p >> readV value+        dragUp (V2 px py) = moveTo (At (V2 px py)) >> drag (At (V2 px py)) (At (V2 px (py - 40))) 1+        wheelOn p = wheel (At p) (V2 0 3)+        (onButton, onKnob) = (V2 (kx + 15) (ky + kh / 2), V2 (kx + 45) (ky + kh / 2))+    checkEq [50, 50] =<< mapM (\how -> moved how onButton) [dragUp, wheelOn]+    check . (> 50) =<< moved dragUp onKnob+    check . (/= 50) =<< moved wheelOn onKnob --- | A content key is taken at its word: while it is unchanged the widget--- neither rebuilds its ops nor repaints, a new key does both, and a theme--- change rebuilds them even though the key did not move, since the ops can--- read the theme.-runCustomWidgetContentKeyTest :: Context -> IORef Int -> IO ()-runCustomWidgetContentKeyTest ctx failed = do+-- | An unkeyed drawing repaints when captured state changes. A content key+-- is taken at its word, except that disabling or a new theme rebuilds the+-- ops (a scope's theme without touching font metrics), and a widget that+-- only moved draws at its new place.+runCustomWidgetContentTest :: Context -> IORef Int -> IO ()+runCustomWidgetContentTest ctx failed = do   let inp = withInputOff 400 300-      red = colorRGBA 255 0 0 255-      blue = colorRGBA 0 0 255 255-      ui key on = column $ do-        label "Other"-        fst <$> customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 40 defaultLayout-          , widgetContent = key-          , widgetDraw = \_ r -> runCanvas (drawRect r (if on then red else blue))-          }-  resp <- warmup2 ctx inp (ui 1 False)-  _ <- takeDamage ctx--  -- Same key, different captured state: the ops it already has stand.-  (_, _, keptDraw, _) <- runFrame ctx inp (ui 1 True)-  keptDmg <- takeDamage ctx-  keptQuads <- drawQuads keptDraw-  assert failed (any ((== blue) . snd) keptQuads)-  case keptDmg of-    DamageClip clip -> assert failed (not (coversRect clip (respRect resp)))-    DamageFull -> assert failed False--  -- A new key rebuilds and repaints.-  (_, _, freshDraw, _) <- runFrame ctx inp (ui 2 True)-  freshDmg <- takeDamage ctx-  freshQuads <- drawQuads freshDraw-  assert failed (any ((== red) . snd) freshQuads)-  case freshDmg of-    DamageClip clip -> assert failed (coversRect clip (respRect resp))-    DamageFull -> assert failed False--  -- Disabling the widget repaints it: the ops rebuild in their disabled form,-  -- and disabled is not one of the roles damage already follows.+      ui key on = afterLabel key (filled (if on then red else blue))+      colours c view = map snd <$> frameQuads c inp view+      repaintedIn c r = takeDamage c >>= assert failed . (`clipCovers` respRect r)+  resp <- warmup2 ctx inp (ui 0 False)+  colours ctx (ui 0 True) >>= \cs -> assert failed (red `elem` cs && blue `notElem` cs)+  repaintedIn ctx resp+  bar <- warmup2 ctx inp (column (progressBarWith' id 12 0.2))+  _ <- runFrame ctx inp (column (progressBarWith' id 12 0.8))+  repaintedIn ctx bar+  _ <- warmup2 ctx inp (ui 1 False)+  colours ctx (ui 1 True) >>= assert failed . elem blue+  takeDamage ctx >>= assert failed . not . (`damageCovers` respRect resp)+  colours ctx (ui 2 True) >>= assert failed . elem red+  repaintedIn ctx resp   let grey = colorRGBA 128 128 128 255       dimmable off = column $ do         label "Other"-        disabledWhen off $ fst <$> customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 40 defaultLayout-          , widgetContent = 4-          , widgetDraw = \cdc r -> runCanvas (drawRect r (if cdcDisabled cdc then grey else blue))-          }-  disabledCtx <- newContext-  dresp <- warmup2 disabledCtx inp (dimmable False)-  _ <- takeDamage disabledCtx-  (_, _, disabledDraw, _) <- runFrame disabledCtx inp (dimmable True)-  disabledDmg <- takeDamage disabledCtx-  disabledQuads <- drawQuads disabledDraw-  assert failed (any ((== grey) . snd) disabledQuads)-  case disabledDmg of-    DamageClip clip -> assert failed (coversRect clip (respRect dresp))-    DamageFull -> pure ()--  -- A keyed widget that only moved still draws at its new place: paint-  -- translates the ops it kept.-  let moved lead = column $ do-        spacer Fit (Fixed lead)-        fst <$> customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 40 defaultLayout-          , widgetContent = 5-          , widgetDraw = \_ r -> runCanvas (drawRect r red)-          }-  settled <- warmup2 ctx inp (moved 40)-  let Rect _ my _ _ = respRect settled+        disabledWhen off $ custom (fixedWH 80 40) 4 $ \cdc r -> filled (if cdcDisabled cdc then grey else blue) cdc r+  dimCtx <- newContext+  dimmed <- warmup2 dimCtx inp (dimmable False)+  colours dimCtx (dimmable True) >>= assert failed . elem grey+  takeDamage dimCtx >>= assert failed . (`damageCovers` respRect dimmed)+  let moved lead = column (spacer Fit (Fixed lead) >> custom (fixedWH 80 40) 5 (filled red))+  Rect _ my _ _ <- respRect <$> warmup2 ctx inp (moved 40)   _ <- warmup2 ctx inp (moved 10)-  (_, _, movedDraw, _) <- runFrame ctx inp (moved 40)-  movedQuads <- drawQuads movedDraw-  assert failed (any (\(Rect _ qy _ _, c) -> c == red && abs (qy - my) < 0.5) movedQuads)--  -- Swapping the theme rebuilds a keyed widget that draws from the theme,-  -- through either theme entry point.-  let accent2 = colorRGBA 7 8 9 255-      accent3 = colorRGBA 11 12 13 255-      themedUi = column $ do-        label "Other"-        fst <$> customWidget defaultCustomWidgetSpec-          { widgetLayout = fixedWH 80 40 defaultLayout-          , widgetContent = 3-          , widgetDraw = \cdc r -> runCanvas (drawRect r (themeAccent (cdcTheme cdc)))-          }+  frameQuads ctx inp (moved 40) >>= assert failed . any (\(Rect _ qy _ _, c) -> c == red && abs (qy - my) < 0.5)+  let (accent2, accent3) = (colorRGBA 7 8 9 255, colorRGBA 11 12 13 255)+      themedUi = afterLabel 3 (\cdc -> filled (themeAccent (cdcTheme cdc)) cdc)   _ <- warmup2 ctx inp themedUi-  theme0 <- getTheme ctx-  setTheme ctx theme0 {themeAccent = accent2}-  (_, _, themedDraw, _) <- runFrame ctx inp themedUi-  themedQuads <- drawQuads themedDraw-  assert failed (any ((== accent2) . snd) themedQuads)+  theme0 <- getThemeIO ctx+  setThemeIO ctx theme0 {themeAccent = accent2}+  colours ctx themedUi >>= assert failed . elem accent2   ctx3 <- withTheme ctx theme0 {themeAccent = accent3}-  (_, _, withThemeDraw, _) <- runFrame ctx3 inp themedUi-  withThemeQuads <- drawQuads withThemeDraw-  assert failed (any ((== accent3) . snd) withThemeQuads)-  setTheme ctx theme0---- | Whether a damage clip covers a widget's rect.-coversRect :: Rect -> Rect -> Bool-coversRect (Rect cx cy cw ch) (Rect x y w h) =-  cx <= x && cy <= y && cx + cw >= x + w && cy + ch >= y + h---- | Verifies the reference rotary knob widget.-runReferenceKnobTest :: Context -> IORef Int -> IO ()-runReferenceKnobTest ctx failed = do-  let inp0 = withInput 300 300-      ui = column $ knob' 0 100 25-  (resp0, val0) <- warmup2 ctx inp0 ui-  assert failed (val0 == 25)--  let pos = centerOf resp0-      dragStart = inp0 { inputMousePos = pos, inputMouseDown = True, inputMousePressed = True }-      -- Drag upward (negative dy in screen coords) to increase knob value-      dragUp = inp0 { inputMousePos = V2 (v2X pos) (v2Y pos - 30), inputMouseDown = True, inputMousePressed = False }-      release = inp0 { inputMousePos = V2 (v2X pos) (v2Y pos - 30), inputMouseDown = False, inputMouseReleased = True }--  _ <- runFrame ctx dragStart ui-  ((respDragged, valDragged), _, _, _) <- runFrame ctx dragUp ui-  assert failed (valDragged > 25)-  assert failed (respChanged respDragged)-  void $ runFrame ctx release ui+  colours ctx3 themedUi >>= assert failed . elem accent3+  setThemeIO ctx theme0+  let scoped c = styled (accentColor c) themedUi+  _ <- warmup2 ctx inp (scoped accent2)+  gen <- readIORef (ctxMetricGen ctx)+  colours ctx (scoped accent3) >>= assert failed . elem accent3+  assertEq failed gen =<< readIORef (ctxMetricGen ctx) --- | Verifies the composable drag-and-drop hook: hover, file, text, and bounds.+-- | 'useDrop' follows the last drag position (SDL may report a drop at+-- (0, 0)), clears it once complete, and gets nothing under a modal or a+-- window on top. runDropTargetTest :: Context -> IORef Int -> IO () runDropTargetTest ctx failed = do-  let inp0 = withInput 300 300-      bounds = Rect 10 10 100 100+  let inp = withInput 300 300       dropPoint = V2 60 60-      ui = column (useDrop bounds)-      dropsInp ds = inp0 {inputDrops = SA.smallArrayFromList ds}-  _ <- warmup2 ctx inp0 ui--  let beginInp = dropsInp [DropEvent DropBegin Nothing ""]-  (tgtBegin, _, _, _) <- runFrame ctx beginInp ui-  assert failed (not (dropHovered tgtBegin))--  let hoverInp = dropsInp [DropEvent DropPosition (Just dropPoint) ""]-  (tgtHover, _, _, _) <- runFrame ctx hoverInp ui-  assert failed (dropHovered tgtHover)-  assert failed (dropPosition tgtHover == Just dropPoint)--  -- Payload coordinates are ignored; attribution follows the last drag position.-  let dropInp =-        dropsInp-          [ DropEvent DropFile (Just dropPoint) "/tmp/a.txt"-          , DropEvent DropText (Just dropPoint) "hello"-          ]-  (tgtDrop, _, _, _) <- runFrame ctx dropInp ui-  assert failed (dropReceived tgtDrop)-  assert failed (dropFiles tgtDrop == ["/tmp/a.txt"])-  assert failed (dropTexts tgtDrop == ["hello"])--  -- A drop whose coordinates SDL reports as (0,0) (no final position seen)-  -- still lands on the target the pointer was hovering.-  let originDrop =-        dropsInp-          [ DropEvent DropFile (Just (V2 0 0)) "/tmp/origin.txt"-          , DropEvent DropComplete Nothing ""-          ]-  (tgtOrigin, _, _, _) <- runFrame ctx originDrop ui-  assert failed (dropFiles tgtOrigin == ["/tmp/origin.txt"])--  -- The completing drop clears hover state.-  (tgtDone, _, _, _) <- runFrame ctx inp0 ui-  assert failed (not (dropHovered tgtDone))+      ui = column (useDrop (Rect 10 10 100 100))+      dropping ds = evalUi ctx inp {inputDrops = SA.smallArrayFromList ds} ui+      file p f = DropEvent DropFile (Just p) f+      (begin, complete) = (DropEvent DropBegin Nothing "", DropEvent DropComplete Nothing "")+  _ <- warmup2 ctx inp ui+  dropping [begin] >>= assert failed . not . dropHovered+  dropping [DropEvent DropPosition (Just dropPoint) ""] >>= \t ->+    assert failed (dropHovered t && dropPosition t == Just dropPoint)+  dropping [file dropPoint "/tmp/a.txt", DropEvent DropText (Just dropPoint) "hello"] >>= \t ->+    assertEq failed (True, ["/tmp/a.txt"], ["hello"]) (dropReceived t, dropFiles t, dropTexts t)+  dropping [file (V2 0 0) "/tmp/origin.txt", complete] >>= \t ->+    assertEq failed (["/tmp/origin.txt"], Just dropPoint) (dropFiles t, dropPosition t)+  dropping [] >>= \t -> assertEq failed (False, Nothing) (dropHovered t, dropPosition t)+  mapM_ dropping [[begin], [DropEvent DropPosition (Just (V2 250 250)) ""]]+  dropping [file (V2 250 250) "/tmp/out.txt", complete] >>= \t -> assertEq failed (False, []) (dropReceived t, dropFiles t)+  open <- newVar True+  let dropAt p =+        (withInput 400 400) {inputDrops = SA.smallArrayFromList [begin, DropEvent DropPosition (Just p) "", file p "a.txt", complete]}+      stacked overlay = (,) <$> useDrop (Rect 0 0 400 400) <*> overlay open (useDrop (Rect 0 0 400 400))+      files c overlay p = (\(page, (_, inner)) -> (dropFiles page, dropFiles <$> inner)) <$> evalUi c (dropAt p) (stacked overlay)+  (_, (onModal, _)) <- warmup2 ctx (withInput 400 400) (stacked (`modal'` "Modal"))+  assertEq failed ([], Just ["a.txt"]) =<< files ctx (`modal'` "Modal") (centerOf onModal)+  assertEq failed ([], Just []) =<< files ctx (`modal'` "Modal") (V2 2 2)+  c <- newContext+  (_, (onWindow, _)) <- warmup2 c (withInput 400 400) (stacked (`floatingWindow'` "Window"))+  assertEq failed ([], Just ["a.txt"]) =<< files c (`floatingWindow'` "Window") (centerOf onWindow) -  -- A fresh drag that moves outside the target no longer delivers to it.-  _ <- runFrame ctx (dropsInp [DropEvent DropBegin Nothing ""]) ui-  _ <- runFrame ctx (dropsInp [DropEvent DropPosition (Just (V2 250 250)) ""]) ui-  let outInp =-        dropsInp-          [ DropEvent DropFile (Just (V2 250 250)) "/tmp/out.txt"-          , DropEvent DropComplete Nothing ""-          ]-  (tgtOut, _, _, _) <- runFrame ctx outInp ui-  assert failed (not (dropReceived tgtOut))-  assert failed (null (dropFiles tgtOut))+runCanvasTextClippedTest :: Context -> IORef Int -> IO ()+runCanvasTextClippedTest _ failed = do+  let cdc = CustomDrawContext False False False False False defaultTheme (monospaceMetrics 10)+      wideFm = monospaceMetrics 16+      narrowFm = monospaceMetrics 8+      monoFont = defaultTextFont {textFontVariant = FontMono}+      ops =+        foldr (:) [] . runCanvasFor cdc $ do+          drawTextClipped (Rect 0 0 80 20) AlignStart AlignMiddle "VeryLongIdentifierName" red+          drawTextClippedWith wideFm monoFont EllipsisMiddle (Rect 0 24 160 20) AlignStart AlignMiddle "Data.Map.Internal.insert" blue+          drawTextClippedWith narrowFm monoFont EllipsisMiddle (Rect 0 48 160 20) AlignStart AlignMiddle "Data.Map.Internal.insert" blue+      texts = [t | DrawTextAligned _ _ _ _ _ _ t _ <- ops]+  case texts of+    [endT, wideMid, narrowMid] -> do+      assert failed ("..." `T.isSuffixOf` endT)+      assert failed ("..." `T.isInfixOf` wideMid && "..." `T.isInfixOf` narrowMid)+      -- Explicit FontMetrics controls truncation width: wider glyphs keep fewer characters.+      assertLt failed (T.length wideMid) (T.length narrowMid)+    _ -> assertEq failed 3 (length texts)
test/integration/Cases/Damage.hs view
@@ -1,230 +1,353 @@-module Cases.Damage-  ( runDamageBoundsResolutionTest-  , runExplicitDamageWidgetTest-  , runDamageQueueClearedPerFrameTest-  , runStateChangeDamageTest-  , runOrphanAnimationDamageSettlesTest-  , runVersionedDrawingDamageTest-  , runClipFrameBackdropTest-  , runTextAreaSelectAllDamageTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Damage (tests) where -import Data.IORef (IORef, readIORef, writeIORef)-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness (centerOf, drawQuads, runClick, tabInp, warmup2, withInputOff)+import Spec+import NanoUI.Shortcut+import Data.ByteString qualified as BS+import Data.IntMap.Strict qualified as IM+import Data.Maybe (fromMaybe, listToMaybe)+import Data.Text qualified as T+import Data.Primitive.SmallArray (smallArrayFromList)+import NanoUI.Internal.Context (Context (..), DamageState (..), PrevFrame (..), emptyPrevFrame, getPrevRectAt, getsDamage)+import NanoUI.Internal.Layout.Arena (arenaCount, getWidgetId) --- | A new version on a versioned drawing repaints its rect. Paint rebuilds the--- ops once the version moves, and nothing else damages them, so a clip frame--- would otherwise keep the pixels it drew last time.-runVersionedDrawingDamageTest :: Context -> IORef Int -> IO ()-runVersionedDrawingDamageTest ctx failed = do-  let inp = withInput 400 300-      ui version = column $ do-        _ <- label "Other"-        drawingVersioned version (fixedWH 80 40) $ \r ->-          runCanvas (drawRect r (colorRGBA 255 0 0 255))-  resp <- warmup2 ctx inp (ui 1)-  _ <- takeDamage ctx-  _ <- runFrame ctx inp (ui 2)-  dmg <- takeDamage ctx-  case dmg of-    DamageClip clip -> assert failed (covers clip (respRect resp))-    DamageFull -> assert failed False+tests :: [Spec]+tests =+  [ spec "damage-rect-math" runDamageRectMathTest+  , spec "damage-explicit" runExplicitDamageTest+  , spec "damage-hover" runHoverDamageTest+  , spec "damage-orphan-anim-settles" runOrphanAnimationDamageSettlesTest+  , spec "damage-content-change" runContentChangeDamageTest+  , spec "clip-frame-paint" runClipFramePaintTest+  , spec "resize-damage" runResizeDamageTest+  , spec "label-button-swap-damage" runLabelButtonSwapDamageTest+  , spec "prev-frame-matches-fresh-walk" runPrevFrameFreshWalkTest+  , spec "scrolled-popup-damage" runScrolledPopupDamageTest+  ] --- | Whether the first rect contains the second.-covers :: Rect -> Rect -> Bool-covers (Rect cx cy cw ch) (Rect x y w h) =-  cx <= x && cy <= y && cx + cw >= x + w && cy + ch >= y + h+-- | Whether a frame's damage is a clip smaller in area than @a@.+clipUnder :: Float -> Damage -> Bool+clipUnder a (DamageClip (Rect _ _ w h)) = w * h < a+clipUnder _ DamageFull = False -runDamageBoundsResolutionTest :: Context -> IORef Int -> IO ()-runDamageBoundsResolutionTest _ failed = do+-- | Damage requests resolve against a rect ('DamageNone' is a union's+-- identity), and rects group into at most four disjoint covering pieces.+runDamageRectMathTest :: Context -> IORef Int -> IO ()+runDamageRectMathTest _ failed = do   let base = Rect 10 20 100 50-      rSelf = resolveDamageRect DamageSelf base-      rInflated = resolveDamageRect (DamageInflated 8.0) base-      rExact = resolveDamageRect (DamageExact (Rect 0 0 500 500)) base-      rCustom = resolveDamageRect (DamageCustom (\(Rect x y w h) -> Rect (x - 1) (y - 2) (w + 10) (h + 20))) base-      rNone = resolveDamageRect DamageNone base--  assertEq failed rSelf base-  assertEq failed rInflated (Rect 2 12 116 66)-  assertEq failed rExact (Rect 0 0 500 500)-  assertEq failed rCustom (Rect 9 18 110 70)-  assertEq failed rNone (Rect 0 0 0 0)-  assertEq failed (resolveDamageRect (DamageUnion (DamageInflated 4.0) (DamageInflated 8.0)) base)-    (rectUnion (Rect 6 16 108 58) (Rect 2 12 116 66))-  -- DamageNone is the identity of a union rather than a rect at the origin.-  assertEq failed (resolveDamageRect (DamageUnion DamageSelf DamageNone) base) base-  assertEq failed (resolveDamageRect (DamageUnion DamageNone (DamageExact base)) (Rect 0 0 0 0)) base--runExplicitDamageWidgetTest :: Context -> IORef Int -> IO ()-runExplicitDamageWidgetTest ctx failed = do-  let inp = withInput 400 300-      ui = columnWith (padAll 20) $ do-        w1 <- button' "First"-        w2 <- button' "Second"-        pure (w1, w2)-  -- Warmup to establish solved layout rects-  _ <- runFrame ctx inp ui-  ((w1, _), _, _, _) <- runFrame ctx inp ui-  _ <- takeDamage ctx+      stretch (Rect x y w h) = Rect (x - 1) (y - 2) (w + 10) (h + 20)+  forM_+    [ (DamageSelf, base)+    , (DamageInflated 8, Rect 2 12 116 66)+    , (DamageExact (Rect 0 0 500 500), Rect 0 0 500 500)+    , (DamageCustom stretch, Rect 9 18 110 70)+    , (DamageNone, Rect 0 0 0 0)+    , (DamageUnion (DamageInflated 4) (DamageInflated 8), rectUnion (Rect 6 16 108 58) (Rect 2 12 116 66))+    , (DamageUnion DamageSelf DamageNone, base)+    ]+    $ \(d, want) -> assertEq failed want (resolveDamageRect d base)+  assertEq failed base (resolveDamageRect (DamageUnion DamageNone (DamageExact base)) (Rect 0 0 0 0))+  let a = Rect 0 0 20 10+  assertEq failed 2 (length (damagePieces [a, Rect 500 400 20 10]))+  forM_ [[a, Rect 30 0 20 10], [a], [], [a, Rect 40 0 20 10, Rect 20 0 20 10]] $ \rs ->+    assertEq failed [] (damagePieces rs)+  let scattered = [Rect (fromIntegral i * 100) (fromIntegral i * 80) 10 10 | i <- [0 .. 7 :: Int]]+      pieces = damagePieces scattered+  assertEq failed 4 (length pieces)+  assert failed (all (\r -> any (`covers` r) pieces) scattered)+  assert failed (and [rectIntersect p q == Nothing | (i, p) <- zip [0 :: Int ..] pieces, (j, q) <- zip [0 ..] pieces, i < j]) -  -- Queue explicit widget damage-  let testUi = columnWith (padAll 20) $ do-        w1' <- button' "First"-        w2' <- button' "Second"-        damageWidgetNow (respId w1') (DamageInflated sliderDamageSlop)-        pure (w1', w2')-  _ <- runFrame ctx inp testUi-  dmg <- takeDamage ctx-  let Rect x1 y1 w1Len h1Len = respRect w1-      expected = rectInflate sliderDamageSlop (Rect x1 y1 w1Len h1Len)-      approxEq (Rect a b c d) (Rect e f g h) =-        abs (a - e) < 0.05 && abs (b - f) < 0.05 && abs (c - g) < 0.05 && abs (d - h) < 0.05+-- | Asked-for damage lasts its own frame, and damage off the window adds+-- nothing. 'clearDirty' keeps the repaint 'markDirty' queued; a host not+-- reading damage gets 'DamageFull' yet keeps what the next frame diffs.+runExplicitDamageTest :: Context -> IORef Int -> IO ()+runExplicitDamageTest ctx failed = do+  let inp = withInputOff 400 300+      ui :: Int -> (Response -> NanoUI ()) -> NanoUI (Response, Response)+      ui n extra = columnWith (fillW . fillH . padAll 20) $ do+        b <- button' "First"+        extra b+        flex+        (b,) <$> rowWith fillW (flex >> labelWith' (fixedW 40) (T.pack (show n)))+      none = const (pure ())+      damageOf n extra = runFrame ctx inp (ui n extra) >> takeDamage ctx+      isEmpty n = assert failed . damageIsEmpty =<< damageOf n none+  (btn, lbl) <- warmup2 ctx inp (ui 1 none)+  dmg <- damageOf 1 (\b -> damageWidgetNow (respId b) (DamageInflated sliderDamageSlop))+  let Rect ex ey ew eh = rectInflate sliderDamageSlop (respRect btn)   case dmg of+    DamageClip (Rect x y w h) -> assert failed (all ((< 0.05) . abs) [x - ex, y - ey, w - ew, h - eh])     DamageFull -> assert failed False-    DamageClip r -> assert failed (approxEq r expected)--runDamageQueueClearedPerFrameTest :: Context -> IORef Int -> IO ()-runDamageQueueClearedPerFrameTest ctx failed = do-  let inp = withInput 400 300-      ui = column (label "Static content")-  _ <- warmup2 ctx inp ui-  _ <- takeDamage ctx--  -- Explicit damage in this frame-  let damagedUi = column $ do-        damageRectNow (Rect 5 5 20 20)-        label "Static content"-  _ <- runFrame ctx inp damagedUi-  dmg1 <- takeDamage ctx-  case dmg1 of-    DamageClip r -> assertEq failed r (Rect 5 5 20 20)-    _ -> assert failed False--  -- Next frame without damage requests: damage is empty-  _ <- runFrame ctx inp ui-  dmg2 <- takeDamage ctx-  assert failed (damageIsEmpty dmg2)--  -- Explicit full-window damage, again only for its own frame-  let fullDamagedUi = column $ do-        damageFullNow-        label "Static content"-  _ <- runFrame ctx inp fullDamagedUi-  dmg3 <- takeDamage ctx-  assertEq failed dmg3 DamageFull-  _ <- runFrame ctx inp ui-  dmg4 <- takeDamage ctx-  assert failed (damageIsEmpty dmg4)--runStateChangeDamageTest :: Context -> IORef Int -> IO ()-runStateChangeDamageTest ctx failed = do-  let inp0 = withInput 400 300-      ui = do-        (name, setName) <- useText ""-        row $ do-          label ("Left pane: " <> name)-          setName =<< textInput name--  -- Warm up and focus textInput via Tab-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- takeDamage ctx+  isEmpty 1+  assertEq failed (DamageClip (Rect 5 5 20 20)) =<< damageOf 1 (const (damageRectNow (Rect 5 5 20 20)))+  isEmpty 1+  assertEq failed DamageFull =<< damageOf 1 (const damageFullNow)+  isEmpty 1+  damageOf 2 (const (damageRectNow (Rect 100 (-200) 50 50))) >>= \case+    DamageClip clip -> assert failed (rectY clip >= rectY (respRect lbl) - 10)+    DamageFull -> assert failed False+  markDirty ctx+  clearDirty ctx+  assert failed . not =<< isDirty ctx+  -- A dirty mark asks for a frame and repaints only what that frame changes.+  isEmpty 2+  writeIORef (ctxDamageWanted ctx) False+  assertEq failed DamageFull =<< damageOf 3 none+  writeIORef (ctxDamageWanted ctx) True+  assertEq failed (DamageClip (Rect 0 0 0 0)) =<< damageOf 3 none+  changed <- damageOf 4 none+  assert failed (clipCovers changed (respRect lbl) && not (damageCovers changed (respRect btn))) -  -- Type a character into focused textInput-  _ <- runFrame ctx (inp0 {inputChars = "a"}) ui-  dmg <- takeDamage ctx-  assertEq failed dmg DamageFull+-- | Hover enter and press repaint only the button; motion inside it asks for+-- no frame.+runHoverDamageTest :: Context -> IORef Int -> IO ()+runHoverDamageTest ctx failed = do+  let ui = column (button' "OK")+      inp0 = withInputOff 240 80+      small = clipUnder (240 * 80 * 0.5)+  _ <- runFrame ctx inp0 ui+  assertEq failed DamageFull =<< takeDamage ctx+  V2 cx cy <- centerOf <$> evalUi ctx inp0 ui+  let over = inp0 {inputMousePos = V2 cx cy}+      idle = over {inputDeltaTime = 1}+      press = applyMouseButton MouseLeft True over+  assert failed =<< needsRedraw ctx inp0 over+  _ <- runFrame ctx over ui+  assert failed . small =<< takeDamage ctx+  _ <- runFrame ctx idle ui+  assert failed . not =<< needsRedraw ctx idle over {inputMousePos = V2 (cx + 1) cy}+  assert failed =<< needsRedraw ctx idle press+  _ <- runFrame ctx press ui+  assert failed . small =<< takeDamage ctx +-- | A perpetual animation repaints a clip over its widget and nothing once+-- the widget is gone; on a widget never laid out, its first frame is whole. runOrphanAnimationDamageSettlesTest :: Context -> IORef Int -> IO () runOrphanAnimationDamageSettlesTest ctx failed = do   let winInp = withInput 400 300       inp = winInp {inputDeltaTime = 0.05}-      withBar = columnWith (padAll 20) $ do-        bar <- currentId-        spacer (Fixed 40) (Fixed 20)-        pure bar+      withBar = columnWith (padAll 20) (currentId <* spacer (Fixed 40) (Fixed 20))       withoutBar = columnWith (padAll 20) (pure ())-  -- Warm up: the bar widget occupies a nonzero 40x20 rect in the arena.-  (wid, _, _, _) <- runFrame ctx inp withBar-  _ <- takeDamage ctx-  -- keepAnimating-style perpetual animation on an established widget.+  wid <- evalUi ctx inp withBar   startAnimation ctx wid 0 1 1e9-  -- Widget present and animating => damage is a clip over it, not a-  -- whole-window repaint.   _ <- runFrame ctx inp withBar-  dmgAnimated <- takeDamage ctx-  case dmgAnimated of-    DamageFull -> assert failed False+  takeDamage ctx >>= \case     DamageClip r -> assert failed (rectW r > 0 && rectH r > 0)-  -- Widget leaves the arena (tab switch). The first absent frame may repaint-  -- its old region.-  _ <- runFrame ctx inp withoutBar-  _ <- takeDamage ctx-  -- The perpetual animation is still live, but it must not force the whole-  -- window to repaint forever after its widget is gone.-  _ <- runFrame ctx inp withoutBar-  live <- anyAnimating ctx-  assert failed live-  dmgAbsent <- takeDamage ctx-  assert failed (damageIsEmpty dmgAbsent)-  -- Guard: a freshly started animation on a widget that has never been laid-  -- out still escalates to a full repaint for its first rect-less frame.+    DamageFull -> assert failed False+  -- The first absent frame may repaint the widget's old region.+  replicateM_ 2 (runFrame ctx inp withoutBar)+  assert failed =<< anyAnimating ctx+  assert failed . damageIsEmpty =<< takeDamage ctx   ctx2 <- newContext   startAnimation ctx2 (WidgetId 777) 0 1 0.3   _ <- runFrame ctx2 winInp (label "bare")-  dmgFresh <- takeDamage ctx2-  assertEq failed dmgFresh DamageFull+  assertEq failed DamageFull =<< takeDamage ctx2   _ <- runFrame ctx2 winInp (label "bare")-  dmgFresh2 <- takeDamage ctx2-  assert failed (dmgFresh2 /= DamageFull)+  assert failed . (/= DamageFull) =<< takeDamage ctx2 --- | A clip frame repaints its region from the window backdrop, as a full frame--- repaints from the cleared window. An idle menu-bar title has no fill, so--- without the backdrop the hover highlight it just lost would stay in the--- retain texture.-runClipFrameBackdropTest :: Context -> IORef Int -> IO ()-runClipFrameBackdropTest ctx failed = do-  writeIORef (ctxPaintFull ctx) False-  let inp0 = withInputOff 400 300-      ui = rowWith (tight . fillW . fixedH 28) $ do-        file <- menuButton' "File" False-        _ <- menuButton' "Edit" False-        pure file-  file <- warmup2 ctx inp0 ui-  _ <- runFrame ctx inp0 {inputMousePos = centerOf file} ui-  (_, _, draw, _) <- runFrame ctx inp0 ui-  dmg <- takeDamage ctx+-- | Changes no rect or text diff sees repaint just the widget: a drawing's+-- new version, select all in a text area (on its own frame), a label shrunk+-- by a slider drag (only 'storeFloat' changes), an image switched in a page.+runContentChangeDamageTest :: Context -> IORef Int -> IO ()+runContentChangeDamageTest _ failed = do+  ctx <- newContext+  let versioned v = column $ do+        label "Other"+        drawingVersioned v (fixedWH 80 40) (\r -> smallArrayFromList [FillRect r (colorRGBA 255 0 0 255)])+  resp <- warmup2 ctx (withInput 400 300) (versioned 1)+  _ <- runFrame ctx (withInput 400 300) (versioned 2)+  assert failed . (`clipCovers` respRect resp) =<< takeDamage ctx+  -- Frame time lets the click's hover fade finish, which would damage the area.+  areaCtx <- newContext+  let inp0 = (withInputOff 800 600) {inputDeltaTime = 0.5}+      notes = column (label "Notes" >> fst <$> withValue "hello world" (textAreaWith' (fixedWH 200 80)))+  area <- warmup2 areaCtx inp0 notes+  _ <- runClick areaCtx inp0 notes (centerOf area)+  _ <- warmup2 areaCtx inp0 notes+  _ <- runFrame areaCtx (chordInp (cmdOrCtrl <> key 'a') inp0) notes+  assert failed . (`clipCovers` respRect area) =<< takeDamage areaCtx+  sliderCtx <- newContext+  ref <- newIORef (50 :: Float)+  let inp = withInputOff 400 100+      ui = row $ do+        (s, v) <- liftIO (readIORef ref) >>= \v0 -> withValue v0 (sliderWith' (fixedW 200) 0 100)+        liftIO (writeIORef ref v)+        (s,) <$> label' (T.pack (show (round v :: Int)))+  (s, _) <- warmup2 sliderCtx inp ui+  let Rect sx sy sw sh = respRect s+      at x = V2 x (sy + sh / 2)+  runDragFrom sliderCtx inp ui (at (sx + sw / 2)) (at (sx + sw + 50))+  assertEq failed 100 =<< readIORef ref+  (_, wide) <- evalUi sliderCtx (holdAt inp (at (sx + sw / 2))) ui+  assert failed . (`clipCovers` respRect wide) =<< takeDamage sliderCtx+  imgCtx <- newContext+  let px a = BS.pack (concat (replicate 16 [a, 0, 0, 255]))+  assert failed . and =<< mapM (\(i, a) -> registerImage imgCtx (ImageId i) 4 4 (px a)) [(1, 60), (2, 120)]+  frameRef <- newIORef (ImageId 1)+  let page = fmap snd . scrollArea (padAll 10 . grow) . column $ do+        label "frames"+        currentId <* (image (fixedWH 40 24) =<< liftIO (readIORef frameRef))+  wid <- warmup2 imgCtx (withInputOff 320 200) page+  writeIORef frameRef (ImageId 2)+  _ <- runFrame imgCtx (withInputOff 320 200) page+  dmg <- takeDamage imgCtx+  assertJustM failed (getPrevRect imgCtx wid) $ \r ->+    assert failed (clipCovers dmg r && clipUnder (320 * 200 / 4) dmg)++-- | A clip frame paints its region over the page backdrop (or an unfilled+-- menu title keeps its lost hover), far changes as two pieces, and with+-- nothing to repaint nothing, not even a page scroller's backdrop.+runClipFramePaintTest :: Context -> IORef Int -> IO ()+runClipFramePaintTest _ failed = do+  let clipped w h ui = do+        ctx <- newContext+        _ <- warmup2 ctx (withInputOff w h) ui+        ctx <$ writeIORef (ctxPaintFull ctx) False+  let menu = rowWith (tight . fillW . fixedH 28) (menuButton' "File" False <* menuButton' "Edit" False)+  ctx <- clipped 400 300 menu+  file <- evalUi ctx (withInputOff 400 300) menu+  _ <- runFrame ctx (withInputOff 400 300) {inputMousePos = centerOf file} menu+  (_, draw, _) <- runFrame ctx (withInputOff 400 300) menu   theme <- readIORef (ctxTheme ctx)   quads <- drawQuads draw-  case dmg of+  takeDamage ctx >>= \case     DamageClip clip -> do       assert failed (covers clip (respRect file))-      case quads of-        (r, c) : _ -> do-          assert failed (covers r clip)-          assertEq failed c (themeWindow theme)-        [] -> assert failed False+      assertJust failed (listToMaybe quads) $ \(r, c) ->+        assert failed (covers r clip) >> assertEq failed (pageBackground theme) c     DamageFull -> assert failed False+  let corners k = columnWith (fillW . fillH) $ do+        label (T.pack (show (k :: Int)))+        flex+        rowWith fillW $ flex >> label (T.pack (show k))+  far <- clipped 800 600 (corners 1)+  (_, dd, _) <- runFrame far (withInputOff 800 600) (corners 2)+  assert failed . (/= DamageFull) =<< takeDamage far+  pieces <- takeDamagePieces far+  assertEq failed 2 (length pieces)+  let clipOf c = Rect (cmdClipX c) (cmdClipY c) (cmdClipW c) (cmdClipH c)+      inPiece c = any ((`covers` clipOf c) . rectInflate 1) pieces+  assert failed (not (null (drawCmdElems dd)) && all inPiece (drawCmdElems dd))+  let page = scrollArea grow (column (label "Static" >> button "B"))+  idle <- clipped 300 200 page+  (_, idleDraw, _) <- runFrame idle (withInputOff 300 200) page+  assert failed . damageIsEmpty =<< takeDamage idle+  assert failed . null =<< drawQuads idleDraw --- | Ctrl+A repaints the text area on the frame that selects, rather than--- leaving the highlight to a follow-up frame.-runTextAreaSelectAllDamageTest :: Context -> IORef Int -> IO ()-runTextAreaSelectAllDamageTest ctx failed = do-  -- Frame time lets the hover fade from the click finish; a live fade would-  -- damage the area anyway.-  let inp0 = (withInputOff 800 600) {inputDeltaTime = 0.5}-      ui = column $ do-        _ <- label "Notes"-        fst <$> textAreaWith' (fixedWH 200 80) "hello world"-  area <- warmup2 ctx inp0 ui-  _ <- runClick ctx inp0 ui (centerOf area)-  _ <- warmup2 ctx inp0 ui-  _ <- takeDamage ctx-  _ <- runFrame ctx inp0 {inputChars = "a", inputModifiers = Modifiers False True False} ui-  dmg <- takeDamage ctx-  case dmg of-    DamageClip clip -> assert failed (covers clip (respRect area))-    DamageFull -> assert failed False+-- | A resized panel (no widget id), scroller (bar lane too), root drawing or+-- hovered button repaints its old and new rects; a drawing overflowing a+-- short root all it drew. A panel that stays put adds nothing.+runResizeDamageTest :: Context -> IORef Int -> IO ()+runResizeDamageTest _ failed = do+  let at w h x y = (withInput w h) {inputMousePos = V2 x y}+      boxed w = panelWith (fixedWH w 40) (void (buttonWith (fixedWH 30 20) ""))+      scroller w = column (void (scrollWith (fixedWH w 60) (replicateM_ 6 (buttonWith (fixedWH 30 20) ""))))+      hoveredButton w = column (void (buttonWith (fixedWH w 20) ""))+      fresh inp ui = newContext >>= \ctx -> ctx <$ warmup2 ctx inp ui+  forM_+    [ (at 300 200 10 10, boxed, \w -> Rect 0 0 w 40, 100, 60)+    , (at 300 200 (-10) (-10), boxed, \w -> Rect 0 0 w 40, 100, 60)+    , (at 300 200 (-10) (-10), boxed, \w -> Rect 0 0 w 40, 60, 100)+    , (at 300 200 10 10, scroller, \w -> Rect 3 3 w 60, 100, 60)+    , (at 300 200 10 10, scroller, \w -> Rect 3 3 w 60, 60, 100)+    , (withInput 200 100, (`redDrawing` 20), \w -> Rect 0 0 w 20, 40, 20)+    , (at 200 100 5 5, hoveredButton, \w -> Rect 3 3 w 20, 40, 20)+    ]+    $ \(inp, ui, rect, from, to) -> do+      ctx <- fresh inp (ui from)+      assert failed . elem (rect from) =<< arenaRects ctx+      _ <- runFrame ctx inp (ui to)+      assert failed . elem (rect to) =<< arenaRects ctx+      assert failed . (`damageCovers` rect (max from to)) =<< takeDamage ctx+  let overflow rootH drawH = columnWith (fixedWH 40 rootH . padAll 0) (redDrawing 40 drawH)+  forM_ [(40, 20), (20, 30)] $ \(h, dh) -> do+    ctx <- fresh (at 200 100 1 1) (overflow 20 40)+    _ <- runFrame ctx (at 200 100 1 1) (overflow h dh)+    assert failed . (`damageCovers` Rect 0 0 40 40) =<< takeDamage ctx+  let steady = column (boxed 100 >> panelWith (fixedWH 80 40) (label "second"))+  ctx <- fresh (withInputOff 300 200) steady+  _ <- runFrame ctx (withInputOff 300 200) steady+  assertEq failed (DamageClip (Rect 0 0 0 0)) =<< takeDamage ctx++-- | An empty label taking back a button's key and rect repaints the rect.+runLabelButtonSwapDamageTest :: Context -> IORef Int -> IO ()+runLabelButtonSwapDamageTest ctx failed = do+  let inp = withInputOff 200 100+      ui asButton = column (if asButton then void (buttonWith (fixedWH 60 20) "") else labelWith (fixedWH 60 20) "")+  _ <- warmup2 ctx inp (ui False)+  forM_ [True, False, True, False] $ \asButton -> do+    _ <- runFrame ctx inp (ui asButton)+    dmg <- takeDamage ctx+    unless asButton $ assert failed (dmg `damageCovers` Rect 3 3 60 20)++-- | The previous-frame maps updated in place equal a walk from empty maps+-- through 48 frames of swaps, images, shared keys and reorders, and each+-- widget's rect by node index ('getPrevRectAt') is its map entry.+runPrevFrameFreshWalkTest :: Context -> IORef Int -> IO ()+runPrevFrameFreshWalkTest ctx failed = do+  ref <- newContext+  let img = ImageId 1+      img2 = ImageId 2+      inp = withInputOff 400 400+      ui :: Int -> NanoUI ()+      ui f = columnWith (fillW . fillH) $ do+        scope (if even f then labelWith (fixedWH 60 20) "" else void (buttonWith (fixedWH 60 20) ""))+        label (if f `mod` 3 == 0 then "" else "x")+        labelWith (fixedWH 40 20) (T.pack (show (f `mod` 4)))+        image (fixedWH 16 16) (if even (f `div` 2) then img else img2)+        scope $+          if f `mod` 4 < 2+            then image (fixedWH 32 32) img+            else imageConfigured defaultImageConfig {icLayout = fixedWH 32 32, icOpacity = if f `mod` 4 == 2 then 0.5 else 1} img+        void (buttonWith (if f `mod` 5 == 0 then fixedWH 0 0 else fixedWH 40 20) "z")+        rowWith tight $ forM_ [1 :: Int, 1, 2] $ \k -> withKey k (void (buttonWith (fixedWH (if odd (f `div` 3) then 30 else 50) 20) "d"))+        rowWith tight $ do+          when (f `mod` 6 < 3) (void (buttonWith (fixedWH 20 20) "p"))+          panelWith (fixedWH 80 40) (label "panel")+        void $ scrollWith (fixedWH 200 (if even (f `div` 3) then 100 else 80)) $ column $+          forM_ (if f `mod` 7 < 3 then [1 .. 6 :: Int] else reverse [2 .. 5]) $ \k -> withKey k (void (button (T.pack (show k))))+        when (f `mod` 8 < 4) $ forM_ [1 .. 3 :: Int] $ \k -> label (T.pack (show k))+      maps c = (\p -> (pfRects p, pfClips p, pfOuterClips p, pfHashes p)) <$> getsDamage c dsPrev+  forM_ [ctx, ref] $ \c -> forM_ [img, img2] $ \i -> assert failed =<< registerImage c i 8 8 (BS.replicate (8 * 8 * 4) 200)+  forM_ [0 .. 47] $ \f -> do+    _ <- runFrame ctx inp (ui f)+    kept <- maps ctx+    modifyIORef' (ctxDamageState ref) (\ds -> ds {dsPrev = emptyPrevFrame})+    _ <- runFrame ref inp (ui f)+    assertEq failed kept =<< maps ref+    n <- arenaCount (ctxNodeArena ctx)+    forM_ [0 .. n - 1] $ \i -> do+      wid <- getWidgetId (ctxNodeArena ctx) i+      inMap <- fromMaybe (Rect 0 0 0 0) <$> getPrevRect ctx wid+      assertEq failed inMap =<< getPrevRectAt ctx i wid++-- | A popup following a scrolled row repaints its old shadow, past its rect,+-- as a clip, also with a scroller nested in the page.+runScrolledPopupDamageTest :: Context -> IORef Int -> IO ()+runScrolledPopupDamageTest _ failed = forM_ [False, True] $ \nested -> do+  ctx <- newContext+  let inp = withInputOff 640 400+      rows = mapM_ (\i -> label (T.pack ("row " <> show (i :: Int))))+      ui = do+        (sc, anchor) <- scrollArea (fixedWH 200 200) . columnWith fillW $ do+          if nested then void (scrollArea (fillW . fixedH 40) (rows [1 .. 6])) else rows [1 .. 4]+          labelWith' fillW "anchor" <* rows [(if nested then 7 else 5) .. 30]+        popup (constVar True) (defaultPopupConfig (AnchorRect (respRect anchor))) {popupPlacement = PlacementRight, popupDismissable = False} (label "tip")+        pure sc+  sc <- warmup2 ctx inp ui+  assertJustM failed (getPrevRect ctx sc) $ \r -> do+    -- Below the nested scroller, over the page's own rows.+    let wheel = inp {inputMousePos = V2 (rectX r + 20) (rectY r + 120), inputScroll = V2 0 1}+    _ <- runFrame ctx wheel ui+    before <- IM.elems <$> floatingPanelRects ctx+    _ <- runFrame ctx wheel ui+    after <- IM.elems <$> floatingPanelRects ctx+    dmg <- takeDamage ctx+    pieces <- takeDamagePieces ctx+    assert failed (before /= after)+    forM_ before $ \(Rect x y w h) -> do+      let shadow = Rect (x + 3) (y + 3) w h+      assert failed (clipCovers dmg shadow && (null pieces || any (`covers` shadow) pieces))++redDrawing :: Float -> Float -> NanoUI ()+redDrawing w h = void (drawing (fixedWH w h) (\r -> smallArrayFromList [FillRect r (colorRGBA 255 0 0 255)]))
+ test/integration/Cases/DamageProps.hs view
@@ -0,0 +1,262 @@+{-# OPTIONS_GHC -O0 #-}+-- | Damage soundness over random interaction scripts: whatever a frame paints+-- differently from the frame before lies inside that frame's damage.+--+-- A headless context paints every frame whole ('ctxPaintFull' is on by+-- default) and still reports damage, so two consecutive frames can be+-- compared directly. A frame's picture is the multiset of its draw+-- triangles (vertices, texture and the clip of the command that draws them,+-- hashed) and of its text spans (rect, text, colours and clip), which the backend+-- rasterises itself. A triangle or span in one frame and not the other is+-- a change; where it shows is its bounding box cut to its clip. Every change+-- with any area must lie inside the union of the frame's damage pieces (or+-- its damage clip when there are no pieces), inflated by a pixel for+-- antialiased edges. 'DamageFull' covers everything.+--+-- Draw order is not compared: a frame that drew the same primitives in+-- another order counts as unchanged. A primitive hidden under an opaque one+-- still counts, so the check can only be stricter than the pixels need.+module Cases.DamageProps (tests) where++import Spec+import Data.Map.Strict qualified as M+import Data.Maybe (fromMaybe)+import Data.Text qualified as T+import NanoUI.Testing.Sim qualified as Sim+import Test.QuickCheck (Args (..), Arbitrary (..), Gen, Property, choose, counterexample, elements, frequency, ioProperty, isSuccess, quickCheckWithResult, stdArgs, vectorOf)+import Test.QuickCheck qualified as QC+import Test.QuickCheck.Random (mkQCGen)++tests :: [Spec]+tests =+  [damageSpec "damage-props" 3 80]++-- | 'propSpec' for 'damageSound', printing how many frames the cases+-- checked: a 'DamageFull' frame covers everything and checks nothing, so the+-- count shows how much of the run the property saw.+damageSpec :: String -> Int -> Int -> Spec+damageSpec name seed n = spec name $ \_ failed -> do+  counts <- newIORef (0, 0)+  r <- quickCheckWithResult stdArgs {replay = Just (mkQCGen seed, 0), maxSuccess = n, chatty = False} (damageSound counts)+  (checked, total) <- readIORef counts+  putStrLn ("  " <> name <> ": checked " <> show checked <> " of " <> show (total :: Int) <> " frames")+  unless (isSuccess r) $ putStrLn (QC.output r) >> modifyIORef' failed (+ 1)++-- | One user action, with points in a 400 x 300 window.+data Act+  = AMove V2+  | AClick V2+  | ADrag V2 V2+  | AWheel V2 Float+  | AType T.Text+  | APress Key+  | AWait Float+  | AThread+  -- ^ Write the view's 'Var' from IO and wake the loop, as a worker+  -- thread does.+  deriving (Show)++-- | A point, most often in the top left where the views put their widgets.+genPoint :: Gen V2+genPoint = frequency [(1, within 400 300), (3, within 260 180)]+  where+    within w h = V2 <$> (fromIntegral <$> choose (0 :: Int, w)) <*> (fromIntegral <$> choose (0 :: Int, h))++instance Arbitrary Act where+  arbitrary =+    frequency+      [ (3, AMove <$> genPoint)+      , (4, AClick <$> genPoint)+      , (1, ADrag <$> genPoint <*> genPoint)+      , (1, AWheel <$> genPoint <*> elements [-3, -1, 1, 3])+      , (1, AType <$> elements ["a", "xy", " ", "\x732B"])+      , (2, APress <$> elements [KeyTab, KeyEscape, KeyLeft, KeyRight, KeyUp, KeyDown, KeyEnter, KeyBackspace])+      , (2, AWait <$> elements [0.05, 0.2, 1])+      , (1, pure AThread)+      ]++-- | Which view a script drives, and the script.+data Script = Script Int [Act]+  deriving (Show)++instance Arbitrary Script where+  arbitrary = Script <$> choose (0, length views - 1) <*> (choose (4, 25) >>= (`vectorOf` arbitrary))+  shrink (Script v acts) = [Script v (take i acts <> drop (i + 1) acts) | i <- [0 .. length acts - 1]]++-- | The views, each built fresh for a script: buttons with a counter, a form+-- of text input, checkbox and slider, a scroll area, a select above tabs,+-- a list that grows, and views whose pixels change with no layout change.+-- Each comes with the write 'AThread' makes: a change to one of its 'Var's+-- from IO, then the wake a worker thread calls.+views :: [IO (NanoUI (), IO ())]+views =+  [ do+      n <- newVar (0 :: Int)+      threaded n (+ 1) . columnWith (padAll 10 . gap 6) $ do+        k <- readVar n+        label (T.pack ("count " <> show k))+        rowWith (gap 4) $ do+          plus <- button "plus"+          when plus (modifyVar n (+ 1))+          minus <- button "minus"+          when minus (modifyVar n (subtract 1))+        void (button "idle")+  , do+      t <- newVar ("text" :: T.Text)+      c <- newVar False+      s <- newVar (30 :: Float)+      threaded c not . columnWith (padAll 10 . gap 6) $ do+        textInput t+        checkbox "check" c+        sliderWith fillW 0 100 s+        v <- readVar s+        label (T.pack (show (round v :: Int)))+  , unthreaded . scrollWith (fixedWH 300 200) $+      forM_ [1 .. 30 :: Int] $ \i -> row (label (T.pack ("row " <> show i)) >> void (button "go"))+  , do+      sel <- newVar (0 :: Int)+      active <- newVar (0 :: Int)+      threaded sel (\i -> (i + 1) `mod` 3) . columnWith (padAll 10 . gap 6) $ do+        selectWith (fixedW 160) ["one", "two", "three"] sel+        tabs active [tab k (T.pack ("tab " <> show k)) (label (T.pack ("body " <> show k))) | k <- [0 .. 2 :: Int]]+  , do+      items <- newVar (2 :: Int)+      threaded items (\k -> (k + 1) `mod` 5) . columnWith (padAll 10 . gap 4) $ do+        add <- button "add"+        when add (modifyVar items (+ 1))+        remove <- button "remove"+        when remove (modifyVar items (max 0 . subtract 1))+        k <- readVar items+        forM_ [1 .. k] $ \i -> label (T.pack ("item " <> show i))+  , do+      -- A box whose colour follows a Var, read and not read in the same+      -- view: what changes is a node's colour, at an unchanged rect.+      hue <- newVar (0 :: Int)+      threaded hue (+ 1) . columnWith (padAll 10 . gap 6) $ do+        h <- readVar hue+        box (fixedWH 60 30) (colorRGBA (fromIntegral ((h * 70) `mod` 256)) 90 140 255)+        rowWith (gap 4) $ do+          next <- button "hue"+          when next (modifyVar hue (+ 1))+          void (button "idle")+  , do+      -- A theme scope and a disabled scope switched by buttons, around+      -- widgets that keep their layout.+      accent <- newVar False+      off <- newVar False+      threaded accent not . columnWith (padAll 10 . gap 6) $ do+        a <- readVar accent+        styled (if a then accentColor (colorRGBA 200 60 40 255) else id) $+          rowWith (gap 4) $ do+            flip' <- button "accent"+            when flip' (modifyVar accent not)+            void (button "plain")+        d <- readVar off+        disabledWhen d $ rowWith (gap 4) $ do+          void (button "inside")+          checkbox "box" accent+        toggle <- button "disable"+        when toggle (modifyVar off not)+  , do+      -- A scoped conditional label ahead of widgets that keep their ids, and+      -- a toggle button whose look follows its Var.+      shown <- newVar False+      on <- newVar False+      threaded on not . columnWith (padAll 10 . gap 6) $ do+        s <- readVar shown+        scope (when s (label "note"))+        show' <- button "show"+        when show' (modifyVar shown not)+        toggleButton Accent "toggle" on+  ]+  where+    -- The view with a thread write of @v@ through @f@. The view keeps the+    -- wake action 'askWake' returns, so the write can call it.+    threaded :: Eq a => Var a -> (a -> a) -> NanoUI () -> IO (NanoUI (), IO ())+    threaded v f ui = do+      wakeRef <- newIORef (pure ())+      pure (askWake >>= liftIO . writeIORef wakeRef >> ui, modifyVarIO v f >> join (readIORef wakeRef))+    unthreaded ui = pure (ui, pure ())++-- | A drawn primitive's identity: a triangle's hash ('trianglePicture'), or+-- a text span's layer, rect, clip, colours and text.+data Prim = Tri Int | Span [Float] T.Text+  deriving (Eq, Ord, Show)++-- | The frame's picture: each primitive with its count and visible rect.+picture :: Context -> Input -> DrawData -> IO (M.Map Prim (Int, Rect))+picture ctx inp dd = do+  tris <- M.mapKeysMonotonic Tri <$> trianglePicture dd+  (base, over) <- collectRasterSpans ctx inp+  let texts = [textPrim layer s | (layer, ss) <- [(0, base), (1, over)], s <- ss]+  pure (M.unionWith count tris (M.fromListWith count [(k, (1, r)) | (k, r) <- texts]))+  where+    count (a, r) (b, _) = (a + b, r)+    rectKey (Rect x y w h) = [x, y, w, h]+    textPrim :: Float -> (Rect, T.Text, Color, Color, Rect) -> (Prim, Rect)+    textPrim layer (r, t, fg, bg, clip) =+      (Span (layer : rectKey r <> rectKey clip <> colorKey fg <> colorKey bg) t, fromMaybe (Rect 0 0 0 0) (rectIntersect r clip))+    colorKey c = [fromIntegral (colorR c), fromIntegral (colorG c), fromIntegral (colorB c), fromIntegral (colorA c)]++-- | The parts of @r@ outside @cut@: up to four rects.+subtractRect :: Rect -> Rect -> [Rect]+subtractRect r@(Rect x y w h) cut = case rectIntersect r cut of+  Nothing -> [r]+  Just (Rect cx cy cw ch) ->+    filter (\(Rect _ _ a b) -> a > 1e-3 && b > 1e-3)+      [ Rect x y w (cy - y)+      , Rect x (cy + ch) w (y + h - cy - ch)+      , Rect x cy (cx - x) ch+      , Rect (cx + cw) cy (x + w - cx - cw) ch+      ]++-- | Whether the union of @pieces@ covers @r@.+coveredBy :: [Rect] -> Rect -> Bool+coveredBy pieces r = null (foldl' (\rs p -> concatMap (`subtractRect` p) rs) [r] pieces)++-- | Run a frame headlessly, then compare its picture with the last frame's+-- against its damage, appending what it found uncovered to @found@.+checkedFrame :: IORef (Int, Int) -> IORef (Maybe (M.Map Prim (Int, Rect))) -> IORef [String] -> Context -> Input -> NanoUI a -> IO (a, Bool)+checkedFrame counts lastRef found ctx inp view = do+  (a, dd, again) <- runFrame ctx inp view+  now <- picture ctx inp dd+  dmg <- takeDamage ctx+  pieces <- takeDamagePieces ctx+  previous <- readIORef lastRef+  writeIORef lastRef (Just now)+  let isClip = case dmg of DamageClip _ -> True; DamageFull -> False+  modifyIORef' counts (\(c, t) -> (if isClip then c + 1 else c, t + 1))+  case (previous, dmg) of+    (Nothing, _) -> pure ()+    (_, DamageFull) -> pure ()+    (Just before, DamageClip clip) -> do+      let regions = map (rectInflate 1) (if null pieces then [clip] else pieces)+          changed = M.elems (M.differenceWith gone before now) <> M.elems (M.differenceWith gone now before)+          gone (n, r) (m, _) = if n > m then Just (n - m, r) else Nothing+          uncovered = [r | (_, r) <- changed, rectW r > 1e-3, rectH r > 1e-3, not (coveredBy regions r)]+      unless (null uncovered) $+        modifyIORef' found (<> ["changes at " <> show (take 3 uncovered) <> " outside damage " <> show dmg <> " pieces " <> show pieces])+  pure (a, again)++runAct :: IO () -> Act -> Sim.Sim () ()+runAct threadWrite = \case+  AMove p -> void (Sim.moveTo (Sim.At p))+  AClick p -> void (Sim.click (Sim.At p))+  ADrag p q -> void (Sim.drag (Sim.At p) (Sim.At q) 3)+  AWheel p dy -> void (Sim.wheel (Sim.At p) (V2 0 dy))+  AType t -> void (Sim.typeText t)+  APress k -> void (Sim.pressKey k)+  AWait dt -> void (Sim.advance dt)+  AThread -> Sim.onContext (const threadWrite) >> void Sim.settle++damageSound :: IORef (Int, Int) -> Script -> Property+damageSound counts (Script which acts) = ioProperty $ do+  (view, threadWrite) <- views !! which+  ctx <- newContext+  quiet <- newIORef 0+  lastRef <- newIORef Nothing+  found <- newIORef []+  let opts = Sim.defaultSimOptions {Sim.simFrameRunner = checkedFrame counts lastRef found}+  Sim.runSimWith opts ctx quiet (withInput 400 300) view (mapM_ (runAct threadWrite) acts >> void (Sim.advance 2) >> void Sim.settle)+  problems <- readIORef found+  pure (counterexample (unlines (take 5 problems)) (null problems))
test/integration/Cases/Demo.hs view
@@ -1,33 +1,19 @@-module Cases.Demo-  ( runControlsTabHeightTest-  , runBoundedRadioTest-  , runColorPickerCommitTest-  , runColorPickerChangeOnceTest-  , runColorPickerBarKeysTest-  , runColorPickerRgbaTest-  , runColorPickerEditTest-  , runColorPickerDragAfterFieldTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Demo (tests) where -import Control.Monad (void)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Spec+import Data.Maybe (listToMaybe) import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness (held, keyInp, pressAt, releaseAt, runClick, spanCenter, tabInp, warmup2, withInputOff)--data DemoTab-  = Controls-  | List-  | Diagnostics-  deriving (Bounded, Enum, Eq, Ord, Read, Show)+import NanoUI.Shortcut+import NanoUI.Testing.Sim -data DemoTheme-  = Light-  | Dark-  | System-  deriving (Bounded, Enum, Eq, Ord, Read, Show)+tests :: [Spec]+tests =+  [ pixelSpec "color-picker-pointer" runColorPickerPointerTest+  , pixelSpec "color-picker-keys" runColorPickerKeysTest+  , pixelSpec "controls-tab-height" runControlsTabHeightTest+  , pixelSpec "bounded-radio-offset" runBoundedRadioTest+  ]  newtype OffsetChoice = OffsetChoice Int   deriving (Eq, Show)@@ -40,258 +26,160 @@   fromEnum (OffsetChoice n) = n   toEnum = OffsetChoice +-- | A bounded radio over an enum not starting at 0 shows, picks and follows its value. runBoundedRadioTest :: Context -> IORef Int -> IO () runBoundedRadioTest ctx failed = do-  let inp = withInputOff 300 160-      ui = boundedRadio' (T.pack . show)-  (_, initial) <- warmup2 ctx inp (ui (OffsetChoice 11))-  assertEq failed initial (OffsetChoice 11)-  spans <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans, "OffsetChoice 12" `T.isInfixOf` txt] of-    r : _ -> do-      (_, selected) <- runClick ctx inp (ui (OffsetChoice 11)) (spanCenter r)-      assertEq failed selected (OffsetChoice 12)-      ((_, retained), _, _, _) <- runFrame ctx inp (ui selected)-      assertEq failed retained selected-      ((_, reset), _, _, _) <- runFrame ctx inp (ui (OffsetChoice 10))-      assertEq failed reset (OffsetChoice 10)-    [] -> assert failed False+  v <- newVar (OffsetChoice 11)+  runSim ctx failed (withInputOff 300 160) (snd <$> held v (enumRadioBy' (T.pack . show))) $ do+    checkEq (OffsetChoice 11) =<< result+    checkEq (OffsetChoice 12) =<< click "OffsetChoice 12"+    checkEq (OffsetChoice 12) =<< frame+    writeV v (OffsetChoice 10)+    checkEq (OffsetChoice 10) =<< frame +-- | Beside a taller column, the demo's controls keep near their height alone, also+-- hovered, and the tab body does not stretch to the column's height. runControlsTabHeightTest :: Context -> IORef Int -> IO () runControlsTabHeightTest ctx failed = do-  let-    inp0 =-      withInputOff 1280 800-    controlsBody dumpRef = do-      heading "Controls"-      (cb, _) <- checkbox' "Feature" False-      _ <- slider 0 100 50-      _ <- select ["Low", "Medium", "High"] 1-      (cp, _) <- colorPicker' (colorRGBA 204 102 102 255)-      _ <- boundedRadio (T.pack . show) Dark-      (ti, _) <- textInput' ""-      separator-      uiIO $ writeIORef dumpRef (Just (cb, cp, ti))-    demoPage dumpRef =-      scrollWith (tight . grow) $-        columnWith (padAll 8 . gap 8 . fillW) $-          rowWith (tight . gap 8 . fillW) $ do-            columnWith (tight . gap 8 . fillW) $ do-              card $ do-                heading "State"-                kv "Feature" "off"-                kv "Volume" "50"-                kv "Quality" "Medium"-                kv "Theme" (T.pack (show Dark))-                kv "Name" "-"-                kv "Clicked" "-"-              card $ do-                heading "Gallery"-                mapM_ (\i -> void (label (T.pack ("thumb line " <> show (i :: Int))))) [1 .. 8]-            card $ do-              (demoTab, setDemoTab) <- useEnum Controls-              setDemoTab-                =<< tabs-                  demoTab-                  [ tab t (T.pack (show t)) $ case t of-                      Controls -> controlsBody dumpRef-                      List -> heading "Tree"-                      Diagnostics -> heading "Diagnostics"-                  | t <- [minBound ..]-                  ]-    -- Heights of the checkbox, colour picker and text input, in that order.-    heights c dumpRef = do-      m <- readIORef dumpRef-      case m of-        Just (cb, cp, ti) -> mapM (fmap (fmap rectH) . getPrevRect c . respId) [cb, cp, ti]-        Nothing -> pure [Nothing, Nothing, Nothing]-    spanOf lbls spans =-      let-        match txt =-          any-            (\lbl -> txt == lbl || T.drop 1 txt == lbl || T.isSuffixOf lbl txt)-            lbls-        ys =-          [ (y, y + h)-          | (Rect _ y _ h, txt, _, _, _) <- spans-          , match txt-          ]-       in-        case ys of-          [] -> 0-          _ -> maximum (map snd ys) - minimum (map fst ys)-  dumpLone <- newIORef Nothing+  let inp0 = withInputOff 1280 800+      controlsBody dumpRef = do+        heading "Controls"+        (cb, _) <- withValue False (checkbox' "Feature")+        _ <- withValue 50 (slider 0 100)+        _ <- withValue 1 (select ["Low", "Medium", "High"])+        (cp, _) <- withValue (colorRGBA 204 102 102 255) colorPicker'+        _ <- withValue (OffsetChoice 11) (enumRadioBy (T.pack . show))+        (ti, _) <- withValue "" textInput'+        separator+        liftIO $ writeIORef dumpRef [cb, cp, ti]+      state = [("Feature", "off"), ("Volume", "50"), ("Quality", "Medium"), ("Theme", "Dark")]+        ++ [("Name", "-"), ("Clicked", "-")]+      demoPage dumpRef =+        scrollWith (tight . grow) . columnWith (padAll 8 . gap 8 . fillW) . rowWith (tight . gap 8 . fillW) $ do+          columnWith (tight . gap 8 . fillW) $ do+            card (heading "State" >> mapM_ (uncurry kv) state)+            card (heading "Gallery" >> forM_ [1 .. 8 :: Int] (\i -> label (T.pack ("thumb line " <> show i))))+          card $ do+            demoTabVar <- useVar ("Controls" :: T.Text)+            let body t = if t == "Controls" then controlsBody dumpRef else heading t+            tabs demoTabVar [tab t t (body t) | t <- ["Controls", "List", "Diagnostics"]]+      -- Heights of the checkbox, colour picker and text input, in that order.+      heights c dumpRef = readIORef dumpRef >>= mapM (fmap (fmap rectH) . getPrevRect c . respId)+      extent lbls ss = case [(y, y + h) | (Rect _ y _ h, txt, _, _, _) <- ss, any (`T.isSuffixOf` txt) lbls] of+        [] -> 0+        ys -> maximum (map snd ys) - minimum (map fst ys)+      tooTall pageH loneH = case (pageH, loneH) of+        (Just p, Just l) -> l >= 8 && p > l * 1.35+        _ -> True+      jumped a b = case (a, b) of+        (Just x, Just y) -> abs (x - y) > 1+        _ -> True+      -- The tab body must not fill the wrap-line height of the left column.+      stretched ss =+        let left = extent ["State", "Clicked", "Gallery"] ss+         in left > 80 && extent ["Controls"] ss > left * 0.92+  dumpLone <- newIORef []   ctxLone <- newPixelContext   _ <- runFrame ctxLone inp0 (columnWith (tight . fillW) (controlsBody dumpLone))   lone <- heights ctxLone dumpLone-  dumpPage <- newIORef Nothing+  dumpPage <- newIORef []   let page = demoPage dumpPage-  _ <- runFrame ctx inp0 page-  _ <- runFrame ctx inp0 page+  _ <- warmup2 ctx inp0 page   page0 <- heights ctx dumpPage   spans0 <- collectTextSpans ctx-  dumped <- readIORef dumpPage-  cbRect <- maybe (pure Nothing) (\(cb, _, _) -> getPrevRect ctx (respId cb)) dumped-  let hover = maybe inp0 (\r -> inp0 {inputMousePos = spanCenter r}) cbRect-  _ <- runFrame ctx hover page+  cbRect <- readIORef dumpPage >>= maybe (pure Nothing) (getPrevRect ctx . respId) . listToMaybe+  _ <- runFrame ctx (maybe inp0 (\r -> inp0 {inputMousePos = spanCenter r}) cbRect) page   pageHover <- heights ctx dumpPage   spansH <- collectTextSpans ctx-  let-    left0 = spanOf ["State", "Clicked", "Gallery"] spans0-    body0 = spanOf ["Controls"] spans0-    leftH = spanOf ["State", "Clicked", "Gallery"] spansH-    bodyH = spanOf ["Controls"] spansH-    tooTall pageH loneH = case (pageH, loneH) of-      (Just p, Just l) -> l >= 8 && p > l * 1.35-      _ -> True-    jumped a b = case (a, b) of-      (Just x, Just y) -> abs (x - y) > 1-      _ -> True-  assert failed (not (or (zipWith tooTall page0 lone)))-  assert failed (not (or (zipWith tooTall pageHover lone)))+  assertEq failed (3, 3) (length lone, length page0)+  assert failed (not (or (zipWith tooTall page0 lone ++ zipWith tooTall pageHover lone)))   assert failed (not (or (zipWith jumped page0 pageHover)))-  -- Body must not fill the wrap-line height of the left column.-  assert failed (not (left0 > 80 && body0 > left0 * 0.92))-  assert failed (not (leftH > 80 && bodyH > leftH * 0.92))---- A press on the SV field previews without committing, a held press keeps--- sampling it without blanking the field or resetting it to white, and the--- release commits.-runColorPickerCommitTest :: Context -> IORef Int -> IO ()-runColorPickerCommitTest ctx failed = do-  let initial = colorRGBA 204 102 102 255-  colorRef <- newIORef initial-  let inp0 = withInput 400 420-      packed c = colorToWord32 c-      ui = held colorRef colorPicker'-  (resp, _) <- warmup2 ctx inp0 ui-  let wid = respId resp-      sv = colorPickerSvSquare (respRect resp)-      pt = V2 (rectX sv + rectW sv * 0.9) (rectY sv + 2)-      press = pressAt inp0 pt-      release = releaseAt press-  _ <- runFrame ctx press ui-  storeDrag <- getStore ctx-  assertEq failed (packed (widgetStoreBaseColor storeDrag wid initial)) (packed initial)-  assert failed (packed (widgetStoreColor storeDrag wid initial) /= packed initial)-  _ <- runFrame ctx press {inputMousePressed = False} ui-  storeHold <- getStore ctx-  assertEq-    failed-    (packed (widgetStoreColor storeHold wid initial))-    (packed (widgetStoreColor storeDrag wid initial))-  _ <- runFrame ctx release ui-  storeDone <- getStore ctx-  assertEq-    failed-    (packed (widgetStoreBaseColor storeDone wid initial))-    (packed (widgetStoreColor storeDone wid initial))+  assert failed (not (stretched spans0 || stretched spansH)) -runColorPickerRgbaTest :: Context -> IORef Int -> IO ()-runColorPickerRgbaTest ctx failed = do-  let inp0 = withInputOff 400 460-      ui = void (colorPickerRGBA (colorRGBA 204 102 102 128))-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  spans <- collectTextSpans ctx-  let has needle = any (\(_, t, _, _, _) -> needle `T.isInfixOf` t) spans-  assert failed (has "#cc666680")-  assert failed (has "128")-  assert failed (has "Current")-  assert failed (has "New")+initial :: Color+initial = colorRGBA 204 102 102 255 --- Typing in a channel field must recolour on the same frame (live edits). The--- fields are numeric: Up steps the focused one, and letters are dropped.-runColorPickerEditTest :: Context -> IORef Int -> IO ()-runColorPickerEditTest ctx failed = do-  let inp0 = withInput 400 460-      initial = colorRGBA 204 102 102 255-      ui = colorPicker' initial-  _ <- warmup2 ctx inp0 ui-  -- Tab past the field and the hue bar to the R field.-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (inp0 {inputKeys = inputKeysFromList [KeyBackspace, KeyBackspace, KeyBackspace]}) ui-  ((_, col), _, _, _) <- runFrame ctx (inp0 {inputChars = "10"}) ui-  assertEq failed (colorR col) 10-  assertEq failed (colorG col) 102-  ((_, stepped), _, _, _) <- runFrame ctx (keyInp KeyUp inp0) ui-  assertEq failed (colorR stepped) 11-  ((_, lettered), _, _, _) <- runFrame ctx (inp0 {inputChars = "x"}) ui-  assertEq failed (colorR lettered) 11+-- | A script against a fresh picker (with alpha when @rgba@) bound to a 'Var' of @c@.+picker :: IORef Int -> Bool -> Float -> Color -> (Var Color -> Sim (Response, Color) ()) -> IO ()+picker failed rgba h c script = do+  ctx <- newPixelContext+  v <- newVar c+  runSim ctx failed (withInput 400 h) (held v (if rgba then colorPickerRGBA' else colorPicker')) (script v) --- A channel field that had focus must not pull the colour back while the--- canvas is dragged: pressing the canvas takes focus away from the field.-runColorPickerDragAfterFieldTest :: Context -> IORef Int -> IO ()-runColorPickerDragAfterFieldTest ctx failed = do-  let initial = colorRGBA 204 102 102 255-  colorRef <- newIORef initial-  let inp0 = withInput 400 460-      ui = held colorRef colorPicker'-      tabKey = tabInp inp0-  (resp, _) <- warmup2 ctx inp0 ui-  -- Tab past the field and the hue bar to the R field.-  _ <- runFrame ctx tabKey ui-  _ <- runFrame ctx tabKey ui-  _ <- runFrame ctx tabKey ui-  let sv = colorPickerSvSquare (respRect resp)-      press = pressAt inp0 (V2 (rectX sv + 2) (rectY sv + 2))-      drag =-        press-          { inputMousePressed = False-          , inputMousePos = V2 (rectX sv + rectW sv * 0.9) (rectY sv + rectH sv * 0.9)-          }-  _ <- runFrame ctx press ui-  _ <- runFrame ctx drag ui-  ((_, col), _, _, _) <- runFrame ctx drag ui-  -- Low value keeps every channel dark; a field still writing R would leave-  -- it at 204.-  assert failed (colorR col < 60)+-- | The picker's committed ("current") and live colours.+storeColors :: WidgetId -> Sim a (Color, Color)+storeColors wid = do+  st <- onContext getStore+  pure (widgetStoreBaseColor st wid initial, widgetStoreColor st wid initial) --- respChanged fires on the frame the colour moves and not on later frames--- (regression: it compared the colour against the initial one). A key step--- commits at once: the base colour follows the live one.-runColorPickerChangeOnceTest :: Context -> IORef Int -> IO ()-runColorPickerChangeOnceTest ctx failed = do-  let initial = colorRGBA 204 102 102 255-  colorRef <- newIORef initial-  let inp0 = withInput 400 420-      ui = held colorRef colorPicker'-      changed inp = (\((resp, _), _, _, _) -> respChanged resp) <$> runFrame ctx inp ui-  (resp, _) <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  moved <- changed (keyInp KeyRight inp0)-  assert failed moved-  store <- getStore ctx-  let wid = respId resp-      base = colorToWord32 (widgetStoreBaseColor store wid initial)-      neu = colorToWord32 (widgetStoreColor store wid initial)-  assert failed (neu /= colorToWord32 initial)-  assertEq failed base neu-  idle <- mapM changed [inp0, inp0]-  assertEq failed idle [False, False]+-- | A press on the SV field previews, a held one keeps sampling, and the release+-- commits; it takes focus from a channel field, which would pull the colour back.+-- The press and release repaint a clip, not everything.+runColorPickerPointerTest :: Context -> IORef Int -> IO ()+runColorPickerPointerTest _ failed = do+  picker failed False 420 initial $ \_ -> do+    (resp, _) <- result+    let Rect x y w _ = colorPickerSvSquare (respRect resp)+    _ <- press (At (V2 (x + w * 0.9) (y + 2)))+    (base, live) <- storeColors (respId resp)+    check (base == initial && live /= initial)+    _ <- frame+    checkEq live . snd =<< storeColors (respId resp)+    _ <- release+    uncurry checkEq =<< storeColors (respId resp)+  picker failed False 460 initial $ \_ -> do+    Rect x y w h <- colorPickerSvSquare . respRect . fst <$> result+    -- Tab past the field and the hue bar to the R field.+    pressTab 3+    _ <- press (At (V2 (x + 2) (y + 2))) >> moveTo (At (V2 (x + w * 0.9) (y + h * 0.9)))+    -- Low value keeps every channel dark; a field still writing R would leave it at 204.+    checkGt 60 . colorR . snd =<< frame+  picker failed True 1200 initial $ \_ -> do+    (resp, _) <- result+    _ <- press (On resp)+    check . (`clipCovers` respRect resp) =<< frameDamage+    _ <- release+    check . (/= DamageFull) =<< frameDamage --- The hue and alpha bars are focus stops after the field. An arrow moves a--- bar's handle the way it is drawn (down raises the hue, up lowers the alpha),--- Shift steps ten times as far, and Home / End jump to the bar's ends.-runColorPickerBarKeysTest :: Context -> IORef Int -> IO ()-runColorPickerBarKeysTest ctx failed = do-  let initial = colorRGBA 204 102 102 200-  colorRef <- newIORef initial-  let inp0 = withInput 440 460-      ui = held colorRef colorPickerRGBA'-      frame inp = (\((_, c), _, _, _) -> c) <$> runFrame ctx inp ui-      key k = inp0 {inputKeys = inputKeysFromList [k]}-  _ <- warmup2 ctx inp0 ui-  _ <- frame (key KeyTab)-  _ <- frame (key KeyTab)-  shifted <- frame ((key KeyDown) {inputModifiers = Modifiers True False False})-  assert failed (colorG shifted > colorG initial + 10)-  home <- frame (key KeyHome)-  assert failed (colorG home <= colorG initial + 1)-  _ <- frame (key KeyTab)-  opaque <- frame (key KeyEnd)-  assertEq failed (colorA opaque) 255-  lowered <- frame (key KeyUp)-  assertEq failed (colorA lowered) 254+-- | An arrow on the field changes and commits once, opaque without an alpha bar;+-- channel fields edit live and numerically; bar keys move handles as drawn (Shift+-- ten times, Home and End to the ends); an arrow's repaint covers every part.+runColorPickerKeysTest :: Context -> IORef Int -> IO ()+runColorPickerKeysTest _ failed = do+  picker failed False 420 initial $ \_ -> do+    wid <- respId . fst <$> result+    pressTab 1+    check . respChanged . fst =<< pressKey KeyRight+    (base, live) <- storeColors wid+    check (live /= initial)+    checkEq base live+    checkEq [False, False] =<< replicateM 2 (respChanged . fst <$> frame)+  picker failed False 420 (colorRGBA 204 102 102 128) $ \v -> do+    pressTab 1 >> void (pressKey KeyRight)+    checkEq 255 . colorA =<< readV v+  picker failed False 460 initial $ \_ -> do+    wid <- respId . fst <$> result+    pressTab 3+    _ <- pressKey KeyUp+    (base, live) <- storeColors wid+    checkEq (205, live) (colorR live, base)+    replicateM_ 3 (pressKey KeyBackspace)+    (_, typed) <- typeText "10"+    checkEq (10, 102) (colorR typed, colorG typed)+    checkEq 11 . colorR . snd =<< pressKey KeyUp+    checkEq 11 . colorR . snd =<< typeText "x"+  picker failed True 460 (colorRGBA 204 102 102 200) $ \_ -> do+    mapM_ expect ["#cc6666c8", "200", "Current", "New"]+    pressTab 2+    checkLt 112 . colorG . snd =<< chord (shift <> key KeyDown)+    checkGt 104 . colorG . snd =<< pressKey KeyHome+    _ <- pressKey KeyTab+    checkEq 255 . colorA . snd =<< pressKey KeyEnd+    checkEq 254 . colorA . snd =<< pressKey KeyUp+  picker failed True 1200 initial $ \_ -> do+    pressTab 1 >> void frame+    _ <- pressKey KeyRight+    dmg <- frameDamage+    parts <- map snd <$> onContext (nodesOfType NodeColorPicker)+    checkEq 4 (length parts)+    check (all (clipCovers dmg) parts)
+ test/integration/Cases/Explain.hs view
@@ -0,0 +1,269 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Explain (tests) where++import Spec+import Data.List (findIndex)+import Data.Maybe (isJust, isNothing, listToMaybe)+import NanoUI.Internal.Context (Context (..), ExplainState (..), setDrawSquareGeometry)+import NanoUI.Internal.Layout.Arena (arenaCount, getNodeRect, getNodeType, getParent, isFloatingNode)++tests :: [Spec]+tests =+  [ spec "explain-outlines" runExplainOutlinesTest+  , spec "explain-damage" runExplainDamageTest+  , spec "explain-hover" runExplainHoverTest+  , spec "explain-window-layer" runExplainWindowLayerTest+  , spec "explain-layers-and-pin" runExplainLayersAndPinTest+  , spec "explain-scope" runExplainScopeTest+  ]++inp :: Input+inp = withInputOff 480 360++-- | Every node's rect and depth in its layer, from 0 at the page root or a floating panel.+layerDepths :: Context -> IO [(Rect, Int)]+layerDepths ctx = do+  let na = ctxNodeArena ctx+      depthOf idx = do+        nt <- getNodeType na idx+        p <- getParent na idx+        if isFloatingNode nt || p < 0 then pure 0 else (+ 1) <$> depthOf p+  n <- arenaCount na+  forM [0 .. n - 1] $ \i -> (,) <$> getNodeRect na i <*> depthOf i++-- | The overlay's colour at a depth.+depthColor :: Theme -> Int -> Color+depthColor theme depth = themeSeries theme !! (depth `rem` length (themeSeries theme))++-- | The top edge of a node's outline at a depth, in that depth's colour.+edge :: Theme -> Int -> Rect -> (Rect, Color)+edge theme d (Rect x y w _) = (Rect x y w 1, depthColor theme d)++-- | Quad equality, tolerating float rounding in the decoded vertices.+sameQuad :: (Rect, Color) -> (Rect, Color) -> Bool+sameQuad (Rect x y w h, c) (Rect x' y' w' h', c') =+  c == c' && all ((< 0.01) . abs) [x - x', y - y', w - w', h - h']++-- | Draw-order index of the first quad matching this one.+drawnIndex :: [(Rect, Color)] -> (Rect, Color) -> Maybe Int+drawnIndex quads q = findIndex (sameQuad q) quads++drawnAt :: [(Rect, Color)] -> (Rect, Color) -> Bool+drawnAt quads = isJust . drawnIndex quads++-- | Draw-order index of the first floating-window background quad.+windowFill :: Theme -> [(Rect, Color)] -> Maybe Int+windowFill theme = findIndex ((== styleBg (themeFloatingWindow theme)) . snd)++-- | Draw plain quads with the overlay on, and return the theme.+outlining :: Context -> IO Theme+outlining ctx = setDrawSquareGeometry ctx True >> setExplainLayout ctx True >> getThemeIO ctx++-- | Run two frames; return the second frame's result and quads.+quadsOf :: Context -> Input -> NanoUI a -> IO (a, [(Rect, Color)])+quadsOf ctx i ui = warmupDraw ctx i ui >>= traverse drawQuads++damageOf :: Context -> Input -> NanoUI a -> IO Damage+damageOf ctx i ui = runFrame ctx i ui >> takeDamage ctx++-- | The node explained after a frame with the pointer at @p@.+explainedAt :: Context -> NanoUI a -> V2 -> IO (Maybe ExplainedNode)+explainedAt ctx view p = runFrame ctx inp {inputMousePos = p} view >> getExplainedNode ctx++-- | The overlay outlines every node in its depth's colour, clipped like the node,+-- without changing layout or hit testing.+runExplainOutlinesTest :: Context -> IORef Int -> IO ()+runExplainOutlinesTest ctx failed = do+  setDrawSquareGeometry ctx True+  theme <- getThemeIO ctx+  let ui = columnWith (padAll 8 . gap 4) (label "top" >> rowWith (padAll 4 . gap 4) (button' "a" <* label "b"))+  (_, quadsOff) <- quadsOf ctx inp ui+  rectsOff <- arenaRects ctx+  setExplainLayout ctx True+  (a, quadsOn) <- quadsOf ctx inp ui+  arenaRects ctx >>= assertEq failed rectsOff+  edges <- map (\(r, d) -> edge theme d r) . filter (\(Rect _ _ w h, _) -> w > 0 && h > 0) <$> layerDepths ctx+  -- The root, the label, the row, the button and its label.+  assert failed (length edges >= 5)+  assert failed (all (drawnAt quadsOn) edges && not (any (drawnAt quadsOff) edges))+  runClick ctx inp ui (centerOf a) >>= assert failed . respClicked+  setExplainLayout ctx False+  (_, quadsOffAgain) <- quadsOf ctx inp ui+  assert failed (not (any (drawnAt quadsOffAgain) edges))+  setExplainLayout ctx True+  (_, quads) <- quadsOf ctx inp . columnWith (padAll 10) $+    scrollArea (fixedWH 120 50) (column (replicateM_ 10 (labelWith (fixedWH 80 20) "row")))+  nodes <- layerDepths ctx+  -- The rows, and only the rows, are at the deepest level.+  let rowDepth = maximum (map snd nodes)+      rows = [r | (r, d) <- nodes, d == rowDepth]+      rowEdge = edge theme rowDepth+  assertEq failed (length rows) 10+  assertJust failed (listToMaybe [r | (r@(Rect _ _ 120 50), _) <- nodes]) $ \scroller@(Rect _ sy _ sh) -> do+    let below = [r | r@(Rect _ y _ _) <- rows, y >= sy + sh]+    assert failed (length below >= 5 && not (any (drawnAt quads . rowEdge) below))+    assert failed (any (drawnAt quads . rowEdge) (take 1 rows))+    assert failed (all (covers scroller) [r | (r, c) <- quads, c == depthColor theme rowDepth])++-- | Toggling the overlay repaints everything, setting it again nothing; a column+-- without an id (no rect diff) repaints its old and new outline when it moves.+runExplainDamageTest :: Context -> IORef Int -> IO ()+runExplainDamageTest ctx failed = do+  writeIORef (ctxPaintFull ctx) False+  let ui = column (label "text")+      idle = damageOf ctx inp ui >>= assert failed . damageIsEmpty+  warmup2 ctx inp ui >> idle+  setExplainLayout ctx True+  needsRedraw ctx inp inp >>= assert failed+  damageOf ctx inp ui >>= assertEq failed DamageFull+  idle+  setExplainLayout ctx True+  needsRedraw ctx inp inp >>= assert failed . not+  idle+  damageOf ctx inp (explainLayout False >> ui) >>= assertEq failed DamageFull+  getExplainLayout ctx >>= assert failed . not+  damageOf ctx inp (explainLayout False >> ui) >>= assert failed . damageIsEmpty+  evalUi ctx inp (explainLayout True >> explainingLayout <* ui) >>= assert failed+  takeDamage ctx >>= assertEq failed DamageFull+  widthRef <- newIORef 40+  let moving = columnWith (padAll 10) $+        liftIO (readIORef widthRef) >>= \w -> columnWith (fixedWH w 30) (pure ())+      sized w = filter (\(Rect _ _ w' h) -> w' == w && h == 30) <$> arenaRects ctx+  warmup2 ctx inp moving+  damageOf ctx inp moving >>= assert failed . damageIsEmpty+  before <- sized 40+  writeIORef widthRef 90+  dmg <- damageOf ctx inp moving+  after <- sized 90+  assertEq failed (1, 1) (length before, length after)+  assert failed (all (clipCovers dmg) (before ++ after))++-- | The node under the pointer is tinted and reported; only moving to another repaints.+runExplainHoverTest :: Context -> IORef Int -> IO ()+runExplainHoverTest ctx failed = do+  setDrawSquareGeometry ctx True+  writeIORef (ctxPaintFull ctx) False+  theme <- getThemeIO ctx+  let box80 = labelWith' (fixedWH 80 20)+      ui = columnWith (padAll 10 . gap 10) ((,) <$> box80 "a" <*> box80 "b")+  (a, b) <- warmup2 ctx inp ui+  let overA = inp {inputMousePos = centerOf a}+      nudged = inp {inputMousePos = v2Add (centerOf a) (V2 2 1)}+      overB = inp {inputMousePos = centerOf b}+      tint = depthColor theme 1+      Rect ax ay aw _ = respRect a+  -- Labels ignore hover, so with the overlay off moving between them needs no frame.+  needsRedraw ctx overA overB >>= assert failed . not+  setExplainLayout ctx True+  _ <- warmup2 ctx inp ui+  getExplainedNode ctx >>= assert failed . isNothing+  needsRedraw ctx inp overA >>= assert failed+  (_, draw, again) <- runFrame ctx overA ui+  quads <- drawQuads draw+  assert failed (again && drawnAt quads (respRect a, colorRGBA (colorR tint) (colorG tint) (colorB tint) 0x40))+  assertJustM failed (getExplainedNode ctx) $ \node -> do+    assertEq failed (respRect a, "Text", 1) (explainedRect node, explainedKind node, explainedDepth node)+    -- The content box (inside the label's padding) is outlined over the tint.+    let Padding l r t _ = explainedPadding node+    assert failed (l > 0 && t > 0 && drawnAt quads (Rect (ax + l) (ay + t) (aw - l - r) 1, tint))+  evalUi ctx overA (explainedNode <* ui) >>= assertEq failed (Just (respRect a)) . fmap explainedRect+  takeDamage ctx >>= assert failed . damageIsEmpty+  forM_ [(overA, overA, False), (overA, nudged, True), (nudged, nudged, False), (nudged, overB, True)] $+    \(from, to, want) -> needsRedraw ctx from to >>= assertEq failed want+  (_, _, againNudged) <- runFrame ctx nudged ui+  takeDamage ctx >>= \dmg -> assert failed (not againNudged && damageIsEmpty dmg)+  (_, _, againB) <- runFrame ctx overB ui+  dmg <- takeDamage ctx+  assert failed (againB && clipCovers dmg (respRect a) && clipCovers dmg (respRect b))+  assertJustM failed (getExplainedNode ctx) $ assertEq failed (respRect b) . explainedRect++-- | A floatingWindow's outlines draw over it, after the page's, with depths from its root.+runExplainWindowLayerTest :: Context -> IORef Int -> IO ()+runExplainWindowLayerTest ctx failed = do+  theme <- outlining ctx+  let win = floatingWindow' (constVar True) "Win" (labelWith' (fixedWH 60 20) "inside")+      ui = label "page" >> snd <$> win+  assertJustM failed (warmup2 ctx inp ui) $ \inner -> do+    (_, quads) <- quadsOf ctx inp {inputMousePos = centerOf inner} ui+    nodes <- layerDepths ctx+    let pageRoot = listToMaybe nodes >>= drawnIndex quads . edge theme 0 . fst+    assertJust failed (lookup (respRect inner) nodes) $ \depth -> do+      assert failed (depth > 0)+      -- The page's outlines, then the window over them, then its outlines.+      let innerEdge = drawnIndex quads (edge theme depth (respRect inner))+      assertJust failed ((,,) <$> pageRoot <*> windowFill theme quads <*> innerEdge) $ \(p, w, i) ->+        assert failed (p < w && w < i)+      assertJustM failed (getExplainedNode ctx) $ \node ->+        assertEq failed (respRect inner, depth) (explainedRect node, explainedDepth node)+  -- With no page, node 0 is the window root, outlined once over its fill.+  (_, quads) <- quadsOf ctx inp win+  assertJustM failed (listToMaybe <$> layerDepths ctx) $ \(r, depth) -> do+    let e = edge theme depth r+    assertEq failed (0, 1) (depth, length (filter (sameQuad e) quads))+    assertJust failed ((,) <$> windowFill theme quads <*> drawnIndex quads e) $ \(f, i) -> assert failed (f < i)++-- | Pinned nodes are outlined, the topmost node is explained, containers are named,+-- and the explained node reports its layout request.+runExplainLayersAndPinTest :: Context -> IORef Int -> IO ()+runExplainLayersAndPinTest ctx failed = do+  theme <- outlining ctx+  let area l = drawing l (const mempty)+      ui = columnWith (tight . gap 0) $+        (++) <$> sequence [area (pinAt 20 20 . fixedWH 60 40), area (fixedWH 200 100)]+          <*> layersWith tight (sequence [area (fixedWH 200 100), area (fixedWH 100 50)])+      farCorner r = let Rect x y w h = respRect r in V2 (x + w - 5) (y + h - 5)+  (rs, quads) <- quadsOf ctx inp ui+  assert failed (any (drawnAt quads . edge theme 1 . respRect) (take 1 rs))+  -- The pinned area, the area it covers, and the upper and lower layers.+  forM_ (zip rs [centerOf, farCorner, farCorner, centerOf]) $ \(r, at) ->+    explainedAt ctx ui (at r) >>= assertEq failed (Just (respRect r)) . fmap explainedRect+  -- Pointing into a container's padding explains the container.+  let square = void (area (fixedWH 10 10))+      kinds = columnWith (tight . gap 0) $ do+        layersWith (padAll 20 . fixedWH 200 100) square+        rowWith (padAll 20 . fixedWH 200 100 . wrap) (square >> square)+        columnWith (padAll 20 . fixedWH 200 100) square+  warmup2 ctx inp kinds+  forM_ [(80, "Container, layered"), (180, "Container, row, wrap"), (280, "Container, column")] $ \(y, kind) ->+    explainedAt ctx kinds (V2 150 y) >>= assertEq failed (Just kind) . fmap explainedKind+  let fields = columnWith (tight . gap 0) $ do+        chips <- rowWith (wrap . gap 6 . fixedW 300 . minH 40) $ label' "chip"+        pinned <- buttonWith' (pinAt 10 50 . pointer PointerBlock . fillW . maxW 120 . fixedH 30) "pin"+        pure (chips, pinned)+  (chip, pinned) <- warmup2 ctx inp fields+  assertJustM failed (explainedAt ctx fields (centerOf pinned)) $ \n -> do+    assertEq failed (Just (respId pinned), Grow 1, Fixed 30, V2 0 0) $+      (explainedWidget n, explainedWidth n, explainedHeight n, explainedMin n)+    assertEq failed (V2 120 1e9, Just (V2 10 50), PointerBlock, Line) $+      (explainedMax n, explainedPin n, explainedPointer n, explainedFlow n)+  -- The wrapping row, hit in its padding beside the chip.+  let Rect cx cy _ ch = respRect chip+  assertJustM failed (explainedAt ctx fields (V2 (cx - 1) (cy + ch / 2))) $ \n -> do+    assertEq failed (Nothing, Fixed 300, Fit, V2 300 40, 6) $+      (explainedWidget n, explainedWidth n, explainedHeight n, explainedMin n, explainedGap n)+    assertEq failed (Row, Wrap, Nothing, PointerAuto) $+      (explainedDirection n, explainedFlow n, explainedPin n, explainedPointer n)++-- | 'explainScope' limits outlining and explaining to its body; off, it records nothing.+runExplainScopeTest :: Context -> IORef Int -> IO ()+runExplainScopeTest ctx failed = do+  theme <- outlining ctx+  let ui scoped = columnWith (padAll 8 . gap 8) $ do+        outside <- labelWith' (fixedWH 80 20) "outside"+        (a, b) <- (if scoped then explainScope else id) $+          rowWith (padAll 4) ((,) <$> labelWith' (fixedWH 60 20) "a" <*> labelWith' (fixedWH 60 20) "b")+        pure (outside, a, b)+      outlined quads r = maybe False (\d -> drawnAt quads (edge theme d r)) . lookup r <$> layerDepths ctx+  ((outside, a, b), quads) <- quadsOf ctx inp (ui True)+  mapM (outlined quads . respRect) [a, b] >>= assertEq failed [True, True]+  outlined quads (respRect outside) >>= assert failed . not+  -- The root column is not outlined either.+  assertJustM failed (listToMaybe <$> arenaRects ctx) $ \root -> outlined quads root >>= assert failed . not+  getExplainedNode ctx >>= assert failed . isNothing+  explainedAt ctx (ui True) (centerOf outside) >>= assert failed . isNothing+  explainedAt ctx (ui True) (centerOf a) >>= assertEq failed (Just (respId a)) . (>>= explainedWidget)+  (_, quadsAll) <- quadsOf ctx inp (ui False)+  outlined quadsAll (respRect outside) >>= assert failed+  setExplainLayout ctx False+  _ <- runFrame ctx inp (ui True)+  esScopes <$> readIORef (ctxExplain ctx) >>= assertEq failed []
+ test/integration/Cases/Focus.hs view
@@ -0,0 +1,385 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Focus (tests) where++import Spec+import Data.Text qualified as T+import NanoUI.Internal.Context (getFocusVisible, intKey)+import NanoUI.Internal.Store (fieldSelection, fieldText, findSlot)+import NanoUI.Internal.Monad (inertView)+import NanoUI.Monad (focusedWidget, releaseFocus)+import NanoUI.Shortcut+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ simSpec "canvas-focus-click" 400 400 canvasFocusUi canvasFocusClick+  , spec "focus-request-kinds" runFocusRequestKindsTest+  , varSimSpec "focus-request-refused" 400 400 "" refusedUi focusRequestRefused+  , varSimSpec "focus-request-modal" 400 400 True modalUi focusRequestModal+  , varSimSpec "focus-request-blurs-previous" 400 400 "" blursUi focusRequestBlursPrevious+  , spec "focus-request-damage" runFocusRequestDamageTest+  , spec "focus-request-first-pass" runFocusRequestFirstPassTest+  , spec "focus-request-idle" runFocusRequestIdleTest+  , spec "focus-request-order" runFocusRequestOrderTest+  , varSimSpec "focus-tab-closes-menus" 400 400 0 closesMenusUi focusTabClosesMenus+  , spec "focus-tab-claimed" runFocusTabClaimedTest+  , spec "focus-reveals" runFocusRevealsTest+  , spec "focus-next-previous" runFocusNextPreviousTest+  , simSpec "focus-clear-release" 400 400 clearReleaseUi focusClearRelease+  , varSimSpec "focus-text-command" 400 400 False textCommandUi focusTextCommand+  , varSimSpec "focus-after-keyed-list" 400 400 [1, 2] keyedListUi focusAfterKeyedList+  , varSimSpec "focus-widget-gone" 400 400 True goneUi focusWidgetGone+  ]++-- | Focus leaves a field the view stops declaring, so a widget that later+-- lands on its id does not come back focused.+goneUi :: Var Bool -> NanoUI WidgetId+goneUi shown = column $ do+  on <- readVar shown+  if on then respId <$> (useVar "" >>= textInput') else WidgetId 0 <$ label "gone"++focusWidgetGone :: Var Bool -> Sim WidgetId ()+focusWidgetGone shown = do+  field <- result+  focusOn field+  checkEq field =<< focusedId+  writeV shown False+  _ <- settle+  checkEq (WidgetId 0) =<< focusedId++-- | A field declared after a keyed list keeps its id, focus and text while+-- the list grows and shrinks.+keyedListUi :: Var [Int] -> NanoUI WidgetId+keyedListUi rows = column $ do+  xs <- readVar rows+  forM_ xs $ \k -> withKey k (label (T.pack ("row " <> show k)))+  respId <$> (useVar "" >>= textInput')++focusAfterKeyedList :: Var [Int] -> Sim WidgetId ()+focusAfterKeyedList rows = do+  field <- result+  focusOn field+  _ <- typeText "a"+  writeV rows [1, 2, 3, 4]+  _ <- settle+  checkEq field =<< result+  checkEq field =<< focusedId+  _ <- typeText "b"+  writeV rows [4]+  _ <- settle+  checkEq field =<< focusedId+  _ <- typeText "c"+  expect "abc"++inp :: Input+inp = withInputOff 400 400++-- | One frame that requests focus for @ids@ after the view: whether it asked+-- for another frame, and the focus after it.+askFocus :: [WidgetId] -> Sim a (Bool, WidgetId)+askFocus ids = afterView (mapM_ requestFocus ids) >> ((,) <$> wantsFrame <*> focusedId)++-- | A field's selection, as (anchor, caret).+selectionOf :: WidgetId -> Sim a (Int, Int)+selectionOf wid = onContext (fmap (\st -> fieldSelection st k (findSlot fieldText "" k st)) . getStore)+  where+    k = intKey wid++-- | Every control can be focused by its response id. A radio group's+-- response carries an option's id, not the group's Tab stop.+runFocusRequestKindsTest :: Context -> IORef Int -> IO ()+runFocusRequestKindsTest _ failed =+  forM_ (filter ((/= "radio") . fst) everyControl) $ \(name, widget) -> do+    ctx <- newContext+    runSim ctx failed inp (column (respId . fst <$> widget)) $ do+      wid <- result+      before <- focusedId+      checkEq (name, False, wid) . (name, before == wid,) . snd =<< askFocus [wid]++-- | Requesting focus for a disabled field, a label, or an unknown id is a+-- no-op and asks for no frame. Requesting @WidgetId 0@ unfocuses the field,+-- and the loop can sleep.+refusedUi :: Var T.Text -> NanoUI [WidgetId]+refusedUi ref = column (mapM (fmap respId) [fst <$> held ref textInput', fst <$> disabled, label' "Label", inertBtn])+  where+    disabled = disabledWhen True (withValue "" textInput')+    inertBtn = inertView (button' "Inert")++focusRequestRefused :: Var T.Text -> Sim [WidgetId] ()+focusRequestRefused ref = do+  [field, off, lbl, inertB] <- result+  checkEq field =<< (askFocus [field] >> typeText "a" >> focusedId)+  forM_ [off, lbl, inertB, WidgetId 987654321] $ \w -> checkEq (False, field) =<< askFocus [w]+  check =<< onContext textFieldActive+  checkEq (True, WidgetId 0) =<< askFocus [WidgetId 0]+  check . not =<< onContext textFieldActive+  _ <- typeText "b" >> settle+  checkEq "a" =<< readV ref+  check . not =<< wouldRedraw id+  checkEq 0 =<< wakeTime++-- | With a modal open, widgets inside it can be focused from code and widgets+-- behind it cannot, even requested every frame, until the modal closes.+modalUi :: Var Bool -> NanoUI (WidgetId, Maybe WidgetId)+modalUi open = column $ do+  (page, _) <- withValue "page" textInput'+  shown <- readVar open+  let dialog = modal' (constVar True) "Dialog" (fst <$> withValue "inside" textInput')+  inner <- if shown then snd <$> dialog else pure Nothing+  pure (respId page, respId <$> inner)++focusRequestModal :: Var Bool -> Sim (WidgetId, Maybe WidgetId) ()+focusRequestModal open = do+  (page, inner) <- result+  checkJust inner $ \r -> do+    checkEq r =<< (askFocus [r] >> frame >> focusedId)+    checkEq [False, False, False] . map ((== page) . snd) =<< replicateM 3 (askFocus [page])+  writeV open False+  checkEq page . snd =<< (askFocus [page] >> askFocus [page])++-- | Losing focus to a request collapses a field's selection, and a search+-- field commits its debounced query, as with a click elsewhere.+blursUi :: Var T.Text -> NanoUI (Response, WidgetId)+blursUi ref = column ((,) <$> search <*> (respId . fst <$> withValue "other" textInput'))+  where+    slow = defaultSearchInputConfig {sicDebounceMs = 600000}+    search = fst <$> held ref (searchInputConfigured' slow)++focusRequestBlursPrevious :: Var T.Text -> Sim (Response, WidgetId) ()+focusRequestBlursPrevious ref = do+  (field, other) <- result+  _ <- askFocus [respId field]+  check . not . respChanged . fst =<< typeText "abc"+  checkEq "abc" =<< readV ref+  _ <- chord (cmdOrCtrl <> key 'a')+  checkEq (0, 3) =<< selectionOf (respId field)+  _ <- askFocus [other]+  checkEq (3, 3) =<< selectionOf (respId field)+  check . respChanged . fst =<< frame+  checkEq other =<< focusedId++-- | The request's frame repaints the old and new focus as clipped damage.+runFocusRequestDamageTest :: Context -> IORef Int -> IO ()+runFocusRequestDamageTest ctx failed = do+  let buttons = sequence [buttonWith' (fixedW 80) "Top" <* flex, buttonWith' (fixedW 80) "Bottom"]+  runSim ctx failed inp (columnWith (fillW . fillH) buttons) $ do+    [a, b] <- result+    _ <- askFocus [respId a] >> settle+    liftIO (writeIORef (ctxPaintFull ctx) False)+    checkEq (respId b) . snd =<< askFocus [respId b]+    dmg <- frameDamage+    pieces <- onContext takeDamagePieces+    check (all (clipCovers dmg . respRect) [a, b])+    check (null pieces || all (\r -> any (`covers` respRect r) pieces) [a, b])++-- | A request from a view pass that a hook write reruns still takes effect.+runFocusRequestFirstPassTest :: Context -> IORef Int -> IO ()+runFocusRequestFirstPassTest ctx failed = do+  r <- evalUi ctx inp . column $ do+    askedVar <- useVar False+    asked <- readVar askedVar+    r <- respId . fst <$> withValue "" textInput'+    r <$ unless asked (requestFocus r >> writeVar askedVar True)+  assertEq failed r =<< getFocusId ctx++-- | Requesting the already focused widget every frame costs no frames. A+-- click on it hides the ring, and later requests do not bring it back.+runFocusRequestIdleTest :: Context -> IORef Int -> IO ()+runFocusRequestIdleTest ctx failed = do+  let ui = column (fst <$> withValue "" textInput' >>= \r -> r <$ requestFocus (respId r))+  (r0, _, first) <- runFrame ctx inp ui+  r <- warmup2 ctx inp ui+  (_, _, dirty) <- runFrame ctx inp ui+  assertEq failed (True, False) (first, dirty)+  assertEq failed (respId r0) =<< getFocusId ctx+  assert failed . not =<< needsRedraw ctx inp inp+  _ <- runClick ctx inp ui (centerOf r)+  _ <- warmup2 ctx inp {inputMousePos = centerOf r} ui+  assert failed . not =<< getFocusVisible ctx+  assertEq failed (respId r0) =<< getFocusId ctx++-- | A request can name a later widget, the frame's last request wins, and a+-- Tab in that frame continues from it. The field focused shows the ring and+-- takes typing from the next frame, not the requesting one.+runFocusRequestOrderTest :: Context -> IORef Int -> IO ()+runFocusRequestOrderTest ctx failed = do+  textRef <- newVar "hello"+  q <- newIORef []+  -- The requests run before the widgets they name.+  let requests = mapM_ requestFocus =<< liftIO (atomicModifyIORef' q ([],))+      widgets = (:) <$> (respId . fst <$> held textRef textInput') <*> mapM (fmap respId . button') ["A", "B"]+      ask f ids = liftIO (writeIORef q ids) >> frameWith f >> ((,) <$> wantsFrame <*> focusedId)+  runSim ctx failed inp (column (requests >> widgets)) $ do+    [field, a, b] <- result+    checkEq (WidgetId 0) =<< focusedId+    checkEq (True, field) =<< ask (\i -> i {inputChars = "y"}) [field]+    check =<< focusRing+    _ <- typeText "!"+    checkEq "hello!" =<< readV textRef+    let asks = [ask id [a, WidgetId 0], ask id [WidgetId 0, b, a], ask tabInp [field]]+    checkEq [WidgetId 0, a, a] . map snd =<< sequence asks++-- | Tab or a focus request away from an open select or a field's edit menu+-- closes it, and so does a right press on the field, which focuses it and+-- opens its edit menu. The arrows then move the caret of the field and leave+-- the select's value alone.+closesMenusUi :: Var Int -> NanoUI (Response, Response)+closesMenusUi index = column ((,) <$> field <*> (fst <$> held index (select' ["One", "Two", "Three"])))+  where+    -- Above the select, where the dropdown does not cover it.+    field = fst <$> withValue "text" textInput'++focusTabClosesMenus :: Var Int -> Sim (Response, Response) ()+focusTabClosesMenus index = do+  (field, sel) <- result+  -- "Three" shows only in the open dropdown, "Paste" only in the edit menu.+  let leaves = [void (pressKey KeyTab), void (rightClick (On field)), void (askFocus [respId field])]+  forM_ leaves $ \leave -> do+    check =<< (click (On sel) >> labelShown "Three")+    leave+    checkEq (respId field) =<< focusedId+    check . not =<< labelShown "Three"+    _ <- pressKey KeyRight >> frame+    checkEq 0 =<< readV index+  forM_ [void (pressKey KeyTab), void (askFocus [respId sel])] $ \leave -> do+    check =<< (rightClick (On field) >> labelShown "Paste")+    checkEq (respId sel) =<< (leave >> focusedId)+    check . not =<< (frame >> labelShown "Paste")++-- | Tab, Shift+Tab and a focus request scroll the widget they focus into+-- its scroller's view, from below the fold, back up when Tab wraps, and+-- from above. Around nested scrollers, the outer one shows the widget where+-- the inner one moved it.+runFocusRevealsTest :: Context -> IORef Int -> IO ()+runFocusRevealsTest ctx failed = do+  target <- newIORef Nothing+  let labels = map T.singleton ['A' .. 'J']+      buttons = scrollArea (fixedH 100 . fillW) (column (mapM (fmap respId . button') labels))+      ui = (mapM_ requestFocus =<< liftIO (readIORef target)) >> buttons+      showsIn c sid = do+        rect <- getPrevRect c =<< getFocusId c+        metrics <- getScrollMetricsIO c sid+        pure $ case (rect, scrollViewport <$> metrics) of+          (Just (Rect _ y _ h), Just (Rect _ vy _ vh)) -> y >= vy - 0.5 && y + h <= vy + vh + 0.5+          _ -> False+      shown = writeIORef target Nothing >> evalUi ctx inp ui >>= showsIn ctx . fst+  nested <- newContext+  let filler = columnWith (fixedH 150 . fillW) (pure ())+      outerUi = scrollArea (fixedH 120 . fillW) (column (filler *> buttons <* filler <* filler))+  _ <- warmup2 nested inp outerUi+  replicateM_ 10 (runFrame nested (tabInp inp) outerUi)+  (outer, (inner, _)) <- evalUi nested inp outerUi+  assert failed =<< ((&&) <$> showsIn nested outer <*> showsIn nested inner)+  (_, ids) <- warmup2 ctx inp ui+  forM_ [1 .. 11 :: Int] $ \i -> runFrame ctx (tabInp inp) ui >> (assertEq failed (i, True) . (i,) =<< shown)+  _ <- runFrame ctx (chordInp (shift <> key KeyTab) inp) ui+  assert failed =<< shown+  writeIORef target (Just (ids !! 4))+  _ <- runFrame ctx inp ui+  assertEq failed (ids !! 4) =<< getFocusId ctx+  assert failed =<< shown++-- | A focused custom widget that claims Tab ('KeysAll', or 'KeysOnly'+-- naming the chord) reads it and keeps focus; one claiming other keys lets+-- Tab move focus on.+runFocusTabClaimedTest :: Context -> IORef Int -> IO ()+runFocusTabClaimedTest _ failed = do+  let claims = [(KeysAll, True), (KeysOnly [key KeyTab], True), (KeysOnly [shift <> key KeyTab], False)]+  forM_ (claims ++ [(KeysNavigate, False)]) $+    \(claim, keeps) -> do+      ctx <- newContext+      let ui = column $ do+            let custom = defaultCustomWidgetSpec {widgetFocusable = True, widgetKeys = claim}+            (r, _) <- customWidget custom {widgetLayout = fixedWH 100 30}+            tabbed <- focusedKeyPressed (respId r) KeyTab+            _ <- button' "Next"+            pure (respId r, tabbed)+      runSim ctx failed inp ui $ do+        (w, _) <- pressTab 1 >> frame+        checkEq w =<< focusedId+        check . snd =<< pressKey KeyTab+        checkEq (claim, keeps) . (claim,) . (== w) =<< focusedId++-- | 'focusNext' and 'focusPrevious' act like Tab and Shift+Tab at the end of+-- the frame, wrapping at both ends; 'isFocused' reports the focused widget.+-- 'requestFocus' with 'currentId' targets the next declared widget. Shift+Tab+-- with nothing focused goes to the last Tab stop, and Tab and Shift+Tab+-- continue from the widget focused from code.+runFocusNextPreviousTest :: Context -> IORef Int -> IO ()+runFocusNextPreviousTest ctx failed = do+  -- The move runs before the widgets, for 'currentId'.+  move <- newIORef (pure ())+  let ui = column $ do+        join (liftIO (readIORef move))+        ids <- mapM (fmap respId . button') ["A", "B", "C"]+        (,) ids <$> mapM isFocused ids+      step m = liftIO (writeIORef move m) >> frame >> liftIO (writeIORef move (pure ())) >> snd <$> frame+  runSim ctx failed inp ui $ do+    ([a, b, c], _) <- result+    checkEq c =<< (chord (shift <> key KeyTab) >> focusedId)+    focused <- mapM step [focusNext, focusPrevious, focusPrevious]+    checkEq [[True, False, False], [False, False, True], [False, True, False]] focused+    check =<< focusRing+    checkEq [True, False, False] =<< step (requestFocus =<< currentId)+    checkEq a =<< focusedId+    forM_ [(key KeyTab, c), (shift <> key KeyTab, a)] $ \(next, after) -> do+      checkEq [False, True, False] =<< step (requestFocus b)+      checkEq after =<< (chord next >> focusedId)++clearReleaseUi :: NanoUI WidgetId+clearReleaseUi = column (respId . fst <$> withValue "hello" textInput')++-- | 'clearFocus' unfocuses at the end of the frame and collapses the field's+-- selection; 'releaseFocus' unfocuses immediately and keeps the selection.+focusClearRelease :: Sim WidgetId ()+focusClearRelease = do+  field <- pressTab 1 >> frame+  _ <- chord (cmdOrCtrl <> key 'a')+  checkEq (0, 5) =<< selectionOf field+  checkEq field =<< afterView (clearFocus >> focusedWidget)+  checkEq (WidgetId 0) =<< focusedId+  checkEq (5, 5) =<< selectionOf field+  _ <- pressKey KeyTab >> chord (cmdOrCtrl <> key 'a')+  checkEq (WidgetId 0) =<< afterView (releaseFocus field >> focusedWidget)+  checkEq (0, 5) =<< selectionOf field++-- | A text command run from code focuses the field like 'requestFocus': at+-- the end of the frame, with the ring, and never when disabled. What Select+-- All selects stays selected for typing to replace.+textCommandUi :: Var Bool -> NanoUI (Response, T.Text)+textCommandUi off = column (readVar off >>= \o -> disabledWhen o (withValue "hello" textInput'))++focusTextCommand :: Var Bool -> Sim (Response, T.Text) ()+focusTextCommand off = do+  field <- respId . fst <$> result+  checkEq (WidgetId 0) =<< afterView (runTextCommand field SelectAll >> focusedWidget)+  checkEq field =<< focusedId+  check =<< focusRing+  checkEq "Z" . snd =<< typeText "Z"+  focusOn (WidgetId 0)+  writeV off True+  checkEq (WidgetId 0) =<< (afterView (runTextCommand field SelectAll) >> frame >> focusedId)++-- | Pressing a focusable canvas focuses it without showing the Tab ring, so+-- 'focusedKeyPressed' matches for it; pressing a plain canvas clears focus,+-- so it no longer matches.+canvasFocusUi :: NanoUI (Response, Response, WidgetId, Bool)+canvasFocusUi = column $ do+  live <- canvasOf True+  still <- canvasOf False+  (live, still,,) <$> focusedWidget <*> focusedKeyPressed (respId live) KeyRight+  where+    canvasOf focusable = canvasConfigured (config focusable) (\_ -> pure ())+    config focusable = defaultCanvasConfig {canvasLayout = size, canvasFocusable = focusable}+    size = fixedWH 100 40++canvasFocusClick :: Sim (Response, Response, WidgetId, Bool) ()+canvasFocusClick = do+  (live, still, _, _) <- result+  let focusedAfter t = (\(_, _, f, _) -> f) <$> (click (On t) >> frame)+      heardRight = (\(_, _, _, h) -> h) <$> pressKey KeyRight+  checkEq (respId live) =<< focusedAfter live+  check . not =<< focusRing+  check =<< heardRight+  checkEq (WidgetId 0) =<< focusedAfter still+  check . not =<< heardRight
test/integration/Cases/Grid.hs view
@@ -1,146 +1,141 @@-module Cases.Grid-  ( runGridColumnsWithFontColorTest-  , runNestedGridTest-  , runStaleFontColorTest-  , runFontCompositionTest-  , runAlignBaselineTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Grid (tests) where -import Control.Monad (void)-import Data.IORef (IORef)+import Spec import Data.List (nub)-import qualified Data.Text as T-import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Layout.Arena (arenaCount, getStyleIdx, getText)-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)+import Data.Maybe (listToMaybe)+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (arenaCount, getStyleIdx, getText) -spanOf :: T.Text -> [(Rect, T.Text, Color, Color, Rect)] -> Maybe (Rect, Color)-spanOf txt spans =-  case [(r, fg) | (r, t, fg, _, _) <- spans, t == txt] of-    (hit : _) -> Just hit-    [] -> Nothing+tests :: [Spec]+tests =+  [ spec "grid-placement" runGridPlacementTest+  , spec "grid-heights" runGridHeightsTest+  , pixelSpec "font-styles" runFontStylesTest+  ] --- | Font colour and grid column count once shared a node slot, so a coloured--- grid child set after 'gridWith' collapsed the grid to one column.-runGridColumnsWithFontColorTest :: Context -> IORef Int -> IO ()-runGridColumnsWithFontColorTest ctx failed = do-  let red = colorRGBA 255 0 0 255-      cells = ["c0", "c1", "c2", "c3"]-      ui =-        gridWith 4 (fontColor red . fillW) $-          mapM_ (void . labelWith (fontColor red)) cells-  _ <- runFrame ctx (withInput 800 200) ui-  spans <- collectTextSpans ctx-  let hits = [spanOf c spans | c <- cells]-      xs = [rectX r | Just (r, _) <- hits]-      ys = [rectY r | Just (r, _) <- hits]-  assertEq failed (length xs) 4-  assertEq failed (length (nub xs)) 4-  assertEq failed (length (nub ys)) 1-  assert failed (and [fg == red | Just (_, fg) <- hits])+red :: Color+red = colorRGBA 255 0 0 255 --- | A grid child that is itself a grid reuses the solver scratch arrays; the--- parent must still place its remaining cells in their own columns and rows.-runNestedGridTest :: Context -> IORef Int -> IO ()-runNestedGridTest ctx failed = do-  let inner tag = gridWith 2 fillW $ mapM_ (\i -> void (label (tag <> T.pack (show i)))) [0 .. 3 :: Int]-      ui =-        gridWith 2 fillW $ do-          inner "a"-          inner "b"-          void (label "tail0")-          void (label "tail1")-  _ <- runFrame ctx (withInput 800 400) ui+-- | Each named span's rect and colour, in order, once the view settles.+spansOf :: Context -> Input -> [T.Text] -> NanoUI a -> IO [Maybe (Rect, Color)]+spansOf ctx inp names ui = do+  _ <- runFrame ctx inp ui   spans <- collectTextSpans ctx-  case (spanOf "a0" spans, spanOf "b0" spans, spanOf "b3" spans, spanOf "tail0" spans, spanOf "tail1" spans) of-    (Just (a0, _), Just (b0, _), Just (b3, _), Just (t0, _), Just (t1, _)) -> do-      -- Outer columns: the second inner grid sits right of the first.-      assert failed (rectX b0 > rectX a0)-      assertEq failed (rectY b0) (rectY a0)-      -- The outer second row starts below both inner grids.-      assert failed (rectY t0 > rectY b3)-      assertEq failed (rectY t1) (rectY t0)-      -- Tail cells take the outer columns, not the inner grid's columns.-      assert failed (rectX t0 < rectX b0)-      assert failed (rectX t1 > rectX b0 - 8 && rectX t1 <= rectX b0)-    _ -> assert failed False+  pure [listToMaybe [(r, fg) | (r, t, fg, _, _) <- spans, t == n] | n <- names] --- | Nodes created without a layout descriptor (widgets, popups, windows) must--- not inherit the font colour of whatever node held their index last frame.-runStaleFontColorTest :: Context -> IORef Int -> IO ()-runStaleFontColorTest ctx failed = do-  let red = colorRGBA 255 0 0 255-      inp = withInput 400 200-  _ <- runFrame ctx inp (column (void (labelWith (fontColor red) "painted")))-  _ <- runFrame ctx inp (column (void (button "plain")))-  spans <- collectTextSpans ctx-  case spanOf "plain" spans of-    Just (_, fg) -> assert failed (fg /= red)-    Nothing -> assert failed False+-- | Cells keep their own columns with a font colour on the grid (the two+-- once shared a node slot) and around a nested grid (which reuses solver+-- scratch); an aligned fit panel keeps its height; grow children share+-- what a column's gaps leave.+runGridPlacementTest :: Context -> IORef Int -> IO ()+runGridPlacementTest ctx failed = do+  let cells = ["c0", "c1", "c2", "c3"]+      coloured = gridWith 4 (fontColor red . fillW) (mapM_ (labelWith (fontColor red)) cells)+  spansOf ctx (withInput 800 200) cells coloured >>= \hits -> do+    assertEq failed (map (\x -> Just (Rect x 3 24 12)) [3, 204, 404, 605]) (map (fmap fst) hits)+    assert failed (all ((== Just red) . fmap snd) hits)+  let inner tag = gridWith 2 fillW $ mapM_ (\i -> label (tag <> T.pack (show i))) [0 .. 3 :: Int]+      nested = gridWith 2 fillW (inner "a" >> inner "b" >> label "tail0" >> label "tail1")+  spansOf ctx (withInput 800 400) ["a0", "b0", "b3", "tail0", "tail1"] nested+    >>= assertEq failed (map Just [Rect 6 6 24 12, Rect 407 6 24 12, Rect 605 26 24 12, Rect 3 49 60 12, Rect 404 49 60 12])+      . map (fmap fst)+  -- The short cell, the tall one and the next row's.+  forM_ [(alignMiddle, 30), (alignBottom, 60)] $ \(align, y) -> do+    _ <- warmup2 ctx (withInput 400 400) . columnWith tight $ gridWith 2 (tight . gap 0) $ do+      panelWith align (label "a")+      panelWith id (replicateM_ 4 (label "x"))+      label "next"+    (\rs -> map (rs !!) [2, 4, 9]) <$> arenaRects ctx >>= assertEq failed [Rect 0 y 18 18, Rect 48 0 18 78, Rect 0 78 48 12]+  _ <- warmup2 ctx (withInput 800 400) (columnWith (gap 10 . fixedH 200 . fixedW 100) (replicateM_ 3 (box fillH red)))+  arenaRects ctx >>= assertEq failed [Rect 0 0 100 200, Rect 3 3 32 58, Rect 3 71 32 58, Rect 3 139 32 58] --- | Font size, colour, weight, style and decoration modifiers compose on one--- label, and the bold/italic/underline helpers set the same style bits.-runFontCompositionTest :: Context -> IORef Int -> IO ()-runFontCompositionTest ctx failed = do+-- | A grid, also with 'gridMinColW', is as tall as its rows, not its cells+-- stacked. A wrapped cell sets its row's height, and a label wider than its+-- 2D scroller is as tall as paint draws it.+runGridHeightsTest :: Context -> IORef Int -> IO ()+runGridHeightsTest ctx failed = do+  let adaptive = columnWith (gridMinColW 140 . fillW) (replicateM_ 7 (button "x"))+      -- Cell count, columns at least, rows, and room left under the cells;+      -- four or five 140-wide adaptive columns fit inside the padding.+      wrappers =+        [ (400, 9, 3, 3, 30, column (gridWith 3 fillW (replicateM_ 9 (button "x")) >> label "after"))+        , (760, 7, 4, 2, 40, columnWith fillW (adaptive >> label "after"))+        , (760, 7, 4, 2, 40, panelWith (padAll 12 . gap 8 . fillW) (adaptive >> label "after"))+        , ( 760, 7, 4, 2, 40, scrollWith (padAll 12 . grow) $ columnWith (tight . gap 20 . fillW) $+              columnWith (tight . gap 6 . fillW) (panelWith (padAll 12 . gap 8 . fillW) adaptive >> label "after") )+        ]+  forM_ wrappers $ \(w, n, minCols, rows, margin, ui) -> do+    _ <- warmup2 ctx (withInput w 600) ui+    spans <- collectTextSpans ctx+    let xs = [r | (r, "x", _, _, _) <- spans]+    assertEq failed n (length xs)+    assert failed (length (nub (map rectX xs)) >= minCols)+    assertEq failed rows (length (nub (map rectY xs)))+    assertJust failed (spanRect "after" spans) $ \after ->+      assert failed (rectY after < maximum [rectY r + rectH r | r <- xs] + margin)+  let text = "words that wrap across several lines in a narrow cell"+      cellGrid width = columnWith tight $ do+        gridWith 2 (tight . fixedW width . gap 1) $+          mapM_ (labelWith (tight . fillW)) ["short", text, "next"]+        labelWith tight "after"+  forM_ [240, 600, 180, 240, 240] $ \width -> do+    _ <- runFrame ctx (withInput 800 1200) (cellGrid width)+    arenaRects ctx >>= \case+      [_, g, short, wrapped, next, after] -> do+        assert failed (rectH wrapped > rectH after && rectY short == rectY wrapped)+        assert failed (rectY next >= rectY wrapped + rectH wrapped && rectY after >= rectY next + rectH next)+        assertEq failed (rectY g + rectH g) (rectY next + rectH next)+        assertPaintedLines failed ctx ["short", "next", "after"] wrapped+      rs -> assertEq failed 6 (length rs)+  _ <- warmup2 ctx (withInput 1000 400) . scrollArea2D (fixedWH 300 200) $ do+    spacer (Fixed 800) (Fixed 20)+    labelWith fillW "a label wider than its scroller but not its content"+    label "after"+  arenaRects ctx >>= \case+    [_, _, wide, _] -> assert failed (rectW wide > 300) >> assertPaintedLines failed ctx ["after"] wide+    rs -> assertEq failed 4 (length rs)++-- | No stale font colour from last frame's node; font modifiers compose on+-- a label as the helpers do; a baseline row lines up labels, a button and a+-- column's first child (the test font's ascent is 0.8 of its line).+runFontStylesTest :: Context -> IORef Int -> IO ()+runFontStylesTest ctx failed = do   let inp = withInput 800 600-      customCol = colorRGBA 12 34 56 255-      ui = column $ do-        void $ label "Standard Text"-        void $ labelWith (fontSize 24.0 . fontBold . fontItalic . fontUnderline . fontColor customCol) "Composed"-        void $ labelWith fontStrike "Strike Text"+  _ <- runFrame ctx inp (column (labelWith (fontColor red) "painted"))+  spansOf ctx inp ["plain"] (column (button "plain")) >>= assertEq failed [Just True] . map (fmap ((/= red) . snd))+  let custom = colorRGBA 12 34 56 255+      composed = column $ do+        label "Standard Text"+        labelWith (fontSize 24.0 . fontBold . fontItalic . fontUnderline . fontColor custom) "Composed"+        labelWith fontStrike "Strike Text"         bold "Bold Helper"         italic "Italic Helper"         underline "Underline Helper"-  _ <- runFrame ctx inp ui-  spans <- collectTextSpans ctx-  case (spanOf "Standard Text" spans, spanOf "Composed" spans) of-    (Just (std, stdFg), Just (r, fg)) -> do-      assertEq failed (rectH std) 16.0-      assertEq failed (rectH r) 24.0-      assertEq failed fg customCol-      assert failed (stdFg /= customCol)-    _ -> assert failed False+  spansOf ctx inp ["Standard Text", "Composed"] composed >>= \case+    [Just (std, stdFg), Just (r, fg)] -> assertEq failed (16, 24, custom, True) (rectH std, rectH r, fg, stdFg /= custom)+    other -> assertEq failed 2 (length other)   let na = ctxNodeArena ctx   n <- arenaCount na   styles <- mapM (\i -> (,) <$> getText na i <*> getStyleIdx na i) [0 .. n - 1]-  case mapM (`lookup` styles) ["Composed", "Strike Text", "Bold Helper", "Italic Helper", "Underline Helper"] of-    Just [composed, strike, b, i, u] -> do-      assertEq failed (textNodeFontWeight composed) WeightBold-      assertEq failed (textNodeFontStyle composed) FontStyleItalic-      assertEq failed (textNodeTextDecoration composed) DecorationUnderline-      assertEq failed (textNodeTextDecoration strike) DecorationStrikethrough-      assertEq failed (textNodeFontWeight b) WeightBold-      assertEq failed (textNodeFontStyle i) FontStyleItalic-      assertEq failed (textNodeTextDecoration u) DecorationUnderline-    _ -> assert failed False---- | Labels of different sizes, a button and a padded column holding a label all--- share one baseline on a baseline-aligned row: the button by its label and the--- column by its first child, not its larger last one. The row is tall enough--- to hold them, so what follows starts below all of them. The test font's--- ascent is 0.8 of its line height.-runAlignBaselineTest :: Context -> IORef Int -> IO ()-runAlignBaselineTest ctx failed = do-  let ui = column $ do+  assertEq failed (Just [WeightBold, WeightBold]) (map textNodeFontWeight <$> mapM (`lookup` styles) ["Composed", "Bold Helper"])+  assertEq failed (Just [FontStyleItalic, FontStyleItalic]) (map textNodeFontStyle <$> mapM (`lookup` styles) ["Composed", "Italic Helper"])+  assertEq failed (Just [DecorationUnderline, DecorationStrikethrough, DecorationUnderline]) $+    map textNodeTextDecoration <$> mapM (`lookup` styles) ["Composed", "Strike Text", "Underline Helper"]+  fieldVar <- newVar ("Field" :: T.Text)+  let baselined = column $ do         rowWith (tight . gap 8) $ do-          void $ labelWith (tight . alignBaseline . fontSize 32) "Big"-          void $ labelWith (tight . alignBaseline) "small"-          void $ buttonWith alignBaseline "Go"-          columnWith (tight . alignBaseline . padXY 0 5) $ do-            void $ label "nested"-            void $ labelWith (tight . fontSize 24) "second"-        void $ label "after"-  _ <- runFrame ctx (withInput 400 200) ui-  spans <- collectTextSpans ctx-  case mapM (`spanOf` spans) ["Big", "small", "Go", "nested", "second", "after"] of-    Just [(big, _), (small, _), (go, _), (nested, _), (second, _), (after, _)] -> do-      let baseline r = rectY r + 0.8 * rectH r-          near r = abs (baseline r - baseline big) < 0.5-      assert failed (near small)-      assert failed (near go)-      assert failed (near nested)-      assert failed (rectY small > rectY big)-      assert failed (rectY after >= maximum [rectY r + rectH r | r <- [big, small, go, second]])-    _ -> assert failed False+          labelWith (tight . alignBaseline . fontSize 32) "Big"+          labelWith (tight . alignBaseline) "small"+          void (buttonWith alignBaseline "Go")+          textInputConfigured defaultTextInputConfig {ticLayout = alignBaseline . fixedW 90} fieldVar+          columnWith (tight . alignBaseline . padXY 0 5) (label "nested" >> labelWith (tight . fontSize 24) "second")+        label "after"+  spansOf ctx (withInput 500 200) ["Big", "small", "Go", "Field", "nested", "second", "after"] baselined >>= \hits ->+    case map fst <$> sequence hits of+      Just [big, small, go, field, nested, second, after] -> do+        let baseline r = rectY r + 0.8 * rectH r+        assert failed (all (\r -> abs (baseline r - baseline big) < 0.5) [small, go, field, nested] && rectY small > rectY big)+        assert failed (rectY after >= maximum [rectY r + rectH r | r <- [big, small, go, field, second]])+      _ -> assert failed False
test/integration/Cases/HostDraw.hs view
@@ -1,84 +1,101 @@-module Cases.HostDraw-  ( runSquareGeometryTest-  , runExternalTextTest-  , runConcentricCirclesTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.HostDraw (tests) where -import Control.Monad (forM, void)-import Data.IORef (IORef)-import Data.Word (Word32, Word8)+import Spec+import Data.List (nub, sort)+import Data.Primitive.PrimArray (primArrayFromList)+import Data.Primitive.SmallArray (smallArrayFromList)+import Data.Text qualified as T+import Data.Word (Word32) import Foreign.ForeignPtr (withForeignPtr)-import Foreign.Ptr (Ptr) import Foreign.Storable (peekByteOff)-import NanoUI-import NanoUI.Context (setDrawExternalText, setDrawSnapScale, setDrawSquareGeometry)-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)+import NanoUI.Internal.Context (setDrawExternalText, setDrawSnapScale, setDrawSquareGeometry)+import NanoUI.Internal.Store (ptrEq) --- | Alpha of every vertex of every indexed triangle.-triangleAlphas :: DrawData -> IO [(Float, Float, Float)]-triangleAlphas dd =-  withForeignPtr (drawVertices dd) $ \vp ->-    withForeignPtr (drawIndices dd) $ \ip ->-      forM [0, 3 .. drawIndexCount dd - 3] $ \i -> do-        a <- alphaAt vp ip i-        b <- alphaAt vp ip (i + 1)-        c <- alphaAt vp ip (i + 2)-        pure (a, b, c)+tests :: [Spec]+tests =+  [ spec "draw-square-geometry" runSquareGeometryTest+  , spec "draw-thick-rounded-stroke" runThickRoundedStrokeTest+  , spec "draw-geometry-guards" runGeometryGuardsTest+  , spec "draw-glyph-pages" runGlyphPagesTest+  , spec "draw-glyph-kerning" runGlyphKerningTest+  , spec "draw-text-input-font" runTextInputFontTest+  , spec "draw-field-font-style" runFieldFontStyleTest+  , spec "draw-external-text" runExternalTextTest+  , spec "draw-external-text-frames" runExternalTextFramesTest+  , spec "draw-text-font-cache" runTextFontCacheTest+  ]++-- | A font that shapes any text to these glyphs: x, y, w, h and UV corners.+shapedFont :: Float -> [[Float]] -> FontMetrics+shapedFont size glyphs = fm   where-    alphaAt :: Ptr Word8 -> Ptr Word8 -> Int -> IO Float-    alphaAt vp ip i = do-      vi <- peekByteOff ip (i * indexSize) :: IO Word32-      peekByteOff vp (fromIntegral vi * vertexSize + 20)+    fm = (monospaceMetrics size) {fmBackend = Just (FontBackend (\_ -> pure fm) (\_ -> pure (Just shaped)))}+    shaped = ShapedGlyphs (primArrayFromList (concat glyphs)) -controls :: NanoUI ()-controls = column $ do-  void (button "ok")-  void (checkbox "check" True)-  void (slider 0 1 0.5)-  void (button' "menu")+drawn :: Context -> NanoUI a -> IO DrawData+drawn ctx ui = (\(_, dd, _) -> dd) <$> runFrame ctx (withInput 300 200) ui --- | Rounded fills and AA strokes carry transparent fringe vertices next to--- opaque ones. Square geometry emits only flat primitives, so every triangle--- has a uniform alpha.+-- | Square geometry emits only flat primitives: no triangle mixes alphas. runSquareGeometryTest :: Context -> IORef Int -> IO () runSquareGeometryTest ctx failed = do-  let inp = withInput 300 200-      uniform (a, b, c) = a == b && b == c-  (_, _, dRound, _) <- runFrame ctx inp controls-  roundTris <- triangleAlphas dRound-  assert failed (not (all uniform roundTris))+  let uniform (a, b, c) = vA a == vA b && vA b == vA c+      controls = column $ do+        void (button "ok")+        void (withValue True (checkbox "check"))+        void (withValue 0.5 (slider 0 1))+        void (button' "menu")+  assert failed . not . all uniform =<< drawTriangles =<< drawn ctx controls   setDrawSquareGeometry ctx True-  (_, _, dSquare, _) <- runFrame ctx inp controls-  squareTris <- triangleAlphas dSquare-  assert failed (not (null squareTris))-  assert failed (all uniform squareTris)-  setDrawSquareGeometry ctx False+  squareTris <- drawTriangles =<< drawn ctx controls+  assert failed (not (null squareTris) && all uniform squareTris) --- | External text keeps text spans but pushes no text quads, so the buffer--- does not grow with the label length.-runExternalTextTest :: Context -> IORef Int -> IO ()-runExternalTextTest ctx failed = do-  let inp = withInput 400 100-      ui txt = column (void (label txt))-  setDrawExternalText ctx True-  (_, _, dShort, _) <- runFrame ctx inp (ui "ab")-  (_, _, dLong, _) <- runFrame ctx inp (ui "abcdefghijklmnop")-  spans <- collectTextSpans ctx-  assertEq failed (drawVertexCount dLong) (drawVertexCount dShort)-  assert failed (any (\(_, t, _, _, _) -> t == "abcdefghijklmnop") spans)-  setDrawExternalText ctx False+-- | A rounded border wider than twice its radius keeps its ink in its box+-- and, translucent, covers each point of its band once.+runThickRoundedStrokeTest :: Context -> IORef Int -> IO ()+runThickRoundedStrokeTest ctx failed = do+  let border ink = drawing (fixedWH 60 60) $ \(Rect x y _ _) ->+        smallArrayFromList [StrokeRoundedRect (Rect (x + 10) (y + 10) 40 40) 1 8 ink]+  inked <- filter (\v -> vRgb v == (0, 0, 1) && vA v > 0)+    <$> (drawnVertices =<< drawn ctx (border (colorRGBA 0 0 255 255)))+  let extent f = maximum (map f inked) - minimum (map f inked)+  assert failed (not (null inked) && extent vX <= 40 && extent vY <= 40)+  (resp, dd, _) <- runFrame ctx (withInput 300 200) (border (colorRGBA 0 0 255 128))+  tris <- drawTriangles dd+  let Rect rx ry _ _ = respRect resp+      alphaAt px py = sum [l0 * vA a + l1 * vA b + l2 * vA c | (a, b, c) <- tris, Just (l0, l1, l2) <- [barycentric a b c]]+        where+          barycentric (Vertex x0 y0 _ _ _ _) (Vertex x1 y1 _ _ _ _) (Vertex x2 y2 _ _ _ _) =+            let d = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)+                l0 = ((y1 - y2) * (px - x2) + (x2 - x1) * (py - y2)) / d+                l1 = ((y2 - y0) * (px - x2) + (x0 - x2) * (py - y2)) / d+                l2 = 1 - l0 - l1+             in if d /= 0 && l0 >= 0 && l1 >= 0 && l2 >= 0 then Just (l0, l1, l2) else Nothing+      -- Off the triangles' shared edges, which both would count.+      points =+        [ (4.3, 4.6), (0.8, 4.3), (4.3, 0.8), (35.7, 4.6), (4.3, 35.4), (35.7, 35.4), (39.2, 35.7)+        , (4.3, 20.7), (20.7, 4.3), (35.7, 20.3), (20.3, 35.7)+        ]+  forM_ points $ \(dx, dy) -> assert failed (abs (alphaAt (rx + 10 + dx) (ry + 10 + dy) - 128 / 255) < 0.01) --- | Circles sharing a centre stay concentric at a fractional centre, filled--- or stroked, whatever their radii (regression: the bounding box's origin--- was snapped to the pixel grid, so @cx - radius@ rounded differently per--- radius and a small disc drawn over a larger one sat off-centre).-runConcentricCirclesTest :: Context -> IORef Int -> IO ()-runConcentricCirclesTest ctx failed = do-  let inp = withInput 200 100-      ui = void $ customWidget defaultCustomWidgetSpec-        { widgetLayout = fixedWH 120 60 defaultLayout-        , widgetDraw = \_ r -> runCanvas $ do+-- | Nothing clipped to nothing gets a command (a host would draw a pixel),+-- a polygon indexing past its points draws nothing, and circles sharing a+-- fractional centre stay concentric under pixel snapping.+runGeometryGuardsTest :: Context -> IORef Int -> IO ()+runGeometryGuardsTest ctx failed = do+  let opsIn ops = drawn ctx (void (drawing (fixedWH 60 60) (smallArrayFromList . ops)))+  clipped <- opsIn $ \r ->+    [FillRect r colorWhite, PushClip (Rect 0 0 10 10), PushClip (Rect 20 20 10 10), FillRect r red, PopClip, PopClip]+  assert failed (not (drawCmdNull clipped))+  assertEq failed [] [c | c <- drawCmdElems clipped, cmdClipW c <= 0 || cmdClipH c <= 0]+  let tri = primArrayFromList [0, 0, 40, 0, 0, 40]+  bad <- opsIn . const $ [FillPolygon tri (primArrayFromList [0, 3]) (primArrayFromList [0, 1, 100]) (Flat red)]+  indices <- withForeignPtr (drawIndices bad) $ \ip ->+    forM [0 .. drawIndexCount bad - 1] $ \i -> peekByteOff ip (i * indexSize) :: IO Word32+  assert failed (all ((< drawVertexCount bad) . fromIntegral) indices)+  let circles = void $ customWidget defaultCustomWidgetSpec+        { widgetLayout = fixedWH 120 60+        , widgetDraw = \cdc r -> runCanvasFor cdc $ do             let fill = V2 (rectX r + 20.3) (rectY r + 20.3)                 ring = V2 (rectX r + 60.7) (rectY r + 20.2)             drawCircle fill 6 (colorRGBA 255 0 0 255)@@ -87,25 +104,266 @@             drawCircle ring 2.5 (colorRGBA 255 255 0 255)         }   setDrawSnapScale ctx 1-  (_, _, dd, _) <- runFrame ctx inp ui-  setDrawSnapScale ctx 0-  verts <- vertexColours dd-  let centreOf rgb = case [(x, y) | (x, y, c) <- verts, c == rgb] of+  verts <- drawnVertices =<< drawn ctx circles+  let centreOf rgb = case [(vX v, vY v) | v <- verts, vRgb v == rgb] of         [] -> Nothing-        ps ->-          let xs = map fst ps-              ys = map snd ps-           in Just ((minimum xs + maximum xs) / 2, (minimum ys + maximum ys) / 2)+        ps -> let (xs, ys) = unzip ps in Just ((minimum xs + maximum xs) / 2, (minimum ys + maximum ys) / 2)       concentric a b = case (centreOf a, centreOf b) of         (Just (ax, ay), Just (bx, by)) -> abs (ax - bx) < 1e-3 && abs (ay - by) < 1e-3         _ -> False-  assert failed (concentric (1, 0, 0) (0, 1, 0))-  assert failed (concentric (0, 0, 1) (1, 1, 0))+  assert failed (concentric (1, 0, 0) (0, 1, 0) && concentric (0, 0, 1) (1, 1, 0))+  where+    red = colorRGBA 255 0 0 255 --- | Position and colour, without alpha, of every vertex.-vertexColours :: DrawData -> IO [(Float, Float, (Float, Float, Float))]-vertexColours dd =-  withForeignPtr (drawVertices dd) $ \vp ->-    forM [0 .. drawVertexCount dd - 1] $ \i -> do-      let at o = peekByteOff vp (i * vertexSize + o) :: IO Float-      (,,) <$> at 0 <*> at 4 <*> ((,,) <$> at 8 <*> at 12 <*> at 16)+-- | Glyphs on two atlas pages draw under each page's texture with the page+-- taken out of their u; a u outside every page is skipped; and a shaped+-- line far longer than its clip does not grow the draw buffers.+runGlyphPagesTest :: Context -> IORef Int -> IO ()+runGlyphPagesTest ctx failed = do+  let glyph x u = [x, 0, 6, 10, u, 0.5, u + 0.25, 0.75]+  dd <- drawn (withFontMetrics ctx (shapedFont 12 [glyph 0 0.25, glyph 8 1.25, glyph 16 1.25])) (label "abc")+  case [c | c <- drawCmdElems dd, cmdTextureId c == glyphPageTextureId 1, cmdIndexCount c > 0] of+    [cmd] -> assertEq failed 12 (cmdIndexCount cmd)+    other -> assertEq failed 1 (length other)+  assertEq failed [0.25, 0.5] . nub . sort . map vU =<< textureVertices (glyphPageTextureId 1) dd+  firstUs <- map vU <$> textureVertices (glyphPageTextureId 0) dd+  assert failed (0.25 `elem` firstUs && 0.5 `elem` firstUs)+  let pastPages = shapedFont 12 [glyph 0 0.25, glyph 8 (-0.25), glyph 16 4.25, glyph 24 (-1)]+  outside <- drawn (withFontMetrics ctx pastPages) (label "abcd")+  assertEq failed [glyphAtlasTextureId] (nub [cmdTextureId c | c <- drawCmdElems outside, cmdIndexCount c > 0])+  let long = shapedFont 12 [glyph (fromIntegral k * 6) 0.25 | k <- [0 .. 9999 :: Int]]+      scrolled = void (scrollArea (fixedWH 120 40) (label "abc"))+  before <- drawn ctx scrolled+  after <- drawn (withFontMetrics ctx long) scrolled+  assert failed (drawVertices before == drawVertices after)++-- | Kerning moves only a pair's second glyph, and end-aligned ink meets the+-- edge. A missing glyph draws an advance box, but no whitespace does.+runGlyphKerningTest :: Context -> IORef Int -> IO ()+runGlyphKerningTest base failed = do+  let uOf c = if c == 'V' then 0.6 else 0.25+      fm =+        (monospaceMetrics 10)+          { fmAdvance = \c -> if c == 'M' then 12 else 10+          , fmKerning = \a b -> if a == 'A' && b == 'V' then -2 else 0+          , fmGlyph = \c -> Just (GlyphQuad 0 0 6 10 (uOf c) 0 (uOf c + 0.25) 1)+          }+      ctx = withFontMetrics base fm+  (lab, dd) <- warmupDraw ctx (withInput 300 100) $+    rowWith (fixedW 100 . tight . gap 0) (labelWith' (fillW . alignEnd . tight) "AVAV")+  xus <- map (\v -> (vX v, vU v)) <$> textureVertices glyphAtlasTextureId dd+  let aXs = [x | (x, u) <- xus, u < 0.55]+      vXs = [x | (x, u) <- xus, u > 0.55]+      Rect bx _ bw _ = respRect lab+  if null aXs || null vXs+    then assert failed False+    else do+      assertEq failed (8, 18) (minimum vXs - minimum aXs, maximum aXs - 6 - minimum aXs)+      assert failed (abs (maximum vXs - (bx + bw)) <= 0.6)+  spaced <- drawn base (label "a\x00A0\&b\x3000\&c d")+  assertEq failed (4 * 6) (sum [cmdIndexCount c | c <- drawCmdElems spaced, cmdTextureId c == glyphAtlasTextureId])++-- | Every text field kind, with its layout changed by the argument.+fieldKinds :: [(Layout -> Layout) -> NanoUI ()]+fieldKinds =+  [ \f -> void (withValue "abc" (textInputConfigured defaultTextInputConfig {ticLayout = f}))+  , \f -> selectableTextWith f "abc"+  , \f -> void (withValue "abc" (textAreaWith' f))+  , \f -> void (withValue "abc" (searchInputConfigured defaultSearchInputConfig {sicLayout = f}))+  , \f -> void (withValue 123 (numericInputConfigured defaultNumericInputConfig {nicLayout = f}))+  ]++-- | Fields, selectable text and text areas set in a larger font draw their+-- value in it, as a label in that font does.+runTextInputFontTest :: Context -> IORef Int -> IO ()+runTextInputFontTest base failed = do+  -- Each font shapes any text to one glyph of its own size.+  let small = shapedFont 12 [[0, 0, 6, 10, 0.25, 0.5, 0.5, 0.75]]+      large = shapedFont 32 [[0, 0, 16, 26, 0.25, 0.5, 0.5, 0.75]]+      ctx = withFontResolver (withFontMetrics base small) (\_ _ _ _ -> pure (large, False)) (\_ _ _ _ _ -> pure (32, 32))+      big = fontSize 32+      extent ui = do+        (_, dd) <- warmupDraw ctx (withInput 400 200) (column ui)+        -- The glyph's own quad: atlas vertices at its UV corners.+        ps <- filter (\v -> vU v `elem` [0.25, 0.5] && vV v `elem` [0.5, 0.75])+          <$> textureVertices glyphAtlasTextureId dd+        let size f = if null ps then 0 else maximum (map f ps) - minimum (map f ps)+        pure (size vX, size vY)+  extent (labelWith big "Hg") >>= assertEq failed (16, 26)+  mapM (extent . ($ big)) fieldKinds >>= assertEq failed (replicate 5 (16, 26))++-- | Fields, selectable text and text areas draw the layout's weight,+-- decoration and tone as a label does: bold draws each glyph twice (the+-- headless font has no bold face), underline adds a rule, muted recolours.+runFieldFontStyleTest :: Context -> IORef Int -> IO ()+runFieldFontStyleTest ctx failed = do+  mutedFg <- themeMuted <$> getThemeIO ctx+  let red = colorRGBA 255 0 0 255+      frameOf ui = snd <$> warmupDraw ctx (withInput 400 300) (column ui)+      quadsIn col f ui = length . filter ((== col) . snd) <$> (drawQuads =<< frameOf (ui f))+      atlasQuads f ui = (\dd -> sum [cmdIndexCount c `div` 6 | c <- drawCmdElems dd, cmdTextureId c == glyphAtlasTextureId]) <$> frameOf (ui f)+  forM_ fieldKinds $ \ui -> do+    assertEq failed 3 =<< ((-) <$> atlasQuads fontBold ui <*> atlasQuads id ui)+    assertEq failed 1 =<< ((-) <$> quadsIn red (fontUnderline . fontColor red) ui <*> quadsIn red (fontColor red) ui)+    assertEq failed 3 =<< ((-) <$> quadsIn mutedFg fontMuted ui <*> quadsIn mutedFg id ui)++-- | A drawing with @txt@ in each kind of text op: plain from its top-left,+-- bold, at twice the size, and centred under a clip that cuts it.+drawingText :: T.Text -> NanoUI Response+drawingText txt = drawing (fixedWH 300 80) $ \(Rect x y _ _) ->+  smallArrayFromList+    [ DrawText x y 0 1 txt drawingInk+    , DrawTextStyled x (y + 20) defaultTextFont {textFontWeight = WeightBold} txt drawingInk+    , DrawTextAligned x (y + 40) 0 1 2 defaultTextFont txt drawingInk+    , PushClip (Rect (x + 140) (y + 60) 20 20)+    , DrawText (x + 150) (y + 70) 0.5 0.5 txt drawingInk+    , PopClip+    ]++drawingInk :: Color+drawingInk = colorRGBA 200 40 40 255++-- | The spans 'collectRasterSpans' adds for drawing text: those past the+-- node spans, base then overlay.+drawnSpans :: Context -> Input -> IO ([(Rect, T.Text, Color, Color, Rect)], [(Rect, T.Text, Color, Color, Rect)])+drawnSpans ctx inp = do+  (base, overlay) <- collectRasterSpans ctx inp+  nodeBase <- collectTextSpans ctx+  nodeOverlay <- collectOverlayTextSpans ctx inp+  pure (drop (length nodeBase) base, drop (length nodeOverlay) overlay)++textsOf :: [(Rect, T.Text, Color, Color, Rect)] -> [T.Text]+textsOf ss = [t | (_, t, _, _, _) <- ss]++-- | A context drawing text externally, as a host that draws spans does.+externalContext :: IO Context+externalContext = newContext >>= \c -> c <$ setDrawExternalText c True++-- | External text pushes no text quads; labels and drawing text become+-- spans, drawing text after the node spans, in op order, with its line box,+-- ink and clip (overlay spans in a floating window). Without it (the SDL+-- host) drawing text draws quads and adds no spans.+runExternalTextTest :: Context -> IORef Int -> IO ()+runExternalTextTest internal failed = do+  let inp = withInput 400 100+      txt = "abcdefghijklmnop"+      -- The vertex counts for a short text and a long one.+      vertexCounts :: Context -> (T.Text -> NanoUI x) -> IO (Int, Int)+      vertexCounts c ui = (,) <$> count c (ui "ab") <*> count c (ui txt)+      count :: Context -> NanoUI x -> IO Int+      count c ui = drawVertexCount . snd <$> warmupDraw c inp ui+  ctx <- externalContext+  vertexCounts ctx (column . label) >>= uncurry (assertEq failed)+  assert failed . hasText txt =<< collectTextSpans ctx+  vertexCounts ctx drawingText >>= uncurry (assertEq failed)+  resp <- warmup2 ctx inp (drawingText txt)+  (base, overlay) <- collectRasterSpans ctx inp+  (spans', spansOver) <- drawnSpans ctx inp+  let r@(Rect x y _ _) = respRect resp+      Rect cx cy _ _ = drawTextBox (ctxFontMetrics ctx) (x + 150) (y + 70) 0.5 0.5 txt+  assertEq failed [txt, txt, txt, txt] (textsOf spans')+  assertEq failed [(x, y), (x, y + 20), (x, y + 40), (cx, cy)] [(bx, by) | (Rect bx by _ _, _, _, _, _) <- spans']+  assertEq failed [r, r, r, Rect (x + 140) (y + 60) 20 20] [clip | (_, _, _, _, clip) <- spans']+  assert failed (all (\(_, _, fg, bg, _) -> fg == drawingInk && bg == Color 0) spans')+  -- Twice the size: the aligned line is twice as tall as the plain one.+  assertEq failed [12, 12, 24, 12] [h | (Rect _ _ _ h, _, _, _, _) <- spans']+  assertEq failed spans' (drop (length base - 4) base)+  assert failed (null spansOver && not (hasText txt overlay))+  floating <- externalContext+  let winInp = withInput 600 300+  _ <- warmup2 floating winInp (floatingWindow' (constVar True) "W" (drawingText "floating"))+  (winBase, winOverlay) <- drawnSpans floating winInp+  assertEq failed ([], replicate 4 "floating") (winBase, textsOf winOverlay)+  nodesOfType NodeWindow floating >>= \case+    (_, win) : _ -> assert failed (all (\(_, _, _, _, clip) -> covers win clip) winOverlay)+    [] -> assert failed False+  vertexCounts internal drawingText >>= \(short, long) -> assertGt failed long short+  assertEq failed ([], []) =<< drawnSpans internal inp++-- | Drawing spans survive a reused frame and reuse off, are culled to the+-- viewport's glyph slack and clipped to it, and on a clip frame come only+-- from drawings it repaints.+runExternalTextFramesTest :: Context -> IORef Int -> IO ()+runExternalTextFramesTest _ failed = do+  let inp = withInputOff 400 300+  ctx <- externalContext+  let frame' = runFrame ctx inp (drawingText "reused") >>= \(_, !dd, _) -> pure dd+      reused = assertEq failed (replicate 4 "reused") . textsOf . fst =<< drawnSpans ctx inp+  replicateM_ 2 frame'+  d1 <- frame'+  reused+  d2 <- frame'+  -- The case returns the field itself, as Cases.Cache does for 'ptrEq'.+  assert failed (ptrEq d1 d2)+  reused+  setDrawReuse ctx False+  _ <- frame'+  reused+  culled <- externalContext+  let line i = T.pack ("line " ++ show i)+      lines' = [0 .. 149 :: Int]+      tall = scrollArea (fixedWH 300 200) . drawing (fixedWH 280 2000) $ \(Rect x y _ _) ->+        smallArrayFromList [DrawText x (y + 13 * fromIntegral i) 0 1 (line i) drawingInk | i <- lines']+  (sid, _) <- warmup2 culled inp tall+  setScrollOffsetIO culled sid 900+  (_, resp) <- warmup2 culled inp tall+  (spans', _) <- drawnSpans culled inp+  assertJustM failed (getScrollMetricsIO culled sid) $ \m -> do+    let view@(Rect _ vy _ vh) = scrollViewport m+        dr@(Rect _ dy _ _) = respRect resp+        lh = fmLineHeight (ctxFontMetrics culled)+        -- 'NanoUI.Internal.Draw.glyphSlackLines' line heights.+        slack = 4 * lh+        inView i = let top = dy + 13 * fromIntegral i in top + lh > vy && top < vy + vh+    assert failed (length spans' > 10 && length spans' < 40)+    assert failed (all (\(Rect _ top _ _, _, _, _, _) -> top + lh + slack >= vy && top - slack <= vy + vh) spans')+    assert failed (all ((`elem` textsOf spans') . line) (filter inView lines'))+    assert failed (all (\(_, _, _, _, clip) -> Just clip == rectIntersect view dr) spans')+  damaged <- externalContext+  let versioned version txt = column $ do+        _ <- drawingVersioned version (fixedWH 200 40) $ \(Rect x y _ _) -> smallArrayFromList [DrawText x y 0 1 txt drawingInk]+        box (fixedWH 10 80) (colorRGBA 0 0 0 0)+        button' "far"+  b <- warmup2 damaged inp (versioned 1 "before")+  let hover = inp {inputMousePos = centerOf b}+  writeIORef (ctxPaintFull damaged) False+  _ <- runFrame damaged hover (versioned 1 "before")+  takeDamage damaged >>= assert failed . (/= DamageFull)+  assertEq failed ([], []) =<< drawnSpans damaged hover+  _ <- runFrame damaged hover (versioned 2 "after")+  dmg <- takeDamage damaged+  (after, _) <- drawnSpans damaged hover+  assertEq failed ["after"] (textsOf after)+  case dmg of+    DamageClip d -> assert failed (all (\(_, _, _, _, clip) -> covers (rectInflate 1 d) clip) after)+    DamageFull -> assert failed False++-- | emitDrawOps keeps a 2-slot MRU resolved-font cache shared by+-- DrawTextStyled and DrawTextAligned, promotes slot 2 on hit, and ignores+-- decoration when matching cached entries.+runTextFontCacheTest :: Context -> IORef Int -> IO ()+runTextFontCacheTest base failed = do+  resolves <- newIORef (0 :: Int)+  let fm = monospaceMetrics 12+      ctx =+        withFontResolver+          (withFontMetrics base fm)+          (\_ _ _ _ -> modifyIORef' resolves (+ 1) >> pure (fm, False))+          (\_ _ _ _ _ -> pure (12, 12))+      fA = defaultTextFont {textFontSize = 18}+      fAUnder = fA {textFontDecoration = DecorationUnderline}+      fB = fA {textFontWeight = WeightBold}+      fC = fA {textFontStyle = FontStyleItalic}+      ui =+        drawing (fixedWH 200 120) $ \(Rect x y _ _) ->+          smallArrayFromList+            [ DrawTextStyled x y fA "" drawingInk+            , DrawTextStyled x y fA "a" drawingInk+            , DrawTextStyled x (y + 15) fB "b" drawingInk+            , DrawTextStyled x (y + 30) fAUnder "c" drawingInk+            , DrawTextStyled x (y + 45) fC "d" drawingInk+            , DrawTextAligned x (y + 60) 0 1 1 fA "e" drawingInk+            , DrawTextStyled x (y + 75) fC "f" drawingInk+            ]+  _ <- drawn ctx ui+  assertEq failed 3 =<< readIORef resolves
+ test/integration/Cases/Images.hs view
@@ -0,0 +1,262 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Images (tests) where++import Spec+import Data.ByteString qualified as BS+import Data.List (unzip4)+import Data.Maybe (fromMaybe)+import Data.Sequence qualified as Seq+import Data.Text qualified as T+import NanoUI.Internal.Context (lookupImageSize, lookupImageUv)++tests :: [Spec]+tests =+  [ spec "image-fit" runImageFitTest+  , spec "image-size" runImageSizeTest+  , spec "image-look" runImageLookTest+  , spec "image-rotation" runImageRotationTest+  , spec "image-damage" runImageDamageTest+  , spec "image-rgba-lifetime" runImageRgbaLifetimeTest+  ]++-- | One corner of a drawn quad: x, y, u, v and alpha.+type Corner = (Float, Float, Float, Float, Float)++-- | Run @ui@ in a column for two frames; return its result, the draw data, and each atlas+-- quad's corners with UVs normalized to image @iid@'s 0-1 range.+frame :: Context -> ImageId -> NanoUI a -> IO (a, DrawData, [[Corner]])+frame ctx iid ui = do+  (a, dd, _) <- run2Frames ctx (withInput 400 400) (column ui)+  (a0, b0, a1, b1) <- fromMaybe (0, 0, 1, 1) <$> lookupImageUv ctx iid+  let corner v = (vX v, vY v, (vU v - a0) / (a1 - a0), (vV v - b0) / (b1 - b0), vA v)+      -- Quad indices are a b c a c d.+      quads (p : q : r : _ : _ : t : rest) = map corner [p, q, r, t] : quads rest+      quads _ = []+  (,,) a dd . quads <$> textureVertices atlasTextureId dd++-- | Each quad's position relative to @o@, its size, and its UV bounds.+bounds :: V2 -> [[Corner]] -> [[Float]]+bounds (V2 ox oy) quads =+  [ [x0 - ox, y0 - oy, maximum xs - x0, maximum ys - y0, minimum us, minimum vs, maximum us, maximum vs]+  | cs <- quads+  , let (xs, ys, us, vs) = unzip4 [(x, y, u, v) | (x, y, u, v, _) <- cs]+        (x0, y0) = (minimum xs, minimum ys)+  ]++-- | The quads' bounds relative to the response's corner.+boundsAt :: Response -> [[Corner]] -> [Float]+boundsAt r = concat . bounds (V2 (rectX (respRect r)) (rectY (respRect r)))++-- | The alpha of every corner drawn.+alphas :: (a, b, [[Corner]]) -> [Float]+alphas (_, _, quads) = [a | (_, _, _, _, a) <- concat quads]++near :: Float -> Float -> Bool+near a b = abs (a - b) < 1.0e-3++-- | Assert equal-length lists of nearly equal numbers; on failure show both.+assertNear :: IORef Int -> [Float] -> [Float] -> IO ()+assertNear failed want got = unless (length want == length got && and (zipWith near want got)) (assertEq failed want got)++-- | Register a white @w@ x @h@ image under id @n@.+whiteImage :: Context -> Int -> Int -> Int -> IO ImageId+whiteImage ctx n w h = ImageId n <$ registerImage ctx (ImageId n) w h (BS.replicate (w * h * 4) 255)++-- | Each fit and alignment places wide and tall images in wide and tall+-- boxes, cropping via UVs, never past the box; the default stretches like+-- 'image'. A crop is the whole image for size and fit; a scale zooms.+runImageFitTest :: Context -> IORef Int -> IO ()+runImageFitTest ctx failed = do+  wide <- whiteImage ctx 1 40 20+  tall <- whiteImage ctx 2 20 40+  big <- whiteImage ctx 3 200 100+  let (wb, tb, full, mid) = ((100, 80), (60, 120), [0, 0, 1, 1], (AlignCenter, AlignMiddle))+      fitted (bw, bh) fit (ax, ay) = defaultImageConfig {icLayout = fixedWH bw bh, icFit = fit, icAlignX = ax, icAlignY = ay}+      -- The rect's size, then the quads' bounds.+      drawnWith iid cfg =+        (\(r, _, quads) -> rectW (respRect r) : rectH (respRect r) : boundsAt r quads) <$> frame ctx iid (imageConfigured' cfg iid)+      sized (bw, bh) = [bw, bh]+  forM_+    [ (wide, wb, FitContain, mid, [0, 15, 100, 50] ++ full), (wide, wb, FitCover, mid, [0, 0, 100, 80, 0.1875, 0, 0.8125, 1])+    , (wide, wb, FitFill, mid, [0, 0, 100, 80] ++ full), (wide, wb, FitNone, mid, [30, 30, 40, 20] ++ full)+    , (wide, wb, FitScaleDown, mid, [30, 30, 40, 20] ++ full), (big, wb, FitScaleDown, mid, [0, 15, 100, 50] ++ full)+    , (big, wb, FitNone, mid, [0, 0, 100, 80, 0.25, 0.1, 0.75, 0.9]), (wide, tb, FitContain, mid, [0, 45, 60, 30] ++ full)+    , (wide, tb, FitCover, mid, [0, 0, 60, 120, 0.375, 0, 0.625, 1]), (tall, wb, FitContain, mid, [30, 0, 40, 80] ++ full)+    , (tall, wb, FitCover, mid, [0, 0, 100, 80, 0, 0.3, 1, 0.7]), (tall, tb, FitContain, mid, [0, 0, 60, 120] ++ full)+    , (wide, tb, FitContain, (AlignStart, AlignTop), [0, 0, 60, 30] ++ full)+    , (wide, tb, FitContain, (AlignEnd, AlignBottom), [0, 90, 60, 30] ++ full)+    , (wide, wb, FitCover, (AlignEnd, AlignMiddle), [0, 0, 100, 80, 0.375, 0, 1, 1])+    , (tall, wb, FitCover, (AlignStart, AlignTop), [0, 0, 100, 80, 0, 0, 1, 0.4])+    ]+    $ \(iid, box', fit, align, want) -> drawnWith iid (fitted box' fit align) >>= assertNear failed (sized box' ++ want)+  let drawn ui = (\(_, _, quads) -> bounds (V2 0 0) quads) <$> frame ctx wide ui+  plain <- drawn (image (fixedWH 100 80) wide)+  drawn (imageConfigured defaultImageConfig {icLayout = fixedWH 100 80} wide) >>= assertEq failed plain+  forM_+    [ (defaultImageConfig {icCrop = Just (Rect 10 0 20 20)}, [20, 20, 0, 0, 20, 20, 0.25, 0, 0.75, 1])+    , (defaultImageConfig {icCrop = Just (Rect 30 10 100 100)}, [10, 10, 0, 0, 10, 10, 0.75, 0.5, 1, 1])+    , (defaultImageConfig {icLayout = fixedWH 100 80, icScale = 2}, [100, 80, 0, 0, 100, 80, 0.25, 0.25, 0.75, 0.75])+    , (defaultImageConfig {icLayout = fixedWH 100 80, icScale = 0.5}, [100, 80, 25, 20, 50, 40, 0, 0, 1, 1])+    , ( defaultImageConfig {icLayout = fixedWH 100 80, icCrop = Just (Rect 0 0 20 20), icScale = 2}+      , [100, 80, 0, 0, 100, 80, 0.125, 0.25, 0.375, 0.75] )+    , ( defaultImageConfig {icLayout = fixedWH 100 80, icCrop = Just (Rect 0 0 20 20), icFit = FitContain}+      , [100, 80, 10, 0, 80, 80, 0, 0, 0.5, 1] )+    ]+    $ \(cfg, want) -> drawnWith wide cfg >>= assertNear failed want+  -- Empty content fits as an empty rect rather than dividing by zero.+  assertEq failed (Rect 10 10 0 0) (fitRect FitContain AlignStart AlignTop (0, 10) (Rect 10 10 100 80))++-- | An unsized axis takes the image's size or keeps its aspect beside a+-- sized one, within limits; a layout 'aspect' overrides it, and a plain+-- 'image' (or an unregistered one) gets the default size.+runImageSizeTest :: Context -> IORef Int -> IO ()+runImageSizeTest ctx failed = do+  wide <- whiteImage ctx 1 40 20+  let sized ui = (\(Rect _ _ w h) -> (w, h)) . respRect <$> warmup2 ctx (withInput 400 400) (columnWith (tight . fixedW 300) ui)+      configured f iid = imageConfigured' defaultImageConfig {icLayout = f} iid+  forM_+    [ (configured id wide, (40, 20)), (configured (fixedW 80) wide, (80, 40)), (configured (fixedH 10) wide, (20, 10))+    , (configured (maxW 20) wide, (20, 10)), (configured (fixedWH 30 30) wide, (30, 30)), (configured id (ImageId 99), (32, 32))+    , (configured fillW wide, (300, 150)), (configured (fillW . aspect 1) wide, (300, 300)), (image' fillW wide, (300, 32))+    , (rowWith (tight . gap 0 . fillW) (configured fillW wide <* box (fixedWH 100 10) (colorRGBA 0 0 0 0)), (200, 100))+    ]+    $ \(ui, want) -> sized ui >>= assertEq failed want++-- | Opacity, tint and disabling fade configured images, drawing image ops+-- (also rotated or cropped) and configured SVG icons. An image id past what+-- a 'Float' holds exactly still draws its own image.+runImageLookTest :: Context -> IORef Int -> IO ()+runImageLookTest ctx failed = do+  iid <- whiteImage ctx 1 40 20+  let cfg = defaultImageConfig {icLayout = fixedWH 20 20}+      alphasOf ui = alphas <$> frame ctx iid ui+      half = replicate 4 (128 / 255)+  alphasOf (imageConfigured cfg iid) >>= assertEq failed (replicate 4 1)+  alphasOf (imageConfigured cfg {icOpacity = 0.5} iid) >>= assertNear failed half+  alphasOf (imageConfigured cfg {icOpacity = 0.5, icLayout = fontColor (colorRGBA 255 0 0 200) . icLayout cfg} iid)+    >>= assertNear failed (replicate 4 (100 / 255))+  faded <- alphasOf (disabledWhen True (imageConfigured cfg {icOpacity = 0.5} iid))+  assert failed (length faded == 4 && all (< 128 / 255) faded)+  alphasOf (imageConfigured cfg {icOpacity = 0} iid) >>= assertEq failed []+  let painted paint = frame ctx iid (canvas (fixedWH 40 40) paint)+      drawn paint = (\(r, _, quads) -> boundsAt r quads) <$> painted paint+  drawn (\(Rect x y _ _) -> drawImage (Rect (x + 10) (y + 5) 16 8) iid colorWhite) >>= assertNear failed [10, 5, 16, 8, 0, 0, 1, 1]+  drawn (\(Rect x y _ _) -> drawImageWith (imageDraw (Rect (x + 10) (y + 10) 16 8) iid) {imageAngle = pi / 2})+    >>= assertNear failed [14, 6, 8, 16, 0, 0, 1, 1]+  drawn (\(Rect x y _ _) -> drawImageWith (imageDraw (Rect x y 8 8) iid) {imageUV = Rect 0.5 0 0.5 1})+    >>= assertNear failed [0, 0, 8, 8, 0.5, 0, 1, 1]+  alphas <$> painted (\r -> drawImageWith (imageDraw r iid) {imageOpacity = 0.5}) >>= assertNear failed half+  alphas <$> painted (\r -> drawImageWith (imageDraw r iid) {imageOpacity = 0}) >>= assertEq failed []+  _ <- whiteImage ctx (2 ^ (24 :: Int)) 40 20+  big <- whiteImage ctx (2 ^ (24 :: Int) + 1) 20 40+  forM_ [image (fixedWH 20 40), imageConfigured defaultImageConfig {icLayout = fixedWH 20 40, icFit = FitContain}] $ \img -> do+    (_, _, quads) <- frame ctx big (img big)+    assertNear failed [0, 0, 1, 1] (concat [drop 4 q | q <- bounds (V2 0 0) quads])+  doc <- either fail pure (parseSvg "<svg viewBox='0 0 24 24'><rect x='2' y='2' width='20' height='20'/></svg>")+  let quadsOf ui = (\(_, dd, _) -> dd) <$> run2Frames ctx (withInput 200 200) (column ui) >>= drawQuads+  plain <- quadsOf (svgIconWith (fixedWH 16 16) doc)+  quadsOf (svgIconConfigured defaultImageConfig {icLayout = fixedWH 16 16} doc) >>= assertEq failed plain+  quadsOf (svgIconConfigured defaultImageConfig {icLayout = fixedWH 16 16 . fontColor colorWhite, icOpacity = 0.5} doc)+    >>= assert failed . any ((== colorRGBA 255 255 255 128) . snd)++-- | A solid rotation reserves the rotated bounds; a floating one keeps the layout and is clipped.+runImageRotationTest :: Context -> IORef Int -> IO ()+runImageRotationTest ctx failed = do+  wide <- whiteImage ctx 1 40 20+  let turned rot = imageConfigured' defaultImageConfig {icRotation = rot} wide+      sizeOf rot = (\(r, _, _) -> [rectW (respRect r), rectH (respRect r)]) <$> frame ctx wide (turned rot)+  sizeOf (RotateFloating (pi / 2)) >>= assertEq failed [40, 20]+  sizeOf (RotateSolid (pi / 2)) >>= assertNear failed [20, 40]+  -- Layout rounds widget sizes to whole pixels.+  [dw, dh] <- sizeOf (RotateSolid (pi / 4))+  assert failed (abs (dw - 60 / sqrt 2) < 1 && dw == dh)+  -- A quarter turn fills its reserved 20x40 box, with the image's top-left at the box's top-right.+  (solid, _, solidQuads) <- frame ctx wide (turned (RotateSolid (pi / 2)))+  let Rect bx by bw bh = respRect solid+  assertNear failed [0, 0, bw, bh, 0, 0, 1, 1] (boundsAt solid solidQuads)+  assert failed (or [near x (bx + bw) && near y by | (x, y, u, v, _) <- concat solidQuads, near u 0, near v 0])+  -- A floating image turned 45 degrees overflows its rect, which clips it.+  (floating, floatDraw, floatQuads) <- frame ctx wide (turned (RotateFloating (pi / 4)))+  let Rect _ _ fw fh = respRect floating+  case bounds (V2 (rectX (respRect floating)) (rectY (respRect floating))) floatQuads of+    [x : y : w : h : _] -> assert failed (x < 0 && y < 0 && x + w > fw && y + h > fh)+    other -> assertEq failed 1 (length other)+  assertEq failed [respRect floating] [Rect (cmdClipX c) (cmdClipY c) (cmdClipW c) (cmdClipH c) | c <- drawCmdElems floatDraw, cmdTextureId c == atlasTextureId]+  -- A changed angle (as in an animation) repaints the image.+  _ <- runFrame ctx (withInput 400 400) (column (turned (RotateFloating (pi / 3))))+  takeDamage ctx >>= assert failed . (`clipCovers` respRect floating)+  -- A rotated image that only moves keeps its ops, translated.+  let at top = (\(_, _, quads) -> bounds (V2 0 top) quads) <$> frame ctx wide (box (fixedWH 10 top) (colorRGBA 0 0 0 0) >> turned (RotateFloating (pi / 3)))+  high <- at 10+  low <- at 30+  assertEq failed 1 (length low)+  assertNear failed (concat high) (concat low)++-- | A new look (an animated fade) or a new image at the same rect repaints+-- the node; drawing it unchanged does not.+runImageDamageTest :: Context -> IORef Int -> IO ()+runImageDamageTest ctx failed = do+  writeIORef (ctxPaintFull ctx) False+  a <- whiteImage ctx 1 40 20+  b <- whiteImage ctx 2 40 20+  let inp = withInput 400 400+      looked o = imageConfigured' defaultImageConfig {icLayout = fixedWH 80 40, icFit = FitContain, icOpacity = o}+      repaints :: (x -> NanoUI Response) -> x -> x -> IO ()+      repaints ui x y = do+        r <- warmup2 ctx inp (column (ui x))+        forM_ [(x, damageIsEmpty), (y, (`clipCovers` respRect r)), (y, damageIsEmpty)] $ \(v, ok) ->+          runFrame ctx inp (column (ui v)) >> takeDamage ctx >>= assert failed . ok+  repaints (\o -> looked o a) 1 0.5+  repaints (looked 1) a b++-- | 'useImageRgba' keeps one image per key while called and frees it on a+-- new key or a skipped frame, for the next to reuse; 'registerImageRgba'+-- keeps an image until 'releaseImageRgba'. A failed image does not stop+-- the rest of a 'registerImages' batch.+runImageRgbaLifetimeTest :: Context -> IORef Int -> IO ()+runImageRgbaLifetimeTest ctx failed = do+  textImage <- newImageHandle+  intImage <- newImageHandle+  scopedImage <- newImageHandle+  let hook owner k = useImageRgba owner k 8 8 (BS.replicate (8 * 8 * 4) 90)+      frameOf :: NanoUI x -> IO x+      frameOf = evalUi ctx (withInput 100 100)+      originOf iid = fmap (\(u0, v0, _, _) -> (u0, v0)) <$> lookupImageUv ctx iid+      sizeIs want iid = lookupImageSize ctx iid >>= assertEq failed want+  Just a <- frameOf (hook textImage ("a" :: T.Text))+  frameOf (hook textImage ("a" :: T.Text)) >>= assertEq failed (Just a)+  sizeIs (Just (8, 8)) a+  aAt <- originOf a+  Just b <- frameOf (hook textImage ("b" :: T.Text))+  assert failed (b /= a)+  sizeIs Nothing a+  originOf b >>= assertEq failed aAt+  frameOf (pure ())+  sizeIs Nothing b+  Just c <- frameOf (hook intImage (1 :: Int))+  originOf c >>= assertEq failed aAt+  assert failed (c /= a && c /= b)+  let shown on = (,) <$> hook intImage (1 :: Int) <*> scope (if on then hook scopedImage ("s" :: T.Text) else pure Nothing)+  (c1, s) <- frameOf (shown True)+  assertEq failed (Just c) c1+  assertJust failed s $ \sid -> do+    sizeIs (Just (8, 8)) sid+    frameOf (shown False) >>= assertEq failed (Just c) . fst+    sizeIs Nothing sid+  own <- newContext+  let register = freshImageId >>= \iid -> (iid,) <$> registerImageRgba iid 8 8 (BS.replicate (8 * 8 * 4) 90)+      ownFrame :: NanoUI x -> IO x+      ownFrame = evalUi own (withInput 100 100)+  (r, okR) <- ownFrame register+  ownFrame (pure ())+  lookupImageSize own r >>= assertEq failed (Just (8, 8))+  rAt <- lookupImageUv own r+  ownFrame (releaseImageRgba r)+  lookupImageSize own r >>= assertEq failed Nothing+  (r2, okR2) <- ownFrame register+  assert failed (okR && okR2)+  lookupImageUv own r2 >>= assertEq failed rAt+  let pixel = BS.replicate 4 255+      batch = Seq.fromList [(ImageId 0, 1, 1, pixel), (ImageId 42, 1, 1, pixel)]+  assertEq failed False =<< registerImages own batch+  assert failed . (/= Nothing) =<< lookupImageUv own (ImageId 42)
+ test/integration/Cases/Ime.hs view
@@ -0,0 +1,371 @@+{-# OPTIONS_GHC -O0 #-}+-- | IME composition: shown at the focused field's caret without changing+-- the value, its keys edit nothing, its commit inserts text, and the frame+-- reports where the candidate window goes.+module Cases.Ime (tests) where++import Spec+import Data.Primitive.PrimArray (primArrayFromList)+import Data.Text qualified as T+import GHC.Stack (HasCallStack)+import NanoUI.Internal.Context (setDrawSquareGeometry)+import NanoUI.Shortcut+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "ime-input" runImeInputTest+  , pixelSpec "ime-preedit-inline" runImePreeditInlineTest+  , pixelSpec "ime-commit" runImeCommitTest+  , pixelSpec "ime-keys" runImeKeysTest+  , pixelSpec "ime-text-area" runImeTextAreaTest+  , pixelSpec "ime-area-paint" runImeAreaPaintTest+  , pixelSpec "ime-scroll" runImeScrollTest+  , pixelSpec "ime-bidi" runImeBidiTest+  , pixelSpec "ime-owner" runImeOwnerTest+  , pixelSpec "ime-damage" runImeDamageTest+  , pixelSpec "ime-repeated-pass" runImeRepeatedPassTest+  , pixelSpec "ime-shortcuts" runImeShortcutsTest+  , pixelSpec "ime-custom-widget" runImeCustomWidgetTest+  , pixelSimSpec "ime-purpose" 400 300 purposeUi imePurpose+  ]++inp :: Input+inp = withInput 400 300++-- | Input composing @txt@ with the IME caret @cursor@ characters in.+composing :: T.Text -> Int -> Input -> Input+composing txt cursor = applyComposition txt cursor 0++-- | Input ending the composition and committing @txt@.+commit :: T.Text -> Input -> Input+commit txt i = (applyComposition "" 0 0 i) {inputChars = txt}++-- | A frame composing (the composition lasts until changed or ended), and+-- one committing.+compose :: T.Text -> Int -> Sim a a+compose txt cursor = frameWith (composing txt cursor)++commitText :: T.Text -> Sim a a+commitText txt = frameWith (commit txt)++-- | Whether the frame reported a change, and the value.+changed :: (Response, T.Text) -> (Bool, T.Text)+changed (r, v) = (respChanged r, v)++-- | Every @yes@ text is a frame span, and no span contains any @no@ text.+shown :: HasCallStack => [T.Text] -> [T.Text] -> Sim a ()+shown yes no = do+  ts <- map (\(_, t, _, _, _) -> t) <$> spans+  check (all (`elem` ts) yes && not (or [n `T.isInfixOf` t | n <- no, t <- ts]))++type Field = (Response, T.Text)++imeArea :: Sim a (Maybe TextInputArea)+imeArea = onContext textInputArea++-- | Run the script on @widget@ holding @v@ in a column, focused by Tab, its+-- caret @back@ characters from the end.+field :: Context -> IORef Int -> T.Text -> Int -> (Var T.Text -> NanoUI Response) -> Sim Field () -> IO ()+field ctx failed v back widget script = do+  ref <- newVar v+  runSim ctx failed inp (column (held ref widget)) $+    pressTab 1 >> replicateM_ back (pressKey KeyLeft) >> script++-- | Composition persists until changed or ended; bad positions clamp.+runImeInputTest :: Context -> IORef Int -> IO ()+runImeInputTest _ failed = do+  let comp s l = inputComposition (applyComposition "かな" s l inp)+      next = clearEphemeral (composing "かな" 1 inp) {inputChars = "x"}+      clamped = [Composition "かな" 1 1, Composition "かな" 2 0, Composition "かな" 1 1]+  assertEq failed [comp 1 1, comp (-1) (-1), comp 1 9] (Just <$> clamped)+  assertEq failed (inputComposition (commit "" (composing "かな" 1 inp))) Nothing+  assertEq failed (inputComposition next, inputChars next) (Just (Composition "かな" 1 0), "")+  assert failed (inputInteracted inp (composing "か" 1 inp))+  assert failed (inputInteracted (composing "か" 1 inp) (composing "かな" 2 inp))++-- | Composition replaces any selection at the caret in plain, search and+-- (masked) password fields; the value and change flag are unchanged.+runImePreeditInlineTest :: Context -> IORef Int -> IO ()+runImePreeditInlineTest ctx failed = do+  field ctx failed "abcd" 2 textInput' $ do+    forM_ [("xyz", "abxyzcd"), ("xyzw", "abxyzwcd")] $ \(c, line) -> do+      checkEq (False, "abcd") . changed =<< compose c (T.length c)+      shown [line] ["abcd"]+    _ <- commitText "" >> chord (shift <> key KeyRight)+    checkEq "abcd" . snd =<< compose "xyz" 3+    shown ["abxyzd"] []+  let password = textInputConfigured' defaultTextInputConfig {ticPassword = True}+  forM_ [(searchInput' "Find", "abxy", []), (password, "****", ["xy"])] $ \(widget, line, hidden) -> do+    c <- newPixelContext+    field c failed "ab" 0 widget (compose "xy" 2 >> shown [line] hidden)++-- | A commit inserts at the caret and ends the composition before any new+-- one in the same input. An empty field shows the composition instead of its+-- placeholder.+runImeCommitTest :: Context -> IORef Int -> IO ()+runImeCommitTest ctx failed = do+  field ctx failed "abcd" 2 textInput' $ do+    _ <- compose "かんじ" 3+    checkEq (True, "ab漢字cd") . changed =<< commitText "漢字"+    shown ["ab漢字cd"] ["かんじ"]+    checkEq "ab漢字xcd" . snd =<< frameWith (\i -> (composing "y" 1 i) {inputChars = "x"})+    shown ["ab漢字xycd"] []+  c <- newPixelContext+  field c failed "" 0 (textInputConfigured' defaultTextInputConfig {ticPlaceholder = "Name"}) $ do+    _ <- compose "かな" 1+    shown ["かな"] ["Name"]+    imeArea >>= (`checkJust` \(TextInputArea (Rect _ _ aw _) cursor _) -> checkEq (32, 16) (aw, cursor))+    checkEq "仮名" . snd =<< commitText "仮名"++-- | A view rerun after a hook write shows the composition and commits it+-- once. ('respChanged' comes from the rerun, which has no events, so+-- 'runImeCommitTest' cannot check this.)+runImeRepeatedPassTest :: Context -> IORef Int -> IO ()+runImeRepeatedPassTest ctx failed =+  field ctx failed "ab" 0 (\v -> textInput' v <* rerun) $ do+    compose "xy" 2 >> shown ["abxy"] []+    checkEq "abz" . snd =<< commitText "z"+  where+    rerun = useVar (0 :: Int) >>= \n -> readVar n >>= writeVar n . (+ 1)++-- | While composing, keys belong to the IME: none edits, submits or moves+-- focus, and Escape does not quit. An empty composition counts as none.+runImeKeysTest :: Context -> IORef Int -> IO ()+runImeKeysTest ctx failed =+  field ctx failed "abcd" 2 (\v -> textInput' v <* button "After") $ do+    let escapeKept f = do+          i <- keyInp KeyEscape . f <$> getInput+          frameWith (const i) >> onContext (`overlayConsumesQuit` i)+    _ <- compose "xyz" 3+    let keys = [KeyBackspace, KeyDelete, KeyLeft, KeyRight, KeyHome, KeyEnd, KeyEnter, KeyEscape, KeyTab]+    forM_ keys $ \k -> do+      (resp, value) <- pressKey k+      check (value == "abcd" && not (respChanged resp || respSubmitted resp))+      checkEq (respId resp) =<< focusedId+    shown ["abxyzcd"] []+    check =<< escapeKept id+    -- The key that ends a composition with nothing committed, an Escape that+    -- cancels it or a Backspace on its last character, is the IME's too.+    check =<< escapeKept (commit "")+    _ <- compose "xyz" 3+    checkEq "abcd" . snd =<< frameWith (keyInp KeyBackspace . commit "")+    check . not =<< escapeKept id+    let emptyComposition i = i {inputComposition = Just (Composition "" 0 0)}+    checkEq "acd" . snd =<< frameWith (keyInp KeyBackspace . emptyComposition)++-- | A text area shows the composition on the caret's row; over a multi-row+-- selection it replaces the first row's part. Enter does nothing, and the+-- commit replaces the selection.+runImeTextAreaTest :: Context -> IORef Int -> IO ()+runImeTextAreaTest ctx failed =+  field ctx failed "one\ntwo\nthree" 0 textArea' $ do+    _ <- pressKey KeyDown >> pressKey KeyEnd+    forM_ [compose "xy" 2, pressKey KeyEnter] $ \step -> checkEq (False, "one\ntwo\nthree") . changed =<< step+    shown ["twoxy", "one"] []+    checkEq (True, "one\ntwo続\nthree") . changed =<< commitText "続"+    shown ["two続"] []+    _ <- pressKey KeyUp >> pressKey KeyHome >> pressKey KeyRight+    _ <- chord (shift <> key KeyDown) >> chord (shift <> key KeyRight)+    checkEq (False, "one\ntwo続\nthree") . changed =<< compose "XY" 2+    shown ["oXY", "two続", "three"] ["one"]+    checkEq (True, "oZo続\nthree") . changed =<< commitText "Z"++-- | 'textInputArea', composition painting, and click placement over a+-- composition, in a field and a text area. No area once focus is gone.+runImeAreaPaintTest :: Context -> IORef Int -> IO ()+runImeAreaPaintTest ctx failed = do+  setDrawSquareGeometry ctx True+  t <- getThemeIO ctx+  ref <- newVar "abcd"+  areaRef <- newVar "one\ntwo"+  let cell = 16+      ui = column (held ref textInput' <* held areaRef textArea')+      near a b = abs (a - b) <= 1+      frames = mapM_ (\i -> runFrame ctx i ui)+      paint step = do+        (_, draw, _) <- runFrame ctx step ui+        (,) <$> drawQuads draw <*> collectTextSpans ctx+      carets quads cx = [r | (r@(Rect x _ w h), _) <- quads, near x cx, w <= 1.5, h >= cell / 2]+      -- On the row showing @line@: a composition @len@ cells long starting+      -- at cell @at@, IME caret @c@ cells in.+      check' line pt len c step = do+        (quads, spans') <- paint step+        assertJust failed (spanRectOf line spans') $ \(Rect sx sy _ sh) -> do+          let x0 = sx + pt * cell+              underlines (Rect x y w h, _) =+                near x x0 && near w (len * cell) && h <= 2 && y > sy + sh / 2 && y < sy + sh + 2+          assertJustM failed (textInputArea ctx) $ \(TextInputArea (Rect ax ay aw ah) cursor _) ->+            assertEq failed (ax, ay, aw, ah, cursor) (x0, sy, len * cell, cell, c * cell)+          assert failed (any underlines quads)+          -- The IME caret is drawn, not the field's caret at its start.+          assert failed (not (null (carets quads (x0 + c * cell))) && null (carets quads x0))+  warmupFocused ctx inp ui+  frames (replicate 2 (keyInp KeyLeft inp))+  spans0 <- collectTextSpans ctx+  assertJust failed (spanRectOf "abcd" spans0) $ \(Rect sx sy _ sh) -> do+    assertJustM failed (textInputArea ctx) $ \(TextInputArea r cursor _) ->+      assertEq failed (r, cursor) (Rect (sx + 2 * cell) sy 1 cell, 0)+    check' "abxyzcd" 2 3 1 (composing "xyz" 1 inp)+    -- A selection inside the composition is highlighted, with no caret.+    (quads, _) <- paint (applyComposition "xyz" 0 2 inp)+    let highlight (Rect x _ w _, col) = near x (sx + 2 * cell) && near w (2 * cell) && col == themeSelection t+    assert failed (any highlight quads)+    assert failed (null (carets quads (sx + 2 * cell)) && null (carets quads (sx + 4 * cell)))+    -- A click between the shown "c" and "d" lands after the value's "c".+    let between = V2 (sx + 6 * cell + 1) (sy + sh / 2)+    assertEq failed "abcd" . snd =<< runClick ctx (applyComposition "xyz" 0 2 inp) ui between+    assertSpansHas failed "abcxyzd" =<< collectTextSpans ctx+  -- The text area's caret starts at the document's start.+  frames [commit "" inp, tabInp inp, keyInp KeyDown inp, keyInp KeyRight inp]+  check' "txywo" 1 2 2 (composing "xy" 2 inp)+  _ <- runClick ctx (commit "" inp) ui (V2 390 290)+  assertEq failed Nothing =<< textInputArea ctx++-- | A long composition scrolls a narrow field to keep the IME caret in+-- view, and scrolls back when the caret returns to the start.+runImeScrollTest :: Context -> IORef Int -> IO ()+runImeScrollTest ctx failed = do+  let narrow = textInputConfigured' defaultTextInputConfig {ticLayout = fixedW 120}+  field ctx failed "abc" 0 narrow $ do+    (resp, _) <- compose "0123456789" 10+    let Rect fx _ fw _ = respRect resp+        caretIn ok = imeArea >>= (`checkJust` \(TextInputArea r cursor _) -> check (ok (rectX r + cursor)))+    caretIn (\x -> x >= fx && x <= fx + fw)+    _ <- compose "0123456789" 0+    caretIn (>= fx)++-- | The area follows the shaped line: a Hebrew composition after Latin text+-- runs right to left, with caret 0 at its right edge.+runImeBidiTest :: Context -> IORef Int -> IO ()+runImeBidiTest base failed = do+  let line = "ab\x05D0\x05D1"+      shape t = if t == line then Just (ShapedText 40 40 (primArrayFromList [0, 10, 40, 30, 20])) else Nothing+      ctx = withFontMetrics base (monospaceMetrics 10) {fmShape = shape}+  field ctx failed "ab" 0 textInput' $ do+    Rect sx _ _ _ <- compose "\x05D0\x05D1" 0 >> rectOf line+    forM_ [(0, 20), (2, 0)] $ \(c, cursor) -> do+      area <- compose "\x05D0\x05D1" c >> imeArea+      checkJust area $ \(TextInputArea (Rect ax _ aw _) cur _) -> checkEq (sx + 20, 20, cursor) (ax, aw, cur)++-- | A composition shows only in the field focused when it last changed.+-- After focus moves it belongs to no field, and keys work again until it+-- changes.+runImeOwnerTest :: Context -> IORef Int -> IO ()+runImeOwnerTest ctx failed = do+  aRef <- newVar "aa"+  bRef <- newVar "bb"+  let comp n = compose (T.take n "xyz") n+  runSim ctx failed inp (column ((,) <$> held aRef textInput' <*> held bRef textInput')) $ do+    -- With no focus it is shown nowhere, and Tab still moves focus.+    _ <- comp 1+    shown [] ["x"]+    ((a, _), (b, _)) <- pressKey KeyTab >> frame+    checkEq (respId a) =<< focusedId+    -- Unchanged, it stays out of the field Tab reached.+    shown [] ["x"]+    _ <- comp 2+    shown ["aaxy"] []+    _ <- click (Within (respRect b))+    checkEq (respId b) =<< focusedId+    shown ["aa", "bb"] ["xy"]+    checkEq "b" . snd . snd =<< (pressKey KeyEnd >> pressKey KeyBackspace)+    _ <- comp 3+    shown ["bxyz"] []+    checkEq "aa" =<< readV aRef++-- | Starting, changing or ending a composition repaints its field on an+-- idle frame.+runImeDamageTest :: Context -> IORef Int -> IO ()+runImeDamageTest ctx failed = do+  let ui = column (label "Above" *> withValue "abcd" textInput' <* label "Below")+  runSim ctx failed inp {inputDeltaTime = 1} ui $ do+    (resp, _) <- pressTab 1 >> settle+    check . damageIsEmpty =<< frameDamage+    check =<< wouldRedraw (composing "x" 1)+    forM_ [composing "x" 1, composing "xy" 2, commit ""] $ \step -> do+      check . (`clipCovers` respRect resp) =<< (frameWith step >> frameDamage)+      check . damageIsEmpty =<< (frameWith step >> frameDamage)++-- | IME keys fire no shortcuts. While composing, presses, releases and held+-- keys are dropped. On the commit frame, passed-on keys reach the field but+-- fire nothing, and the commit is inserted even with Ctrl held. Ctrl+G is+-- free in a text field on every platform; on macOS Ctrl+D is the Emacs+-- delete-forward key, which the field takes.+runImeShortcutsTest :: Context -> IORef Int -> IO ()+runImeShortcutsTest ctx failed = do+  fired <- newIORef ([] :: [T.Text])+  seen <- newIORef ([] :: [T.Text])+  let note r c = liftIO (modifyIORef' r (c :))+      widget v = do+        r <- textInput' v+        forM_ [ctrl <> key 's', key KeyEscape, ctrl <> key KeyEnter, ctrl <> key 'g'] $ \c ->+          whenM (shortcut c) (note fired (shortcutLabel c))+        forM_ [("pressed", keyPressed), ("released", keyReleased), ("held", keyHeld)] $ \(n, on) ->+          whenM (on (KeyChar 's')) (note seen n)+        pure r+      -- A frame on input @f@, with no key or modifier held after it.+      step f = do+        liftIO (writeIORef fired [] >> writeIORef seen [])+        (_, value) <- frameWith f+        modifyInput (\i -> i {inputKeysHeld = mempty, inputModifiers = noModifiers})+        liftIO ((,,) value <$> readIORef fired <*> readIORef seen)+      valueFired f = (\(v, fs, _) -> (v, fs)) <$> step f+      composingKeys =+        map chordInp [ctrl <> key 's', ctrl <> key 'g', key KeyEscape, ctrl <> key KeyEnter]+          ++ [keyUpInp (KeyChar 's'), \i -> i {inputKeysHeld = inputKeysFromList [KeyChar 's']}]+  field ctx failed "ab" 0 widget $ do+    _ <- compose "かな" 2+    forM_ composingKeys $ \f -> checkEq ("ab", [], []) =<< step f+    checkEq ("ab漢字", [], []) =<< step (chordInp (ctrl <> key 's') . commit "漢字")+    _ <- compose "かな" 2+    checkEq ("ab漢字かな", []) =<< valueFired (chordInp (ctrl <> key 'g') . commit "かな")+    -- A key passed on with the commit still reaches the field.+    _ <- compose "かな" 2+    checkEq ("ab漢字かなx", []) =<< valueFired (keyInp KeyLeft . commit "x")+    checkEq ("ab漢字かなyx", []) =<< valueFired (\i -> i {inputChars = "y"})+    forM_ [ctrl <> key 's', ctrl <> key 'g'] $ \c ->+      checkEq ("ab漢字かなyx", [shortcutLabel c]) =<< valueFired (chordInp c)++-- | A custom widget takes text with 'useInputMethod' while focused: it gets+-- the composition to draw, the IME gets its keys, and the IME area is its+-- caret. Unfocused, it requests and receives nothing.+runImeCustomWidgetTest :: Context -> IORef Int -> IO ()+runImeCustomWidgetTest ctx failed = do+  seen <- newIORef ([] :: [T.Text])+  let caret = Rect 40 20 2 16+      size = fixedWH 100 40+      spec' = defaultCustomWidgetSpec {widgetFocusable = True, widgetKeys = KeysAll, widgetLayout = size}+      ui = column $ do+        wid <- nextId+        preedit <- useInputMethod wid InputNormal caret+        (_, ()) <- customWidgetWithId wid spec'+        whenM (shortcut (key KeyEscape)) (liftIO (modifyIORef' seen ("escape" :)))+        pure preedit+  runSim ctx failed inp ui $ do+    checkEq Nothing =<< compose "か" 1+    checkEq Nothing =<< imeArea+    checkEq Nothing =<< (commitText "" >> pressKey KeyTab >> frame)+    checkEq (Just (TextInputArea caret 0 InputNormal)) =<< imeArea+    checkEq (Just (Composition "か" 1 0)) =<< compose "か" 1+    _ <- pressKey KeyEscape+    checkEq [] =<< liftIO (readIORef seen)+    checkEq Nothing =<< commitText ""++-- | Fields report their input purpose (secure for passwords, numeric for+-- numbers), already on the frame Tab focuses them. Selectable labels and+-- buttons take no text.+purposeUi :: NanoUI ()+purposeUi = column $ do+  _ <- button "Before"+  _ <- withValue "secret" (textInputConfigured defaultTextInputConfig {ticPassword = True})+  _ <- withValue 3 numericInput+  _ <- withValue "notes" textArea+  selectableText "label"++imePurpose :: Sim () ()+imePurpose = do+  let purpose = fmap textInputAreaPurpose <$> imeArea+      purposes = [Nothing, Just InputSecure, Just InputNumeric, Just InputNormal, Nothing]+  checkEq purposes =<< replicateM 5 (pressKey KeyTab >> purpose)+  checkEq Nothing =<< (frame >> purpose)
test/integration/Cases/Keyboard.hs view
@@ -1,201 +1,95 @@-module Cases.Keyboard-  ( runKeyboardButtonTest-  , runKeyboardCheckboxTest-  , runKeyboardSliderTest-  , runKeyboardRadioTest-  , runKeyboardToggleTest-  , runKeyboardTabHeaderTest-  , runKeyboardDisabledTest-  , runKeyboardModalEligibilityTest-  , runKeyboardFocusRingTest-  ) where--import Data.IORef (IORef, newIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import NanoUI-import NanoUI.Context (Context (..), getFocusVisible, intKey)-import NanoUI.Emit qualified as Emit-import NanoUI.Store (WidgetStore (..))-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt)-import NanoUI.Testing.Harness (centerOf, clickPair, held, keyInp, tabInp, warmup2, withInputOff)---- Retaining focus while a widget becomes disabled must not bypass the same--- guard used by pointer interaction. Exercise the shared key-navigation hook.-runKeyboardDisabledTest :: Context -> IORef Int -> IO ()-runKeyboardDisabledTest _ctx failed = do-  let inp = withInputOff 300 160-      check :: (Eq a, Show a) => NanoUI (Response, a) -> Input -> IO ()-      check widget pressed = do-        ctx <- newContext-        ((resp, before), _, _, _) <- runFrame ctx inp widget-        let wid = respId resp-        st <- getStore ctx-        writeIORef (ctxFocusId ctx) wid-        ((afterResp, after), _, _, _) <- runFrame ctx pressed (disabledWhen True widget)-        assertEq failed after before-        assert failed (not (respChanged afterResp) && not (respClicked afterResp))-        afterStore <- getStore ctx-        assertEq failed-          (IM.lookup (intKey wid) (storeText st))-          (IM.lookup (intKey wid) (storeText afterStore))-  check (checkbox' "Disabled" False) (keyInp KeyEnter inp)-  check (checkbox' "Disabled" False) (spaceInp inp)-  check (slider' 0 100 50) (keyInp KeyRight inp)-  check (toggleSwitch' False) (spaceInp inp)-  check (textInput' "initial") (inp {inputChars = "x"})-  check (textArea' "initial") (inp {inputChars = "x"})-  check (searchField' "Search" "initial") (inp {inputChars = "x"})-  check (comboBox' "Choose" ["initial", "other"] "initial") (inp {inputChars = "x"})-  check (do r <- button' "Disabled"; pure (r, respClicked r)) (keyInp KeyEnter inp)--runKeyboardModalEligibilityTest :: Context -> IORef Int -> IO ()-runKeyboardModalEligibilityTest ctx failed = do-  let inp = withInputOff 400 300-      ui = column $ do-        outside <- checkbox' "Outside" False-        (_, inside) <- modal True "Modal" (checkbox' "Inside" False)-        pure (outside, inside)-  ((outside, inside), _, _, _) <- runFrame ctx inp ui-  writeIORef (ctxFocusId ctx) (respId (fst outside))-  (((_, outsideValue), _), _, _, _) <- runFrame ctx (keyInp KeyEnter inp) ui-  assert failed (not outsideValue)-  case inside of-    Nothing -> assert failed False-    Just (resp, _) -> do-      writeIORef (ctxFocusId ctx) (respId resp)-      ((_, after), _, _, _) <- runFrame ctx (keyInp KeyEnter inp) ui-      assert failed (maybe False snd after)---- | A space key-down frame (space arrives as a character, not a Key).-spaceInp :: Input -> Input-spaceInp inp = inp {inputChars = " "}+{-# OPTIONS_GHC -O0 #-}+module Cases.Keyboard (tests) where --- | Plain buttons activate with Enter and Space while focused.-runKeyboardButtonTest :: Context -> IORef Int -> IO ()-runKeyboardButtonTest ctx failed = do-  let inp0 = withInputOff 200 120-      ui = column $ do-        a <- button "A"-        b <- button "B"-        pure (a, b)-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  ((aEnter, _), _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) ui-  assert failed aEnter-  ((aSpace, _), _, _, _) <- runFrame ctx (spaceInp inp0) ui-  assert failed aSpace-  _ <- runFrame ctx (tabInp inp0) ui-  ((_, bEnter), _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) ui-  assert failed bEnter+import Spec+import NanoUI.Testing.Sim --- | A focused checkbox toggles with Space and Enter, and 'Emit.checkbox'--- emits its new value on keyboard activation.-runKeyboardCheckboxTest :: Context -> IORef Int -> IO ()-runKeyboardCheckboxTest ctx failed = do-  checkedRef <- newIORef False-  let inp0 = withInputOff 200 100-      ui = column (held checkedRef (checkbox' "Opt"))-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  ((_, checked1), _, _, _) <- runFrame ctx (spaceInp inp0) ui-  assert failed checked1-  ((_, checked2), _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) ui-  assert failed (not checked2)-  let emitUi = do-        wid <- currentId-        Emit.checkbox "Emit" False id-        pure wid-  (wid, _, _, _) <- runFrame ctx inp0 emitUi-  writeIORef (ctxFocusId ctx) wid-  (_, messages, _, _) <- runFrame ctx (keyInp KeyEnter inp0) emitUi-  assertEq failed [True] (decodeMessages messages :: [Bool])+tests :: [Spec]+tests =+  [ spec "keyboard-disabled" runKeyboardDisabledTest+  , simSpec "keyboard-modal-eligibility" 400 300 modalEligibilityUi keyboardModalEligibility+  , spec "keyboard-focused-controls" runFocusedControlsTest+  , simSpec "keyboard-focus-ring" 300 160 (column (button' "Go")) keyboardFocusRing+  ] --- | A focused slider steps with the arrow keys.-runKeyboardSliderTest :: Context -> IORef Int -> IO ()-runKeyboardSliderTest ctx failed = do-  valueRef <- newIORef 50-  let inp0 = withInputOff 300 80-      ui = column (held valueRef (slider' 0 100))-  (_, v0) <- warmup2 ctx inp0 ui-  assertEq failed v0 50-  _ <- runFrame ctx (tabInp inp0) ui-  ((_, v1), _, _, _) <- runFrame ctx (keyInp KeyRight inp0) ui-  assertGt failed v1 50-  ((_, v2), _, _, _) <- runFrame ctx (keyInp KeyLeft inp0) ui-  assertEq failed v2 50-  ((_, v3), _, _, _) <- runFrame ctx (keyInp KeyDown inp0) ui-  assertEq failed v3 49-  ((_, v4), _, _, _) <- runFrame ctx (keyInp KeyUp inp0) ui-  assertEq failed v4 50+-- | Retaining focus while a control becomes disabled must not bypass the+-- guard pointer interaction uses, through the shared key-navigation hook:+-- Enter, Space, an arrow and typing change nothing.+runKeyboardDisabledTest :: Context -> IORef Int -> IO ()+runKeyboardDisabledTest _ failed =+  forM_ everyControl $ \(name, widget) -> forM_ keys $ \(keyName, pressed) -> do+    ctx <- newContext+    ((resp, before), _, _) <- runFrame ctx inp widget+    setFocus ctx (respId resp)+    ((r, after), _, _) <- runFrame ctx (pressed inp) (disabledWhen True widget)+    assertEq failed (name, keyName, before, False) (name, keyName, after, respChanged r || respClicked r)+  where+    inp = withInputOff 300 160+    keys :: [(String, Input -> Input)]+    keys = [("Enter", keyInp KeyEnter), ("Space", spaceInp), ("Right", keyInp KeyRight), ("x", typed)]+    typed i = i {inputChars = "x"} --- | A focused radio group changes selection with the arrow keys.-runKeyboardRadioTest :: Context -> IORef Int -> IO ()-runKeyboardRadioTest ctx failed = do-  selectedRef <- newIORef 0-  let inp0 = withInputOff 200 160-      ui = column (held selectedRef (radio' ["A", "B", "C"]))-  (_, sel0) <- warmup2 ctx inp0 ui-  assertEq failed sel0 0-  _ <- runFrame ctx (tabInp inp0) ui-  ((_, sel1), _, _, _) <- runFrame ctx (keyInp KeyDown inp0) ui-  assertEq failed sel1 1-  ((_, sel2), _, _, _) <- runFrame ctx (keyInp KeyDown inp0) ui-  assertEq failed sel2 2-  ((_, sel3), _, _, _) <- runFrame ctx (keyInp KeyUp inp0) ui-  assertEq failed sel3 1+modalEligibilityUi :: NanoUI ((Response, Bool), Maybe (Response, Bool))+modalEligibilityUi = column $ do+  outside <- withValue False (checkbox' "Outside")+  (_, inside) <- modal' (constVar True) "Modal" (withValue False (checkbox' "Inside"))+  pure (outside, inside) --- | A toggle switch flips with Space and Enter while focused, and on click.-runKeyboardToggleTest :: Context -> IORef Int -> IO ()-runKeyboardToggleTest ctx failed = do-  onRef <- newIORef False-  let inp0 = withInputOff 200 100-      ui = column (held onRef toggleSwitch')-  (resp0, v0) <- warmup2 ctx inp0 ui-  assert failed (not v0)-  _ <- runFrame ctx (tabInp inp0) ui-  ((_, v1), _, _, _) <- runFrame ctx (spaceInp inp0) ui-  assert failed v1-  ((_, v2), _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) ui-  assert failed (not v2)-  let (press, release) = clickPair inp0 (centerOf resp0)-  _ <- runFrame ctx press ui-  ((clicked, v3), _, _, _) <- runFrame ctx release ui-  assert failed (respClicked clicked && v3)-  _ <- runFrame ctx press ui-  ((clicked2, v4), _, _, _) <- runFrame ctx release ui-  assert failed (respClicked clicked2 && not v4)+-- | Behind a modal a focused checkbox ignores Enter; inside it, it toggles.+keyboardModalEligibility :: Sim ((Response, Bool), Maybe (Response, Bool)) ()+keyboardModalEligibility = do+  ((outside, _), inside) <- result+  focusOn (respId outside)+  check . not . snd . fst =<< pressKey KeyEnter+  checkJust inside $ \(resp, _) -> do+    focusOn (respId resp)+    check . maybe False snd . snd =<< pressKey KeyEnter -data KB = KBA | KBB-  deriving (Eq, Show)+-- | A Space press, which also types a space.+spaceInp :: Input -> Input+spaceInp inp = (keyInp KeySpace inp) {inputChars = " "} --- | Tab headers are focusable and switch the active tab with Enter.-runKeyboardTabHeaderTest :: Context -> IORef Int -> IO ()-runKeyboardTabHeaderTest ctx failed = do-  let inp0 = withInputOff 300 100-      ui cur =-        tabs cur-          [ tab KBA "Alpha" (label "BodyA")-          , tab KBB "Beta" (label "BodyB")-          ]-  _ <- warmup2 ctx inp0 (ui KBA)-  _ <- runFrame ctx (tabInp inp0) (ui KBA)-  (active1, _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) (ui KBA)-  assertEq failed active1 KBA-  _ <- runFrame ctx (tabInp inp0) (ui KBA)-  (active2, _, _, _) <- runFrame ctx (keyInp KeyEnter inp0) (ui KBA)-  assertEq failed active2 KBB+-- | Focused by Tab, buttons activate with Enter and Space, checkboxes and+-- toggles flip with them (a toggle on a click too), a slider steps with the+-- arrows, a radio group moves its choice with them, and Enter on a tab+-- header opens its tab.+runFocusedControlsTest :: Context -> IORef Int -> IO ()+runFocusedControlsTest _ failed = do+  let run :: NanoUI a -> Sim a () -> IO ()+      run ui script = do+        ctx <- newPixelContext+        runSim ctx failed (withInputOff 300 160) (column ui) (pressTab 1 >> script)+      space = frameWith spaceInp+      after = fmap (map snd) . mapM pressKey+  run ((,) <$> button "A" <*> button "B") $ do+    checkEq [True, True] . map fst =<< sequence [pressKey KeyEnter, space]+    checkEq True . snd =<< (pressTab 1 >> pressKey KeyEnter)+  checked <- newVar False+  run (held checked (checkbox' "Opt")) $+    checkEq [True, False] . map snd =<< sequence [space, pressKey KeyEnter]+  value <- newVar 50+  run (held value (slider' 0 100)) $ do+    (v : rest) <- after [KeyRight, KeyLeft, KeyDown, KeyUp]+    checkLt 50 v+    checkEq [50, 49, 50] rest+  choice <- newVar 0+  run (held choice (radio' ["A", "B", "C"])) (checkEq [1, 2, 1] =<< after [KeyDown, KeyDown, KeyUp])+  on <- newVar False+  run (held on (toggleSwitchWith' id)) $ do+    (resp, _) <- result+    checkEq [True, False] . map snd =<< sequence [space, pressKey KeyEnter]+    clicks <- replicateM 2 (click (On resp))+    checkEq [(True, True), (True, False)] [(respClicked r, v) | (r, v) <- clicks]+  let headers = [tab (1 :: Int) "Alpha" (label "BodyA"), tab 2 "Beta" (label "BodyB")]+  run (tabActive <$> tabs' (constVar 1) headers) $ do+    checkEq 1 =<< pressKey KeyEnter+    checkEq 2 =<< (pressTab 1 >> pressKey KeyEnter) --- Moving focus with Tab shows the focus ring; a pointer press hides it.-runKeyboardFocusRingTest :: Context -> IORef Int -> IO ()-runKeyboardFocusRingTest ctx failed = do-  let inp = withInputOff 300 160-      ui = column (button' "Go")-  _ <- warmup2 ctx inp ui-  assert failed . not =<< getFocusVisible ctx-  _ <- runFrame ctx (tabInp inp) ui-  assert failed =<< getFocusVisible ctx-  let (press, release) = clickPair inp (V2 5 150)-  _ <- runFrame ctx press ui-  _ <- runFrame ctx release ui-  assert failed . not =<< getFocusVisible ctx+-- | Moving focus with Tab shows the focus ring; a pointer press hides it.+keyboardFocusRing :: Sim Response ()+keyboardFocusRing = do+  check . not =<< focusRing+  pressTab 1+  check =<< focusRing+  _ <- click (At (V2 5 150))+  check . not =<< focusRing
+ test/integration/Cases/Labels.hs view
@@ -0,0 +1,108 @@+{-# OPTIONS_GHC -O0 #-}+-- | Labels cut to their room, and toggle buttons.+module Cases.Labels (tests) where++import Data.Primitive.PrimArray (primArrayFromList)+import Data.Text qualified as T+import NanoUI.Testing.Sim+import Spec++tests :: [Spec]+tests =+  [ spec "label-truncates" runTruncateTest+  , spec "toggle-button" runToggleButtonTest+  , spec "ellipsis-modes-and-tabular" runEllipsisAndTabularTest+  ]++-- | The text spans drawn inside a widget's rect.+spansIn :: Context -> Rect -> IO [(Rect, T.Text)]+spansIn ctx r = (\ss -> [(s, t) | (s, t, _, _, _) <- ss, rectIntersect s r /= Nothing]) <$> collectTextSpans ctx++-- | Buttons and selects (short of the chevron) end text that does not fit in+-- dots, measured by its shaped width; text that fits, or overflows by under+-- half a pixel, shows whole.+runTruncateTest :: Context -> IORef Int -> IO ()+runTruncateTest base failed = do+  let inp = withInputOff 400 200+      long = "A label much longer than the button"+      dotted = T.isSuffixOf "..."+      cutIn ctx r k = spansIn ctx r >>= \case+        [(s, t)] -> assert failed (dotted t) >> k s t+        cut -> assertEq failed 1 (length cut)+      ui = column $ do+        narrow <- buttonWith' (fixedW 90) long+        fits <- button' "Save"+        (sel, _) <- withValue 0 (selectWith' (fixedW 120) ["An option far too long for the field", "Short"])+        pure (narrow, fits, sel)+  (narrow, fits, sel) <- warmup2 base inp ui+  let Rect nx _ nw _ = respRect narrow+      Rect sx _ sw _ = respRect sel+  cutIn base (respRect narrow) $ \(Rect x _ w _) t ->+    assert failed (T.length t < T.length long && x >= nx && x + w <= nx + nw)+  assertEq failed ["Save"] . map snd =<< spansIn base (respRect fits)+  cutIn base (respRect sel) $ \(Rect x _ w _) _ -> assert failed (x + w <= sx + sw - 16)+  -- Shaping sets a text 8 a character; unshaped advances are 10.+  let shaped t =+        let n = T.length t+         in ShapedText (8 * fromIntegral n) (8 * fromIntegral n) (primArrayFromList [8 * fromIntegral i | i <- [0 .. n]])+      fm = (monospaceMetrics 10) {fmBackend = Just (FontBackend prepare (\_ -> pure Nothing))}+      prepare t = pure fm {fmShape = \t' -> if t' == t then Just (shaped t) else Nothing}+      shapedCtx = withFontMetrics base fm+  resp <- warmup2 shapedCtx inp (column (buttonWith' (fixedW 90) long))+  cutIn shapedCtx (respRect resp) $ \r t -> assertEq failed (8 * fromIntegral (T.length t)) (rectW r)+  let slack = withFontMetrics base (monospaceMetrics 10.04)+  warmup slack inp (column (labelWith (maxW 80) "12345678"))+  assertEq failed ["12345678"] . map snd =<< spansIn slack (Rect 0 0 400 200)++-- | A click turns a toggle button on and fills it in its tone; another+-- turns it off.+runToggleButtonTest :: Context -> IORef Int -> IO ()+runToggleButtonTest ctx failed = do+  ref <- newVar False+  tint <- themeWarning <$> getThemeIO ctx+  let inp = withInputOff 300 200+      ui = column (toggleButton' Warning "M" ref)+  runSim ctx failed inp ui $ do+    resp <- result+    _ <- click (On resp)+    checkEq True =<< readV ref+    (_, draw) <- liftIO (warmupDraw ctx inp ui)+    check . elem tint . fillsIn (respRect resp) =<< liftIO (drawQuads draw)+    _ <- click (On resp)+    checkEq False =<< readV ref++runEllipsisAndTabularTest :: Context -> IORef Int -> IO ()+runEllipsisAndTabularTest base failed = do+  let inp = withInputOff 400 240+      ellUi = column $ do+        row (labelWith (maxW 140 . ellipsisMiddle) "Data.Map.Internal.insertWithKey")+        row (labelWith (maxW 140 . ellipsisStart) "src/Stronghead/Eventlog/Model.hs")+  warmup2 base inp ellUi+  ss <- collectTextSpans base+  let texts = [t | (_, t, _, _, _) <- ss]+  case texts of+    [midT, startT] -> do+      assert failed ("Da" `T.isPrefixOf` midT && "..." `T.isInfixOf` midT && "ey" `T.isSuffixOf` midT)+      assert failed ("..." `T.isPrefixOf` startT && "hs" `T.isSuffixOf` startT)+    _ -> assertEq failed 2 (length texts)+  let propFm =+        (monospaceMetrics 10)+          { fmAdvance = \c -> case c of+              ' ' -> 4+              '1' -> 5+              '8' -> 10+              _ -> 7+          }+      propCtx = withFontMetrics base propFm+      tabUi = column $ do+        labelWith fontTabular "111.5"+        labelWith fontTabular "888.5"+        label "111.5"+        label "888.5"+  warmup2 propCtx inp tabUi+  tss <- collectTextSpans propCtx+  case [rectW r | (r, _, _, _, _) <- tss] of+    [tw1, tw8, pw1, pw8] -> do+      assert failed (abs (tw1 - tw8) <= 0.01)+      assertLt failed pw1 pw8+    ws -> assertEq failed 4 (length ws)
+ test/integration/Cases/LayoutFlow.hs view
@@ -0,0 +1,816 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.LayoutFlow (tests) where++import Spec+import Data.List (findIndex)+import Data.Primitive.SmallArray (smallArrayFromList)+import Data.Text qualified as T+import NanoUI.Adornment qualified as A+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena+  ( GeomCol+  , StyleCol+  , TagCol (..)+  , TreeCol (..)+  , arenaArrays+  , geomStride+  , getClipRect+  , styleStride+  , tagStride+  , treeStride+  , writeTagEnum+  , writeTree+  )+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "layout-flow" runLayoutFlowTest+  , spec "wrap-matches-paint" runWrapMatchesPaintTest+  , simSpec "aspect-bad-ratio" 400 400 badRatioUi badRatio+  , simSpec "primed-containers" 400 400 primedUi primedRects+  , spec "flex-sizing" runFlexSizingTest+  , pixelSpec "label-align-end" runLabelAlignEndTest+  , spec "empty-frame" runEmptyFrameTest+  , spec "layout-flow-rects" runLayoutFlowRectsTest+  , spec "layout-text-sizes" runTextSizesTest+  , spec "wrap-refit-in-column" runWrapRefitInColumnTest+  , spec "flow-in-scroller" runFlowInScrollerTest+  , spec "layer-paint-order" runLayerPaintOrderTest+  , spec "layout-flow-damage" runLayoutFlowDamageTest+  , spec "arena-columns-fit-strides" runArenaColumnsFitStridesTest+  , spec "pointer-owner" runPointerOwnerTest+  , spec "covered-field-focus" runCoveredFieldFocusTest+  , spec "covered-widget-no-pointer" runCoveredWidgetNoPointerTest+  , spec "container-queries" runContainerQueryTest+  , pixelSpec "items-align" runItemsAlignTest+  , pixelSpec "items-stretch-and-justify" runItemsStretchAndJustifyTest+  ]++red, green, blue, yellow :: Color+red = colorRGBA 255 0 0 255+green = colorRGBA 0 255 0 255+blue = colorRGBA 0 0 255 255+yellow = colorRGBA 255 255 0 255++input0 :: Input+input0 = withInputOff 400 300++-- | Every rect but the root's after the view settles.+layoutOf :: Context -> NanoUI a -> IO [Rect]+layoutOf ctx ui = warmup2 ctx input0 ui >> drop 1 <$> arenaRects ctx++-- | The rects of nodes @is@ in the last frame, in arena order.+rectsAt :: Context -> [Int] -> IO [Rect]+rectsAt ctx is = (\rs -> [r | (i, r) <- zip [0 ..] rs, i `elem` is]) <$> arenaRects ctx++-- | 'runSim' on 'input0'.+sim :: Context -> IORef Int -> NanoUI a -> Sim a r -> IO r+sim ctx failed = runSim ctx failed input0++-- | Hover, press, hold and release on the target; the press and release results.+pressThrough :: Target -> Sim a (a, a)+pressThrough t = do+  _ <- moveTo t+  pressed <- press t+  _ <- frame+  (pressed,) <$> release++-- | Non-root rects of layers and 'layered', wrapping rows and columns with+-- 'lineAlign', pins (which take no space), 'aspect', 'center', 'flex', grow+-- children under a maximum, and an empty label.+runLayoutFlowRectsTest :: Context -> IORef Int -> IO ()+runLayoutFlowRectsTest ctx failed =+  forM_ cases $ \(ui, want) -> layoutOf ctx ui >>= assertEq failed want+  where+    wrapRow w = columnWith tight $ rowWith (wrap . fixedW w . tight . gap 10 . lineGap 5) $ do+      box (alignBottom . fixedWH 30 10) red+      forM_ [(30, 20), (30, 10), (50, 10), (120, 10), (20, 10)] $ \(bw, bh) -> box (fixedWH bw bh) red+    chips a = columnWith tight $ rowWith (wrap . lineAlign a . fixedW 100 . tight . gap 10 . lineGap 0) $ do+      replicateM_ 4 (box (fixedWH 30 10) red)+      box (fillW . fixedH 10) blue+    chipRects s = [Rect 0 0 100 30, Rect s 0 30 10, Rect (s + 40) 0 30 10, Rect s 10 30 10, Rect (s + 40) 10 30 10, Rect 0 20 100 10]+    in300 = columnWith (tight . gap 0 . fixedW 300)+    inBox = columnWith (tight . fixedW 200 . fixedH 100) . center+    ends container = container $ box (fixedWH 20 10) red >> flex >> box (fixedWH 20 10) blue+    cases =+      [ ( columnWith tight $ layersWith (padAll 4) $ do+            box (fixedWH 100 60) red+            box (alignEnd . alignBottom . fixedWH 20 10) blue+            box (alignCenter . alignMiddle . fixedWH 10 10) blue+            box (fillW . fixedH 6) green+            box (alignEnd . percent 50 . fixedH 6) green+            box (fillH . fixedW 5) yellow+        , [Rect 0 0 108 68, Rect 4 4 100 60, Rect 84 54 20 10, Rect 49 29 10 10, Rect 4 4 100 6, Rect 54 4 50 6, Rect 4 4 5 60] )+      , ( columnWith tight $ panelWith (layered . padAll 5) $ do+            box (fixedWH 60 40) red+            box (alignEnd . alignBottom . fixedWH 10 10) blue+        , [Rect 0 0 70 50, Rect 5 5 60 40, Rect 55 35 10 10] )+      , ( columnWith tight $ rowWith (layered . tight . fixedW 60) $ do+            label "one two three four five six"+            box (alignEnd . fixedWH 10 10) blue+        , [Rect 0 0 60 72, Rect 0 0 60 72, Rect 50 0 10 10] )+      , ( columnWith tight $ do+            layersWith (fixedW 100 . tight) $ label "one two three four five six seven eight nine ten"+            label "x"+        , [Rect 0 0 100 84, Rect 0 0 96 84, Rect 0 92 12 12] )+      , (wrapRow 100, [Rect 0 0 100 65, Rect 0 10 30 10, Rect 40 0 30 20, Rect 0 25 30 10, Rect 40 25 50 10, Rect 0 40 120 10, Rect 0 55 20 10])+      , (wrapRow 200, [Rect 0 0 200 35, Rect 0 10 30 10, Rect 40 0 30 20, Rect 80 0 30 10, Rect 120 0 50 10, Rect 0 25 120 10, Rect 130 25 20 10])+      , ( columnWith tight $ rowWith (wrap . fixedW 100 . tight . gap 0) $ do+            box (fixedWH 60 10) red+            box (fillW . minW 30 . fixedH 10) blue+            box (fixedWH 70 10) green+        , [Rect 0 0 100 20, Rect 0 0 60 10, Rect 60 0 40 10, Rect 0 10 70 10] )+      , (chips LinesStart, chipRects 0)+      , (chips LinesCenter, chipRects 15)+      , (chips LinesEnd, chipRects 30)+      , ( columnWith tight $ columnWith (wrap . fixedH 100 . tight . gap 0 . lineGap 5) $ replicateM_ 5 (box (fixedWH 20 40) red)+        , [Rect 0 0 70 100, Rect 0 0 20 40, Rect 0 40 20 40, Rect 25 0 20 40, Rect 25 40 20 40, Rect 50 0 20 40] )+      , ( columnWith tight . columnWith (wrap . lineAlign LinesEnd . fixedH 100 . tight . gap 0 . lineGap 5) $+            replicateM_ 3 (box (fixedWH 20 40) red)+        , [Rect 0 0 45 100, Rect 0 20 20 40, Rect 0 60 20 40, Rect 25 60 20 40] )+      , ( columnWith (tight . gap 0) $ do+            rowWith (padAll 5 . gap 10) $ do+              box (fixedWH 40 40) red+              box (pinAt 30 12 . fixedWH 16 16) blue+              box (fixedWH 40 40) green+              box (pinAt 0 0 . fillW . fixedH 4) yellow+            box (fixedWH 10 10) yellow+        , [Rect 0 0 100 50, Rect 5 5 40 40, Rect 35 17 16 16, Rect 55 5 40 40, Rect 5 5 90 4, Rect 0 50 10 10] )+      , ( columnWith (tight . gap 0) $ columnWith (tight . fixedWH 200 100) $ do+            -- Pinned past an aligned position: inset, overhanging, shortened, shifted.+            box (pinAt (-16) (-16) . alignEnd . alignBottom . fixedWH 40 40) red+            box (pinAt 6 (-6) . alignEnd . alignTop . fixedWH 12 12) blue+            box (pinAt (-10) 0 . alignEnd . fillW . fixedH 4) green+            box (pinAt 10 0 . alignCenter . alignMiddle . fixedWH 20 10) yellow+        , [Rect 0 0 200 100, Rect 144 44 40 40, Rect 194 (-6) 12 12, Rect 0 0 190 4, Rect 100 45 20 10] )+      , (in300 (box (fillW . aspect 2) red), [Rect 0 0 300 150])+      , (in300 (box (fixedW 80 . aspect 4) red), [Rect 0 0 80 20])+      , (in300 (box (fixedH 50 . aspect 2) red), [Rect 0 0 100 50])+      , (in300 (box (fillW . aspect 1 . maxH 50) red), [Rect 0 0 300 50])+      , (in300 (rowWith (tight . gap 0 . fillW) (box (fillW . aspect 2) red >> box (fixedWH 100 10) blue)), [Rect 0 0 300 100, Rect 0 0 200 100, Rect 200 0 100 10])+      , -- A panel keeps the ratio's height whatever its content.+        (in300 (panelWith (tight . fillW . aspect 10) (box (fixedWH 20 100) red) >> box (fixedWH 10 10) blue), [Rect 0 0 300 30, Rect 0 0 20 100, Rect 0 30 10 10])+      , -- A non-positive ratio is ignored.+        (in300 (box (fixedWH 40 20 . aspect 0) red), [Rect 0 0 40 20])+      , (inBox (box (fixedWH 20 10) red), [Rect 0 0 200 100, Rect 90 45 20 10, Rect 90 45 20 10])+      , -- The block of both boxes and the gap between them sits mid-height.+        ( inBox (box (fixedWH 40 10) red >> box (alignCenter . fixedWH 20 10) blue)+        , [Rect 0 0 200 100, Rect 80 36 40 28, Rect 80 36 40 10, Rect 90 54 20 10] )+      , (ends (columnWith (tight . gap 0 . fixedW 100 . fixedH 200)), [Rect 0 0 20 10, Rect 0 10 8 180, Rect 0 190 20 10])+      , (ends (rowWith (tight . gap 0 . fixedW 200 . fixedH 50)), [Rect 0 0 20 10, Rect 20 0 160 8, Rect 180 0 20 10])+      , ( rowWith (tight . gap 0 . fixedW 400 . fixedH 20) $ do+            box (fillW . maxW 100) red+            box fillW green+            box (minW 80) blue+        , [Rect 0 0 100 32, Rect 100 0 220 32, Rect 320 0 80 32] )+      , ( columnWith (tight . gap 0 . fixedW 20 . fixedH 300) (box (fillH . maxH 50) red >> box fillH green)+        , [Rect 0 0 20 50, Rect 0 50 20 250] )+      , -- A negative weight grows nothing and takes nothing from the others.+        ( rowWith (tight . gap 0 . fixedW 300 . fixedH 20) (box fillW red >> box (\l -> l {layoutWidth = Grow (-1)}) green)+        , [Rect 0 0 268 32, Rect 268 0 32 32] )+      , ( columnWith tight (columnWith tight (label "a" >> label "" >> label "b") >> label "after")+        , [Rect 0 0 12 52, Rect 0 0 12 12, Rect 0 20 0 12, Rect 0 40 12 12, Rect 0 60 60 12] )+      ]++-- | Labels with fixed or percentage sizes measure as they are placed, and+-- paint wraps where the solve placed them (each case names the label's rect+-- and the other spans). Fixed sizes outside a node's limits take the limit.+runTextSizesTest :: Context -> IORef Int -> IO ()+runTextSizesTest ctx failed = do+  forM_ cases $ \(ui, idx, others, want) -> do+    rs <- layoutOf ctx ui+    assertEq failed want rs+    assertJust failed (lookup idx (zip [0 :: Int ..] rs)) (assertPaintedLines failed ctx others)+  let narrow l = l {layoutWidth = Fixed 100, layoutHeight = Fixed 28}+      field f = textInputConfigured' defaultTextInputConfig {ticLayout = f}+      custom = defaultCustomWidgetSpec {widgetLayout = narrow . minW 160, widgetMeasure = Just (\_ _ -> (100, 28))}+      limits = rowWith tight $ do+        (a, _) <- withValue "" (field narrow)+        b <- button' "Go"+        (c, ()) <- customWidget custom+        d <- button' "End"+        (fixed, _) <- withValue "" (field (fixedWH 100 28))+        pure [a, b, c, d, fixed]+  map respRect <$> warmup2 ctx input0 limits+    >>= assertEq failed [Rect 0 0 160 28, Rect 168 0 48 18, Rect 224 0 160 28, Rect 392 0 60 18, Rect 460 0 100 28]+  where+    fixedLabel w = labelWith (\l -> l {layoutWidth = Fixed w})+    cases =+      [ ( columnWith tight $ do+            rowWith tight (labelWith (fixedWH 100 20 . alignEnd) "Name" >> void (button "Go"))+            fixedLabel 100 "a fixed label wide enough to wrap"+        , 3, ["Name", "Go"], [Rect 0 0 156 20, Rect 0 0 100 20, Rect 108 0 48 18, Rect 0 28 100 60] )+      , ( columnWith tight . columnWith tight $ do+            labelWith (\l -> (minW 200 l) {layoutWidth = Fixed 100}) "a fixed label wide enough to wrap twice over"+            label "after"+        , 1, ["after"], [Rect 0 0 200 56, Rect 0 0 200 36, Rect 0 44 60 12] )+      , ( columnWith tight $ do+            columnWith (tight . fixedW 400) $ do+              box (percent 50 . alignEnd . fixedH 10) red+              labelWith (percent 50) "percent sized text wraps at its own width"+            gridWith 2 (tight . fixedW 401 . gap 1) (box (percent 50 . fixedH 10) red >> box (fixedH 10) blue)+            rowWith (tight . fixedH 40) $ box (\l -> l {layoutWidth = Fixed 10, layoutHeight = Percent 50}) red+        , 2+        , []+        , [ Rect 0 0 400 54, Rect 200 0 200 10, Rect 0 18 200 36, Rect 0 62 401 10, Rect 0 62 100 10+          , Rect 201 62 32 10, Rect 0 80 10 40, Rect 0 80 10 20+          ] )+      ]++-- | An unbounded wrapping row wraps at its column's width and refits its+-- height. Widening the window reflows it onto one line with a full repaint.+runWrapRefitInColumnTest :: Context -> IORef Int -> IO ()+runWrapRefitInColumnTest ctx failed = do+  let ui = columnWith (tight . gap 0) $ do+        rowWith (wrap . tight . gap 0) (replicateM_ 10 (box (fixedWH 50 10) red))+        box (fixedWH 10 10) blue+  _ <- warmup2 ctx (withInputOff 220 300) ui+  rectsAt ctx [1, 11, 12] >>= assertEq failed [Rect 0 0 220 30, Rect 50 20 50 10, Rect 0 30 10 10]+  warmup ctx (withInputOff 600 300) ui+  takeDamage ctx >>= assertEq failed DamageFull+  rectsAt ctx [1, 12] >>= assertEq failed [Rect 0 0 500 10, Rect 0 10 10 10]++-- | A wrapping row or a pinned child in a scroller sets its range, and a pin+-- is clipped to the viewport. A scroller stacks its children whatever flow+-- its layout asks for.+runFlowInScrollerTest :: Context -> IORef Int -> IO ()+runFlowInScrollerTest ctx failed = do+  let scrolled w h body = columnWith tight (scrollArea (fixedWH w h . tight) body)+      rangeOf sid want = assertJustM failed (getScrollMetricsIO ctx sid) (assertEq failed want . v2Y . scrollRange)+      bottom b = rectY b + rectH b+      wrapped = scrolled 120 50 $ rowWith (wrap . fillW . tight . gap 0) (replicateM_ 12 (box (fixedWH 40 20) red))+  (sid, _) <- warmup2 ctx input0 wrapped+  r : boxes <- drop 2 <$> arenaRects ctx+  assertEq failed 12 (length boxes)+  assert failed (all (\b -> rectX b + rectW b <= 120) boxes && rectH r >= 80)+  assertEq failed (bottom r) (maximum (map bottom boxes))+  rangeOf sid (rectH r - 50)+  setScrollOffsetIO ctx sid (rectH r - 50)+  warmup ctx input0 wrapped+  arenaRects ctx >>= assertEq failed 50 . bottom . last+  let pinned = scrolled 100 50 (box (fixedWH 80 20) red >> box (pinAt 0 200 . fixedWH 30 30) blue)+  (pid, _) <- warmup2 ctx input0 pinned+  rangeOf pid 180+  setScrollOffsetIO ctx pid 180+  warmup ctx input0 pinned+  rectsAt ctx [2, 3] >>= assertEq failed [Rect 0 (-180) 80 20, Rect 0 20 30 30]+  assertJustM failed (getClipRect (ctxNodeArena ctx) 3) (assert failed . covers (Rect 0 0 100 50))+  fresh <- newContext+  forM_ [layered, wrap] $ \flow -> do+    (fid, _) <- warmup2 fresh input0 . columnWith tight . scrollArea2D (flow . fixedWH 100 50 . tight . gap 0) $+      replicateM_ 3 (box (fixedWH 40 20) red)+    arenaRects fresh >>= assertEq failed [0, 20, 40] . map rectY . drop 2+    assertJustM failed (getScrollMetricsIO fresh fid) (assertEq failed 10 . v2Y . scrollRange)++-- | Each case's first colour is painted before its second. A pinned child+-- outside its parent is still painted, also on a frame that repaints only it.+runLayerPaintOrderTest :: Context -> IORef Int -> IO ()+runLayerPaintOrderTest ctx failed = do+  forM_ cases $ \(ui, under, over) -> do+    quads <- drawQuads . snd =<< warmupDraw ctx input0 ui+    let indexOf col = findIndex ((== col) . snd) quads+    assertJust failed ((,) <$> indexOf under <*> indexOf over) $ \(u, o) -> assert failed (u < o)+  let outside version = columnWith (tight . gap 0 . fillW) $ do+        layersWith tight $ box (pinAt 10 10 . fixedWH 20 20) green+        rowWith (tight . fixedWH 50 20) $+          drawingVersioned version (pinAt 200 0 . fixedWH 20 20) $ \r ->+            smallArrayFromList [FillRect r (if version == 1 then red else blue)]+      drawn draw = map snd <$> drawQuads draw+  full <- drawn . snd =<< warmupDraw ctx input0 (outside 1)+  assert failed (green `elem` full && red `elem` full)+  writeIORef (ctxPaintFull ctx) False+  (_, draw, _) <- runFrame ctx input0 (outside 2)+  takeDamage ctx >>= \d -> assert failed (d /= DamageFull)+  assert failed . elem blue =<< drawn draw+  where+    sq n = fixedWH n n+    cases =+      [ (rowWith tight (box (sq 60) green >> box (sq 20) yellow), yellow, green)+      , (layersWith tight (box (sq 60) red >> box (sq 20) blue), red, blue)+      , (rowWith tight (box (sq 40) red >> box (pinAt 10 10 . sq 10) blue), red, blue)+      , (layersWith tight (box (pinAt 5 5 . sq 10) blue >> box (sq 60) red), red, blue)+      ]++-- | Changing only a pin offset, a row's wrap flag, or its line gap relayouts+-- the frame and repaints the moved children's old and new rects.+runLayoutFlowDamageTest :: Context -> IORef Int -> IO ()+runLayoutFlowDamageTest ctx failed = do+  let ui x wrapped lg = columnWith (tight . gap 0) $ do+        rowWith (tight . fixedWH 200 60) $ do+          box (fixedWH 50 50) green+          box (pinAt x 10 . fixedWH 20 20) blue+        rowWith ((if wrapped then wrap else id) . lineGap lg . fixedW 100 . tight . gap 0) $ do+          box (fixedWH 70 10) red+          box (fixedWH 40 10) yellow+      step view moved repainted = do+        warmup ctx input0 view+        dmg <- takeDamage ctx+        rectsAt ctx (map fst moved) >>= assertEq failed (map snd moved)+        forM_ repainted $ assert failed . damageCovers dmg+  _ <- warmup2 ctx input0 (ui 10 False 0)+  writeIORef (ctxPaintFull ctx) False+  step (ui 120 False 0) [(3, Rect 120 10 20 20)] [Rect 10 10 20 20, Rect 120 10 20 20]+  -- The yellow box moves onto its own line.+  step (ui 120 True 0) [(4, Rect 0 60 100 20), (6, Rect 0 70 40 10)] [Rect 70 60 40 10, Rect 0 70 40 10]+  step (ui 120 True 5) [(4, Rect 0 60 100 25), (6, Rect 0 75 40 10)] [Rect 0 75 40 10]++-- | Every arena column fits within its row stride; otherwise it would+-- overwrite the next node's row.+runArenaColumnsFitStridesTest :: Context -> IORef Int -> IO ()+runArenaColumnsFitStridesTest _ failed =+  assert failed $+    and+      [ columns (minBound :: GeomCol) <= geomStride+      , columns (minBound :: StyleCol) <= styleStride+      , columns (minBound :: TagCol) <= tagStride+      , columns (minBound :: TreeCol) <= treeStride+      ]+  where+    columns :: (Enum c, Bounded c) => c -> Int+    columns c = fromEnum (maxBound `asTypeOf` c) + 1++-- | Each point names the widget it hovers, makes hot and clicks, if any: the+-- topmost, by layer and pin, and under 'pointer' modes ('PointerBlock' over+-- the button, 'PointerPass' through a drawing).+runPointerOwnerTest :: Context -> IORef Int -> IO ()+runPointerOwnerTest ctx failed =+  forM_ cases $ \(ui, points) -> sim ctx failed ui $ do+    ws <- result+    let only want = [Just i == want | i <- [0 .. length ws - 1]]+    forM_ (points ws) $ \(t, want) -> do+      _ <- moveTo t+      hovered <- moveTo t+      checkEq (maybe (WidgetId 0) (respId . (ws !!)) want) =<< hotId+      checkEq (only want) (map respHovered hovered)+      checkEq (only want) . map respClicked =<< click t+  where+    btn f w h = buttonWith' (f . fixedWH w h) "b"+    over inner = columnWith tight ((\a b -> [a, b]) <$> btn id 200 100 <*> inner)+    panelOver mode = over (panelWith (pointer mode . pinAt 10 10 . fixedWH 120 60) (btn id 40 20))+    drawingOver mode = over (drawing (pointer mode . pinAt 20 20 . fixedWH 100 50) (const mempty))+    cases =+      [ (layers (sequence [btn id 120 40, btn id 120 40]), const [(at 63 23, Just 1)])+      , (rowWith tight (sequence [btn id 120 40, btn (pinAt 20 10) 40 20]), const [(at 40 20, Just 1), (at 100 20, Just 0)])+      , (layersWith tight (sequence [btn (pinAt 10 10) 40 20, btn id 120 60]), const [(at 30 20, Just 0)])+      , ( rowWith tight ((:) <$> btn id 200 100 <*> layersWith (pinAt 10 10 . tight) (sequence [btn id 50 50, btn id 20 20]))+        , const [(at 15 15, Just 2), (at 40 40, Just 1), (at 150 50, Just 0)] )+      , (panelOver PointerAuto, \ws -> [(at 100 60, Just 0), (On (ws !! 1), Just 1), (at 190 90, Just 0)])+      , (panelOver PointerBlock, \ws -> [(at 100 60, Nothing), (On (ws !! 1), Just 1), (at 190 90, Just 0)])+      , ( columnWith tight . panelWith (pointer PointerBlock . fixedWH 300 200) $+            (: []) <$> btn id 200 100 <* box (pinAt 0 0 . fixedWH 150 80 . pointer PointerBlock) red+        , const [(at 100 60, Nothing), (at 190 90, Just 0)] )+      , (drawingOver PointerAuto, const [(at 60 40, Just 1)])+      , (drawingOver PointerPass, const [(at 60 40, Just 0)])+      , ( columnWith tight $ (\a b -> [a, b]) <$> drawing (fixedWH 200 100) (const mempty) <*> btn (pinAt 10 10) 60 30+        , const [(at 40 25, Just 1), (at 150 70, Just 0)] )+      ]++-- | Focus and the text cursor follow the topmost widget: a button or a+-- blocking panel over a field or select keeps focus as it was, while a+-- field over a button or another field takes it.+runCoveredFieldFocusTest :: Context -> IORef Int -> IO ()+runCoveredFieldFocusTest ctx failed = do+  let field f t = fst <$> withValue t (textInputConfigured' defaultTextInputConfig {ticLayout = f})+      onLeft r = At (V2 (rectX (respRect r) + 20) (rectY (respRect r) + rectH (respRect r) / 2))+      focusAfter t = click t >> focusedId+      layeredUi = column $ do+        (f, cover) <- layers $ (,) <$> field (fixedW 200) "under" <*> buttonWith' (alignEnd . fixedWH 40 20) "x"+        (under, top) <- layers $ (,) <$> buttonWith' (fixedWH 200 30) "under" <*> field (fixedW 100) "over"+        pure (f, cover, under, top)+  sim ctx failed layeredUi $ do+    (f, cover, _, top) <- result+    check . (/= UiCursorText) =<< cursorAt (On cover)+    checkEq UiCursorText =<< cursorAt (onLeft f)+    (_, cover1, _, _) <- click (On cover)+    check (respClicked cover1)+    checkEq (WidgetId 0) =<< focusedId+    checkEq (respId f) =<< focusAfter (onLeft f)+    checkEq (respId f) =<< focusAfter (On cover)+    (_, _, under, _) <- click (On top)+    check (not (respClicked under))+    checkEq (respId top) =<< focusedId+  let pinnedOver = columnWith tight $ do+        cover <- buttonWith' (pinAt 100 0 . fixedWH 60 20) "x"+        f <- field (fixedW 200) "text"+        (s, over) <- layersWith tight $+          (,) <$> (fst <$> withValue 0 (selectWith' (fixedW 200) ["Alpha", "Beta"])) <*> buttonWith' (alignEnd . fixedWH 40 20) "y"+        pure (cover, f, s, over)+  newContext >>= \c -> runSim c failed input0 pinnedOver $ do+    (cover, f, _, over) <- result+    (cover1, _, _, _) <- click (On cover)+    check (respClicked cover1)+    checkEq (WidgetId 0) =<< focusedId+    checkEq (respId f) =<< focusAfter (onLeft f)+    checkEq (respId f) =<< focusAfter (On cover)+    (_, _, _, over1) <- click (On over)+    check (respClicked over1)+    checkEq (WidgetId 0) =<< focusedId+  let pinnedField = columnWith tight (field (pinAt 50 0 . fixedW 100) "pinned" <* field (fixedW 300) "under")+  newContext >>= \c -> runSim c failed input0 pinnedField $ do+    pinned <- result+    checkEq UiCursorText =<< cursorAt (On pinned)+    _ <- rightClick (On pinned)+    checkEq (respId pinned) =<< focusedId+  let blocked mode = columnWith tight $+        field (fixedW 200) "text" <* panelWith (pointer mode . pinAt 60 0 . fixedWH 80 20) (pure ())+  forM_ [(PointerAuto, True), (PointerBlock, False)] $ \(mode, through) -> sim ctx failed (blocked mode) $ do+    f <- result+    let p = At (V2 (rectX (respRect f) + 100) (rectY (respRect f) + 10))+    checkEq through . (== UiCursorText) =<< cursorAt p+    _ <- click p+    checkEq (if through then respId f else WidgetId 0) =<< focusedId+    void (click (At (V2 390 290)))++-- | A widget under a pinned button shows no tooltip, moves no slider and+-- opens no select. A chip's control adornment takes its own click.+runCoveredWidgetNoPointerTest :: Context -> IORef Int -> IO ()+runCoveredWidgetNoPointerTest ctx failed = do+  let tipped txt w = w <$ tooltipConfigured defaultTooltipConfig {tooltipDelay = 0} w txt+      tipShown txt t = moveTo t >> labelShown txt+      covered = columnWith tight $ do+        _ <- drawing (fixedWH 200 100) (const mempty) >>= tipped "Canvas tip"+        buttonWith' (pinAt 10 10 . fixedWH 60 30) "pin"+  sim ctx failed covered $ do+    pin <- On <$> result+    check . not =<< tipShown "Canvas tip" pin+    check =<< tipShown "Canvas tip" (At (V2 150 70))+  valueRef <- newVar (0 :: Float)+  let sliderUi = columnWith (tight . fixedW 300) $+        held valueRef (sliderWith' id 0 100) >> buttonWith' (pinAt 200 0 . fixedWH 60 20) "x"+  sim ctx failed sliderUi $ do+    (_, b) <- pressThrough . On =<< result+    check (respClicked b)+    checkEq 0 =<< readV valueRef+  let selectUi = columnWith tight $+        withValue 0 (selectWith (fixedW 200) ["Alpha", "Beta", "Gamma"]) >> buttonWith' (pinAt 120 0 . fixedWH 60 20) "y"+  sim ctx failed selectUi $ do+    onB <- On <$> result+    _ <- pressThrough onB+    _ <- moveTo onB+    expectNot "Gamma"+  removes <- newIORef (0 :: Int)+  let remove = A.trailing (A.control (whenM (buttonWith tight "x") (liftIO (modifyIORef' removes (+ 1)))))+      chipOver = columnWith tight $ layersWith tight $ do+        under <- drawing (fixedWH 200 100) (const mempty)+        (under,) <$> buttonConfigured' defaultButtonConfig {bcAdornments = remove} "Chip"+  sim ctx failed chipOver $ do+    _ <- moveTo "Chip"+    (under1, chip1) <- moveTo "Chip"+    check (respHovered chip1 && not (respHovered under1))+    ((under2, _), (_, chip3)) <- pressThrough "x"+    check (not (respHovered under2 || respPressed under2) && not (respClicked chip3))+    checkEq 1 =<< liftIO (readIORef removes)+  let labelUi = columnWith tight $ do+        l <- labelWith' (fixedWH 200 40) "Covered text" >>= tipped "Label tip"+        l <$ buttonWith' (pinAt 100 0 . fixedWH 60 30) "on top"+  sim ctx failed labelUi $+    forM_ [(V2 130 15, False), (V2 40 15, True)] $ \(p, uncovered) -> do+      _ <- moveTo (At p)+      checkEq uncovered . respHovered =<< moveTo (At p)+      checkEq uncovered =<< tipShown "Label tip" (At p)++-- | Grow, percent, shrink and aspect sizing, 12 px a character. Locking the+-- largest grow child must lock the middle one on a later sweep (one sweep+-- gives it 55), and percent children give a gap's overflow back.+runFlexSizingTest :: Context -> IORef Int -> IO ()+runFlexSizingTest ctx failed = forM_ cases $ \(w, h, ui, size, want) -> do+  ids <- warmup2 ctx (withInput w h) ui+  got <- mapM (fmap (maybe [] size) . getPrevRect ctx) ids+  let near a b = abs (a - b) <= 0.5+  unless (map length got == map length want && and (zipWith near (concat got) (concat want))) $+    assertEq failed want got+  where+    sized l txt = respId <$> labelWith' (l . tight) txt+    filling l = sized (fillW . l)+    shrink l = l {layoutWidth = Shrink 1}+    rowOf w = rowWith (fixedW w . tight . gap 0) . sequence+    widths = pure . rectW+    sizes r = [rectW r, rectH r]+    -- Spacers keep a non-zero width: prev-rect tracking skips zero-area rects.+    growSpacer = currentId <* spacer (Fixed 10) (Grow 1)+    halves = rowWith (fixedW 206 . tight . gap 6) (sequence [sized (percent 50) "A", sized (percent 50) "B"])+    cases :: [(Float, Float, NanoUI [WidgetId], Rect -> [Float], [[Float]])]+    cases =+      [ (210, 40, rowOf 210 [filling id "A", filling id "AAAAA"], widths, [[105], [105]])+      , (200, 40, rowOf 200 [filling id "A", filling id (T.replicate 15 "A")], widths, [[20], [180]])+      , (240, 40, rowOf 240 (map (`filling` "A") [minW 12, minW 60, minW 130]), widths, [[50], [60], [130]])+      , (60, 200, columnWith (fixedH 200 . tight . gap 0) (sequence [growSpacer, growSpacer]), pure . rectH, [[100], [100]])+      , (200, 80, rowOf 200 [sized (percent 25) "A", sized (percent 75) "B"], widths, [[50], [150]])+      , (300, 80, halves, \r -> [rectX r, rectW r], [[0, 100], [106, 100]])+      , ( 400+        , 200+        , rowOf 100 [sized shrink "abcdefghijkl", spacer (Grow 1) (Fixed 5) >> respId <$> buttonWith' tight "X"]+        , \r -> [rectX r + rectW r]+        , [[64], [100]]+        )+      , (400, 200, rowOf 100 [sized shrink "abcdefghijkl" <* labelWith (shrink . tight) "ab"], widths, [[100]])+      , (320, 240, columnWith (fixedW 160 . tight) (sequence [sized (fixedAspectW 160 2) "X"]), sizes, [[160, 80]])+      ]++-- | An end-aligned label's text ends at the label's right edge.+runLabelAlignEndTest :: Context -> IORef Int -> IO ()+runLabelAlignEndTest ctx failed = do+  let tw = fmAdvance (ctxFontMetrics ctx) ' ' * 2+      ui = rowWith (fixedW (tw + 4) . tight . gap 0) (labelWith' (fillW . alignEnd . tight) "ab")+  lab <- warmup2 ctx emptyInput {inputWindowSize = Size (tw + 12) 8} ui+  assertJustM failed (spanRect "ab" <$> collectTextSpans ctx) $ \(Rect x _ w _) -> do+    let Rect bx _ bw _ = respRect lab+    assert failed (abs (x + w - (bx + bw)) <= 0.6 && abs (w - tw) <= 0.6)+  checkLabelAlignEndInk failed++-- | Nesting past the level array's first capacity lays out, a responsive row+-- stacks only below its breakpoint, and a multi-line kv value pushes the next+-- row down.+-- | The primed containers report where they were laid out, around the label+-- inside each.+primedUi :: NanoUI [(Rect, Rect)]+primedUi = column $ do+  let inside f = f (respRect <$> buttonWith' id "x")+  p <- inside (panelWith' id)+  c <- inside (calloutWith' (colorRGBA 200 0 0 255) id)+  g <- inside (gridWith' 2 id)+  l <- inside (layersWith' id)+  pure [(b, respRect r) | (b, r) <- [p, c, g, l]]++primedRects :: Sim [(Rect, Rect)] ()+primedRects = do+  rs <- result+  checkEq 4 (length rs)+  mapM_ (\(Rect bx by bw bh, Rect x y w h) -> check (bw > 0 && bx >= x && by >= y && bx + bw <= x + w + 1.0e-3 && by + bh <= y + h + 1.0e-3)) rs++-- | A width/height ratio that is zero, negative or infinite gives a square+-- instead of an infinite or negative side.+badRatioUi :: NanoUI [Rect]+badRatioUi = column $ forM [fixedAspectW 40 0, fixedAspectW 40 (-2), fixedAspectH 40 (1 / 0)] $ \f ->+  respRect <$> buttonWith' f "x"++badRatio :: Sim [Rect] ()+badRatio = mapM_ (\(Rect _ _ w h) -> checkEq (40, 40) (w, h)) =<< result++-- | A wrapping label is laid out as tall as the lines paint draws for it, at+-- fractional positions and widths: the solve wraps at the width the node+-- snaps to, as paint does, so the next label never overlaps its last line+-- and no blank line is left above it.+runWrapMatchesPaintTest :: Context -> IORef Int -> IO ()+runWrapMatchesPaintTest _ failed =+  forM_ [(s, p, w) | s <- [1, 1.5], p <- [10, 10.15 .. 11], w <- [150, 151.3 .. 175]] $ \(s, p, w) -> do+    ctx <- (`withFontMetrics` (monospaceMetrics 12) {fmSnapScale = s}) <$> newContext+    let ui = columnWith (fixedW w . gap 0 . \l -> l {layoutPadding = Padding p p 0 0}) $ do+          labelWith fillW "the quick brown fox jumps over the lazy dog"+          label "END"+    runSim ctx failed (withInput 400 400) ui $ do+      shown <- spans+      let lineRects = [r | (r, t, _, _, _) <- shown, T.strip t /= "END"]+          bottom = maximum (0 : [rectY r + rectH r | r <- lineRects])+      Rect _ endY _ _ <- rectOf "END"+      check (not (null lineRects))+      checkEq (s, p, w, True) (s, p, w, endY + 1.0e-3 >= bottom && endY - bottom < 2)++runLayoutFlowTest :: Context -> IORef Int -> IO ()+runLayoutFlowTest ctx failed = do+  let nest :: Int -> NanoUI ()+      nest 0 = label "deep"+      nest k = column (nest (k - 1))+      stacking = responsiveRowCol 720 (tight . gap 8 . fillW) $ do+        columnWith (tight . gap 8 . fillW) (card (label "LeftTop") >> card (label "LeftBot"))+        card (label "Right")+      kvs = column . card $ kv "Notes" "Line 1\nLine 2\nLine 3\nLine 4\nLine 5" >> kv "Tree" "0"+      above a b = join ((\ra rb -> checkGt (rectY rb) (rectY ra + 1)) <$> rectOf a <*> rectOf b)+  runSim ctx failed (withInput 300 300) (nest 320) (expect "deep")+  responsiveCtx <- newPixelContext+  runSim responsiveCtx failed (withInput 520 800) stacking $ do+    above "LeftBot" "Right"+    _ <- resize 1200 800+    right <- rectOf "Right"+    leftTop <- rectOf "LeftTop"+    checkGt (rectX right) (rectX leftTop + 1)+  kvCtx <- newPixelContext+  runSim kvCtx failed (withInput 320 400) kvs (above "Line 5" "Tree")+  -- More than 8 shrinkable children hitting staggered floors triggers waterFillShrink.+  shrinkCtx <- newPixelContext+  let floors = [100, 49, 45.4, 45.08, 45.06, 45.055, 45.054, 45.0539, 45.05388, 0, 0, 0 :: Float]+      shrinkUi = rowWith (tight . gap 0 . fixedW 600) $+        forM_ floors $ \mw ->+          rowWith (\l -> (tight . gap 0 . minW mw $ l) {layoutWidth = Shrink 1, layoutHeight = Fixed 10}) $+            box (fixedWH 100 10) red+  _ <- warmup2 shrinkCtx (withInput 700 100) shrinkUi+  -- Each item is a row + inner box (2 nodes per item) after the outer row (node 0).+  allRs <- arenaRects shrinkCtx+  let ws = [rectW (allRs !! (1 + 2 * i)) | i <- [0 .. length floors - 1]]+  assertEq failed (length floors) (length ws)+  assert failed (all (\(mw, w) -> w + 0.5 >= mw) (zip floors ws))+  assert failed (abs (sum ws - 600) <= 1.0)++-- | A frame with no widgets runs input, redraw and cursor queries on the+-- empty arena, not on node 0, which starts out as its own child: reading it+-- recursed without end.+runEmptyFrameTest :: Context -> IORef Int -> IO ()+runEmptyFrameTest ctx failed = do+  arrays <- arenaArrays (ctxNodeArena ctx)+  writeTagEnum arrays 0 TagNodeType NodeContainer+  writeTree arrays 0 TreeFirstChild 0+  writeTree arrays 0 TreeNextSibling (-1)+  let inp0 = (withInput 320 200) {inputMousePos = V2 40 40}+  _ <- runFrame ctx inp0 (pure ())+  _ <- runFrame ctx (applyMouseButton MouseLeft True inp0) {inputScroll = V2 0 1} (pure ())+  _ <- needsRedraw ctx inp0 (inp0 {inputMousePos = V2 60 60})+  _ <- uiCursorKind ctx inp0+  wid <- warmup2 ctx inp0 (row (currentId <* image (fixedWH 40 24) (ImageId 0)))+  assertJustM failed (getPrevRect ctx wid) $ \(Rect _ _ w h) ->+    assert failed (abs (w - 40) <= 0.5 && abs (h - 24) <= 0.5)++runContainerQueryTest :: Context -> IORef Int -> IO ()+runContainerQueryTest ctx failed = do+  let pair prefix =+        responsiveRowColIn 220 tight $ do+          label (prefix <> "-A")+          label (prefix <> "-B")+      cqUi =+        rowWith (gap 8 . tight) $ do+          columnWith (fixedW 150 . tight) (pair "narrow")+          columnWith (fixedW 260 . tight) (pair "wide")+  runSim ctx failed (withInput 500 200) cqUi $ do+    na <- rectOf "narrow-A"+    nb <- rectOf "narrow-B"+    wa <- rectOf "wide-A"+    wb <- rectOf "wide-B"+    checkGt (rectY nb) (rectY na + 4)+    checkGt (rectX wb) (rectX wa + 4)+  -- withContainerQuery schedules a follow-up frame only when its projected+  -- discrete bucket changes, not on pixel resizes within the same bucket.+  let bucketUi =+        withContainerQuery (fillW . fillH) (\(Size w _) -> if w >= 300 then (2 :: Int) else 1) $ \cols ->+          gridWith cols (fillW . tight) $ do+            label "Q1"+            label "Q2"+  c <- newContext+  _ <- warmup2 c (withInput 400 200) bucketUi+  (_, _, followSameBucket) <- runFrame c (withInput 360 200) bucketUi+  assertEq failed False followSameBucket+  (_, _, followCrossBucket) <- runFrame c (withInput 250 200) bucketUi+  assertEq failed True followCrossBucket+  -- Check layout convenience modifiers: direction, fitW, fitH, growW, growH,+  -- percentH, spacerW, spacerH, clipBox.+  c2 <- newContext+  let helperUi =+        columnWith (fixedWH 200 100 . tight . gap 0) $ do+          rowWith (direction Row . fitW . fitH . tight . gap 0) $ do+            box (fixedWH 20 10) red+            spacerW 15+            box (fixedWH 20 10) green+          spacerH 10+          clipBox (fixedWH 80 30) $+            box (fixedWH 120 50) blue+          rowWith (fillW . percentH 50 . tight . gap 0) $ do+            box (growW 1 . growH 1) yellow+            box (growW 3 . growH 1) red+  _ <- warmup2 c2 (withInput 400 300) helperUi+  arenaRects c2 >>= \case+    [_, _, r1, _, r2, _, clipR, _, _, g1, g2] -> do+      assertEq failed 35 (rectX r2 - rectX r1)+      assertEq failed (Rect 0 20 80 30) clipR+      assertEq failed 50 (rectH g1)+      assertEq failed 50 (rectW g1)+      assertEq failed 150 (rectW g2)+    rs -> assertEq failed 11 (length rs)++-- | 'itemsStretch' stretches unaligned Fit cross-axis children while preserving+-- explicit alignment and fixed sizes; 'justify*' distributes leftover main-axis+-- slack in both Row and Column.+runItemsStretchAndJustifyTest :: Context -> IORef Int -> IO ()+runItemsStretchAndJustifyTest ctx failed = do+  let inp = withInput 500 400+  -- Column with itemsStretch: unaligned Fit child stretches to 200; explicit+  -- alignStart and fixedW children keep their own width.+  let colStretch = columnWith (tight . gap 4 . fixedW 200 . itemsStretch) $ do+        panelWith (tight . fixedH 20) (label "stretch")+        panelWith (tight . fixedH 20 . alignStart) (label "explicit")+        box (fixedWH 40 20) green+  _ <- warmup2 ctx inp colStretch+  arenaRects ctx >>= \case+    [_, pStretch, _, pExplicit, _, fixedBox] -> do+      assertEq failed 200 (rectW pStretch)+      assertLt failed (rectW pExplicit) 150+      assertEq failed 40 (rectW fixedBox)+    rs -> assertEq failed 6 (length rs)+  -- Row with itemsStretch: unaligned Fit child stretches to row height 60;+  -- explicit alignTop keeps its own height.+  let rowStretch = rowWith (tight . gap 4 . fixedWH 200 60 . itemsStretch) $ do+        panelWith (tight . fixedW 40) (label "s")+        panelWith (tight . fixedW 40 . alignTop) (label "t")+  _ <- warmup2 ctx inp rowStretch+  arenaRects ctx >>= \case+    [_, pStretch, _, pTop, _] -> do+      assertEq failed 60 (rectH pStretch)+      assertLt failed (rectH pTop) 40+    rs -> assertEq failed 5 (length rs)+  -- Justify in Row (width 200, three 20px boxes, gap 10 -> content 80, slack 120):+  let rowJ j = rowWith (tight . gap 10 . fixedWH 200 30 . j) $ do+        box (fixedWH 20 20) red+        box (fixedWH 20 20) green+        box (fixedWH 20 20) blue+  forM_+    [ (justifyStart, [0, 30, 60])+    , (justifyCenter, [60, 90, 120])+    , (justifyEnd, [120, 150, 180])+    , (justifyBetween, [0, 90, 180])+    ]+    $ \(j, wantXs) -> do+      _ <- warmup2 ctx inp (rowJ j)+      arenaRects ctx >>= \case+        [_, a, b, c] -> assertEq failed wantXs (map rectX [a, b, c])+        rs -> assertEq failed 4 (length rs)+  -- Single child under justifyBetween starts at 0 (no division by zero).+  _ <- warmup2 ctx inp (rowWith (tight . fixedWH 200 30 . justifyBetween) (box (fixedWH 20 20) red))+  arenaRects ctx >>= \case+    [_, a] -> assertEq failed 0 (rectX a)+    rs -> assertEq failed 2 (length rs)+  -- Justify in Column (height 200, two 20px boxes, gap 10 -> content 50, slack 150):+  let colJ j = columnWith (tight . gap 10 . fixedWH 60 200 . j) $ do+        box (fixedWH 20 20) red+        box (fixedWH 20 20) green+  forM_+    [ (justifyStart, [0, 30])+    , (justifyCenter, [75, 105])+    , (justifyEnd, [150, 180])+    , (justifyBetween, [0, 180])+    ]+    $ \(j, wantYs) -> do+      _ <- warmup2 ctx inp (colJ j)+      arenaRects ctx >>= \case+        [_, a, b] -> assertEq failed wantYs (map rectY [a, b])+        rs -> assertEq failed 3 (length rs)++-- | Container cross-axis alignment ('itemsCenter', 'itemsEnd', 'itemsBaseline')+-- applies to children without explicit alignment, lets explicit child modifiers+-- (including 'alignTop' and 'alignStart') override it, does not leak into nested+-- containers or pinned children, and keeps fill-width text left-aligned.+runItemsAlignTest :: Context -> IORef Int -> IO ()+runItemsAlignTest ctx failed = do+  let inp = withInput 500 400+  -- Row with itemsCenter: short child centers vertically, explicit alignTop/alignBottom+  -- override it, nested row keeps ItemsStart, and pinned child ignores itemsCenter.+  let rowUi = rowWith (tight . gap 4 . fixedWH 300 60 . itemsCenter) $ do+        box (fixedWH 20 20) green+        box (fixedWH 20 20 . alignTop) red+        box (fixedWH 20 20 . alignBottom) blue+        rowWith (tight . gap 0 . fixedWH 60 60) (box (fixedWH 10 10) yellow)+        box (pinAt 4 4 . fixedWH 12 12) red+  _ <- warmup2 ctx inp rowUi+  arenaRects ctx >>= \case+    [_, midBox, topBox, botBox, _, nestedBox, pinnedBox] -> do+      assertEq failed 20 (rectY midBox)+      assertEq failed 0 (rectY topBox)+      assertEq failed 40 (rectY botBox)+      assertEq failed 0 (rectY nestedBox)+      assertEq failed (Rect 4 4 12 12) pinnedBox+    rs -> assertEq failed 7 (length rs)+  -- Column with itemsCenter: fit child centers horizontally, explicit alignStart+  -- overrides it, and a fillW label keeps left-aligned text spans.+  let colUi = columnWith (tight . gap 4 . fixedW 200 . itemsCenter) $ do+        box (fixedWH 40 16) green+        box (fixedWH 40 16 . alignStart) red+        labelWith (tight . fillW) "left-fill"+  _ <- warmup2 ctx inp colUi+  arenaRects ctx >>= \case+    [_, centeredBox, startBox, _] -> do+      assertEq failed 80 (rectX centeredBox)+      assertEq failed 0 (rectX startBox)+    rs -> assertEq failed 4 (length rs)+  colSpans <- collectTextSpans ctx+  assertJust failed (spanRect "left-fill" colSpans) $ \r ->+    assertEq failed 0 (rectX r)+  -- Row with itemsBaseline aligns labels and buttons without per-child alignBaseline,+  -- ignores stretched grow-height children such as vertical separators, and respects+  -- an explicit alignTop override.+  let baseUi = rowWith (tight . gap 8 . fixedH 60 . itemsBaseline) $ do+        labelWith (tight . fontSize 32) "Big"+        separator+        labelWith tight "small"+        void (button "Go")+        labelWith (tight . alignTop) "top"+  _ <- warmup2 ctx inp baseUi+  baseSpans <- collectTextSpans ctx+  case mapM (`spanRect` baseSpans) ["Big", "small", "Go", "top"] of+    Just [big, small, go, topLbl] -> do+      let baseline r = rectY r + 0.8 * rectH r+      assert failed (abs (baseline small - baseline big) < 0.5)+      assert failed (abs (baseline go - baseline big) < 0.5)+      assert failed (rectY small > rectY big)+      assert failed (rectY small + rectH small <= 60)+      assertEq failed 0 (rectY topLbl)+    _ -> assert failed False+  -- Grid with itemsCenter centers short cells vertically in taller grid rows,+  -- and changing itemsAlign dynamically invalidates the layout cache.+  let gridUi ia = gridWith 2 (tight . gap 0 . fixedW 200 . itemsAlign ia) $ do+        box (fixedWH 20 20) green+        box (fixedWH 20 60) blue+  _ <- warmup2 ctx inp (gridUi ItemsCenter)+  arenaRects ctx >>= \case+    [_, shortCell, _] -> assertEq failed 20 (rectY shortCell)+    rs -> assertEq failed 3 (length rs)+  _ <- runFrame ctx inp (gridUi ItemsEnd)+  arenaRects ctx >>= \case+    [_, shortCell, _] -> assertEq failed 40 (rectY shortCell)+    rs -> assertEq failed 3 (length rs)
+ test/integration/Cases/LayoutProps.hs view
@@ -0,0 +1,439 @@+{-# OPTIONS_GHC -O0 #-}+-- | Properties of the layout solve over random container trees: children+-- stay inside their parents, siblings in a line do not overlap, grow+-- children share the leftover space by factor, and every edge lands on the+-- device pixel grid.+module Cases.LayoutProps (tests) where++import Spec+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena+  ( AxisSizing (..)+  , SizingTag (..)+  , StyleCol (..)+  , TreeCol (..)+  , arenaArrays+  , arenaCount+  , getDirection+  , getFirstChild+  , getFlow+  , getHeightSizing+  , getNextSibling+  , getNodeRect+  , getNodeType+  , getPadding+  , getParent+  , getWidthSizing+  , isFloatingNode+  , isScrollNode+  , readStyle+  , readTree+  )+import NanoUI.Testing.Sim qualified as Sim+import Test.QuickCheck (Arbitrary (..), Gen, Property, choose, counterexample, elements, frequency, ioProperty, sized, vectorOf)++tests :: [Spec]+tests =+  [ propSpec "layout-props" 7 400 layoutProperties+  , sceneSpec "wrap-row-height" wrapRowScene+  , sceneSpec "grid-cell-height" gridCellScene+  , sceneSpec "fill-label-height" fillLabelScene+  , sceneSpec "wrap-percent-height" wrapPercentScene+  , sceneSpec "wrap-row-in-row-alignment" wrapInRowScene+  ]++-- Scenes whose heights depend on width, measured at one width and laid out+-- at another. Each broke a property before the solve refit heights at the+-- width a node is laid out at.+--+-- A fit column in a 51 px row measures its wrapped row at 51 px (two lines,+-- 72 px tall) but lays it out at the 138 px its content asks for (one line,+-- 42 px of content).+--+-- A 72 px column holds a two-column grid with a filling label, which lays+-- out a line taller in its 25 px cell than the column measured it.+--+-- A fit column in a 148 px wrapped row holds a filling label in a grow+-- column, which lays out fewer lines at the column's width than it measured+-- at the row's.+--+-- A 235 px wrapped row holds a 44 % column, a checkbox and a button: the+-- percentage of the line breaks it into two lines.+--+-- A grow wrapped row in a row is 40 px wide, where its filling label takes+-- four lines, and is centred in the row at that height.++-- | Check one scene at snap scale 1, printing what it breaks.+sceneSpec :: String -> Scene -> Spec+sceneSpec name scene = spec name $ \_ failed -> do+  problems <- violations 1 <$> sceneNodes 1 scene+  unless (null problems) (mapM_ putStrLn problems >> modifyIORef' failed (+ 1))++wrapInRowScene :: Scene+wrapInRowScene =+  Scene 900 700 $+    Box KRow (Mods SFit SFit 10 3 2)+      [ Box KCol (Mods SFit SFit 0 3 2) [Leaf LCheck, Leaf LCheck, Box KRow (Mods SFit SFit 4 0 1) [Leaf LSep]]+      , Box KRow (Mods SFit SFill 4 0 0)+          [ Box KRow (Mods (SPercent 87) SFit 4 0 3) []+          , Box KWrap (Mods (SGrow 3) SFit 0 8 1) [Leaf (LGrow 2), Leaf (LGrow 4), Leaf (LLabelFill 27)]+          ]+      ]++gridCellScene :: Scene+gridCellScene =+  Scene 1600 1200 $+    Box KCol (Mods (SGrow 2) (SGrow 3) 4 8 0)+      [ Box KWrap (Mods (SFixed 293) SFill 0 8 1) []+      , Box KCol (Mods (SFixed 72) SFit 10 8 2) [Box (KGrid 2) (Mods SFit SFit 0 3 1) [Leaf (LLabelFill 91)]]+      ]++fillLabelScene :: Scene+fillLabelScene =+  Scene 640 480 $+    Box KWrap (Mods (SFixed 148) SFill 0 3 0)+      [ Box KCol (Mods SFit SFill 4 8 1)+          [ Box KCol (Mods (SGrow 3) SFit 0 3 3) [Leaf (LLabelFill 17)]+          , Leaf (LGrow 3)+          , Box KRow (Mods SFit SFit 0 0 2) [Leaf (LLabel 29)]+          ]+      ]++wrapPercentScene :: Scene+wrapPercentScene =+  Scene 900 700 $+    Box KCol (Mods SFit SFill 4 0 1)+      [ Leaf (LGrow 2)+      , Box KWrap (Mods (SFixed 235) SFit 0 8 0) [Box KCol (Mods (SPercent 44) SFit 0 3 2) [], Leaf LCheck, Leaf (LButton 36)]+      ]++wrapRowScene :: Scene+wrapRowScene =+  Scene 1600 1200 $+    Box KRow (Mods (SFixed 51) SFit 0 0 0)+      [ Box KCol (Mods SFit SFill 4 3 0)+          [ Box KWrap (Mods SFill SFit 10 8 3) [Leaf (LSpacer 7 20), Leaf (LMeasured 94 26)]+          , Box KRow (Mods SFit (SGrow 1) 4 0 0) [Leaf (LButton 4)]+          ]+      ]++-- | A random container tree. Leaves are labels, buttons, spacers, checkboxes,+-- separators and measured drawings, all small enough that a tree fits a+-- large window, so most containers have room for their children.+data Box = Box Kind Mods [Box] | Leaf Leaf+  deriving (Show)++data Kind = KRow | KCol | KGrid Int | KWrap | KScroll+  deriving (Show)++data Leaf+  = LLabel Int+  | LLabelFill Int+  | LButton Int+  | LSpacer Int Int+  | -- | A spacer that grows by this factor along its parent's main axis.+    LGrow Int+  | LCheck+  | LMeasured Int Int+  | LSep+  deriving (Show)++data Sz = SFit | SFill | SGrow Int | SPercent Int | SFixed Int+  deriving (Show)++data Mods = Mods {mW :: Sz, mH :: Sz, mGap :: Int, mPad :: Int, mAlign :: Int}+  deriving (Show)++-- | A tree and the window it lays out in.+data Scene = Scene Float Float Box+  deriving (Show)++instance Arbitrary Scene where+  arbitrary = do+    (w, h) <- elements [(1600, 1200), (900, 700), (640, 480)]+    Scene w h <$> sized (\n -> genBox (min 3 (1 + n `div` 30)))+  shrink (Scene w h b) = [Scene w h b' | b' <- shrinkBox b]++shrinkBox :: Box -> [Box]+shrinkBox = \case+  Leaf _ -> []+  Box k m kids ->+    kids+      <> [Box k m (take i kids <> drop (i + 1) kids) | i <- [0 .. length kids - 1]]+      <> [Box k m (take i kids <> [kid'] <> drop (i + 1) kids) | (i, kid) <- zip [0 ..] kids, kid' <- shrinkBox kid]+      <> [Box k (m {mH = SFit}) kids | not (isFit (mH m))]+      <> [Box k (m {mW = SFit}) kids | not (isFit (mW m))]+  where+    isFit SFit = True+    isFit _ = False++genBox :: Int -> Gen Box+genBox depth+  | depth <= 0 = Leaf <$> genLeaf+  | otherwise =+      frequency+        [ (1, Leaf <$> genLeaf)+        , (3, genKind >>= \k -> Box k <$> genMods <*> (choose (1, 5) >>= (`vectorOf` genChild k)))+        ]++  where+    genChild = \case+      KGrid _ -> Leaf <$> genLeaf+      KWrap -> Leaf <$> genLeaf+      _ -> genBox (depth - 1)++genKind :: Gen Kind+genKind = frequency [(4, pure KRow), (4, pure KCol), (1, KGrid <$> choose (1, 4)), (1, pure KWrap), (1, pure KScroll)]++genLeaf :: Gen Leaf+genLeaf =+  frequency+    [ (3, LLabel <$> choose (0, 99))+    , (1, LLabelFill <$> choose (0, 99))+    , (2, LButton <$> choose (0, 99))+    , (2, LSpacer <$> choose (0, 60) <*> choose (0, 40))+    , (3, LGrow <$> choose (1, 4))+    , (1, pure LCheck)+    , (1, LMeasured <$> choose (10, 120) <*> choose (8, 40))+    , (1, pure LSep)+    ]++-- | A container's sizes and spacing.+genMods :: Gen Mods+genMods =+  Mods+    <$> genWidth+    <*> frequency [(5, pure SFit), (1, pure SFill), (1, SGrow <$> choose (1, 3)), (1, SFixed <$> choose (30, 300))]+    <*> elements [0, 0, 4, 10]+    <*> elements [0, 0, 3, 8]+    <*> choose (0, 11)+  where+    genWidth = frequency [(4, pure SFit), (2, pure SFill), (2, SGrow <$> choose (1, 3)), (1, SPercent <$> choose (20, 100)), (1, SFixed <$> choose (40, 400))]++-- | Short words, so a label is one line unless its width is a share.+textOf :: Int -> T.Text+textOf i = T.unwords (take (1 + i `mod` 3) (drop (i `mod` 5) (cycle ["alpha", "be", "gamma", "d", "eps"])))++data Axis = AxisRow | AxisCol | AxisNone++renderBox :: Axis -> Box -> NanoUI ()+renderBox axis = \case+  Box kind m kids -> do+    let lay = mods m+        inner a = mapM_ (renderBox a) kids+    case kind of+      KRow -> rowWith lay (inner AxisRow)+      KCol -> columnWith lay (inner AxisCol)+      KGrid n -> gridWith n lay (inner AxisNone)+      KWrap -> rowWith (wrap . lay) (inner AxisNone)+      KScroll -> scrollWith lay (inner AxisCol)+  Leaf leaf -> case leaf of+    LLabel i -> label (textOf i)+    LLabelFill i -> labelWith fillW (textOf i)+    LButton i -> void (button (textOf i))+    LSpacer w h -> spacer (Fixed (fromIntegral w)) (Fixed (fromIntegral h))+    LGrow f -> case axis of+      AxisRow -> spacer (Grow (fromIntegral f)) (Fixed 10)+      AxisCol -> spacer (Fixed 10) (Grow (fromIntegral f))+      AxisNone -> spacer (Fixed 10) (Fixed 10)+    LCheck -> void (withValue False (checkbox "check"))+    LMeasured w h ->+      void $ customWidget defaultCustomWidgetSpec+        { widgetMeasure = Just (\_ (avail, _) -> (min avail (fromIntegral w), fromIntegral h))+        , widgetLayout = fillW+        }+    LSep -> separator+  where+    mods m =+      align (mAlign m) . gap (fromIntegral (mGap m)) . padAll (fromIntegral (mPad m)) . width (mW m) . height (mH m)+    width = \case+      SFit -> id+      SFill -> fillW+      SGrow f -> \l -> l {layoutWidth = Grow (fromIntegral f)}+      SPercent p -> \l -> l {layoutWidth = Percent (fromIntegral p)}+      SFixed px -> \l -> l {layoutWidth = Fixed (fromIntegral px)}+    height = \case+      SFit -> id+      SFill -> fillH+      SGrow f -> \l -> l {layoutHeight = Grow (fromIntegral f)}+      SPercent _ -> id+      SFixed px -> \l -> l {layoutHeight = Fixed (fromIntegral px)}+    align = \case+      1 -> alignMiddle+      2 -> alignEnd+      4 -> itemsCenter+      5 -> itemsEnd+      6 -> itemsBaseline+      7 -> itemsCenter . alignMiddle+      8 -> itemsStretch+      9 -> justifyCenter+      10 -> justifyEnd+      11 -> justifyBetween+      _ -> id++-- | What the checks read of one node.+data Node = Node+  { nType :: NodeType+  , nRect :: Rect+  , nKids :: [Int]+  -- ^ Children in declaration order.+  , nRow :: Bool+  , nLine :: Bool+  -- ^ A single row or column: not wrapped, layered or a grid.+  , nPad :: Padding+  , nGap :: Float+  , nCols :: Int+  -- ^ A grid's column count, else 0.+  , nMain :: AxisSizing+  -- ^ The sizing along the parent's main axis.+  , nFloating :: Bool+  -- ^ Floating, or inside a floating node.+  }++readNodes :: Context -> IO [(Int, Node)]+readNodes ctx = do+  let na = ctxNodeArena ctx+  a <- arenaArrays na+  n <- arenaCount na+  let children i = getFirstChild na i >>= collect []+      collect acc c = if c < 0 then pure acc else getNextSibling na c >>= collect (c : acc)+  nodes <- forM [0 .. n - 1] $ \i -> do+    nt <- getNodeType na i+    parent <- getParent na i+    rowParent <- if parent < 0 then pure True else (== DirRow) <$> getDirection na parent+    dir <- getDirection na i+    flow <- getFlow na i+    cols <- readTree a i TreeGridCols+    node <-+      Node nt+        <$> getNodeRect na i+        <*> children i+        <*> pure (dir == DirRow)+        <*> pure (flow == Line && cols <= 0 && nt == NodeContainer)+        <*> getPadding na i+        <*> readStyle a i StyleGap+        <*> pure (max 0 cols)+        <*> (if rowParent then getWidthSizing na i else getHeightSizing na i)+        <*> pure (isFloatingNode nt)+    pure (i, node, parent)+  -- A parent precedes its children, so one pass marks floating subtrees.+  let marked = foldl' mark [] nodes+      mark acc (i, node, parent) =+        let inherited = maybe False nFloating (lookup parent acc)+         in acc <> [(i, node {nFloating = nFloating node || inherited})]+  pure marked++-- | The broken properties of the solved arena, described.+violations :: Float -> [(Int, Node)] -> [String]+violations scale nodes = concatMap check nodes+  where+    eps = 1e-3+    get i = lookup i nodes+    check (i, p)+      | nFloating p || isScrollNode (nType p) = []+      | otherwise =+          let kids = [(c, k) | c <- nKids p, Just k <- [get c], not (nFloating k)]+           in snapped i p <> contained i p kids <> lined i p kids <> grown i p kids+    -- Every edge times the scale is a whole device pixel.+    snapped i p =+      let Rect x y w h = nRect p+          off v = abs (v * scale - fromIntegral (round (v * scale) :: Int)) > eps+       in ["node " <> show i <> " off the grid at scale " <> show scale <> ": " <> show (nRect p) | scale > 0, any off [x, y, x + w, y + h]]+    -- Children lie inside the parent along each axis on which they fit: the+    -- children's sizes along a line plus its gaps, or else their extent,+    -- plus padding, are at most the parent's size. A grid child also has+    -- to fit its column: one wider overhangs its cell as its alignment+    -- says, which may cross the grid's edge.+    contained i p kids+      | null kids = []+      | otherwise =+          let Rect px py pw ph = nRect p+              Padding pl pr pt pb = nPad p+              rects = map (nRect . snd) kids+              gaps = nGap p * fromIntegral (length kids - 1)+              extent lo hi = maximum (map hi rects) - minimum (map lo rects)+              needW+                | nLine p && nRow p = sum (map rectW rects) + gaps+                | nLine p = maximum (map rectW rects)+                | otherwise = extent rectX (\r -> rectX r + rectW r)+              needH+                | nLine p && not (nRow p) = sum (map rectH rects) + gaps+                | nLine p = maximum (map rectH rects)+                | otherwise = extent rectY (\r -> rectY r + rectH r)+              fitsW = needW + pl + pr <= pw + eps+              fitsH = needH + pt + pb <= ph + eps+              colW = (pw - pl - pr - nGap p * fromIntegral (nCols p - 1)) / fromIntegral (nCols p)+              inCell (Rect _ _ w _) = nCols p <= 0 || w <= colW + eps+              outW r@(Rect x _ w _) = inCell r && (x < px - eps || x + w > px + pw + eps)+              outH (Rect _ y _ h) = y < py - eps || y + h > py + ph + eps+           in [ "child " <> show c <> " " <> show (nRect k) <> " outside parent " <> show i <> " " <> show (nRect p)+              | (c, k) <- kids+              , (fitsW && outW (nRect k)) || (fitsH && outH (nRect k))+              ]+    -- In a row or column that fits, each child starts at or after the end+    -- of the one declared before it.+    lined i p kids+      | not (nLine p) = []+      | otherwise =+          let lo r = if nRow p then rectX r else rectY r+              len r = if nRow p then rectW r else rectH r+              rects = map (nRect . snd) kids+              Padding pl pr pt pb = nPad p+              room = (if nRow p then rectW (nRect p) - pl - pr else rectH (nRect p) - pt - pb) - nGap p * fromIntegral (length kids - 1)+           in [ "siblings overlap in " <> show i <> ": " <> show a <> " then " <> show b+              | sum (map len rects) <= room + eps+              , (a, b) <- zip rects (drop 1 rects)+              , lo b < lo a + len a - eps+              ]+    -- Grow children without a maximum take the leftover space by factor,+    -- none below its content size. A grow spacer's content is 8 px, so a+    -- spacer longer than that takes exactly its factor's share, no more per+    -- unit of factor than any other grow child; a spacer near 8 px had a+    -- share no larger. Each snapped length is within a pixel of the exact+    -- one, so two shares per unit of factor differ by at most @1 / f + 1 /+    -- g@. With room to spare, the grow children fill it, to within a pixel+    -- per child and one for the parent: padding need not be whole device+    -- pixels, so each edge rounds on its own.+    grown i p kids+      | not (nLine p) = []+      | otherwise =+          let len r = if nRow p then rectW r else rectH r+              isGrow k = axTag (nMain k) == SizingGrow && axVal (nMain k) > 0+              growing = [(k, axVal (nMain k)) | (_, k) <- kids, isGrow k]+              others = [len (nRect k) | (_, k) <- kids, not (isGrow k)]+              Padding pl pr pt pb = nPad p+              inner = if nRow p then rectW (nRect p) - pl - pr else rectH (nRect p) - pt - pb+              leftover = inner - sum others - nGap p * fromIntegral (length kids - 1)+              perUnit (k, f) = len (nRect k) / f+              spacers = [a | a@(k, _) <- growing, nType k == NodeSpacer]+              unlocked = [a | a@(k, _) <- spacers, len (nRect k) > spacerContent + tol]+              locked = [a | a@(k, _) <- spacers, len (nRect k) <= spacerContent + tol]+              tol = 1 + eps+              share a b = "grow spacer in " <> show i <> " has " <> show (perUnit a) <> " per unit of factor, another grow child " <> show (perUnit b)+           in if null growing || any ((< 1e8) . axMax . nMain . fst) growing || leftover <= tol+                then []+                else+                  [share a b | a@(_, f) <- unlocked, b@(_, g) <- growing, perUnit a > perUnit b + 1 / f + 1 / g + eps]+                    <> [share a b | a@(_, f) <- unlocked, b@(_, g) <- unlocked, perUnit a < perUnit b - 1 / f - 1 / g - eps]+                    <> [share a b | a@(k, f) <- locked, b@(_, g) <- unlocked, f * perUnit b > len (nRect k) + tol + f / g]+                    <> [ "grow children of " <> show i <> " take " <> show taken <> " of leftover " <> show leftover+                       | let taken = sum [len (nRect k) | (k, _) <- growing]+                       , abs (taken - leftover) > tol * fromIntegral (length kids + 1)+                       ]+    spacerContent = 8++-- | The scene's nodes after it settles at snap scale @s@.+sceneNodes :: Float -> Scene -> IO [(Int, Node)]+sceneNodes s (Scene w h root) = do+  ctx <- (`withFontMetrics` (monospaceMetrics 12) {fmSnapScale = s}) <$> newContext+  quiet <- newIORef 0+  Sim.runSim ctx quiet (withInput w h) (columnWith (fillW . fillH) (renderBox AxisCol root)) (pure ())+  readNodes ctx++-- | Lay a scene out at each snap scale and check every property.+layoutProperties :: Scene -> Property+layoutProperties scene = ioProperty $ do+  found <- forM [1, 1.25, 1.5, 1.75] $ \s -> violations s <$> sceneNodes s scene+  let problems = concat found+  pure (counterexample (unlines (take 12 problems)) (null problems))
+ test/integration/Cases/LayoutReuse.hs view
@@ -0,0 +1,197 @@+{-# OPTIONS_GHC -O0 #-}+-- | A solve that puts back what the last one placed lays out as solving+-- from scratch does.+module Cases.LayoutReuse (tests) where++import Spec+import Data.Bits (shiftR, xor)+import Data.Text qualified as T+import Data.Word (Word64)+import NanoUI.Adornment (affix, leading, trailing)+import NanoUI.Testing.Sim (Sim, checkEq, settle, writeV)++tests :: [Spec]+tests =+  [ spec "position-reuse" runPositionReuseTest+  , varSimSpec "reuse-rechecks-placed-measure" 300 200 "abcdefg hi j" placedMeasureUi placedMeasure+  ]++-- | A measured drawing whose measure gives the same size at the offered+-- width but a different height at the width it is placed at must not keep+-- the cached height. Both texts are one 120 px line unwrapped; at 70 px the+-- first wraps to two lines and the second to three.+placedMeasureUi :: Var T.Text -> NanoUI Rect+placedMeasureUi ref = columnWith (fixedW 70 . gap 0 . \l -> l {layoutPadding = Padding 0 0 0 0}) $ do+  txt <- readVar ref+  respRect . fst <$> customWidget defaultCustomWidgetSpec+    { widgetMeasure = Just (\_ (w, _) -> (min w (charW * fromIntegral (T.length txt)), lineH * fromIntegral (linesAt w txt)))+    , widgetLayout = fillW+    }++placedMeasure :: Var T.Text -> Sim Rect ()+placedMeasure ref = do+  checkEq (2 * lineH) . rectH =<< settle+  writeV ref "abc defghi j"+  checkEq (3 * lineH) . rectH =<< settle++charW, lineH :: Float+charW = 10+lineH = 14++-- | Greedy word wrap of @t@ at width @w@ with 'charW' per character: the+-- line count, or 1 when @w@ is unbounded.+linesAt :: Float -> T.Text -> Int+linesAt w t+  | w >= 1.0e8 = 1+  | otherwise = go (0 :: Float) 1 (T.words t)+  where+    go _ n [] = n+    go cur n (x : xs)+      | cur == 0 = go (len x) n xs+      | cur + charW + len x <= w = go (cur + charW + len x) n xs+      | otherwise = go (len x) (n + 1) xs+    len x = charW * fromIntegral (T.length x)++-- | Run each frame on a context that keeps its layout cache and on one that+-- solves every frame from scratch, and check they lay out the same.+sameAsFullSolves :: IORef Int -> [(Input, NanoUI ())] -> IO ()+sameAsFullSolves failed frames = do+  reusing <- newContext+  fresh <- newContext+  forM_ frames $ \(inp, ui) -> sameAsFreshSolve failed fresh reusing inp ui++-- | A ticking label beside rows that stay put, a label that gains and loses+-- a line so everything below it moves, a window that resizes, and a label+-- whose container narrows. Then+-- randomised trees of every container kind, with texts that change at+-- different rates and a window that resizes now and then.+runPositionReuseTest :: Context -> IORef Int -> IO ()+runPositionReuseTest _ failed = do+  let inp = withInput 640 400+      rows = forM_ [1 .. 30 :: Int] $ \i -> row $ do+        label (T.pack ("row " <> show i))+        void (button "b")+        labelWith fillW (T.replicate (i `mod` 5) "wrapping words ")+      ticking f = column $ do+        label (T.pack ("tick " <> show f))+        rows+      shifting f = column $ do+        label (if even f then "one line" else "two\nlines")+        void (scroll rows)+  sameAsFullSolves failed [(inp, ticking f) | f <- [0 .. 5 :: Int]]+  sameAsFullSolves failed [(inp, shifting f) | f <- [0 .. 5 :: Int]]+  sameAsFullSolves failed [(withInput w 400, ticking (0 :: Int)) | w <- [640, 640, 500, 500, 640]]+  -- A wrapping label measures again when only its container's width changes.+  let long = "a long label that wraps onto several lines at a narrow width"+  sameAsFullSolves failed [(inp, columnWith (fixedWH w 200) (label long)) | w <- [360, 120]]+  forM_ [1 .. 16 :: Word64] $ \seed -> do+    let t = gen (mix seed) 0+        size f = if (f `div` 13) `mod` 2 == 0 then withInput 900 700 else withInput 640 700+    sameAsFullSolves failed [(size f, columnWith (fillW . fillH) (render f False t)) | f <- [0 .. 29]]++data Kind = KCol | KRow | KGrid Int | KScroll | KScroll2D | KLayers | KWrapRow | KWrapCol | KWindow++data Leaf = LLabel | LLabelFill | LLabelLines | LButton | LButtonAdorned | LSpacer | LSep | LCheck | LMeasured++data Tree = Node Kind Word64 [Tree] | Leaf Leaf Word64++mix :: Word64 -> Word64+mix z0 =+  let z1 = (z0 `xor` (z0 `shiftR` 30)) * 0xbf58476d1ce4e5b9+      z2 = (z1 `xor` (z1 `shiftR` 27)) * 0x94d049bb133111eb+   in z2 `xor` (z2 `shiftR` 31)++hash2 :: Word64 -> Word64 -> Word64+hash2 a b = mix (a * 0x9e3779b97f4a7c15 + b)++pick :: Word64 -> Int -> Int+pick h n = fromIntegral (h `mod` fromIntegral n)++gen :: Word64 -> Int -> Tree+gen h depth+  | depth >= 4 || (depth > 1 && pick (hash2 h 1) 4 == 0) =+      Leaf ([LLabel, LLabelFill, LLabelLines, LButton, LButtonAdorned, LSpacer, LSep, LCheck, LMeasured] !! pick (hash2 h 6) 9) (hash2 h 7)+  | otherwise =+      let kind = case pick (hash2 h 2) 20 of+            0 -> KGrid (1 + pick (hash2 h 3) 4)+            1 -> KScroll+            2 -> KScroll2D+            3 -> KLayers+            4 -> KWrapRow+            5 -> KWrapCol+            6 | depth > 0 -> KWindow+            n | n < 13 -> KCol+            _ -> KRow+          kids = 1 + pick (hash2 h 4) (if depth == 0 then 8 else 5)+       in Node kind (hash2 h 5) [gen (hash2 h (100 + fromIntegral i)) (depth + 1) | i <- [1 .. kids]]++containerMods :: Word64 -> Bool -> Layout -> Layout+containerMods m inLayers =+  let f i = pick (hash2 m i)+      width = case f 1 10 of+        0 -> fillW+        1 -> \l -> l {layoutWidth = Percent (fromIntegral (30 + f 2 60))}+        2 -> \l -> l {layoutWidth = Fixed (fromIntegral (80 + f 3 300))}+        3 -> \l -> l {layoutWidth = Shrink 1}+        4 -> \l -> l {layoutWidth = Grow 2}+        _ -> id+      height = case f 4 10 of+        0 -> fillH+        1 -> \l -> l {layoutHeight = Fixed (fromIntegral (40 + f 5 200))}+        _ -> id+      spaced = if f 6 3 == 0 then gap (fromIntegral (f 7 12)) else id+      packed = if f 8 2 == 0 then tight else id+      lo = if f 9 6 == 0 then minW (fromIntegral (20 + f 10 100)) else id+      hi = if f 11 6 == 0 then maxW (fromIntegral (100 + f 12 300)) else id+      aligned = case f 13 8 of+        0 -> alignMiddle+        1 -> alignEnd+        2 -> alignBaseline+        _ -> id+      pinned = if not inLayers && f 14 12 == 0 then pinAt (fromIntegral (f 15 20)) (fromIntegral (f 16 20)) else id+      ratio = if f 17 25 == 0 then aspect 1.5 else id+      padded = if f 18 5 == 0 then padAll (fromIntegral (f 19 10)) else id+   in padded . ratio . pinned . aligned . hi . lo . packed . spaced . height . width++-- | Leaf @i@'s content version at frame @f@: it changes every frame, every+-- third, every seventh, or never.+version :: Word64 -> Int -> Word64+version i f = hash2 i (fromIntegral (f `div` ([1, 3, 7, 1000] !! pick (hash2 i 1) 4)))++words' :: Word64 -> Bool -> T.Text+words' v lines' =+  let n = 1 + pick v 12+      ws = [["alpha", "be", "gamma", "d", "epsilonic"] !! pick (hash2 v (fromIntegral j)) 5 | j <- [1 .. n]]+   in T.intercalate (if lines' && pick v 3 == 0 then "\n" else " ") ws++render :: Int -> Bool -> Tree -> NanoUI ()+render f inLayers = \case+  Node kind m kids -> do+    let mods = containerMods m inLayers+        body inner = mapM_ (render f inner) kids+    case kind of+      KCol -> columnWith mods (body False)+      KRow -> rowWith mods (body False)+      KGrid n -> gridWith n mods (body False)+      KScroll -> scrollWith mods (body False)+      KScroll2D -> scroll2DWith mods (body False)+      KLayers -> layersWith mods (body True)+      KWrapRow -> rowWith (wrap . mods) (body False)+      KWrapCol -> columnWith (wrap . mods) (body False)+      KWindow -> void (floatingWindow' (constVar True) (T.pack ("W" <> show (m `mod` 1000))) (columnWith mods (body False)))+  Leaf kind i -> do+    let v = version i f+    case kind of+      LLabel -> label (words' v False)+      LLabelFill -> labelWith (fillW . maxW (fromIntegral (120 + pick v 200))) (words' v False)+      LLabelLines -> labelWith fillW (words' v True)+      LButton -> void (button (words' v False))+      LButtonAdorned -> void (buttonConfigured defaultButtonConfig {bcAdornments = leading (affix "$") <> trailing (affix (T.pack (show (pick v 1000))))} (words' v False))+      LSpacer -> spacer (Fixed (fromIntegral (5 + pick v 60))) (Fixed (fromIntegral (5 + pick (hash2 v 9) 30)))+      LSep -> separator+      LCheck -> void ((snd <$> withValue (pick v 2 == 0) (checkbox (words' v False))))+      LMeasured ->+        void $ customWidget defaultCustomWidgetSpec+          { widgetMeasure = Just (\_ (w, _) -> (min w 90, fromIntegral (12 + pick v 20)))+          , widgetLayout = fillW+          }
test/integration/Cases/Modal.hs view
@@ -1,208 +1,212 @@-module Cases.Modal-  ( runModalCloseDamageTest-  , runModalNoPhantomScrollTest-  , runModalOverlayTest-  , runModalFitsTextTest-  , runModalFractionalScaleNoScrollTest-  , runModalFillLabelFitsTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Modal (tests) where -import Control.Monad (forM_, when)-import Data.IORef (IORef)+import Spec+import Data.Maybe (isJust, listToMaybe) import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt, evalUi, withInput)-import NanoUI.Testing.Harness-  ( centerOf-  , checkIdleFullDamage-  , clickPair-  , keyInp-  , runClick-  , spanYOf-  , warmup2-  , withInputOff-  )+import NanoUI.Internal.Context (setDrawSquareGeometry)+import NanoUI.Testing.Sim -runModalOverlayTest :: Context -> IORef Int -> IO ()-runModalOverlayTest ctx failed = do-  let-    inp0 = withInput 320 200-    ui = column $ do-      outside <- button' "Outside"-      (dlg, mInside) <- modal True "Title" (button' "Inside")-      pure (outside, dlg, mInside)-    closedUi = column $ do-      _ <- button "Outside"-      (dlg, mInside) <- modal False "Title" (button' "Inside")-      pure (dlg, mInside)+tests :: [Spec]+tests =+  [ simSpec "modal-constant" 800 200 constantUi modalConstant+  , spec "modal-var" runModalVarTest+  , spec "modal-nested-dismiss" runModalNestedDismissTest+  , simSpec "modal-over-inner-window" 500 400 innerWindowUi modalOverInnerWindow+  , spec "modal-fractional-scale-no-scroll" runModalFractionalScaleNoScrollTest+  , spec "modal-snaps-to-device-pixels" runModalSnapsTest+  , spec "modal-fill-label-fits" runModalFillLabelFitsTest+  , spec "modal-tree-selection" runModalTreeSelectionTest+  ] -  (dlgClosed, mInsideClosed) <- evalUi ctx inp0 closedUi-  assert failed (not (respClicked dlgClosed))-  assert failed (case mInsideClosed of Nothing -> True; _ -> False)-  closedSpans <- collectOverlayTextSpans ctx inp0-  assert failed (not (any (\(_, txt, _, _, _) -> "Title" `T.isInfixOf` txt) closedSpans))+-- | Whether the frame's Escape went to an overlay rather than quitting.+escapeTaken :: Sim a Bool+escapeTaken = onContext (`overlayConsumesQuit` keyInp KeyEscape emptyInput) -  (_, _, mInside0) <- warmup2 ctx inp0 ui-  overlays <- collectOverlayTextSpans ctx inp0-  assert failed (any (\(_, txt, _, _, _) -> "Title" `T.isInfixOf` txt) overlays)-  assert failed (any (\(_, txt, _, _, _) -> "Inside" `T.isInfixOf` txt) overlays)-  assert failed (not (any (\(_, txt, _, _, _) -> T.strip txt == "X") overlays))+sentence :: T.Text+sentence = "A sentence that is wider than the smallest modal allows." -  case mInside0 of-    Nothing -> assert failed False-    Just inside -> do-      let (pressIn, releaseIn) = clickPair inp0 (centerOf inside)-      _ <- runFrame ctx pressIn ui-      ((_, _, mClicked), _, _, _) <- runFrame ctx releaseIn ui-      assert failed (maybe False respClicked mClicked)+constantUi :: NanoUI (Response, Maybe Response)+constantUi = column $ do+  _ <- button "Outside"+  modal' (constVar True) "Title" $ do+    r <- button' "Inside"+    muted sentence+    r <$ forM_ [1 .. 40 :: Int] (\i -> label (T.pack ("Row " <> show i))) -      let (backdrop, _) = clickPair inp0 (V2 4 4)-      ((_, dlgHit, _), _, _, _) <- runFrame ctx backdrop ui-      assert failed (respClicked dlgHit)+-- | A modal on a constant fits the window but widens for a label, has no+-- close button, and reports a press beside it and Escape while staying open.+modalConstant :: Sim (Response, Maybe Response) ()+modalConstant = do+  (dlg, _) <- result+  check (rectH (respRect dlg) <= 200)+  whole <- (\ss -> [r | (r, t, _, _, _) <- ss, t == sentence]) <$> spans+  checkEq [True] (map ((< rectW (respRect dlg) + 0.5) . rectW) whole)+  checkEq Nothing =<< findSpan "X"+  check . maybe False respClicked . snd =<< click "Inside"+  check . respClicked . fst =<< press (At (V2 4 4))+  _ <- release+  check . respClicked . fst =<< pressKey KeyEscape+  check =<< escapeTaken+  expect "Title" -      let esc = keyInp KeyEscape inp0-      ((_, dlgEsc, _), _, _, _) <- runFrame ctx esc ui-      assert failed (respClicked dlgEsc)-      consumed <- overlayConsumesQuit ctx esc-      assert failed consumed-      _ <- runFrame ctx esc closedUi-      leftover <- overlayConsumesQuit ctx esc-      assert failed (not leftover)+-- | A modal on a Var closes itself (the Escape frame already draws it closed),+-- and opening and closing each repaint the whole window once.+runModalVarTest :: Context -> IORef Int -> IO ()+runModalVarTest ctx failed = do+  open <- newVar False+  let ui = column $ do+        whenM (button "Open") (writeVar open True)+        modal open "Title" (whenM (button "Close") (writeVar open False))+      damage = frameDamage+  runSim ctx failed (withInputOff 320 240) ui $ do+    _ <- pressKey KeyEscape+    checkEq False =<< escapeTaken+    _ <- click "Open"+    expect "Title"+    _ <- click "Close"+    checkEq False =<< readV open+    _ <- damage >> click "Open"+    checkEq DamageFull =<< damage+    -- The idle frame after settles the button's release, as a clip.+    check . (\d -> d /= DamageFull && not (damageIsEmpty d)) =<< (advance 1 >> damage)+    _ <- pressKey KeyEscape+    checkEq False =<< readV open+    checkEq 2 =<< onContext lastFramePasses+    check =<< escapeTaken+    expectNot "Title"+    checkEq DamageFull =<< damage+    -- The second pass no longer built it, so the next frame repaints no more.+    _ <- frame+    check . (/= DamageFull) =<< damage -  let tallUi = modal True "Tall" $ do-        forM_ [1 .. 40 :: Int] (\i -> label (T.pack ("Row " <> show i)))-        button "Close"-  (dlgTall, _) <- warmup2 ctx inp0 tallUi-  assert failed (rectH (respRect dlgTall) <= 200)+-- | A newly opened modal closes the edit menu it hides, and a modal declared in+-- another's body closes first, on Escape or a click on the outer one.+runModalNestedDismissTest :: Context -> IORef Int -> IO ()+runModalNestedDismissTest ctx failed = do+  outer <- newVar False+  inner <- newVar True+  let ui = column $ do+        field <- fst <$> withValue "text" textInput'+        (dlg, _) <- modal' outer "Settings" $ do+          forM_ [1 .. 10 :: Int] (\i -> label (T.pack ("Setting " <> show i)))+          modal inner "Confirm" (label "confirm body")+        pure (field, dlg)+      states = (,) <$> readV outer <*> readV inner+  runSim ctx failed (withInput 640 480) ui $ do+    _ <- rightClick . On . fst =<< result+    expect "Paste"+    _ <- writeV outer True >> settle+    _ <- pressKey KeyEscape+    checkEq (True, False) =<< states+    Rect dx dy dw _ <- respRect . snd <$> (writeV inner True >> settle)+    _ <- click (At (V2 (dx + dw / 2) (dy + 8)))+    checkEq (True, False) =<< states -runModalNoPhantomScrollTest :: Context -> IORef Int -> IO ()-runModalNoPhantomScrollTest ctx failed = do-  let inp0 = withInput 400 300-      ui = modal True "About" $ do-        _ <- label "Immediate-mode GUI for Haskell."-        rowWith fillW $ do-          _ <- spacer (Grow 1) Fit-          _ <- button "Close"-          pure ()-  (dlg, _) <- warmup2 ctx inp0 ui-  let Rect _ _ mw mh = respRect dlg-  assert failed (mw > 0 && mh > 0)-  off0 <- getScrollOffset ctx (respId dlg)-  let wheel = inp0 {inputMousePos = centerOf dlg, inputScroll = V2 0 1}-  _ <- runFrame ctx wheel ui-  off1 <- getScrollOffset ctx (respId dlg)-  assertEq failed off0 0-  assertEq failed off1 0+innerWindowUi :: NanoUI (Maybe (Response, Maybe Response))+innerWindowUi = fmap snd . modalWith' (fixedWH 460 380) (constVar True) "Settings" $ do+  (_, hidden) <- floatingWindow' (constVar True) "Inspector" (buttonWith' (fixedWH 420 200) "Hidden")+  ok <- button' "OK"+  pure (ok, hidden) --- Opening and closing a modal each repaint the whole window on the next idle--- frame.-runModalCloseDamageTest :: Context -> IORef Int -> IO ()-runModalCloseDamageTest ctx failed = do-  let ui = do-        (open, setOpen) <- useFlag False-        resp <- button' "Open"-        when (respClicked resp) (setOpen True)-        (dlg, _) <- modal open "Title" (label "body")-        when (respClicked dlg) (setOpen False)-        pure resp-      inp0 = withInputOff 320 240-      esc = keyInp KeyEscape inp0-      idle = inp0 {inputDeltaTime = 1}-  _ <- runFrame ctx inp0 ui-  (resp, _, _, _) <- runFrame ctx inp0 ui-  _ <- runClick ctx inp0 ui (centerOf resp)-  checkIdleFullDamage failed ctx idle idle ui-  _ <- runFrame ctx esc ui-  checkIdleFullDamage failed ctx idle idle ui+-- | Where the modal panel covers a window in its body, clicks, title-bar drags+-- and edge drags (and the resize cursor) go to the modal, not the window.+modalOverInnerWindow :: Sim (Maybe (Response, Maybe Response)) ()+modalOverInnerWindow = do+  Just (ok, Just hidden) <- result+  check (isJust (rectIntersect (respRect hidden) (respRect ok)))+  checkEq (Just (True, False)) . fmap (\(o, h) -> (respClicked o, any respClicked h)) =<< click (On ok)+  let windows = map snd <$> onContext (nodesOfType NodeWindow)+  before@[Rect x y w h] <- windows+  _ <- drag (At (V2 (x + w / 2) (y + 10))) (At (V2 (x + w / 2 - 40) (y + 40))) 1+  checkEq before =<< windows+  let edge = V2 (x + 3) (y + h / 2)+  check . (/= UiCursorEwResize) =<< cursorAt (At edge)+  _ <- drag (At edge) (At (V2 (x - 37) (y + h / 2))) 1+  checkEq before =<< windows --- At a fractional display scale, a modal sized to its content does not scroll--- when that content uses fixed sizes off the device-pixel grid (regression:--- the solve rounded the measured sizes inside the modal before placement laid--- it out from them, and snapping a child's origin pushed its bottom below its--- measured bottom so content-sized parents grew level after level; the body--- overflowed its viewport by more than the scroll tolerance).+-- At fractional display scales, fixed-size content must fit a content-sized+-- modal without accumulating rounding error through nested containers. runModalFractionalScaleNoScrollTest :: Context -> IORef Int -> IO ()-runModalFractionalScaleNoScrollTest _ failed =-  forM_ [(scale, rows, nested) | scale <- [1, 1.25, 1.5, 1.75], rows <- [4 .. 8 :: Int], nested <- [False, True]] $ \(scale, rows, nested) -> do-    base <- newContext-    let ctx = withFontMetrics base ((monospaceMetrics 12) {fmSnapScale = scale})-        inp = withInputOff 1000 1000-        field i = rowWith (fillW . fixedH 30 . alignMid) (label (T.pack ("Field " <> show i)))-        section = columnWith (fillW . gap 6) $ do-          label "Section"-          columnWith (fillW . gap 0) $ do-            spacer Fit (Fixed 3)-            forM_ [1 .. rows] field-            spacer Fit (Fixed 3)-        body = columnWith (gap 10) (section >> section >> section >> button "Close")-        -- As the arena's root, and inside other content as an app opens one.-        ui-          | nested = column (label "Behind" >> fst <$> modal True "Details" body)-          | otherwise = fst <$> modal True "Details" body-        -- Whether a wheel over the modal moves its first field.-        scrolls c i = do-          dlg <- warmup2 c i ui-          let wheel = i {inputMousePos = centerOf dlg, inputScroll = V2 0 3}-          spans0 <- collectOverlayTextSpans c i-          _ <- runFrame c wheel ui-          spans1 <- collectOverlayTextSpans c wheel-          assert failed (not (null (spanYOf "Field 1" spans0)))-          pure (spanYOf "Field 1" spans1 /= spanYOf "Field 1" spans0)-    fits <- scrolls ctx inp-    assertEq failed fits False-    -- The same body in a short window does scroll, so the check can fail.-    short <- newContext-    clipped <- scrolls (withFontMetrics short ((monospaceMetrics 12) {fmSnapScale = scale})) (withInputOff 1000 300)-    assertEq failed clipped True+runModalFractionalScaleNoScrollTest _ failed = forM_ cases $ \(s, n, nested) -> do+  let field i = rowWith (fillW . fixedH 30 . alignMiddle) (label (T.pack ("Field " <> show i)))+      section = columnWith (fillW . gap 6) $ do+        label "Section"+        columnWith (fillW . gap 0) (spacer Fit (Fixed 3) >> forM_ [1 .. n] field >> spacer Fit (Fixed 3))+      body = columnWith (gap 10) (section >> section >> section >> button "Close")+      dialog = fst <$> modal' (constVar True) "Details" body+      -- As the arena's root, and inside other content as an app opens one.+      ui = if nested then column (label "Behind" >> dialog) else dialog+      scrolls winH = do+        ctx <- (`withFontMetrics` (monospaceMetrics 12) {fmSnapScale = s}) <$> newContext+        runSim ctx failed (withInputOff 1000 winH) ui $ do+          y0 <- rectOf "Field 1"+          dlg <- result+          _ <- wheel (On dlg) (V2 0 3)+          (/= Just (rectY y0)) . fmap rectY <$> findSpan "Field 1"+  assertEq failed False =<< scrolls 1000+  -- The same body in a short window does scroll, so the check can fail.+  assertEq failed True =<< scrolls 300+  where+    cases = [(s, n, nested) | s <- [1, 1.25, 1.5, 1.75], n <- [4 .. 8 :: Int], nested <- [False, True]] --- A modal widens for a filling label instead of wrapping it, so the label--- stays one line inside the modal (regression: the label reported no width, the--- modal stayed at its minimum, and the wrapped body overflowed into a scroll).-runModalFitsTextTest :: Context -> IORef Int -> IO ()-runModalFitsTextTest ctx failed = do-  let inp = withInput 800 600-      sentence = T.pack "A sentence that is wider than the smallest modal allows."-      ui = fst <$> modal True "About" (muted sentence)-  dlg <- warmup2 ctx inp ui-  spans <- collectOverlayTextSpans ctx inp-  let Rect _ _ dw _ = respRect dlg-      whole = [r | (r, t, _, _, _) <- spans, t == sentence]-  assertEq failed (length whole) 1-  forM_ whole $ \(Rect _ _ tw _) -> assertGt failed (dw + 0.5) tw+-- | A modal's content lands on the device pixel grid at fractional scales,+-- as the page's does: grow shares of an odd width split into cells whose+-- edges are whole device pixels and meet with no column left between them.+runModalSnapsTest :: Context -> IORef Int -> IO ()+runModalSnapsTest _ failed = forM_ [1.25, 1.5, 1.75] $ \s -> do+  ctx <- (`withFontMetrics` (monospaceMetrics 12) {fmSnapScale = s}) <$> newContext+  let cell t = respRect <$> buttonWith' (fillW . minW 0) t+      body = rowWith (fixedW 301.3 . gap 0) (sequence [cell "a", cell "b", cell "c"])+      onGridAt v = abs (v * s - fromIntegral (round (v * s) :: Int)) < 1.0e-3+  runSim ctx failed (withInput 1000 600) (snd <$> modal' (constVar True) "Cells" body) $ do+    mRects <- result+    case mRects of+      Nothing -> check False+      Just rects -> do+        forM_ rects $ \(Rect x y w h) -> check (all onGridAt [x, y, x + w, y + h])+        forM_ (zip rects (drop 1 rects)) $ \(Rect x _ w _, Rect x' _ _ _) -> check (abs (x + w - x') < 1.0e-3) --- A modal fits a body with a filling label set in a smaller font than the--- base, with its last row in view (regression: placing the modal measured--- every label in the base font, so the smaller label, sized for its own font,--- wrapped onto a second line the modal had not measured; the modal scrolled--- and clipped its buttons).+-- | A modal measures each label in its requested font size and keeps the last+-- row visible when the measured body fits. runModalFillLabelFitsTest :: Context -> IORef Int -> IO () runModalFillLabelFitsTest _ failed = forM_ [12, 17] $ \base -> do   ctx <- (`withFontMetrics` monospaceMetrics base) <$> newContext-  -- Wide enough for the label on one line in its own font, but not in the-  -- base font.-  let inp = withInput 2000 800-      body =-        columnWith (gap 14 . minW 560 . \l -> l {layoutPadding = Padding 0 0 0 0}) $ do-          labelWith (tight . fillW) "How cabal should log in to Hackage for uploads:"-          _ <- radio ["cabal's config file (no login found in it)", "A username and password", "An API token"] (0 :: Int)-          labelWith (tight . fillW . fontSize 14) "Kept in memory for this session only. The password goes to cabal on its standard input."-          separator-          rowWith (fillW . gap 8 . alignMid . tight) $ do-            flex-            _ <- button "Cancel"-            button' "Use this login"-      ui = modal True "Hackage login" body-  (dlg, mOk) <- warmup2 ctx inp ui-  spans0 <- collectOverlayTextSpans ctx inp-  let wheel = inp {inputMousePos = centerOf dlg, inputScroll = V2 0 3}-  _ <- runFrame ctx wheel ui-  spans1 <- collectOverlayTextSpans ctx wheel-  assert failed (not (null (spanYOf "An API token" spans0)))-  assertEq failed (spanYOf "An API token" spans1) (spanYOf "An API token" spans0)-  case mOk of-    Nothing -> assert failed False-    Just ok -> do-      let Rect _ dy _ dh = respRect dlg-          Rect _ by _ bh = respRect ok-      assertGt failed (dy + dh + 0.5) (by + bh)+  -- Wide enough for the label on one line in its own font, not the base one.+  let body = columnWith (gap 14 . minW 560 . \l -> l {layoutPadding = Padding 0 0 0 0}) $ do+        labelWith (tight . fillW) "How cabal should log in to Hackage for uploads:"+        let logins = ["cabal's config file (no login found in it)", "A username and password", "An API token"]+        _ <- withValue (0 :: Int) (radio logins)+        labelWith (tight . fillW . fontSize 14) $+          "Kept in memory for this session only. The password goes to cabal on its standard input."+        separator+        ok <- rowWith (fillW . gap 8 . alignMiddle . tight) (flex >> button "Cancel" >> button' "Use this login")+        void (buttonWith' (\l -> l {layoutWidth = Percent 50}) "HalfFit")+        pure ok+  runSim ctx failed (withInput 2000 800) (modal' (constVar True) "Hackage login" body) $ do+    (dlg, mOk) <- result+    pctR <- rectOf "HalfFit"+    check (rectW pctR > 0 && rectW pctR < 1000)+    y0 <- rectY <$> rectOf "An API token"+    _ <- wheel (On dlg) (V2 0 3)+    checkEq y0 . rectY =<< rectOf "An API token"+    let bottom r = rectY (respRect r) + rectH (respRect r)+    checkJust mOk $ \ok -> checkGt (bottom dlg + 0.5) (bottom ok)++-- | A tree in a modal draws its selected row apart, as one on the page does.+runModalTreeSelectionTest :: Context -> IORef Int -> IO ()+runModalTreeSelectionTest ctx failed = do+  setDrawSquareGeometry ctx True+  let inp0 = withInput 320 200+      items = [TreeItem "alpha" [], TreeItem "beta" []]+      -- The last fill under a row's whole label is that row's background.+      rowFills sel = do+        (_, draw) <- warmupDraw ctx inp0 (modal' (constVar True) "Pick" (tree' "t" items (constVar sel)))+        quads <- drawQuads draw+        spans' <- collectOverlayTextSpans ctx inp0+        let under lbl = spanRectOf lbl spans' >>= \r -> listToMaybe [c | (q, c) <- reverse quads, covers q r]+        pure (under "alpha", under "beta")+  (alpha0, beta0) <- rowFills 0+  (alpha1, beta1) <- rowFills 1+  assert failed (isJust alpha0 && isJust beta0)+  assert failed (alpha0 /= alpha1 && beta0 /= beta1)
+ test/integration/Cases/NativeWindow.hs view
@@ -0,0 +1,415 @@+{-# OPTIONS_GHC -O0 #-}+{-# LANGUAGE TypeFamilies #-}+{-# OPTIONS_GHC -Wno-orphans #-}++module Cases.NativeWindow (tests) where++import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (IOException, try)+import Data.ByteString qualified as BS+import Data.Either (isLeft)+import Data.Maybe (fromJust, isJust, isNothing)+import Spec+import GHC.TypeLits (symbolSing)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Runner (LoopWindows (..))+import NanoUI.Runner.Windows+import NanoUI.Testing.Sim+import System.Timeout (timeout)++tests :: [Spec]+tests =+  [ spec "native-window-without-host" runWithoutHostTest+  , spec "native-window-screenshot-requests" runScreenshotRequestsTest+  , spec "native-window-screenshot-lifecycle" runScreenshotLifecycleTest+  , spec "native-window-setters" runSettersTest+  , spec "native-window-commands-and-state" runCommandsTest+  , spec "native-window-children" runChildrenTest+  , spec "native-window-runner" runWindowsRunnerTest+  ]++type instance BackendSession ('Custom "test") = Int++inp :: Input+inp = withInput 200 100++-- | Install a host for a window opened with @settings@, recording its calls newest first.++recordingHost :: WindowSettings -> Context -> IO (IORef [String])+recordingHost settings ctx = do+  calls <- newIORef []+  let note c = modifyIORef' calls (c :)+  installWindowHost ctx settings $+    defaultWindowHost+      { hostSetTitle = \t -> note ("title " ++ show t)+      , hostSetIcon = \img -> note ("icon " ++ show (rgbaWidth img))+      , hostSetMinSize = \s -> note ("min " ++ show s)+      , hostSetMaxSize = \s -> note ("max " ++ show s)+      , hostSetOpacity = \o -> note ("opacity " ++ show o)+      , hostSetMode = \m -> note ("mode " ++ show m)+      , hostMove = \x y -> note ("move " ++ show (x, y))+      , hostCenter = note "center"+      , hostResize = \s -> note ("resize " ++ show s)+      , hostMinimize = note "minimize"+      , hostMaximize = note "maximize"+      , hostRestore = note "restore"+      }+  pure calls++-- | A fresh context with a recording host for a default window.+recording :: IO (Context, IORef [String])+recording = newContext >>= \ctx -> (,) ctx <$> recordingHost defaultWindowSettings ctx++-- | What a view asks of the host in a frame, oldest first.+asked :: Context -> IORef [String] -> NanoUI a -> IO [String]+asked ctx calls v = warmup ctx inp v >> reverse <$> readIORef calls <* writeIORef calls []++solid :: Int -> Int -> RgbaPixels+solid w h = fromJust (rgbaPixels w h (BS.replicate (w * h * 4) 255))++-- | Whether the action threw an 'IOException'.+throws :: IO a -> IO Bool+throws action = isLeft <$> try @IOException action++-- | Pixels need 4 bytes a pixel and a positive size. Without a window, requests do+-- nothing, a screenshot is answered with nothing, and the state is the frame's. A+-- backend session value is found by its own singleton only, and leaves with the session.+runWithoutHostTest :: Context -> IORef Int -> IO ()+runWithoutHostTest ctx failed = do+  let bytes n = BS.replicate n 7+      sized = [(2, 3, 24), (2, 3, 23), (2, 3, 25), (0, 3, 0), (-2, -3, 24)]+  assertEq failed [True, False, False, False, False] [isJust (rgbaPixels w h (bytes n)) | (w, h, n) <- sized]+  assertEq failed Nothing (rgbaPixels (maxBound `div` 2 + 1) 4 BS.empty)+  answers <- newIORef []+  st <- evalUi ctx inp $ do+    requestScreenshot (\shot -> modifyIORef' answers (fmap screenshotScale shot :))+    setWindowTitle "title"+    setWindowIcon (solid 2 2)+    setWindowMinSize (Just (Size 10 10))+    setWindowMode Fullscreen+    moveWindow 5 6+    toggleMaximized+    quit+    askWindow+  assertEq failed [Nothing] =<< readIORef answers+  assertEq failed defaultWindowState {winSize = Size 200 100} st+  assertEq failed False =<< quitRequested ctx+  assertEq failed Nothing =<< join (evalUi ctx inp askScreenshot)+  assertEq failed noWindowCapabilities =<< warmup2 ctx inp askWindowCapabilities+  assert failed =<< requestWindowClose ctx+  let caps = allWindowCapabilities {wcMove = False}+  installWindowHost ctx defaultWindowSettings defaultWindowHost {hostCapabilities = caps}+  assertEq failed caps =<< warmup2 ctx inp askWindowCapabilities+  let here = SCustom (symbolSing @"test")+  separate <- newContext+  withBackendSession ctx here 7 $ do+    assertEq failed (Just 7) =<< warmup2 ctx {ctxHotId = ctxHotId ctx} inp (askBackendSession here)+    assert failed . isNothing =<< backendSession SSdl ctx+    assert failed . isNothing =<< backendSession (SCustom (symbolSing @"other")) ctx+    assert failed . isNothing =<< backendSession here separate+  assert failed . isNothing =<< backendSession here ctx++-- | Screenshots are answered once each after their frame, in order, from one capture+-- at the reported scale, requesting a frame; failures and throws still answer all.+runScreenshotRequestsTest :: Context -> IORef Int -> IO ()+runScreenshotRequestsTest ctx failed = do+  calls <- recordingHost defaultWindowSettings ctx+  reportWindowState ctx defaultWindowState {winScale = 2}+  answers <- newIORef ([] :: [(String, Maybe (Int, Float))])+  captures <- newIORef (0 :: Int)+  let capture = Just (solid 3 2) <$ modifyIORef' captures (+ 1)+      shot sh = (rgbaWidth (screenshotPixels sh), screenshotScale sh)+      ask names = warmup ctx inp . (label "shots" >>) . forM_ names $ \name ->+        requestScreenshot (\s -> modifyIORef' answers ((name, shot <$> s) :))+      expectNow as n = assertEq failed (as, n) =<< ((,) <$> readIORef answers <*> readIORef captures)+      two = [("second", Just (3, 2)), ("first", Just (3, 2))]+  ask []+  answerScreenshots ctx capture+  expectNow [] 0+  ask ["first", "second"]+  expectNow [] 0+  clearDirty ctx+  answerScreenshots ctx capture+  expectNow two 1+  assert failed =<< isDirty ctx+  answerScreenshots ctx capture+  expectNow two 1+  ask ["failed"]+  answerScreenshots ctx (pure Nothing)+  expectNow (("failed", Nothing) : two) 1+  ask ["replaced"]+  _ <- recordingHost defaultWindowSettings ctx+  expectNow (("replaced", Nothing) : ("failed", Nothing) : two) 1+  assertEq failed [] =<< readIORef calls+  done <- newIORef []+  let request action = evalUi ctx inp (requestScreenshot action)+      note s = modifyIORef' done (isJust s :)+      broken = ioError (userError "capture failed")+  request note >> request note+  assert failed =<< throws (answerScreenshots ctx broken)+  assertEq failed [False, False] =<< readIORef done+  writeIORef done []+  request (const broken) >> request note+  assert failed =<< throws (answerScreenshots ctx (pure (Just (solid 1 1))))+  assertEq failed [True] =<< readIORef done+  events <- newIORef ([] :: [String])+  request (\_ -> modifyIORef' events ("answer" :))+  let event e = modifyIORef' events (e :)+  answerScreenshotsAfter ctx (Nothing <$ event "capture") (event "present")+  assertEq failed ["answer", "present", "capture"] =<< readIORef events+  request (const broken) >> request note+  assert failed =<< throws (closeWindowHost ctx)+  assertEq failed [False, True] =<< readIORef done+  closeWindowHost ctx++-- | 'useScreenshot' waits in a task for the next frame on screen; a key captures once.+-- A screenshot requested from a click is requested once, though the click reruns the+-- view. Closing or replacing a window answers pending requests; a closed host is not+-- called.+runScreenshotLifecycleTest :: Context -> IORef Int -> IO ()+runScreenshotLifecycleTest base failed = do+  job <- newTask+  _ <- recordingHost defaultWindowSettings base+  woken <- newWakeSignal base+  captures <- newIORef (0 :: Int)+  let capture = Just (solid 4 4) <$ modifyIORef' captures (+ 1)+      ui = fmap (rgbaWidth . screenshotPixels) <$> useScreenshot job ("shot" :: String)+      answered = evalUi base inp ui <* answerScreenshots base capture+      go :: Int -> IO (Maybe Int)+      go n = answered >>= \s -> if isJust s || n == 0 then pure s else woken 2000000 >> go (n - 1)+  assertEq failed (Just 4) =<< go 20+  replicateM_ 3 answered+  assertEq failed 1 =<< readIORef captures+  cancelTasks base+  answers <- newIORef (0 :: Int)+  passes <- newIORef (0 :: Int)+  let view = do+        liftIO (modifyIORef' passes (+ 1))+        shotsVar <- useVar (0 :: Int)+        shots <- readVar shotsVar+        whenM (button "Shot") $+          requestScreenshot (\_ -> modifyIORef' answers (+ 1)) >> writeVar shotsVar (shots + 1)+  runSim base failed inp view $ do+    _ <- press "Shot"+    liftIO (writeIORef passes 0)+    _ <- release+    checkEq 2 =<< liftIO (readIORef passes)+  answerScreenshots base (pure (Just (solid 1 1)))+  assertEq failed 1 =<< readIORef answers+  ctx <- newContext+  _ <- recordingHost defaultWindowSettings ctx+  oldShoot <- evalUi ctx inp askScreenshot+  _ <- recordingHost defaultWindowSettings ctx+  assertEq failed (Just Nothing) =<< timeout 1000000 oldShoot+  wait <- newWakeSignal ctx+  shoot <- evalUi ctx inp askScreenshot+  answer <- newEmptyMVar+  _ <- forkIO (shoot >>= putMVar answer)+  _ <- wait 1000000+  closeWindowHost ctx+  assertEq failed (Just Nothing) =<< timeout 1000000 (takeMVar answer)+  assertEq failed (Just Nothing) =<< timeout 1000000 shoot+  closeWindowHost ctx+  calls <- recordingHost defaultWindowSettings ctx+  closeWindowHost ctx+  evalUi ctx inp (setWindowTitle "closed")+  assertEq failed [] =<< readIORef calls++-- | Installing a host applies the settings a window does not open with; setters then+-- reach it only on a change, retrying after a failure. A size limit set past the+-- other moves the other first, so the host never sees a minimum above the maximum.+runSettersTest :: Context -> IORef Int -> IO ()+runSettersTest ctx failed = do+  let sz w h = "Just (Size {sizeW = " ++ show (w :: Float) ++ ", sizeH = " ++ show (h :: Float) ++ "})"+      opened =+        defaultWindowSettings+          { wsTitle = "opened", wsMinSize = Just (Size 100 50), wsIcon = Just (solid 2 2), wsOpacity = 0.5+          , wsPosition = WindowPositionAt 30 20, wsMode = Fullscreen+          }+  calls <- recordingHost opened ctx+  assertEq failed ["min " ++ sz 100 50, "icon 2", "opacity 0.5", "move (30,20)"] . reverse =<< readIORef calls+  writeIORef calls []+  let unchanged = setWindowTitle "opened" >> setWindowMode Fullscreen >> setWindowOpacity 0.5+      centered = defaultWindowSettings {wsPosition = WindowPositionCentered}+  assertEq failed [] =<< asked ctx calls unchanged+  assertEq failed ["center"] =<< readIORef =<< recordingHost centered ctx+  assertEq failed [] =<< readIORef =<< recordingHost defaultWindowSettings ctx+  (c1, calls1) <- recording+  let view (title, icon, minSize, opacity, mode) = do+        setWindowTitle title+        setWindowIcon (solid icon icon)+        setWindowMinSize minSize+        setWindowMaxSize Nothing+        setWindowOpacity opacity+        setWindowMode mode+      first = ("a", 2, Just (Size 100 50), 0.5, Windowed)+  forM_+    [ (first, ["title \"a\"", "icon 2", "min " ++ sz 100 50, "opacity 0.5"])+    , (first, [])+    , (first, [])+    , (("a", 4, Just (Size 100 50), 7, Hidden), ["icon 4", "opacity 1.0", "mode Hidden"])+    , (("b", 4, Nothing, 1, Hidden), ["title \"b\"", "min Nothing"])+    ]+    $ \(v, want) -> assertEq failed want =<< asked c1 calls1 (view v)+  (c2, calls2) <- recording+  forM_+    [ (setWindowMaxSize (Just (Size 300 200)), ["max " ++ sz 300 200])+    , (setWindowMinSize (Just (Size 400 100)), ["max " ++ sz 400 200, "min " ++ sz 400 100])+    , (setWindowMaxSize (Just (Size 350 50)), ["min " ++ sz 350 50, "max " ++ sz 350 50])+    , (setWindowMinSize (Just (Size 0 80)), ["max " ++ sz 350 80, "min " ++ sz 0 80])+    , (setWindowMaxSize Nothing, ["max Nothing"])+    , (setWindowMinSize (Just (Size 500 500)), ["min " ++ sz 500 500])+    ]+    $ \(v, want) -> assertEq failed want =<< asked c2 calls2 v+  c3 <- newContext+  attempts <- newIORef (0 :: Int)+  installWindowHost c3 defaultWindowSettings defaultWindowHost+    { hostSetTitle = \_ -> do+        modifyIORef' attempts (+ 1)+        n <- readIORef attempts+        when (n == 1) (ioError (userError "native failure"))+    }+  assert failed =<< throws (evalUi c3 inp (setWindowTitle "retry"))+  replicateM_ 2 (evalUi c3 inp (setWindowTitle "retry"))+  assertEq failed 2 =<< readIORef attempts+  -- A native limit is scaled, rounded and outset; 0, NaN or infinity is none, and a+  -- huge one stops at Int32's top.+  forM_+    [ ((302, 0), sizeLimitAt 1.5 (2, 3) (Just (Size 200 (-1))))+    , ((0, 908), sizeLimitAt 1 (8, 8) (Just (Size (1 / 0) 900)))+    , ((0, 900), sizeLimitAt 1 (0, 0) (Just (Size (0 / 0) 900)))+    , ((0x7FFFFFFF, 0), sizeLimitAt 1 (8, 0) (Just (Size 3e9 0)))+    , ((0x7FFFFFFF, 0x7FFFFFFF), sizeLimitAt 2 (16, 39) (Just (Size 1e20 3.4e38)))+    ]+    $ uncurry (assertEq failed)++-- | Commands act on every call; toggling follows the reported state. A state change+-- wakes only a view that read it, and repaints one that paints it.+runCommandsTest :: Context -> IORef Int -> IO ()+runCommandsTest ctx failed = do+  calls <- recordingHost defaultWindowSettings ctx+  let commands = do+        moveWindow 5 6 >> centerWindow >> resizeWindow (Size 300 200)+        minimizeWindow >> maximizeWindow >> restoreWindow+  replicateM_ 2 $+    assertEq failed ["move (5,6)", "center", "resize " ++ show (Size 300 200), "minimize", "maximize", "restore"]+      =<< asked ctx calls commands+  assertEq failed ["maximize"] =<< asked ctx calls toggleMaximized+  reportWindowState ctx defaultWindowState {winMaximized = True}+  assertEq failed ["restore"] =<< asked ctx calls toggleMaximized+  (c, _) <- recording+  let reported =+        defaultWindowState+          {winSize = Size 9 9, winScale = 2, winPosition = Just (10, 20), winFocused = False, winFullscreen = True}+      changed st = clearDirty c >> reportWindowState c st >> isDirty c+      ui = do+        st <- askWindow+        label "focus"+        box (fixedWH 40 40) (if winFocused st then colorRGBA 0 255 0 255 else colorRGBA 128 128 128 255)+  assertEq failed False =<< changed reported+  assertEq failed reported {winSize = Size 200 100} =<< evalUi c inp askWindow+  assertEq failed False =<< changed reported+  replicateM_ 3 (runFrame c inp ui)+  assert failed . (/= DamageFull) =<< takeDamage c+  assertEq failed False =<< changed reported {winPosition = Just (99, 88)}+  assertEq failed (Just (99, 88)) . winPosition =<< evalUi c inp askWindow+  assertEq failed True =<< changed reported {winPosition = Just (99, 88), winFocused = True}+  _ <- runFrame c inp ui+  -- The box that shows focus repaints, not the window.+  assert failed . (\d -> d /= DamageFull && not (damageIsEmpty d)) =<< takeDamage c++-- | A view declares a further window while its 'Var' holds 'True', under the+-- same key each frame; the declared view runs on a context of its own. A+-- changing write counts as a change, an equal one does not.+runChildrenTest :: Context -> IORef Int -> IO ()+runChildrenTest ctx failed = do+  open <- newVar False+  ran <- newIORef (0 :: Int)+  let body = liftIO (modifyIORef' ran (+ 1))+      view = label "first" >> nativeWindow open defaultWindowSettings {wsTitle = "second"} body+      declared = runFrame ctx inp view >> childWindows ctx+  assertEq failed 0 . length =<< declared+  before <- varChangeCount+  writeVarIO open True+  afterOpen <- varChangeCount+  writeVarIO open True+  afterSame <- varChangeCount+  assertEq failed (True, afterOpen) (afterOpen > before, afterSame)+  first <- declared+  again <- declared+  assertEq failed [("second", True)] [(wsTitle (childSettings c), True) | c <- first]+  assertEq failed (map childKey first) (map childKey again)+  assertEq failed 0 =<< readIORef ran+  other <- newContext+  forM_ first $ \c -> runFrame other inp (childView c)+  assertEq failed 1 =<< readIORef ran+  assertEq failed 0 . length =<< childWindows other+  writeVarIO open False+  assertEq failed 0 . length =<< declared++-- | The session runner's further windows, with windows that are contexts:+-- a declaration opens one, whose view runs again when the declaring view+-- draws (it may close over that frame's values) but not on an idle pass. A+-- 'Var' it writes asks the first window for a frame. Its close request+-- writes 'False' and closes it.+runWindowsRunnerTest :: Context -> IORef Int -> IO ()+runWindowsRunnerTest ctx failed = do+  open <- newVar True+  shared <- newVar (0 :: Int)+  frames <- newIORef (0 :: Int)+  childSaw <- newIORef []+  closed <- newIORef []+  -- The size the host gives the window, its resize watch, whether the watch+  -- was removed, and each frame's size and full-repaint flag, newest first.+  hostSize <- newIORef Nothing+  watch <- newIORef (pure ())+  unwatched <- newIORef False+  childDraws <- newIORef []+  let ops =+        WindowOps+          { woOpen = \_ settings -> (,) (wsTitle settings) <$> newContext+          , woClose = \t -> modifyIORef' closed (t :)+          , woApplyEvent = const+          , woIsButtonEdge = const False+          , woIsClose = id+          , woSync = \_ c i -> (\s -> (c, maybe i (\sz -> i {inputWindowSize = sz}) s)) <$> readIORef hostSize+          , woDraw = \_ c v i force -> do+              modifyIORef' childDraws ((inputWindowSize i, force) :)+              (\(_, _, more) -> more) <$> runFrame c i v+          , woCursor = \_ _ _ -> pure ()+          , woPacingMs = const 16+          , woWatchResize = \_ act -> writeIORef unwatched False >> writeIORef watch act >> pure (writeIORef unwatched True)+          }+      firstFrame = do+        n <- liftIO (atomicModifyIORef' frames (\k -> (k + 1, k + 1)))+        nativeWindow open defaultWindowSettings {wsTitle = "second"} $ do+          liftIO (modifyIORef' childSaw (n :))+          when (n == 3) (writeVar shared 1)+  windows <- newWindows ops+  let lw = loopWindows windows+      mainFrame = runFrame ctx inp firstFrame <* lwDrew lw+      step = afterMainPass windows ctx+      settled = replicateM_ 4 step >> length <$> readIORef childSaw+  _ <- mainFrame+  opening <- settled+  assertEq failed (True, True) . (,) (opening >= 2) . all (== 1) =<< readIORef childSaw+  _ <- mainFrame+  step+  assertEq failed [2] . take 1 =<< readIORef childSaw+  quiet <- settled+  assertEq failed quiet =<< settled+  -- With the loop held (a modal size loop), the resize watch draws the+  -- window at its new size, repainting it whole.+  before <- length <$> readIORef childDraws+  writeIORef hostSize (Just (Size 300 200))+  join (readIORef watch)+  assertEq failed [(Size 300 200, True)] . (\ds -> take (length ds - before) ds) =<< readIORef childDraws+  assertEq failed False =<< lwFirstDue lw+  _ <- mainFrame+  step+  assertEq failed True =<< lwFirstDue lw+  [(_, queue)] <- openWindows windows+  queue True+  step+  assertEq failed (["second"], False, 0) =<< (,,) <$> readIORef closed <*> readVarIO open <*> (length <$> openWindows windows)+  assertEq failed True =<< readIORef unwatched
test/integration/Cases/NoThunks.hs view
@@ -1,58 +1,36 @@-module Cases.NoThunks (runNoThunksTest) where+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DerivingStrategies #-}+{-# OPTIONS_GHC -O0 -Wno-orphans #-}+module Cases.NoThunks (tests) where -import Data.IORef (IORef, readIORef)+import Spec import qualified Data.IntMap.Strict as IM-import NanoUI.Context (Context (..))-import NanoUI.Store (WidgetStore (..))+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Store (WidgetStore (..)) import NoThunks.Class (NoThunks, noThunks) -import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, withInput)+deriving anyclass instance NoThunks V2 --- | Long-lived widget state must not retain thunks in stored values. Run a--- frame whose widgets populate several store maps, then check every stored--- value directly with nothunks. (Container spines/lists are not checked:--- on GHC 9.14 nothunks flags WHNF list and IntMap internals as thunks, a--- false positive. Individual values (Text, Int, Float, Float pairs) are--- checked precisely, which catches the strict-container WHNF trap--- where a stored tuple's components remain unevaluated.)+tests :: [Spec]+tests = [spec "no-thunks" runNoThunksTest]++-- | Long-lived widget state keeps no thunks in its stored values, such as a+-- stored tuple's components (the strict-container WHNF trap). Values only:+-- on GHC 9.14 nothunks flags WHNF list and IntMap spines as thunks. runNoThunksTest :: Context -> IORef Int -> IO () runNoThunksTest ctx failed = do-  let inp = withInput 300 200-      ui = column $ do-        _ <- textInput "hello"-        _ <- slider 0 100 42-        pure ()-  _ <- runFrame ctx inp ui-  _ <- runFrame ctx inp ui+  _ <- warmup2 ctx (withInput 300 200) (column (withValue "hello" textInput >> withValue 42 (slider 0 100)))   store <- readIORef (ctxStore ctx)-  checkAll failed "storeText" (storeText store)-  checkAll failed "storeInt" (storeInt store)-  checkAll failed "storeFloat" (storeFloat store)-  checkAll failed "storeDouble" (storeDouble store)-  checkAll failed "storePoint" (storePoint store)+  checkAll "storeText" (storeText store)+  checkAll "storeInt" (storeInt store)+  checkAll "storeFloat" (storeFloat store)+  checkAll "storeDouble" (storeDouble store)+  checkAll "storePoint" (storePoint store)+  checkAll "storeQuiet" (storeQuiet store)   where-    checkAll ::-      NoThunks v => IORef Int -> String -> IM.IntMap v -> IO ()-    checkAll failed' what m =-      IM.foldlWithKey'-        (\acc !k !v -> acc >> checkOne failed' what k v)-        (pure ())-        m--    checkOne :: NoThunks v => IORef Int -> String -> Int -> v -> IO ()-    checkOne failed' what k v = do-      result <- noThunks [] v-      case result of-        Nothing -> pure ()-        Just info -> do-          putStrLn-            ( "thunks retained in "-                ++ what-                ++ " at key "-                ++ show k-                ++ ": "-                ++ show info-            )-          assert failed' False+    checkAll :: NoThunks v => String -> IM.IntMap v -> IO ()+    checkAll what m =+      forM_ (IM.toList m) $ \(k, !v) ->+        noThunks [] v >>= mapM_ (\info -> do+          putStrLn ("thunks retained in " ++ what ++ " at key " ++ show k ++ ": " ++ show info)+          assert failed False)
test/integration/Cases/NumericInput.hs view
@@ -1,67 +1,83 @@-module Cases.NumericInput-  ( runNumericInputHexTest-  , runNumericInputTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.NumericInput (tests) where -import Data.IORef (IORef, newIORef)+import Spec import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness (held, pressAt, releaseAt, warmup2)+import NanoUI.Shortcut qualified as Shortcut+import NanoUI.Testing.Sim --- A numeric field steps with the arrow keys (Shift steps ten times as far),--- drops typing that is not a number, clamps to its range while typing, and--- Enter rewrites the text as the clamped value. The stepper's lower half steps--- down.-runNumericInputTest :: Context -> IORef Int -> IO ()-runNumericInputTest ctx failed = do-  valueRef <- newIORef 12-  let inp = withInput 320 120-      cfg = defaultNumericInputConfig {nicMin = 0, nicMax = 100}-      ui = column (held valueRef (numericInputConfigured' cfg))-      step event = (\((_, v), _, _, _) -> v) <$> runFrame ctx event ui-      key k = inp {inputKeys = inputKeysFromList [k]}-  (resp, _) <- warmup2 ctx inp ui-  _ <- step (key KeyTab)-  stepped <- step (key KeyUp)-  assertEq failed stepped 13-  steppedTen <- step ((key KeyUp) {inputModifiers = Modifiers True False False})-  assertEq failed steppedTen 23-  rejected <- step (inp {inputChars = "4x"})-  assertEq failed rejected 23-  clamped <- step (inp {inputChars = "4"})-  assertEq failed clamped 100-  assert failed =<< spanShown ctx "234"-  _ <- step (key KeyEnter)-  assert failed =<< spanShown ctx "100"-  let Rect x y w h = respRect resp-      press = pressAt inp (V2 (x + w - 4) (y + h * 0.75))-  pressed <- step press-  assertEq failed pressed 99-  released <- step (releaseAt press)-  assertEq failed released 99+tests :: [Spec]+tests =+  [ spec "numeric-input" runNumericInputTest+  , spec "numeric-input-command" runNumericInputCommandTest+  ] --- Hexadecimal mode shows upper-case digits, takes hexadecimal typing but no--- decimal point, and steps like decimal mode.-runNumericInputHexTest :: Context -> IORef Int -> IO ()-runNumericInputHexTest ctx failed = do-  valueRef <- newIORef 255-  let inp = withInput 320 120-      cfg = defaultNumericInputConfig {nicMin = 0, nicHex = True, nicDecimals = 2}-      ui = column (held valueRef (numericInputConfigured' cfg))-      step event = (\((_, v), _, _, _) -> v) <$> runFrame ctx event ui-      key k = inp {inputKeys = inputKeysFromList [k]}-  _ <- warmup2 ctx inp ui-  assert failed =<< spanShown ctx "FF"-  _ <- step (key KeyTab)-  typed <- step (inp {inputChars = "a"})-  assertEq failed typed 0xFFA-  point <- step (inp {inputChars = "."})-  assertEq failed point 0xFFA-  stepped <- step (key KeyUp)-  assertEq failed stepped 0xFFB-  assert failed =<< spanShown ctx "FFB"+-- | Each script drives a fresh field with its config and value, focused by+-- Tab, and checks the values its frames return.+runNumericInputTest :: Context -> IORef Int -> IO ()+runNumericInputTest _ failed =+  forM_ cases $ \(cfg, initial, script) -> do+    ctx <- newContext+    ref <- newVar initial+    runSim ctx failed (withInput 320 120) (column (held ref (numericInputConfigured' cfg))) $+      pressTab 1 >> script+  where+    range = defaultNumericInputConfig {nicMin = 0, nicMax = 100}+    values = fmap (map snd) . sequence+    shown txt = check =<< labelShown txt+    cases =+      [ -- The arrows step (Shift ten times as far), typing that is not a+        -- number is dropped, typing clamps to the range, and Enter rewrites+        -- the text as the clamped value. The stepper's lower half steps down.+        ( range+        , 12+        , do+            (resp, _) <- result+            let shiftUp = chord (Shortcut.shift <> Shortcut.key KeyUp)+            checkEq [13, 23, 23, 100] =<< values [pressKey KeyUp, shiftUp, typeText "4x", typeText "4"]+            shown "234"+            _ <- pressKey KeyEnter+            shown "100"+            let Rect x y w h = respRect resp+            checkEq [99, 99] =<< values [press (At (V2 (x + w - 4) (y + h * 0.75))), release]+        )+      , -- Hexadecimal shows upper-case digits, takes hexadecimal typing but no+        -- decimal point, and steps like decimal.+        ( defaultNumericInputConfig {nicMin = 0, nicHex = True, nicDecimals = 2}+        , 255+        , do+            shown "FF"+            checkEq [0xFFA, 0xFFA, 0xFFB] =<< values [typeText "a", typeText ".", pressKey KeyUp]+            shown "FFB"+        )+      , -- Focus keeps a value its decimals do not show rather than reading+        -- the shown text back.+        (range, 2.5, checkEq [2.5, 2.5] =<< values [result, frame])+      , -- A number typed without its leading zero is read, so Enter keeps it.+        ( defaultNumericInputConfig {nicDecimals = 2}+        , 0+        , forM_ [(".5", 0.5, "0.50"), ("-.25", -0.25, "-0.25")] $ \(typed, value, txt :: T.Text) -> do+            _ <- chord (Shortcut.cmdOrCtrl <> Shortcut.key 'a') >> typeText typed+            checkEq value . snd =<< pressKey KeyEnter+            shown txt+        )+      ] -spanShown :: Context -> T.Text -> IO Bool-spanShown ctx txt = any (\(_, t, _, _, _) -> t == txt) <$> collectTextSpans ctx+-- | A command run on a focused numeric field from above it in the view, before+-- this frame declares it, still edits it, and pulses 'respChanged' once,+-- leaving no change behind for later frames.+runNumericInputCommandTest :: Context -> IORef Int -> IO ()+runNumericInputCommandTest ctx failed = do+  valueRef <- newVar 12+  pending <- newIORef []+  field <- newIORef Nothing+  -- The commands run before the field.+  let ui = column $ do+        cmds <- liftIO (atomicModifyIORef' pending ([],))+        liftIO (readIORef field) >>= mapM_ (\wid -> mapM_ (runTextCommand wid) cmds)+        (resp, v) <- held valueRef numericInput'+        (respChanged resp, v) <$ liftIO (writeIORef field (Just (respId resp)))+  runSim ctx failed (withInput 320 120) ui $ do+    pressTab 1+    liftIO (writeIORef pending [ReplaceAll "42"])+    checkEq [(True, 42), (False, 42), (False, 42)] =<< replicateM 3 frame
+ test/integration/Cases/PaneGrid.hs view
@@ -0,0 +1,829 @@+{-# OPTIONS_GHC -O0 #-}+-- | The pane grid: the split tree it reports and adopts, when an+-- arrangement settles, padding, pane sizes, drag handles and dividers.+module Cases.PaneGrid (tests) where++import Control.Exception (IOException, try)+import Data.Either (isLeft)+import Data.IntMap.Strict qualified as IM+import Data.Map.Strict qualified as M+import Data.Maybe (isJust, listToMaybe)+import Data.Text qualified as T+import Data.Word (Word64)+import NanoUI.Internal.Context (setDrawExternalText)+import NanoUI.Internal.Widgets.SplitPane+  ( DropPreview (..)+  , PaneDrop (..)+  , dropPreviewTreeSized+  , dropTargetForPane+  , layoutNode+  , reflowFixed+  , topLevelDropTarget+  )+import NanoUI.Testing.Sim+import Spec++tests :: [Spec]+tests =+  [ spec "pane-grid-layout" runLayoutTest+  , spec "pane-grid-divider" runDividerTest+  , spec "pane-grid-controlled" runControlledTest+  , spec "pane-grid-pane-drag" runPaneDragTest+  , spec "pane-grid-drop" runDropTest+  , spec "pane-grid-tab-drop" runTabDropTest+  , spec "pane-grid-clip" runClipTest+  , simSpec "pane-grid-escape" 600 400 ((,) <$> paneGrid halvesGrid <*> takeEscape) escapeRestores+  , spec "pane-grid-empty" runEmptyTest+  , spec "pane-grid-validation" runValidationTest+  , spec "pane-grid-mixed-drag" runMixedDragTest+  , spec "pane-grid-drop-preview" runDropPreviewTest+  , spec "pane-grid-pinned-pane" runPinnedPaneTest+  , spec "pane-grid-clipped-control" runClippedControlTest+  , spec "pane-grid-native-tabs" runNativeTabsTest+  ]++-- | Two panes side by side in a 600 by 400 grid: a 16px gutter from 292 to+-- 308, down the middle.+halves :: GridNode+halves = Split 30 AxisV 0.5 (Pane 10) (Pane 20)++-- | 'halves' filling the window.+halvesGrid :: PaneGridConfig+halvesGrid = defaultPaneGridConfig {pgLayout = fillW . fillH, pgTree = InitialTree (Just halves)}++-- | The left pane at its 40px minimum, its ratio below it; the gutter runs+-- from 40 to 56.+narrowLeft :: GridNode+narrowLeft = Split 30 AxisV 0 (Pane 10) (Pane 20)++-- | A fresh context running @script@ against @ui@ in a 600 by 400 window.+inGrid :: IORef Int -> NanoUI a -> Sim a r -> IO r+inGrid failed ui script = newContext >>= \ctx -> runSim ctx failed (withInput 600 400) ui script++-- | A pane view that, once @flag@ is set, runs @act@ in pane @target@.+actOnce :: IORef Bool -> Word64 -> (PaneGridCtx -> NanoUI ()) -> Word64 -> PaneGridCtx -> NanoUI PaneView+actOnce flag target act pid pctx = do+  wanted <- liftIO (readIORef flag)+  when (wanted && pid == target) (liftIO (writeIORef flag False) >> act pctx)+  pure (PaneView "P" False)++-- | A tree the caller holds fixed.+controlled :: Maybe GridNode -> PaneTree+controlled = ControlledTree . constVar++splitH :: PaneGridCtx -> NanoUI ()+splitH pctx = void (pgcSplit pctx AxisH)++-- | One pane left, two stacked right.+mixed :: GridNode+mixed = Split 2 AxisV 0.5 (Pane 1) (Split 4 AxisH 0.5 (Pane 3) (Pane 5))++-- | Record @v@ as pane @pid@'s.+note :: IORef (IM.IntMap v) -> Word64 -> v -> NanoUI ()+note ref pid v = liftIO (modifyIORef' ref (IM.insert (fromIntegral pid) v))++-- | What the panes record in @ref@ while @act@ runs.+recording :: IORef (IM.IntMap v) -> Sim a b -> Sim a (IM.IntMap v)+recording ref act = liftIO (writeIORef ref IM.empty) >> act >> liftIO (readIORef ref)++-- | The ratio of the root split.+rootRatio :: Maybe GridNode -> Maybe Float+rootRatio = \case+  Just (Split _ _ r _ _) -> Just r+  _ -> Nothing++-- | Press at @from@, nudge past the drag threshold, hold at @to@ for two+-- frames and release there; the frame after.+dragPane :: V2 -> V2 -> Sim a a+dragPane from@(V2 x y) to = do+  _ <- press (At from)+  mapM_ moveTo [At (V2 (x + 20) y), At to, At to]+  _ <- release+  frame++-- | A grid, the rect each pane's body was laid out at, and the rect each+-- pane was told it has ('pgcRect').+probeGrid ::+  (PaneGridConfig -> PaneGridConfig)+  -> (Word64 -> NanoUI ())+  -> IO (NanoUI PaneGridResponse, IORef (IM.IntMap Rect), IORef (IM.IntMap Rect))+probeGrid f body = do+  laid <- newIORef IM.empty+  told <- newIORef IM.empty+  let cfg =+        f+          halvesGrid+            { pgSpacing = 4+            , pgLeeway = 6+            , pgViewPane = \pid pctx -> do+                note told pid (pgcRect pctx)+                (_, area) <- mouseArea (fillW . fillH) (body pid)+                note laid pid (respRect area)+                pure (PaneView "P" False)+            }+  pure (paneGrid cfg, laid, told)++-- | 'pgLayout' padding insets the panes, content wider than a slot keeps both+-- slots, 'pgcRect' is where a pane is laid out, and 'pgDividerColor' fills+-- the gutter.+runLayoutTest :: Context -> IORef Int -> IO ()+runLayoutTest _ failed = do+  let wide pid = when (pid == 10) . void . panelWith (fillW . fillH) . rowWith fillW $ do+        labelWith fillW "A title that runs on"+        box (minW 900 . minH 900 . fillW) (colorRGBA 255 0 0 255)+      split axis c = c {pgTree = InitialTree (Just (Split 30 axis 0.5 (Pane 10) (Pane 20)))}+  -- Padded: 560 inside the padding, less a 16px gutter, halved.+      padded c = c {pgLayout = fillW . fillH . padAll 20}+  forM_+    [ (padded, const (pure ()), Rect 20 20 272 360, Rect 308 20 272 360)+    , (split AxisV, wide, Rect 0 0 292 400, Rect 308 0 292 400)+    , (split AxisH, wide, Rect 0 0 600 192, Rect 0 208 600 192)+    ]+    $ \(f, body, first, second) -> do+      ctx <- newContext+      (ui, laid, told) <- probeGrid f body+      replicateM_ 4 (runFrame ctx (withInput 600 400) ui)+      l <- readIORef laid+      assertEq failed (Just first, Just second) (IM.lookup 10 l, IM.lookup 20 l)+      assertEq failed l =<< readIORef told+  let c = colorRGBA 10 20 30 255+  ctx <- newContext+  (_, dd) <- warmupDraw ctx (withInput 600 400) (paneGrid halvesGrid {pgDividerColor = Just c})+  assert failed . elem (Rect 292 0 16 400, c) =<< drawQuads dd++-- | A divider drag sets 'pgrChanged' while it moves and 'pgrCommitted' on its+-- release (a split sets both, a still press neither), repainting both panes.+-- A divider at a minimum its ratio lies below follows from the first pixel,+-- and a drag released while the grid was not built is over.+runDividerTest :: Context -> IORef Int -> IO ()+runDividerTest _ failed = do+  splitNow <- newIORef False+  -- The flags of every pass of a frame: a grid that changes runs the view+  -- again, and an app acts on the pass that saw the change.+  seen <- newIORef (False, False)+  let labelled pid pctx = do+        _ <- actOnce splitNow 10 splitH pid pctx+        PaneView "P" False <$ label (if pid == 10 then "left" else "right")+      ui = do+        resp <- paneGrid halvesGrid {pgViewPane = labelled}+        liftIO (modifyIORef' seen (\(c, k) -> (c || pgrChanged resp, k || pgrCommitted resp)))+      flags act = liftIO (writeIORef seen (False, False)) >> act >> liftIO (readIORef seen)+  inGrid failed ui $ do+    moving <- mapM flags [press (at 300 200), moveTo (at 360 200)]+    -- The right pane moved from x 308 to 368, and the left one grew.+    check . (`damageCovers` Rect 0 0 600 400) =<< frameDamage+    right <- findSpan "right"+    checkJust right $ \r -> checkGt (rectX r) 350+    rest <- mapM flags [moveTo (at 360 200), release, frame, click (at 300 200), frame]+    splitting <- mapM flags [liftIO (writeIORef splitNow True) >> frame, frame]+    let none = (False, False)+    checkEq [none, (True, False), none, (False, True), none, none, none] (moving ++ rest)+    checkEq [(True, True), none] splitting+  -- The left pane ends 70px wide: its 40px minimum and the 30 moved.+  let narrow = paneGrid halvesGrid {pgTree = InitialTree (Just narrowLeft)}+  inGrid failed narrow $ do+    r <- drag (at 48 200) (at 78 200) 1+    checkJust (rootRatio (pgrTree r)) $ \ratio -> check (abs (ratio - 70 / 584) < 1.0e-4)+  -- A press elsewhere, still held when the grid is back, leaves the divider.+  shownRef <- newIORef True+  let showing = liftIO . writeIORef shownRef+      sometimes = do+        shown <- liftIO (readIORef shownRef)+        if shown then pgrTree <$> paneGrid halvesGrid else pure Nothing+  inGrid failed sometimes $ do+    _ <- press (at 300 200)+    dragged <- moveTo (at 350 200)+    check (dragged /= Just halves)+    showing False+    _ <- release+    _ <- press (at 100 100)+    showing True+    -- The first frame back lays the grid out; the next has its rect to drag in.+    replicateM_ 2 (checkEq dragged =<< moveTo (at 150 100))+    checkEq dragged =<< release++-- | A controlled tree passed back each frame keeps the grid, mid-drag too;+-- another replaces it; one not passed back is rejected, and a new+-- 'InitialTree' seed changes nothing. A tree in a Var resets from the view,+-- and written over a maximized pane shows it unmaximized, taking drops.+runControlledTest :: Context -> IORef Int -> IO ()+runControlledTest _ failed = do+  given <- newIORef (Just halves)+  let passedBack = do+        t <- liftIO (readIORef given)+        resp <- paneGrid halvesGrid {pgTree = ControlledTree (constVar t)}+        liftIO (writeIORef given (pgrTree resp))+        pure resp+      other = Split 5 AxisH 0.25 (Pane 1) (Pane 2)+      dragged = Just (0.5 + 100 / 584)+  inGrid failed passedBack $ do+    checkEq dragged . rootRatio . pgrTree =<< drag (at 300 200) (at 400 200) 2+    liftIO (writeIORef given (Just other))+    r <- frame+    checkEq (Just other, [1, 2]) (pgrTree r, pgrPanes r)+  edit <- newIORef False+  proposed <- newIORef Nothing+  let rejecting = do+        r <- paneGrid halvesGrid {pgTree = controlled (Just halves), pgViewPane = actOnce edit 10 splitH}+        when (pgrChanged r) (liftIO (writeIORef proposed (pgrTree r)))+        pure r+  ctx <- newContext+  runSim ctx failed (withInputOff 600 400) rejecting $ do+    liftIO (writeIORef edit True)+    _ <- frame+    change <- liftIO (readIORef proposed)+    check (change /= Nothing && change /= Just halves)+    checkEq (Just halves) . pgrTree =<< frame+  kept <- evalUi ctx (withInputOff 600 400) (paneGrid halvesGrid {pgTree = InitialTree (Just (Pane 90))})+  assertEq failed (Just halves) (pgrTree kept)+  resetNow <- newIORef False+  maximize <- newIORef False+  arrangement <- newVar (Just halves)+  let inVarCfg = halvesGrid {pgTree = ControlledTree arrangement, pgViewPane = actOnce maximize 20 pgcMaximize}+      inVar = do+        resp <- paneGrid inVarCfg+        wanted <- liftIO (readIORef resetNow)+        when wanted (liftIO (writeIORef resetNow False) >> writeVar arrangement (Just halves))+        pure resp+      raise ref = liftIO (writeIORef ref True) >> settle+  inGrid failed inVar $ do+    _ <- drag (at 300 200) (at 400 200) 1+    checkEq dragged . rootRatio . pgrTree =<< frame+    checkEq (Just 0.5) . rootRatio . pgrTree =<< raise resetNow+    checkEq 20 . pgrMaximizedPane =<< raise maximize+    writeV arrangement (Just (Split 5 AxisV 0.5 (Pane 1) (Pane 2)))+    _ <- moveTo (at 5 200)+    checkEq (Just (OutsideGrid PaneLeft)) . fmap pgdLocation . pgrDropTarget =<< settle+    writeV arrangement (Just halves)+    checkEq 0 . pgrMaximizedPane =<< settle++-- | A press on a 'paneDragHandle' drags its pane (onto the other's middle to+-- swap them) under a repainting indicator. Below the handle, on its button,+-- past its pane or under a scrim, a press drags nothing.+runPaneDragTest :: Context -> IORef Int -> IO ()+runPaneDragTest _ failed = do+  clicks <- newIORef (0 :: Int)+  -- The handle is the top 40px of each pane; its button is at its right end.+  let handled _ pctx = do+        paneDragHandle pctx (fillW . fixedH 40) $ do+          flex+          whenM (buttonWith (fixedWH 40 30) "x") (liftIO (modifyIORef' clicks (+ 1)))+        pure (PaneView "P" False)+  inGrid failed (paneGrid halvesGrid {pgViewPane = handled}) $ do+    panes <- mapM (\from -> pgrPanes <$> dragPane from (V2 454 200)) [V2 60 20, V2 60 200, V2 270 20]+    checkEq (replicate 3 [20, 10]) panes+    checkEq 0 =<< liftIO (readIORef clicks)+    checkEq UiCursorGrab =<< cursorAt (at 60 20)+  let overrun pid pctx = do+        when (pid == 10) $ paneDragHandle pctx (fixedWH 200 30) (pure ())+        pure (PaneView "P" False)+  inGrid failed (paneGrid halvesGrid {pgTree = InitialTree (Just narrowLeft), pgViewPane = overrun}) $+    checkEq (Just narrowLeft) . pgrTree =<< dragPane (V2 100 15) (V2 300 200)+  -- The indicator sits 12px right of and below the pointer, and repaints+  -- though the drop zone stays the same.+  let anywhere = paneGrid halvesGrid {pgViewPane = \_ _ -> pure (PaneView "P" True)}+  inGrid failed anywhere $ do+    _ <- press (at 100 200)+    mapM_ (\x -> moveTo (at x 200)) [300, 305, 310]+    check . (`damageCovers` Rect 317 212 117 28) =<< frameDamage+  let covered = columnWith (fillW . fillH) $ do+        r <- anywhere+        panelWith (pinAt 0 0 . pointer PointerBlock . fixedWH 600 400) (pure ())+        pure r+  inGrid failed covered $ forM_ [V2 300 200, V2 150 200] $ \from ->+    checkEq (Just halves) . pgrTree =<< dragPane from (V2 450 200)++-- | The pointer at the edge or beside a divider previews an external drop+-- (no extra pane rendered), elsewhere none. A drop commits once, focused, a+-- replaced grid's target is stale, and an overlay covers the drop zone.+runDropTest :: Context -> IORef Int -> IO ()+runDropTest _ failed = do+  rendered <- newIORef []+  let noting pid _ = PaneView "Pane" False <$ liftIO (modifyIORef' rendered (pid :))+      recorder = paneGrid halvesGrid {pgViewPane = noting}+      hover x = moveTo (at x 200)+  inGrid failed recorder $ do+    liftIO (writeIORef rendered [])+    preview <- hover 5+    checkEq (Just halves, False) (pgrTree preview, pgrChanged preview)+    checkEq [20, 10] =<< liftIO (readIORef rendered)+    checkJust (pgrDropTarget preview) $ \target -> do+      checkEq (OutsideGrid PaneLeft, 10) (pgdLocation target, pgdPane target)+      check (rectW (pgdRect target) > 0 && rectH (pgdRect target) == 400)+    checkEq (Just (BesidePane 10 PaneRight)) . fmap pgdLocation . pgrDropTarget =<< hover 280+    forM_ [-1, 150, 300] $ \x -> do+      r <- hover x+      checkEq (Just halves, Nothing) (pgrTree r, pgrDropTarget r)+  ctx <- newContext+  let edge = (withInput 600 400) {inputMousePos = V2 5 200}+      view = paneGrid halvesGrid+      committing = do+        r <- view+        commits <- forM (pgrDropTarget r) $ \target -> (,) <$> commitPaneDrop target <*> commitPaneDrop target+        pure (r, commits)+  _ <- warmup2 ctx edge view+  ((before, commits), _, dirty) <- runFrame ctx edge committing+  assert failed dirty+  assertEq failed (Just halves) (pgrTree before)+  after <- evalUi ctx edge view+  assertJust failed commits $ \(committed, repeated) -> do+    assertEq failed Nothing repeated+    assertJust failed committed $ \(pid, arrangement) ->+      assertEq failed (Just arrangement, pid, 3) (pgrTree after, pgrFocusedPane after, pgrPaneCount after)+  stale <- maybe (fail "missing target") pure (pgrDropTarget after)+  let replaced = paneGrid halvesGrid {pgTree = controlled (Just (Pane 90))}+  assertEq failed Nothing =<< evalUi ctx edge (replaced >> commitPaneDrop stale)+  covered <- newContext+  let overlaid = columnWith (fillW . fillH) $ do+        r <- paneGrid defaultPaneGridConfig {pgLayout = fillW . fillH}+        void (buttonWith' (pinAt 0 150 . fixedWH 80 100) "Overlay")+        pure r+  r <- warmup covered edge overlaid >> warmup2 covered edge overlaid+  assertEq failed (1, Nothing) (pgrPaneCount r, pgrDropTarget r)++-- | A tab dragged onto the grid's edge previews without an uncommitted pane,+-- and its release, consumed in the frame rendering its source, commits one.+runTabDropTest :: Context -> IORef Int -> IO ()+runTabDropTest ctx failed = do+  dragHandle <- newDrag+  headers <- newIORef []+  let tabsPane pid _ = do+        r <- tabBar' (constVar (1 :: Int)) [tab 1 "Alpha" (), tab 2 "Beta" ()]+        liftIO (modifyIORef' headers (++ [((pid, k), h) | (k, h) <- tabHeaders r]))+        pure (PaneView "Editor" False)+      ui = do+        liftIO (writeIORef headers [])+        response <- paneGrid defaultPaneGridConfig {pgLayout = fillW . fillH, pgViewPane = tabsPane}+        gesture <- useDrag dragHandle =<< liftIO (readIORef headers)+        committed <- case (gesture, pgrDropTarget response) of+          (Just d, Just target) | dragPhase d == DragReleased -> commitPaneDrop target+          _ -> pure Nothing+        pure (response, committed)+  runSim ctx failed (withInput 600 400) ui $ do+    _ <- press "Alpha"+    checkEq 1 . pgrPaneCount . fst =<< moveTo (at 5 200)+    check . isJust . snd =<< release+    checkEq 2 . pgrPaneCount . fst =<< frame++-- | Content is cut to its pane: a button or a scroller's bar past it takes+-- no click or grab there. A bar dragged in a pane that drags from anywhere+-- scrolls and leaves the pane.+runClipTest :: Context -> IORef Int -> IO ()+runClipTest ctx failed = do+  clicks <- newIORef (0 :: Int)+  ids <- newIORef IM.empty+  let tall = box (fixedWH 100 2000) (colorRGBA 200 0 0 255)+      body 10 = do+        (wid, _) <- scrollArea (fixedWH 450 300) tall+        hidden <- rowWith (tight . gap 0) $ do+          box (fixedWH 400 30) (colorRGBA 200 0 0 255)+          buttonWith' (fixedWH 60 30) "Hidden"+        when (respClicked hidden) (liftIO (modifyIORef' clicks (+ 1)))+        note ids 0 (respId hidden)+        pure wid+      body _ = fst <$> scrollArea (tight . grow) tall+      pane pid _ = body pid >>= note ids pid >> pure (PaneView "P" True)+      ui = paneGrid halvesGrid {pgViewPane = pane}+  runSim ctx failed (withInput 600 400) ui $ do+    known <- liftIO (readIORef ids)+    [hidden, Rect wx wy ww _, Rect px py pw _] <- mapM (prevRect . (known IM.!)) [0, 10, 20]+    -- Laid out past the pane, which ends at 292.+    check (rectX hidden >= 292)+    _ <- click (Within hidden)+    checkEq 0 =<< liftIO (readIORef clicks)+    checkGt (wx + ww) 320+    kinds <- mapM (\d -> cursorAt (at (wx + ww - d) (wy + 10))) [1 .. 16]+    check (UiCursorGrab `notElem` kinds)+    -- The other pane's thumb, at the top of the bar along its right edge.+    thumbs <- filterM (\d -> (== UiCursorGrab) <$> cursorAt (at (px + pw - d) (py + 10))) [1 .. 16]+    checkJust (listToMaybe thumbs) $ \d -> do+      _ <- press (at (px + pw - d) (py + 10))+      replicateM_ 2 (moveTo (at (px + pw - d) (py + 60)))+      checkEq (Just halves) . pgrTree =<< release+      flip checkGt 0 =<< scrollOffsetOf (known IM.! 20)++-- | A focused grid takes Escape only to restore a maximized pane; otherwise+-- the key goes on to a handler after it.+escapeRestores :: Sim (PaneGridResponse, Bool) ()+escapeRestores = do+  pressTab 1+  check . snd =<< pressKey KeyEscape+  _ <- pressKey (KeyChar 'm')+  check . (/= 0) . pgrMaximizedPane . fst =<< settle+  check . not . snd =<< pressKey KeyEscape+  checkEq 0 . pgrMaximizedPane . fst =<< settle++-- | A grid with no tree has no panes, a pane closed in it leaves none, and a+-- controlled tree brings one back or clears it.+runEmptyTest :: Context -> IORef Int -> IO ()+runEmptyTest ctx failed = do+  close <- newIORef False+  let inp = withInputOff 600 400+      withTree t = paneGrid halvesGrid {pgTree = t, pgViewPane = actOnce close 1 pgcClose}+      one = controlled (Just (Pane 1))+      none = InitialTree Nothing+  empty <- warmup2 ctx inp (withTree none)+  assertEq failed (Nothing, 0, []) (pgrTree empty, pgrPaneCount empty, pgrPanes empty)+  _ <- warmup2 ctx inp (withTree one)+  writeIORef close True+  _ <- evalUi ctx inp (withTree none)+  closed <- warmup2 ctx inp (withTree none)+  assertEq failed (Nothing, 0) (pgrTree closed, pgrPaneCount closed)+  assertEq failed [1] . pgrPanes =<< evalUi ctx inp (withTree one)+  assertEq failed [] . pgrPanes =<< evalUi ctx inp (withTree (controlled Nothing))++runValidationTest :: Context -> IORef Int -> IO ()+runValidationTest ctx failed = do+  assertEq failed (Right ()) (validateGridTree halves)+  let invalid =+        [ Pane 0+        , Pane (2 ^ (63 :: Int))+        , Split 1 AxisV 0.5 (Pane 1) (Pane 2)+        , Split 3 AxisV 0.5 (Pane 1) (Pane 1)+        , Split 3 AxisV (0 / 0) (Pane 1) (Pane 2)+        , Split 3 AxisV 1.1 (Pane 1) (Pane 2)+        ]+  forM_ invalid $ \arrangement -> do+    assert failed (isLeft (validateGridTree arrangement))+    outcome <- try @IOException $ runFrame ctx (withInput 600 400) $+      paneGrid defaultPaneGridConfig {pgTree = controlled (Just arrangement)}+    assert failed (isLeft outcome)++-- | Drop previews simulate the post-drop layout (lifting a pane re-flows a+-- mixed-axis grid) and size-preserving drops keep the pane's extent. Live, a+-- drop lands with every pane's state, outside the grid cancels, and a drag+-- from a close button lifts nothing.+runMixedDragTest :: Context -> IORef Int -> IO ()+runMixedDragTest ctx failed = do+  let minSize = 40+      gutter = 4+      base = Rect 0 0 600 400+      lay t = fst (layoutNode minSize gutter t base)+      tree0 = Split 100 AxisV 0.5 (Pane 1) (Split 101 AxisH 0.5 (Pane 2) (Pane 3))+      r2 = lay tree0 M.! 2+      r3 = lay tree0 M.! 3+      preview dt = dpRect <$> dropPreviewTreeSized Nothing minSize gutter tree0 1 0 base dt+      within (Rect x y w h) fx fy = V2 (x + w * fx) (y + h * fy)+  assertEq failed (M.fromList [(1, Rect 0 0 298 400), (2, Rect 302 0 298 198), (3, Rect 302 202 298 198)]) (lay tree0)+  -- With pane 1 lifted the right branch fills the grid, so an edge drop on+  -- pane 3 lands across its foot, not in half its old rect (302 301 298 99).+  forM_+    [ (dropTargetForPane r3 (within r3 0.5 0.9) 3, DropSplit 3 AxisH False, Rect 0 303 600 97)+    , (dropTargetForPane r2 (within r2 0.9 0.5) 2, DropSplit 2 AxisV False, r2)+    , (dropTargetForPane r2 (spanCenter r2) 2, DropSwap 2, r2)+    , (DropTop AxisV True, DropTop AxisV True, Rect 0 0 298 400)+    ]+    $ \(dt, want, rect) -> assertEq failed (want, Just rect) (dt, preview dt)+  assertEq failed (Just (DropTop AxisV True)) (topLevelDropTarget 20 base (V2 5 200))+  assertEq failed Nothing (topLevelDropTarget 20 base (V2 300 200))+  let sizedTree = Split 100 AxisV 0.25 (Pane 1) (Split 101 AxisH 0.3 (Pane 2) (Pane 3))+      s1 = lay sizedTree M.! 1+      s2 = lay sizedTree M.! 2+      sized src p = dropPreviewTreeSized (Just src) minSize gutter sizedTree p 102 base+  forM_ [True, False] $ \onA -> do+    let both ax = [DropTop ax onA, DropSplit 3 ax onA]+    forM_ (both AxisV) $ \dt -> assertJust failed (sized s1 1 dt) $ \dp ->+      assertEq failed (Just (dpRect dp)) (M.lookup 1 (lay (dpTree dp)))+    -- Extents carry across axes, within the destination's minimum.+    forM_+      ( [(s1, 1, dt, rectW, rectW s1) | dt <- both AxisV]+          <> [(s1, 1, dt, rectH, rectW s1) | dt <- both AxisH]+          <> [(s2, 2, DropTop AxisH onA, rectH, rectH s2)]+          <> [(s2, 2, dt, rectW, rectH s2) | dt <- both AxisV]+          <> [(Rect 0 0 500 400, 1, DropTop AxisH onA, rectH, 312)]+      )+      $ \(src, p, dt, size, want) ->+        assertJust failed (sized src p dt) $ \dp -> assert failed (abs (size (dpRect dp) - want) < 0.01)+  assertEq failed (Just s2) (dpRect <$> sized s1 1 (DropSwap 2))+  rects <- newIORef IM.empty+  closeRects <- newIORef IM.empty+  stateUpdates <- newIORef IM.empty+  paneStates <- newIORef IM.empty+  let ui =+        paneGrid+          halvesGrid+            { pgTree = InitialTree (Just mixed)+            , pgViewPane = \pid pctx -> do+                note rects pid (pgcRect pctx)+                valueVar <- useVar (0 :: Int)+                value <- readVar valueVar+                marker <- nextId+                pending <- liftIO (IM.lookup (fromIntegral pid) <$> readIORef stateUpdates)+                forM_ pending $ \n -> do+                  writeVar valueVar n+                  liftIO (modifyIORef' stateUpdates (IM.delete (fromIntegral pid)))+                note paneStates pid (marker, value)+                close <- button' "x"+                note closeRects pid (respRect close)+                when (respClicked close) (pgcClose pctx)+                pure (PaneView "P" True)+            }+      key = fromIntegral :: Word64 -> Int+      states = liftIO (readIORef paneStates)+  runSim ctx failed (withInput 600 400) ui $ do+    [pa, pb, pc] <- pgrPanes <$> result+    let expected = IM.fromList [(key p, key p + 100) | p <- [pa, pb, pc]]+    liftIO (writeIORef stateUpdates expected)+    rs <- recording rects settle+    initialStates <- states+    checkEq expected (IM.map snd initialStates)+    Just ra <- pure (IM.lookup (key pa) rs)+    Just rc <- pure (IM.lookup (key pc) rs)+    let ps = IM.elems rs+        gx = minimum (map rectX ps)+        gy = minimum (map rectY ps)+        gw = maximum (map (\r -> rectX r + rectW r) ps) - gx+        gh = maximum (map (\r -> rectY r + rectH r) ps) - gy+        -- In the header, 2px from the divider, whose leeway must not steal it.+        grab = At (V2 (rectX ra + rectW ra - 2) (rectY ra + 12))+        -- In pane 3's bottom zone, clear of the 20px top-level band, at the+        -- grid's middle: with pane 1 lifted, pane 3 spans the grid.+        dest = V2 (gx + gw / 2) (rectY rc + rectH rc - 30)+    -- The order checked below is the same after a top-level band drop.+    checkEq Nothing (topLevelDropTarget 20 (Rect gx gy gw gh) dest)+    _ <- press grab+    liftIO (writeIORef paneStates IM.empty)+    during <- recording rects (moveTo (At dest))+    checkEq (IM.delete (key pa) initialStates) =<< states+    checkEq (IM.keys (IM.delete (key pa) rs)) (IM.keys during)+    check (all ((== gw) . rectW) during)+    -- Back over the grab point the pane stays lifted and the drag no click.+    check . not . IM.member (key pa) =<< recording rects (moveTo grab)+    checkEq [pa, pb, pc] . pgrPanes =<< (moveTo (at (-20) (-20)) >> release)+    checkEq initialStates =<< (settle >> states)+    checkEq [pb, pc, pa] . pgrPanes =<< (press grab >> moveTo (At dest) >> release)+    checkEq initialStates =<< (settle >> states)+    Just closePos <- fmap spanCenter . IM.lookup (key pa) <$> liftIO (readIORef closeRects)+    _ <- press (At closePos)+    checkEq 3 . IM.size =<< recording rects (moveTo (At (v2Add closePos (V2 60 40))))+    checkEq [pb, pc] . pgrPanes =<< (moveTo (At closePos) >> release)++-- | Hovering a target lays the grid out as the drop will leave it, the+-- dragged pane's slot empty: over uneven splits a highlight on the pre-drop+-- panes lines up with nothing.+runDropPreviewTest :: Context -> IORef Int -> IO ()+runDropPreviewTest ctx failed = do+  -- Per pane: 'pgcRect', and the solved rect of a full-width strip inside it.+  seen <- newIORef IM.empty+  let ui =+        paneGrid+          halvesGrid+            { pgTree = InitialTree (Just mixed)+            , pgViewPane = \pid pctx -> do+                strip <- labelWith' (fixedH 20 . fillW . tight) "H"+                note seen pid (pgcRect pctx, respRect strip)+                pure (PaneView "P" True)+            }+      -- The layout once the input has settled (the strip's rect lags a frame).+      layout = settle >> recording seen frame+      -- Lift pane @p@, park it outside the grid, hover at @dest@ of that+      -- lifted layout, and release: the layouts lifted, hovering and after.+      lift p dest = do+        Just (Rect px py _ _, _) <- IM.lookup p <$> layout+        _ <- press (at (px + 10) (py + 10))+        lifted <- moveTo (at (-50) (-50)) >> layout+        during <- moveTo (At (dest lifted)) >> layout+        (lifted, during,) <$> (release >> layout)+      spot q (fx, fy) lifted = case IM.lookup q lifted of+        Just (Rect x y w h, _) -> V2 (x + w * fx) (y + h * fy)+        Nothing -> V2 (-50) (-50)+      -- Whole pixels: a dragged ratio leaves float dust (112.00001).+      wholePx (Rect x y w h) = Rect (r x) (r y) (r w) (r h) where r v = fromIntegral (round v :: Int)+      -- Nothing moves on release, and the dragged pane takes the empty slot.+      previewed p (lifted, during, after) = do+        check (not (IM.member p lifted) && not (IM.member p during) && IM.member p after)+        checkEq during (IM.delete p after)+  runSim ctx failed (withInput 600 400) ui $ do+    -- Pane 1 left, 3 and 5 right, uneven.+    _ <- drag (at 300 200) (at 120 200) 1+    uneven <- layout+    checkEq (IM.fromList [(1, Rect 0 0 112 400), (3, Rect 128 0 472 192), (5, Rect 128 208 472 192)]) $+      IM.map (wholePx . fst) uneven+    -- The model rects are the solver's: the strip spans its pane.+    let across r = (rectX (wholePx r), rectW (wholePx r))+    check (all (\(m, s) -> across m == across s) uneven)+    -- A centre drop swaps: lifted, pane 3 spans the top row, and the hover+    -- already shows it in pane 1's narrow column.+    swap@(liftedS, duringS, _) <- lift 1 (spot 3 (0.5, 0.5))+    checkEq (Just (Rect 0 0 600 192)) (wholePx . fst <$> IM.lookup 3 liftedS)+    checkEq (Just (Rect 0 0 112 400)) (wholePx . fst <$> IM.lookup 3 duringS)+    previewed 1 swap+    -- Edge drops show the target already halved.+    previewed 1 =<< lift 1 (spot 5 (0.1, 0.5))+    previewed 5 =<< lift 5 (spot 3 (0.5, 0.9))+    -- The grid's outer band squeezes the whole grid into the other half.+    top@(_, duringT, _) <- lift 3 (const (V2 590 200))+    check (all (\(Rect x _ w _, _) -> x + w <= 300) duringT)+    previewed 3 top+    -- A gutter still targets the nearer pane, so the preview holds across it.+    gut@(liftedG, duringG, _) <- lift 1 $ \lifted ->+      let panes = map fst (IM.elems lifted)+          gutterPoints =+            [ pt+            | Rect x y w h <- panes+            , pt@(V2 px py) <- [V2 (x + w + 2) (y + h / 2), V2 (x + w / 2) (y + h + 2)]+            , px > 20 && px < 580 && py > 20 && py < 380+            , not (any (`rectContains` pt) panes)+            ]+       in case gutterPoints of+            pt : _ -> pt+            [] -> V2 (-50) (-50)+    check (duringG /= liftedG)+    previewed 1 gut+    -- Outside the grid the release cancels and the uneven layout comes back+    -- (a top-level drop would re-split it 50/50).+    start <- layout+    (_, duringC, afterC) <- lift 1 (const (V2 (-20) 200))+    check (not (IM.member 1 duringC))+    checkEq start afterC++-- | A pinned pane keeps its width from the first frame of a resize; unpinned,+-- both sides scale.+runPinnedPaneTest :: Context -> IORef Int -> IO ()+runPinnedPaneTest ctx failed = do+  rects <- newIORef IM.empty+  pin <- newIORef True+  let ui = do+        pinned <- liftIO (readIORef pin)+        paneGrid+          halvesGrid+            { pgFixedPanes = if pinned then (== 10) else const False+            , pgViewPane = \pid pctx -> PaneView "P" False <$ note rects pid (pgcRect pctx)+            }+  runSim ctx failed (withInput 600 400) ui $ do+    -- The 16px gutter leaves 584 to share.+    _ <- drag (at 300 200) (at 120 200) 1+    forM_+      [ (True, 600, 2, [(10, 112), (20, 472)])+      , (True, 900, 1, [(10, 112)])+      , (True, 900, 3, [(10, 112), (20, 772)])+      , (True, 600, 3, [(10, 112), (20, 472)])+      , -- Unpinned it scales; pinned again, it keeps the width it was left at.+        (False, 900, 3, [(10, 169.5)])+      , (True, 600, 3, [(10, 169.5)])+      , -- With no room for the pin and the neighbour's minimum, the pin gives way.+        (True, 100, 3, [(10, 44), (20, 40)])+      ]+      $ \(pinned, w, n, want) -> do+        -- @n@ frames at the width, then one more to report what they solved+        -- ('pgcRect' lags a frame, so @n = 1@ reads the first frame at a size).+        liftIO (writeIORef pin pinned)+        modifyInput (\i -> i {inputWindowSize = Size w 400})+        ms <- replicateM_ n frame >> recording rects frame+        forM_ want $ \(p, x) -> case IM.lookup p ms of+          Just r | abs (rectW r - x) <= 1 -> pure ()+          got -> checkEq (pinned, w, p, Just x) (pinned, w, p, rectW <$> got)+  -- The pure re-ratio on trees the widget case cannot reach: two pins at+  -- once, a pin under a split on the other axis, and a right-hand pin held+  -- through a drag growing the grid by a fraction a frame without walking.+  let lay t r = fst (layoutNode 40 16 t r)+      reflow fixed old new = reflowFixed (`elem` fixed) 40 16 old new+      area = Rect 0 0+      ends = Split 10 AxisV 0.25 (Pane 1) (Split 11 AxisV 0.5 (Pane 2) (Pane 3))+      stacked = Split 20 AxisH 0.5 (Split 21 AxisV 0.5 (Pane 1) (Pane 2)) (Pane 3)+      stacked' = reflow [1] (area 600 400) (area 900 600) stacked+      rightPin = Split 30 AxisV 0.5 (Pane 1) (Pane 2)+      widthAt k = area (600 + k * 2 / 3) 400+  forM_+    [ (ends, area 600 400, rectW, [(1, 146), (3, 211)])+    , (reflow [1, 3] (area 600 400) (area 900 400) ends, area 900 400, rectW, [(1, 146), (3, 211), (2, 511)])+    , (stacked, area 600 400, rectW, [(1, 292)])+    , (stacked', area 900 600, rectW, [(1, 292), (2, 592)])+    , (stacked', area 900 600, rectH, [(1, 292), (3, 292)])+    , (rightPin, widthAt 0, rectW, [(2, 292)])+    , (foldl (\t k -> reflow [2] (widthAt k) (widthAt (k + 1)) t) rightPin [0 .. 29 :: Float], widthAt 30, rectW, [(2, 292)])+    ]+    $ \(t, r, size, want) -> forM_ want $ \(p, x) -> case M.lookup p (lay t r) of+      Just g | abs (size g - x) <= 0.01 -> pure ()+      got -> assertEq failed (r, p, Just x) (r, p, size <$> got)++-- | A button scrolled above its viewport can overlap the header, but its+-- hidden rect must not claim the header's drag press.+runClippedControlTest :: Context -> IORef Int -> IO ()+runClippedControlTest ctx failed = do+  rendered <- newIORef False+  geometry <- newIORef Nothing+  let ui =+        paneGrid+          defaultPaneGridConfig+            { pgLayout = fillW . fillH+            , pgViewPane = \_ _ -> do+                liftIO (writeIORef rendered True)+                header <- labelWith' (fixedH 40 . fillW . tight) "Header"+                (sid, target) <- scrollArea (fixedH 120 . fillW . tight) . columnWith tight $+                  button' "Scrolled control" <* replicateM_ 20 (label "Scroll content")+                liftIO (writeIORef geometry (Just (respId header, sid, respId target)))+                pure (PaneView "Panel" True)+            }+  runSim ctx failed (withInput 300 240) ui $ do+    Just (headerId, sid, targetId) <- liftIO (readIORef geometry)+    hr <- prevRect headerId+    br <- prevRect targetId+    -- Scroll the button's centre to the header's.+    onContext (\c -> setScrollOffsetIO c sid (rectY br + rectH br / 2 - (rectY hr + rectH hr / 2)))+    grab <- settle >> targetPoint (OnWidget targetId)+    check (rectContains hr grab)+    _ <- press (At grab)+    liftIO (writeIORef rendered False)+    _ <- moveTo (At (v2Add grab (V2 30 0)))+    check . not =<< liftIO (readIORef rendered)++runNativeTabsTest :: Context -> IORef Int -> IO ()+runNativeTabsTest ctx failed = do+  assert failed (isLeft (validateGridTree (PaneTabs 100 [] 10)))+  assert failed (isLeft (validateGridTree (PaneTabs 100 [10, 20] 99)))+  let merged = dropPreviewTreeSized Nothing 40 8 halves 10 99 (Rect 0 0 600 400) (DropTab 20 Nothing)+  case dpTree <$> merged of+    Just (PaneTabs _ pids act) -> assertEq failed ([20, 10], 10) (pids, act)+    other -> assertEq failed (Just (PaneTabs 99 [20, 10] 10)) other+  treeVar <- newVar (Just (PaneTabs 100 [10, 20] 10))+  let tabName 10 = "Alpha"+      tabName 20 = "Beta"+      tabName n = "Pane " <> T.pack (show n)+      ui =+        paneGrid+          defaultPaneGridConfig+            { pgLayout = fillW . fillH+            , pgTree = ControlledTree treeVar+            , pgCenterDrop = CenterTab+            , pgTabTitle = tabName+            , pgClosableTabs = True+            , pgViewPane = \pid _ -> do+                let t = "body-" <> tabName pid+                label t+                pure (PaneView (tabName pid) True)+            }+  runSim ctx failed (withInput 400 300) ui $ do+    check =<< textShown "Alpha"+    check =<< textShown "Beta"+    check =<< textShown "body-Alpha"+    check . not =<< textShown "body-Beta"+    _ <- click "Beta" >> settle+    check =<< textShown "body-Beta"+    check . not =<< textShown "body-Alpha"+    betaR <- rectOf "Beta"+    -- Click the close button right next to "Beta" in its tab pill.+    _ <- click (at (rectX betaR + rectW betaR + 10) (rectY betaR + rectH betaR / 2)) >> settle+    checkEq (Just (Pane 10)) =<< readV treeVar+    check =<< textShown "body-Alpha"+  -- Custom tab rendering via pgViewTab.+  customCtx <- newContext+  customTree <- newVar (Just (PaneTabs 200 [10, 20] 10))+  let customUi =+        paneGrid+          defaultPaneGridConfig+            { pgLayout = fillW . fillH+            , pgTree = ControlledTree customTree+            , pgCenterDrop = CenterTab+            , pgTabTitle = tabName+            , pgClosableTabs = False+            , pgViewTab = Just (\pid isAct -> label ((if isAct then "* " else "") <> tabName pid))+            , pgViewPane = \pid _ -> do+                label ("body-" <> tabName pid)+                pure (PaneView (tabName pid) True)+            }+  runSim customCtx failed (withInput 400 300) customUi $ do+    check =<< textShown "* Alpha"+    check =<< textShown "Beta"+    _ <- click "Beta" >> settle+    check =<< textShown "* Beta"+    check =<< textShown "body-Beta"+  -- pgcInTabs is True inside PaneTabs and False for standalone or maximized panes;+  -- dragging a tab whose PaneView title is empty falls back to pgTabTitle.+  inTabsRef <- newIORef (IM.empty :: IM.IntMap Bool)+  tabDragTree <- newVar (Just (Split 300 AxisV 0.5 (PaneTabs 200 [10, 20] 10) (Pane 30)))+  let inTabsUi =+        paneGrid+          defaultPaneGridConfig+            { pgLayout = fillW . fillH+            , pgTree = ControlledTree tabDragTree+            , pgCenterDrop = CenterTab+            , pgTabTitle = \pid -> "Tab-" <> T.pack (show pid)+            , pgViewPane = \pid pctx -> do+                liftIO (modifyIORef' inTabsRef (IM.insert (fromIntegral pid) (pgcInTabs pctx)))+                label ("body-" <> T.pack (show pid))+                pure (PaneView "" True)+            }+  inTabsCtx <- newContext+  setDrawExternalText inTabsCtx True+  runSim inTabsCtx failed (withInput 600 300) inTabsUi $ do+    m <- liftIO (readIORef inTabsRef)+    checkEq (Just True) (IM.lookup 10 m)+    checkEq (Just False) (IM.lookup 30 m)+    -- Drag standalone pane 30 whose pvTitle is ""; its ghost label falls back to pgTabTitle ("Tab-30").+    bodyR <- rectOf "body-30"+    let start = V2 (rectX bodyR + rectW bodyR / 2) (rectY bodyR + rectH bodyR / 2)+    _ <- press (At start) >> moveTo (At (V2 (rectX bodyR - 120) (rectY bodyR + 80)))+    check =<< textShown "Tab-30"+    _ <- release >> settle+    pure ()+  -- Pure GridNode tree helpers round-trip cleanly.+  let t0 = Pane 1+      t1 = treeSplit 1 100 AxisV False 2 t0+      t2 = treeAddTab 1 200 Nothing 3 t1+      t3 = treeSelectTab 1 t2+  assertEq failed [1, 3, 2] (treePanes t2)+  assertEq failed (Just (Split 100 AxisV 0.5 (PaneTabs 200 [1, 3] 1) (Pane 2))) (Just t3)+  assertEq failed (Just (Split 100 AxisV 0.5 (Pane 1) (Pane 2))) (treeRemovePane 3 t3)+  assertEq failed (Just (Pane 2)) (treeRemovePane 1 (Split 100 AxisV 0.5 (Pane 1) (Pane 2)))+  assertEq failed Nothing (treeRemovePane 1 (Pane 1))
+ test/integration/Cases/Passes.hs view
@@ -0,0 +1,221 @@+{-# OPTIONS_GHC -O0 #-}+{-# LANGUAGE OverloadedRecordDot #-}++-- | What one interaction costs: view passes in the frame that saw it, the+-- kind of damage it produced, and the frames that followed before the view+-- settled. Each row runs on a fresh context. Also what every view run+-- starts from.+module Cases.Passes (tests) where++import Spec+import Data.Primitive.PrimVar (readPrimVar)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO.Utf8 qualified as TIO+import GHC.Generics (Generic)+import NanoUI.Internal.Context (Context (..), ExplainState (..), InputMethodRequest (..))+import NanoUI.Internal.Context.Types (readContainerStack, writeContainerStack)+import NanoUI.Internal.Id.Cursor (readIdCursor)+import NanoUI.Internal.Layout.Arena (arenaCount)+import System.Directory (doesDirectoryExist)+import System.FilePath ((</>))++-- | A model kept whole in one Var, for the rows that focus its fields.+data Model = Model {title :: !Text, volume :: !Float, name :: !Text}+  deriving (Eq, Generic)++data Entry = Entry {rowId :: !Int, rowName :: !Text, rowDone :: !Bool}+  deriving (Eq, Generic)++rows20 :: [Entry]+rows20 = [Entry i ("Row " <> T.pack (show i)) False | i <- [0 .. 19]]++-- | The response of the fourth row a view collects, after the view runs.+fourth :: IORef [Response] -> NanoUI () -> NanoUI Response+fourth hits ui = do+  liftIO (writeIORef hits [])+  ui+  rs <- liftIO (readIORef hits)+  pure (reverse rs !! 3)++tests :: [Spec]+tests =+  [ spec "passes-per-interaction" runPassesTest+  , spec "per-build-reset" runPerBuildResetTest+  ]++-- | Each 'Context' field "NanoUI.Internal.Context.Types" tags as reset by+-- @resetUiBuild@, shown. A field tagged there needs an entry here.+perBuild :: Context -> IO [(String, String)]+perBuild ctx =+  mapM sequenceA+    [ ("ctxNodeArena", show <$> arenaCount (ctxNodeArena ctx))+    , ("ctxHotId", show <$> readIORef (ctxHotId ctx))+    , ("ctxInputMethod", show <$> readIORef (ctxInputMethod ctx))+    , ("ctxIdCursor", show <$> readIdCursor (ctxIdCursor ctx))+    , ("ctxExplain", show . esScopes <$> readIORef (ctxExplain ctx))+    , ("ctxContainerStack", show <$> readContainerStack (ctxContainerStack ctx))+    , ("ctxFocusablesCount", show <$> readPrimVar (ctxFocusablesCount ctx))+    , ("ctxCursorZones", show <$> readIORef (ctxCursorZones ctx))+    , ("ctxCursorRegions", show <$> readIORef (ctxCursorRegions ctx))+    , ("ctxChildWindows", show . length <$> readIORef (ctxChildWindows ctx))+    ]++-- | Every view run starts with each per-build field at its value in a fresh+-- context. The view sets each field (a button, a native window, writes at+-- its end) and the pointer hovers the button, so between frames none is at+-- that value. The number of fields checked must match the number of tags in+-- the 'Context' record.+runPerBuildResetTest :: Context -> IORef Int -> IO ()+runPerBuildResetTest ctx failed = do+  fresh <- perBuild ctx+  starts <- newIORef []+  let view = do+        c <- askContext+        liftIO (perBuild c >>= \s -> modifyIORef starts (s :))+        _ <- button' "Press"+        nativeWindow (constVar True) defaultWindowSettings (pure ())+        liftIO $ do+          -- For the focused widget, which the frame's end keeps.+          focus <- readIORef (ctxFocusId c)+          writeIORef (ctxInputMethod c) (Just (InputMethodRequest focus Nothing InputNormal))+          modifyIORef' (ctxExplain c) (\es -> es {esScopes = [(0, 1)]})+          writeContainerStack (ctxContainerStack c) [0]+          writeIORef (ctxCursorZones c) [(Rect 0 0 1 1, UiCursorMove)]+          writeIORef (ctxCursorRegions c) [(0, 1, UiCursorMove)]+      inp = withInput 400 300+  _ <- runFrame ctx inp view+  buttons <- nodesOfType NodeButton ctx+  let over = case buttons of+        (_, r) : _ -> inp {inputMousePos = spanCenter r}+        [] -> inp+  replicateM_ 2 (runFrame ctx over view)+  between <- perBuild ctx+  _ <- runFrame ctx over view+  seen <- reverse <$> readIORef starts+  forM_ (zip [1 :: Int ..] seen) $ \(i, s) ->+    forM_ (zip fresh s) $ \((name, want), (_, got)) ->+      when (want /= got) $ complain ("view run " <> show i <> " starts with " <> name <> " = " <> got <> ", not " <> want)+  forM_ (zip fresh between) $ \((name, want), (_, got)) ->+    when (want == got) $ complain ("the test view leaves " <> name <> " at its initial value " <> want)+  root : _ <- filterM doesDirectoryExist ["lib", "packages/nano-ui/lib"]+  src <- TIO.readFile (root </> "NanoUI" </> "Internal" </> "Context" </> "Types.hs")+  let tags = T.count "Reset by @resetUiBuild@." (T.unwords (filter (/= "--") (T.words src)))+  when (tags /= length fresh) $+    complain (show tags <> " Context fields are tagged as reset per build; this test checks " <> show (length fresh))+  where+    complain msg = putStrLn ("  " <> msg) >> bump failed++data Kind = Full | Clip | NoDamage+  deriving (Eq, Show)++kindOf :: Damage -> Kind+kindOf DamageFull = Full+kindOf d+  | damageIsEmpty d = NoDamage+  | otherwise = Clip++-- | Passes, damage kind and follow-up frames.+type Cost = (Int, Kind, Int)++costOf :: FrameCost -> Cost+costOf (FrameCost p d f) = (p, kindOf d, f)++inp0 :: Input+inp0 = (withInputOff 400 300) {inputDeltaTime = 0.5}++-- | One keystroke into the view's first focusable, a text field.+typeInto :: NanoUI a -> IO Cost+typeInto ui = do+  ctx <- newContext+  warmupFocused ctx inp0 ui+  _ <- run2Frames ctx inp0 ui+  costOf . snd <$> frameCost ctx (inp0 {inputChars = "a"}) inp0 ui++-- | A press on the response the view returns, then a measured release, or+-- a held move 30 px right when @dragging@.+pressOn :: Bool -> NanoUI Response -> IO Cost+pressOn dragging ui = do+  ctx <- newContext+  pos@(V2 x y) <- centerOf <$> warmup2 ctx inp0 ui+  let hover = inp0 {inputMousePos = pos}+      moved = holdAt hover (V2 (x + 30) y)+      (next, after) = if dragging then (moved, moved) else (releaseAt (pressAt hover pos), hover)+  _ <- run2Frames ctx hover ui+  _ <- runFrame ctx (pressAt hover pos) ui+  costOf . snd <$> frameCost ctx next after ui++clickOn, dragOn :: NanoUI Response -> IO Cost+clickOn = pressOn False+dragOn = pressOn True++-- | A frame with no input, once the view has settled.+idleFrame :: NanoUI a -> IO Cost+idleFrame ui = do+  ctx <- newContext+  _ <- run2Frames ctx inp0 ui+  costOf . snd <$> frameCost ctx inp0 inp0 ui++-- | The hooks Vars replaced (23217753) cost (2, Full, 1) for a bound field.+runPassesTest :: Context -> IORef Int -> IO ()+runPassesTest _ failed = do+  let fresh :: a -> (Var a -> IO b) -> IO b+      fresh x k = newVar x >>= k+      counter above v = column $ do+        when above (label . T.pack . show =<< readVar v)+        r <- button' "+"+        when (respClicked r) (modifyVar v (+ (1 :: Int)))+        unless above (label . T.pack . show =<< readVar v)+        pure r+      -- A list in one Var, a checkbox per row and the row's name after it.+      checkRows xs = do+        v <- newVar xs+        hits <- newIORef []+        clickOn . fourth hits . column . forEachVar rowId v $ \r -> row $ do+          resp <- checkbox' "" r.rowDone+          label =<< readVar r.rowName+          liftIO (modifyIORef hits (resp :))+  rows <-+    sequence+      [ ("field", (1, Clip, 1),) <$> fresh "" (\v -> typeInto (column (textInput' v)))+      , ("field, label below", (1, Full, 1),) <$> fresh "" (\v -> typeInto (column (textInput' v <* (label =<< readVar v))))+      , ("field, label above", (2, Full, 1),) <$> fresh "" (\v -> typeInto (column ((label =<< readVar v) >> textInput' v)))+      , ("field read before, written after", (2, Clip, 1),) <$> fresh "" (\v -> typeInto (column (do x <- readVar v; (r, x') <- withValue x textInput'; writeVar v x'; pure r)))+      , ("withValue field", (1, Clip, 1),) <$> (newIORef ("" :: Text) >>= \ref -> typeInto (column (do x <- liftIO (readIORef ref); (r, x') <- withValue x textInput'; liftIO (writeIORef ref x'); pure r)))+      , ("slider", (1, Clip, 1),) <$> fresh 50 (\v -> dragOn (column (sliderWith' (fixedW 200) 0 100 v)))+      , ("checkbox", (1, Clip, 1),) <$> fresh False (\v -> clickOn (column (checkbox' "Opt" v)))+      , ("plain button", (1, Clip, 0),) <$> clickOn (column (button' "+"))+      , ("display above", (2, Clip, 0),) <$> fresh 0 (clickOn . counter True)+      , ("display below", (1, Clip, 0),) <$> fresh 0 (clickOn . counter False)+      , ("equal writes, idle", (1, NoDamage, 0),) <$> fresh "x" (\v -> idleFrame (column (writeVar v "x" >> textInput' v)))+      , -- One Var holding a record: a field read elsewhere is another part.+        ("model: field above slider", (1, Clip, 1),) <$> fresh (Model "t" 50 "") (\m -> dragOn (column (do label =<< readVar m.title; sliderWith' (fixedW 200) 0 100 m.volume)))+      , ("model: field below slider", (1, Clip, 1),) <$> fresh (Model "t" 50 "") (\m -> dragOn (column (sliderWith' (fixedW 200) 0 100 m.volume <* (label =<< readVar m.title))))+      , ("model: field above field", (1, Clip, 1),) <$> fresh (Model "t" 50 "") (\m -> typeInto (column (do label =<< readVar m.title; textInput' m.name)))+      , ("model: whole read above field", (2, Clip, 1),) <$> fresh (Model "t" 50 "") (\m -> typeInto (column (do x <- readVar m; label x.title; textInput' m.name)))+      , ("model: zoomVar part above field", (2, Clip, 1),) <$> fresh (Model "t" 50 "") (\m -> typeInto (column (do label =<< readVar (zoomVar (.title) (\t x -> x {title = t}) m); textInput' m.name)))+      , ("forEachVar rows: click row 3", (1, Clip, 1),) <$> checkRows rows20+      , -- Rows are told apart by one of 63 bits of their key's hash, so+        -- keys 64 apart, as from the 64th row on, share it: the earlier+        -- rows' checkboxes count as showing the one clicked.+        ("forEachVar rows, keys 64 apart: click row 3", (2, Clip, 1),) <$> checkRows (map (\e -> e {rowId = e.rowId * 64}) rows20)+      , ("withElemVars rows: click row 3", (2, Clip, 1),) <$> do+          v <- newVar rows20+          hits <- newIORef []+          clickOn . fourth hits . column . withElemVars rowId v $ \xs at -> forM_ xs $ \x -> withKey (rowId x) . row $ do+            resp <- checkbox' "" (at x).rowDone+            label =<< readVar (at x).rowName+            liftIO (modifyIORef hits (resp :))+      , -- A row that changes its own key changes the list's order of keys,+        -- which forEachVar laid the rows out by.+        ("forEachVar row rekeys itself", (2, Full, 0),) <$> do+          v <- newVar rows20+          hits <- newIORef []+          clickOn . fourth hits . column . forEachVar rowId v $ \r -> row $ do+            resp <- button' "Rekey"+            when (respClicked resp) (modifyVar r.rowId (+ 100))+            liftIO (modifyIORef hits (resp :))+      ]+  forM_ rows $ \(name, expected, actual) -> do+    putStrLn ("  " <> name <> ": " <> show actual)+    when (expected /= actual) (putStrLn ("  expected " <> show expected) >> bump failed)
+ test/integration/Cases/Paths.hs view
@@ -0,0 +1,682 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Paths (tests) where++import Spec+import Data.Foldable (toList)+import Data.IntMap.Strict qualified as IM+import Data.Primitive.PrimArray (PrimArray, indexPrimArray, primArrayFromList, primArrayToList, sizeofPrimArray)+import GHC.Stack (HasCallStack)+import NanoUI.Internal.Context (Context (..), DrawingCacheState (..), setDrawSnapScale)+import NanoUI.Internal.Canvas (emitOp)+import NanoUI.Internal.Path (fillPathOps)+import NanoUI.Internal.Context.Types (CustomDrawOpCacheEntry (..))+import NanoUI.Path qualified as P++tests :: [Spec]+tests =+  [ spec "path-curves" runCurvesTest+  , spec "path-strokes" runStrokeTest+  , spec "path-fill-triangulation" runFillTriangulationTest+  , spec "path-transforms" runTransformTest+  , spec "path-degenerate" runDegenerateTest+  , spec "path-fill-holes" runFillHolesTest+  , spec "path-stroke-dashes" runDashTest+  , spec "path-stroke-joins" runJoinGeometryTest+  , spec "path-gradients" runGradientTest+  , spec "path-shapes-and-clip" runShapesAndClipTest+  , spec "path-canvas-frames" runCanvasFramesTest+  ]++red, black, blue, green, white :: Color+red = colorRGBA 220 40 40 255+black = colorBlack+blue = colorRGBA 0 0 255 255+green = colorRGBA 0 255 0 255+white = colorWhite++-- | A canvas block's ops, flattened at @scale@ device pixels per logical pixel.+opsAt :: Float -> CanvasM () -> [DrawOp]+opsAt scale = toList . runCanvasFor (CustomDrawContext False False False False False defaultTheme (monospaceMetrics 16) {fmSnapScale = scale})++pairs :: PrimArray Float -> [V2]+pairs pts = [V2 (indexPrimArray pts (2 * i)) (indexPrimArray pts (2 * i + 1)) | i <- [0 .. sizeofPrimArray pts `div` 2 - 1]]++-- | Each stroke's points and whether it closes.+strokes :: [DrawOp] -> [([V2], Bool)]+strokes ops = [(pairs pts, closed) | StrokePolyline pts _ closed _ _ _ _ <- ops]++-- | Each filled polygon's outline and triangles.+fills :: [DrawOp] -> [([V2], [Int])]+fills ops = [(pairs pts, primArrayToList tris) | FillPolygon pts _ tris _ <- ops]++-- | A path's strokes (width 1) and fills, at scale 1.+stroked :: P.Path -> [([V2], Bool)]+stroked path = strokes (opsAt 1 (drawStrokePath path 1 black))++filled :: P.Path -> [([V2], [Int])]+filled path = fills (opsAt 1 (drawPath path red))++-- | The ops of a stroke with this style and a solid paint.+styledStroke :: P.Stroke -> P.Path -> [DrawOp]+styledStroke st path = opsAt 1 (drawStrokePathWith st path (P.Solid black))++-- | Check the single element; fail if there is not exactly one.+single :: HasCallStack => IORef Int -> [a] -> (a -> IO ()) -> IO ()+single failed xs k = case xs of [x] -> k x; _ -> assertEq failed 1 (length xs)++-- | Require points pairwise within @eps@, showing both lists otherwise.+assertNear :: HasCallStack => IORef Int -> Float -> [V2] -> [V2] -> IO ()+assertNear failed eps want got = unless (length want == length got && and (zipWith (near eps) want got)) (assertEq failed want got)++dist :: V2 -> V2 -> Float+dist (V2 x0 y0) (V2 x1 y1) = sqrt ((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0))++near :: Float -> V2 -> V2 -> Bool+near eps a b = dist a b <= eps++xsOf, ysOf :: [V2] -> [Float]+xsOf pts = [x | V2 x _ <- pts]+ysOf pts = [y | V2 _ y <- pts]++-- | A line's first and last points.+ends :: [V2] -> [V2]+ends pts = take 1 pts ++ drop (length pts - 1) pts++triples :: [a] -> [(a, a, a)]+triples (a : b : c : rest) = (a, b, c) : triples rest+triples _ = []++-- | Distance from a point to an open polyline.+polyDist :: [V2] -> V2 -> Float+polyDist ps p@(V2 px py) = minimum (zipWith seg ps (drop 1 ps))+  where+    seg (V2 ax ay) (V2 bx by) =+      let (dx, dy) = (bx - ax, by - ay)+          t = max 0 (min 1 (((px - ax) * dx + (py - ay) * dy) / max 1e-12 (dx * dx + dy * dy)))+       in dist p (V2 (ax + t * dx) (ay + t * dy))++-- | Signed shoelace area, positive for a ring that is clockwise on screen.+polyArea :: [V2] -> Float+polyArea ps = sum [x0 * y1 - x1 * y0 | (V2 x0 y0, V2 x1 y1) <- zip ps (drop 1 ps ++ take 1 ps)] / 2++-- | Total triangle area, and whether the index list is well formed.+covered :: [V2] -> [Int] -> (Float, Bool)+covered ps tris = (sum [area (ps !! a, ps !! b, ps !! c) | (a, b, c) <- triples tris], all (\i -> i >= 0 && i < length ps) tris && length tris `mod` 3 == 0)+  where+    area (V2 x0 y0, V2 x1 y1, V2 x2 y2) = abs ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) / 2++-- | Deterministic pseudo-random number in [0, 1).+rnd :: Int -> Float+rnd k = let v = sin (fromIntegral k * 12.9898) * 43758.5453 in v - fromIntegral (floor v :: Int)++-- | Evaluate the Bezier curve with these control points at @t@.+bezier :: [V2] -> Float -> V2+bezier [p] _ = p+bezier ps t = bezier (zipWith (\(V2 x0 y0) (V2 x1 y1) -> V2 (x0 + t * (x1 - x0)) (y0 + t * (y1 - y0))) ps (drop 1 ps)) t++-- | Whether a point lies on the axis-aligned ellipse centred at @c@ with radii @rx@ and @ry@.+onEllipse :: V2 -> Float -> Float -> V2 -> Bool+onEllipse (V2 cx cy) rx ry (V2 x y) = abs (((x - cx) / rx) ^ (2 :: Int) + ((y - cy) / ry) ^ (2 :: Int) - 1) < 1e-3++-- | Curves flatten to within a quarter device pixel at every scale (and not+-- much finer), keeping their ends; SVG arc flags pick the side and size.+runCurvesTest :: Context -> IORef Int -> IO ()+runCurvesTest _ failed = do+  let centre = V2 100 100+      ring scale = strokes (opsAt scale (drawStrokePath (P.circle centre 50) 1 black))+      count scale = sum [length pts | (pts, _) <- ring scale]+  forM_ [1, 2, 3] $ \scale -> single failed (ring scale) $ \(pts, closed) -> do+    let tol = 0.25 / scale+        sags = [50 - dist centre (V2 ((ax + bx) / 2) ((ay + by) / 2)) | (V2 ax ay, V2 bx by) <- zip pts (drop 1 pts ++ take 1 pts)]+    assert failed (closed && all (\p -> abs (dist centre p - 50) < 1e-3) pts && all (<= tol + 1e-3) sags)+    assertGt failed (maximum sags) (tol / 2)+  assert failed (count 3 > count 2 && count 2 > count 1)+  let (p0, c1, c2, q, p3) = (V2 10 10, V2 400 (-100), V2 (-200) 300, V2 150 (-200), V2 300 300)+      samples = [fromIntegral k / 2000 | k <- [0 .. 2000 :: Int]]+  forM_ [(s, c) | s <- [1, 2], c <- [(P.cubicTo c1 c2 p3, [p0, c1, c2, p3]), (P.quadTo q p3, [p0, q, p3])]] $ \(scale, (seg, ctrl)) ->+    single failed (strokes (opsAt scale (drawStrokePath (P.moveTo p0 <> seg) 1 black))) $ \(pts, closed) -> do+      assertEq failed (False, [p0, p3]) (closed, ends pts)+      assertLt failed (maximum (map (polyDist pts . bezier ctrl) samples)) (0.25 / scale + 1e-3)+      -- Every emitted point lies on the curve.+      assert failed (all (\p -> minimum (map (dist p . bezier ctrl) samples) < 1) pts)+  -- A straight "curve" is one chord.+  single failed (stroked (P.moveTo p0 <> P.cubicTo (V2 20 10) (V2 30 10) (V2 40 10))) $ \(pts, _) -> assertEq failed [p0, V2 40 10] pts+  let c = V2 50 50+      onCircle a = V2 (50 + 30 * cos a) (50 + 30 * sin a)+      svgArc radius large clockwise = map fst (stroked (P.moveTo (V2 0 0) <> P.arcTo (V2 radius radius) 0 large clockwise (V2 20 0)))+      onSmallCircle = all (\p -> abs (dist (V2 10 0) p - 10) < 1e-3)+  single failed (stroked (P.arc c 30 0.3 1.2)) $ \(pts, closed) -> do+    assert failed (not closed)+    assertNear failed 1e-3 [onCircle 0.3, onCircle 1.5] (ends pts)+  -- A negative sweep turns the other way.+  single failed (stroked (P.arc c 30 0.3 (-1.2))) $ \(pts, _) -> do+    assertNear failed 1e-3 [onCircle (-0.9)] (drop 1 (ends pts))+    assert failed (all (<= 50 + 30 * sin 0.3 + 1e-3) (ysOf pts))+  -- An arc after a moveTo draws a line to the arc's start (a pie slice).+  single failed (filled (P.moveTo c <> P.arc c 30 0 (pi / 2) <> P.close)) $ \(pts, _) -> do+    assertEq failed [c] (take 1 pts)+    assertLt failed (abs (abs (polyArea pts) - 30 * 30 * pi / 4)) 30+  -- Clockwise goes over the top; small radii scale up to span the ends; the+  -- large arc bulges further; a zero radius is a line.+  single failed (svgArc 10 False True) $ \pts -> do+    assertEq failed [V2 0 0, V2 20 0] (ends pts)+    assert failed (onSmallCircle pts && minimum (ysOf pts) < -9.7)+  single failed (svgArc 10 False False) $ \pts -> assertGt failed (maximum (ysOf pts)) 9.7+  single failed (svgArc 2 False True) $ assert failed . onSmallCircle+  single failed (svgArc 20 True True) $ \pts -> assertLt failed (minimum (ysOf pts)) (-37)+  single failed (svgArc 20 False True) $ \pts -> assertGt failed (minimum (ysOf pts)) (-2.7)+  single failed (svgArc 0 False True) $ assertEq failed [V2 0 0, V2 20 0]+  -- An elliptical arc follows the ellipse's rotation.+  single failed (stroked (P.ellipticalArc c (V2 40 20) (pi / 2) 0 pi)) $ \(pts, _) -> do+    assertNear failed 1e-3 [V2 50 90, V2 50 10] (ends pts)+    assert failed (all (onEllipse c 20 40) pts)+    assertLt failed (abs (minimum (xsOf pts) - 30)) 0.3++-- | Open and closed strokes, subpaths, and line caps.+runStrokeTest :: Context -> IORef Int -> IO ()+runStrokeTest _ failed = do+  let (a, b, c) = (V2 0 0, V2 10 0, V2 10 10)+      plain ops = [(primArrayToList pts, w, closed) | StrokePolyline pts w closed _ _ _ _ <- ops]+      line w path = plain (opsAt 1 (drawStrokePath path w black))+      capped cap = styledStroke (P.stroke 4) {P.strokeCap = cap}+      caps ops = [cap | StrokePolyline _ _ _ cap _ _ _ <- ops]+  assertEq failed [([0, 0, 10, 0, 10, 10], 3, False)] (line 3 (P.polyline [a, b, c]))+  -- Closing drops a last point that repeats the first.+  assertEq failed [([0, 0, 10, 0, 10, 10], 2, True)] (line 2 (P.moveTo a <> P.lineTo b <> P.lineTo c <> P.lineTo a <> P.close))+  -- Returning to the start without closing leaves the line open.+  assertEq failed [([0, 0, 10, 0, 10, 10, 0, 0], 2, False)] (line 2 (P.moveTo a <> P.lineTo b <> P.lineTo c <> P.lineTo a))+  -- Each subpath is a separate polyline. A close returns to the subpath's start.+  assertEq failed [([0, 0, 10, 0, 10, 10], 1, True), ([0, 0, 0, 20], 1, False)] (line 1 (P.polygon [a, b, c] <> P.lineTo (V2 0 20)))+  assertEq failed 2 (length (opsAt 1 (drawStrokePath (P.polyline [a, b] <> P.polyline [c, V2 20 20]) 1 black)))+  -- Caps are carried on the polyline op. A closed subpath has none, and a+  -- closed two-point subpath becomes an open line with butt caps.+  forM_ [P.ButtCap, P.SquareCap, P.RoundCap] $ \cap -> do+    let ops = capped cap (P.polyline [a, b])+    assertEq failed ([([0, 0, 10, 0], 4, False)], [cap]) (plain ops, caps ops)+  assertEq failed [([0, 0, 10, 0, 10, 10], 4, True)] (plain (capped P.RoundCap (P.polygon [a, b, c])))+  assertEq failed [P.ButtCap] (caps (capped P.RoundCap (P.moveTo a <> P.lineTo b <> P.close)))+  -- A fill closes an open subpath.+  assertEq failed [([a, b, c], [0, 1, 2])] (filled (P.polyline [a, b, c]))++-- | Each subpath fills as one polygon whose triangles cover exactly its area, in either winding.+runFillTriangulationTest :: Context -> IORef Int -> IO ()+runFillTriangulationTest _ failed = do+  let c = V2 60 60+      -- @k@ corners around the centre; corner @i@ is at distance @rad i@.+      ring k rad = [V2 (60 + rad i * cos a) (60 + rad i * sin a) | i <- [0 .. k - 1 :: Int], let a = 2 * pi * fromIntegral i / fromIntegral k]+      star = ring 10 (\i -> if even i then 50 else 20)+      ell = [V2 0 0, V2 60 0, V2 60 20, V2 20 20, V2 20 60, V2 0 60]+      comb = [V2 0 0, V2 100 0, V2 100 40, V2 80 40, V2 80 10, V2 60 10, V2 60 40, V2 40 40, V2 40 10, V2 20 10, V2 20 40, V2 0 40]+      shapes =+        [ ("circle", P.circle c 50), ("ellipse", P.ellipse c (V2 50 20)), ("rounded rect", P.roundedRect (Rect 0 0 100 60) 12)+        , ("hexagon", P.polygon (ring 6 (const 40))), ("star", P.polygon star), ("star anticlockwise", P.polygon (reverse star))+        , ("L", P.polygon ell), ("comb", P.polygon comb)+        , ("band", P.arc c 50 0 (1.5 * pi) <> P.arc c 25 (1.5 * pi) (-1.5 * pi) <> P.close)+        , ("blob", P.moveTo (V2 0 0) <> P.cubicTo (V2 60 (-30)) (V2 100 30) (V2 100 60) <> P.quadTo (V2 50 100) (V2 0 60) <> P.close)+          -- A one-slice pie chart: out to the rim and back along the same radius.+        , ("whole pie", P.moveTo c <> P.arc c 50 (-pi / 2) (2 * pi) <> P.close)+        , ("pie over half", P.moveTo c <> P.arc c 50 0.3 (1.6 * pi) <> P.close)+        ]+          -- Random simple star polygons with 5 to 64 corners.+          <> [("random star " <> show seed, P.polygon (ring (5 + seed `mod` 60) (\i -> 5 + 50 * rnd (seed * 1000 + i)))) | seed <- [1 .. 60 :: Int]]+          -- Large rings, where ear clipping looks up blockers in its grid:+          -- stars, and an area chart's top edge closed along a baseline.+          <> [("random star of " <> show k, P.polygon (ring k (\i -> 5 + 50 * rnd (k + i)))) | k <- [300, 2000]]+          <> [("area of 2000 samples", P.polygon ([V2 (fromIntegral i * 0.05) (10 + 30 * rnd (7 * i)) | i <- [0 .. 1999 :: Int]] <> [V2 99.95 60, V2 0 60]))]+  forM_ shapes $ \(name, shape) ->+    assertEq failed (name, [True]) . (,) name $+      [ inRange && length tris == 3 * (length pts - 2) && abs (area - want) <= 1e-3 * want+      | (pts, tris) <- filled shape+      , let (area, inRange) = covered pts tris+            want = abs (polyArea pts)+      ]+  -- Filled area matches the shape: exactly for straight sides, within tolerance for curves.+  let areaOf shape = sum [abs (polyArea pts) | (pts, _) <- filled shape]+  assertLt failed (abs (areaOf (P.polygon ell) - 2000)) 1e-3+  assertLt failed (abs (areaOf (P.polygon comb) - 2800)) 1e-3+  assertLt failed (abs (areaOf (P.circle c 50) - pi * 50 * 50)) (2 * pi * 50 * 0.25)+  assertLt failed (abs (areaOf (P.roundedRect (Rect 0 0 100 60) 12) - (6000 - (4 - pi) * 144))) (2 * pi * 12 * 0.25)+  -- Disjoint subpaths fill as separate polygons. Under the non-zero rule, a+  -- subpath inside another with the same winding merges into it.+  assertEq failed [2, 1] [length (filled (P.rect r0 <> P.rect r1)) | (r0, r1) <- [(Rect 0 0 10 10, Rect 20 0 10 10), (Rect 0 0 100 100, Rect 20 20 10 10)]]++-- | Transforms compose inside out, apply before flattening, and scale stroke+-- widths. Non-path canvas ops follow a transform as far as their shape allows.+runTransformTest :: Context -> IORef Int -> IO ()+runTransformTest _ failed = do+  let tri = [V2 1 0, V2 2 0, V2 2 1]+      triangle = drawPath (P.polygon tri) red+      outline block = concat [pts | (pts, _) <- fills (opsAt 1 block)]+      at = map . P.transformPoint+      -- Rotate a quarter turn, (x, y) to (-y, x), then scale.+      rotatedThenScaled = [V2 (-2 * y) (3 * x) | V2 x y <- tri]+      points block = sum [length pts | (pts, _) <- strokes (opsAt 1 block)]+      circle r = drawStrokePath (P.circle (V2 0 0) r) 1 black+      widths t w = [w' | StrokePolyline _ w' _ _ _ _ _ <- opsAt 1 (withTransform t (drawStrokePath (P.polyline [V2 0 0, V2 1 1]) w black))]+  forM_+    [ (rotatedThenScaled, outline (withTransform (P.scale 2 3) (withTransform (P.rotate (pi / 2)) triangle)))+    , (rotatedThenScaled, outline (withTransform (P.scale 2 3 <> P.rotate (pi / 2)) triangle))+    , ([V2 (-3 * y) (2 * x) | V2 x y <- tri], outline (withTransform (P.rotate (pi / 2) <> P.scale 2 3) triangle))+    , (rotatedThenScaled, at (P.scale 2 3 <> P.rotate (pi / 2)) tri)+    , ([V2 9 9], at (P.rotateAround (V2 9 9) 1.1) [V2 9 9]), ([V2 13 4], at (P.translate 3 4 <> P.affine 1 0 0 1 10 0) [V2 0 0])+    , (tri, outline (withTransform mempty triangle))+    , -- A transform applies only inside its block.+      (at (P.translate 5 0) tri <> tri, outline (withTransform (P.translate 5 0) triangle >> triangle))+    ]+    $ uncurry (assertNear failed 1e-4)+  -- Flattening uses the transformed size.+  assertGt failed (points (withTransform (P.scale 10 10) (circle 10))) (points (circle 10))+  assertEq failed (points (circle 100)) (points (withTransform (P.scale 10 10) (circle 10)))+  assertEq failed (points (circle 100)) (points (withTransform (P.scale 10 1) (circle 10)))+  -- A stroke's width scales with the transform.+  assertEq failed ([6], [4]) (widths (P.scale 3 3) 2, widths (P.scale 8 2) 1)+  let under t block = opsAt 1 (withTransform t block)+      r0 = Rect 10 20 10 20+      corners = [[tl, tr, br, bl] | [FillQuadGradient _ tl tr br bl] <- [under (P.rotate pi) (drawQuadGradient (Rect 0 0 10 10) red green blue white)]]+      -- If the block is a single rotated image: its centre, size, angle and UVs.+      turned block = [([V2 (x + w / 2) (y + h / 2), V2 w h], angle, (u0, v0, u1, v1)) | [DrawImage (Rect x y w h) angle _ u0 v0 u1 v1 _] <- [block], angle /= 0]+      turnedImage r angle = drawImageWith (imageDraw r (ImageId 7)) {imageAngle = angle, imageTint = red}+      hi = drawText (V2 4 0) AlignCenter AlignMiddle "hi" red+  -- A flip keeps rect sizes positive and mirrors gradients and images.+  assertEq failed [] . map fst . filter (not . snd) . zip [0 :: Int ..] $+    [ [FillRect (Rect 15 25 10 20) red] == under (P.translate 5 5) (drawRect r0 red)+    , [FillRect (Rect (-20) 20 10 20) red] == under (P.scale (-1) 1) (drawRect r0 red)+    , [FillRoundedRect (Rect 20 40 20 40) 8 red] == under (P.scale 2 2) (drawRoundedRect r0 4 red)+    , [DrawText 9 5 0.5 0.5 "hi" red] == under (P.translate 5 5) hi+      -- A rotation leaves text as plain 'DrawText'; a scale scales the text.+    , case under (P.rotate 0.3) hi of [DrawText {}] -> True; _ -> False+    , [DrawTextAligned 17 5 0.5 0.5 3 defaultTextFont "hi" red] == under (P.translate 5 5 <> P.scale 3 3) hi+    , [DrawTextAligned 17 5 0 1 6 defaultTextFont {textFontSize = 12} "hi" red]+        == under (P.translate 5 5 <> P.scale 3 3) (withTransform (P.scale 2 2) (drawTextWith defaultTextFont {textFontSize = 12} (V2 2 0) AlignStart AlignTop "hi" red))+    , [FillQuadGradient (Rect (-10) 0 10 10) blue red red blue] == under (P.scale (-1) 1) (drawLinearGradientH (Rect 0 0 10 10) red blue)+    , [FillQuadGradient (Rect 0 (-10) 10 10) blue blue red red] == under (P.scale 1 (-1)) (drawLinearGradientV (Rect 0 0 10 10) red blue)+    , [DrawImageRect (Rect (-10) 0 10 10) 7 1 0 0 1 red] == under (P.scale (-1) 1) (drawImage (Rect 0 0 10 10) (ImageId 7) red)+      -- A rect of negative size draws as it does untransformed: a quad+      -- gradient not at all, an image mirrored.+    , null (under (P.translate 5 0) (drawQuadGradient (Rect 50 0 (-20) 10) red green blue white))+    , [DrawImageRect (Rect 25 0 40 40) 7 1 0 0 1 red] == under (P.translate 5 0) (drawImage (Rect 60 0 (-40) 40) (ImageId 7) red)+    , [DrawImageRect (Rect (-60) 0 40 40) 7 0 0 1 1 red] == under (P.scale (-1) 1) (drawImage (Rect 60 0 (-40) 40) (ImageId 7) red)+      -- A half turn rotates a gradient's corner colours, and so does a+      -- quarter turn of a linear gradient.+    , corners == [[blue, white, red, green]]+    , [[red, red, blue, blue]] == [[tl, tr, br, bl] | [FillQuadGradient _ tl tr br bl] <- [under (P.rotate (pi / 2)) (drawLinearGradientH (Rect 0 0 10 10) red blue)]]+      -- A quarter turn would move the quad's diagonal, which changes a blend+      -- of four colours, so that quad becomes a polygon with its corner colours.+    , [[red, green, blue, white]]+        == [map Color (primArrayToList cs) | [FillPolygon _ _ _ (Shaded cs)] <- [under (P.rotate (pi / 2)) (drawQuadGradient (Rect 0 0 10 10) red green blue white)]]+    ]+  -- A quarter turn keeps rects as rects.+  assertNear failed 1e-4 [V2 (-20) 0, V2 20 10] $+    concat [[V2 x y, V2 w h] | [FillRect (Rect x y w h) col] <- [under (P.rotate (pi / 2)) (drawRect (Rect 0 0 10 20) red)], col == red]+  assertNear failed 1e-4 [V2 2 0, V2 2 20, V2 4 0] $+    concat [[V2 x0 y0, V2 x1 y1, V2 w 0] | [StrokeLineAA x0 y0 x1 y1 w col] <- [under (P.translate 2 0 <> P.rotate (pi / 2) <> P.scale 4 4) (drawStrokeAA (V2 0 0) (V2 5 0) 1 red)], col == red]+  -- A rect at any other angle becomes a polygon of the same area.+  single failed (fills (under (P.rotateAround (V2 15 30) (pi / 5)) (drawRect r0 red))) $ \(pts, tris) -> do+    assertEq failed 4 (length pts)+    assertLt failed (abs (fst (covered pts tris) - 200)) 1e-2+    assertNear failed 1e-3 [V2 15 30] [V2 (sum (xsOf pts) / 4) (sum (ysOf pts) / 4)]+  -- A circle stays a circle under rotation and uniform scale; a non-uniform scale makes an ellipse.+  assertNear failed 1e-4 [V2 20 0, V2 10 0] $+    concat [[V2 x y, V2 r 0] | [FillCircle x y r _] <- [under (P.rotate (pi / 2) <> P.scale 2 2) (drawCircle (V2 0 (-10)) 5 red)]]+  single failed (fills (under (P.scale 2 1) (drawCircle (V2 10 10) 5 red))) $ assert failed . all (onEllipse (V2 20 10) 10 5) . fst+  single failed (strokes (under (P.scale 1 2) (drawStrokeCircle (V2 0 0) 10 2 red))) $ \(pts, closed) ->+    assert failed (closed && all (onEllipse (V2 0 0) 9 18) pts)+  -- A rotation rotates an image, adding to its own angle; a flip mirrors it.+  forM_+    [ (under (P.translate 30 0 <> P.rotate (pi / 2)) (drawImage (Rect 0 0 20 10) (ImageId 7) red), [V2 25 10, V2 20 10], pi / 2, (0, 0, 1, 1))+    , (under (P.rotate 0.3 <> P.scale 2 2) (turnedImage (Rect 0 0 10 10) 0.2), [V2 (10 * cos 0.3 - 10 * sin 0.3) (10 * sin 0.3 + 10 * cos 0.3), V2 20 20], 0.5, (0, 0, 1, 1))+    , (under (P.scale (-1) 1) (turnedImage (Rect 0 0 10 10) 0.2), [V2 (-5) 5, V2 10 10], pi - 0.2, (0, 1, 1, 0))+    ]+    $ \(block, want, wantAngle, uvs) -> single failed (turned block) $ \(got, angle, uv) -> do+      assertNear failed 1e-3 want got+      assert failed (abs (angle - wantAngle) < 1e-5 && uv == uvs)++-- | Degenerate paths draw nothing, or only their valid parts. Output never+-- contains NaN or infinity, and point counts stay bounded.+runDegenerateTest :: Context -> IORef Int -> IO ()+runDegenerateTest _ failed = do+  let nan = 0 / 0 :: Float+      inf = 1 / 0 :: Float+      p = V2 5 5+      numbersIn op = case op of+        FillPolygon pts _ _ _ -> primArrayToList pts+        StrokePolyline pts w _ _ _ _ _ -> w : primArrayToList pts+        FillRect (Rect x y w h) _ -> [x, y, w, h]+        FillCircle x y r _ -> [x, y, r]+        _ -> []+      sound ops = all (\v -> not (isNaN v || isInfinite v)) (concatMap numbersIn ops)+      both path = opsAt 1 (drawPath path red >> drawStrokePath path 2 black)+      lines' = map fst . stroked+      segment w = opsAt 1 (drawStrokePath (P.polyline [V2 0 0, V2 10 0]) w black)+  -- Zero lengths and radii, collinear points, NaNs, bad widths and NaN transforms draw nothing.+  assertEq failed [] . map fst . filter (not . null . snd) . zip [0 :: Int ..] $+    [ both (P.moveTo p <> P.lineTo p <> P.lineTo p), both (P.moveTo p <> P.lineTo p <> P.close), both (P.circle p 0)+    , both (P.arc p 0 0 pi), both (P.moveTo p), both mempty, both (P.polygon [])+    , opsAt 1 (drawPath (P.polygon [V2 0 0, V2 5 0, V2 10 0]) red)+    , both (P.circle p nan), both (P.arc p 10 0 nan), segment nan, segment 0, segment (-1)+    , opsAt 1 (withTransform (P.scale nan 1) (drawPath (P.circle p 5) red >> drawRect (Rect 0 0 5 5) red >> drawCircle p 3 red))+    , opsAt 1 (withTransform (P.rotate inf) (drawPath (P.circle p 5) red))+    ]+  -- A zero-length subpath is a dot with round or square caps, and a lone+  -- move draws nothing.+  let capped cap path = [(pairs pts, c) | StrokePolyline pts _ _ c _ _ _ <- styledStroke (P.stroke 2) {P.strokeCap = cap} path]+  forM_ [P.RoundCap, P.SquareCap] $ \cap ->+    forM_ [P.moveTo p <> P.lineTo p, P.moveTo p <> P.close, P.circle p 0] $ \path ->+      single failed (capped cap path) $ \(ps, c) -> do+        assertEq failed cap c+        assert failed (case ps of [a, b] -> a == p && dist a b > 0 && dist a b < 0.01; _ -> False)+  assertEq failed [] (capped P.ButtCap (P.moveTo p <> P.lineTo p))+  assertEq failed [[V2 0 0, V2 10 0]] (map fst (capped P.RoundCap (P.moveTo p <> P.moveTo (V2 0 0) <> P.lineTo (V2 10 0) <> P.moveTo p)))+  -- Repeated points are dropped, and segments with NaN or infinity are skipped.+  assertEq failed [[V2 0 0, V2 10 0, V2 10 10]] (lines' (P.polyline [V2 0 0, V2 0 0, V2 10 0, V2 10 0, V2 10 10]))+  assertEq failed [[V2 0 0, V2 10 0]] (lines' (P.polyline [V2 0 0, V2 nan 3, V2 inf 0, V2 10 0]))+  assertEq failed [[V2 0 0, V2 10 0]] (lines' (P.moveTo (V2 0 0) <> P.cubicTo (V2 nan 0) (V2 1 1) (V2 2 2) <> P.arcTo (V2 inf 1) 0 False False (V2 3 3) <> P.lineTo (V2 10 0)))+  -- Huge shapes get a bounded point count; a sweep of many turns draws one turn.+  forM_ [P.circle p 1e7, P.moveTo (V2 0 0) <> P.cubicTo (V2 1e9 0) (V2 (-1e9) 1e9) (V2 1e9 1e9)] $ \path ->+    let n = sum (map length (lines' path)) in assert failed (n > 4 && n <= 1025)+  assert failed (opsAt 1 (drawPath (P.moveTo (V2 30 0) <> P.arc (V2 0 0) 30 0 (2 * pi)) red) == opsAt 1 (drawPath (P.moveTo (V2 30 0) <> P.arc (V2 0 0) 30 0 1e9) red))+  assert failed (opsAt 1 (drawPath (P.circle (V2 0 0) (-30)) red) == opsAt 1 (drawPath (P.circle (V2 0 0) 30) red))+  -- An arc whose radius dwarfs its chord becomes a line, and the subpath continues.+  forM_ [1e7, 1e9, 1e12, 1e20] $ \radius ->+    assertEq failed [[V2 0 0, V2 20 0, V2 20 20]] (lines' (P.moveTo (V2 0 0) <> P.arcTo (V2 radius radius) 0 False True (V2 20 0) <> P.lineTo (V2 20 20)))+  assertEq failed [2] (map length (lines' (P.arc (V2 0 1e8) 1e8 (-pi / 2) 1e-6)))+  -- A full circle closes exactly at its start, with no sliver edge at the seam.+  forM_ [(V2 0 0, 3000), (V2 123.4 (-56.7), 777)] $ \(centre, radius) ->+    single failed (strokes (opsAt 2 (drawStrokePath (P.circle centre radius) 1 black))) $ \(pts, closed) -> do+      assert failed closed+      assertGt failed (minimum (zipWith dist pts (drop 1 pts ++ take 1 pts))) 1+  -- An invalid display scale flattens as scale 1.+  forM_ [0, -2, nan, inf] $ \scale -> assert failed (opsAt 1 (drawPath (P.circle p 40) red) == opsAt scale (drawPath (P.circle p 40) red))+  -- A self-intersecting pentagram fills partially, with valid output.+  let crossing = opsAt 1 (drawPath (P.polygon [V2 (50 * cos a) (50 * sin a) | i <- [0 .. 4 :: Int], let a = 4 * pi * fromIntegral i / 5]) red)+  assert failed (sound crossing && all (\(pts, tris) -> snd (covered pts tris)) (fills crossing))+  assert failed (sound (both (P.polyline [V2 0 0, V2 nan nan, V2 1e30 1e30, V2 (-1e30) 0])))++-- | Points, ring starts and triangles of each filled polygon under a fill rule.+polygons :: P.FillRule -> P.Path -> [([V2], [Int], [Int])]+polygons rule path = [(pairs pts, primArrayToList rings, primArrayToList tris) | FillPolygon pts rings tris _ <- opsAt 1 (drawPathWith rule path (P.Solid red))]++-- | Area covered by a polygon's triangles, or 'Nothing' if an index is out of range.+coverage :: ([V2], [Int], [Int]) -> Maybe Float+coverage (pts, _, tris) = let (a, ok) = covered pts tris in if ok then Just a else Nothing++-- | A square outline, clockwise on screen ('square') or anticlockwise ('squareBack').+square, squareBack :: Float -> Float -> Float -> P.Path+square x y s = P.polygon [V2 x y, V2 (x + s) y, V2 (x + s) (y + s), V2 x (y + s)]+squareBack x y s = P.polygon [V2 x y, V2 x (y + s), V2 (x + s) (y + s), V2 (x + s) y]++-- | Whether any triangle covers a point.+coversPoint :: ([V2], [Int], [Int]) -> V2 -> Bool+coversPoint (pts, _, tris) p = any inside [(pts !! a, pts !! b, pts !! c) | (a, b, c) <- triples tris]+  where+    side (V2 x0 y0) (V2 x1 y1) (V2 x y) = (x1 - x0) * (y - y0) - (y1 - y0) * (x - x0)+    inside (a, b, c) = let ds = [side a b p, side b c p, side c a p] in all (> 0) ds || all (< 0) ds++-- | A nested subpath is a hole when the fill rule leaves it unfilled, and+-- the triangles cover exactly the filled area.+runFillHolesTest :: Context -> IORef Int -> IO ()+runFillHolesTest _ failed = do+  let c = V2 60 60+      -- A circle wound the other way.+      circleBack r = P.moveTo (V2 (60 + r) 60) <> P.arc c r 0 (-2 * pi) <> P.close+      areaNear want got = abs (got - want) <= 1e-3 * want+      check :: String -> P.FillRule -> P.Path -> [Float] -> IO ()+      check name rule path wantAreas =+        let got = map coverage (polygons rule path)+         in unless (length got == length wantAreas && and (zipWith (\w a -> maybe False (areaNear w) a) wantAreas got)) $+              assertEq failed (name, map Just wantAreas) (name, got)+      nestedSquare k = square (5 * fromIntegral k) (5 * fromIntegral k) (200 - 10 * fromIntegral k)+      nestedBack k = (if even k then square else squareBack) (5 * fromIntegral k) (5 * fromIntegral k) (200 - 10 * fromIntegral k)+      bands = [s * s - (s - 10) * (s - 10) | j <- [0 .. 9 :: Int], let s = 200 - 20 * fromIntegral j]+      cells = foldMap (\k -> square (10 * fromIntegral (k `mod` 10)) (10 * fromIntegral (k `div` 10)) 5) [0 .. 99 :: Int]+  forM_+    -- Holes by rule and winding, islands, crossings, repeated loops, and+    -- many subpaths each finding its parent.+    [ ("even-odd hole", P.EvenOdd, square 0 0 100 <> square 20 20 60, [6400])+    , ("non-zero hole", P.NonZero, square 0 0 100 <> squareBack 20 20 60, [6400])+    , ("non-zero same way", P.NonZero, square 0 0 100 <> square 20 20 60, [10000])+    , ("two holes", P.EvenOdd, square 0 0 100 <> square 10 10 30 <> squareBack 60 10 30, [8200])+    , ("island", P.EvenOdd, square 0 0 100 <> square 20 20 60 <> square 40 40 20, [6400, 400])+    , ("island non-zero", P.NonZero, square 0 0 100 <> squareBack 20 20 60 <> square 40 40 20, [6400, 400])+    , ("crossing", P.EvenOdd, square 0 0 60 <> square 40 40 60, [3600, 3600])+    , ("same loop twice", P.EvenOdd, square 0 0 50 <> square 0 0 50, [])+    , ("same loop three times", P.EvenOdd, square 0 0 50 <> square 0 0 50 <> square 0 0 50, [2500])+    , ("loop and its reverse", P.NonZero, square 0 0 50 <> squareBack 0 0 50, [])+    , ("same loop twice, non-zero", P.NonZero, square 0 0 50 <> square 0 0 50, [2500])+    , ("copies inside a square", P.EvenOdd, square 0 0 100 <> square 20 20 60 <> square 20 20 60, [6400, 3600])+    , ("20 nested, even-odd", P.EvenOdd, foldMap nestedSquare [0 .. 19 :: Int], bands)+    , ("20 nested, non-zero alternating", P.NonZero, foldMap nestedBack [0 .. 19 :: Int], bands)+    , ("20 nested, non-zero same way", P.NonZero, foldMap nestedSquare [0 .. 19 :: Int], [40000])+    , ("100 apart", P.NonZero, cells, replicate 100 25)+    , ("100 holes", P.EvenOdd, square (-10) (-10) 120 <> cells, [14400 - 2500])+    ]+    $ \(name, rule, path, want) -> check name rule path want+  -- Concentric circles: an annulus, like a glyph with a curved counter.+  let ringArea = sum (map (maybe 0 id . coverage) (polygons P.EvenOdd (P.circle c 50 <> P.circle c 30)))+  assertLt failed (abs (ringArea - pi * (50 * 50 - 30 * 30))) (2 * pi * 80 * 0.25)+  assertEq failed [3] [length rings | (_, rings, _) <- polygons P.NonZero (P.circle c 50 <> circleBack 30)]+  single failed (polygons P.EvenOdd (P.circle c 50 <> P.circle c 30)) $ \poly@(_, rings, _) -> do+    assertEq failed 3 (length rings)+    assert failed (not (coversPoint poly c) && coversPoint poly (V2 60 20))+  -- Many holes in a row, each a random convex polygon.+  let blob i = [V2 (25 + 50 * fromIntegral i + 12 * cos a) (50 + 12 * sin a) | k <- [0 .. 7 :: Int], let a = 2 * pi * (fromIntegral k + 0.4 * rnd (i * 10 + k)) / 8]+      blobs = map blob [0 .. 7 :: Int]+  single failed (polygons P.EvenOdd (square 0 0 400 <> foldMap P.polygon blobs)) $ \poly ->+    assertLt failed (abs (maybe 0 id (coverage poly) - (160000 - sum (map (abs . polyArea) blobs)))) 1+  -- A single subpath is one polygon with one ring.+  assertEq failed [[0, 4]] [rings | (_, rings, _) <- polygons P.EvenOdd (square 0 0 10)]+  -- 'fillPathOps', which backends use, matches the canvas output.+  assert failed (opsAt 1 (drawPathWith P.EvenOdd (square 0 0 10) (P.Solid red)) == fillPathOps 0.25 mempty P.EvenOdd (square 0 0 10) (P.Solid red))++-- | Dashes split a stroke by the pattern, measured in transformed lengths.+runDashTest :: Context -> IORef Int -> IO ()+runDashTest _ failed = do+  let dashedWith st pattern off path = [(pairs pts, cap) | StrokePolyline pts _ closed cap _ _ _ <- opsAt 1 (st (drawStrokePathWith (P.stroke 2) {P.strokeDash = pattern, P.strokeDashOffset = off, P.strokeCap = P.RoundCap} path (P.Solid black))), not closed]+      dashed = dashedWith id+      line = P.polyline [V2 0 0, V2 100 0]+      spans' = map (\(ps, _) -> xsOf (ends ps))+  assertEq failed [[0, 10], [15, 25], [30, 40], [45, 55], [60, 70], [75, 85], [90, 100]] (spans' (dashed [10, 5] 0 line))+  -- An offset starts partway into the pattern; an odd-length pattern is repeated twice.+  assertEq failed [[0, 5], [10, 20], [25, 35], [40, 50], [55, 65], [70, 80], [85, 95]] (spans' (dashed [10, 5] 5 line))+  assertEq failed [[0, 10], [20, 30], [40, 50], [60, 70], [80, 90]] (spans' (dashed [10] 0 line))+  -- Each dash is capped.+  assert failed (all ((== P.RoundCap) . snd) (dashed [10, 5] 0 line))+  -- A dash turns a corner with its line.+  assertEq failed [[V2 0 0, V2 10 0, V2 10 5]] (map fst (dashed [15, 100] 0 (P.polyline [V2 0 0, V2 10 0, V2 10 10])))+  -- Dashes on a closed subpath run around it.+  assertEq failed [[V2 0 0, V2 5 0], [V2 10 0, V2 10 5], [V2 10 10, V2 5 10], [V2 0 10, V2 0 5]] (map fst (dashed [5, 5] 0 (square 0 0 10)))+  -- A closed two-point subpath runs there and back, dashed both ways.+  assertEq failed [[V2 0 0, V2 5 0], [V2 10 0, V2 5 0]] (map fst (dashed [5, 5] 0 (P.moveTo (V2 0 0) <> P.lineTo (V2 10 0) <> P.close)))+  -- Zero-length dashes become very short dots.+  let dots = dashed [0, 10] 0 line+  assertEq failed 11 (length dots)+  assert failed (all (\(ps, _) -> case ps of [V2 x0 _, V2 x1 _] -> x1 - x0 > 0 && x1 - x0 < 0.01; _ -> False) dots)+  -- Dashes too short to move off a point at its float precision do not+  -- repeat forever: the segment is solid, from a dash or a gap.+  forM_ [0, 0.007] $ \off -> assertEq failed [[V2 131072 0, V2 131082 0]] (map fst (dashed [0.006, 0.004] off (P.polyline [V2 131072 0, V2 131082 0])))+  -- An invalid or too fine pattern draws a solid line.+  forM_ [[-1, 2], [0, 0], [0.001]] $ \pattern -> assertEq failed [[V2 0 0, V2 100 0]] (map fst (dashed pattern 0 line))+  -- A transform scales the pattern with the line.+  assertEq failed [[0, 20], [30, 50], [60, 80], [90, 100]] (spans' (dashedWith (withTransform (P.scale 2 2)) [10, 5] 0 (P.polyline [V2 0 0, V2 50 0])))++-- | Vertex positions (relative to the canvas corner) and alphas from one+-- frame that draws a canvas at scale 1.+canvasVertices :: Context -> (Rect -> CanvasM ()) -> IO [(V2, Float)]+canvasVertices ctx draw = do+  setDrawSnapScale ctx 1+  (resp, dd, _) <- runFrame ctx (withInput 300 300) (canvas (fixedWH 200 200) draw)+  setDrawSnapScale ctx 0+  let Rect ox oy _ _ = respRect resp+  map (\v -> (V2 (vX v - ox) (vY v - oy), vA v)) <$> drawnVertices dd++-- | How far stroke vertices reach outward past a corner (miter tip, round+-- arc or bevel edge), and past a line end for each cap.+runJoinGeometryTest :: Context -> IORef Int -> IO ()+runJoinGeometryTest ctx failed = do+  let corner = V2 100 100+      -- The vertices of a polyline through these points, relative to the canvas.+      strokeVerts st pts = map fst <$> canvasVertices ctx (\(Rect x y _ _) -> drawStrokePathWith st (P.polyline [V2 (x + px) (y + py) | V2 px py <- pts]) (P.Solid black))+      -- How far the vertices near @p@ reach along @dir@.+      reachFrom p dir vs = maximum [v2Dot (v2Sub q p) dir | q <- vs, dist q p < 30]+      -- A right-angle corner whose outside faces the top right.+      reach st = reachFrom corner (V2 (sqrt 0.5) (negate (sqrt 0.5))) <$> strokeVerts st [V2 40 100, corner, V2 100 160]+      edge = 5 + 0.5+      roundJoin = (P.stroke 10) {P.strokeJoin = P.RoundJoin}+  miter <- reach (P.stroke 10)+  bevel <- reach (P.stroke 10) {P.strokeJoin = P.BevelJoin}+  roundJ <- reach roundJoin+  -- A right angle's miter is 1.41 times the width, so a limit of 1.3 bevels it.+  limited <- reach (P.stroke 10) {P.strokeMiterLimit = 1.3}+  assertLt failed (abs (miter - edge * sqrt 2)) 0.01+  assert failed (roundJ > edge * 0.95 && roundJ < edge + 0.01)+  assertLt failed (abs (bevel - edge * sqrt 0.5)) 0.01+  assertLt failed (abs (limited - bevel)) 0.01+  -- A round join where a line turns back on itself rounds the tip, the way+  -- the line was heading, whichever way it points.+  forM_ [V2 60 0, V2 60 80] $ \(V2 dx dy) -> do+    let len = sqrt (dx * dx + dy * dy)+        tip = V2 (40 + dx) (100 + dy)+    tipReach <- reachFrom tip (V2 (dx / len) (dy / len)) <$> strokeVerts roundJoin [V2 40 100, tip, V2 40 100]+    assert failed (tipReach > edge * 0.95 && tipReach < edge + 0.01)+  -- Each cap extends past the line end by its expected amount.+  let capReach cap = (\vs -> maximum [px - 100 | V2 px py <- vs, abs (py - 100) < 20, px > 90, px < 130]) <$> strokeVerts (P.stroke 10) {P.strokeCap = cap} [V2 40 100, corner]+  butt <- capReach P.ButtCap+  sq <- capReach P.SquareCap+  roundC <- capReach P.RoundCap+  assertEq failed [True, True, True] [abs (butt - 0) < 0.01, abs (sq - edge + 0.5) < 0.01, abs (roundC - edge) < 0.01]+  -- An end repeated in a polyline op still gets its cap.+  vs <- canvasVertices ctx $ \(Rect x y _ _) ->+    let a = [x + 40, y + 100]+        b = [x + 100, y + 100]+     in emitOp (StrokePolyline (primArrayFromList (a ++ a ++ b ++ b)) 10 False P.SquareCap P.MiterJoin 4 (Flat black))+  let near100 = [q | (q@(V2 _ py), _) <- vs, abs (py - 100) < 20]+  assertLt failed (abs (maximum [px - 100 | V2 px _ <- near100] - 5)) 0.01+  assertLt failed (abs (maximum [40 - px | V2 px _ <- near100] - 5)) 0.01+  where+    v2Dot (V2 a b) (V2 c d) = a * c + b * d++-- | A linear gradient colours points by position, splits geometry at its+-- stops, and follows transforms.+runGradientTest :: Context -> IORef Int -> IO ()+runGradientTest _ failed = do+  let shaded ops = [(pairs pts, primArrayToList tris, map Color (primArrayToList cs)) | FillPolygon pts _ tris (Shaded cs) <- ops]+      gradient p0 p1 stops path = shaded (opsAt 1 (drawPathWith P.NonZero path (P.Linear p0 p1 stops)))+      bar = P.rect (Rect 0 0 100 10)+      channel f c = fromIntegral (f c) :: Float+      flat paint = [c | FillPolygon _ _ _ (Flat c) <- opsAt 1 (drawPathWith P.NonZero bar paint)]+  -- Two stops spanning the shape: corner colours only, no extra vertices.+  single failed (gradient (V2 0 0) (V2 100 0) [(0, red), (1, blue)] bar) $ \(pts, _, cols) ->+    assertEq failed (4, [red, blue, blue, red]) (length pts, cols)+  -- A gradient over part of the shape splits it at every stop, and no+  -- triangle crosses a stop.+  single failed (gradient (V2 25 0) (V2 75 0) [(0, red), (0.5, green), (1, blue)] bar) $ \(pts, tris, cols) -> do+    let xs = xsOf pts+        straddles v (a, b, c) = let gs = [xs !! i | i <- [a, b, c]] in minimum gs < v - 1e-3 && maximum gs > v + 1e-3+    assert failed (all (\v -> any (\x -> abs (x - v) < 1e-3) xs) [25, 50, 75])+    assert failed (not (or [straddles v t | v <- [25, 50, 75], t <- triples tris]))+    assertLt failed (abs (fst (covered pts tris) - 1000)) 1e-2+    assert failed (and [c == (if x <= 25 then red else if x >= 75 then blue else c) | (V2 x _, c) <- zip pts cols])+    assert failed (and [c == green | (V2 x _, c) <- zip pts cols, abs (x - 50) < 1e-3])+  -- Two stops at one offset are a hard edge: each side keeps its own+  -- colour up to the pixel across the edge.+  single failed (gradient (V2 0 0) (V2 100 0) [(0, red), (0.5, red), (0.5, blue), (1, blue)] bar) $ \(pts, _, cols) -> do+    assert failed (any (\x -> abs (x - 49.5) < 1e-3) (xsOf pts) && any (\x -> abs (x - 50.5) < 1e-3) (xsOf pts))+    assert failed (and [c == (if x < 50 then red else blue) | (V2 x _, c) <- zip pts cols])+  -- Rotated with its shape, each point keeps its unrotated colour.+  let turn = P.rotateAround (V2 50 5) 0.7+  single failed (shaded (opsAt 1 (withTransform turn (drawPathWith P.NonZero bar (P.Linear (V2 0 0) (V2 100 0) [(0, red), (1, blue)]))))) $ \(pts, _, cols) ->+    forM_ (zip pts cols) $ \(p, c) -> case P.invert turn of+      Just back ->+        let V2 x _ = P.transformPoint back p+         in assertLt failed (abs (channel colorB c - (channel colorB red + (255 - channel colorB red) * x / 100))) 1.5+      Nothing -> assert failed False+  -- A zero-length gradient, or one with a single stop, is a flat fill.+  assert failed (null (gradient (V2 5 5) (V2 5 5) [(0, red), (1, blue)] bar))+  assertEq failed ([blue], [red]) (flat (P.Linear (V2 5 5) (V2 5 5) [(0, red), (1, blue)]), flat (P.Linear (V2 0 0) (V2 100 0) [(0, red)]))+  -- A stroke takes the colours along its centre line.+  assertEq failed [[red, blue]] [map Color (primArrayToList cs) | StrokePolyline _ _ _ _ _ _ (Shaded cs) <- opsAt 1 (drawStrokePathWith (P.stroke 4) (P.polyline [V2 0 0, V2 100 0]) (P.Linear (V2 0 0) (V2 100 0) [(0, red), (1, blue)]))]+  -- A four-corner gradient at a non-quarter angle becomes a shaded polygon+  -- with its corner colours.+  single failed [(pts, cs) | FillPolygon pts _ _ (Shaded cs) <- opsAt 1 (withTransform (P.rotate 0.5) (drawQuadGradient (Rect 0 0 10 10) red green blue black))] $ \(pts, cs) -> do+    assertNear failed 1e-4 (map (P.transformPoint (P.rotate 0.5)) [V2 0 0, V2 10 0, V2 10 10, V2 0 10]) (pairs pts)+    assertEq failed [red, green, blue, black] (map Color (primArrayToList cs))++-- | Per-corner rounded rects, inverse transforms, and clips the frame applies.+runShapesAndClipTest :: Context -> IORef Int -> IO ()+runShapesAndClipTest ctx failed = do+  let areaOf path = sum [abs (polyArea pts) | (pts, _) <- filled path]+      quarterCut r = (4 - pi) / 4 * r * r+      -- Area that flattening a quarter circle of radius @r@ may lose.+      flat r = pi / 2 * r * 0.25+  assertLt failed (abs (areaOf (P.roundedRectCorners (Rect 0 0 100 60) 0 20 0 10) - (6000 - quarterCut 20 - quarterCut 10))) (flat 20 + flat 10)+  -- Oversized radii scale down together until they fit, as in CSS.+  assertLt failed (abs (areaOf (P.roundedRectCorners (Rect 0 0 100 60) 60 60 0 0) - (6000 - 2 * quarterCut 50))) (2 * flat 50)+  -- An infinite radius is as large as the corners allow: a pill, or a lone+  -- corner as wide as the shorter side.+  assertLt failed (abs (areaOf (P.roundedRect (Rect 10 10 80 40) (1 / 0)) - (3200 - 4 * quarterCut 20))) (4 * flat 20)+  assertLt failed (abs (areaOf (P.roundedRectCorners (Rect 10 10 80 40) (1 / 0) 0 0 0) - (3200 - quarterCut 40))) (flat 40)+  assert failed (filled (P.roundedRectCorners (Rect 0 0 10 10) 0 0 (-3) 0) == filled (P.rect (Rect 0 0 10 10)))+  assert failed (filled (P.roundedRect (Rect 0 0 40 20) 6) == filled (P.roundedRectCorners (Rect 0 0 40 20) 6 6 6 6))+  -- A negative width or height spans the same rectangle.+  forM_ [Rect 50 0 (-50) 30, Rect 0 30 50 (-30), Rect 50 30 (-50) (-30)] $ \r ->+    assert failed (filled (P.roundedRectCorners r 5 8 0 3) == filled (P.roundedRectCorners (Rect 0 0 50 30) 5 8 0 3))+  let t = P.translate 3 (-2) <> P.rotate 0.4 <> P.scale 2 (-0.5) <> P.affine 1 0.3 0 1 0 0+      pts = [V2 1 2, V2 (-40) 7, V2 0 0]+  case P.invert t of+    Just back -> assertNear failed 1e-3 pts (map (P.transformPoint back . P.transformPoint t) pts)+    Nothing -> assert failed False+  assertEq failed [True, True] [P.invert (P.scale 0 1) == Nothing, P.invert (P.scale (0 / 0) 1) == Nothing]+  let clipOps block = [op | op <- opsAt 1 block, case op of PushClip _ -> True; PopClip -> True; _ -> False]+  assert failed (clipOps (withClip (Rect 1 2 3 4) (drawRect (Rect 0 0 10 10) red)) == [PushClip (Rect 1 2 3 4), PopClip])+  assert failed (clipOps (withTransform (P.translate 5 5) (withClip (Rect 1 2 3 4) (pure ()))) == [PushClip (Rect 6 7 3 4), PopClip])+  -- Under rotation, the clip is the bounding box of the rotated rect.+  case clipOps (withTransform (P.rotate (pi / 4)) (withClip (Rect 0 0 10 10) (pure ()))) of+    [PushClip (Rect x y w h), PopClip] -> assertNear failed 1e-3 [V2 (-10 * sqrt 0.5) 0, V2 (20 * sqrt 0.5) (20 * sqrt 0.5)] [V2 x y, V2 w h]+    _ -> assert failed False+  -- In a frame, the content is clipped and later draws are not.+  (resp, dd, _) <- runFrame ctx (withInput 300 300) . canvas (fixedWH 100 100) $ \(Rect x y _ _) -> do+    withClip (Rect (x + 10) (y + 10) 20 20) (drawRect (Rect x y 100 100) red)+    drawRect (Rect x y 50 50) black+  let Rect x y _ _ = respRect resp+      clips = [(cmdClipX c - x, cmdClipY c - y, cmdClipW c, cmdClipH c) | c <- drawCmdElems dd, cmdIndexCount c > 0]+  assert failed ((10, 10, 20, 20) `elem` clips && any (\(_, _, w, _) -> w >= 100) clips)++-- | A canvas repaints only when its drawing changes and flattens for the+-- display scale; a configured one sees hover and sets its cursor.+runCanvasFramesTest :: Context -> IORef Int -> IO ()+runCanvasFramesTest ctx failed = do+  let inp = withInputOff 400 300+      ui turn = column $ do+        label "Other"+        drawn <- canvas (fixedWH 120 120) $ \(Rect x y w h) ->+          withTransform (P.rotateAround (V2 (x + w / 2) (y + h / 2)) turn) $ do+            drawPath (P.roundedRect (Rect (x + 20) (y + 20) 80 80) 10) red+            drawStrokePath (P.circle (V2 (x + 60) (y + 60)) 30) 2 black+        (keyed, ()) <- customWidget defaultCustomWidgetSpec+          { widgetLayout = fixedWH 60 60+          , widgetContent = 1+          , widgetDraw = \cdc (Rect x y _ _) -> runCanvasFor cdc (drawPath (P.circle (V2 (x + 30) (y + 30)) 25) red)+          }+        pure (drawn, keyed)+      cached c = IM.elems . dcsCustomDrawOpCache <$> readIORef (ctxDrawingCache c)+      -- Filled point count of each cached canvas.+      pointsIn c = map (\e -> sum [sizeofPrimArray pts `div` 2 | FillPolygon pts _ _ _ <- toList (cdeOps e)]) <$> cached c+  (drawn, keyed) <- warmup2 ctx inp (ui 0)+  _ <- runFrame ctx inp (ui 0)+  takeDamage ctx >>= \same -> assert failed (not (any (damageCovers same . respRect) [drawn, keyed]))+  _ <- runFrame ctx inp (ui 0.4)+  takeDamage ctx >>= assert failed . (`clipCovers` respRect drawn)+  -- Both flatten finer at a higher display scale, including the keyed one whose key is unchanged.+  before <- pointsIn ctx+  let dense = withFontMetrics ctx (ctxFontMetrics ctx) {fmSnapScale = 3}+  _ <- warmup2 dense inp (ui 0.4)+  after <- pointsIn dense+  assertEq failed (2, 2, True) (length before, length after, and (zipWith (<) before after))+  configured <- newContext+  let cfg key = defaultCanvasConfig {canvasLayout = fixedWH 60 40, canvasContent = key, canvasCursor = Just (\_ _ _ -> UiCursorPointer)}+      hovered key = canvasConfigured (cfg key) $ \r -> drawContext >>= \cdc -> drawRect r (if cdcHovered cdc then red else black)+  resp <- warmup2 configured (withInput 300 300) (hovered 1)+  let hoverAt = (withInput 300 300) {inputMousePos = centerOf resp}+  _ <- run2Frames configured hoverAt (hovered 1)+  cached configured >>= \es -> assertEq failed [red] [c | e <- es, FillRect _ c <- toList (cdeOps e)]+  assertEq failed UiCursorPointer =<< uiCursorKind configured hoverAt
+ test/integration/Cases/PointerExtra.hs view
@@ -0,0 +1,185 @@+{-# OPTIONS_GHC -O0 #-}+-- | Middle, side and other mouse buttons. A non-left click is reported+-- separately from a plain click, and a held or clicked button belongs to the+-- widget it was pressed on.+module Cases.PointerExtra (tests) where++import Spec+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (findNodeM, getNodeRect, getText)+import NanoUI.Runner (shouldRedrawFrame)+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "pointer-button-sets" runButtonSetsTest+  , spec "focus-loss-releases-buttons" runFocusLossReleasesButtonsTest+  , varSimSpec "hovered-widget-gone" 300 200 True hoverGoneUi hoverGone+  , spec "pointer-held-ownership" runHeldOwnershipTest+  , spec "pointer-blocked" runBlockedTest+  , simSpec "pointer-middle-click" 400 300 middleUi middleClicks+  , spec "pointer-mouse-area" runMouseAreaTest+  ]++-- | Button sets track every button, extras by number. Presses and releases+-- appear only in the frame they happen in. Any held button counts as a held+-- pointer, and a press or release frame redraws.+-- | Losing focus releases held mouse buttons as it releases keys, so a drag+-- or a held stepper arrow does not outlive a release sent to another window.+runFocusLossReleasesButtonsTest :: Context -> IORef Int -> IO ()+runFocusLossReleasesButtonsTest _ failed = do+  let pressed = applyMouseButton MouseLeft True emptyInput+      blurred = releaseAllKeys pressed+  assertEq failed False (heldIn MouseLeft blurred)+  assertEq failed True (releasedIn MouseLeft blurred)++-- | A hovered widget the view stops declaring starts no fade-out: nothing+-- animates and the loop can sleep at once.+hoverGoneUi :: Var Bool -> NanoUI ()+hoverGoneUi shown = column $ do+  on <- readVar shown+  when on (void (button "Delete"))+  label "rest"++hoverGone :: Var Bool -> Sim () ()+hoverGone shown = do+  _ <- moveTo "Delete" >> advance 1 >> settle+  writeV shown False+  _ <- settle+  check . not =<< onContext anyAnimating+  check . not =<< wantsFrame++runButtonSetsTest :: Context -> IORef Int -> IO ()+runButtonSetsTest _ failed = do+  let every = [MouseLeft, MouseRight, MouseMiddle, MouseBack, MouseForward, MouseOther 6, MouseOther 32]+      down = foldr (`applyMouseButton` True) emptyInput every+  assertEq failed (buttonsFromList every) (inputButtonsHeld down)+  assertEq failed (buttonsFromList every) (inputButtonsPressed down)+  -- Lists come back in button-number order; numbers 1 to 5 are the named buttons.+  let ordered = [MouseLeft, MouseMiddle, MouseRight, MouseBack, MouseForward, MouseOther 6]+  assertEq failed (ordered <> [MouseOther 32]) (buttonsToList (inputButtonsHeld down))+  assertEq failed ordered (map mouseButtonNumber [1 .. 6])+  -- A button past 32 is not tracked.+  assert failed (buttonsNull (inputButtonsHeld (applyMouseButton (MouseOther 33) True emptyInput)))+  let up = applyMouseButton (MouseOther 6) False (clearEphemeral down)+  assert failed (releasedIn (MouseOther 6) up && not (heldIn (MouseOther 6) up) && heldIn MouseLeft up)+  assert failed (anyButtonReleased up && not (anyButtonPressed up))+  -- The next frame keeps what is held and drops the presses.+  assertEq failed (inputButtonsHeld down) (inputButtonsHeld (clearEphemeral down))+  assert failed (buttonsNull (inputButtonsPressed (clearEphemeral down)))+  let middle = pressWith MouseMiddle emptyInput (V2 20 20)+      back = pressWith MouseBack emptyInput (V2 20 20)+      backUp = releaseWith MouseBack (clearEphemeral back)+  assertEq failed [True, True, False] (map inputPointerHeld [middle, back, backUp])+  -- Whether an idle loop that already saw the input redraws for it again.+  let redrawsAgain i = newContext >>= \idle -> shouldRedrawFrame idle i i False False False+  assertEq failed [True, True, True] =<< mapM redrawsAgain [middle, back, backUp]++-- | A right, middle or extra-button click on a widget is that widget's alone,+-- and not a plain click. A drag from one button onto another holds and clicks+-- neither, and neither does a release on a widget that moved under the press.+runHeldOwnershipTest :: Context -> IORef Int -> IO ()+runHeldOwnershipTest ctx failed = do+  order <- newIORef ["Alpha", "Beta" :: T.Text]+  let ui = row (liftIO (readIORef order) >>= mapM (\n -> withKey n (button' n)))+      (q, h, c) = ((False, False, False), (True, False, False), (False, True, False))+  runSim ctx failed (withInputOff 400 300) ui $ do+    [a, b] <- map On <$> result+    forM_ [MouseMiddle, MouseRight, MouseOther 7] $ \btn -> do+      let flags = map (\r -> (respHeldWith btn r, respClickedWith btn r, respClicked r || respPressed r))+      rs <- sequence+        [pressButton btn b, releaseButton btn, frame, pressButton btn a, moveTo b, releaseButton btn]+      checkEq [[q, h], [q, c], [q, q], [h, q], [q, q], [q, q]] (map flags rs)+      check (respHovered (rs !! 4 !! 1))+      _ <- pressButton btn a+      _ <- liftIO (writeIORef order ["Beta", "Alpha"]) >> frame+      check . not . any (respClickedWith btn) =<< releaseButton btn+      liftIO (writeIORef order ["Alpha", "Beta"]) >> settle++-- | 'mousePressed', 'mouseHeld' and 'mouseReleased' see a button anywhere on+-- the layer. Inside 'disabledWhen', or on the page beside a modal, neither+-- they nor a widget see a middle or side button.+runBlockedTest :: Context -> IORef Int -> IO ()+runBlockedTest ctx failed = do+  mode <- newIORef (False, False)+  let listen = (,,) <$> mousePressed MouseBack <*> mouseHeld MouseBack <*> mouseReleased MouseBack+      ui = do+        (off, covered) <- liftIO (readIORef mode)+        r <- disabledWhen off ((,) <$> buttonWith' (fixedWH 380 280) "Under" <*> listen)+        r <$ modal' (constVar covered) "Cover" (label "on top")+      untouched (r, heard) =+        not (respHovered r || or [respHeldWith b r || respClickedWith b r | b <- [MouseMiddle, MouseBack]])+          && heard == (False, False, False)+  runSim ctx failed (withInputOff 400 300) ui $ do+    Rect x y _ _ <- respRect . fst <$> result+    let corner = At (V2 (x + 4) (y + 4))+    heard <- map snd <$> sequence [pressButton MouseBack corner, frame, releaseButton MouseBack]+    checkEq [(True, True, False), (False, True, False), (False, False, True)] heard+    forM_ [(True, False), (False, True)] $ \m -> do+      _ <- liftIO (writeIORef mode m) >> settle+      rs <- concat <$> mapM (\b -> sequence [pressButton b corner, releaseButton b]) [MouseMiddle, MouseBack]+      check (all untouched rs)++middleUi :: NanoUI (TabResponse Int, Response)+middleUi = do+  bar <- tabBar' (constVar 0) [closableTab 0 "Alpha" (), closableTab 1 "Beta" (), tab 2 "Gamma" ()]+  (bar,) . fst <$> popup' (constVar True) (defaultPopupConfig (AnchorPoint (V2 40 80))) (label "Popup body")++-- | A middle click on a closable tab's header or close button requests a close+-- without selecting the tab; a tab without a close button stays. A middle+-- press outside a popup dismisses it; one inside does not.+middleClicks :: Sim (TabResponse Int, Response) ()+middleClicks = do+  na <- ctxNodeArena <$> simContext+  let isClose = fmap ("\215" `T.isInfixOf`) . getText na+  Just closeX <- liftIO (traverse (getNodeRect na) =<< findNodeM na isClose)+  targets <- sequence [rectOf "Beta", pure closeX, rectOf "Gamma"]+  closed <- mapM (fmap (\(bar, _) -> (tabClosed bar, tabActive bar)) . clickWith MouseMiddle . Within) targets+  checkEq [(Just 1, 0), (Just 0, 0), (Nothing, 0)] closed+  inside <- On . snd <$> result+  let dismisses t = (respClicked . snd <$> pressButton MouseMiddle t) <* releaseButton MouseMiddle+  checkEq [False, True] =<< mapM dismisses [inside, At (V2 380 280)]++-- | A mouse area reports hover and every button over it and its labels, but+-- not over a child button. Content it reveals on hover stays while the pointer+-- is on it, even with a pinned node elsewhere (which turns on pointer+-- covering). A slider dragged inside one keeps the release.+runMouseAreaTest :: Context -> IORef Int -> IO ()+runMouseAreaTest ctx failed = do+  hoveredRef <- newIORef False+  let ui = columnWith tight $ do+        shown <- liftIO (readIORef hoveredRef)+        ((l, b), area) <- mouseArea (fixedWH 300 80) $ do+          l <- label' "Name"+          b <- if shown then Just <$> button' "Delete" else pure Nothing+          pure (l, b)+        liftIO (writeIORef hoveredRef (respHovered area))+        _ <- buttonWith' (pinAt 320 0 . fixedWH 40 20) "pinned"+        volume <- mouseArea (fixedWH 300 80) (label "Volume" >> withValue 50 (slider' 0 100))+        pure (l, b, area, volume)+  runSim ctx failed (withInputOff 400 300) ui $ do+    (l, _, area0, ((s, _), _)) <- result+    (_, _, areaMid, _) <- clickWith MouseMiddle (On l)+    check (respClickedWith MouseMiddle areaMid && not (respClicked areaMid))+    (_, _, areaRight, _) <- pressButton MouseRight (On l) <* releaseButton MouseRight+    check (respHeldWith MouseRight areaRight && respHovered areaRight)+    let beside = V2 250 60+    check (rectContains (respRect area0) beside)+    (_, _, areaLeft, _) <- click (At beside)+    check (respClicked areaLeft && respClickedWith MouseLeft areaLeft)+    (_, Just b, _, _) <- moveTo (On l) >> settle+    rs <- replicateM 4 (moveTo (On b))+    check (all (\(_, b', a, _) -> respHovered a && maybe False respHovered b') rs)+    (_, bClicked, aClicked, _) <- click (On b)+    check (maybe False respClicked bClicked && not (respClicked aClicked))+    forM_ [MouseRight, MouseMiddle, MouseOther 7] $ \btn -> do+      (_, heldChild, heldArea, _) <- pressButton btn (On b)+      (_, clickedChild, clickedArea, _) <- releaseButton btn+      check (maybe False (respHeldWith btn) heldChild && not (respHeldWith btn heldArea))+      check (maybe False (respClickedWith btn) clickedChild && not (respClickedWith btn clickedArea))+    let V2 x y = centerOf s+    (_, _, _, ((_, v), _)) <- press (At (V2 x y)) >> moveTo (At (V2 (x + 40) y))+    check (v > 50)+    (_, _, _, (_, released)) <- release+    check (not (respClicked released || respClickedWith MouseLeft released))
+ test/integration/Cases/PointerOwnership.hs view
@@ -0,0 +1,324 @@+{-# OPTIONS_GHC -O0 #-}+-- | The pointer belongs to whatever is on top. Every kind of overlay is opened+-- over every kind of pointer-driven widget, the pointer clicks, drags, wheels+-- and right-clicks on the overlay, and the widget underneath must not notice.+module Cases.PointerOwnership (tests) where++import Spec+import Data.IntMap.Strict qualified as IM+import Data.Maybe (fromMaybe, listToMaybe)+import Data.Text qualified as T+import Data.Text.IO.Utf8 qualified as TIO+import NanoUI.Internal.Context+  ( Context (ctxActiveId)+  , InteractionState (..)+  , getsInteraction+  , intKey+  , textInputMenuRect+  , textInputMenuWidget+  )+import NanoUI.Internal.Store (Slot (..), WidgetStore (..), isSelectOpen, slotKey)+import NanoUI.Internal.Widgets.TextArea (loadTextAreaState, tasBuffer, tasSelectionAnchor)+import NanoUI.Testing.Sim+import NanoUI.Widgets.TextBuffer (getCursor)+import System.Directory (doesDirectoryExist, listDirectory)+import System.FilePath (makeRelative, takeExtension, (</>))++tests :: [Spec]+tests =+  [ pixelSpec "pointer-ownership" runPointerOwnershipTest+  , spec "pointer-routing-lint" runPointerRoutingLintTest+  , pixelSimSpec "pointer-capture" 900 700 captureUi pointerCapture+  , simSpec "color-picker-bar-slack" 600 500 slackUi colorPickerBarSlack+  ]++red :: Color+red = colorRGBA 200 40 40 255++slackUi :: NanoUI (Response, Color)+slackUi = columnWith tight $ do+  _ <- buttonWith' (pinAt 500 400 . fixedWH 30 30) "x"+  columnWith (pointer PointerBlock . tight) (withValue red colorPicker')++-- | A colour picker's hue bar takes presses a little beside itself, even in a+-- view with a pinned node (where presses check what covers their widget).+colorPickerBarSlack :: Sim (Response, Color) ()+colorPickerBarSlack = do+  -- The field, then the hue bar; down its middle stretch, off hue 0 at either end.+  _ : Rect hx hy _ hh : _ <- map snd <$> onContext (nodesOfType NodeColorPicker)+  let p = At (V2 (hx - 1) (hy + hh * 0.3))+  (_, c) <- moveTo p >> press p >> moveTo (At (V2 (hx - 1) (hy + hh * 0.5)))+  check (c /= red)++-- | The page's result: the overlay's source, and the widget under test.+type Page = (Response, (Response, String))++-- | Something drawn over the page. Its source is declared above the widget+-- under test; @ovOpen@ opens it, given the source's response and the point+-- that has to end up covered, and @ovRect@ finds where it landed.+data Overlay = Overlay+  { ovName :: String+  , ovSource :: NanoUI Response+  , ovOpen :: Response -> V2 -> Sim Page ()+  , ovRect :: Response -> Sim Page (Maybe Rect)+  }++-- | A widget that reacts to the pointer. @vcHot@ is a point where a press,+-- drag or wheel changes it, and @vcProbe@ reads state its value leaves out.+data Victim = Victim+  { vcName :: String+  , vcUi :: NanoUI (Response, String)+  , vcHot :: Context -> Response -> IO V2+  , vcProbe :: Context -> Response -> IO String+  }++data Gesture = ClickDrag | Wheel | RightClick+  deriving (Eq, Show)++numbered :: T.Text -> [Int] -> [T.Text]+numbered what = map (\i -> what <> " " <> T.pack (show i))++overlays :: [Overlay]+overlays =+  [ -- A right click low in the field and left of the hot point, so the menu+    -- opens down and to the right, over it.+    Overlay "text-menu" (fst <$> withValue "source text" textInput') openMenu menuPanelRect+  , Overlay "select-dropdown" (fst <$> withValue 0 (selectWith' fillW options)) clickSource spanPanelRect+  , Overlay "combo-dropdown" (fst <$> withValue "" (comboBox' "pick" options)) clickSource spanPanelRect+  , Overlay "popup" popupSource alreadyOpen nodePanelRect+  , Overlay "window" (fst <$> floatingWindow' (constVar True) "Overlay window" panelBody) alreadyOpen nodePanelRect+  , Overlay "modal" (fst <$> modal' (constVar True) "Overlay modal" panelBody) alreadyOpen nodePanelRect+  ]+  where+    options = numbered "option" [1 .. 12]+    openMenu src (V2 hx _) =+      let Rect _ sy _ sh = respRect src in void (rightClick (At (V2 (hx - 30) (sy + sh - 3))))+    clickSource src _ = void (click (On src))+    alreadyOpen _ _ = pure ()+    popupSource = do+      anchor <- button' "popup source"+      let cfg = defaultPopupConfig (AnchorRect (respRect anchor))+      fst <$> popup' (constVar True) cfg {popupPlacement = PlacementBelow, popupDismissable = False} panelBody+    panelBody = columnWith (fixedWH 420 420) (mapM_ label (numbered "overlay line" [1 .. 6]))+    -- Overlays the frame draws itself: the panel rect rides on their spans.+    spanPanelRect _ = do+      inp <- getInput+      listToMaybe . map (\(_, _, _, _, r) -> r) <$> onContext (`collectOverlayTextSpans` inp)+    -- Floating panels, which are layout nodes.+    nodePanelRect src = onContext (`getPrevRect` respId src)+    -- The text-edit menu's popup, at the rect it was drawn at.+    menuPanelRect _ = do+      _ <- frame+      onContext (\ctx -> (>>= \m -> if rectW (textInputMenuRect m) > 0 then Just (textInputMenuRect m) else Nothing) <$> getsInteraction ctx isTextInputMenu)++victims :: IO [Victim]+victims = do+  -- The tab bar does not keep its own state, so the test holds it.+  tabRef <- newVar (0 :: Int)+  let tabBarUi v = toResponse <$> tabBar' v [tab i (T.pack ("tab " <> show i)) () | i <- [0 .. 3 :: Int]]+      plain name ui place = Victim name ui (hotAt place) (\_ _ -> pure "")+      -- The point @fx@ across and @fy@ down the rect, moved by @dx@ and @dy@.+      pt fx dx fy dy (Rect x y w h) = V2 (x + w * fx + dx) (y + h * fy + dy)+      -- Where a press changes each control, and what else of its state to watch.+      control (name, ui) = case name of+        -- The last option.+        "radio" -> plain name ui (pt 0.5 0 1 (-6))+        "slider" -> plain name ui (pt 0.8 0 0.5 0)+        "color picker" -> plain name ui (spanCenter . colorPickerSvSquare)+        -- The up arrow.+        "numeric input" -> plain name ui (pt 1 (-8) 0.25 0)+        "text input" -> (plain name ui spanCenter) {vcProbe = caretProbe}+        "text area" -> (plain name ui spanCenter) {vcProbe = areaProbe}+        "select" -> (plain name ui spanCenter) {vcProbe = selectProbe}+        _ -> plain name ui spanCenter+  pure $+    map control everyControl+      ++ [ -- The second tab.+           plain "tab-bar" (fmap show <$> held tabRef tabBarUi) (pt 0 90 0.5 0)+         , -- On the scrollbar lane, where a press drags the thumb.+           (plain "scroll-area" (fmap show <$> scroller) (pt 1 (-5) 0.7 0)) {vcProbe = scrollProbe}+         , -- On the boundary between the two headers, where a press resizes.+           (plain "table-columns" (fmap show <$> tableUi) spanCenter) {vcHot = headerBoundary}+         ]+  where+    hotAt place _ = pure . place . respRect+    scroller = do+      (wid, ()) <- scrollArea (fillW . fixedH 140) (mapM_ label (numbered "scroll line" [1 .. 40]))+      ctx <- askContext+      rect <- liftIO (getPrevRect ctx wid)+      pure (mempty {rawRespId = wid, rawRespRect = fromMaybe (Rect 0 0 0 0) rect}, ())+    tableUi = do+      sortVar <- useVar (SortCol 0 SortAsc)+      sort <- readVar sortVar+      let rows = [(name, "value") | name <- numbered "row" [1 .. 4]]+          cols = headed "Name" fst <> headed "Value" snd+      r <- tableWith' (fixedH 120) "victim table" cols rows (constVar sort)+      pure (toResponse r, (tableSort r, tableColOrder r))+    headerBoundary ctx r = do+      spans' <- collectTextSpans ctx+      let valueX = listToMaybe [x | (Rect x _ _ _, txt, _, _, _) <- spans', "Value" `T.isPrefixOf` txt]+      pure (maybe (V2 0 0) (\x -> V2 (x - 9) (rectY (respRect r) + 12)) valueX)+    caretProbe ctx r = do+      st <- getStore ctx+      let slot s = IM.lookup (slotKey s (intKey (respId r))) (storeInt st)+      pure (show (slot SlotCursor, slot SlotAnchor))+    areaProbe ctx r = do+      st <- getStore ctx+      let s = loadTextAreaState st (intKey (respId r))+      off <- getScrollOffsetIO ctx (respId r)+      pure (show (getCursor (tasBuffer s), tasSelectionAnchor s, off))+    scrollProbe ctx r = show <$> getScrollOffsetIO ctx (respId r)+    selectProbe ctx r = (\st -> show (isSelectOpen st (intKey (respId r)))) <$> getStore ctx++-- | The source on top, then the widget under test pushed right and down by+-- spacers so its hot point lands under the overlay.+page :: Maybe Overlay -> Victim -> V2 -> NanoUI Page+page mOv vc (V2 dx dy) =+  columnWith (fixedW 860) $ do+    src <- maybe (label' "no overlay") ovSource mOv+    spacer (Fixed 0) (Fixed dy)+    victim <- row (spacer (Fixed dx) (Fixed 0) >> columnWith (fixedW 320) (vcUi vc))+    pure (src, victim)++-- | Run @script@ on the page with the overlay open, given the widget's hot+-- point (@offset@ into its rect) and where the overlay landed.+withPage :: IORef Int -> Maybe Overlay -> Victim -> V2 -> V2 -> (V2 -> Maybe Rect -> Sim Page r) -> IO r+withPage failed mOv vc (V2 offX offY) shift script = do+  ctx <- newPixelContext+  runSim ctx failed (withInput 900 700) (page mOv vc shift) $ do+    (src, (resp, _)) <- result+    let hot = V2 (rectX (respRect resp) + offX) (rectY (respRect resp) + offY)+    forM_ mOv (\ov -> ovOpen ov src hot)+    (src', _) <- moveTo (At hot)+    script hot =<< maybe (pure (Just (Rect 0 0 900 700))) (`ovRect` src') mOv++runPointerOwnershipTest :: Context -> IORef Int -> IO ()+runPointerOwnershipTest _ failed = do+  vcs <- victims+  let report name msgs = forM_ msgs $ \msg -> putStrLn ("  " <> name <> ": " <> msg) >> bump failed+  forM_ vcs $ \vc -> do+    -- Found with nothing on top, which could hide the spans some widgets need.+    offset <- withPage failed Nothing vc (V2 0 0) (V2 0 0) $ \_ _ -> do+      (_, (resp, _)) <- result+      V2 hx hy <- onContext (\ctx -> vcHot vc ctx resp)+      pure (V2 (hx - rectX (respRect resp)) (hy - rectY (respRect resp)))+    -- The control: with no overlay the widget does notice.+    noticed <- scenario failed Nothing vc offset (V2 0 0) ClickDrag+    when (null noticed) $+      report (vcName vc) ["ignores a click and drag on its hot point, so it tests nothing"]+    forM_ overlays $ \ov -> do+      -- An unshifted run says how far to push the hot point under the overlay.+      shift <- withPage failed (Just ov) vc offset (V2 0 0) $ \(V2 hx hy) mRect ->+        pure (maybe (V2 0 0) (\(Rect ox oy _ _) -> V2 (max 0 (ox + 40 - hx)) (max 0 (oy + 60 - hy))) mRect)+      forM_ [ClickDrag, Wheel, RightClick] $ \gesture ->+        report (ovName ov <> " over " <> vcName vc <> " (" <> show gesture <> ")")+          =<< scenario failed (Just ov) vc offset shift gesture++-- | Everything the widget noticed while the gesture ran on the overlay, or on+-- the widget itself when there is none.+scenario :: IORef Int -> Maybe Overlay -> Victim -> V2 -> V2 -> Gesture -> IO [String]+scenario failed mOv vc offset shift gesture = withPage failed mOv vc offset shift $ \hot@(V2 hx hy) -> \case+  Nothing -> pure ["overlay did not open"]+  Just r | not (rectContains r hot) -> pure ["hot " <> show hot <> " is not under the overlay at " <> show r]+  Just _ -> do+    (_, (resp0, value0)) <- frame+    probe0 <- onContext (\ctx -> vcProbe vc ctx resp0)+    focus0 <- focusedId+    let victimId = respId resp0+        -- Each step, and whether its flags count (hover once the gesture ends is fair).+        steps = case gesture of+          ClickDrag ->+            [ (True, press (At hot))+            , (True, moveTo (At (V2 (hx + 14) (hy - 9))))+            , (True, moveTo (At (V2 (hx + 28) (hy - 18))))+            , (True, release)+            , (False, frame)+            ]+          Wheel -> [(True, frameWith (\i -> i {inputScroll = V2 0 s})) | s <- [3, -3, 3]]+          RightClick ->+            [(True, pressButton MouseRight (At hot)), (True, releaseButton MouseRight), (False, frame)]+    fmap concat . forM (zip [1 :: Int ..] steps) $ \(i, (flags, step)) -> do+      (_, (resp, value)) <- step+      probe <- onContext (\ctx -> vcProbe vc ctx resp)+      focus <- focusedId+      active <- onContext (readIORef . ctxActiveId)+      menu <- onContext (`getsInteraction` isTextInputMenu)+      let state =+            [ (value /= value0, "value " <> value0 <> " -> " <> value)+            , (probe /= probe0, "state " <> probe0 <> " -> " <> probe)+            , (focus == victimId && focus0 /= victimId, "took focus")+            , (active == victimId, "became the active widget")+            , (fmap textInputMenuWidget menu == Just victimId, "opened its context menu")+            ]+          response =+            [ (flags && flag resp, name)+            | (flag, name) <-+                [ (respHovered, "hovered")+                , (respPressed, "pressed")+                , (respClicked, "clicked")+                , (respChanged, "changed")+                , (respRightPressed, "right-pressed")+                , (respRightClicked, "right-clicked")+                ]+            ]+      pure ["frame " <> show i <> ": " <> what | (True, what) <- state <> response]++-- | The frame's unrouted input is for routing code and what watches the whole+-- window; a widget reading presses from it reacts through whatever is on top.+-- The scan starts at the imports, so a re-export passes.+runPointerRoutingLintTest :: Context -> IORef Int -> IO ()+runPointerRoutingLintTest _ failed = do+  root : _ <- filterM doesDirectoryExist ["lib", "packages/nano-ui/lib"]+  files <- haskellFiles root+  when (length files < 50) $ complain ("only " <> show (length files) <> " sources under " <> root)+  forM_ files $ \file -> do+    src <- snd . T.breakOn "\nimport " <$> TIO.readFile file+    let rel = map (\c -> if c == '\\' then '/' else c) (makeRelative root file)+    when ("askFrameInput" `T.isInfixOf` src && rel `notElem` allowed) $+      complain (rel <> " reads the unrouted input (askFrameInput); widgets use askInput")+  where+    allowed =+      [ "NanoUI/Internal/Monad.hs" -- exports it+      , "NanoUI/Internal/Monad/Core.hs" -- defines it+      , "NanoUI/Internal/Widgets/Node.hs" -- routes a floating panel's body and a dropdown's owner+      , "NanoUI/Internal/Widgets/Behavior.hs" -- useDismissable: a press anywhere else dismisses+      , "NanoUI/Internal/Widgets/Popup.hs" -- tooltips: a press anywhere shuts one; one over its target stays+      , "NanoUI/Internal/ChildWindow.hs" -- a further floatingWindow's view starts from its frame's input, as a frame does+      ]+    complain msg = putStrLn ("  " <> msg) >> bump failed+    haskellFiles dir = do+      entries <- map (dir </>) <$> listDirectory dir+      dirs <- filterM doesDirectoryExist entries+      (filter ((== ".hs") . takeExtension) entries <>) . concat <$> mapM haskellFiles dirs++captureUi :: NanoUI ((Response, Float), Maybe Response)+captureUi = do+  s <- columnWith (fixedW 320) (withValue 50 (slider' 0 100))+  (_, b) <- floatingWindow' (constVar True) "Capture window" (columnWith (fixedWH 300 200) (button' "inside"))+  pure (s, b)++-- | A held button stays with the layer it went down in, page or window, and+-- wakes nothing in the other; a press is routed afresh even with another+-- button still down.+pointerCapture :: Sim ((Response, Float), Maybe Response) ()+pointerCapture = do+  ((slider0, _), Just inside0) <- result+  let Rect sx sy sw sh = respRect slider0+      Rect bx by _ bh = respRect inside0+      onTrack = At (V2 (sx + sw * 0.25) (sy + sh / 2))+      onButton = On inside0+  -- The scenario needs the window clear of the slider.+  check (v2X (centerOf inside0) > sx + sw)+  ((_, dragged), overWindow) <- press onTrack >> moveTo onButton+  checkEq 100 dragged+  check (maybe False (not . respHovered) overWindow)+  ((_, rested), free) <- release >> moveTo onButton+  check (maybe False respHovered free)+  ((overPage, crossed), _) <- press (At (V2 (bx + 4) (by + bh + 40))) >> moveTo onTrack+  checkEq rested crossed+  check (not (respHovered overPage))+  ((freed, _), _) <- release >> frame+  check (respHovered freed)+  -- With the right button held on the page, a left click in the window lands.+  (_, chorded) <- pressButton MouseRight onTrack >> click onButton+  check (maybe False respClicked chorded)
test/integration/Cases/PointerRelease.hs view
@@ -1,146 +1,105 @@+{-# OPTIONS_GHC -O0 #-} -- | A click belongs to the widget its press went down on. Dragging off a -- widget and letting go over a neighbour must fire nothing.-module Cases.PointerRelease-  ( runReleaseElsewhereTest-  , runRightReleaseElsewhereTest-  , runReleaseReturnsTest-  , runOverlapPressTest-  ) where+module Cases.PointerRelease (tests) where -import Control.Monad (void)-import Data.IORef (IORef, newIORef)-import Data.Maybe (isJust, isNothing)-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, withInput)-import NanoUI.Testing.Harness (centerOf, held, warmup2)+import Spec+import Data.Maybe (isJust)+import Data.Text qualified as T+import NanoUI.Testing.Sim --- | Press one widget, drag onto another, release: neither one fires, this--- frame or the next.+tests :: [Spec]+tests =+  [ spec "release-elsewhere" runReleaseElsewhereTest+  , spec "release-moved" runReleaseMovedTest+  , spec "release-tap-and-modal" runReleaseTapAndModalTest+  ]++-- | A drag between widgets fires neither, that frame or the next, while one+-- that comes back still clicks; a context menu opens where its right press+-- went down. Of two overlapping widgets the press goes to the one painted on+-- top, and a button clipped by its panel takes no click. runReleaseElsewhereTest :: Context -> IORef Int -> IO () runReleaseElsewhereTest ctx failed = do-  -- The checkbox drives its own state across frames, so a stray toggle sticks-  -- and the value assertions below have something to catch.-  flag <- newIORef False-  let inp0 = withInput 320 240-      ui = column $ do+  flag <- newVar False+  let ui = column $ do         a <- button' "Alpha"         b <- button' "Beta"         (cb, on) <- held flag (checkbox' "Flag")-        pure (a, b, cb, on)--  (a, b, cb, _) <- warmup2 ctx inp0 ui-  let at r = inp0 {inputMousePos = centerOf r}-      pressOn r = (at r) {inputMouseDown = True, inputMousePressed = True}-      dragTo r p = p {inputMousePos = centerOf r, inputMousePressed = False}-      releaseOn r p = (dragTo r p) {inputMouseDown = False, inputMouseReleased = True}--  -- Button to button.-  _ <- runFrame ctx (pressOn a) ui-  ((_, bDrag, _, _), _, _, _) <- runFrame ctx (dragTo b (pressOn a)) ui-  assert failed (not (respHovered bDrag) && not (respPressed bDrag))-  ((aUp, bUp, _, _), _, _, _) <- runFrame ctx (releaseOn b (pressOn a)) ui-  assert failed (not (respClicked aUp) && not (respClicked bUp))-  ((aNext, bNext, _, _), _, _, _) <- runFrame ctx (at b) ui-  assert failed (not (respClicked aNext) && not (respClicked bNext))--  -- Button to checkbox: the checkbox must not toggle.-  _ <- runFrame ctx (pressOn a) ui-  ((_, _, cbUp, _), _, _, _) <- runFrame ctx (releaseOn cb (pressOn a)) ui-  assert failed (not (respClicked cbUp))-  ((_, _, _, checked), _, _, _) <- runFrame ctx (at cb) ui-  assert failed (not checked)--  -- Checkbox to button: neither fires, and the box stays clear.-  _ <- runFrame ctx (pressOn cb) ui-  ((_, bOver, cbOff, _), _, _, _) <- runFrame ctx (releaseOn b (pressOn cb)) ui-  assert failed (not (respClicked bOver) && not (respClicked cbOff))-  ((_, _, _, stillOff), _, _, _) <- runFrame ctx (at b) ui-  assert failed (not stillOff)---- | The same rule for the right button: a context menu opens where the right--- press went down, not where it came up. Also covers the container path, since--- the menu area's response comes from a container node rather than a leaf.-runRightReleaseElsewhereTest :: Context -> IORef Int -> IO ()-runRightReleaseElsewhereTest ctx failed = do-  let inp0 = withInput 320 240-      ui = column $ do-        a <- button' "Alpha"-        (lbl, menu) <--          contextMenuArea (fixedH 60 . fillW) (label' "Area") (const (menuItem "Cut"))-        pure (a, lbl, menu)-  (a, lbl, _) <- warmup2 ctx inp0 ui-  let rightPressOn r =-        inp0-          { inputMousePos = centerOf r-          , inputMouseRightDown = True-          , inputMouseRightPressed = True-          }-      rightReleaseOn r p =-        p-          { inputMousePos = centerOf r-          , inputMouseRightPressed = False-          , inputMouseRightDown = False-          , inputMouseRightReleased = True-          }--  -- Right press on the button, release over the menu area: no menu.-  _ <- runFrame ctx (rightPressOn a) ui-  ((aUp, _, menuUp), _, _, _) <- runFrame ctx (rightReleaseOn lbl (rightPressOn a)) ui-  assert failed (not (respRightClicked aUp))-  assert failed (isNothing menuUp)--  -- Right press and release inside the area: the menu opens.-  _ <- runFrame ctx (rightPressOn lbl) ui-  ((_, _, menuSame), _, _, _) <- runFrame ctx (rightReleaseOn lbl (rightPressOn lbl)) ui-  assert failed (isJust menuSame)---- | Leaving a widget mid-press and coming back still clicks it, and a plain--- press-release on one widget is unaffected.-runReleaseReturnsTest :: Context -> IORef Int -> IO ()-runReleaseReturnsTest ctx failed = do-  let inp0 = withInput 320 240-      ui = column $ do-        a <- button' "Alpha"-        b <- button' "Beta"-        pure (a, b)-  (a, b) <- warmup2 ctx inp0 ui-  let at r = inp0 {inputMousePos = centerOf r}-      pressOn r = (at r) {inputMouseDown = True, inputMousePressed = True}-      moveTo r p = p {inputMousePos = centerOf r, inputMousePressed = False}-      releaseOn r p = (moveTo r p) {inputMouseDown = False, inputMouseReleased = True}--  -- Straight click.-  _ <- runFrame ctx (pressOn a) ui-  ((aUp, _), _, _, _) <- runFrame ctx (releaseOn a (pressOn a)) ui-  assert failed (respClicked aUp)+        -- The menu area's response comes from a container node, not a leaf.+        (area, menu) <- contextMenuArea (fixedH 60 . fillW) (label' "Area") (const (menuItem "Cut"))+        overlapping <- rowWith (gap (-30)) (mapM (buttonWith' (fixedW 80)) ["Left", "Right"])+        clipped <- panelWith (fixedWH 200 60) (column (mapM button' ["One", "Two", "Three"]))+        pure ([a, b, cb, area] <> overlapping <> drop 2 clipped, on, isJust menu)+  runSim ctx failed (withInput 320 400) ui $ do+    (rs, _, _) <- result+    let on i = On (rs !! i)+        responses (xs, _, _) = xs+    forM_ [(0, 1), (0, 2), (2, 1)] $ \(from, to) -> do+      (over, _, _) <- press (on from) >> moveTo (on to)+      check (not (respHovered (over !! to) || respPressed (over !! to)))+      ups <- sequence [release, frame]+      check (not (or [respClicked r || checked | (rs', checked, _) <- ups, r <- take 3 rs']))+    check . respClicked . (!! 0) . responses =<< click (on 0)+    check . respClicked . (!! 1) . responses =<< (press (on 1) >> moveTo (on 0) >> moveTo (on 1) >> release)+    _ <- pressButton MouseRight (on 0) >> moveTo (on 3)+    (up, _, menuUp) <- releaseButton MouseRight+    check (not (respRightClicked (up !! 0) || menuUp))+    check . (\(_, _, menu) -> menu) =<< rightClick (on 3)+    let Rect lx ly lw lh = respRect (rs !! 4)+        overlap = At (V2 (lx + lw - 10) (ly + lh / 2))+    _ <- moveTo overlap+    checkEq (respId (rs !! 4)) =<< hotId+    pressed <- map respPressed . take 2 . drop 4 . responses <$> (press overlap >> frame)+    checkEq [True, False] pressed+    _ <- release+    [p] <- map snd <$> onContext (nodesOfType NodePanel)+    check (not (rectContains p (centerOf (rs !! 6))))+    ups <- sequence [press (on 6), release]+    check (not (or [respHovered t || respClicked t | (xs, _, _) <- ups, t <- drop 6 xs])) -  -- Wander off and back before letting go.-  _ <- runFrame ctx (pressOn b) ui-  _ <- runFrame ctx (moveTo a (pressOn b)) ui-  ((_, bBack), _, _, _) <- runFrame ctx (releaseOn b (pressOn b)) ui-  assert failed (respClicked bBack)-  void (runFrame ctx inp0 ui)+-- | A release on a control that moved there in the release's own frame does+-- not click it: the user did not see it there. A release on a control that+-- moved in an earlier frame, while the button was held, clicks it in the+-- release's own frame.+runReleaseMovedTest :: Context -> IORef Int -> IO ()+runReleaseMovedTest _ failed = do+  forM_ [False, True] $ \earlier -> do+    sel <- newVar (0 :: Int)+    cur <- newVar (0 :: Int)+    let radioUi = snd <$> held sel (radio' ["one", "two", "three"])+        tabsUi = snd <$> held cur (`tabBar'` [tab 0 "Alpha" (), tab 1 "Beta" ()])+    forM_ [("two", radioUi), ("Beta", tabsUi)] $ \(lbl, body) -> do+      ctx <- newContext+      shift <- newIORef 0+      let ui = column (liftIO (readIORef shift) >>= \d -> columnWith (fixedH d . fillW) (pure ()) >> body)+      runSim ctx failed (withInput 320 240) ui $ do+        V2 px py <- targetPoint (Labelled lbl)+        _ <- press (At (V2 px py))+        liftIO (writeIORef shift 100)+        when earlier $ void (moveTo (At (V2 px (py + 100))))+        released <- frameWith (releaseWith MouseLeft . \i -> i {inputMousePos = V2 px (py + 100)})+        after <- frame+        checkEq (if earlier then (1, 1) else (0, 0)) (released, after) --- | Where two widgets overlap, a held press belongs to the one hover lights--- up: the earlier sibling, which paints on top.-runOverlapPressTest :: Context -> IORef Int -> IO ()-runOverlapPressTest ctx failed = do-  let inp0 = withInput 320 240-      ui = rowWith (gap (-30)) $ do-        a <- buttonWith' (fixedW 80) "Alpha"-        b <- buttonWith' (fixedW 80) "Beta"-        pure (a, b)-  (a, _) <- warmup2 ctx inp0 ui-  let Rect ax ay aw ah = respRect a-      overlap = inp0 {inputMousePos = V2 (ax + aw - 10) (ay + ah / 2)}-      press = overlap {inputMouseDown = True, inputMousePressed = True}-      held' = overlap {inputMouseDown = True}-  _ <- runFrame ctx overlap ui-  hot <- getHotId ctx-  assert failed (hot == respId a)-  _ <- runFrame ctx press ui-  ((aHeld, bHeld), _, _, _) <- runFrame ctx held' ui-  assert failed (respPressed aHeld && not (respPressed bHeld))-  void (runFrame ctx (overlap {inputMouseReleased = True}) ui)-  void (runFrame ctx inp0 ui)+-- | A press and release in one frame clicks the button the user saw, not the+-- keyed one the click moves there. A modal that opens while a page button is+-- held hides it from the release.+runReleaseTapAndModalTest :: Context -> IORef Int -> IO ()+runReleaseTapAndModalTest ctx failed = do+  items <- newVar [1 .. 5 :: Int]+  open <- newVar False+  let ui = column $ do+        xs <- readVar items+        forM_ xs $ \i -> withKey i $+          whenM (button (T.pack ("Delete " <> show i))) (modifyVar items (filter (/= i)))+        modal open "Error" (label "Something failed")+  runSim ctx failed (withInput 320 240) ui $ do+    p <- targetPoint "Delete 3"+    _ <- frameWith (\i -> applyMouseButton MouseLeft False (pressWith MouseLeft i p))+    replicateM_ 2 frame+    checkEq [1, 2, 4, 5] =<< readV items+    _ <- press "Delete 1"+    writeV open True+    _ <- frame >> release >> frame >> frame+    checkEq [1, 2, 4, 5] =<< readV items
+ test/integration/Cases/Reorder.hs view
@@ -0,0 +1,144 @@+{-# OPTIONS_GHC -O0 #-}+-- | 'useReorder': a drag past the threshold moves an item, with a live+-- preview, over wrapped rows too, and a click moves nothing.+module Cases.Reorder (tests) where++import Spec+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "reorder-drag" runReorderDragTest+  , spec "reorder-preview-stable" runReorderPreviewStableTest+  , spec "reorder-stale-drag" runReorderStaleDragTest+  , spec "reorder-owned-press" runReorderOwnedPressTest+  , spec "insertion-index-bounds" runInsertionIndexTest+  , spec "drag-idle-and-abort" runDragIdleAndAbortTest+  ]++-- | Five 40 by 30 slots in a row, 50 apart.+slotsInRow :: [Rect]+slotsInRow = [Rect (fromIntegral i * 50) 0 40 30 | i <- [0 .. 4 :: Int]]++-- Synthetic owned responses isolate the reorder math from widget layout.+responses :: Input -> [(Int, Rect)] -> [(Int, Response)]+responses inp = map $ \(i, rect) -> (i, mempty+  { rawRespRect = rect+  , rawRespHeld = if heldIn MouseLeft inp && rectContains rect (inputMousePos inp)+      then buttonsFromList [MouseLeft] else noButtons+  })++-- | 'useReorder' over fixed rects on a fresh context, for an idle frame, a+-- press at @from@, a hold at each of @path@, the release and an idle frame.+dragThrough :: [Int] -> [Rect] -> V2 -> [V2] -> IO [Reorder]+dragThrough order rects from path = do+  ctx <- newContext+  let inp = withInput 400 200+      down = pressAt inp from+      holds = map (holdAt down) path+      frames = [inp, down] ++ holds ++ [releaseAt (last (down : holds)), inp]+  mapM (\i -> evalUi ctx i (useReorder order (responses i (zip order rects)))) frames++runReorderDragTest :: Context -> IORef Int -> IO ()+runReorderDragTest _ failed = do+  let order = [0 .. 4]+      moved = [1, 2, 3, 4, 0]+  [_, pressed, nudged, dragged, dropped, after] <- dragThrough order slotsInRow (V2 20 15) [V2 23 15, V2 230 15]+  assertEq failed (Just 0) (reorderDragging pressed)+  -- Under the threshold: no preview yet.+  assertEq failed (False, order) (reorderMoved nudged, reorderPreview nudged)+  assertEq failed (True, moved, order) (reorderMoved dragged, reorderPreview dragged, reorderOrder dragged)+  assertEq failed (True, moved) (reorderMoved dropped, reorderOrder dropped)+  assertEq failed (False, Nothing) (reorderMoved after, reorderDragging after)+  -- Item ids can be any Int: negative ones drag like the rest.+  [_, _, _, negDropped, _] <- dragThrough [-1, -2, 0, 3, -7] slotsInRow (V2 20 15) [V2 230 15]+  assertEq failed [-2, 0, 3, -7, -1] (reorderOrder negDropped)+  -- A press and release in place is a click: nothing moves.+  [_, _, clicked, _] <- dragThrough order slotsInRow (V2 120 15) []+  assertEq failed (False, order) (reorderMoved clicked, reorderOrder clicked)+  -- Wrapped over two rows: the item takes the place of the one nearest the+  -- pointer on the second row, even in the gap right of it.+  let wrapped = take 3 slotsInRow ++ [Rect 0 40 40 30, Rect 50 40 40 30]+  [_, _, _, wrapDropped, _] <- dragThrough order wrapped (V2 20 15) [V2 43 55]+  assertEq failed [1, 2, 3, 0, 4] (reorderOrder wrapDropped)++-- | Drawn from the preview, the dragged item sits in the slot it is over,+-- so the target stays put frame after frame.+runReorderPreviewStableTest :: Context -> IORef Int -> IO ()+runReorderPreviewStableTest ctx failed = do+  shown <- newIORef [0 .. 4 :: Int]+  let ui = do+        drawn <- liftIO (readIORef shown)+        input <- askInput+        r <- useReorder [0 .. 4] (responses input (zip drawn slotsInRow))+        liftIO (writeIORef shown (reorderPreview r))+        pure r+  runSim ctx failed (withInput 400 200) ui $ do+    _ <- press (At (V2 20 15))+    previews <- replicateM 3 (reorderPreview <$> moveTo (At (V2 170 15)))+    checkEq (replicate 3 [1, 2, 3, 0, 4]) previews++-- | A drag released while the hook did not run is over: a press elsewhere,+-- still held when the hook runs again, carries no item and drops none.+runReorderStaleDragTest :: Context -> IORef Int -> IO ()+runReorderStaleDragTest ctx failed = do+  let inp = withInput 400 200+      order = [0 .. 4]+      reorderAt i = evalUi ctx i (useReorder order (responses i (zip order slotsInRow)))+      skip i = evalUi ctx i (pure ())+      down = pressAt inp (V2 20 15)+      far = holdAt down (V2 230 15)+      elsewhere = pressAt inp (V2 300 150)+      later = holdAt elsewhere (V2 230 160)+  mapM_ reorderAt [inp, down]+  assertEq failed (Just 0) . reorderDragging =<< reorderAt far+  mapM_ skip [releaseAt far, elsewhere]+  assertEq failed Nothing . reorderDragging =<< reorderAt later+  assertEq failed order . reorderOrder =<< reorderAt (releaseAt later)++-- | Covered and clipped controls cannot start a reorder gesture.+runReorderOwnedPressTest :: Context -> IORef Int -> IO ()+runReorderOwnedPressTest _ failed = do+  let contents = columnWith tight $ do+        items <- rowWith (tight . gap 10) $+          forM [0, 1 :: Int] $ \i -> (i,) <$> buttonWith' (fixedWH 40 30) "Item"+        useReorder [0, 1] items+      covered = layersWith (fixedWH 100 50) $ do+        r <- contents+        panelWith (pointer PointerBlock . fixedWH 40 30) (pure ())+        pure r+      clipped = scrollWith (fixedWH 40 30) contents+  forM_ [(covered, V2 20 15), (clipped, V2 70 15)] $ \(ui, pos) -> do+    ctx <- newContext+    runSim ctx failed (withInputOff 300 100) ui $ do+      checkEq Nothing . reorderDragging =<< press (At pos)+      _ <- moveTo (At (V2 90 15))+      checkEq [0, 1] . reorderOrder =<< release++runInsertionIndexTest :: Context -> IORef Int -> IO ()+runInsertionIndexTest _ failed = do+  let bounds = Rect 0 0 250 30+      hit = insertionIndex DragAxisX bounds slotsInRow+  assertEq failed [Just 0, Just 2, Just 5] (map hit [V2 1 15, V2 100 15, V2 249 15])+  forM_ [V2 (-1) 15, V2 251 15, V2 20 (-1), V2 20 31] $ \p ->+    assertEq failed Nothing (hit p)+  assertEq failed (Just 0) (insertionIndex DragAxisX bounds [] (V2 10 10))+  let column2 = [Rect 0 0 30 40, Rect 0 50 30 40]+  assertEq failed (Just 1) (insertionIndex DragAxisY (Rect 0 0 30 100) column2 (V2 15 55))+  assertEq failed (Just 1) (insertionIndex DragAxisX (Rect 50 0 100 30) slotsInRow (V2 51 15))++-- | A drag whose pointer leaves for nowhere ends, and one held still asks for+-- no more frames.+runDragIdleAndAbortTest :: Context -> IORef Int -> IO ()+runDragIdleAndAbortTest ctx failed = do+  dragHandle <- newDrag+  let inp = withInput 400 200+      ui = useDrag dragHandle [(1 :: Int, mempty {rawRespHeld = buttonsFromList [MouseLeft]})]+      down = pressAt inp (V2 10 10)+      moved = holdAt down (V2 40 10)+  _ <- evalUi ctx down ui+  assertEq failed Nothing =<< evalUi ctx (inp {inputMousePos = V2 (-10000) (-10000)}) ui+  mapM_ (\i -> runFrame ctx i ui) [down, moved, moved]+  (gesture, _, dirty) <- runFrame ctx moved ui+  assertEq failed (Just Dragging) (dragPhase <$> gesture)+  assert failed (not dirty)
test/integration/Cases/RichText.hs view
@@ -1,66 +1,340 @@-module Cases.RichText-  ( runRichTextWrapTest-  , runRichTextLinkTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.RichText (tests) where -import Control.Monad (void)-import Data.IORef (IORef)+import Spec+import Control.Exception (evaluate)+import Data.Foldable (toList)+import Data.IntMap.Strict qualified as IM+import Data.List (groupBy, sortOn)+import Data.Maybe (listToMaybe)+import Data.Primitive.PrimArray (primArrayFromList) import Data.Text qualified as T-import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Testing (UiCursorKind (..), cursorKindIs, runFrame)-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness (clickPair, drawQuads, warmup2)+import NanoUI.Internal.Context (Context (..), CustomDrawingEntry (..), DrawingCacheState (..), hoverZoneCrossed, intKey, lookupCustomDrawing)+import NanoUI.Internal.Context.Types (CustomDrawOpCacheEntry (..))+import NanoUI.Internal.Widgets.Custom (mkCustomDrawContext)+import NanoUI.Internal.Store (fieldRichSelection, lookupSlot, ptrEq)+import NanoUI.Shortcut (cmdOrCtrl, key)+import NanoUI.Testing.Sim --- | A paragraph wraps at its column's width, taking a line's height per line,--- and mixed pieces share a line.+tests :: [Spec]+tests =+  [ spec "rich-text-wrap" runRichTextWrapTest+  , spec "rich-text-link" runRichTextLinkTest+  , spec "rich-text-align" runRichTextAlignTest+  , spec "rich-text-many" runRichTextManyTest+  , spec "rich-text-background" runRichTextBackgroundTest+  , spec "rich-text-scroll-cull" runRichTextScrollCullTest+  , spec "rich-text-relayout" runRichTextRelayoutTest+  , spec "rich-text-scroll-popup" runRichTextScrollPopupTest+  , spec "rich-text-selection" runSelectionTest+  , spec "rich-text-tooltips" runRichTextTooltipsTest+  ]++inp400 :: Input+inp400 = withInput 400 400++-- | The ops the rich text @resp@ draws in its last laid-out rect.+drawnOps :: Context -> Response -> IO [DrawOp]+drawnOps ctx resp = do+  Just entry <- lookupCustomDrawing ctx (respId resp)+  cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) (respId resp)+  pure (toList (cdrBuild entry cdc (respRect resp)))++-- | The paragraph's rect and ops once the view settles.+settledOps :: Context -> Input -> NanoUI Response -> IO (Rect, [DrawOp])+settledOps ctx inp ui = warmup2 ctx inp ui >>= \resp -> (respRect resp,) <$> drawnOps ctx resp++-- | Each text op's position and text.+texts :: [DrawOp] -> [(Float, Float, T.Text)]+texts ops = [(x, y, t) | DrawTextStyled x y _ t _ <- ops]++-- | The ops a widget was last painted with, and their bounds.+cachedOps :: Context -> WidgetId -> IO (Maybe (Rect, [DrawOp]))+cachedOps c wid =+  fmap (\e -> (cdeBounds e, toList (cdeOps e))) . IM.lookup (intKey wid) . dcsCustomDrawOpCache <$> readIORef (ctxDrawingCache c)++-- | Focus @r@ and select all of it.+selectAll :: Context -> Input -> NanoUI a -> Response -> IO ()+selectAll c inp ui r = setFocus c (respId r) >> void (evalUi c (chordInp (cmdOrCtrl <> key 'a') inp) ui)++-- | Wrapping at the column's width, leading-space indents, 'textBreak'+-- policies (whole words, or anywhere but inside a flag), and newlines+-- beside joiners and marks under 'breakAnywhere'. runRichTextWrapTest :: Context -> IORef Int -> IO () runRichTextWrapTest ctx failed = do-  let inp = withInput 400 400-      paragraph = [inlineText (T.replicate 12 "word "), strong "bold", " end"]-      ui = columnWith (fixedW 200) $ do-        one <- fst <$> richText' ["word"]-        wrapped <- fst <$> richText' paragraph-        pure (one, wrapped)-  (one, wrapped) <- warmup2 ctx inp ui-  let Rect _ _ _ lineH = respRect one-      Rect _ _ w h = respRect wrapped-  assert failed (lineH > 0)-  assert failed (w <= 200)-  -- Twelve words and two more pieces cannot fit on one 200px line.-  assert failed (h >= 2 * lineH)+  let fm = ctxFontMetrics ctx+      heightOf f pieces = rectH . respRect . fst <$> warmup2 ctx (withInput 600 400) (column (richTextWith' f pieces))+      flag = "\x1F1FA\x1F1F8"+  lineH <- heightOf id ["word"]+  let paragraph = [inlineText (T.replicate 12 "word "), strong "bold", " end"]+  Rect _ _ w h <- respRect <$> warmup2 ctx inp400 (columnWith (fixedW 200) (fst <$> richText' paragraph))+  assert failed (lineH > 0 && w <= 200 && h >= 2 * lineH)   assertEq failed 0 (round h `mod` round lineH :: Int)+  (Rect rx _ _ _, indented) <- settledOps ctx inp400 (column (fst <$> richText' ["  where\n    go = 1"]))+  case ([x - rx | (x, _, "where") <- texts indented], [x - rx | (x, _, "go") <- texts indented]) of+    ([wx], [gx]) -> assert failed (wx > 0 && abs (gx - 2 * wx) < 0.5)+    _ -> assert failed False+  advA <- lineWidthIO fm "a"+  advFlag <- lineWidthIO fm (T.take 1 flag)+  monoH <- heightOf fontMono ["a"]+  assert failed (monoH > 0 && advA > 0 && advFlag > 0)+  let word = [inlineText "abcdefghijklmnop"]+  assertEq failed [monoH, 2 * monoH]+    =<< sequence [heightOf (fontMono . fixedW (8 * advA)) word, heightOf (fontMono . breakAnywhere . fixedW (8.5 * advA)) word]+  -- Each flag is two regional indicators that fit a line only together.+  flagH <- heightOf id [inlineText flag]+  assertEq failed (3 * flagH) =<< heightOf (breakAnywhere . fixedW (1.5 * advFlag)) [inlineText (T.replicate 3 flag)]+  forM_ ["one\n\x200Dtwo", "one\x200D\ntwo", "one\n\x0301two"] $ \txt -> do+    (_, ops) <- settledOps ctx inp400 (column (fst <$> richTextWith' breakAnywhere [inlineText txt]))+    let drawn = [(y, t) | (_, y, t) <- texts ops]+    assertEq failed (txt, 2, T.filter (/= '\n') txt) $+      (txt, length (groupBy (\a b -> fst a == fst b) drawn), T.concat (map snd drawn)) --- | A link reports its target when clicked and shows the pointer cursor;--- text beside it reports nothing.+-- | A link reports its target when clicked, shows the pointer and one+-- underline when hovered; text beside it, or a drag from there onto it,+-- reports nothing. A move along the link runs no frame, one onto it does. runRichTextLinkTest :: Context -> IORef Int -> IO () runRichTextLinkTest ctx failed = do-  let inp0 = withInput 400 400+  let fm = ctxFontMetrics ctx       ui = column (richText' ["Go to ", hyperlink "docs-target" "the docs", " now"])-      fm = ctxFontMetrics ctx-  (resp, _) <- warmup2 ctx inp0 ui   prefixW <- sum <$> mapM (lineWidthIO fm) ["Go", " ", "to", " "]   linkW <- sum <$> mapM (lineWidthIO fm) ["the", " ", "docs"]-  let Rect rx ry _ rh = respRect resp-      onLink = V2 (rx + prefixW + linkW / 2) (ry + rh / 2)-      onText = V2 (rx + 2) (ry + rh / 2)-      clickAt pos = do-        let (press, release) = clickPair inp0 pos-        void (runFrame ctx inp0 {inputMousePos = pos} ui)-        void (runFrame ctx press ui)-        ((_, clicked), _, _, _) <- runFrame ctx release ui-        pure clicked-  linkClick <- clickAt onLink-  assertEq failed (Just "docs-target") linkClick-  pointer <- cursorKindIs ctx inp0 {inputMousePos = onLink} UiCursorPointer-  assert failed pointer-  -- The hovered link is underlined once, across its words and the space-  -- between them.-  (_, _, dd, _) <- runFrame ctx inp0 {inputMousePos = onLink} ui-  quads <- drawQuads dd-  let underlines = [r | (r@(Rect _ _ w h), _) <- quads, h < 3, abs (w - linkW) < 0.5]-  assertEq failed 1 (length underlines)-  textClick <- clickAt onText-  assertEq failed Nothing textClick-  plainCursor <- cursorKindIs ctx inp0 {inputMousePos = onText} UiCursorPointer-  assert failed (not plainCursor)+  docsW <- lineWidthIO fm "docs"+  runSim ctx failed inp400 ui $ do+    Rect rx ry _ rh <- respRect . fst <$> result+    let pt dx = V2 (rx + dx) (ry + rh / 2)+        (onLink, onLinkStart, onText) = (pt (prefixW + linkW / 2), pt (prefixW + 1), pt 2)+        onLinkEnd = pt (prefixW + linkW - docsW / 2)+        clickAt p = moveTo (At p) >> snd <$> click (At p)+        cursorIsPointer p = (== UiCursorPointer) <$> cursorAt (At p)+    checkEq (Just "docs-target") =<< clickAt onLink+    check =<< cursorIsPointer onLink+    (_, dd, _) <- liftIO . (\i -> runFrame ctx i ui) =<< getInput+    quads <- liftIO (drawQuads dd)+    checkEq 1 (length [r | (r@(Rect _ _ w h), _) <- quads, h < 3, abs (w - linkW) < 0.5])+    checkEq Nothing =<< clickAt onText+    check . not =<< cursorIsPointer onText+    checkEq Nothing . snd =<< drag (At onText) (At onLink) 1+    _ <- moveTo (At onLinkStart)+    check . not =<< liftIO (hoverZoneCrossed ctx onLinkStart onLinkEnd)+    check =<< liftIO (hoverZoneCrossed ctx onText onLinkStart)++-- | Each line aligns within the box, a fit-width paragraph lands where a+-- full-width one does, and a word wider than the box starts at its left edge.+runRichTextAlignTest :: Context -> IORef Int -> IO ()+runRichTextAlignTest ctx failed = do+  let fm = ctxFontMetrics ctx+      paragraph = [inlineText "a few words of different lengths ", strong "wrapping", " over several lines here"]+      -- The paragraph's box and each drawn line's left and right edges.+      linesOf width align = do+        (r, ops) <- settledOps ctx inp400 (columnWith (fixedW 200) (fst <$> richTextWith' (width . align) paragraph))+        extents <- forM (texts ops) $ \(x, y, t) -> (\w -> (y, x, x + w)) <$> lineWidthIO fm t+        let lines' = groupBy (\(a, _, _) (b, _, _) -> a == b) extents+        pure (r, [(minimum [x0 | (_, x0, _) <- l], maximum [x1 | (_, _, x1) <- l]) | l <- lines'])+  forM_ [(alignEnd, 1), (alignCenter, 0.5 :: Float)] $ \(align, pt) -> do+    (Rect rx _ rw _, full) <- linesOf fillW align+    (_, fitted) <- linesOf id align+    assert failed (length full > 1)+    forM_ full $ \(x0, x1) -> assertEq failed (round (rx + pt * rw) :: Int) (round (x0 + pt * (x1 - x0)))+    assertEq failed full fitted+    (Rect ox _ _ _, ops) <-+      settledOps ctx inp400 (columnWith (fixedW 40) (fst <$> richTextWith' (fillW . align) ["supercalifragilistic", " short"]))+    let xs = [x | (x, _, _) <- texts ops]+    assert failed (not (null xs) && all (>= ox - 0.5) xs)++-- | A view with more paragraphs than the cache bound still keeps them all:+-- an unchanged frame measures nothing.+runRichTextManyTest :: Context -> IORef Int -> IO ()+runRichTextManyTest base failed = do+  measured <- newIORef (0 :: Int)+  recording <- newIORef False+  let fm = ctxFontMetrics base+      prepare _ = readIORef recording >>= \on -> fm <$ when on (modifyIORef' measured (+ 1))+  -- Evaluated once so every frame shares this context and its metrics source.+  ctx <- evaluate (withFontMetrics base fm {fmBackend = Just (FontBackend prepare (const (pure Nothing)))})+  let ui = column (forM_ [1 .. 4500 :: Int] (\i -> richText [inlineText (T.pack (show i))]))+      frame' = runFrame ctx inp400 (liftIO (writeIORef recording True) *> ui <* liftIO (writeIORef recording False))+  replicateM_ 3 frame'+  writeIORef measured 0+  replicateM_ 2 frame'+  assertEq failed 0 =<< readIORef measured++-- | A piece's background spans its words and inner spaces, under them, the+-- line box's height. Changing the colour counts as a new paragraph.+runRichTextBackgroundTest :: Context -> IORef Int -> IO ()+runRichTextBackgroundTest ctx failed = do+  let fm = ctxFontMetrics ctx+      tint = colorRGBA 1 2 3 255+      opsOf c = settledOps ctx inp400 . column $+        fst <$> richText' ["Run ", inlineBackground c (inlineCode " cabal build "), " first"]+  (Rect rx ry _ rh, ops) <- opsOf tint+  prefixW <- sum <$> mapM (lineWidthIO fm) ["Run", " ", " "]+  codeW <- sum <$> mapM (lineWidthIO fm) ["cabal", " ", "build"]+  -- One line, so its box is the paragraph's.+  case [r | FillRect r c <- ops, c == tint] of+    [Rect x y w h] -> assert failed (all ((< 0.5) . abs) [x - (rx + prefixW), w - codeW, y - ry, h - rh])+    fills -> assertEq failed 1 (length fills)+  -- Under the words: the fill comes before the first text op.+  assert failed (length (takeWhile (\case DrawTextStyled {} -> False; _ -> True) ops) >= 1)+  (_, plain) <- opsOf (colorRGBA 9 9 9 255)+  assertEq failed [] [r | FillRect r c <- plain, c == tint]++-- | A paragraph far taller than its scroller draws only the words near the+-- viewport, and every row of the viewport inside its padding still shows+-- one, wherever the scroller is. Monospace glyphs are boxes a line tall.+runRichTextScrollCullTest :: Context -> IORef Int -> IO ()+runRichTextScrollCullTest ctx failed = do+  let inp = withInputOff 300 220+      paragraph = [inlineText (T.pack ("word" <> show i <> " ")) | i <- [1 .. 2000 :: Int]]+      ui = fmap fst $ scrollArea (fillW . fixedH 100) (richTextWith fillW paragraph)+  sid <- warmup2 ctx inp ui+  forM_ [0, 3333, 1000000] $ \off -> do+    setScrollOffsetIO ctx sid off+    (_, draw) <- warmupDraw ctx inp ui+    assertJustM failed (getPrevRect ctx sid) $ \(Rect rx ry rw rh) -> do+      quads <- drawQuads draw+      -- Glyph boxes, not the scroller's backdrop, border or bar.+      let glyphs = [r | (r@(Rect qx _ qw qh), _) <- quads, qw < 40, qh < 40, qx < rx + rw / 2]+          shown y = any (\(Rect _ gy _ gh) -> gy <= y && y < gy + gh) glyphs+      assert failed (length quads < 1000 && all shown [ry + fromIntegral k | k <- [12, 17 .. floor rh - 12 :: Int]])++-- | A paragraph resized every frame, or capped under a width while hovered,+-- edited and resized, draws as one laid out from the start. The same pieces+-- (a Markdown document's closed blocks) still follow layout and theme.+runRichTextRelayoutTest :: Context -> IORef Int -> IO ()+runRichTextRelayoutTest ctx failed = do+  let paragraph t = [inlineText t, strong "wrapping", " over several lines ", hyperlink "x" "here"]+      ui width t = column (fst <$> richTextWith' width (paragraph t))+      sameAsFresh c inp view = do+        drawn <- evalUi c inp view >>= cachedOps c . respId+        fresh <- newContext >>= \f -> warmup f inp view >> evalUi f inp view >>= cachedOps f . respId+        assert failed (drawn /= Nothing && drawn == fresh)+        pure drawn+      resized = ui fillW "a few words of different lengths "+  void (warmup2 ctx (withInputOff 400 400) resized)+  forM_ [180, 260, 150, 320, 400] $ \w -> sameAsFresh ctx (withInputOff w 400) resized+  capCtx <- newContext+  let cap = 170+      step inp t =+        sameAsFresh capCtx inp (ui (maxW cap) t) >>= mapM_ (\(Rect _ _ w h, _) -> do+          laidOut <- newContext >>= \c -> warmup2 c inp (ui (fixedW w) t)+          assertEq failed (rectH (respRect laidOut)) h)+      (short, long) = ("a few words ", "other words, a much longer run of them this time, enough for more lines ")+  Rect rx ry rw rh <- respRect <$> warmup2 capCtx (withInputOff 400 400) (ui (maxW cap) short)+  -- Under its cap, so the solver offers it a width it does not take.+  assert failed (rw > 0 && rw < cap)+  let over = (withInputOff 400 400) {inputMousePos = V2 (rx + rw / 2) (ry + rh / 2)}+  mapM_ (uncurry step) [(over, short), (withInputOff 400 400, short), (over, short), (over, long), (withInputOff 120 400, long)]+  mapM_ (step (withInputOff 400 400)) [long, short]+  let pieces = ["kept ", strong "pieces", hyperlink "x" " here"]+      (red, blue) = (colorRGBA 200 10 10 255, colorRGBA 10 10 200 255)+      colorsOf theme f = do+        (_, ops) <- settledOps ctx inp400 (column (setTheme theme >> fst <$> richTextWith' f pieces))+        pure [c | DrawTextStyled _ _ _ "kept" c <- ops]+  assertEq failed [[red], [blue]] =<< mapM (colorsOf defaultTheme . fontColor) [red, blue]+  dark <- colorsOf defaultTheme id+  light <- colorsOf defaultLightTheme id+  assert failed (length dark == 1 && dark /= light)++-- | A scroll area in a fixed-width popup is as tall as its wrapped paragraphs,+-- as a column is, up to the popup's height cap, past which it scrolls.+runRichTextScrollPopupTest :: Context -> IORef Int -> IO ()+runRichTextScrollPopupTest _ failed = do+  let cfg = (defaultPopupConfig (AnchorPoint (V2 20 20))) {popupPlacement = PlacementBelow, popupDismissable = False}+      paragraph = [inlineText (T.replicate 60 "word ")]+      body = do+        one <- fst <$> richTextWith' (tight . fillW . fontMono) ["word"]+        _ <- richTextWith' (tight . fillW . fontMono) paragraph+        b <- fst <$> richTextWith' (tight . fillW) paragraph+        pure (rectH (respRect one), respRect b)+      -- The popup's rect and the body's result, laid out from the start.+      inPopup inner = do+        c <- newContext+        (resp, r) <- warmup2 c (withInput 800 800) (popupWith' (constVar True) cfg (fixedW 560 . maxH 420) inner)+        pure (c, respRect resp, r)+      bottom r = rectY r + rectH r+  (_, columnPopup, Just (lineH, wrapped)) <- inPopup (columnWith fillW body)+  -- Each paragraph wraps to several lines, and all of them stay under the cap.+  assert failed (rectH wrapped >= 3 * lineH && rectH columnPopup < 400)+  forM_ [id, columnWith (tight . fillW)] $ \holder -> do+    (c, scrollPopup, Just (sid, (_, last'))) <- inPopup (scrollArea fillW (holder body))+    assertEq failed (round (rectH columnPopup) :: Int) (round (rectH scrollPopup))+    assertJustM failed (getPrevRect c sid) $ \view -> assert failed (bottom last' <= bottom view + 0.5)+  (c, cappedPopup, Just (sid, rects)) <- inPopup (scrollArea fillW (replicateM 4 body))+  assertEq failed 420 (round (rectH cappedPopup) :: Int)+  -- Inside the popup and its padding, with more below than it shows.+  assertJustM failed (getPrevRect c sid) $ \view ->+    assert failed (rectH view > 0 && bottom view <= bottom cappedPopup - 6 + 0.5 && bottom (snd (last rects)) > bottom view)++-- | A selection shows only while focused, with no focus ring, and survives+-- styling, streaming and cache eviction. A shaped 'breakAnywhere' line+-- highlights without a gap.+runSelectionTest :: Context -> IORef Int -> IO ()+runSelectionTest base failed = do+  theme <- readIORef (ctxTheme base)+  let inp = withInputOff 500 300+      selection ops = [r | FillRect r c <- ops, c == themeSelection theme]+      paragraph t = fst <$> selectableRichText' [t]+      two = column ((,) <$> paragraph "first paragraph" <*> paragraph "second paragraph")+  (a, b) <- warmup2 base inp two+  selectAll base inp two a+  selected <- drawnOps base a+  assert failed (not (null (selection selected)) && null [() | StrokeRoundedRect {} <- selected])+  runClick base inp two (centerOf b) >> warmup base inp two+  assert failed . null . selection =<< drawnOps base a+  copied <- newIORef Nothing+  ctx <- (\c -> withClipboard c (readIORef copied) (\t -> True <$ writeIORef copied (Just t))) <$> newContext+  let pieces suffix = ["one ", strong "two\n", inlineText ("three" <> suffix)]+      ui style suffix = selectableRichTextWith' (fixedW 240 . style) (pieces suffix)+      copyFrom c view = do+        writeIORef copied Nothing+        _ <- evalUi c (chordInp (cmdOrCtrl <> key 'c') inp) view+        assertEq failed (Just "one two\nthree") =<< readIORef copied+  (r, _) <- warmup2 ctx inp (ui id "")+  selectAll ctx inp (ui id "") r+  forM_ [fontColor (colorRGB 200 20 20), fontSize 24, alignEnd] $ \style ->+    evalUi ctx inp (ui style "") >> copyFrom ctx (ui style "")+  -- A stream appending text preserves the existing range rather than clearing it.+  copyFrom ctx (ui id " appended")+  -- Evict all measurement state, keeping widget identity and interaction state.+  evicted <- (\p -> ctx {ctxParagraphs = p}) <$> newHost+  copyFrom evicted (ui id " appended")+  let slot = lookupSlot fieldRichSelection (intKey (respId r)) <$> getStore evicted+  before <- slot+  replicateM_ 3 (evalUi evicted inp (ui id " appended"))+  after <- slot+  assert failed (maybe False id (ptrEq <$> before <*> after))+  let txt = "a\x65E5\&e\x0301\&b"+      fm = monospaceMetrics 10+      shapedTxt = ShapedText 47 47 (primArrayFromList [0, 10, 27, 32, 37, 47])+      prepare t = pure fm {fmShape = \t' -> if t' == t && t == txt then Just shapedTxt else Nothing}+      shapedUi = column (fst <$> selectableRichTextWith' breakAnywhere [inlineText txt])+  shaped <- newContext >>= \c -> evaluate (withFontMetrics c fm {fmBackend = Just (FontBackend prepare (const (pure Nothing)))})+  resp <- warmup2 shaped inp shapedUi+  let Rect rx _ rw _ = respRect resp+  assertEq failed 47 rw+  selectAll shaped inp shapedUi resp+  ranges <- sortOn fst . map (\(Rect x _ w _) -> (x - rx, x - rx + w)) . selection <$> drawnOps shaped resp+  assertEq failed (Just 0, 47) (fst <$> listToMaybe ranges, maximum (0 : map snd ranges))+  assert failed (and (zipWith (\(_, e) (s, _) -> s <= e + 0.01) ranges (drop 1 ranges)))++runRichTextTooltipsTest :: Context -> IORef Int -> IO ()+runRichTextTooltipsTest ctx failed = do+  let fm = ctxFontMetrics ctx+      ui =+        column $+          richText'+            [ inlineTooltip "garbage collector" (inlineCode "GC")+            , " "+            , inlineTooltip "Opens documentation" (hyperlink "https://example.com" "Open link")+            ]+  (resp, _) <- warmup2 ctx inp400 ui+  openW <- lineWidthIO fm "Open link"+  let Rect rx ry rw rh = respRect resp+      pt = V2 (rx + rw - openW / 2 - 1) (ry + rh / 2)+      hover = inp400 {inputMousePos = pt}+  _ <- evalUi ctx hover ui+  w <- getWakeAt ctx+  assert failed (w > 0)+  (_, clicked) <- runClick ctx inp400 ui pt+  assertEq failed (Just "https://example.com") clicked
test/integration/Cases/Runner.hs view
@@ -1,5 +1,9 @@-module Cases.Runner (runSessionLoopTest, runDrawingLockTest) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Runner (tests) where +import Spec+import Control.Concurrent (threadDelay)+import Data.Foldable (toList) import Control.Exception   ( IOException   , MaskingState (Unmasked)@@ -7,15 +11,88 @@   , throwIO   , try   )-import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef)-import NanoUI (Input (..), V2 (..), emptyInput)-import NanoUI.Debug (newDebugSampler)+import NanoUI.Internal.Context (takeThreadWake, wakeFromThread) import NanoUI.Runner-import NanoUI.Testing (Context, clearDirty)-import NanoUI.Testing.Assert (assertEq)+import NanoUI.Shortcut (ctrl, key) --- Exercise queued edges, a dirty follow-up frame, skipped input, and blocking--- waits without requiring a native window or depending on wall-clock timing.+tests :: [Spec]+tests =+  [ spec "session-loop" runSessionLoopTest+  , spec "session-loop-wakes" runSessionLoopWakesTest+  , spec "session-loop-hard-quit" runSessionLoopHardQuitTest+  , spec "session-loop-keys" runSessionLoopKeysTest+  , spec "session-loop-close" runSessionLoopCloseTest+  , spec "session-loop-clicks" runSessionLoopClicksTest+  , spec "session-loop-continuous" runSessionLoopContinuousTest+  , spec "session-loop-paced-wait" runSessionLoopPacedWaitTest+  , spec "drawing-lock" runDrawingLockTest+  ]++-- | A driver with no events, nothing to draw, and event 3 as the floatingWindow's+-- close. Each test overrides the fields it watches.+quietDriver :: DebugSamplerRef -> SessionDriver Int+quietDriver debug =+  SessionDriver+    { sdPollEvents = pure []+    , sdWaitEvents = \_ -> pure [3]+    , sdPacedWait = Nothing+    , sdApplyEvent = \inp _ -> inp+    , sdIsButtonEdge = const False+    , sdIsSessionQuit = (== 3)+    , sdSyncDisplay = \c inp -> pure (c, inp)+    , sdDebug = debug+    , sdContinuous = False+    , sdVsyncOff = False+    , sdPacingMs = 16+    , sdPresentPaces = pure False+    , sdAlignSec = 0+    , sdShouldDraw = \_ _ _ _ _ -> pure False+    , sdDraw = \_ _ _ -> pure False+    , sdOnCursor = \_ _ -> pure ()+    , sdShouldQuit = const False+    , sdWindows = Nothing+    }++-- | One batch of events per driver wait. A wait past the last batch throws,+-- so a runaway loop fails the test instead of hanging.+batchedWaits :: [[Int]] -> IO (Int -> IO [Int])+batchedWaits batches = do+  queue <- newIORef batches+  pure $ \_ -> atomicModifyIORef' queue (\case b : rest -> (rest, Just b); [] -> ([], Nothing))+    >>= maybe (throwIO (userError "the loop went on past its last events")) pure++-- | Run the session loop over @batches@ ('batchedWaits'), drawing on every+-- pass unless @edit@, which adjusts the driver, says otherwise.+runLoop :: Context -> (SessionDriver Int -> SessionDriver Int) -> [[Int]] -> IO ()+runLoop ctx edit batches = do+  debug <- newDebugSampler+  waits <- batchedWaits batches+  clearDirty ctx+  let driver = edit (quietDriver debug) {sdWaitEvents = waits, sdShouldDraw = \_ _ _ _ _ -> pure True}+  runSessionLoop driver ctx emptyInput++-- | A draw that runs one frame of @view@.+viewing :: NanoUI a -> Context -> Input -> Bool -> IO Bool+viewing view c inp _ = False <$ evalUi c inp view++-- | 'runLoop', counting the frames drawn.+drawCount :: Context -> (SessionDriver Int -> SessionDriver Int) -> [[Int]] -> IO Int+drawCount ctx edit batches = do+  drawn <- newIORef (0 :: Int)+  let counted d = let d' = edit d in d' {sdDraw = \c inp dbg -> modifyIORef' drawn (+ 1) >> sdDraw d' c inp dbg}+  runLoop ctx counted batches+  readIORef drawn++-- | Notes each frame's close request, quitting on one once @quitAfter@ holds+-- of those noted before.+closeWatcher :: IORef [Bool] -> ([Bool] -> Bool) -> NanoUI ()+closeWatcher seen quitAfter = do+  closing <- winCloseRequested <$> askWindow+  before <- liftIO (atomicModifyIORef' seen (\s -> (s <> [closing], s)))+  when (closing && quitAfter before) quit++-- | Queued edges, a dirty follow-up frame, skipped input and blocking waits,+-- without a native window or wall-clock timing. runSessionLoopTest :: Context -> IORef Int -> IO () runSessionLoopTest ctx failed = do   logRef <- newIORef []@@ -25,41 +102,29 @@   let     note message = modifyIORef' logRef (<> [message])     driver =-      SessionDriver-        { sdPollEvents = do-            note "poll"-            pure []+      (quietDriver debug)+        { sdPollEvents = [] <$ note "poll"         , sdWaitEvents = \timeout -> do             note ("wait " <> show timeout)-            (expected, events) <- atomicModifyIORef' waits $ \batches -> case batches of+            (expected, events) <- atomicModifyIORef' waits $ \case               batch : rest -> (rest, batch)               [] -> ([], (timeout, [3]))             assertEq failed expected timeout             pure events         , sdApplyEvent = \inp event -> inp {inputMousePos = V2 (fromIntegral event) 0}         , sdIsButtonEdge = const True-        , sdIsHardQuit = const False-        , sdIsSessionQuit = (== 3)-        , sdSyncDisplay = \c inp -> pure (c, inp)-        , sdDebug = debug-        , sdContinuous = False-        , sdPacingMs = 16-        , sdPresentPaces = pure False-        , sdAlignSec = 0         , sdShouldDraw = \_ previous current _ _ -> do             note ("decide " <> show (inputMousePos previous, inputMousePos current))             pure (inputMousePos current == V2 1 0)-        , sdDraw = \_ inp _ -> do+        , sdDraw = \_ _ _ -> do             n <- atomicModifyIORef' draws (\n -> (n + 1, n + 1))             note "draw"-            pure (n <= 2, inp {inputMousePos = V2 10 0})+            pure (n <= 2)         , sdOnCursor = \_ _ -> note "cursor"-        , sdShouldQuit = const False         }   -- A new context starts dirty, which would make the first wait immediate.   clearDirty ctx   runSessionLoop driver ctx emptyInput-  actual <- readIORef logRef   assertEq     failed     [ "wait -1"@@ -73,13 +138,228 @@     , "draw"     , "cursor"     , "wait -1"-    , "decide " <> show (V2 10 0, V2 10 0)+    , "decide " <> show (V2 2 0, V2 2 0)     , "cursor"     , "wait -1"     ]-    actual+    =<< readIORef logRef   assertEq failed 3 =<< readIORef draws +-- | Quick presses count up to a triple click; another button restarts.+runSessionLoopClicksTest :: Context -> IORef Int -> IO ()+runSessionLoopClicksTest ctx failed = do+  clicks <- newIORef []+  let buttonOf = \case+        1 -> Just (MouseLeft, True)+        2 -> Just (MouseLeft, False)+        4 -> Just (MouseRight, True)+        _ -> Nothing+  runLoop+    ctx+    ( \d ->+        d+          { sdApplyEvent = \inp e -> maybe inp (\(b, down) -> applyMouseButton b down inp) (buttonOf e)+          , sdIsButtonEdge = \e -> buttonOf e /= Nothing+          , sdDraw = \_ inp _ ->+              False <$ when (anyButtonPressed inp) (modifyIORef' clicks (<> [inputMouseClicks inp]))+          }+    )+    [[1, 2, 1, 2, 1, 2, 4], [3]]+  assertEq failed [1, 2, 3, 1] =<< readIORef clicks++-- | A requested wake bounds the idle wait (sleeping to it, not polling) and+-- draws when due; a thread's wake draws through 'shouldRedrawFrame' alone; a+-- wake a month away fits the 32-bit millisecond timeout backends take.+runSessionLoopWakesTest :: Context -> IORef Int -> IO ()+runSessionLoopWakesTest ctx failed = do+  logRef <- newIORef []+  waits <- newIORef (0 :: Int)+  debug <- newDebugSampler+  let+    note message = modifyIORef' logRef (<> [message])+    driver =+      (quietDriver debug)+        { sdWaitEvents = \timeout -> do+            n <- atomicModifyIORef' waits (\n -> (n + 1, n))+            if n == 0+              then do+                note (if timeout > 0 && timeout <= 40 then "timed wait" else "wait " <> show timeout)+                [] <$ threadDelay (max 0 timeout * 1000)+              else [3] <$ note ("wait " <> show timeout)+        , sdShouldDraw = \_ _ _ _ due -> due <$ note ("due " <> show due)+        , sdDraw = \_ _ _ -> False <$ note "draw"+        }+  clearDirty ctx+  requestWakeAfter ctx 0.03+  runSessionLoop driver ctx emptyInput+  assertEq failed ["timed wait", "due True", "draw", "wait -1"] =<< readIORef logRef+  assertEq failed 0 =<< getWakeAt ctx+  let threadWake d =+        d+          { sdWaitEvents = \t -> do+              events <- sdWaitEvents d t+              -- A job finishing ends the wait with no event of its own.+              when (null events) (wakeFromThread ctx)+              pure events+          , sdShouldDraw = \c prev cur wasAnim due -> shouldRedrawFrame c prev cur wasAnim False due+          }+  assertEq failed 1 =<< drawCount ctx threadWake [[], [3]]+  takeThreadWake ctx+  timeouts <- newIORef []+  clearDirty ctx+  requestWakeAfter ctx (30 * 86400)+  let farWake = (quietDriver debug) {sdWaitEvents = \timeout -> [3] <$ modifyIORef' timeouts (timeout :)}+  runSessionLoop farWake ctx emptyInput+  ts <- readIORef timeouts+  assert failed (not (null ts) && all (\t -> t > 0 && t <= 2147483647) ts)++-- | A continuous session waits 0 ms between passes while its presents wait+-- for the display or vsync is off on purpose, and the pacing wait when the+-- presents do not wait though vsync was asked for. A session that is not+-- continuous still blocks.+runSessionLoopContinuousTest :: Context -> IORef Int -> IO ()+runSessionLoopContinuousTest ctx failed = do+  let firstWait continuous paces vsyncOff = do+        timeouts <- newIORef []+        waits <- batchedWaits [[], [3]]+        runLoop+          ctx+          ( \d ->+              d+                { sdContinuous = continuous+                , sdVsyncOff = vsyncOff+                , sdPresentPaces = pure paces+                , sdWaitEvents = \t -> modifyIORef' timeouts (<> [t]) >> waits t+                }+          )+          []+        take 1 <$> readIORef timeouts+  assertEq failed [0] =<< firstWait True True False+  assertEq failed [0] =<< firstWait True False True+  assertEq failed [16] =<< firstWait True False False+  assertEq failed [-1] =<< firstWait False False False++-- | The loop hands the wait for a frame paced by time to the backend's+-- 'sdPacedWait', and any other wait, a timed wake as long as the pacing wait+-- among them, to 'sdWaitEvents'.+runSessionLoopPacedWaitTest :: Context -> IORef Int -> IO ()+runSessionLoopPacedWaitTest ctx failed = do+  let firstWait continuous = do+        calls <- newIORef []+        waits <- batchedWaits [[], [3]]+        let noted (how :: String) t = modifyIORef' calls (<> [(how, t)]) >> waits t+        runLoop ctx (\d -> d {sdContinuous = continuous, sdPacedWait = Just (noted "paced"), sdWaitEvents = noted "plain"}) []+        take 1 <$> readIORef calls+  assertEq failed [("paced", 16 :: Int)] =<< firstWait True+  requestWakeAfter ctx 0.014+  assertEq failed ["plain"] . map fst =<< firstWait False++-- | Ctrl+C quits after its frame (Ctrl released later in the batch too, a+-- bare c not), unless a shortcut or a focused text field takes it; with+-- 'wsExitOnCloseRequest' off it asks to close instead. Events: 1 Ctrl+C,+-- 2 releases Ctrl, 4 types c, 5 Tab, others nothing.+runSessionLoopHardQuitTest :: Context -> IORef Int -> IO ()+runSessionLoopHardQuitTest ctx failed = do+  copies <- newIORef (0 :: Int)+  let typed inp = \case+        1 -> chordInp (ctrl <> key 'c') inp+        2 -> inp {inputModifiers = (inputModifiers inp) {modCtrl = False}}+        4 -> inp {inputChars = inputChars inp <> "c"}+        5 -> chordInp (key KeyTab) inp+        _ -> inp+      quits = drawCount ctx (\d -> d {sdApplyEvent = typed})+      frames view = drawCount ctx (\d -> d {sdApplyEvent = typed, sdDraw = viewing view})+      copy = whenM (shortcut (ctrl <> key 'c')) (liftIO (modifyIORef' copies (+ 1)))+  assertEq failed 1 =<< quits [[1, 2], [6], [3]]+  assertEq failed 1 =<< quits [[1], [6], [3]]+  assertEq failed 2 =<< quits [[4, 2], [6], [3]]+  assertEq failed 2 =<< frames copy [[1], [6], [3]]+  assertEq failed 1 =<< readIORef copies+  -- Two Tabs focus the field; one more wraps round to the button.+  let fields = button "b" >> void (withValue "" textInput')+  assertEq failed 4 =<< frames fields [[5], [5], [1], [6], [3]]+  assertEq failed 2 =<< frames fields [[5], [1]]+  installWindowHost ctx defaultWindowSettings {wsExitOnCloseRequest = False} defaultWindowHost+  seen <- newIORef []+  assertEq failed 2 =<< frames (closeWatcher seen (const True)) [[1], [6]]+  assertEq failed [False, True] =<< readIORef seen++-- | A batch splits into frames so text precedes each frame's one command key+-- and every key sees its own modifiers; repeats and typing share a frame.+-- Each auto-repeat or retyped character draws, though the input is equal.+runSessionLoopKeysTest :: Context -> IORef Int -> IO ()+runSessionLoopKeysTest ctx failed = do+  frames <- newIORef []+  -- 1 types "l" with its key, 2 presses Enter, 3 types "x", 4 holds Ctrl,+  -- 5 presses S, 6 releases S, 7 releases Ctrl.+  let ctrlOn on inp = inp {inputModifiers = noModifiers {modCtrl = on}}+      apply inp = \case+        1 -> (applyKey (KeyChar 'l') True inp) {inputChars = inputChars inp <> "l"}+        2 -> applyKey KeyEnter True inp+        3 -> inp {inputChars = inputChars inp <> "x"}+        4 -> ctrlOn True inp+        5 -> applyKey (KeyChar 's') True inp+        6 -> applyKey (KeyChar 's') False inp+        7 -> ctrlOn False inp+        _ -> inp+      record _ inp _ =+        False <$ modifyIORef' frames (<> [(inputChars inp, toList (inputKeys inp), modCtrl (inputModifiers inp))])+      keyed d = d {sdApplyEvent = apply, sdIsSessionQuit = (== 0), sdDraw = record}+      run batches = writeIORef frames [] >> runLoop ctx keyed (batches ++ [[0]]) >> readIORef frames+  let ctrlS = ("", [KeyChar 's'], True)+  assertEq failed [("ll", [KeyChar 'l', KeyChar 'l', KeyEnter, KeyEnter], False), ("x", [], False), ctrlS, ("", [], False)]+    =<< run [[1, 1, 2, 2, 3, 4, 5, 6, 7]]+  -- One event per batch, as in steady typing, adds no frames.+  assertEq failed 7 . length =<< run (map pure [1, 2, 3, 4, 5, 6, 7])+  -- 1 presses Down (a repeat while held), 2 releases it, and 4 types "a".+  let typeA inp =+        applyKey (KeyChar 'a') False (applyKey (KeyChar 'a') True inp) {inputChars = inputChars inp <> "a"}+      repeats d =+        d+          { sdApplyEvent = \inp -> \case+              1 -> applyKey KeyDown True inp+              2 -> applyKey KeyDown False inp+              4 -> typeA inp+              _ -> inp+          , sdShouldDraw = \c prev cur anim due -> shouldRedrawFrame c prev cur anim False due+          }+  assertEq failed 7 =<< drawCount ctx repeats [[1], [1], [1], [1], [2], [4], [4], [3]]++-- | With 'wsExitOnCloseRequest' on, a close request, or 'quit' in a frame+-- drawn before the loop, ends the session. Off, each request reaches the+-- next frame only (past a pass that draws none) until one calls 'quit'.+runSessionLoopCloseTest :: Context -> IORef Int -> IO ()+runSessionLoopCloseTest _ failed = do+  let fresh exitOnClose = do+        ctx <- newContext+        let settings = defaultWindowSettings {wsExitOnCloseRequest = exitOnClose}+        ctx <$ installWindowHost ctx settings defaultWindowHost+  exits <- fresh True+  assertEq failed 1 =<< drawCount exits id [[], [3]]+  quitFirst <- fresh True+  evalUi quitFirst emptyInput quit+  assertEq failed 0 =<< drawCount quitFirst id []+  asks <- fresh False+  seen <- newIORef []+  runLoop asks (\d -> d {sdDraw = viewing (closeWatcher seen ((== 1) . length . filter id))}) [[3], [], [3]]+  assertEq failed [True, False, True] =<< readIORef seen+  skips <- fresh False+  decisions <- newIORef (0 :: Int)+  seenAfterSkip <- newIORef []+  runLoop+    skips+    ( \d ->+        d+          { -- The first pass, the close request's, draws nothing.+            sdShouldDraw = \_ _ _ _ _ -> atomicModifyIORef' decisions (\n -> (n + 1, n > 0))+          , sdDraw = viewing (closeWatcher seenAfterSkip (const True))+          }+    )+    [[3], [], [3]]+  assertEq failed [True] =<< readIORef seenAfterSkip++-- | The drawing lock runs its action unmasked, is not re-entrant, and is+-- free again after an action that throws. runDrawingLockTest :: Context -> IORef Int -> IO () runDrawingLockTest _ failed = do   lock <- newDrawingLock@@ -87,8 +367,6 @@     assertEq failed Unmasked =<< getMaskingState     assertEq failed Nothing =<< tryWithDrawingLock lock (pure ())   assertEq failed (Just ()) result-  failure <--    try (tryWithDrawingLock lock (throwIO (userError "draw failed"))) ::-      IO (Either IOException (Maybe ()))+  failure <- try @IOException (tryWithDrawingLock lock (throwIO (userError "draw failed")))   assertEq failed True (either (const True) (const False) failure)   assertEq failed (Just ()) =<< tryWithDrawingLock lock (pure ())
test/integration/Cases/SIMD.hs view
@@ -1,66 +1,85 @@-module Cases.SIMD (runSimdWritesTest) where+{-# OPTIONS_GHC -O0 #-}+module Cases.SIMD (tests) where -import Control.Monad (forM, forM_)-import Data.IORef (IORef)+import Spec+import Data.List (sort)+import Data.Primitive.PrimArray (primArrayToList)+import Data.Vector.Unboxed qualified as U+import Data.Vector.Unboxed.Mutable qualified as UM import Data.Word (Word32, Word8) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Utils (fillBytes) import Foreign.Ptr (Ptr) import Foreign.Storable (peekByteOff)-import NanoUI.SIMD-import NanoUI.Testing (Context)-import NanoUI.Testing.Assert (assertEq)+import NanoUI.Internal.SIMD --- Check the renderer's interleaved vertex ABI, triangle winding and byte--- offsets directly. Guard bytes also catch writes beyond either buffer range.+tests :: [Spec]+tests =+  [ spec "simd-writes" runSimdWritesTest+  , spec "draw-layer-offsets" runDrawLayersTest+  ]++-- | The renderer's interleaved vertex ABI, triangle winding and byte offsets,+-- checked directly. Guard bytes catch writes past either buffer's range. runSimdWritesTest :: Context -> IORef Int -> IO () runSimdWritesTest _ failed = do-  let-    solid vp ip = pokeQuadSIMD vp 16 ip 16 2 3 5 7 0 0.25 0.5 1 1 0 0.5 1 7-    gradient vp ip =-      pokeQuadGradientSIMD-        vp-        16-        ip-        16-        2-        3-        5-        7-        0.25-        0.5-        (1, 0, 0, 1)-        (0, 1, 0, 1)-        (0, 0, 1, 1)-        (1, 1, 1, 0.5)-        7-    solidVertices =-      [ [2, 3, 1, 0, 0.5, 1, 0, 0.25]-      , [7, 3, 1, 0, 0.5, 1, 0.5, 0.25]-      , [7, 10, 1, 0, 0.5, 1, 0.5, 1]-      , [2, 10, 1, 0, 0.5, 1, 0, 1]-      ]-    gradientVertices =-      [ [2, 3, 1, 0, 0, 1, 0.25, 0.5]-      , [7, 3, 0, 1, 0, 1, 0.25, 0.5]-      , [7, 10, 0, 0, 1, 1, 0.25, 0.5]-      , [2, 10, 1, 1, 1, 0.5, 0.25, 0.5]-      ]-    checkQuad :: (Ptr Word8 -> Ptr Word8 -> IO ()) -> [[Float]] -> IO ()-    checkQuad write expected =-      allocaBytes 160 $ \vp -> allocaBytes 56 $ \ip -> do-        fillBytes vp 0xa5 160-        fillBytes ip 0xa5 56-        write vp ip-        actual <- forM [0 .. 31 :: Int] $ \i -> peekByteOff vp (16 + i * 4)-        indices <- forM [0 .. 5 :: Int] $ \i -> peekByteOff ip (16 + i * 4)-        assertEq failed (concat expected) actual-        assertEq failed ([7, 8, 9, 7, 9, 10] :: [Word32]) indices-        forM_ [(vp, 144), (ip, 40)] $ \(ptr, end) -> do-          guardBytes <- mapM (peekByteOff ptr) ([0 .. 15] ++ [end .. end + 15])-          assertEq failed (replicate 32 0xa5 :: [Word8]) guardBytes-  checkQuad solid solidVertices-  checkQuad gradient gradientVertices-  let-    expectedOffsets = ((1, 2), (4, 6), (7, 10), (10, 14))-  assertEq failed expectedOffsets (concentricOffsetsSIMD 1 2 3 4 0 1 2 3)+  let checkQuad :: (Ptr Word8 -> Ptr Word8 -> IO ()) -> [[Float]] -> IO ()+      checkQuad write expected =+        allocaBytes 160 $ \vp -> allocaBytes 56 $ \ip -> do+          fillBytes vp 0xa5 160+          fillBytes ip 0xa5 56+          write vp ip+          let words4 p n = forM [0 .. n - 1 :: Int] (\i -> peekByteOff p (16 + i * 4))+          assertEq failed (concat expected) =<< words4 vp 32+          assertEq failed ([7, 8, 9, 7, 9, 10] :: [Word32]) =<< words4 ip 6+          forM_ [(vp, 144), (ip, 40)] $ \(ptr, end) -> do+            guards <- mapM (peekByteOff ptr) ([0 .. 15] ++ [end .. end + 15])+            assertEq failed (replicate 32 0xa5 :: [Word8]) guards+  checkQuad+    (\vp ip -> pokeQuadSIMD vp 16 ip 16 2 3 5 7 0 0.25 0.5 1 1 0 0.5 1 7)+    [ [2, 3, 1, 0, 0.5, 1, 0, 0.25]+    , [7, 3, 1, 0, 0.5, 1, 0.5, 0.25]+    , [7, 10, 1, 0, 0.5, 1, 0.5, 1]+    , [2, 10, 1, 0, 0.5, 1, 0, 1]+    ]+  checkQuad+    ( \vp ip ->+        pokeQuadGradientSIMD vp 16 ip 16 2 3 5 7 0.25 0.5 (1, 0, 0, 1) (0, 1, 0, 1) (0, 0, 1, 1) (1, 1, 1, 0.5) 7+    )+    [ [2, 3, 1, 0, 0, 1, 0.25, 0.5]+    , [7, 3, 0, 1, 0, 1, 0.25, 0.5]+    , [7, 10, 0, 0, 1, 1, 0.25, 0.5]+    , [2, 10, 1, 1, 1, 0.5, 0.25, 0.5]+    ]+  assertEq failed ((1, 2), (4, 6), (7, 10), (10, 14)) (concentricOffsetsSIMD 1 2 3 4 0 1 2 3)++-- | Draw commands survive an unboxed vector growing. Empty layers have equal+-- bounds, grouping keeps command order within a layer, and visiting the+-- layers rebuilds the whole command stream.+runDrawLayersTest :: Context -> IORef Int -> IO ()+runDrawLayersTest _ failed = do+  let commands = [DrawCmd 1 2 3 4 (-7) 19 maxBound layer 0 | layer <- [minBound .. maxBound]]+      grown = U.create $ do+        v <- U.thaw (U.fromList commands)+        w <- UM.grow v (length commands)+        UM.copy (UM.drop (length commands) w) v+        pure w+  assertEq failed (commands ++ commands) (U.toList grown)+  let overlay = column (button "outside" >> void (modal' (constVar True) "overlay" (button "inside")))+  forM_ [pure (), label "content", overlay] $ \view -> do+    ctx <- newContext+    replicateM_ 3 $ do+      (_, dd, _) <- runFrame ctx emptyInput view+      let cmds = drawCmdElems dd+          tags = map (fromEnum . cmdLayer) cmds+          offsets = primArrayToList (drawLayerOffsets dd)+      assertEq failed (sort tags) tags+      assertEq failed (5, [0], [length cmds]) (length offsets, take 1 offsets, drop 4 offsets)+      visited <- forM [minBound .. maxBound :: Layer] $ \layer -> do+        ref <- newIORef []+        forDrawCmdsInLayer_ layer dd (\cmd -> modifyIORef' ref (cmd :))+        actual <- reverse <$> readIORef ref+        assertEq failed (filter ((== layer) . cmdLayer) cmds) actual+        assertEq failed (sort (map cmdIndexOffset actual)) (map cmdIndexOffset actual)+        pure actual+      assertEq failed cmds (concat visited)
test/integration/Cases/Scroll.hs view
@@ -1,749 +1,763 @@-module Cases.Scroll-  ( runNestedScrollFocusTest-  , runNestedScrollTest-  , runScrollBarGutterTest-  , runScrollButtonClickTest-  , runScrollDamageTest-  , runScrollHoverClipTest-  , runScrollThumbCursorTest-  , runScrollTopClipTest-  , runScrolledOutImmunityTest-  , run2DPadFillOverflowTest-  , run2DPadOverflowScrollsTest-  , runScrollLockstepProbeTest-  , runPageScrollBackdropCoverageTest-  , runScrollStepTest-  , runScrollSmoothTest-  , runScrollMetricsTest-  , runScrollIntoViewTest-  , runScrollGlideClampTest-  , runScroll2DGrowMinWidthTest-  ) where--import Control.Monad (forM, forM_, replicateM, replicateM_, void, when)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.List (sort)-import Data.Maybe (isJust, isNothing, listToMaybe)-import Foreign.ForeignPtr (withForeignPtr)-import Foreign.Ptr (Ptr, castPtr)-import Foreign.Storable (peekElemOff)-import Data.Text qualified as T-import NanoUI-import NanoUI.Context (ctxNodeArena, setDrawSnapScale)-import NanoUI.Layout.Arena-  ( NodeType (..)-  , findNodeM-  , getNodeValue-  , getNodeType-  , getRect-  , getScrollContentW-  , getWidgetId-  )-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt, withInput)-import NanoUI.Testing.Harness-  ( assertScrollGutterPad-  , centerOf-  , drawQuads-  , findGrabHover-  , runClick-  , spanCenter-  , spanYOf-  , tabInp-  , warmup2-  , withInputOff-  )--runScrollThumbCursorTest :: Context -> IORef Int -> IO ()-runScrollThumbCursorTest ctx failed = do-  let inp0 = withInput 200 120-      ui = scrollArea (fillW . fixedH 80)-             (column (replicateM 8 (label "scroll line") >> pure ()))-  ((sid, ()), _, _, _) <- runFrame ctx inp0 ui >>= \_ -> runFrame ctx inp0 ui-  mrect <- getPrevRect ctx sid-  case mrect of-    Nothing -> assert failed False-    Just (Rect rx ry rw rh) -> do-      let thumbX = rx + rw - scrollBarGutter ScrollBarList 0 / 2-          tryYs = [ry + rh * n / 8 | n <- [1 .. 7]]-      mHover <- findGrabHover ctx ui inp0 thumbX tryYs-      case mHover of-        Nothing -> assert failed False-        Just hover -> do-          kind <- uiCursorKind ctx hover-          assertEq failed kind UiCursorGrab-          let press = hover {inputMouseDown = True, inputMousePressed = True}-          _ <- runFrame ctx press ui-          grabbing <- cursorKindIs ctx press UiCursorGrabbing-          assert failed grabbing---- The scroll content's right edge stops at the scrollbar gutter, one gap--- before the bar. The gap matches the scroller's right padding and is never--- under the side gap. A list bar keeps that gap to its well's edge as well;--- a page bar sits a side gap inside the page's edge.-runScrollBarGutterTest :: Context -> IORef Int -> IO ()-runScrollBarGutterTest ctx failed = do-  let listPad = padR (layoutPadding defaultLayout)-      wideThen n = do-        r <- labelWith' fillW "Wide"-        _ <- replicateM n (label "scroll line")-        pure r-      cases =-        [ ( withInput 200 120-          , scrollArea (fillW . fixedH 60) (wideThen 8)-          , scrollBarGutter ScrollBarList listPad-          , listPad-          )-        , ( withInput 240 140-          , scrollArea (tight . grow) (wideThen 20)-          , scrollBarGutter ScrollBarPage 0-          , 0-          )-        , ( withInput 240 140-          , scrollArea (padAll 12 . grow) (wideThen 20)-          , scrollBarGutter ScrollBarPage 12-          , 12-          )-        , ( withInput 240 140-          , panelWith grow (scrollArea (tight . grow) (wideThen 20))-          , scrollBarGutter ScrollBarList 0-          , 0-          )-        ]-  forM_ cases $ \(inp0, ui, gutter, endPad) -> do-    (sid, child) <- warmup2 ctx inp0 ui-    assertScrollGutterPad failed ctx sid child gutter endPad-  -- The padded page's bar takes the pointer just inside the page's edge. The-  -- sliver past it and the gap before it stay clear.-  let inp0 = withInputOff 240 140-      page = scrollArea (padAll 12 . grow) (wideThen 20)-  (sid, _) <- warmup2 ctx inp0 page-  mrect <- getPrevRect ctx sid-  case mrect of-    Nothing -> assert failed False-    Just (Rect sx sy sw sh) -> do-      let ys = [sy + sh * n / 8 | n <- [1 .. 7]]-      let barLeft = sx + sw - scrollBarGutter ScrollBarPage 12-      onBar <- findGrabHover ctx page inp0 (barLeft + scrollBarWidth / 2) ys-      assert failed (isJust onBar)-      past <- findGrabHover ctx page inp0 (sx + sw - 1) ys-      assert failed (isNothing past)-      gapBefore <- findGrabHover ctx page inp0 (barLeft - 6) ys-      assert failed (isNothing gapBefore)---- Each change of a scroll offset damages the scroll viewport only.-runScrollDamageTest :: Context -> IORef Int -> IO ()-runScrollDamageTest ctx failed = do-  let scrollUi =-        fmap fst $-          scrollArea (fillW . fixedH 60) $-            column (replicateM 8 (label "scroll line") >> pure ())-      inp0 = withInputOff 200 120-  sid <- warmup2 ctx inp0 scrollUi-  forM_ [24, 48] $ \off -> do-    _ <- runFrame ctx inp0 (scrollUi >> uiIO (setScrollOffset ctx sid off))-    dScroll <- takeDamage ctx-    case dScroll of-      DamageFull -> assert failed False-      DamageClip r -> assert failed (rectW r > 0 && rectH r > 0 && rectH r <= 60 + defaultDamageSlop * 2 && not (damageIsEmpty dScroll))---- Ghosting guard: a grow×grow (page-level) scroll container paints no well,--- so on clip frames the strip vacated by scrolled content has no covering--- command and the retained texture would show stale pixels, a ghost of a--- previous scroll position. Every frame must emit a full-viewport fill (the--- window-color backdrop) so clip replay repaints the whole viewport.-runPageScrollBackdropCoverageTest :: Context -> IORef Int -> IO ()-runPageScrollBackdropCoverageTest ctx failed = do-  let inp0 = withInputOff 300 220-      ui = fmap fst $-        scrollArea-          grow-          (column (replicateM 20 (label "scroll backdrop line") >> pure ()))-  sid <- warmup2 ctx inp0 ui-  setScrollOffset ctx sid 120-  _ <- runFrame ctx inp0 ui-  (_, _, draw, _) <- runFrame ctx inp0 ui-  mRect <- getPrevRect ctx sid-  case mRect of-    Nothing -> assert failed False-    Just (Rect rx ry rw rh) -> do-      quads <- drawQuads draw-      let covered =-            any-              (\(Rect qx qy qw qh, _) ->-                abs (qx - rx) <= 0.6-                  && abs (qy - ry) <= 0.6-                  && abs (qx + qw - (rx + rw)) <= 0.6-                  && abs (qy + qh - (ry + rh)) <= 0.6)-              quads-      assert failed covered--runScrollTopClipTest :: Context -> IORef Int -> IO ()-runScrollTopClipTest ctx failed = do-  cbRef <- newIORef Nothing-  let inp0 = withInputOff 400 160-      ui = do-        scrollWith (tight . grow) $-          columnWith (padAll 8 . gap 8 . fillW) $-            card $ do-              heading "Controls"-              (cb, _) <- checkbox' "Feature" False-              _ <- slider 0 100 50-              mapM_ (\i -> void (label (T.pack ("pad line " <> show (i :: Int))))) [1 .. 16]-              uiIO $ writeIORef cbRef (Just cb)-              pure ()-      clipFits dmg = case dmg of-        DamageFull -> True-        DamageClip (Rect _ y _ h) -> y >= -1 && y + h <= 160 + 1-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  mCb <- readIORef cbRef-  case mCb of-    Nothing -> assert failed False-    Just cb -> do-      mR <- getPrevRect ctx (respId cb)-      case mR of-        Nothing -> assert failed False-        Just r -> do-          let hover = inp0 {inputMousePos = spanCenter r}-          _ <- runFrame ctx hover ui-          dHover <- takeDamage ctx-          assert failed (clipFits dHover)--runNestedScrollTest :: Context -> IORef Int -> IO ()-runNestedScrollTest ctx failed = do-  let inp0 = withInput 200 200-      ui = scrollArea (fillW . fixedH 90) $-             column $ do-               (inner, ()) <- scrollArea (fillW . fixedH 40) $-                                column (mapM_ (\i -> label (T.pack ("in " <> show (i :: Int)))) [1 .. 12])-               mapM_ (\i -> label (T.pack ("out " <> show (i :: Int)))) [1 .. 12]-               pure inner-  (outer, inner) <- warmup2 ctx inp0 ui-  mInner <- getPrevRect ctx inner-  mOuter <- getPrevRect ctx outer-  case (mInner, mOuter) of-    (Just r@(Rect ix iy iw ih), Just (Rect _ oy _ oh)) | iw > 0 && ih > 0 -> do-      let hoverInner = inp0 {inputMousePos = spanCenter r}-          wheelInner = hoverInner {inputScroll = V2 0 1}-      offI0 <- getScrollOffset ctx inner-      offO0 <- getScrollOffset ctx outer-      _ <- runFrame ctx wheelInner ui-      offI1 <- getScrollOffset ctx inner-      offO1 <- getScrollOffset ctx outer-      assertGt failed offI1 offI0-      assertEq failed offO1 offO0-      let pumpInner = do-            before <- getScrollOffset ctx inner-            _ <- runFrame ctx wheelInner ui-            after <- getScrollOffset ctx inner-            if after > before then pumpInner else pure ()-      pumpInner-      offO2 <- getScrollOffset ctx outer-      assertEq failed offO2 offO1-      -- Hit rects follow the scroll offset: a wheel just above the fully-      -- scrolled inner viewport must not reach the inner scroller.-      offIMax <- getScrollOffset ctx inner-      _ <- runFrame ctx (inp0 {inputMousePos = V2 (ix + iw / 2) (iy - 6), inputScroll = V2 0 (-1)}) ui-      offIAbove <- getScrollOffset ctx inner-      assertEq failed offIAbove offIMax-      let hoverOuterY = min (oy + oh - 4) (iy + ih + 8)-          wheelOuter = inp0 {inputMousePos = V2 (ix + iw / 2) hoverOuterY, inputScroll = V2 0 1}-      offO3 <- getScrollOffset ctx outer-      _ <- runFrame ctx wheelOuter ui-      offO4 <- getScrollOffset ctx outer-      assertGt failed offO4 offO3-    _ -> assert failed False--runScrollHoverClipTest :: Context -> IORef Int -> IO ()-runScrollHoverClipTest ctx failed = do-  let inp0 = withInput 200 200-      ui = scrollArea (fillW . fixedH 80) $-             column $ do-                mapM_ (\i -> label (T.pack ("out " <> show (i :: Int)))) [1 .. 10]-                (inner, ()) <- scrollArea (fillW . fixedH 36) $-                                 column (mapM_ (\i -> label (T.pack ("in " <> show (i :: Int)))) [1 .. 8])-                pure inner-  (_, inner) <- warmup2 ctx inp0 ui-  mInner <- getPrevRect ctx inner-  case mInner of-    Just r@(Rect _ _ iw ih) | iw > 0 && ih > 0 -> do-      let hoverHidden = inp0 {inputMousePos = spanCenter r, inputScroll = V2 0 1}-      offI0 <- getScrollOffset ctx inner-      _ <- runFrame ctx hoverHidden ui-      offI1 <- getScrollOffset ctx inner-      assert failed (offI1 <= offI0)-    _ -> assert failed False---- A button scrolled into view inside a fixed-height or a page-level (grow)--- scroller receives the click at its visual position.-runScrollButtonClickTest :: Context -> IORef Int -> IO ()-runScrollButtonClickTest ctx failed = do-  pixel <- newPixelContext-  forM_-    [ (ctx, withInput 240 160, fillW . fixedH 80)-    , (pixel, withInput 640 120, tight . grow)-    ] $ \(c, inp0, scrollLayout) -> do-      let ui = do-            (hit, setHit) <- useText ""-            (sid, resp) <- scrollArea scrollLayout $-                             column $ do-                               mapM_ (\_ -> void (label "pad")) [(1 :: Int) .. 6]-                               b <- button' "Target"-                               when (respClicked b) (setHit "yes")-                               pure b-            pure (sid, hit, resp)-      (sid, hit0, _) <- warmup2 c inp0 ui-      assertEq failed hit0 ""-      mScroll <- getPrevRect c sid-      case mScroll of-        Just r -> do-          let wheel = inp0 {inputMousePos = spanCenter r, inputScroll = V2 0 1}-          forM_ [(1 :: Int) .. 8] $ \_ -> void (runFrame c wheel ui)-          off <- getScrollOffset c sid-          assertGt failed off 0-          ((_, _, resp1), _, _, _) <- runFrame c inp0 ui-          (_, hit1, _) <- runClick c inp0 ui (centerOf resp1)-          assertEq failed hit1 "yes"-        _ -> assert failed False--runNestedScrollFocusTest :: Context -> IORef Int -> IO ()-runNestedScrollFocusTest ctx failed = do-  let inp0 = withInput 240 220-      ui = scrollArea (fillW . fixedH 90) $-             column $ do-               pair <- scrollArea (fillW . fixedH 50) $-                         column $ do-                           b <- button' "In"-                           mapM_ (\i -> label (T.pack ("in " <> show (i :: Int)))) [1 .. 10]-                           pure b-               mapM_ (\i -> label (T.pack ("out " <> show (i :: Int)))) [1 .. 10]-               pure pair-  (_, (inner, _)) <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  focus <- getFocusId ctx-  assert failed (focus /= WidgetId 0)-  offI0 <- getScrollOffset ctx inner-  -- Wheel events scroll only the scroller under the mouse; owning focus is not-  -- enough, so scrolling away from the inner scroller must not move it.-  let away = inp0 {inputMousePos = V2 230 210, inputScroll = V2 0 1}-  _ <- runFrame ctx away ui-  offI1 <- getScrollOffset ctx inner-  assertEq failed offI1 offI0---- A button scrolled out of its viewport keeps its last rect, but a pointer--- there must not hover it, show its cursor, or click it.-runScrolledOutImmunityTest :: Context -> IORef Int -> IO ()-runScrolledOutImmunityTest ctx failed = do-  let inp0 = withInput 240 160-      ui = do-        (hit, setHit) <- useText ""-        (sid, b) <- scrollArea (fillW . fixedH 8) $-                      column $ do-                        mapM_ (\_ -> void (label "pad")) [(1 :: Int) .. 40]-                        btn <- button' "Target"-                        when (respClicked btn) (setHit "yes")-                        pure btn-        pure (sid, b, hit)-  (sid, b, hit0) <- warmup2 ctx inp0 ui-  assertEq failed hit0 ""-  mScroll <- getPrevRect ctx sid-  case mScroll of-    Just r -> do-      let wheel = inp0 {inputMousePos = spanCenter r, inputScroll = V2 0 1}-      forM_ [(1 :: Int) .. 80] $ \_ -> void (runFrame ctx wheel ui)-      mBtn <- getPrevRect ctx (respId b)-      case mBtn of-        Just br -> do-          let pos = spanCenter br-              hover = inp0 {inputMousePos = pos}-          kind <- uiCursorKind ctx hover-          assertEq failed kind UiCursorDefault-          _ <- runFrame ctx hover ui-          hot <- getHotId ctx-          assert failed (hot /= respId b)-          (_, _, hit1) <- runClick ctx hover ui pos-          assertEq failed hit1 ""-        _ -> assert failed False-    _ -> assert failed False---- | Probe for the reported scroll stair-stepping artifact. Steps a scroll--- container through fractional offsets at a simulated display scale of 2 and--- decodes the final (snapped) vertex buffer, comparing the per-row motion of--- text (glyph quads) against geometry (fill quads such as separators).--- Asserts every row's text and the adjacent geometry moved by the exact same--- delta on every transition (text/geometry lockstep).-runScrollLockstepProbeTest :: Context -> IORef Int -> IO ()-runScrollLockstepProbeTest ctx failed = do-  setDrawSnapScale ctx 2-  let inp0 = withInput 300 220-      rows =-        [ ("Feature", "Enabled")-        , ("Volume", "50")-        , ("Quality", "High")-        , ("Accent", "#3D7EFF")-        , ("Theme", "Tomorrow at Midnight Min")-        , ("Theme radio", "Theme radio value")-        , ("Name", "Ada Lovelace")-        , ("Notes", "short note")-        , ("Tree", "1 visible item")-        , ("Table sort", "Name")-        ]-      kvRow k v =-        rowWith (tight . gap 12 . alignMid . fillW) $ do-          labelWith (minW 88 . tight) (T.pack k)-          labelWith (tight . fillW . alignEnd) (T.pack v)-      keys = map (T.pack . fst) rows-      ui =-        scrollArea-          (fillW . fixedH 200)-          (column (mapM_ (\(k, v) -> kvRow k v >> separator) rows))-  _ <- runFrame ctx inp0 ui-  ((sid, ()), _, _, _) <- runFrame ctx inp0 ui-  let steps = [0.0, 0.3, 0.6, 1.0, 1.3, 1.7, 2.0, 2.4, 2.7, 3.1, 3.4, 3.8]-  yss <- forM steps $ \off -> do-    setScrollOffset ctx sid off-    _ <- runFrame ctx inp0 ui-    (_, _, draw, _) <- runFrame ctx inp0 ui-    spans <- collectTextSpans ctx-    let keyYs = [listToMaybe (spanYOf k spans) | k <- keys]-    quads <- decodeQuads draw-    let fillTops =-          [ qy1-          | (qx1, qy1, qx2, _, u, v) <- quads-          , abs (u - whitePixelU) < 1.0e-6-          , abs (v - whitePixelV) < 1.0e-6-          , qx2 - qx1 > 60.0-          ]-    pure (keyYs, fillTops)-  forM_ (zip yss (drop 1 yss)) $ \((keyA, fillA), (keyB, fillB)) -> do-    let sKeyA = sort [y | Just y <- keyA]-        sKeyB = sort [y | Just y <- keyB]-        sFillA = sort (filter (> 1.0) fillA)-        sFillB = sort (filter (> 1.0) fillB)-        textDs = [x2 - x1 | (x1, x2) <- zip sKeyA sKeyB]-        fillDs = [x2 - x1 | (x1, x2) <- zip sFillA sFillB]-        n = min (length textDs) (length fillDs)-        t0 = case textDs of-          d : _ -> d-          [] -> 0-        f0 = case fillDs of-          d : _ -> d-          [] -> 0-        textUniform = null (take n [i | i <- textDs, abs (i - t0) > 1.0e-3])-        fillUniform = null (take n [i | i <- fillDs, abs (i - f0) > 1.0e-3])-        sync = null textDs || null fillDs || abs (t0 - f0) <= 1.0e-3-    assert failed (textUniform && fillUniform && sync)---- | Decode the final (post-snap) quad list from a DrawData vertex buffer.--- The harness emits each Quad as 4 consecutive vertices of 8 floats:--- x, y, r, g, b, a, u, v at a 32 byte stride (vertexSize).-decodeQuads :: DrawData -> IO [(Float, Float, Float, Float, Float, Float)]-decodeQuads dd =-  withForeignPtr (drawVertices dd) $ \vp -> do-    let n = drawVertexCount dd `div` 4-        fptr = castPtr vp :: Ptr Float-    forM [0 .. n - 1] $ \q -> do-      let vBase = q * 8 * 4-      xs <- forM [0 .. 3] $ \k -> do-        let o = vBase + k * 8-        x <- peekElemOff fptr o-        y <- peekElemOff fptr (o + 1)-        u <- peekElemOff fptr (o + 6)-        v <- peekElemOff fptr (o + 7)-        pure (x, y, u, v)-      let x1 = minimum [x | (x, _, _, _) <- xs]-          y1 = minimum [y | (_, y, _, _) <- xs]-          x2 = maximum [x | (x, _, _, _) <- xs]-          y2 = maximum [y | (_, y, _, _) <- xs]-          (_u, _v) =-            case xs of-              (_, _, u, v) : _ -> (u, v)-              [] -> (0, 0)-      pure (x1, y1, x2, y2, _u, _v)--whitePixelU :: Float-whitePixelU = 1.5 / 1024.0--whitePixelV :: Float-whitePixelV = 1.5 / 1024.0---- A padded 2D scroller whose fill-width child fits the viewport must not--- report horizontal overflow: content size is measured from the content--- origin (after the leading padding), not from the padding-box origin,--- which double-counts the padding and makes a fitting child look padX--- wider than the viewport every frame. Same for the main axis of a padded--- 1D vertical scroller. Fitting content must not wheel-scroll either: the--- trailing padding extends the scroll range only once an axis genuinely--- overflows.-run2DPadFillOverflowTest :: Context -> IORef Int -> IO ()-run2DPadFillOverflowTest ctx failed = do-  let inp0 = withInput 320 240-      ui =-        scrollArea2D (padAll 6 . fixedH 168 . fillW) $-          columnWith (tight . fillW) $-            mapM_ (void . label) (map T.pack ["alpha", "beta", "gamma"])-  (wid, ()) <- warmup2 ctx inp0 ui-  mState <- scrollNodeState ctx wid True-  case mState of-    Nothing -> assert failed False-    Just (contentW, innerW) -> assert failed (contentW <= innerW + overflowEps)-  -- No phantom scroll range: wheeling must not move either axis.-  let wheel = inp0 {inputScroll = V2 5 5}-  _ <- runFrame ctx wheel ui-  V2 offX offY <- getScrollOffset2D ctx wid-  assert failed (offX == 0 && offY == 0)-  let ui1 = scrollArea (padAll 6 . fixedH 80 . fillW) (labelWith tight (T.pack "fits"))-  (wid1, ()) <- warmup2 ctx inp0 ui1-  mState1 <- scrollNodeState ctx wid1 False-  case mState1 of-    Nothing -> assert failed False-    Just (contentH, innerH) -> assert failed (contentH <= innerH + overflowEps)---- Padding (padAll 6) used by the 2D pad tests, and the resulting reduction--- of the scroller rect to the padded inner size.-padTestPx, padTestBoth :: Float-padTestPx = 6-padTestBoth = padTestPx * 2---- Same overflow epsilon as scrollAxisOverflows / scrollAxisRange.-overflowEps :: Float-overflowEps = 0.5--scrollNodeState :: Context -> WidgetId -> Bool -> IO (Maybe (Float, Float))-scrollNodeState ctx wid is2D = do-  let na = ctxNodeArena ctx-  found <- findNodeM na $ \i -> do-    nt <- getNodeType na i-    if nt == NodeScrollContainer then (== wid) <$> getWidgetId na i else pure False-  forM found $ \i -> do-    contentMain <--      if is2D-        then getScrollContentW na i-        else getNodeValue na i-    (_, _, rw, rh) <- getRect na i-    pure (contentMain, if is2D then rw - padTestBoth else rh - padTestBoth)---- The other side of the pad fix: a padded 2D scroller whose child really is--- wider and taller than the viewport must still report overflow on both--- axes, wheel-scroll vertically, and let scrolling reach the trailing--- padding at the end (the range extends past the last child by padB).-run2DPadOverflowScrollsTest :: Context -> IORef Int -> IO ()-run2DPadOverflowScrollsTest ctx failed = do-  let inp0 = (withInput 320 240) {inputMousePos = V2 100 100}-      ui =-        scrollArea2D (padAll 6 . fixedH 168 . fillW) $-          columnWith (tight . fillW) $ do-            labelWith (tight . fixedW 500) (T.pack "wide child")-            mapM_ (void . label) (map T.pack (replicate 30 "scroll line"))-  (wid, ()) <- warmup2 ctx inp0 ui-  mState <- scrollNodeState ctx wid True-  case mState of-    Nothing -> assert failed False-    Just (contentW, innerW) -> do-      -- The 500px child genuinely overflows the ~308px inner width.-      assertGt failed contentW (innerW + 40)-  mStateH <- scrollNodeState ctx wid False-  case mStateH of-    Nothing -> assert failed False-    Just (contentH, innerH) -> do-      assertGt failed contentH (innerH + 100)-      -- Scroll far past the end: the clamp must land on the trailing-pad-      -- extended range (content + padB - view), not the flush content - view,-      -- so the bottom padding is reachable. The horizontal bar is active-      -- (the 500px child overflows), so it takes its lane out of the vertical-      -- viewport: view = innerH - laneH.-      let laneH =-            scrollBarGutter ScrollBarList padTestPx-          wheelDown = inp0 {inputScroll = V2 0 50}-      replicateM_ 40 (runFrame ctx wheelDown ui)-      V2 _ offEnd <- getScrollOffset2D ctx wid-      assert failed (abs (offEnd - (contentH + padTestPx - (innerH - laneH))) < 1.5)---- The wheel covers the configured step per notch: the context's by default,--- and the scroller's own once it is given one.-runScrollStepTest :: Context -> IORef Int -> IO ()-runScrollStepTest ctx failed = do-  let inp0 = withInput 200 120-      ui = scrollArea (fillW . fixedH 80) (column (replicateM_ 16 (label "scroll line")))-  setScrollTuning ctx defaultScrollTuning {scrollWheelStep = 40}-  (sid, ()) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx sid-  case mRect of-    Nothing -> assert failed False-    Just r -> do-      let wheel = inp0 {inputMousePos = spanCenter r, inputScroll = V2 0 1}-      _ <- runFrame ctx wheel ui-      assertEq failed 40 =<< getScrollOffset ctx sid-      -- The scroller's own step overrides the context's from the next notch on.-      setScrollStep ctx sid 12-      _ <- runFrame ctx wheel ui-      assertEq failed 52 =<< getScrollOffset ctx sid-      -- Back to the context's step.-      setScrollStep ctx sid 0-      _ <- runFrame ctx wheel ui-      assertEq failed 92 =<< getScrollOffset ctx sid---- With a glide time set, a notch eases onto its target over several frames,--- and the frame loop counts the scroller as animating until it lands.-runScrollSmoothTest :: Context -> IORef Int -> IO ()-runScrollSmoothTest ctx failed = do-  let inp0 = withInput 200 120-      ui = scrollArea (fillW . fixedH 80) (column (replicateM_ 16 (label "scroll line")))-  setScrollTuning ctx defaultScrollTuning {scrollWheelStep = 60, scrollSmoothTime = 0.2}-  (sid, ()) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx sid-  case mRect of-    Nothing -> assert failed False-    Just r -> do-      let tick = inp0 {inputMousePos = spanCenter r, inputDeltaTime = 1 / 60}-          wheel = tick {inputScroll = V2 0 1}-      _ <- runFrame ctx wheel ui-      partial <- getScrollOffset ctx sid-      assertGt failed partial 0-      assert failed (partial < 60)-      assert failed =<< scrollGliding ctx sid-      assert failed =<< anyAnimating ctx-      -- It settles exactly on the target, and stops asking for frames there.-      replicateM_ 30 (runFrame ctx tick ui)-      assertEq failed 60 =<< getScrollOffset ctx sid-      gliding <- scrollGliding ctx sid-      assert failed (not gliding)-      -- A notch mid-glide adds to the throw instead of restarting it.-      _ <- runFrame ctx wheel ui-      _ <- runFrame ctx wheel ui-      replicateM_ 30 (runFrame ctx tick ui)-      assertEq failed 180 =<< getScrollOffset ctx sid-      -- Setting an offset outright wins over whatever was in flight.-      _ <- runFrame ctx wheel ui-      setScrollOffset ctx sid 20-      replicateM_ 5 (runFrame ctx tick ui)-      assertEq failed 20 =<< getScrollOffset ctx sid---- The metrics a scroller publishes each frame, and the commands that read--- them: to the end, back to the start, and by whole pages.-runScrollMetricsTest :: Context -> IORef Int -> IO ()-runScrollMetricsTest ctx failed = do-  let inp0 = withInput 200 160-      ui = scrollArea (fillW . fixedH 80) (column (replicateM_ 16 (label "scroll line")))-  (sid, ()) <- warmup2 ctx inp0 ui-  mMetrics <- getScrollMetrics ctx sid-  case mMetrics of-    Nothing -> assert failed False-    Just m -> do-      assertEq failed (scrollAxes m) ScrollAxisY-      assertEq failed (scrollOffset m) (V2 0 0)-      assertGt failed (v2Y (scrollRange m)) 0-      assertEq failed (v2X (scrollRange m)) 0-      -- The viewport is the scroller's box inside its padding and bar lane.-      mRect <- getPrevRect ctx sid-      case mRect of-        Nothing -> assert failed False-        Just r -> do-          assert failed (rectW (scrollViewport m) <= rectW r)-          assert failed (rectH (scrollViewport m) <= rectH r)-      scrollToEnd ctx sid ScrollInstant-      _ <- runFrame ctx inp0 ui-      assertEq failed (v2Y (scrollRange m)) =<< getScrollOffset ctx sid-      scrollToStart ctx sid ScrollInstant-      _ <- runFrame ctx inp0 ui-      assertEq failed 0 =<< getScrollOffset ctx sid-      scrollPages ctx sid (V2 0 1) ScrollInstant-      _ <- runFrame ctx inp0 ui-      paged <- getScrollOffset ctx sid-      assertEq failed (min (v2Y (scrollRange m)) (rectH (scrollViewport m))) paged---- Scrolling a widget into view, by widget and by content rectangle.-runScrollIntoViewTest :: Context -> IORef Int -> IO ()-runScrollIntoViewTest ctx failed = do-  let inp0 = withInput 200 160-      ui =-        scrollArea (fillW . fixedH 80) $-          column (forM [1 .. 16 :: Int] (\i -> label' (T.pack ("line " <> show i))))-  (sid, rows) <- warmup2 ctx inp0 ui-  let target = respId (rows !! 11)-  scrollIntoView ctx sid target ScrollStart ScrollInstant-  _ <- runFrame ctx inp0 ui-  mAfter <- getScrollMetrics ctx sid-  mRow <- getPrevRect ctx target-  case (mAfter, mRow) of-    (Just m, Just r) -> do-      -- The row sits against the top of the viewport, whole.-      assert failed (abs (rectY r - rectY (scrollViewport m)) < 1.5)-      -- Already in view: the nearest alignment leaves the offset alone.-      before <- getScrollOffset ctx sid-      scrollIntoView ctx sid target ScrollNearest ScrollInstant-      _ <- runFrame ctx inp0 ui-      assertEq failed before =<< getScrollOffset ctx sid-      -- A row above the viewport comes back to the top edge.-      let above = respId (rows !! 1)-      scrollIntoView ctx sid above ScrollNearest ScrollInstant-      _ <- runFrame ctx inp0 ui-      mAbove <- getPrevRect ctx above-      case mAbove of-        Nothing -> assert failed False-        Just ra -> assert failed (abs (rectY ra - rectY (scrollViewport m)) < 1.5)-      -- A content rectangle no widget was built for (a virtualized row)-      -- lands the same way.-      let rowH = rectH r-      scrollRectIntoView ctx sid (Rect 0 (rowH * 8) 10 rowH) ScrollStart ScrollInstant-      _ <- runFrame ctx inp0 ui-      off <- getScrollOffset ctx sid-      assert failed (abs (off - rowH * 8) < 1.5)-    _ -> assert failed False---- Content that shrinks under a glide pulls the glide back with it: the--- scroller must not coast to an offset the shorter content cannot reach and--- sit there showing nothing.-runScrollGlideClampTest :: Context -> IORef Int -> IO ()-runScrollGlideClampTest ctx failed = do-  rows <- newIORef (40 :: Int)-  let inp0 = withInput 200 120-      ui = do-        n <- uiIO (readIORef rows)-        scrollArea (fillW . fixedH 80) (column (replicateM_ n (label "scroll line")))-  setScrollTuning ctx defaultScrollTuning {scrollWheelStep = 60, scrollSmoothTime = 0.2}-  (sid, ()) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx sid-  case mRect of-    Nothing -> assert failed False-    Just r -> do-      let tick = inp0 {inputMousePos = spanCenter r, inputDeltaTime = 1 / 60}-          wheel = tick {inputScroll = V2 0 8}-      _ <- runFrame ctx wheel ui-      assert failed =<< scrollGliding ctx sid-      writeIORef rows 12-      replicateM_ 40 (runFrame ctx tick ui)-      mMetrics <- getScrollMetrics ctx sid-      off <- getScrollOffset ctx sid-      case mMetrics of-        Nothing -> assert failed False-        Just m -> do-          assertGt failed (v2Y (scrollRange m)) 0-          assert failed (off <= v2Y (scrollRange m) + 0.5)---- A grow cell with its own minimum width counts as that minimum in a 2D--- scroller, not as its widest label: the row fits once the window clears the--- cell's minimum and the fixed cells beside it. Without a minimum, a grow--- wrapper's content still counts, so wide content keeps its sideways scroll.-runScroll2DGrowMinWidthTest :: Context -> IORef Int -> IO ()-runScroll2DGrowMinWidthTest ctx failed = do-  let longName = T.replicate 12 (T.pack "long name ")-      rows cell =-        scrollArea2D (fillW . fixedH 120) $-          columnWith (fillW . tight) $-            replicateM_ 3 $-              rowWith (fillW . gap 10 . tight) $ do-                void cell-                rowWith (fixedW 80 . tight) (label (T.pack "size"))-      minCell = columnWith (grow . minW 100 . tight) (label longName)-      rangeX inp ui = do-        (wid, ()) <- warmup2 ctx inp ui-        maybe (-1) (v2X . scrollRange) <$> getScrollMetrics ctx wid-  -- The row's least width is 100 + 10 + 80 = 190: fits at 400, not at 150.-  wide <- rangeX (withInput 400 200) (rows minCell)-  assertEq failed wide 0-  narrow <- rangeX (withInput 150 200) (rows minCell)-  assertGt failed narrow 0-  wrapped <- rangeX (withInput 400 200) (rows (columnWith (grow . tight) (rowWith (fixedW 600 . tight) (label (T.pack "wide")))))-  assertGt failed wrapped 0+{-# OPTIONS_GHC -O0 #-}+module Cases.Scroll (tests) where++import Spec+import Data.List (sort)+import Data.Maybe (isJust)+import Data.Text qualified as T+import NanoUI.Internal.Context (ctxNodeArena, setDrawSnapScale)+import NanoUI.Internal.Layout.Arena+  ( findNodeM+  , getNodeValue+  , getNodeType+  , getNodeRect+  , getScrollContentW+  , getWidgetId+  )+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "scroll-thumb" runScrollThumbTest+  , pixelSpec "scroll-bar-gutter" runScrollBarGutterTest+  , spec "scroll-bar-short-track" runScrollBarShortTrackTest+  , spec "scroll-damage" runScrollDamageTest+  , spec "page-backdrop" runPageBackdropTest+  , spec "scroll-tall-label-cull" runTallLabelCullTest+  , spec "nested-scroll" runNestedScrollTest+  , spec "scroll-hit" runScrollHitTest+  , spec "scroll-disjoint-viewport" runDisjointViewportTest+  , spec "scroll-lockstep-probe" runScrollLockstepProbeTest+  , spec "scroll-2d-layout" runScroll2DLayoutTest+  , pixelSpec "scroll-wheel-tuning" runScrollTuningTest+  , pixelSpec "scroll-commands" runScrollCommandsTest+  , spec "scroll-wheel-routing" runWheelRoutingTest+  , spec "scroll-grow-and-overlay" runScrollGrowOverlayTest+  , spec "scroll-focusable-list-nav" runScrollFocusableListNavTest+  ]++-- | Labels @prefix 1@ to @prefix n@.+numbered :: String -> Int -> NanoUI ()+numbered prefix n = mapM_ (\i -> label (T.pack (prefix <> show i))) [1 .. n]++-- | The thumb shows a grab cursor and, pressed, a grabbing one, and neither+-- behind a modal. Hovered or dragged anywhere it brightens; moving onto or+-- off the bar wakes a frame repainting the bar alone, moving along it none.+runScrollThumbTest :: Context -> IORef Int -> IO ()+runScrollThumbTest ctx failed = do+  dialog <- newVar False+  let off = withInputOff 200 120+      eightLines = scrollArea (fillW . fixedH 80) (column (replicateM_ 8 (label "scroll line")))+      ui = eightLines <* modal dialog "Title" (label "body")+  (sid, ()) <- warmup2 ctx off ui+  theme <- readIORef (ctxTheme ctx)+  let rest = scrollBarThumbColor (themeInput theme) theme+      hovered = scrollBarThumbHoverColor (themeInput theme) theme+      thumbIs inp want = do+        (_, dd, _) <- runFrame ctx inp ui+        colors <- map snd <$> drawQuads dd+        assert failed (want `elem` colors && notElem (if want == rest then hovered else rest) colors)+  assertJustM failed (getPrevRect ctx sid) $ \(Rect rx ry rw rh) -> do+    let thumbX = rx + rw - scrollBarGutter ScrollBarList 0 / 2+        onBar y = off {inputMousePos = V2 thumbX y}+        over = onBar (ry + rh / 2)+    assert failed =<< needsRedraw ctx off over+    thumbIs over hovered+    damage <- takeDamage ctx+    assert failed (case damage of DamageClip r -> rectW r < 30; DamageFull -> False)+    assert failed . not =<< needsRedraw ctx over (onBar (ry + rh / 2 + 4))+    assert failed =<< needsRedraw ctx over off+    thumbIs off rest+    thumbIs (applyMouseButton MouseLeft True over) hovered+    thumbIs (holdAt off (V2 20 (ry + rh / 2))) hovered+    thumbIs (applyMouseButton MouseLeft False off) rest+    assertJustM failed (findGrabHover ctx ui off thumbX [ry + rh * n / 8 | n <- [1 .. 7]]) $ \hover -> do+      let down = applyMouseButton MouseLeft True hover+      _ <- runFrame ctx down ui+      assert failed =<< cursorKindIs ctx down UiCursorGrabbing+      _ <- runFrame ctx (releaseAt down) ui+      writeVarIO dialog True+      assertEq failed UiCursorDefault =<< cursorOver ctx hover ui (inputMousePos hover)++-- | Content stops one gap (the right padding, at least the side gap) before+-- the bar's gutter. A list bar keeps that gap to its well's edge; a page bar+-- sits a side gap inside the page's edge, where it alone takes the pointer.+runScrollBarGutterTest :: Context -> IORef Int -> IO ()+runScrollBarGutterTest ctx failed = do+  let listPad = padR (layoutPadding defaultLayout)+      wideThen n = labelWith' fillW "Wide" <* replicateM_ n (label "scroll line")+      page = scrollArea (padAll 12 . grow) (wideThen 20)+      grown = scrollArea (tight . grow) (wideThen 20)+      listBar = scrollBarGutter ScrollBarList+  forM_+    [ (withInput 200 120, scrollArea (fillW . fixedH 60) (wideThen 8), listBar listPad, listPad)+    , (withInput 240 140, grown, scrollBarGutter ScrollBarPage 0, 0)+    , (withInput 240 140, page, scrollBarGutter ScrollBarPage 12, 12)+    , (withInput 240 140, panelWith grow grown, listBar 0, 0)+    ]+    $ \(inp0, ui, gutter, endPad) -> do+      (sid, child) <- warmup2 ctx inp0 ui+      assertScrollGutterPad failed ctx sid child gutter endPad+  let inp0 = withInputOff 240 140+  (sid, _) <- warmup2 ctx inp0 page+  assertJustM failed (getPrevRect ctx sid) $ \(Rect sx sy sw sh) -> do+    let barLeft = sx + sw - scrollBarGutter ScrollBarPage 12+        grabs x = isJust <$> findGrabHover ctx page inp0 x [sy + sh * n / 8 | n <- [1 .. 7]]+    hits <- mapM grabs [barLeft + scrollBarWidth / 2, sx + sw - 1, barLeft - 6]+    assertEq failed [True, False, False] hits++-- | A track shorter than the smallest thumb shows no bar, rather than a+-- thumb that overruns it and moves against the offset.+runScrollBarShortTrackTest :: Context -> IORef Int -> IO ()+runScrollBarShortTrackTest _ failed = do+  let bar h = scrollBarLayout ScrollBarList DirColumn 0 0 100 h (Padding 0 0 0 0) 500+  assert failed (not (isJust (bar 20 0)))+  -- A track as long as the smallest thumb still shows one.+  assertJust failed (bar 22 100) $ \layout -> assert failed (covers (sbTrack layout) (sbThumb layout))++-- | A scroll damages the viewport only. A text edit repaints the bar's lane+-- only when the content's size changes. A hover in a page scroller damages+-- within the window.+runScrollDamageTest :: Context -> IORef Int -> IO ()+runScrollDamageTest ctx failed = do+  let inp0 = withInputOff 200 120+      linesOf :: T.Text -> T.Text -> NanoUI WidgetId+      linesOf firstLine lastLine = fmap fst . scrollArea (fillW . fixedH 60) . column $ do+        label firstLine+        replicateM_ 6 (label "scroll line")+        label lastLine+      clipOf c = takeDamage c >>= \case+        DamageClip r -> pure (Just r)+        DamageFull -> pure Nothing+      painted r = rectW r > 0 && rectH r > 0+      ui = linesOf "count 1" "last"+  sid <- warmup2 ctx inp0 ui+  forM_ [24, 48] $ \off -> do+    _ <- runFrame ctx inp0 (ui <* liftIO (setScrollOffsetIO ctx sid off))+    assertJustM failed (clipOf ctx) $ \r -> assert failed (painted r && rectH r <= 60 + defaultDamageSlop * 2)+  setScrollOffsetIO ctx sid 0+  _ <- warmup2 ctx inp0 ui+  assertJustM failed (getPrevRect ctx sid) $ \(Rect sx sy sw sh) -> do+    _ <- runFrame ctx inp0 (linesOf "count 2" "last")+    let lane = V2 (sx + sw - 2) (sy + sh / 2)+    assertJustM failed (clipOf ctx) $ \r -> assert failed (painted r && not (rectContains r lane))+  -- On the page the lines that move repaint the window whole, so make the+  -- content taller in a floating window, which clips them to its viewport.+  let inWindow lastLine = snd <$> floatingWindow' (constVar True) "Lines" (linesOf "count 1" lastLine)+      winInp = withInputOff 640 400+  mWsid <- warmup2 ctx winInp (inWindow "last")+  assertJust failed mWsid $ \wsid -> assertJustM failed (getPrevRect ctx wsid) $ \(Rect wx wy ww wh) -> do+    _ <- runFrame ctx winInp (inWindow "last\nmore\nmore")+    assertJustM failed (clipOf ctx) $ \r -> assert failed (rectContains r (V2 (wx + ww - 2) (wy + wh / 2)))+  pixel <- newPixelContext+  let controls = scrollWith (tight . grow) . columnWith (padAll 8 . gap 8 . fillW) . card $ do+        heading "Controls"+        (cb, _) <- withValue False (checkbox' "Feature")+        void (withValue 50 (slider 0 100))+        numbered "pad line " 16+        pure cb+  runSim pixel failed (withInputOff 400 160) controls $ do+    _ <- moveTo . On =<< result+    dmg <- frameDamage+    check (case dmg of DamageFull -> True; DamageClip (Rect _ y _ h) -> y >= -1 && y + h <= 161)++-- | A page-level scroller paints no well, so every clip frame fills its+-- viewport, or the strip scrolled content vacates shows a ghost. A full+-- frame leaves the page surface to the backend clear ('pageColor' or+-- 'panelPage' if set), and the scroller's backdrop only over something drawn+-- under it.+runPageBackdropTest :: Context -> IORef Int -> IO ()+runPageBackdropTest ctx failed = do+  theme <- readIORef (ctxTheme ctx)+  let inp0 = withInputOff 300 220+      page around = fmap fst . around $ scrollArea grow (column (replicateM_ 20 (label "backdrop line")))+      near a b = abs (a - b) <= 0.6+      sameViewport (Rect rx ry rw rh) (Rect qx qy qw qh) =+        near qx rx && near qy ry && near (qx + qw) (rx + rw) && near (qy + qh) (ry + rh)+      -- The frame after @prep@ on a fresh context: its clear colour, and+      -- how many quads fill the scroller's viewport.+      frameAfter full ui prep = do+        c <- newContext+        writeIORef (ctxPaintFull c) full+        sid <- warmup2 c inp0 ui+        void (prep c sid)+        (_, draw, _) <- runFrame c inp0 ui+        quads <- drawQuads draw+        Just r <- getPrevRect c sid+        pure (drawClear draw, length [() | (q, _) <- quads, sameViewport r q])+      red = colorRGBA 1 2 3 255+      -- A clip frame after a scroll that repaints a few lines (a frame with+      -- nothing damaged paints nothing).+      scrolled c sid = do+        setScrollOffsetIO c sid 120+        _ <- runFrame c inp0 (page id)+        damageRect c (Rect 10 10 20 20)+  (_, fills) <- frameAfter False (page id) scrolled+  assertGt failed fills 0+  forM_+    [ (id, themeWindow theme, 0)+    , (themed (pageColor red theme), red, 0)+    , (themed (panelPage theme), styleBg (themePanel theme), 0)+    , (panel, themeWindow theme, 1)+    ]+    $ \(around, bg, n) -> assertEq failed (bg, n) =<< frameAfter True (page around) (\_ _ -> pure ())++-- | A label far taller than its scroller draws only the lines near the+-- viewport, wherever it is scrolled, yet every row of the viewport shows a+-- glyph (monospace glyphs are boxes a line tall).+runTallLabelCullTest :: Context -> IORef Int -> IO ()+runTallLabelCullTest ctx failed = do+  let inp0 = withInputOff 300 220+      txt = T.intercalate "\n" [T.pack ("line " <> show i) | i <- [1 .. 1000 :: Int]]+      ui = fmap fst $ scrollArea (fillW . fixedH 100) (labelWith fillW txt)+  sid <- warmup2 ctx inp0 ui+  forM_ [0, 3333, 1000000] $ \off -> do+    setScrollOffsetIO ctx sid off+    (_, draw, _) <- run2Frames ctx inp0 ui+    assertJustM failed (getPrevRect ctx sid) $ \(Rect rx ry rw rh) -> do+      quads <- drawQuads draw+      -- Glyph boxes, not the scroller's backdrop, border or bar.+      let glyphs = [r | (r@(Rect qx _ qw qh), _) <- quads, qw < 40, qh < 40, qx < rx + rw / 2]+          shown y = any (\(Rect _ gy _ gh) -> gy <= y && y < gy + gh) glyphs+      assert failed (length quads < 400)+      assert failed (all shown [ry + fromIntegral k | k <- [12, 17 .. floor rh - 12 :: Int]])++-- | The wheel goes to the scroller under the pointer, not the focused one:+-- the inner of two nested ones, the outer once the inner is at its end, and+-- by where they are drawn (not above the scrolled inner viewport). An inner+-- scroller clipped out below the outer viewport takes none.+runNestedScrollTest :: Context -> IORef Int -> IO ()+runNestedScrollTest ctx failed = do+  let ui = scrollArea (fillW . fixedH 90) . column $ do+        (inner, _) <- scrollArea (fillW . fixedH 40) . column $ button' "In" >> numbered "in " 12+        numbered "out " 12+        pure inner+  runSim ctx failed (withInput 240 220) ui $ do+    (outer, inner) <- result+    let offsets = (,) <$> scrollOffsetOf outer <*> scrollOffsetOf inner+        notch = frameWith (\i -> i {inputScroll = V2 0 1})+        pump prev = do+          (_, now) <- notch >> offsets+          when (now > prev) (pump now)+    r@(Rect ix iy iw ih) <- prevRect inner+    Rect _ oy _ oh <- prevRect outer+    pressTab 1+    check . (/= WidgetId 0) =<< focusedId+    _ <- wheel (at 230 210) (V2 0 1)+    checkEq (0, 0) =<< offsets+    _ <- wheel (Within r) (V2 0 1)+    (o1, i1) <- offsets+    checkEq 0 o1+    checkGt i1 0+    pump i1+    (o2, iMax) <- offsets+    checkEq 0 o2+    _ <- wheel (at (ix + iw / 2) (iy - 6)) (V2 0 (-1))+    checkEq iMax . snd =<< offsets+    _ <- wheel (at (ix + iw / 2) (min (oy + oh - 4) (iy + ih + 8))) (V2 0 1)+    o3 <- fst <$> offsets+    checkGt o3 0+  c <- newContext+  let below = scrollArea (fillW . fixedH 80) . column $ do+        numbered "out " 10+        fst <$> scrollArea (fillW . fixedH 36) (column (numbered "in " 8))+  runSim c failed (withInput 200 400) below $ do+    (_, inner) <- result+    r <- prevRect inner+    check (v2Y (spanCenter r) > 80 && v2Y (spanCenter r) < 400)+    _ <- wheel (Within r) (V2 0 1)+    checkEq 0 =<< scrollOffsetOf inner++-- | A button scrolled into view, in a fixed or a page-level scroller, takes+-- the click where it is drawn. One scrolled out keeps its last rect, but a+-- pointer there neither hovers it, shows its cursor nor clicks it.+runScrollHitTest :: Context -> IORef Int -> IO ()+runScrollHitTest _ failed = do+  let target layout pads = do+        hitVar <- useVar ("" :: T.Text)+        hit <- readVar hitVar+        (sid, btn) <- scrollArea layout . column $ do+          replicateM_ pads (label "pad")+          b <- button' "Target"+          when (respClicked b) (writeVar hitVar "yes")+          pure b+        pure (sid, btn, hit)+      wheelDown n = do+        (sid, _, _) <- result+        replicateM_ n (wheel (OnWidget sid) (V2 0 1))+        scrollOffsetOf sid+      hitOf (_, _, hit) = hit+  let hosts =+        [(newContext, withInput 240 160, fillW . fixedH 80), (newPixelContext, withInput 640 120, tight . grow)]+  forM_ hosts $+    \(mk, inp, layout) -> do+      ctx <- mk+      runSim ctx failed inp (target layout 6) $ do+        off <- wheelDown 8+        checkGt off 0+        (_, b, _) <- frame+        checkEq "yes" . hitOf =<< click (On b)+  ctx <- newContext+  runSim ctx failed (withInput 240 160) (target (fillW . fixedH 8) 40) $ do+    _ <- wheelDown 80+    (_, b, _) <- result+    r <- prevRect (respId b)+    checkEq UiCursorDefault =<< cursorAt (Within r)+    check . (/= respId b) =<< hotId+    checkEq "" . hitOf =<< click (Within r)++-- | Content of a scroller outside its parent's viewport has an empty clip+-- (rather than none, which would draw it) and takes no pointer input, even scrolled up into the+-- outer viewport's rect. In view, a pinned button wins over layered ones,+-- and the top layer's button wins beside it.+runDisjointViewportTest :: Context -> IORef Int -> IO ()+runDisjointViewportTest ctx failed = do+  let filler h = spacer (Fixed 10) (Fixed h)+      ui = fmap (\(outer, (inner, bs)) -> (outer, inner, bs)) . scrollArea (fixedH 100 . fillW) . column $ do+        filler 150+        inner <- scrollArea (fixedH 30 . fillW) . column $ do+          stacked <- layers (mapM (buttonWith' (fixedWH 100 20)) ["Under", "Over"])+          pinned <- buttonWith' (pinAt 60 0 . fixedWH 40 20) "Pin"+          filler 200+          pure (stacked ++ [pinned])+        filler 100+        pure inner+      -- A point on the top layer's button left of the pinned one, and on the pinned one.+      targets bs =+        let V2 _ y = centerOf (bs !! 1)+         in [(1, V2 (rectX (respRect (bs !! 1)) + 10) y), (2 :: Int, centerOf (bs !! 2))]+      buttonsAfter offsets = liftIO offsets >> (\(_, _, bs) -> bs) <$> settle+      hotAt p = moveTo (At p) >> frame >> hotId+  runSim ctx failed (withInputOff 300 200) ui $ do+    (outer, inner, _) <- result+    hidden <- buttonsAfter (setScrollOffsetIO ctx inner 100)+    mapM_ expectNot ["Under", "Over", "Pin"]+    forM_ (targets hidden) $ \(_, p) -> do+      check (v2Y p > 0 && v2Y p < 100)+      check . (`notElem` map respId hidden) =<< hotAt p+      (_, _, pressed) <- press (At p)+      check (not (any (\r -> respHovered r || respPressed r) pressed))+      (_, _, clicked) <- release+      check (not (any respClicked clicked))+    shown <- buttonsAfter (setScrollOffsetIO ctx inner 0 >> setScrollOffsetIO ctx outer 140)+    forM_ (targets shown) $ \(i, p) -> do+      checkEq (respId (shown !! i)) =<< hotAt p+      (_, _, clicked) <- click (At p)+      checkEq [j == i | j <- [0 .. 2]] (map respClicked clicked)++-- | Probe for the reported scroll stair-stepping: at a display scale of 2,+-- through fractional offsets, each row's text and the separators beside it+-- move by the same delta in the final (snapped) vertex buffer.+runScrollLockstepProbeTest :: Context -> IORef Int -> IO ()+runScrollLockstepProbeTest ctx failed = do+  setDrawSnapScale ctx 2+  let inp0 = withInput 300 220+      rows =+        [ ("Feature", "Enabled")+        , ("Volume", "50")+        , ("Quality", "High")+        , ("Accent", "#3D7EFF")+        , ("Theme", "Tomorrow at Midnight Min")+        , ("Theme radio", "Theme radio value")+        , ("Name", "Ada Lovelace")+        , ("Notes", "short note")+        , ("Tree", "1 visible item")+        , ("Table sort", "Name")+        ]+      kvRow k v = rowWith (tight . gap 12 . alignMiddle . fillW) $ do+        labelWith (minW 88 . tight) k+        labelWith (tight . fillW . alignEnd) v+      ui = scrollArea (fillW . fixedH 200) (column (mapM_ (\(k, v) -> kvRow k v >> separator) rows))+  (sid, ()) <- warmup2 ctx inp0 ui+  yss <- forM [0.0, 0.3, 0.6, 1.0, 1.3, 1.7, 2.0, 2.4, 2.7, 3.1, 3.4, 3.8] $ \off -> do+    setScrollOffsetIO ctx sid off+    (_, draw, _) <- run2Frames ctx inp0 ui+    ss <- collectTextSpans ctx+    vs <- drawnVertices draw+    -- Solid fills sample the atlas's white texel (a copy of+    -- 'NanoUI.Internal.Draw.Arena.whitePixel', which tests cannot import).+    let white = 1.5 / 1024+        solid u v = abs (u - white) < 1.0e-6 && abs (v - white) < 1.0e-6+        keyYs = [y | (k, _) <- rows, y <- take 1 (spanYOf k ss)]+        -- The buffer holds each quad as four vertices.+        quads (a : b : c : d : rest) = [a, b, c, d] : quads rest+        quads _ = []+        fills =+          [ (minimum (map vY q), maximum xs - minimum xs)+          | q@(v : _) <- quads vs+          , solid (vU v) (vV v)+          , let xs = map vX q+          ]+    pure (sort keyYs, sort [y1 | (y1, w) <- fills, w > 60, y1 > 1])+  -- The probe found rows and separators to compare at every step.+  assert failed (all (\(ks, fs) -> not (null ks) && not (null fs)) yss)+  let steady ds = and [abs (d - e) <= 1.0e-3 | (d, e) <- zip ds (drop 1 ds)]+  forM_ (zip yss (drop 1 yss)) $ \((keyA, fillA), (keyB, fillB)) -> do+    let textDs = zipWith subtract keyA keyB+        fillDs = zipWith subtract fillA fillB+        n = min (length textDs) (length fillDs)+    case (textDs, fillDs) of+      (t0 : _, f0 : _) -> assert failed (all (steady . take n) [textDs, fillDs] && abs (t0 - f0) <= 1e-3)+      _ -> pure ()++-- | The main extent of the scroll node @wid@ (its content width for a 2D+-- one, its content height for a 1D one) and the size inside its 6px padding.+scrollNodeState :: Context -> WidgetId -> Bool -> IO (Maybe (Float, Float))+scrollNodeState ctx wid is2D = do+  let na = ctxNodeArena ctx+  found <- findNodeM na $ \i -> do+    nt <- getNodeType na i+    if nt == NodeScrollContainer then (== wid) <$> getWidgetId na i else pure False+  forM found $ \i -> do+    contentMain <- if is2D then getScrollContentW na i else getNodeValue na i+    Rect _ _ rw rh <- getNodeRect na i+    pure (contentMain, (if is2D then rw else rh) - 12)++-- | 2D layout: a grow cell counts its own minimum width (zero too), not its+-- widest label, and a grow wrapper without one its content. A fit-width+-- scroller capped in height makes room for its bar. Children line up along+-- the direction (a grid layout lines them down). Padding counts once: a+-- fitting child shows no overflow and does not wheel, an overflowing one+-- wheels on to the trailing padding.+runScroll2DLayoutTest :: Context -> IORef Int -> IO ()+runScroll2DLayoutTest _ failed = do+  let longName = T.replicate 12 "long name "+      row3 = replicateM_ 3 . rowWith (fillW . gap 10 . tight)+      rows cell = scrollArea2D (fillW . fixedH 120) . columnWith (fillW . tight) . row3 $ do+        void cell+        rowWith (fixedW 80 . tight) (label "size")+      rangeX w ui = do+        c <- newContext+        (wid, ()) <- warmup2 c (withInput w 200) ui+        maybe (-1) (v2X . scrollRange) <$> getScrollMetricsIO c wid+      minCell m = columnWith (grow . minW m . tight) (label longName)+  -- The row's least width is 100 + 10 + 80 = 190: it fits at 400, not at 150.+  ranges <-+    sequence+      [ rangeX 400 (rows (minCell 100))+      , rangeX 150 (rows (minCell 0))+      , rangeX 150 (rows (minCell 100))+      , rangeX 400 (rows (columnWith (grow . tight) (rowWith (fixedW 600 . tight) (label "wide"))))+      ]+  assertEq failed [True, True, False, False] (map (== 0) ranges)+  assert failed (all (>= 0) ranges)+  fit <- newContext+  let items = mapM_ (label . T.pack . ("item " <>) . show) [10 .. 59 :: Int]+  _ <- warmup2 fit (withInput 400 300) (columnWith tight (scrollWith (maxH 200) items))+  -- Seven glyphs of the test font, as wide as its lines are tall.+  assertEq failed (replicate 50 (7 * 12)) . map rectW . drop 2 =<< arenaRects fit+  let sideways l = l {layoutDirection = Row}+  forM_ [(sideways, V2 300 0, map rectX, [0, 100 .. 500]), (gridCols 3, V2 0 40, map rectY, [0, 40 .. 200])] $+    \(lay, range, along, want) -> do+      c <- newContext+      let boxes = replicateM_ 6 (box (fixedWH 100 40) (colorRGBA 255 0 0 255))+          area = scrollArea2D (lay . tight . gap 0 . fixedWH 300 200) boxes+      (sid, ()) <- warmup2 c (withInput 400 300) (columnWith tight area)+      assertEq failed want . along . drop 2 =<< arenaRects c+      assertJustM failed (getScrollMetricsIO c sid) $ \m -> assertEq failed range (scrollRange m)+  padded <- newPixelContext+  let inp0 = (withInput 320 240) {inputMousePos = V2 100 100}+      within (content, inner) = assert failed (content <= inner + 0.5)+      paddedArea = scrollArea2D (padAll 6 . fixedH 168 . fillW) . columnWith (tight . fillW)+      fits = paddedArea (mapM_ label ["alpha", "beta", "gamma"])+  (wid, ()) <- warmup2 padded inp0 fits+  assertJustM failed (scrollNodeState padded wid True) within+  _ <- runFrame padded inp0 {inputScroll = V2 5 5} fits+  assertEq failed (V2 0 0) =<< getScrollOffset2DIO padded wid+  (wid1, ()) <- warmup2 padded inp0 (scrollArea (padAll 6 . fixedH 80 . fillW) (labelWith tight "fits"))+  assertJustM failed (scrollNodeState padded wid1 False) within+  over <- newPixelContext+  let overflows = paddedArea (labelWith (tight . fixedW 500) "wide child" >> numbered "line " 30)+  (wid2, ()) <- warmup2 over inp0 overflows+  assertJustM failed (scrollNodeState over wid2 True) $ \(contentW, innerW) ->+    assertGt failed contentW (innerW + 40)+  assertJustM failed (scrollNodeState over wid2 False) $ \(contentH, innerH) -> do+    assertGt failed contentH (innerH + 100)+    -- Far past the end, the clamp lands on content + padB - view, where the+    -- active horizontal bar takes its lane out of the view.+    replicateM_ 40 (runFrame over inp0 {inputScroll = V2 0 50} overflows)+    V2 _ offEnd <- getScrollOffset2DIO over wid2+    assert failed (abs (offEnd - (contentH + 6 - (innerH - scrollBarGutter ScrollBarList 6))) < 1.5)++-- | A notch covers the context's step, or the scroller's own. With a glide+-- time it eases onto its target, animating until it lands exactly; a notch+-- mid-glide adds to the throw, an offset set outright wins, and content+-- shrinking under the glide pulls it back within reach.+runScrollTuningTest :: Context -> IORef Int -> IO ()+runScrollTuningTest ctx failed = do+  rows <- newIORef (40 :: Int)+  let ui = do+        n <- liftIO (readIORef rows)+        fst <$> scrollArea (fillW . fixedH 80) (column (replicateM_ n (label "scroll line")))+  setScrollTuningIO ctx defaultScrollTuning {scrollWheelStep = 40}+  runSim ctx failed (withInput 200 120) ui $ do+    sid <- result+    let notch = frameWith (\i -> i {inputScroll = V2 0 1})+        offset = scrollOffsetOf sid+        gliding = liftIO (scrollGlidingIO ctx sid)+        io = liftIO+    _ <- moveTo (OnWidget sid)+    checkEq 40 =<< (notch >> offset)+    io (setScrollStepIO ctx sid 12)+    checkEq 52 =<< (notch >> offset)+    io (setScrollStepIO ctx sid 0)+    checkEq 92 =<< (notch >> offset)+    io (setScrollTuningIO ctx defaultScrollTuning {scrollWheelStep = 60, scrollSmoothTime = 0.2})+    io (setScrollOffsetIO ctx sid 0)+    modifyInput (\i -> i {inputDeltaTime = 1 / 60})+    partial <- notch >> offset+    check (partial > 0 && partial < 60)+    check =<< gliding+    check =<< io (anyAnimating ctx)+    replicateM_ 30 frame+    checkEq 60 =<< offset+    check . not =<< gliding+    replicateM_ 2 notch >> replicateM_ 30 frame+    checkEq 180 =<< offset+    _ <- notch+    io (setScrollOffsetIO ctx sid 20)+    replicateM_ 5 frame+    checkEq 20 =<< offset+    _ <- frameWith (\i -> i {inputScroll = V2 0 8})+    check =<< gliding+    io (writeIORef rows 12)+    replicateM_ 40 frame+    Just m <- io (getScrollMetricsIO ctx sid)+    checkGt (v2Y (scrollRange m)) 0+    check . (<= v2Y (scrollRange m) + 0.5) =<< offset++-- | The published metrics and the commands reading them: to the end, the+-- start, a page, and a widget or a content rect brought into view. Brought+-- into view on a frame the wheel moved, a row lands where asked: the last+-- frame's rects go with the offset they were placed at.+runScrollCommandsTest :: Context -> IORef Int -> IO ()+runScrollCommandsTest ctx failed = do+  setScrollTuningIO ctx defaultScrollTuning {scrollSmoothTime = 0}+  jump <- newIORef False+  let lines16 = column (forM [1 .. 16 :: Int] (\i -> label' (T.pack ("line " <> show i))))+      ui = do+        (sid, rows) <- scrollArea (fillW . fixedH 80) lines16+        go <- liftIO (readIORef jump)+        when go $ liftIO (scrollIntoViewIO ctx sid (respId (rows !! 11)) ScrollStart ScrollInstant)+        pure (sid, rows)+  runSim ctx failed (withInput 200 160) ui $ do+    (sid, rows) <- result+    Just m <- liftIO (getScrollMetricsIO ctx sid)+    r <- prevRect sid+    let range = v2Y (scrollRange m)+        view = scrollViewport m+        after cmd = liftIO cmd >> frame >> scrollOffsetOf sid+        target = respId (rows !! 11)+        atTop wid = prevRect wid >>= \rr -> check (abs (rectY rr - rectY view) < 1.5)+    checkEq (ScrollAxisY, V2 0 0, 0) (scrollAxes m, scrollOffset m, v2X (scrollRange m))+    checkGt range 0+    -- The viewport is the scroller's box inside its padding and bar lane.+    check (rectW view <= rectW r && rectH view <= rectH r)+    checkEq range =<< after (scrollToEndIO ctx sid ScrollInstant)+    checkEq 0 =<< after (scrollToStartIO ctx sid ScrollInstant)+    checkEq (min range (rectH view)) =<< after (scrollPagesIO ctx sid (V2 0 1) ScrollInstant)+    placed <- after (scrollIntoViewIO ctx sid target ScrollStart ScrollInstant)+    atTop target+    -- Already in view: the nearest alignment leaves the offset alone.+    checkEq placed =<< after (scrollIntoViewIO ctx sid target ScrollNearest ScrollInstant)+    -- A row above the viewport comes back to the top edge.+    _ <- after (scrollIntoViewIO ctx sid (respId (rows !! 1)) ScrollNearest ScrollInstant)+    atTop (respId (rows !! 1))+    rowH <- rectH <$> prevRect target+    off <- after (scrollRectIntoViewIO ctx sid (Rect 0 (rowH * 8) 10 rowH) ScrollStart ScrollInstant)+    check (abs (off - rowH * 8) < 1.5)+    _ <- after (scrollToStartIO ctx sid ScrollInstant)+    _ <- moveTo (OnWidget sid)+    liftIO (writeIORef jump True)+    _ <- frameWith (\i -> i {inputScroll = V2 0 1})+    liftIO (writeIORef jump False)+    _ <- frame+    atTop target++-- | On a fresh context, hover where @aim@ points given the scrollers the+-- view returns, turn the wheel by @d@ there, and say which scrollers moved.+wheelMoves :: IORef Int -> NanoUI [WidgetId] -> ([WidgetId] -> Sim [WidgetId] Target) -> V2 -> IO [Bool]+wheelMoves failed ui aim d = do+  ctx <- newContext+  runSim ctx failed (withInputOff 400 300) ui $ do+    _ <- flip wheel d =<< aim =<< result+    map (/= V2 0 0) <$> (mapM scrollOffset2DOf =<< result)++-- | Which scroller takes the wheel: the topmost under the pointer, though+-- declared first, unless a 'PointerBlock' panel over it (not inside it)+-- takes it; one in the overflow of a short root; not a nested one that fits+-- or one clipped under the page's bar lane, where the page's thumb takes a+-- press. The unused axis goes on outward, to a horizontal scroller inside a+-- vertical page (past rows that hold none; the one under the pointer first),+-- between 1D and 2D scrollers either way, and stops at a popup.+runWheelRoutingTest :: Context -> IORef Int -> IO ()+runWheelRoutingTest _ failed = do+  let rows n = column (replicateM_ n (label "row"))+      across w h l = (fixedWH w h l) {layoutDirection = Row}+      cells = replicateM_ 30 (label "wide cell")+      wide = box (fixedWH 600 10) (colorRGBA 90 90 90 255)+      page body = (\(o, is) -> o : is) <$> scrollArea (fixedWH 300 200) (column body)+      pair (a, b) = [a, b]+      on k sids = pure (OnWidget (sids !! k))+      point p _ = pure (At p)+      firstRect = prevRect . (!! 0)+      expectMoves want ui aim d = assertEq failed want =<< wheelMoves failed ui aim d+      overlapping mode = fmap pair . columnWith tight $ do+        (top, ()) <- scrollArea (pinAt 20 20 . fixedWH 120 100) (rows 30)+        (under, ()) <- scrollArea (fixedWH 360 240) (rows 60)+        panelWith (pointer mode . pinAt 200 20 . fixedWH 100 80) (pure ())+        pure (top, under)+  forM_+    [ (PointerAuto, V2 60 60, [True, False])+    , (PointerAuto, V2 250 60, [False, True])+    , (PointerBlock, V2 250 60, [False, False])+    , (PointerBlock, V2 250 200, [False, True])+    ]+    $ \(mode, p, want) -> expectMoves want (overlapping mode) (point p) (V2 0 1)+  let carded = fmap (pure . fst) . columnWith tight $ do+        r <- scrollArea (fixedWH 300 200) . column $ do+          panelWith (pointer PointerBlock . fixedWH 200 60) (pure ())+          rows 30+        box (pinAt 350 250 . fixedWH 10 10) (colorRGBA 255 0 0 255)+        pure r+      overflowing = fmap pure . columnWith (tight . fixedH 100) $ do+        box (fixedWH 10 150) (colorRGBA 90 90 90 255)+        fst <$> scrollArea (fixedWH 300 100) (rows 30)+      belowRoot sids = firstRect sids >>= \r -> Within r <$ checkGt (rectY r) 100+  expectMoves [True] carded (point (V2 60 30)) (V2 0 1)+  expectMoves [True] overflowing belowRoot (V2 0 1)+  let innerThen layout body = page ((: []) . fst <$> scrollArea layout body <* rows 30)+      fitting = innerThen (fillW . fixedH 100) (replicateM_ 2 (label "fits"))+      wider = innerThen (fixedWH 400 150) (replicateM_ 30 (label "inner row"))+      halfBar = scrollBarGutter ScrollBarList 0 / 2+      lane sids = (\(Rect px py pw _) -> at (px + pw - halfBar) (py + 10)) <$> firstRect sids+  expectMoves [True, False] fitting (on 1) (V2 0 1)+  expectMoves [True, False] wider lane (V2 0 1)+  ctx <- newContext+  runSim ctx failed (withInputOff 400 300) wider $ do+    _ <- press =<< lane =<< result+    checkEq UiCursorGrabbing =<< pointerCursor+  let inside = page $ do+        replicateM_ 3 (row (label "plain" >> void (button' "b")))+        (inner, ()) <- column (scrollArea (across 200 40) cells)+        rows 20+        pure [inner]+      cornerOf sids = (\(Rect x y _ _) -> at (x + 10) (y + 5)) <$> firstRect sids+      strips = page $ do+        (strip, ()) <- scrollArea (across 200 40) (label "fits")+        replicateM_ 3 (label "row")+        (carousel, ()) <- scrollArea (across 200 40) cells+        rows 20+        pure [strip, carousel]+  expectMoves [False, True] inside cornerOf (V2 1 0)+  expectMoves [False, False, False] strips (on 1) (V2 1 0)+  let inRow = fmap pair . scrollArea (across 300 200) $ do+        (inner, ()) <- scrollArea2D (fixedWH 150 100) (column (wide >> rows 30))+        replicateM_ 30 (label "outer cell")+        pure inner+      in2D = fmap pair . scrollArea2D (fixedWH 300 200) . column $ do+        (list, ()) <- scrollArea (fixedWH 100 80) (rows 30)+        wide+        rows 30+        pure list+  expectMoves [False, True] inRow (on 1) (V2 1 0)+  expectMoves [False, True] in2D (on 1) (V2 0 1)+  expectMoves [True, False] in2D (on 1) (V2 1 0)+  let popupAt = defaultPopupConfig (AnchorPoint (V2 200 20))+      popped = page $ do+        rows 30+        maybe [] pure . snd <$> popup' (constVar True) popupAt (fst <$> scrollArea (across 150 40) cells)+  assertEq failed False . (!! 0) =<< wheelMoves failed popped (on 1) (V2 0 1)+  assertEq failed False . (!! 1) =<< wheelMoves failed popped (point (V2 20 150)) (V2 1 0)+  assertEq failed True . (!! 0) =<< wheelMoves failed popped (point (V2 20 150)) (V2 0 1)++runScrollGrowOverlayTest :: Context -> IORef Int -> IO ()+runScrollGrowOverlayTest ctx failed = do+  let inp = withInputOff 400 300+      bareVert = ScrollConfig ScrollNone ScrollAuto True False+      splitUi =+        columnWith (fixedWH 300 200 . tight . gap 0) $+          (,)+            <$> (fst <$> scrollAreaConfigured bareVert (grow . minW 0 . minH 0) (numbered "top " 30))+            <*> (fst <$> scrollAreaConfigured bareVert (grow . minW 0 . minH 0) (numbered "bot " 2))+  (topId, botId) <- warmup2 ctx inp splitUi+  assertJustM failed (getPrevRect ctx topId) $ \(Rect _ _ _ th) ->+    assert failed (abs (th - 100) <= 1)+  assertJustM failed (getPrevRect ctx botId) $ \(Rect _ _ _ bh) ->+    assert failed (abs (bh - 100) <= 1)+  c2 <- newContext+  let overlayCfg = ScrollConfig ScrollNone ScrollOverlay True False+      autoCfg = ScrollConfig ScrollNone ScrollAuto True False+      overlayUi = column $ do+        ovResp <- scrollConfigured overlayCfg (fixedWH 200 80 . tight) (buttonWith' (fillW . fixedH 20) "ov-btn" <* numbered "ov " 20)+        auResp <- scrollConfigured autoCfg (fixedWH 200 80 . tight) (buttonWith' (fillW . fixedH 20) "au-btn" <* numbered "au " 20)+        pure (respRect ovResp, respRect auResp)+  (Rect _ _ ow _, Rect _ _ aw _) <- warmup2 c2 inp overlayUi+  assert failed (abs (ow - 200) <= 0.5)+  assertLt failed aw 198++-- | Focusable scroll containers ('scrollFocusable') take focus on click and+-- Tab, isolate keyboard list navigation ('useListNav' / 'useListNavWith') per+-- focused list, and scroll the selected row into view.+runScrollFocusableListNavTest :: Context -> IORef Int -> IO ()+runScrollFocusableListNavTest ctx failed = do+  selA <- newVar (Just 0 :: Maybe Int)+  selB <- newVar (Nothing :: Maybe Int)+  actA <- newIORef ([] :: [Int])+  let rowH = 24 :: Float+      listCfg = defaultScrollConfig {scrollPolicyX = ScrollNone, scrollFocusable = True}+      listBox tag selVar onAct useWith = withKey (tag :: T.Text) $ do+        sid <- currentId+        sel <- readVar selVar+        nav <-+          if useWith+            then useListNavWith sid 30 sel (NavRowRect (\i -> Rect 0 (fromIntegral i * rowH) 1 rowH))+            else useListNav sid 30 sel rowH+        when (lnChanged nav) (writeVar selVar (lnIndex nav))+        when (lnActivated nav) (forM_ (lnIndex nav) (liftIO . onAct))+        scrollConfigured listCfg (fixedWH 160 120 . tight . gap 0) $+          forM_ [0 .. 29 :: Int] $ \i ->+            void (mouseArea (fillW . fixedH rowH) (label (tag <> "-" <> T.pack (show i))))+        pure sid+      ui = rowWith (tight . gap 12) $+        (,)+          <$> listBox "A" selA (\i -> modifyIORef' actA (++ [i])) False+          <*> listBox "B" selB (const (pure ())) True+  runSim ctx failed (withInput 400 200) ui $ do+    (sidA, sidB) <- result+    -- Clicking inside List A focuses List A.+    _ <- click (At (V2 40 40)) >> settle+    checkEq sidA =<< focusedId+    -- Down moves List A to Just 1 without moving List B.+    _ <- pressKey KeyDown >> settle+    checkEq (Just 1, Nothing) =<< ((,) <$> readV selA <*> readV selB)+    -- End jumps to row 29 and scrolls List A down; List B stays at Nothing.+    _ <- pressKey KeyEnd >> settle+    checkEq (Just 29, Nothing) =<< ((,) <$> readV selA <*> readV selB)+    offA <- onContext (\c -> v2Y <$> getScrollOffset2DIO c sidA)+    offB <- onContext (\c -> v2Y <$> getScrollOffset2DIO c sidB)+    checkGt offA 400+    checkEq 0 offB+    -- PageUp steps back by viewport height / rowH (5 rows), Enter activates.+    _ <- pressKey KeyPageUp >> settle+    checkEq (Just 24) =<< readV selA+    _ <- pressKey KeyEnter >> settle+    checkEq [24] =<< liftIO (readIORef actA)+    -- Home jumps back to 0 and scrolls back to top.+    _ <- pressKey KeyHome >> settle+    checkEq (Just 0) =<< readV selA+    offA0 <- onContext (\c -> v2Y <$> getScrollOffset2DIO c sidA)+    checkEq 0 offA0+    -- Tab moves focus to List B (Nothing selection); Down selects row 0, Down moves to row 1.+    _ <- pressKey KeyTab >> settle+    checkEq sidB =<< focusedId+    _ <- pressKey KeyDown >> settle+    checkEq (Just 0, Just 0) =<< ((,) <$> readV selA <*> readV selB)+    _ <- pressKey KeyDown >> settle+    checkEq (Just 0, Just 1) =<< ((,) <$> readV selA <*> readV selB)+    -- Reset List B to Nothing; Up from Nothing selects the last row (29) and scrolls there.+    liftIO (writeVarIO selB Nothing)+    _ <- pressKey KeyUp >> settle+    checkEq (Just 29) =<< readV selB+    offB29 <- onContext (\c -> v2Y <$> getScrollOffset2DIO c sidB)+    checkGt offB29 400
test/integration/Cases/Select.hs view
@@ -1,234 +1,313 @@-module Cases.Select-  ( runSelectDragToSelectTest-  , runSelectKeyboardTest-  , runSelectOverlayDamageTest-  , runSelectChangeOnceTest-  , runSelectCloseKeepsFocusTest-  , runSliderCursorTest-  , runTreeKeyboardTest-  , runTreeSelectTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Select (tests) where -import Data.IORef (IORef, newIORef)-import Data.Text qualified as T-import NanoUI+import Spec+import Data.Bifunctor (first) import Data.Primitive.SmallArray qualified as SA-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, withInput)-import NanoUI.Testing.Harness-  ( assertSpansHas-  , centerOf-  , clickPair-  , hasText-  , held-  , keyInp-  , runClick-  , tabInp-  , warmup2-  )+import Data.Text qualified as T+import NanoUI.Testing.Sim -runSliderCursorTest :: Context -> IORef Int -> IO ()-runSliderCursorTest ctx failed = do-  let inp0 = withInput 300 80-      ui = column (slider' 0 100 50)-  (resp, _) <- warmup2 ctx inp0 ui-  let Rect rx ry rw rh = respRect resp-      track = sliderTrackBounds rx ry rw rh-      trackMid = V2 (rectX track + rectW track / 2) (rectY track + rectH track / 2)-      offPos = V2 (rx + rw + 20) (ry + rh + 20)-      hoverTrack = inp0 {inputMousePos = trackMid}-  _ <- runFrame ctx hoverTrack ui-  hoverKind <- uiCursorKind ctx hoverTrack-  assertEq failed hoverKind UiCursorGrab-  let pressTrack = hoverTrack {inputMouseDown = True, inputMousePressed = True}-  _ <- runFrame ctx pressTrack ui-  grabbing <- cursorKindIs ctx pressTrack UiCursorGrabbing-  assert failed grabbing-  let dragOff = pressTrack {inputMousePos = offPos}-  _ <- runFrame ctx dragOff ui-  grabbingOff <- cursorKindIs ctx dragOff UiCursorGrabbing-  assert failed grabbingOff-  let hoverOff = inp0 {inputMousePos = offPos}-  _ <- runFrame ctx hoverOff ui-  isDefault <- cursorKindIs ctx hoverOff UiCursorDefault-  assert failed isDefault+tests :: [Spec]+tests =+  [ pixelSimSpec "slider-cursor" 300 80 (column (withValue 50 (slider' 0 100))) sliderCursor+  , varSimSpec "select-mouse-and-keys" 320 200 1 mouseAndKeysUi selectMouseAndKeys+  , varSimSpec "select-drag-pick" 320 200 0 mouseAndKeysUi selectDragPick+  , varSimSpec "select-owner-gone" 320 200 True ownerGoneUi selectOwnerGone+  , simSpec "select-dropdown-paint" 640 480 (column (withValue 0 (select' lowHigh))) selectDropdownPaint+  , spec "select-keys-after-focus-moves" runSelectKeysAfterFocusMovesTest+  , spec "select-dropdown-clips-rows" runSelectDropdownClipsRowsTest+  , spec "choices-unreached-index" runChoicesUnreachedIndexTest+  , spec "tree-mouse-and-keys" runTreeTest+  , spec "tree-late-items-expanded" runTreeLateItemsExpandedTest+  , spec "radio-groups" runRadioGroupsTest+  , simSpec "sliders-drag-apart" 300 120 (column ((,) <$> twenty <*> twenty)) slidersDragApart+  , spec "slider-bad-values-settle" runSliderBadValuesTest+  , spec "slider-stale-drag" (runStaleDragTest (slider' 0 100) (40, 0))+  , spec "knob-stale-drag" (runStaleDragTest (knob' 0 100) (0, -30))+  ] -runSelectOverlayDamageTest :: Context -> IORef Int -> IO ()-runSelectOverlayDamageTest ctx failed = do-  let ui = column (select' ["Low", "Medium", "High"] 0)-      inp0 = (withInput 320 160) {inputMousePos = V2 20 20}+twenty :: NanoUI (Response, Float)+twenty = withValue 20 (slider' 0 100)++lowHigh :: [T.Text]+lowHigh = ["Low", "Medium", "High"]++-- | Whether a dropdown of 'lowHigh' shows: one of its options drawn on the+-- overlay layer.+selectOpen :: Sim a Bool+selectOpen = do+  inp <- getInput+  any (\(_, t, _, _, _) -> spanLabel t `elem` lowHigh) <$> onContext (`collectOverlayTextSpans` inp)++-- | A press opens the select, and a release on the row the pointer was+-- dragged to picks that row and closes the dropdown.+selectDragPick :: Var Int -> Sim (Response, Int) ()+selectDragPick ref = do+  (resp, _) <- result+  _ <- press (On resp)+  expect "High"+  _ <- moveTo "High" >> moveTo "High"+  _ <- release >> frame+  checkEq 2 =<< readV ref+  check . not =<< selectOpen++-- | A select's open dropdown closes when the select is no longer declared,+-- and Escape then reaches the view instead of staying reserved for it.+ownerGoneUi :: Var Bool -> NanoUI (Maybe Response, Bool)+ownerGoneUi shown = column $ do+  on <- readVar shown+  r <- if on then Just . fst <$> withValue 0 (select' (SA.smallArrayFromList lowHigh)) else pure Nothing+  (r,) <$> takeEscape++selectOwnerGone :: Var Bool -> Sim (Maybe Response, Bool) ()+selectOwnerGone shown = do+  Just resp <- fst <$> result+  _ <- press (On resp) >> frame+  expect "High"+  writeV shown False+  _ <- release >> settle+  expectNot "High"+  check . snd =<< pressKey KeyEscape+  _ <- moveTo (At (V2 10 10)) >> advance 1 >> settle+  check . not =<< wouldRedraw (\i -> i {inputMousePos = V2 20 20})++-- | A slider's track shows the grab cursor, and grabbing while pressed; with+-- the button up off it, the default.+sliderCursor :: Sim (Response, Float) ()+sliderCursor = do+  Rect rx ry rw rh <- respRect . fst <$> result+  checkEq UiCursorGrab =<< cursorAt (Within (sliderTrackBounds rx ry rw rh))+  _ <- press (Within (sliderTrackBounds rx ry rw rh))+  checkEq UiCursorGrabbing =<< pointerCursor+  checkEq UiCursorDefault =<< (release >> cursorAt (At (V2 (rx + rw + 20) (ry + rh + 20))))++-- | A select opens on the press, and a release on the row it was dragged to+-- picks that row. Open, the arrows move the pick and Escape closes it, and a+-- click on its own field closes it and keeps focus. Closed and focused, the+-- arrows step without opening it, Home and Page Up pick the first option, End+-- and Page Down the last, and Space or Enter opens and closes it: the+-- dropdown a key opens shows from the next frame, and one a key closes goes+-- in the same frame. Rows show the pointer cursor, hovered and pressed, and a+-- pick reports one change.+mouseAndKeysUi :: Var Int -> NanoUI (Response, Int)+mouseAndKeysUi ref = column (held ref (select' (SA.smallArrayFromList lowHigh)))++selectMouseAndKeys :: Var Int -> Sim (Response, Int) ()+selectMouseAndKeys ref = do+  (resp, _) <- result+  -- The value lands on the frame after the key.+  let valuesAfter = mapM (\k -> pressKey k >> frame >> readV ref)+  _ <- press (On resp)+  expect "High"+  checkEq UiCursorPointer =<< cursorAt "Low"+  checkEq (0, False) =<< (release >> (,) <$> readV ref <*> selectOpen)+  _ <- click (On resp)+  checkEq [1, 0] =<< valuesAfter [KeyDown, KeyUp]+  let openAfter = mapM (>> selectOpen)+  checkEq [False, True, False] =<< openAfter [pressKey KeyEscape, click (On resp), click (On resp)]+  checkEq (respId resp) =<< focusedId+  checkEq [1, 0, 2, 0, 2, 0] =<< valuesAfter [KeyRight, KeyLeft, KeyEnd, KeyHome, KeyPageDown, KeyPageUp]+  check . not =<< selectOpen+  checkEq [True, False, True, False] =<< openAfter (map ((>> frame) . pressKey) [KeySpace, KeySpace, KeyEnter, KeyEnter])+  _ <- click (On resp)+  checkEq UiCursorPointer =<< cursorAt "High"+  (pressed, _) <- press "High"+  checkEq UiCursorPointer =<< pointerCursor+  rest <- sequence [release, frame, frame, frame]+  checkEq [2, 2, 2, 2] (map snd rest)+  checkEq 1 (length (filter respChanged (pressed : map fst rest)))+  checkEq [False, False, False] (map (respChanged . fst) (drop 1 rest))++-- | An open dropdown's spans carry the colours it paints, the picked row in+-- the accent colour. A hover moving inside it, which the arena does not hold,+-- repaints the dropdown as a clip, not the window.+selectDropdownPaint :: Sim (Response, Int) ()+selectDropdownPaint = do+  theme <- onContext getThemeIO+  (resp, _) <- click . On . fst =<< result+  modifyInput (\i -> i {inputDeltaTime = 1})+  _ <- moveTo (At (V2 600 400))+  inp <- getInput+  overlays <- onContext (`collectOverlayTextSpans` inp)+  let fgOf lbl = [fg | (_, txt, fg, _, _) <- overlays, txt == lbl]+  checkEq [themeAccent theme] (fgOf "Low")+  check (length (fgOf "Medium") == 1 && themeAccent theme `notElem` fgOf "Medium")+  high <- rectOf "High"+  let overHigh i = i {inputMousePos = V2 (v2X (centerOf resp)) (rectY high + 0.5)}+  check =<< wouldRedraw overHigh+  _ <- frameDamage >> frameWith overHigh+  dmg <- frameDamage+  forM_ overlays $ \(_, _, _, _, dropRect) -> check (clipCovers dmg dropRect)++-- | Keys reach an open select only while it has focus: a right-click on a+-- text field closes it, and a field that takes focus by 'holdFocus' keeps+-- the arrows to itself. A modal opened over it closes it too, as the modal+-- hides it, so Escape then reaches the modal.+runSelectKeysAfterFocusMovesTest :: Context -> IORef Int -> IO ()+runSelectKeysAfterFocusMovesTest ctx failed = do+  grabRef <- newIORef False+  dialog <- newVar False+  -- The field above the select, clear of its dropdown.+  let ui = column $ do+        (t, _) <- withValue "text" textInput'+        (s, v) <- withValue 0 (select' lowHigh)+        whenM (liftIO (readIORef grabRef)) (holdFocus (respId t))+        modal dialog "Title" (label "body")+        pure (s, t, v)+      valueAfterDown = (\(_, _, v) -> v) <$> (pressKey KeyDown >> frame)+  runSim ctx failed (withInput 320 300) ui $ do+    (s, t, _) <- result+    check =<< (click (On s) >> selectOpen)+    writeV dialog True+    check . not =<< (frame >> selectOpen)+    _ <- pressKey KeyEscape+    checkEq False =<< readV dialog+    _ <- click (On s) >> rightClick (On t)+    check . not =<< selectOpen+    checkEq 0 =<< valueAfterDown+    _ <- pressKey KeyEscape >> click (On s)+    liftIO (writeIORef grabRef True)+    checkEq (respId t) =<< (frame >> focusedId)+    checkEq 0 =<< valueAfterDown++-- | A select's dropdown is as wide as the select, and an option wider than+-- that is clipped to the dropdown rather than drawn over the page, where+-- closing the dropdown would not repaint it.+runSelectDropdownClipsRowsTest :: Context -> IORef Int -> IO ()+runSelectDropdownClipsRowsTest ctx failed = do+  let long = "A rather long option label"+      ui = column (withValue 0 (selectWith' (fixedW 80) [long, "Short"]))+      inp0 = (withInput 640 480) {inputMousePos = V2 600 400}   (resp, _) <- warmup2 ctx inp0 ui-  let pos = centerOf resp-      open = snd (clickPair inp0 pos)-  _ <- runClick ctx inp0 ui pos-  let idle = open {inputMouseReleased = False, inputDeltaTime = 1}-  _ <- runFrame ctx idle ui-  overlays <- collectOverlayTextSpans ctx idle-  case [rectY r | (r, txt, _, _, _) <- overlays, "High" `T.isInfixOf` txt] of-    (highY : _) -> do-      let overMenu = idle {inputMousePos = V2 (v2X pos) (highY + 0.5)}-      need <- needsRedraw ctx idle overMenu-      assert failed need-      _ <- runFrame ctx overMenu ui-      dmg <- takeDamage ctx-      assertEq failed dmg DamageFull+  let away = (snd (clickPair inp0 (centerOf resp))) {inputButtonsReleased = noButtons}+  _ <- runClick ctx inp0 ui (centerOf resp)+  (_, dd, _) <- runFrame ctx away ui+  overlays <- collectOverlayTextSpans ctx away+  case [(r, dropRect) | (r, txt, _, _, dropRect) <- overlays, txt == long] of+    (r, dropRect) : _ -> do+      assertGt failed (rectX r + rectW r) (rectX dropRect + rectW dropRect)+      let clipOf c = Rect (cmdClipX c) (cmdClipY c) (cmdClipW c) (cmdClipH c)+          overlayCmds = [c | c <- drawCmdElems dd, cmdLayer c == LayerOverlay, cmdIndexCount c > 0]+      assert failed (any ((rectInflate 1 dropRect `covers`) . clipOf) overlayCmds)     [] -> assert failed False -runTreeSelectTest :: Context -> IORef Int -> IO ()-runTreeSelectTest ctx failed = do-  let inp0 = withInput 40 12-      items = [TreeItem "alpha" [], TreeItem "beta" []]-      ui = column (tree' "t" items 0)-  (resp, sel0) <- warmup2 ctx inp0 ui-  assertEq failed sel0 0-  let Rect rx ry _rh rh = respRect resp-      (press, release) = clickPair inp0 (V2 (rx + 1) (ry + rh * 0.75))-  _ <- runFrame ctx press ui-  ((_, sel), _, _, _) <- runFrame ctx release ui-  assertEq failed sel 1+-- | A select, a radio group and a tree given an index their options do not+-- reach show it clamped but leave the caller's index alone, so a choice+-- restored before the options load is still there when they do. Picking the+-- option shown is still a pick, by a click or, on the select, by End, which+-- reports the change.+runChoicesUnreachedIndexTest :: Context -> IORef Int -> IO ()+runChoicesUnreachedIndexTest ctx failed = do+  loaded <- newIORef False+  refs@[selRef, radioRef, treeRef] <- mapM newVar [2, 2, 2]+  let ui = do+        shown <- liftIO (readIORef loaded)+        let opts os = if shown then os else []+        column $ do+          s <- select' (opts lowHigh) selRef+          radio (opts ["One", "Two", "Three"]) radioRef+          tree "t" [TreeItem o [] | o <- opts ["Red", "Green", "Blue"]] treeRef+          pure s+      -- The values, and the marks of the radio's options and the tree's rows.+      state = liftIO ((,) <$> mapM readVarIO refs <*> buttonValues ctx)+  runSim ctx failed (withInput 320 400) ui $ do+    checkEq [2, 2, 2] . fst =<< state+    liftIO (writeIORef loaded True)+    checkEq ([2, 2, 2], [0, 0, 1, 0, 0, 1]) =<< (settle >> state)+    mapM_ (`writeV` 5) refs+    checkEq ([5, 5, 5], [0, 0, 1, 0, 0, 1]) =<< (settle >> state)+    _ <- click "Three" >> click "Blue" >> (click . On =<< result) >> click "High"+    checkEq [2, 2, 2] . fst =<< state+    writeV selRef 5+    focusOn . respId =<< settle+    check . respChanged =<< (pressKey KeyEnd >> frame)+    checkEq 2 =<< readV selRef --- A tree renders expanded, moves its selection with the arrow keys, and--- Enter collapses the selected parent.-runTreeKeyboardTest :: Context -> IORef Int -> IO ()-runTreeKeyboardTest ctx failed = do-  selectedRef <- newIORef 0+-- | A tree draws a clicked row selected on the click's frame, though its rows+-- were added before the click was read. The arrows move the selection, Left+-- goes to the parent, and Enter collapses it.+runTreeTest :: Context -> IORef Int -> IO ()+runTreeTest ctx failed = do+  ref <- newVar 0   let items = SA.smallArrayFromList [TreeItem "root" [TreeItem "child" []], TreeItem "leaf" []]-      ui = column (held selectedRef (tree' "k" items))-      inp0 = withInput 40 12-  _ <- warmup2 ctx inp0 ui-  spans0 <- collectTextSpans ctx-  assert failed (hasText "root" spans0 && hasText "child" spans0 && hasText "leaf" spans0)-  _ <- runFrame ctx (tabInp inp0) ui-  ((_, sel1), _, _, _) <- runFrame ctx (keyInp KeyDown inp0) ui-  assertEq failed sel1 1-  ((_, sel0), _, _, _) <- runFrame ctx (keyInp KeyUp inp0) ui-  assertEq failed sel0 0-  _ <- runFrame ctx (keyInp KeyDown inp0) ui-  ((_, parentSel), _, _, _) <- runFrame ctx (keyInp KeyLeft inp0) ui-  assertEq failed parentSel 0-  _ <- runFrame ctx (keyInp KeyEnter inp0) ui-  _ <- runFrame ctx inp0 ui-  spans <- collectTextSpans ctx-  assert failed (not (hasText "child" spans))-  ((_, afterCollapsed), _, _, _) <- runFrame ctx (keyInp KeyDown inp0) ui-  assertEq failed afterCollapsed 2+      value = readV ref+  runSim ctx failed (withInput 200 120) (column (held ref (tree' "k" items))) $ do+    _ <- click "child"+    checkEq (1, [0, 1, 0]) =<< ((,) <$> value <*> onContext buttonValues)+    -- Tab focuses the first row; the arrows move focus and selection.+    pressTab 1+    checkEq [1, 0, 1, 0] =<< mapM (\k -> pressKey k >> value) [KeyDown, KeyUp, KeyDown, KeyLeft]+    _ <- pressKey KeyEnter >> frame+    expectNot "child"+    checkEq 2 =<< (pressKey KeyDown >> value) --- Open dropdown rows show the pointer cursor on hover and press, and--- respChanged fires on the frame the selection changes and not on later--- frames (regression: it compared the index against the initial one, so it--- stayed set, and Emit.select emitted, every frame after a pick).-runSelectChangeOnceTest :: Context -> IORef Int -> IO ()-runSelectChangeOnceTest ctx failed = do-  indexRef <- newIORef 1-  let inp0 = withInput 320 200-      ui = held indexRef (select' ["Low", "Medium", "High"])-  (resp, _) <- warmup2 ctx inp0 ui-  let (openPress, openRelease) = clickPair inp0 (centerOf resp)-  _ <- runFrame ctx openPress ui-  _ <- runFrame ctx openRelease ui-  overlays <- collectOverlayTextSpans ctx openRelease-  case [rectY r | (r, txt, _, _, _) <- overlays, "Low" `T.isInfixOf` txt] of-    (lowY : _) -> do-      let lowPos = V2 (v2X (centerOf resp)) (lowY + 0.5)-          hover = inp0 {inputMousePos = lowPos}-          (pickPress, pickRelease) = clickPair inp0 lowPos-          frame inp = (\((r, i), _, _, _) -> (respChanged r, i)) <$> runFrame ctx inp ui-      _ <- runFrame ctx hover ui-      hoverKind <- uiCursorKind ctx hover-      assertEq failed hoverKind UiCursorPointer-      pressed <- frame pickPress-      pressKind <- uiCursorKind ctx pickPress-      assertEq failed pressKind UiCursorPointer-      rest <- mapM frame [pickRelease, inp0, inp0, inp0]-      let results = pressed : rest-      assertEq failed (map snd rest) [0, 0, 0, 0]-      assertEq failed (length (filter fst results)) 1-      assertEq failed (map fst (drop 1 rest)) [False, False, False]-    [] -> assert failed False+-- | A tree whose parents arrive after its first frame, empty or holding a+-- placeholder leaf, opens every parent, as one built with them does.+runTreeLateItemsExpandedTest :: Context -> IORef Int -> IO ()+runTreeLateItemsExpandedTest ctx failed = do+  itemsRef <- newIORef []+  let ui = liftIO (readIORef itemsRef) >>= \items -> column (withValue 0 (tree' "late" items))+  runSim ctx failed (withInput 200 120) ui $ do+    forM_ [[TreeItem "Loading" []], [TreeItem "root" [TreeItem "child" []]]] $ \items ->+      liftIO (writeIORef itemsRef items) >> settle+    expect "child" -runSelectDragToSelectTest :: Context -> IORef Int -> IO ()-runSelectDragToSelectTest ctx failed = do-  let inp0 = withInput 320 200-      ui = select' ["Low", "Medium", "High"] 1-  (resp, idx0) <- warmup2 ctx inp0 ui-  assertEq failed idx0 1-  let Rect sx sy sw _ = respRect resp-      btnMid = V2 (sx + sw / 2) (sy + 10)-      press = inp0 {inputMousePos = btnMid, inputMouseDown = True, inputMousePressed = True}-  -- 1. On mousedown, the menu should show up immediately-  _ <- runFrame ctx press ui-  overlaysPress <- collectOverlayTextSpans ctx press-  assert failed (any (\(_, txt, _, _, _) -> "Low" `T.isInfixOf` txt) overlaysPress)-  assert failed (any (\(_, txt, _, _, _) -> "High" `T.isInfixOf` txt) overlaysPress)-  case [rectY r | (r, txt, _, _, _) <- overlaysPress, "Low" `T.isInfixOf` txt] of-    (lowY : _) -> do-      -- 2. Move mouse over an item while still pressed-      let drag = inp0 {inputMousePos = V2 (sx + sw / 2) (lowY + 0.5), inputMouseDown = True}-      _ <- runFrame ctx drag ui-      overlaysDrag <- collectOverlayTextSpans ctx drag-      assert failed (any (\(_, txt, _, _, _) -> "Low" `T.isInfixOf` txt) overlaysDrag)-      kind <- uiCursorKind ctx drag-      assertEq failed kind UiCursorPointer-      -- 3. Mouseup over the item selects it and closes the menu-      let release = drag {inputMouseDown = False, inputMouseReleased = True}-      ((_, idx1), _, _, _) <- runFrame ctx release ui-      assertEq failed idx1 0-      overlaysClosed <- collectOverlayTextSpans ctx release-      assert failed (not (any (\(_, txt, _, _, _) -> "Low" `T.isInfixOf` txt) overlaysClosed))-      spans <- collectTextSpans ctx-      assertSpansHas failed "Low" spans-    _ -> assert failed False+-- | Radio groups side by side keep separate selections, a steady frame asks+-- for nothing, and a click moves a mark on the frame it lands.+runRadioGroupsTest :: Context -> IORef Int -> IO ()+runRadioGroupsTest ctx failed = do+  aRef <- newVar (0 :: Int)+  bRef <- newVar 2+  let ui = column ((,) <$> held aRef (radio' ["x", "y"]) <*> held bRef (radio' ["p", "q", "r"]))+  runSim ctx failed (withInput 200 240) ui $ do+    check . not =<< wantsFrame+    checkEq [1, 0, 0, 0, 1] =<< onContext buttonValues+    _ <- click "q"+    checkEq ([1, 0, 0, 1, 0], [0, 1]) =<< ((,) <$> onContext buttonValues <*> mapM readV [aRef, bRef]) -runSelectKeyboardTest :: Context -> IORef Int -> IO ()-runSelectKeyboardTest ctx failed = do-  indexRef <- newIORef 1-  let inp0 = withInput 320 200-      ui = column (held indexRef (select' (SA.smallArrayFromList ["Low", "Medium", "High"])))-  (resp, idx0) <- warmup2 ctx inp0 ui-  assertEq failed idx0 1-  let (openPress, openRelease) = clickPair inp0 (centerOf resp)-  _ <- runFrame ctx openPress ui-  _ <- runFrame ctx openRelease ui-  _ <- runFrame ctx (keyInp KeyDown openRelease) ui-  ((_, idx1), _, _, _) <- runFrame ctx openRelease ui-  assertEq failed idx1 2-  _ <- runFrame ctx (keyInp KeyUp openRelease) ui-  ((_, idx2), _, _, _) <- runFrame ctx openRelease ui-  assertEq failed idx2 1-  _ <- runFrame ctx (openRelease {inputKeys = inputKeysFromList [KeyEscape], inputMouseReleased = False}) ui-  let idleAfterOpen = openRelease {inputMouseReleased = False}-  _ <- runFrame ctx idleAfterOpen ui-  overlays <- collectOverlayTextSpans ctx idleAfterOpen-  assert failed (not (any (\(_, txt, _, _, _) -> txt `elem` ["Low", "Medium", "High"]) overlays))-  _ <- runFrame ctx (tabInp inp0) ui-  focus <- getFocusId ctx-  assert failed (focus /= WidgetId 0)-  _ <- runFrame ctx (keyInp KeyRight inp0) ui-  ((_, idx3), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed idx3 2-  closedOverlays <- collectOverlayTextSpans ctx inp0-  assert failed (not (any (\(_, txt, _, _, _) -> txt `elem` ["Low", "Medium", "High"]) closedOverlays))-  _ <- runFrame ctx (keyInp KeyLeft inp0) ui-  ((_, idx4), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed idx4 1+-- | Sibling sliders keep separate drags: dragging the second leaves the first.+slidersDragApart :: Sim ((Response, Float), (Response, Float)) ()+slidersDragApart = do+  (_, (second, _)) <- result+  let Rect rx ry rw rh = respRect second+      Rect tx ty tw th = sliderTrackBounds rx ry rw rh+  _ <- press (At (V2 (tx + tw * 0.25) (ty + th / 2)))+  ((_, v1), (_, v2)) <- moveTo (At (V2 (tx + tw * 0.75) (ty + th / 2)))+  checkEq 20 v1+  checkLt 50 v2 --- Clicking an open select's own field closes the dropdown and keeps the--- select focused (regression: the closing press cleared focus).-runSelectCloseKeepsFocusTest :: Context -> IORef Int -> IO ()-runSelectCloseKeepsFocusTest ctx failed = do-  indexRef <- newIORef 1-  let inp0 = withInput 320 200-      ui = column (held indexRef (select' (SA.smallArrayFromList ["Low", "Medium", "High"])))-      listed spans = any (\(_, txt, _, _, _) -> txt == "Low") spans-  (resp, _) <- warmup2 ctx inp0 ui-  let mid = centerOf resp-      openRelease = snd (clickPair inp0 mid)-      closeRelease = snd (clickPair openRelease mid)-  _ <- runClick ctx inp0 ui mid-  assert failed . listed =<< collectOverlayTextSpans ctx openRelease-  _ <- runClick ctx openRelease ui mid-  let idle = closeRelease {inputMouseReleased = False}-  _ <- runFrame ctx idle ui-  assert failed . not . listed =<< collectOverlayTextSpans ctx idle-  focus <- getFocusId ctx-  assertEq failed focus (respId resp)+-- | A slider given a value outside its range shows it clamped, and one given+-- a NaN bound, equal bounds or a reversed range, which keeps a value inside+-- it, settles rather than adopting the value afresh on every frame.+runSliderBadValuesTest :: Context -> IORef Int -> IO ()+runSliderBadValuesTest _ failed = do+  let nan = 0 / 0+      cases = [(0, 1, 1.2, Just 1), (nan, 1, 0.5, Nothing), (0, nan, 0.5, Nothing), (5, 5, 5, Nothing)]+  forM_ (cases ++ [(100, 0, 50, Just 50)]) $+    \(lo, hi, given, shown) -> do+      ctx <- newContext+      runSim ctx failed (withInput 300 80) (column (withValue given (slider' lo hi))) $ do+        (resp, v) <- frame+        again <- wantsFrame+        check (not (respChanged resp) && not again)+        forM_ shown (`checkEq` v)++-- | A drag released while its slider, or its knob (whose drag 'useDrag2DOn'+-- runs), is not built stays over: a later press elsewhere, held while the+-- widget comes back, leaves its value alone. The drag moves the pointer by+-- @(dx, dy)@.+runStaleDragTest :: (Var Float -> NanoUI Response) -> (Float, Float) -> Context -> IORef Int -> IO ()+runStaleDragTest widget (dx, dy) ctx failed = do+  shownRef <- newIORef True+  let built shown = if shown then first Just <$> withValue 50 widget else pure (Nothing, 50)+      ui = column (liftIO (readIORef shownRef) >>= built)+      showing = liftIO . writeIORef shownRef+  runSim ctx failed (withInput 300 200) ui $ do+    Just resp <- fst <$> result+    let V2 x y = centerOf resp+    _ <- press (On resp)+    checkLt 50 . snd =<< moveTo (At (V2 (x + dx) (y + dy)))+    showing False+    _ <- frame >> release >> press (At (V2 200 150))+    showing True+    checkEq 50 . snd =<< moveTo (At (V2 200 100))
+ test/integration/Cases/Shader.hs view
@@ -0,0 +1,276 @@+{-# OPTIONS_GHC -O0 #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Core shader tests: std140 uniform packing, surface shader draw commands,+-- non-GPU fallback, paint-hash invalidation, and Tier 2 effect spans.+module Cases.Shader (tests) where++import Data.Int (Int32)+import Data.Primitive.ByteArray (ByteArray, indexByteArray, sizeofByteArray)+import Data.Primitive.SmallArray (indexSmallArray, sizeofSmallArray)+import Data.Proxy (Proxy (..))+import Data.Vector.Unboxed qualified as U+import Data.Word (Word8)+import GHC.Float (castWord32ToFloat)+import GHC.Generics (Generic)+import NanoUI.Internal.Shader (hashShaderProgram)+import NanoUI.Internal.Uniforms (packUniformBytes)+import Spec++tests :: [Spec]+tests =+  [ spec "shader-uniforms" runUniformsTest+  , spec "shader-surface-fallback" runSurfaceFallbackTest+  , spec "shader-surface-draw" runSurfaceDrawTest+  , spec "shader-damage" runShaderDamageTest+  , spec "shader-effect-span" runEffectSpanTest+  , spec "shader-effect-damage" runEffectDamageTest+  ]++data MixedUniforms = MixedUniforms+  { muSpeed :: !Float+  , muTint :: !V3+  , muPhase :: !Float+  , muBounds :: !Rect+  }+  deriving (Eq, Generic, Show)++instance Uniforms MixedUniforms++data NestedUniforms = NestedUniforms+  { nuTag :: !Int32+  , nuColor :: !Color+  , nuPos :: !V2+  }+  deriving (Eq, Generic, Show)++instance Uniforms NestedUniforms++readF32 :: ByteArray -> Int -> Float+readF32 ba off = castWord32ToFloat (indexByteArray ba (off `div` 4))++readI32 :: ByteArray -> Int -> Int32+readI32 ba off = indexByteArray ba (off `div` 4)++readU8 :: ByteArray -> Int -> Word8+readU8 = indexByteArray++nearF :: Float -> Float -> Bool+nearF a b = abs (a - b) < 1.0e-4++runUniformsTest :: Context -> IORef Int -> IO ()+runUniformsTest _ failed = do+  assertEq failed 0 (uniformSize (Proxy :: Proxy ()))+  assertEq failed 16 (uniformSize (Proxy :: Proxy Float))+  assertEq failed 16 (uniformSize (Proxy :: Proxy V2))+  assertEq failed 16 (uniformSize (Proxy :: Proxy V3))+  assertEq failed 16 (uniformSize (Proxy :: Proxy V4))+  assertEq failed 16 (uniformSize (Proxy :: Proxy Color))+  assertEq failed 16 (uniformSize (Proxy :: Proxy Rect))+  -- (Float, V3): Float at 0, V3 aligned to 16 (size 12), rounded to 32.+  assertEq failed 32 (uniformSize (Proxy :: Proxy (Float, V3)))+  -- (V3, Float): V3 at 0 (size 12), Float fits at 12 (size 4), total 16.+  assertEq failed 16 (uniformSize (Proxy :: Proxy (V3, Float)))++  -- MixedUniforms layout:+  -- muSpeed :: Float @ 0+  -- muTint  :: V3    @ 16 (12 bytes -> ends at 28)+  -- muPhase :: Float @ 28 (4 bytes -> ends at 32)+  -- muBounds:: Rect  @ 32 (16 bytes -> ends at 48)+  let fields = uniformLayout (Proxy :: Proxy MixedUniforms)+  assertEq+    failed+    [ UniformField "muSpeed" GFloat 0+    , UniformField "muTint" GVec3 16+    , UniformField "muPhase" GFloat 28+    , UniformField "muBounds" GVec4 32+    ]+    fields+  assertEq failed 48 (uniformSize (Proxy :: Proxy MixedUniforms))++  ba <- packUniformBytes (MixedUniforms 2.5 (V3 0.25 0.5 0.75) 1.25 (Rect 10 20 30 40))+  assertEq failed 48 (sizeofByteArray ba)+  assert failed (nearF 2.5 (readF32 ba 0))+  -- Padding bytes 4..15 must be zeroed.+  forM_ [4 .. 15] $ \i -> assertEq failed (0 :: Word8) (readU8 ba i)+  assert failed (nearF 0.25 (readF32 ba 16))+  assert failed (nearF 0.5 (readF32 ba 20))+  assert failed (nearF 0.75 (readF32 ba 24))+  assert failed (nearF 1.25 (readF32 ba 28))+  assert failed (nearF 10 (readF32 ba 32))+  assert failed (nearF 20 (readF32 ba 36))+  assert failed (nearF 30 (readF32 ba 40))+  assert failed (nearF 40 (readF32 ba 44))++  -- NestedUniforms: Int32 @ 0, Color (vec4) @ 16, V2 @ 32 -> size 48.+  nba <- packUniformBytes (NestedUniforms 7 (colorRGBA 255 0 128 255) (V2 3 4))+  assertEq failed 48 (sizeofByteArray nba)+  assertEq failed (7 :: Int32) (readI32 nba 0)+  assert failed (nearF 1.0 (readF32 nba 16))+  assert failed (nearF 0.0 (readF32 nba 20))+  assert failed (nearF (128 / 255) (readF32 nba 24))+  assert failed (nearF 1.0 (readF32 nba 28))+  assert failed (nearF 3.0 (readF32 nba 32))+  assert failed (nearF 4.0 (readF32 nba 36))++testSurfaceShader :: Shader 'Surface Float+testSurfaceShader =+  rawShader emptyShaderProgram {spGlsl150 = Just "// test surface\n"}++testColorEffect :: Shader 'ColorEffect Float+testColorEffect =+  rawShader emptyShaderProgram {spGlsl150 = Just "// test color effect\n", spNeedsTex = True}++runSurfaceFallbackTest :: Context -> IORef Int -> IO ()+runSurfaceFallbackTest ctx failed = do+  -- Default capabilities report no shader support.+  (caps, _, _) <- runFrame ctx (withInput 320 200) askShaderCapabilities+  assertEq failed noShaderCapabilities caps++  let fallback = colorRGBA 200 100 50 255+      cfg =+        defaultShaderConfig+          { scLayout = fixedWH 120 60+          , scCornerRadius = 8+          , scFallback = fallback+          }+  (_, dd, _) <- run2Frames ctx (withInput 320 200) (column (shaderConfigured cfg testSurfaceShader 0.5))+  assertEq failed 0 (sizeofSmallArray (drawShaderCalls dd))+  let cmds = U.toList (drawCommands dd)+  assert failed (not (null cmds))+  assert failed (all ((== 0) . cmdShader) cmds)++runSurfaceDrawTest :: Context -> IORef Int -> IO ()+runSurfaceDrawTest ctx failed = do+  setShaderCapabilities ctx (ShaderCapabilities True False)+  setDrawPixelScale ctx 2.0+  let mapped = contramapShader (* 2.0) testSurfaceShader+      fixed = fixUniform 3.5 mapped+      cfg =+        defaultShaderConfig+          { scLayout = fixedWH 100 50+          , scCornerRadius = 6+          }+  (r, dd, _) <- run2Frames ctx (withInput 320 200) (columnWith tight (shaderConfigured' cfg fixed ()))+  requireEq "shader call count" 1 (sizeofSmallArray (drawShaderCalls dd))+  let sc = indexSmallArray (drawShaderCalls dd) 0+      expectedHash = hashShaderProgram (scProgram sc)+  assertEq failed expectedHash (scHash sc)+  assertEq failed (sysUniformBytes + 16) (scUniformLength sc)+  assert failed (scUniformOffset sc + scUniformLength sc <= sizeofByteArray (drawUniformBytes dd))+  let ub = drawUniformBytes dd+      off = scUniformOffset sc+      Rect rx ry rw rh = respRect r+  -- SysUniforms: uRect at +0, uUvRect at +16, uMeta at +32.+  assert failed (nearF rx (readF32 ub off))+  assert failed (nearF ry (readF32 ub (off + 4)))+  assert failed (nearF rw (readF32 ub (off + 8)))+  assert failed (nearF rh (readF32 ub (off + 12)))+  assert failed (nearF 1.0 (readF32 ub (off + 24)))+  assert failed (nearF 1.0 (readF32 ub (off + 28)))+  assert failed (nearF 2.0 (readF32 ub (off + 32)))+  assert failed (nearF 6.0 (readF32 ub (off + 36)))+  -- User uniform: fixed 3.5 mapped through (* 2.0) = 7.0 at +sysUniformBytes.+  assert failed (nearF 7.0 (readF32 ub (off + sysUniformBytes)))+  let shaderCmds = filter ((> 0) . cmdShader) (U.toList (drawCommands dd))+  assertEq failed [1 :: Int32] (map cmdShader shaderCmds)++runShaderDamageTest :: Context -> IORef Int -> IO ()+runShaderDamageTest ctx failed = do+  setShaderCapabilities ctx (ShaderCapabilities True False)+  let ui t =+        columnWith (gap 8) $ do+          label "Header"+          shaderBox (fixedWH 80 40) testSurfaceShader t+      dmgOf t = runFrame ctx (withInput 320 200) (ui t) >> takeDamage ctx+  -- Frame 1: initial full paint.+  _ <- dmgOf 1.0+  -- Frame 2: identical uniform must produce zero damage (idle costs nothing).+  d2 <- dmgOf 1.0+  assert failed (damageIsEmpty d2)+  -- Frame 3: changing uniform must invalidate locally without full repaint.+  d3 <- dmgOf 2.0+  case d3 of+    DamageClip _ -> pure ()+    other -> putStrLn ("expected DamageClip on uniform change, got " ++ show other) >> bump failed+  -- Frame 4: settling at 2.0 must return to empty damage.+  d4 <- dmgOf 2.0+  assert failed (damageIsEmpty d4)++runEffectSpanTest :: Context -> IORef Int -> IO ()+runEffectSpanTest ctx failed = do+  let ui =+        columnWith (gap 8) $ do+          box (fixedWH 40 20) (colorRGBA 255 0 0 255)+          (innerVal, effResp) <- withShaderWith' (padAll 4) testColorEffect 0.5 $ do+            box (fixedWH 60 30) (colorRGBA 0 255 0 255)+            pure (42 :: Int)+          (inner2, effResp2) <- withShader' testColorEffect 0.5 $ do+            box (fixedWH 40 20) (colorRGBA 0 0 255 255)+            pure ("ok" :: String)+          pure (innerVal, effResp, inner2, effResp2)++  -- Without capNodeEffects, no effect spans are emitted and children draw directly,+  -- while withShader'/withShaderWith' still return the inner value and container Response.+  setShaderCapabilities ctx (ShaderCapabilities True False)+  ((v1, r1, v2, r2), ddOff, _) <- run2Frames ctx (withInput 320 200) ui+  assertEq failed (42, "ok") (v1, v2)+  assert failed (respId r1 /= WidgetId 0 && respId r2 /= WidgetId 0)+  assertEq failed (68, 38) (rectW (respRect r1), rectH (respRect r1))+  assertEq failed (40, 20) (rectW (respRect r2), rectH (respRect r2))+  assertEq failed 0 (sizeofSmallArray (drawEffectSpans ddOff))++  -- With capNodeEffects, two EffectSpans bracket the wrapped subtrees without+  -- merging commands from the sibling box before them.+  setShaderCapabilities ctx (ShaderCapabilities True True)+  ((_, r1On, _, r2On), ddOn, _) <- run2Frames ctx (withInput 320 200) ui+  assertEq failed (68, 38) (rectW (respRect r1On), rectH (respRect r1On))+  assertEq failed (40, 20) (rectW (respRect r2On), rectH (respRect r2On))+  requireEq "effect span count" 2 (sizeofSmallArray (drawEffectSpans ddOn))+  let es = indexSmallArray (drawEffectSpans ddOn) 0+  assertGt failed (esCmdEnd es) (esCmdStart es)+  assertEq failed 1 (sizeofSmallArray (esPasses es))+  assert failed (length (U.toList (drawCommands ddOn)) >= 3)++runEffectDamageTest :: Context -> IORef Int -> IO ()+runEffectDamageTest ctx failed = do+  setShaderCapabilities ctx (ShaderCapabilities True True)+  let blurProg =+        emptyShaderProgram+          { spGlsl150 = Just "#version 150\nout vec4 fragColor;\nvoid main(){ fragColor = vec4(1.0); }\n"+          , spNeedsTex = True+          }+      marginEffect :: Shader 'LayerEffect Float+      marginEffect = rawLayerShader (\m -> V2 m m) blurProg+      ui showEff col =+        columnWith (padAll 40 . tight) $+          if showEff+            then withShader marginEffect 12.0 (box (fixedWH 40 30) col)+            else box (fixedWH 40 30) col+      red = colorRGBA 220 30 30 255+      green = colorRGBA 30 220 30 255+      step showEff col = runFrame ctx (withInput 320 200) (ui showEff col) >> takeDamage ctx+  _ <- step True red+  -- Identical subtree + uniform: zero damage.+  dIdle <- step True red+  assert failed (damageIsEmpty dIdle)+  -- Child change inside margin effect: damage rect expands by (12, 12) around (40, 40, 40, 30) -> covers [28..92] x [28..82].+  dDirty <- step True green+  case dDirty of+    DamageClip (Rect dx dy dw dh) -> do+      assert failed (dx <= 28.5 && dy <= 28.5)+      assert failed (dx + dw >= 91.5 && dy + dh >= 81.5)+    other -> putStrLn ("expected margin-expanded DamageClip, got " ++ show other) >> bump failed+  -- Settles back to zero damage.+  dSettle <- step True green+  assert failed (damageIsEmpty dSettle)+  -- Unmounting the effect must still damage the previous frame's margin-expanded halo [28..92] x [28..82].+  dUnmount <- step False green+  assert failed (not (damageIsEmpty dUnmount))+  case dUnmount of+    DamageClip (Rect dx dy dw dh) -> do+      assert failed (dx <= 28.5 && dy <= 28.5)+      assert failed (dx + dw >= 91.5 && dy + dh >= 81.5)+    DamageFull -> pure ()
test/integration/Cases/Shaping.hs view
@@ -1,53 +1,71 @@-module Cases.Shaping-  ( runBidiRunsTest-  , runShapedCaretTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Shaping (tests) where -import Data.IORef (IORef)+import Spec import Data.Primitive.PrimArray (primArrayFromList)-import NanoUI import NanoUI.Bidi (BidiRun (..), bidiRuns, needsBidi)-import NanoUI.Testing (Context, caretX, selectionSpans, textIndexAtX)-import NanoUI.Testing.Assert (assert, assertEq) +tests :: [Spec]+tests =+  [ spec "bidi-runs" runBidiRunsTest+  , spec "shaped-carets" runShapedCaretTest+  ]+ -- | Direction runs come out in visual order, with numbers and spaces -- resolved against their neighbours. runBidiRunsTest :: Context -> IORef Int -> IO () runBidiRunsTest _ failed = do   assert failed (not (needsBidi "plain text 123"))-  assertEq failed [] (bidiRuns "")-  assertEq failed [BidiRun 0 5 False] (bidiRuns "hello")-  -- A left-to-right line: the space before Hebrew stays with the Latin.-  assertEq failed [BidiRun 0 4 False, BidiRun 4 7 True] (bidiRuns "abc \x05D0\x05D1\x05D2")-  -- A right-to-left line puts the trailing Latin word on the left.-  assertEq failed [BidiRun 4 7 False, BidiRun 0 4 True] (bidiRuns "\x05D0\x05D1\x05D2 abc")-  -- Numbers in Hebrew read left to right, left of the word before them.-  assertEq failed [BidiRun 5 8 False, BidiRun 0 5 True] (bidiRuns "\x05E9\x05DC\x05D5\x05DD 123")-  -- Latin in the middle of an Arabic line.-  assertEq-    failed-    [BidiRun 7 10 True, BidiRun 4 7 False, BidiRun 0 4 True]-    (bidiRuns "\x0645\x0631\x062D abc\x0628\x0627\x0644")+  forM_ cases $ \(txt, want) -> assertEq failed (txt, want) (txt, bidiRuns txt)+  where+    -- Numbers in Hebrew read left to right, left of the word before them,+    -- and a separator or terminator beside the digits stays with them.+    hebrewThen = [BidiRun 5 8 False, BidiRun 0 5 True]+    cases =+      [ ("", [])+      , ("hello", [BidiRun 0 5 False])+      , -- A left-to-right line: the space before Hebrew stays with the Latin.+        ("abc \x05D0\x05D1\x05D2", [BidiRun 0 4 False, BidiRun 4 7 True])+      , -- A right-to-left line puts the trailing Latin word on the left.+        ("\x05D0\x05D1\x05D2 abc", [BidiRun 4 7 False, BidiRun 0 4 True])+      , ("\x05E9\x05DC\x05D5\x05DD 123", hebrewThen)+      , ("\x05E9\x05DC\x05D5\x05DD 1.5", hebrewThen)+      , ("\x05E9\x05DC\x05D5\x05DD 50%", hebrewThen)+      , -- A byte order mark does not turn a line right to left.+        ("\xFEFF# Title.", [BidiRun 0 9 False])+      , ("\x0645\x0631\x062D abc\x0628\x0627\x0644", [BidiRun 7 10 True, BidiRun 4 7 False, BidiRun 0 4 True])+      ]  -- | Carets, hit testing and selection spans follow a host's shaped layout,--- including right-to-left carets that decrease.+-- including right-to-left carets that decrease. A click lands between+-- user-perceived characters, on whichever side is nearer, never inside a+-- flag or between a letter and its accent. Without shaping, a font taken as+-- monospace places carets and finds them by whole advances alike. runShapedCaretTest :: Context -> IORef Int -> IO () runShapedCaretTest _ failed = do   let rtl = "\x05D0\x05D1\x05D2"       mixed = "ab\x05D0\x05D1"+      flag = "\x1F1EC\x1F1E7"+      accented = "ae\x0301\&b"       shape t         | t == rtl = Just (ShapedText 30 30 (primArrayFromList [30, 20, 10, 0]))         | t == mixed = Just (ShapedText 40 40 (primArrayFromList [0, 10, 40, 30, 20]))+        -- The flag is one glyph, which its two characters share.+        | t == flag = Just (ShapedText 16 16 (primArrayFromList [0, 8, 16]))         | otherwise = Nothing       fm = (monospaceMetrics 16) {fmShape = shape}-  assertEq failed 30 (caretX fm rtl 0)-  assertEq failed 0 (caretX fm rtl 3)-  assertEq failed 0 (caretX fm rtl 99)-  assertEq failed 2 (textIndexAtX fm rtl 12)-  assertEq failed 0 (textIndexAtX fm rtl 100)-  assertEq failed [(10, 30)] (selectionSpans fm rtl 0 2)-  assertEq failed [] (selectionSpans fm rtl 2 2)+      -- ' ', 'x' and 'M' share an advance, so the font is taken as monospace.+      unshaped = (monospaceMetrics 10) {fmAdvance = \c -> if c == 'i' then 4 else 10}+  assertEq failed [30, 0, 0, 20] [caretX fm rtl 0, caretX fm rtl 3, caretX fm rtl 99, caretX unshaped "iiii" 2]+  assertEq+    failed+    [2, 0, 3, 2, 0, 1, 3, 4, 2]+    -- Unshaped, the accent takes an advance of its own, as 'lineWidth'+    -- measures it.+    [ textIndexAtX fm rtl 12, textIndexAtX fm rtl 100, textIndexAtX fm mixed 29, textIndexAtX fm flag 10+    , textIndexAtX fm flag 6, textIndexAtX unshaped accented 17, textIndexAtX unshaped accented 23+    , textIndexAtX unshaped accented 37, textIndexAtX unshaped "iiii" 20+    ]   -- Selecting the Hebrew of a mixed line covers its run, not the Latin.-  assertEq failed [(20, 40)] (selectionSpans fm mixed 2 4)-  assertEq failed [(0, 10)] (selectionSpans fm mixed 0 1)-  assertEq failed 3 (textIndexAtX fm mixed 29)+  assertEq failed [[(10, 30)], [], [(20, 40)], [(0, 10)]] $+    [selectionSpans fm rtl 0 2, selectionSpans fm rtl 2 2, selectionSpans fm mixed 2 4, selectionSpans fm mixed 0 1]
+ test/integration/Cases/Shortcut.hs view
@@ -0,0 +1,341 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Shortcut (tests) where++import Spec+import Data.Either (isRight)+import Data.Foldable (toList)+import Data.Text qualified as T+import NanoUI.Internal.Input (isHardQuitInput, takeFrame)+import NanoUI.Shortcut+import System.Info (os)++tests :: [Spec]+tests =+  [ spec "shortcut-parse-label" runShortcutParseTest+  , spec "shortcut-exact-modifiers" runShortcutExactModifiersTest+  , spec "shortcut-once-per-press" runShortcutOncePerPressTest+  , spec "shortcut-modal" runShortcutModalTest+  , spec "shortcut-focused-field" runShortcutFocusedFieldTest+  , spec "shortcut-focused-control" runShortcutFocusedControlTest+  , spec "shortcut-escape-tab" runShortcutEscapeTabTest+  , spec "shortcut-menu-item" runShortcutMenuItemTest+  , spec "key-release-held" runKeyReleaseTest+  , spec "key-listeners-focus" runKeyListenersFocusTest+  , spec "key-repeats" runKeyRepeatsTest+  , spec "key-repeats-widgets" runKeyRepeatsWidgetsTest+  , spec "shortcut-disabled-focus" runShortcutDisabledFocusTest+  , spec "shortcut-precise-claims" runPreciseClaimsTest+  ]++inp0 :: Input+inp0 = withInput 400 300++runShortcutDisabledFocusTest :: Context -> IORef Int -> IO ()+runShortcutDisabledFocusTest ctx failed = do+  let ui disabled = do+        before <- keyPressed KeyDelete+        (field, _) <- disabledWhen disabled (withValue "value" textInput')+        after <- shortcut (ctrl <> key 'a')+        pure (field, before, after)+  (field, _, _) <- warmup2 ctx inp0 (ui False)+  setFocus ctx (respId field)+  (_, _, after) <- evalUi ctx (chordInp (ctrl <> key 'a') inp0) (ui True)+  assertEq failed True after+  _ <- warmup2 ctx inp0 (ui True)+  (_, before, _) <- evalUi ctx (keyInp KeyDelete inp0) (ui True)+  assertEq failed True before++ctrlHeld :: Modifiers+ctrlHeld = noModifiers {modCtrl = True}++runPreciseClaimsTest :: Context -> IORef Int -> IO ()+runPreciseClaimsTest ctx failed = do+  let ui claim chord = do+        (r, _) <- customWidget defaultCustomWidgetSpec {widgetFocusable = True, widgetKeys = claim}+        global <- shortcut chord+        local <- focusedKeyPressed (respId r) (maybe KeyEscape id (shortcutKey chord))+        pure (r, global, local)+      check claim chord expected = do+        (r, _, _) <- warmup2 ctx inp0 (ui claim chord)+        setFocus ctx (respId r)+        (_, global, local) <- evalUi ctx (chordInp chord inp0) (ui claim chord)+        assertEq failed expected global+        assertEq failed True local+      exact = KeysOnly [ctrl <> key 'k', key KeyDelete]+  check exact (ctrl <> key 'k') False+  check exact (alt <> key 'k') True+  check exact (key 'k') True+  check exact (key KeyDelete) False+  check KeysAll (ctrl <> key 'k') False+  check KeysNone (ctrl <> key 'k') True+  check KeysReadOnly (cmdOrCtrl <> key 'c') False+  check KeysReadOnly (key KeyDelete) True++-- | Build the view @mk note@ and a frame runner returning what @note@+-- recorded that frame, newest first.+noting :: Context -> ((T.Text -> NanoUI ()) -> NanoUI a) -> IO (NanoUI a, Input -> IO [T.Text])+noting ctx mk = do+  fired <- newIORef []+  let ui = mk (\c -> liftIO (modifyIORef' fired (c :)))+  pure (ui, \i -> writeIORef fired [] >> runFrame ctx i ui >> readIORef fired)++binds :: (T.Text -> NanoUI ()) -> [Shortcut] -> NanoUI ()+binds note = mapM_ (\c -> whenM (shortcut c) (note (shortcutLabel c)))++-- | Press each chord in its own frame and expect only it to fire, or nothing.+fires :: IORef Int -> (Input -> IO [T.Text]) -> Bool -> [Shortcut] -> IO ()+fires failed press yes = mapM_ (\c -> let l = shortcutLabel c in assertEq failed (l, [l | yes]) . (l,) =<< press (chordInp c inp0))++-- | Parsed chords equal the '<>'-built ones for every key and modifier, and+-- labels match what a menu shows.+runShortcutParseTest :: Context -> IORef Int -> IO ()+runShortcutParseTest _ failed = do+  forM_+    [ ("C-s", ctrl <> key 's'), ("C-S-P", ctrl <> shift <> key 'P'), ("A-<Enter>", alt <> key KeyEnter)+    , ("<F5>", key (KeyF 5)), ("<F24>", key (KeyF 24)), ("<PageDown>", key KeyPageDown)+    , ("s-k", super <> key 'k'), ("M-s", cmdOrCtrl <> key 's')+    , ("C-+", ctrl <> key '+'), ("C-S-+", ctrl <> shift <> key '+'), ("C--", ctrl <> key '-'), ("-", key '-')+    , ("<", key '<'), ("C-<", ctrl <> key '<'), ("<Escape>", key KeyEscape), ("C-=", ctrl <> key '=')+    ]+    $ \(txt, sc) -> assertEq failed (txt, Right sc) (txt, parseShortcut txt)+  -- The last key wins and modifiers accumulate; a chord without a key never fires.+  assertEq failed (shift <> ctrl <> key 'b') (ctrl <> key 'a' <> shift <> key 'b')+  -- The space bar is a named key, whichever way the chord names it.+  assertEq failed (ctrl <> key KeySpace) (ctrl <> key ' ')+  assertEq failed (Right (ctrl <> key KeySpace)) (parseShortcut "C- ")+  assertEq failed "Ctrl+Shift" (shortcutLabel (ctrl <> shift))+  assertEq failed [] (filter (isRight . parseShortcut) ["", "C-", "C-S-", "X-p", "<F25>", "<F0>", "C-<Bogus>", "ab", "<Enter"])+  -- Round-trip every key under every modifier combination.+  let keys = [KeyBackspace, KeyDelete, KeyEnter, KeyEscape, KeyTab, KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, KeyPageUp, KeyPageDown, KeyInsert, KeySpace, KeyPrintScreen, KeyPause, KeyCapsLock, KeyNumLock, KeyScrollLock, KeyMenu] ++ map KeyF [1 .. 24] ++ map KeyChar "a1=+-<>,."+      chordText (Shortcut k m) = T.concat ([p | (True, p) <- zip [modCtrl m, modShift m, modAlt m, modSuper m] ["C-", "S-", "A-", "s-"]] ++ foldMap (pure . keyText) k)+      keyText = \case+        KeyChar ch -> T.singleton ch+        k -> "<" <> keyLabel k <> ">"+  assertEq failed [] [sc | k <- keys, [sh, ct, a, u] <- replicateM 4 [False, True], let sc = Shortcut (Just k) (Modifiers sh ct a u), parseShortcut (chordText sc) /= Right sc]+  forM_ [("S-C-p", "Ctrl+Shift+P"), ("C-+", "Ctrl++"), ("<Escape>", "Escape"), ("<PageDown>", "PageDown"), ("<F11>", "F11")] $ \(txt, lbl) ->+    assertEq failed (Right lbl) (shortcutLabel <$> parseShortcut txt)++-- | A chord needs exactly its modifiers; typed text and releases do not fire it.+runShortcutExactModifiersTest :: Context -> IORef Int -> IO ()+runShortcutExactModifiersTest ctx failed = do+  (ui, press) <- noting ctx $ \note -> column (binds note [ctrl <> key 's', ctrl <> shift <> key 's', key 's'] >> label "view")+  warmup ctx inp0 ui+  fires failed press True [ctrl <> key 's', ctrl <> shift <> key 's', key 's']+  fires failed press False [ctrl <> alt <> key 's', super <> key 's', ctrl <> key 't']+  forM_ [inp0, inp0 {inputChars = "s", inputModifiers = ctrlHeld}, keyUpInp (KeyChar 's') inp0 {inputModifiers = ctrlHeld}] $ \i ->+    assertEq failed [] =<< press i+  assertEq failed [True, False] [shortcutIn (ctrl <> key 's') (chordInp k inp0) | k <- [ctrl <> key 's', ctrl <> shift <> key 's']]++-- | A press fires once: not again in the rerun pass after a hook write, not+-- for a second binding, and not for repeats within the frame.+runShortcutOncePerPressTest :: Context -> IORef Int -> IO ()+runShortcutOncePerPressTest ctx failed = do+  (ui, press) <- noting ctx $ \note -> column $ do+    note "pass"+    nVar <- useVar (0 :: Int)+    n <- readVar nVar+    whenM (shortcut (ctrl <> key 'k')) (note "fired" >> writeVar nVar (n + 1))+    whenM (shortcut (ctrl <> key 'k')) (note "again")+    label (T.pack (show n))+  warmup ctx inp0 ui+  let ctrlK = chordInp (ctrl <> key 'k') inp0+  forM_ [ctrlK, ctrlK {inputKeys = inputKeysFromList [KeyChar 'k', KeyChar 'k']}] $ \i ->+    assertEq failed ["pass", "fired", "pass"] =<< press i+  assertEq failed ["pass"] =<< press inp0+  assertSpansHas failed "2" =<< collectTextSpans ctx++-- | With a modal open only its own shortcuts fire, and raw key queries outside it return 'False'.+runShortcutModalTest :: Context -> IORef Int -> IO ()+runShortcutModalTest ctx failed = do+  openRef <- newIORef True+  (ui, press) <- noting ctx $ \note -> column $ do+    binds note [ctrl <> key 's']+    open <- liftIO (readIORef openRef)+    _ <- modal' (constVar open) "Dialog" (binds note [ctrl <> key 'd'] >> label "Body")+    binds note [ctrl <> key 'e']+    whenM (keyPressed (KeyChar 'e')) (note "raw")+  warmup2 ctx inp0 ui+  fires failed press False [ctrl <> key 's', ctrl <> key 'e']+  fires failed press True [ctrl <> key 'd']+  writeIORef openRef False+  warmup2 ctx inp0 ui+  fires failed press True [ctrl <> key 's']+  assertEq failed ["raw", "Ctrl+E"] =<< press (chordInp (ctrl <> key 'e') inp0)+  fires failed press False [ctrl <> key 'd']++-- | A focused text field keeps its typing and editing keys, even when a+-- shortcut was bound first; other chords still fire.+runShortcutFocusedFieldTest :: Context -> IORef Int -> IO ()+runShortcutFocusedFieldTest ctx failed = do+  textRef <- newVar "hello"+  (ui, press) <- noting ctx $ \note -> column $ do+    binds note [cmdOrCtrl <> key 'a', ctrl <> key 's', key 'j', shift <> key 'j', alt <> key 'j', key KeyEnter, ctrl <> key KeyLeft, key (KeyF 2), ctrl <> key KeySpace]+    held textRef textInput'+  warmupFocused ctx inp0 ui+  fires failed press False [cmdOrCtrl <> key 'a']+  _ <- runFrame ctx (keyInp KeyBackspace inp0) ui+  assertEq failed "" =<< readVarIO textRef+  fires failed press False [key 'j', shift <> key 'j', key KeyEnter, ctrl <> key KeyLeft]+  -- Alt with a letter types on macOS (Option).+  fires failed press True ([ctrl <> key 's', key (KeyF 2), ctrl <> key KeySpace] ++ [alt <> key 'j' | os /= "darwin"])+  setFocus ctx (WidgetId 0)+  fires failed press True [cmdOrCtrl <> key 'a', key 'j', key KeyEnter]++-- | A focused button keeps Enter and Space (plain or with Shift), a slider+-- also the arrows, a select Down but not Ctrl+Down, and a text area Enter,+-- Shift+Enter and the vertical arrows. Ctrl+Enter, Alt+Left and similar go+-- to shortcuts instead.+runShortcutFocusedControlTest :: Context -> IORef Int -> IO ()+runShortcutFocusedControlTest _ failed = do+  let passed = [ctrl <> key KeyEnter, key KeyRight, shift <> key KeyRight, alt <> key KeyLeft, key 's']+      chords = key KeyEnter : shift <> key KeyEnter : passed+      -- A frame runner on a fresh view of @widget@ with @bound@ bound, focused.+      focusedOn bound widget = do+        c <- newContext+        (ui, press) <- noting c (\note -> column (binds note bound >> widget note))+        press <$ warmupFocused c inp0 ui+  pressB <- focusedOn chords (\note -> whenM (button "Go") (note "button"))+  forM_ [key KeyEnter, shift <> key KeyEnter] $ \c -> assertEq failed ["button"] =<< pressB (chordInp c inp0)+  fires failed pressB True passed+  pressS <- focusedOn chords (\_ -> void (withValue 5 (slider 0 10)))+  fires failed pressS False [key KeyEnter, key KeyRight, shift <> key KeyRight]+  fires failed pressS True [ctrl <> key KeyEnter, alt <> key KeyLeft, key 's']+  selRef <- newVar 0+  pressSel <- focusedOn [ctrl <> key KeyDown] (\_ -> void (held selRef (select' ["a", "b", "c"])))+  let chosenAfter c = pressSel (chordInp c inp0) >> pressSel inp0 >> readVarIO selRef+  assertEq failed [0, 1] =<< mapM chosenAfter [ctrl <> key KeyDown, key KeyDown]+  areaRef <- newVar "hi"+  let areaKept = [key KeyEnter, shift <> key KeyEnter, key KeyUp]+      areaPassed = [ctrl <> key KeyEnter, alt <> key KeyEnter, ctrl <> key KeyUp, alt <> key KeyDown]+  pressA <- focusedOn (areaKept ++ areaPassed) (\_ -> void (held areaRef textArea'))+  fires failed pressA False areaKept+  fires failed pressA True areaPassed+  assertEq failed 2 . T.count "\n" =<< readVarIO areaRef++-- | An Escape shortcut consumes Escape so the app does not quit, and a Tab+-- shortcut does not move focus.+runShortcutEscapeTabTest :: Context -> IORef Int -> IO ()+runShortcutEscapeTabTest ctx failed = do+  (ui, press) <- noting ctx $ \note -> column $ do+    binds note [key KeyEscape]+    whenM takeEscape (note "take")+    binds note [ctrl <> key KeyTab]+    respId <$> button' "a" <* button' "b"+  a <- warmup2 ctx inp0 ui+  fires failed press True [key KeyEscape]+  assert failed =<< overlayConsumesQuit ctx (keyInp KeyEscape inp0)+  _ <- runFrame ctx (tabInp inp0) ui+  assertEq failed a =<< getFocusId ctx+  fires failed press True [ctrl <> key KeyTab]+  assertEq failed a =<< getFocusId ctx++-- | A menu row binds its chord only while the menu is open and shows its+-- label. A keyless chord shows its modifiers and binds nothing.+runShortcutMenuItemTest :: Context -> IORef Int -> IO ()+runShortcutMenuItemTest ctx failed = do+  (ui, press) <- noting ctx $ \note -> column $ do+    target <- button' "Target"+    _ <- contextMenu target $ do+      whenM (menuItemShortcut "Save" (ctrl <> key 's')) (note "Ctrl+S")+      void (menuItemShortcut "Help" (ctrl <> shift))+    pure target+  target <- warmup2 ctx inp0 ui+  fires failed press False [ctrl <> key 's']+  let (down, up) = rightClickPair inp0 (centerOf target)+  mapM_ press [down, up]+  shown <- (++) <$> collectTextSpans ctx <*> collectOverlayTextSpans ctx inp0+  assert failed (hasText "Save  Ctrl+S" shown && hasText "Help  Ctrl+Shift" shown)+  fires failed press False [key 's', ctrl <> key 'd']+  fires failed press True [ctrl <> key 's']++-- | Releases and held keys reach the view; 'clearEphemeral' clears releases+-- like presses. An auto-repeat is held once and is no new press. Losing+-- keyboard focus releases held keys and modifiers. Ctrl+C is a hard quit+-- when it arrives as a key, with Ctrl alone (Ctrl+Alt is AltGr, and+-- Ctrl+Shift+C is a shortcut). A modifier change ends a frame that holds+-- keys or text, so typing x and then pressing Ctrl+S does not read the x as+-- Ctrl+X.+runKeyReleaseTest :: Context -> IORef Int -> IO ()+runKeyReleaseTest ctx failed = do+  let keys = sequence [keyPressed KeySpace, keyReleased KeySpace, keyHeld KeySpace]+      ui = column keys+      down = applyKey KeySpace True inp0+      holding = clearEphemeral down+      up = applyKey KeySpace False holding+      repeated = applyKey KeySpace True holding+  warmup ctx inp0 ui+  forM_ [(down, [True, False, True]), (holding, [False, False, True]), (up, [False, True, False]), (clearEphemeral up, [False, False, False])] $ \(i, seen) ->+    assertEq failed seen =<< evalUi ctx i ui+  assertEq failed ([KeySpace], [], [KeySpace]) (toList (inputKeysHeld holding), toList (inputKeysReleased (clearEphemeral up)), toList (inputKeysHeld repeated))+  assertEq failed [True, False] (map (pressedOnceIn KeySpace) [down, repeated])+  assert failed (inputInteracted holding up)+  assertEq failed [False, False, False] =<< evalUi ctx down (disabledWhen True keys)+  let blurred = releaseAllKeys (clearEphemeral (chordInp (ctrl <> key 's') inp0))+  assertEq failed ([], [KeyChar 's'], noModifiers) (toList (inputKeysHeld blurred), toList (inputKeysReleased blurred), inputModifiers blurred)+  let quits =+        [ctrl <> key 'c', key 'c', ctrl <> shift <> key 'x', ctrl <> alt <> key 'c', ctrl <> shift <> key 'c']+  assertEq failed [True, False, False, False, False] (map (isHardQuitInput . (`chordInp` inp0)) quits)+  let events =+        [ applyKey (KeyChar 'x') True+        , \i -> i {inputChars = inputChars i <> "x"}+        , \i -> i {inputModifiers = ctrlHeld}+        , applyKey (KeyChar 's') True+        ]+      split i = takeFrame (flip ($)) (const False) i+      (typed, _, rest) = split inp0 events+      (chorded, _, rest') = split (clearEphemeral typed) rest+  assertEq failed ("x", [KeyChar 'x'], noModifiers, 2) (inputChars typed, toList (inputKeys typed), inputModifiers typed, length rest)+  assertEq failed ("", [KeyChar 's'], ctrlHeld, 0) (inputChars chorded, toList (inputKeys chorded), inputModifiers chorded, length rest')++-- | Key queries match only keys not claimed by the focused widget: a text+-- field claims Delete, while F2 reaches the view. The raw input still has both.+runKeyListenersFocusTest :: Context -> IORef Int -> IO ()+runKeyListenersFocusTest ctx failed = do+  textRef <- newVar "hello"+  let listen = mapM (\k -> (,) <$> keyPressed k <*> keyHeld k) [KeyDelete, KeyF 2]+      ui = column (listen <* held textRef textInput')+      pressBoth = applyKey (KeyF 2) True (applyKey KeyDelete True inp0)+  warmupFocused ctx inp0 ui+  assertEq failed [(False, False), (True, True)] =<< evalUi ctx pressBoth ui+  assert failed (pressedIn KeyDelete pressBoth && heldIn KeyDelete pressBoth)+  setFocus ctx (WidgetId 0)+  _ <- runFrame ctx inp0 ui+  assertEq failed [(True, True), (True, True)] =<< evalUi ctx pressBoth ui++-- | Auto-repeats are presses but not new ones: 'shortcut' and 'keyPressed'+-- fire on them, 'shortcutOnce' and 'keyPressedOnce' do not. A 'shortcutOnce'+-- that does not fire leaves the repeat to a later 'shortcut'.+runKeyRepeatsTest :: Context -> IORef Int -> IO ()+runKeyRepeatsTest ctx failed = do+  (ui, press) <- noting ctx $ \note -> column $ do+    whenM (shortcut (ctrl <> key 'k')) (note "k")+    whenM (shortcutOnce (ctrl <> key 'j')) (note "j once")+    whenM (shortcut (ctrl <> key 'j')) (note "j")+    whenM (keyPressed (KeyChar 'k')) (note "pressed")+    whenM (keyPressedOnce (KeyChar 'k')) (note "pressed once")+  warmup ctx inp0 ui+  let down c = chordInp (ctrl <> key c) inp0+      repeated c = (applyKey (KeyChar c) True (clearEphemeral (down c)))+  assertEq failed ["pressed once", "pressed", "k"] =<< press (down 'k')+  assertEq failed ["pressed", "k"] =<< press (repeated 'k')+  assertEq failed ["j once"] =<< press (down 'j')+  assertEq failed ["j"] =<< press (repeated 'j')++-- | Held Enter repeats line breaks in a text area but clicks a button and+-- submits a text field only once.+runKeyRepeatsWidgetsTest :: Context -> IORef Int -> IO ()+runKeyRepeatsWidgetsTest ctx failed = do+  areaRef <- newVar ""+  let area = column (held areaRef textArea')+  warmupFocused ctx inp0 area+  mapM_ (\i -> runFrame ctx i area) [keyInp KeyEnter inp0, keyRepeatInp KeyEnter inp0, keyRepeatInp KeyEnter inp0]+  assertEq failed "\n\n\n" =<< readVarIO areaRef+  c <- newContext+  let buttons = column (button' "Go")+  warmupFocused c inp0 buttons+  assertEq failed [True, False] . map respClicked =<< mapM (\i -> evalUi c i buttons) [keyInp KeyEnter inp0, keyRepeatInp KeyEnter inp0]+  f <- newContext+  fieldRef <- newVar "x"+  let field = column (held fieldRef textInput')+  warmupFocused f inp0 field+  assertEq failed [True, False] . map (respSubmitted . fst) =<< mapM (\i -> evalUi f i field) [keyInp KeyEnter inp0, keyRepeatInp KeyEnter inp0]
+ test/integration/Cases/SimFuzz.hs view
@@ -0,0 +1,167 @@+{-# OPTIONS_GHC -O0 #-}+-- | Random input streams over views rich in widgets. After every frame the+-- context is consistent: focus is on nothing or on a widget the frame laid+-- out, and with no button held nothing is active and no pointer drag goes+-- on. After the stream, a view left alone settles: it asks for no frame and+-- no timed wake, as idle costs nothing.+module Cases.SimFuzz (tests) where++import Spec+import Data.Primitive.SmallArray (smallArrayFromList)+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (lookupNodeByWidgetId)+import NanoUI.Testing.Sim qualified as Sim+import Test.QuickCheck (Arbitrary (..), Gen, Property, choose, counterexample, elements, frequency, ioProperty, vectorOf)++tests :: [Spec]+tests =+  [propSpec "sim-fuzz" 11 150 fuzzView]++width, height :: Float+width = 480+height = 360++-- | One input event or pause.+data Ev+  = EMove V2+  | EClick V2+  | ERightClick V2+  | EDoubleClick V2+  | EDrag V2 V2+  | EWheel V2 V2+  | EType T.Text+  | EKey Key+  | EWait Float+  deriving (Show)++genPoint :: Gen V2+genPoint = V2 <$> coord width <*> coord height+  where+    coord m = (\k -> m * fromIntegral k / 64) <$> choose (0 :: Int, 64)++instance Arbitrary Ev where+  arbitrary =+    frequency+      [ (3, EMove <$> genPoint)+      , (5, EClick <$> genPoint)+      , (1, ERightClick <$> genPoint)+      , (1, EDoubleClick <$> genPoint)+      , (2, EDrag <$> genPoint <*> genPoint)+      , (1, EWheel <$> genPoint <*> elements [V2 0 3, V2 0 (-3), V2 2 0, V2 0 1])+      , (2, EType <$> elements ["a", "hello", "12", " ", "\x732B\x72AC", "e\x0301"])+      , (3, EKey <$> elements [KeyTab, KeyEscape, KeyLeft, KeyRight, KeyUp, KeyDown, KeyEnter, KeyBackspace, KeyDelete, KeySpace, KeyHome, KeyEnd, KeyPageDown])+      , (2, EWait <$> elements [0.016, 0.1, 0.5, 2])+      ]++-- | Which view a stream drives, and the stream.+data Events = Events Int [Ev]+  deriving (Show)++instance Arbitrary Events where+  arbitrary = Events <$> choose (0, length views - 1) <*> (choose (5, 40) >>= (`vectorOf` arbitrary))+  shrink (Events v evs) = [Events v (take i evs <> drop (i + 1) evs) | i <- [0 .. length evs - 1]]++type Row = (T.Text, T.Text, T.Text)++-- | The views, each built fresh for a stream: every focusable control in a+-- scroll area; tabs over a table, a tree and a text area; a modal opened by+-- a button beside a menu and a context menu; a select, a combo box and a+-- numeric field over a long list.+views :: [IO (NanoUI ())]+views =+  [ pure . scrollWith (fillW . fillH) . columnWith (gap 4) $ mapM_ (void . snd) everyControl+  , do+      active <- newVar (0 :: Int)+      sortCol <- newVar (SortCol 0 SortAsc)+      sel <- newVar 0+      notes <- newVar (T.unlines (replicate 12 "a line of notes"))+      let cols = headed "Name" (\(a, _, _) -> a) <> headed "Dept" (\(_, b, _) -> b) <> headed "City" (\(_, _, c) -> c)+          rows = [(T.pack ("name " <> show i), "Eng", "Austin") | i <- [1 .. 20 :: Int]] :: [Row]+          items = smallArrayFromList [TreeItem "root" [TreeItem "child" [TreeItem "leaf" []], TreeItem "other" []], TreeItem "second" []]+      pure . columnWith (fillW . fillH) $+        tabs active+          [ tab 0 "Table" (table "people" cols rows sortCol)+          , tab 1 "Tree" (tree "files" items sel)+          , tab 2 "Notes" (textAreaWith (fillW . fixedH 200) notes)+          ]+  , do+      open <- newVar False+      menuOpen <- newVar False+      name <- newVar ("name" :: T.Text)+      pure . columnWith (padAll 10 . gap 6) $ do+        m <- readVar menuOpen+        file <- menuButton' "File" m+        when (respClicked file) (writeVar menuOpen (not m))+        let cfg = (defaultPopupConfig (AnchorRect (respRect file))) {popupPlacement = PlacementBelow}+        (pop, _) <- popup' (constVar m) cfg (void (menuItem "New") >> void (menuItem "Open"))+        when (respClicked pop) (writeVar menuOpen False)+        b <- button' "Open dialog"+        when (respClicked b) (writeVar open True)+        _ <- contextMenu b (void (menuItem "Cut") >> void (menuItem "Copy"))+        void . modal' open "Dialog" $ do+          textInput name+          close <- button "Close"+          when close (writeVar open False)+  , do+      sel <- newVar 0+      combo <- newVar ("a" :: T.Text)+      num <- newVar 3+      pure . scrollWith (fillW . fillH) . columnWith (gap 4) $ do+        selectWith (fixedW 160) ["one", "two", "three", "four"] sel+        comboBox "Pick" ["a", "b", "c", "alpha"] combo+        numericInput num+        forM_ [1 .. 40 :: Int] $ \i -> label (T.pack ("line " <> show i))+  ]++-- | The broken invariants after a frame on @inp@.+frameProblems :: Context -> Input -> IO [String]+frameProblems ctx inp = do+  focus <- getFocusId ctx+  focusNode <- lookupNodeByWidgetId (ctxNodeArena ctx) focus+  active <- readIORef (ctxActiveId ctx)+  dragging <- pointerDragActive ctx+  let up = inputButtonsHeld inp == mempty && inputButtonsPressed inp == mempty+  pure $+    ["focus on " <> show focus <> ", which has no node" | focus /= WidgetId 0, focusNode == Nothing]+      <> ["active " <> show active <> " with no button held" | up, active /= WidgetId 0]+      <> ["a pointer drag with no button held" | up, dragging]++-- | Run a frame, then record what it broke.+checkedFrame :: IORef [String] -> Context -> Input -> NanoUI a -> IO (a, Bool)+checkedFrame found ctx inp view = do+  (a, _, again) <- runFrame ctx inp view+  problems <- frameProblems ctx inp+  unless (null problems) $ modifyIORef' found (<> problems)+  pure (a, again)++runEv :: Ev -> Sim.Sim () ()+runEv = \case+  EMove p -> void (Sim.moveTo (Sim.At p))+  EClick p -> void (Sim.click (Sim.At p))+  ERightClick p -> void (Sim.rightClick (Sim.At p))+  EDoubleClick p -> void (Sim.doubleClick (Sim.At p))+  EDrag p q -> void (Sim.drag (Sim.At p) (Sim.At q) 4)+  EWheel p d -> void (Sim.wheel (Sim.At p) d)+  EType t -> void (Sim.typeText t)+  EKey k -> void (Sim.pressKey k)+  EWait dt -> void (Sim.advance dt)++fuzzView :: Events -> Property+fuzzView (Events which evs) = ioProperty $ do+  view <- views !! which+  ctx <- newContext+  quiet <- newIORef 0+  found <- newIORef []+  let opts = Sim.defaultSimOptions {Sim.simFrameRunner = checkedFrame found}+  idle <- Sim.runSimWith opts ctx quiet (withInput width height) view $ do+    mapM_ runEv evs+    -- Left alone: the pointer off the window, and time past every+    -- animation and delay.+    Sim.modifyInput (\i -> i {inputMousePos = V2 (-10) (-10)})+    replicateM_ 3 (Sim.advance 5)+    _ <- Sim.settle+    (,) <$> Sim.wantsFrame <*> Sim.wakeTime+  problems <- readIORef found+  let settled = ["still wants frames or a wake: " <> show idle | idle /= (False, 0)]+  pure (counterexample (unlines (take 6 (problems <> settled))) (null problems && null settled))
test/integration/Cases/State.hs view
@@ -1,142 +1,335 @@-module Cases.State-  ( runControlledInputsTest-  , runControlledStateTest-  , runHookStateTest-  , runCollectionApiTest-  ) where--import Control.Monad (forM_, when)-import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)-import Data.ByteString qualified as BS-import Data.IntMap.Strict qualified as IM-import Data.Text (Text)-import Data.Sequence qualified as Seq-import Data.Primitive.SmallArray qualified as SA-import NanoUI-import NanoUI.Context (Context (..), getStore, intKey, registerImages, lookupImageUv)-import NanoUI.Store (WidgetStore (..))-import NanoUI.Testing (clearDirty, collectTextSpans, isDirty, runFrame)-import NanoUI.Testing.Assert (assert, assertEq)-import NanoUI.Testing.Harness (keyInp, tabInp, warmup2, withInputOff)+{-# OPTIONS_GHC -O0 #-}+{-# LANGUAGE OverloadedRecordDot #-} -runCollectionApiTest :: Context -> IORef Int -> IO ()-runCollectionApiTest ctx failed = do-  seen <- newIORef []-  _ <- runFrame ctx (withInputOff 300 100) $-    hstack (SA.smallArrayFromList [uiIO (modifyIORef' seen (key :)) | key <- [7, 2, 9 :: Int]])-  assertEq failed [9, 2, 7] =<< readIORef seen-  ((emptySelect, emptyRadio, combo), _, _, _) <- runFrame ctx (withInputOff 300 200) $-    withKey ("collection-options" :: Text) $ column $ do-      selectIndex <- select (SA.emptySmallArray :: SA.SmallArray Text) 5-      radioIndex <- radio (Seq.empty :: Seq.Seq Text) (-1)-      comboValue <- comboBox "Choose" (Seq.fromList ["Alpha", "Beta"]) "Beta"-      pure (selectIndex, radioIndex, comboValue)-  assertEq failed 0 emptySelect-  assertEq failed 0 emptyRadio-  assertEq failed "Beta" combo-  -- A failed image must not prevent later registrations in traversal order.-  ok <- registerImages ctx (Seq.fromList [(ImageId 0, 1, 1, BS.replicate 4 255), (ImageId 42, 1, 1, BS.replicate 4 255)])-  assertEq failed False ok-  registered <- lookupImageUv ctx (ImageId 42)-  assertEq failed True (case registered of Just _ -> True; Nothing -> False)+module Cases.State (tests) where -runControlledStateTest :: Context -> IORef Int -> IO ()-runControlledStateTest ctx failed = do-  callbacks <- newIORef []-  let-    inp = withInputOff 300 200-    ui checked text value = column $ do-      expectedId <- currentId-      (check, checked') <- checkbox' "Controlled" checked-      when (respChanged check) (uiIO (modifyIORef' callbacks (<> [checked'])))-      (field, _) <- textInput' text-      (range, _) <- slider' 0 100 value-      pure (expectedId, check, field, range)-  _ <- runFrame ctx inp (ui True "initial" 25)-  ((expectedId, check, field, range), _, _, _) <--    runFrame ctx inp (ui False "replacement" 75)-  assertEq failed expectedId (respId check)-  store <- getStore ctx-  assertEq failed (Just 0) (IM.lookup (intKey (respId check)) (storeInt store))-  assertEq-    failed-    (Just "replacement")-    (IM.lookup (intKey (respId field)) (storeText store))-  assertEq failed (Just 75) (IM.lookup (intKey (respId range)) (storeFloat store))-  assertEq failed [] =<< readIORef callbacks+import Spec+import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Exception (ErrorCall (..), throwIO, try)+import Data.Text (Text)+import Data.Text qualified as T+import Effectful (Eff, IOE, runEff)+import Effectful.State.Static.Local (State, evalState, get, modify)+import GHC.Clock (getMonotonicTime)+import GHC.Generics (Generic)+import NanoUI.Effectful (Ui, embedNanoUI, runFrameEff, withRunInNanoUI)+import NanoUI.Monad (localInput)+import NanoUI.Shortcut qualified as Shortcut+import NanoUI.Testing.Sim -  -- Keyboard activation notifies the owner, which may decline the change.-  writeIORef (ctxFocusId ctx) (respId check)-  _ <--    runFrame-      ctx-      (keyInp KeyEnter inp)-      (ui False "replacement" 75)-  assertEq failed [True] =<< readIORef callbacks-  _ <- runFrame ctx inp (ui False "replacement" 75)-  settled <- getStore ctx-  assertEq failed (Just 0) (IM.lookup (intKey (respId check)) (storeInt settled))-  assertEq failed [True] =<< readIORef callbacks+tests :: [Spec]+tests =+  [ spec "controlled-inputs" runControlledInputsTest+  , pixelSpec "basic-widgets" runBasicWidgetsTest+  , spec "var-slots" runVarSlotTest+  , spec "var-lifecycle" runVarLifecycleTest+  , spec "var-focus" runVarFocusTest+  , spec "var-shared" runVarSharedTest+  , spec "var-late-writes" runVarLateWritesTest+  , spec "embed-state" runEmbedStateTest+  , spec "host-slot" runHostSlotTest+  , varSimSpec "search-input-debounce" 320 100 "" debounced searchDebounce+  ] --- | Inputs show the value the caller passes: a value the caller changes--- between frames is shown, a user edit the caller passes back is kept, and--- one it ignores is undone on the next frame. 'runControlledStateTest' covers--- a declined checkbox toggle.+-- | Inputs show the caller's value, reporting no change for the caller's+-- own; a user edit is reported and stays only if the caller passes it back. runControlledInputsTest :: Context -> IORef Int -> IO () runControlledInputsTest ctx failed = do-  let-    inp = withInputOff 300 200-    ui (checked, text) = column $ do-      checked' <- checkbox "Opt" checked-      text' <- textInput text-      pure (checked', text')-  _ <- warmup2 ctx inp (ui (False, "one"))+  model <- newIORef (False, "one")+  let inp = withInputOff 300 200+      ui = column $ do+        (checked, text) <- liftIO (readIORef model)+        (cb, checked') <- withValue checked (checkbox' "Opt")+        text' <- snd <$> withValue text textInput+        pure (cb, (respChanged cb, (checked', text')))+  _ <- warmup2 ctx inp ui   forM_     [ -- The caller's new values, with no input.-      (inp, (True, "two"), (True, "two"))+      (inp, (True, "two"), (False, (True, "two")))     , -- Tab focuses the checkbox; Space toggles it and the caller keeps it.-      (tabInp inp, (True, "two"), (True, "two"))-    , (inp {inputChars = " "}, (True, "two"), (False, "two"))-    , (tabInp inp, (False, "two"), (False, "two"))-    , -- Tab moved focus to the field. A kept edit stays.-      (inp {inputChars = "x"}, (False, "two"), (False, "twox"))-    , (inp, (False, "twox"), (False, "twox"))-    , -- An ignored edit is undone on the following frame.-      (inp {inputChars = "y"}, (False, "twox"), (False, "twoxy"))-    , (inp, (False, "twox"), (False, "twox"))+      (tabInp inp, (True, "two"), (False, (True, "two")))+    , ((keyInp KeySpace inp) {inputChars = " "}, (True, "two"), (True, (False, "two")))+    , (tabInp inp, (False, "two"), (False, (False, "two")))+    , -- Tab moved focus to the field. A kept edit stays; an ignored one goes.+      (inp {inputChars = "x"}, (False, "two"), (False, (False, "twox")))+    , (inp, (False, "twox"), (False, (False, "twox")))+    , (inp {inputChars = "y"}, (False, "twox"), (False, (False, "twoxy")))+    , (inp, (False, "twox"), (False, (False, "twox")))+    , -- Back on the checkbox, Enter toggles it, and the caller declines.+      (tabInp inp, (False, "twox"), (False, (False, "twox")))+    , (keyInp KeyEnter inp, (False, "twox"), (True, (True, "twox")))+    , (inp, (False, "twox"), (False, (False, "twox")))     ]-    $ \(input, value, expected) -> do-      (result, _, _, _) <- runFrame ctx input (ui value)-      assertEq failed expected result-      spans <- collectTextSpans ctx-      assert failed (any (\(_, txt, _, _, _) -> txt == snd expected) spans)+    $ \(input, value, want@(_, (checked, text))) -> do+      writeIORef model value+      (cb, got) <- evalUi ctx input ui+      assertEq failed want got+      assertEq failed (Just (if checked then 1 else 0)) =<< widgetValue ctx (respId cb)+      assert failed . any (\(_, t, _, _, _) -> t == text) =<< collectTextSpans ctx -runHookStateTest :: Context -> IORef Int -> IO ()-runHookStateTest ctx failed = do-  let-    inp = withInputOff 300 100-    check :: (Eq a, Show a) => Text -> NanoUI (a, a -> NanoUI ()) -> a -> a -> IO ()-    check key hook initial changed = do-      let-        evaluate = runNanoUI ctx inp (withKey key hook)-      (value, setValue) <- evaluate-      assertEq failed initial value-      clearDirty ctx-      runNanoUI ctx inp (setValue initial)-      assertEq failed False =<< isDirty ctx+-- | Positional Vars of every slot type keep their value, wake only on a+-- change, start over on a value of another type, and ignore widgets that+-- come and go before them. A Var map keeps a row until it is dropped.+runVarSlotTest :: Context -> IORef Int -> IO ()+runVarSlotTest ctx failed = do+  let inp = withInputOff 300 100+      keyed :: Text -> NanoUI a -> IO a+      keyed k = runNanoUI ctx inp . withKey k+      holds :: (Eq a, Show a) => Text -> NanoUI (Var a) -> a -> a -> IO ()+      holds k slot initial changed = do+        let evaluate = keyed k (slot >>= \v -> (v,) <$> readVar v)+        (v, value) <- evaluate+        assertEq failed initial value+        clearDirty ctx+        runNanoUI ctx inp (writeVar v initial)+        assertEq failed False =<< isDirty ctx+        runNanoUI ctx inp (writeVar v changed)+        assertEq failed True =<< isDirty ctx+        assertEq failed changed . snd =<< evaluate+  holds "int" (useVar (0 :: Int)) 0 12+  holds "float" (useVar (0 :: Float)) 0 1.5+  holds "double" (useVar (0 :: Double)) 0 2.5+  holds "text" (useVar ("initial" :: Text)) "initial" "changed"+  holds "flag" (useVar False) False True+  holds "enum" (useEnumVar LT) LT GT+  holds "sort" (useVar (SortCol 0 SortAsc)) (SortCol 0 SortAsc) (SortCol 2 SortDesc)+  let asInt = keyed "slot" (readVar =<< useVar (5 :: Int))+  assertEq failed 5 =<< asInt+  keyed "slot" (useVar (5 :: Int) >>= \v -> writeVar v 9)+  assertEq failed 9 =<< asInt+  assertEq failed "five" =<< keyed "slot" (readVar =<< useVar ("five" :: Text))+  assertEq failed 5 =<< asInt+  keyed "enum" (useEnumVar LT >>= \v -> writeVar v EQ)+  assertEq failed False =<< keyed "enum" (readVar =<< useEnumVar False)+  let view extra = column $ do+        when extra (void (button "extra"))+        n <- useVar (0 :: Int)+        r <- button' "+"+        when (respClicked r) (modifyVar n (+ 1))+        (r,) <$> readVar n+  (r0, _) <- warmup2 ctx inp (view False)+  assertEq failed 1 . snd =<< runClick ctx inp (view False) (centerOf r0)+  assertEq failed 1 . snd =<< warmup2 ctx inp (view True)+  m <- newVarMap+  let row' k = runNanoUI ctx inp (varAt m (k :: Int) (0 :: Int))+  a <- row' 1+  runNanoUI ctx inp (writeVar a 5)+  assertEq failed 5 =<< (readVarIO =<< row' 1)+  assertEq failed 0 =<< (readVarIO =<< row' 2)+  runNanoUI ctx inp (dropVar m 1)+  assertEq failed 0 =<< (readVarIO =<< row' 1)+  runNanoUI ctx inp (writeVar a 6 >> retainVars (/= 2) m)+  assertEq failed 0 =<< (readVarIO =<< row' 2) -      runNanoUI ctx inp (setValue changed)-      assertEq failed True =<< isDirty ctx-      assertEq failed changed . fst =<< evaluate+-- | A key press runs once even when its write reruns the view (the Passes+-- spec counts what that costs). Owned Vars survive hiding and keyed+-- reordering, and independent ones do not share state.+runVarLifecycleTest :: Context -> IORef Int -> IO ()+runVarLifecycleTest ctx failed = do+  left <- newVar (0 :: Int)+  let inp = withInputOff 300 100+      item :: Text -> NanoUI (Var Int)+      item name = withKey name (useVar 0)+      view = do+        label . T.pack . show =<< readVar left+        whenM (shortcut (Shortcut.key 'a')) $ do+          modifyVar left (+ 1)+          modifyVar left (+ 1)+        readVar left+  _ <- warmup2 ctx inp view+  assertEq failed 2 =<< evalUi ctx (keyInp (KeyChar 'a') inp) view+  assert failed . any (\(_, text, _, _, _) -> text == "2") =<< collectTextSpans ctx+  runNanoUI ctx inp (modifyVar left (+ 3) >> writeVar left 0)+  assertEq failed 0 =<< readVarIO left+  (owned, _) <- evalUi ctx inp ((,) <$> item "left" <*> item "right")+  writeVarIO owned 7+  _ <- runFrame ctx inp (item "right")+  (right, left') <- evalUi ctx inp ((,) <$> item "right" <*> item "left")+  assertEq failed (0, 7) =<< ((,) <$> readVarIO right <*> readVarIO left') -      -- Reuse the original setter: comparing against its captured initial-      -- value would incorrectly discard this update back to the initial.-      runNanoUI ctx inp (setValue initial)-      assertEq failed initial . fst =<< evaluate-  check "int" (useInt 0) 0 12-  check "float" (useFloat 0) 0 1.5-  check "text" (useText "initial") "initial" "changed"-  check "flag" (useFlag False) False True-  check "enum" (useEnum LT) LT GT-  check "dynamic" (useState (0 :: Int, False)) (0, False) (12, True)-  check "table-sort" (useTableSort (SortCol 0 SortAsc)) (SortCol 0 SortAsc) (SortCol 2 SortDesc)+data Item = Item {rowKey :: !Int, rowName :: !Text, rowDone :: !Bool}+  deriving (Eq, Show, Generic)++newtype Items = Items {rows :: [Item]}+  deriving (Eq, Show, Generic)++-- | Field focus and element Vars write through to the whole value, an+-- element's Var follows its key when the list is reordered, and a write+-- through a removed element's Var changes nothing, so wakes nothing.+runVarFocusTest :: Context -> IORef Int -> IO ()+runVarFocusTest ctx failed = do+  model <- newVar (Items [Item 1 "one" False, Item 2 "two" False, Item 3 "three" False])+  let inp = withInputOff 400 300+      view = column $ forEachVar rowKey model.rows $ \item -> do+        checkbox "done" item.rowDone+        label =<< readVar item.rowName+  _ <- warmup2 ctx inp view+  runNanoUI ctx inp (modifyVar model.rows reverse)+  _ <- warmup2 ctx inp view+  first : _ <- runNanoUI ctx inp (withElemVars rowKey model.rows (\xs elemVar -> pure (map elemVar xs)))+  runNanoUI ctx inp (writeVar first.rowName "THREE")+  assertEq failed ["THREE", "two", "one"] . map rowName . rows =<< readVarIO model+  runNanoUI ctx inp (modifyVar model.rows (filter ((/= 3) . rowKey)))+  clearDirty ctx+  runNanoUI ctx inp (writeVar first.rowDone True)+  assertEq failed [False, False] . map rowDone . rows =<< readVarIO model+  assertEq failed False =<< isDirty ctx+  pair <- newVar ((1 :: Int), ("a" :: Text))+  runNanoUI ctx inp (writeVar (zoomVar snd (\b (a, _) -> (a, b)) pair) "b")+  assertEq failed (1, "b") =<< readVarIO pair++-- | A Var shown in two contexts: a write in one is not a backwards write in+-- the other, and each repaints what it shows.+runVarSharedTest :: Context -> IORef Int -> IO ()+runVarSharedTest ctx failed = do+  other <- newContext+  shared <- newVar (0 :: Int)+  let inp = withInputOff 300 100+      view = column $ do+        label . T.pack . show =<< readVar shared+        r <- button' "+"+        when (respClicked r) (modifyVar shared (+ 1))+        pure r+  r <- warmup2 ctx inp view+  _ <- warmup2 other inp view+  _ <- runClick ctx inp view (centerOf r)+  assertEq failed 1 =<< readVarIO shared+  _ <- runFrame other inp view+  assert failed . any (\(_, t, _, _, _) -> t == "1") =<< collectTextSpans other++-- | Writes a frame's bookkeeping misses repaint on the next frame: one in a+-- frame an exception cut short (leaving no rerun), and a thread's write+-- landing after the pass read the Var, also beside a write to another part.+-- The label that shows the new value is damaged, not the whole window.+runVarLateWritesTest :: Context -> IORef Int -> IO ()+runVarLateWritesTest ctx failed = do+  v <- newVar (0 :: Int)+  item <- newVar (Item 1 "one" False)+  let inp = withInputOff 300 100+      view = label . T.pack . show =<< readVar v+      failing = readVar v >> writeVar v 1 >> liftIO (throwIO (ErrorCall "view failed") :: IO ())+  _ <- warmup2 ctx inp view+  r <- try @ErrorCall (runFrame ctx inp failing)+  assert failed (either (const True) (const False) r)+  _ <- runFrame ctx inp view+  assertEq failed 1 =<< lastFramePasses ctx+  assert failed . shownOnly =<< takeDamage ctx+  let named = label =<< readVar item.rowName+      -- The thread's write, as if it landed here.+      landing name = liftIO (writeVarIO item.rowName name)+  _ <- warmup2 ctx inp named+  forM_ [landing "uno", landing "ein" >> writeVar item.rowDone True] $ \late -> do+    _ <- runFrame ctx inp (named >> late)+    _ <- runFrame ctx inp named+    assert failed . shownOnly =<< takeDamage ctx++-- | Damage that repaints a label in the top left and not the whole window.+shownOnly :: Damage -> Bool+shownOnly = \case+  DamageClip (Rect x y w h) -> x < 10 && y < 10 && w > 0 && w < 100 && h > 0 && h < 40+  DamageFull -> False++-- | Pointer cursor over a button and a (pressed) checkbox only. A checkbox+-- shows its Var's value before any click stores state, and each click at+-- once. A slider in a filling column spans it to its maximum.+runBasicWidgetsTest :: Context -> IORef Int -> IO ()+runBasicWidgetsTest ctx failed = do+  checked <- newVar True+  level <- newVar 0+  let ui = columnWith fillW ((,,) <$> button' "Click" <*> checkbox' "Opt" checked <*> slider' 0 100 level)+      wantsPointer = liftIO . pointerCursorWanted ctx =<< getInput+      showsChecked cb on = do+        checkEq on =<< readV checked+        checkEq (Just (if on then 1 else 0)) =<< liftIO (widgetValue ctx (respId cb))+  runSim ctx failed (withInput 400 200) ui $ do+    (btn, cb, sl) <- result+    showsChecked cb True+    check =<< (moveTo (On btn) >> wantsPointer)+    check . not =<< (moveTo (At (V2 (-1) (-1))) >> wantsPointer)+    check =<< (moveTo (On cb) >> wantsPointer)+    check =<< (press (On cb) >> wantsPointer)+    _ <- release+    showsChecked cb False+    _ <- frame+    showsChecked cb False+    let Rect cx cy _ _ = respRect cb+    _ <- click (At (V2 (cx + 1) (cy + 0.5)))+    showsChecked cb True+    let Rect sx sy sw sh = respRect sl+        Rect tx ty tw th = sliderTrackBounds sx sy sw sh+    checkGt sw 300+    _ <- press (At (V2 (tx + tw - 2) (ty + th / 2)))+    flip checkGt 90 =<< readV level++-- | An Effectful view embeds NanoUI, and a body run in a NanoUI scope keeps+-- the effect's state and sees that scope's input.+runEmbedStateTest :: Context -> IORef Int -> IO ()+runEmbedStateTest ctx failed = do+  let ui :: Eff '[Ui, State Int, IOE] (Int, Float)+      ui = do+        _ <- embedNanoUI (column (pure ()))+        modify (+ (1 :: Int))+        w <- withRunInNanoUI $ \run -> column $ do+          run (modify (+ (1 :: Int)))+          inp <- askInput+          localInput inp {inputWindowSize = Size 123 45} (run (embedNanoUI windowWidth))+        (,w) <$> get+  ((n, w), _, _) <- runFrameEff (runEff . evalState (0 :: Int)) ctx (withInput 80 80) ui+  assertEq failed (2, 123) (n, w)++-- | Hosts hand the view what the app set, each of its own type, and a compact+-- host hands back the whole value.+runHostSlotTest :: Context -> IORef Int -> IO ()+runHostSlotTest ctx failed = do+  stringHost <- newHost+  intHost <- newHost+  otherHost <- newHost+  compactOwner <- newHost+  let ask :: Host a -> IO (Maybe a)+      ask h = evalUi ctx (withInput 80 80) (column (pure ()) >> askHost h)+  assertEq failed Nothing =<< ask stringHost+  setHost stringHost ("ok" :: String)+  setHost intHost (1 :: Int)+  setHost otherHost ("independent" :: String)+  assertEq failed (Just "ok") =<< ask stringHost+  assertEq failed (Just 1) =<< ask intHost+  assertEq failed (Just "independent") =<< ask otherHost+  _ <- compactHost compactOwner ([0 .. 9999] :: [Int])+  got <- evalUi ctx (withInput 80 80) (column (pure ()) >> askCompact compactOwner)+  assertEq failed (Just (10000, 9999)) ((\xs -> (length xs, last xs)) <$> got)+  shared <- newVar (0 :: Int)+  dones <- replicateM 4 newEmptyMVar+  forM_ dones $ \done -> void . forkIO $ do+    replicateM_ 250 (modifyVarIO shared (+ 1))+    putMVar done ()+  mapM_ takeMVar dones+  assertEq failed 1000 =<< readVarIO shared++-- | A search field on a 20 ms debounce, bound to the Var.+debounced :: Var Text -> NanoUI (Response, Text)+debounced query = column (held query (searchInputConfigured' defaultSearchInputConfig {sicDebounceMs = 20}))++-- | A search field commits caller-set text after one pause (with no edit time+-- it once never did, waking every period), and typing on a wake 20 ms after+-- the last edit.+searchDebounce :: Var Text -> Sim (Response, Text) ()+searchDebounce query = do+  let showing want changed (resp, txt) = checkEq (want, changed) (txt, respChanged resp)+      afterPause us = liftIO (threadDelay us) >> frame+  pressTab 1+  writeV query "recent"+  showing "recent" False =<< frame+  wakeTime >>= \t -> checkGt t 0+  showing "recent" True =<< afterPause 30000+  checkEq 0 =<< wakeTime+  writeV query ""+  _ <- afterPause 30000+  showing "a" False =<< typeText "a"+  before <- liftIO getMonotonicTime+  showing "ab" False =<< typeText "b"+  after <- liftIO getMonotonicTime+  -- The edit is stamped during its frame: the wake is 20 ms past a moment in it.+  wakeTime >>= \t -> check (t >= before + 0.02 && t <= after + 0.022)+  showing "ab" True =<< afterPause 30000+  checkEq 0 =<< wakeTime+  showing "ab" False =<< afterPause 25000
test/integration/Cases/Styling.hs view
@@ -1,138 +1,408 @@-module Cases.Styling-  ( runDisabledPointerTest-  , runDisabledFocusOrderTest-  , runDisabledLookTest-  , runStyledPaintTest-  , runStyledNestingTest-  , runStyledDamageTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Styling (tests) where -import Control.Monad (forM_)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Testing+import Spec+import Data.Bits ((.&.)) import Data.Text (Text)-import NanoUI.Testing.Assert (assert, assertEq)-import NanoUI.Testing.Harness (centerOf, clickPair, drawQuads, held, tabInp, warmup2, warmupDraw, withInputOff)+import Data.Text qualified as T+import NanoUI.Adornment qualified as A+import NanoUI.Internal.Context (Context (..), RecordedOp (..), drawRecordedOps, setDrawRecordOps)+import NanoUI.Internal.Layout.Arena (arenaCount, getNodeRect, getNodeType, getStyleIdx, lookupNodeByWidgetId, nodeFontBits)+import NanoUI.Testing.Sim --- | A pointer press, drag and typing on a disabled widget change nothing and--- give it no focus.-runDisabledPointerTest :: Context -> IORef Int -> IO ()-runDisabledPointerTest _ failed = do-  let inp = withInputOff 400 200-      check :: (Eq a, Show a) => String -> a -> (a -> NanoUI (Response, a)) -> IO ()-      check name initial widget = do-        ctx <- newContext-        ref <- newIORef initial-        let ui = column (disabledWhen True (held ref widget))-        (resp, _) <- warmup2 ctx inp ui-        let V2 cx cy = centerOf resp-            (press, release) = clickPair inp (V2 cx cy)-            dragged = press {inputMousePressed = False, inputMousePos = V2 (cx + 60) cy}-        mapM_ (\i -> runFrame ctx i ui) [press, dragged, release {inputMousePos = V2 (cx + 60) cy}]-        _ <- runFrame ctx inp {inputMousePos = V2 cx cy, inputChars = "x"} ui-        (after, _, _, _) <- runFrame ctx inp ui-        value <- readIORef ref-        focus <- readIORef (ctxFocusId ctx)-        assertEqNamed name value initial-        assert failed (not (respClicked (fst after)) && not (respHovered (fst after)))-        if focus /= respId resp then pure () else putStrLn ("  disabled " <> name <> ": took focus")-        assert failed (focus /= respId resp)-      assertEqNamed :: (Eq b, Show b) => String -> b -> b -> IO ()-      assertEqNamed name a b =-        if a == b then pure () else do-          putStrLn ("  disabled " <> name <> ": " <> show a <> " /= " <> show b)-          assertEq failed a b-  check "button" False (\_ -> (\r -> (r, respClicked r)) <$> button' "Go")-  check "checkbox" False (checkbox' "Check")-  check "toggle" False toggleSwitch'-  check "slider" (50 :: Float) (slider' 0 100)-  check "knob" (50 :: Float) (knob' 0 100)-  check "radio" (0 :: Int) (radio' ["One", "Two"])-  check "select" (0 :: Int) (select' ["One", "Two"])-  check "text input" ("initial" :: Text) textInput'-  check "numeric input" (5 :: Double) numericInput'+tests :: [Spec]+tests =+  [ spec "disabled-pointer" runDisabledPointerTest+  , simSpec "disabled-focus-order" 300 200 focusOrderUi disabledFocusOrder+  , spec "styled-paint" runStyledPaintTest+  , spec "styled-nesting" runStyledNestingTest+  , spec "font-size-label-fit" runFontSizeLabelFitTest+  , spec "border-left" runBorderLeftTest+  , spec "background-moves-shades" runBackgroundMovesShadesTest+  , spec "label-font-flags" runLabelFontFlagsTest+  , spec "checkbox-box-center" runCheckboxBoxCenterTest+  , pixelSpec "font-size-scale-relative" runFontSizeScaleRelativeTest+  , pixelSpec "uniform-control-heights" runUniformControlHeightsTest+  , spec "button-group" runButtonGroupTest+  , pixelSpec "single-line-and-font-inheritance" runSingleLineAndFontInheritanceTest+  ] --- | Tab skips a disabled widget.-runDisabledFocusOrderTest :: Context -> IORef Int -> IO ()-runDisabledFocusOrderTest ctx failed = do-  let inp = withInputOff 300 200-      ui = column $ do-        a <- button' "A"-        _ <- disabledWhen True (button' "B")-        c <- button' "C"-        pure (a, c)-  (a, c) <- warmup2 ctx inp ui-  writeIORef (ctxFocusId ctx) (respId a)-  _ <- runFrame ctx (tabInp inp) ui-  focus <- readIORef (ctxFocusId ctx)-  assertEq failed focus (respId c)+inp :: Input+inp = withInputOff 300 200 --- | A disabled button paints its fill faded toward the window colour.-runDisabledLookTest :: Context -> IORef Int -> IO ()-runDisabledLookTest ctx failed = do-  theme <- getTheme ctx-  let inp = withInputOff 300 200-      enabledBg = styleBg (themeButton theme)+-- | A press, drag or typing on a disabled widget changes nothing and gives no focus;+-- its fill fades toward the page.+runDisabledPointerTest :: Context -> IORef Int -> IO ()+runDisabledPointerTest ctx failed = do+  let untouched :: (Eq a, Show a) => a -> (Var a -> NanoUI Response) -> IO ()+      untouched initial widget = do+        c <- newContext+        ref <- newVar initial+        runSim c failed (withInputOff 400 200) (column (disabledWhen True (widget ref))) $ do+          r <- result+          let p@(V2 x y) = centerOf r+          _ <- drag (At p) (At (V2 (x + 60) y)) 1+          _ <- typeText "x"+          after <- moveTo (At p)+          checkEq initial =<< readV ref+          check (not (respClicked after) && not (respHovered after))+          check . (/= respId r) =<< focusedId+  untouched False (\_ -> button' "Go")+  untouched False (checkbox' "Check")+  untouched False (toggleSwitchWith' id)+  untouched (50 :: Float) (slider' 0 100)+  untouched (50 :: Float) (knobWith' id 36 0 100)+  untouched (0 :: Int) (radio' ["One", "Two"])+  untouched (0 :: Int) (select' ["One", "Two"])+  untouched ("initial" :: Text) textInput'+  untouched (5 :: Double) numericInput'+  theme <- getThemeIO ctx+  let enabledBg = styleBg (themeButton theme)       fadedBg = styleBg (themeButton (disabledTheme theme))-  (_, draw) <- warmupDraw ctx inp (column (disabledWhen True (button "Off")))-  quads <- drawQuads draw-  assert failed (any ((== fadedBg) . snd) quads)-  assert failed (not (any ((== enabledBg) . snd) quads))-  assert failed (fadedBg /= enabledBg)+  quads <- map snd <$> (drawQuads . snd =<< warmupDraw ctx inp (column (disabledWhen True (button "Off"))))+  assert failed (fadedBg /= enabledBg && fadedBg `elem` quads && enabledBg `notElem` quads) --- | A styled scope paints only the widgets inside it with its theme.+focusOrderUi :: NanoUI (Response, Response)+focusOrderUi = column ((,) <$> button' "A" <* disabledWhen True (button' "B") <*> button' "C")++-- | Tab skips a disabled widget.+disabledFocusOrder :: Sim (Response, Response) ()+disabledFocusOrder = do+  (a, c) <- result+  focusOn (respId a)+  pressTab 1+  checkEq (respId c) =<< focusedId++-- | A styled scope paints only its own widgets. Changing only its theme repaints but+-- measures no text (it once dropped the text caches on every change). runStyledPaintTest :: Context -> IORef Int -> IO ()-runStyledPaintTest ctx failed = do-  let inp = withInputOff 300 200+runStyledPaintTest base failed = do+  measured <- newIORef (0 :: Int)+  let ctx = withMeasureText base (\t -> modifyIORef' measured (+ 1) >> pure (8 * fromIntegral (T.length t), 16))+      ui c = column $ do+        label "Some text"+        (,) <$> styled (buttonStyle (background c)) (button' "Red") <*> button' "Plain"       red = colorRGBA 200 30 40 255-      ui = column $ do-        inside <- styled (buttonStyle (background red)) (button' "Red")-        outside <- button' "Plain"-        pure (inside, outside)-  ((inside, outside), draw) <- warmupDraw ctx inp ui+  ((inside, outside), draw) <- warmupDraw ctx inp (ui red)   quads <- drawQuads draw-  let fills r = [c | (q, c) <- quads, rectIntersect q (respRect r) /= Nothing]-  assert failed (red `elem` fills inside)-  assert failed (red `notElem` fills outside)+  assert failed (red `elem` fillsIn (respRect inside) quads && red `notElem` fillsIn (respRect outside) quads)+  writeIORef measured 0+  forM_ [colorRGBA 30 200 60 255, red] $ \c -> do+    (_, recoloured, _) <- runFrame ctx inp (ui c)+    assertEq failed DamageFull =<< takeDamage ctx+    assert failed . elem c . map snd =<< drawQuads recoloured+  assertEq failed 0 =<< readIORef measured --- | Nested scopes modify the theme around them, and 'uiTheme' reads it.+-- | Nested scopes modify the theme around them. runStyledNestingTest :: Context -> IORef Int -> IO () runStyledNestingTest ctx failed = do-  base <- getTheme ctx-  let inp = withInputOff 300 200-      teal = colorRGBA 20 160 150 255-  (outerAccent, innerAccent, innerRadius, afterAccent) <--    warmup2 ctx inp $ column $ do-      (o, (i, r)) <- styled (accentColor teal) $ do-        o <- themeAccent <$> uiTheme-        ir <- styled (buttonStyle (cornerRadius 9)) $ do-          t <- uiTheme-          pure (themeAccent t, styleCornerRadius (themeButton t))-        pure (o, ir)-      a <- themeAccent <$> uiTheme-      pure (o, i, r, a)-  assertEq failed outerAccent teal-  assertEq failed innerAccent teal-  assertEq failed innerRadius 9-  assertEq failed afterAccent (themeAccent base)-  -- A primary button inside a disabled scope is still faded.-  offTheme <- warmup2 ctx inp (column (disabledWhen True (styled primary uiTheme)))-  assertEq failed (styleBg (themeButton offTheme)) (styleBg (themeButton (disabledTheme (primary base))))+  base <- getThemeIO ctx+  let teal = colorRGBA 20 160 150 255+  seen <- warmup2 ctx inp $ column $ do+    (o, (i, r)) <- styled (accentColor teal) $ do+      o <- themeAccent <$> uiTheme+      let accentAndRadius t = (themeAccent t, styleCornerRadius (themeButton t))+      ir <- styled (buttonStyle (cornerRadius 9)) (accentAndRadius <$> uiTheme)+      pure (o, ir)+    (,,,) o i r . themeAccent <$> uiTheme+  assertEq failed (teal, teal, 9, themeAccent base) seen --- | Changing only a scope's theme repaints.-runStyledDamageTest :: Context -> IORef Int -> IO ()-runStyledDamageTest ctx failed = do-  let inp = withInputOff 300 200-      ui c = column (styled (buttonStyle (background c)) (button "B"))-      blue = colorRGBA 30 60 200 255-      green = colorRGBA 30 200 60 255-  _ <- warmup2 ctx inp (ui blue)-  _ <- takeDamage ctx-  forM_ [green, blue] $ \c -> do-    (_, _, draw, _) <- runFrame ctx inp (ui c)-    dmg <- takeDamage ctx-    assertEq failed dmg DamageFull-    quads <- drawQuads draw-    assert failed (any ((== c) . snd) quads)+-- | A widget with its own font size is laid out in that font: with 24 px cells "Big" is+-- 72 px plus two 24 px spaces of padding, not the base font's 60 px.+runFontSizeLabelFitTest :: Context -> IORef Int -> IO ()+runFontSizeLabelFitTest base failed = do+  doc <- either fail pure (parseSvg "<svg viewBox='0 0 24 24'><rect width='24' height='24'/></svg>")+  let ctx = withMonospaceFonts 12 24 base+      sized = fontSize 24+      adornedCfg = defaultButtonConfig {bcLayout = sized, bcAdornments = A.leading (A.iconSized 16 doc)}+      ui = column $ (,,) <$> buttonWith' (fontSize 24) "Big" <*> button' "Big" <*> buttonConfigured' adornedCfg "Big"+  (big, plain, adorned) <- warmup2 ctx (withInputOff 600 300) ui+  labels <- (\ss -> [rectW r | (r, "Big", _, _, _) <- ss, covers (respRect big) r]) <$> collectTextSpans ctx+  assertEq failed ([72], 72 + 2 * 24) (labels, rectW (respRect big))+  assertEq failed (3 * 12 + 2 * 12) (rectW (respRect plain))+  assertEq failed (rectW (respRect big) + 16 + 8) (rectW (respRect adorned))++-- | 'borderLeft' draws one bar down the left edge and no other side.+runBorderLeftTest :: Context -> IORef Int -> IO ()+runBorderLeftTest ctx failed = do+  let col = colorRGBA 220 40 90 255+      ui =+        styled (panelStyle (borderLeft 3 col . cornerRadius 0)) $+          panelWith (fixedWH 120 40 . tight) (snd <$> mouseArea (fillW . fillH) (pure ()))+  (inner, draw) <- warmupDraw ctx inp ui+  quads <- drawQuads draw+  let Rect x y _ h = respRect inner+  assertEq failed [Rect x y 3 h] [q | (q, c) <- quads, c == col]++-- | 'background' moves the hover and press shades with it (a teal field once went back+-- to the theme's well when focused); a shade equal to the old fill follows it.+runBackgroundMovesShadesTest :: Context -> IORef Int -> IO ()+runBackgroundMovesShadesTest ctx failed = do+  base <- getThemeIO ctx+  ref <- newVar ("text" :: Text)+  let teal = colorRGBA 13 148 136 255+      field = background teal (themeInput base)+      ui = styled (inputStyle (background teal)) $ column $ do+        r <- textInput' ref+        r <$ requestFocus (respId r)+  _ <- warmupDraw ctx inp ui+  (r, draw, _) <- runFrame ctx inp ui+  quads <- drawQuads draw+  assert failed (styleActiveBg field /= styleActiveBg (themeInput base))+  assert failed (styleActiveBg field `elem` fillsIn (respRect r) quads)+  let surface = themePanel base+  assertEq failed (styleHoverBg surface == styleBg surface) (styleHoverBg (background teal surface) == teal)++-- | Button, select and checkbox labels take their layout's font flags (once dropped),+-- leaving the widget's own style bits alone.+runLabelFontFlagsTest :: Context -> IORef Int -> IO ()+runLabelFontFlagsTest ctx failed = do+  base <- getThemeIO ctx+  sel <- newVar (0 :: Int)+  on <- newVar False+  let flags = fontBold . fontItalic . fontDanger+      ui = column $ do+        b <- buttonWith' flags "Delete"+        s <- currentId+        selectWith flags ["Option"] sel+        c <- currentId+        checkboxWith flags "Bold box" on+        p <- currentId+        checkbox "Plain box" on+        pure (respId b, s, c, p)+  ((b, s, c, p), _) <- warmupDraw ctx (withInputOff 500 300) ui+  painted <- collectTextSpans ctx+  assertEq failed [[themeDanger base] | _ <- [1 .. 3 :: Int]] $+    map (\t -> [fg | (_, t', fg, _, _) <- painted, t' == t]) ["Delete", "Option", "Bold box"]+  let styleOf wid = lookupNodeByWidgetId (ctxNodeArena ctx) wid >>= maybe (pure 0) (getStyleIdx (ctxNodeArena ctx))+  [bs, ss, cs, ps] <- mapM styleOf [b, s, c, p]+  assertEq failed (replicate 3 WeightBold) $+    map textNodeFontWeight [nodeFontBits NodeButton bs, nodeFontBits NodeSelect ss, nodeFontBits NodeButton cs]+  assertEq failed FontStyleItalic (textNodeFontStyle (nodeFontBits NodeButton bs))+  assertEq failed (ps .&. 0xFFFFFFFF) (cs .&. 0xFFFFFFFF)++-- | A checkbox taller than its box centres its square across the full height,+-- aligned with its single-line label, and sizes its box from its own font size.+runCheckboxBoxCenterTest :: Context -> IORef Int -> IO ()+runCheckboxBoxCenterTest base failed = do+  let ctx = withMonospaceFonts 12 24 base+  setDrawRecordOps ctx True+  on <- newVar True+  let ui = columnWith (tight . gap 4) $ do+        r1 <- checkboxWith' (fixedH 48) "Tall" on+        r2 <- checkboxWith' (fontSize 24 . fixedH 48) "Big" on+        pure (r1, r2)+  ((r1, r2), _) <- warmupDraw ctx (withInputOff 300 200) ui+  theme <- getThemeIO ctx+  ops <- drawRecordedOps ctx+  -- Checked checkbox fills its rounded box in themeAccent.+  let accentBox r = [q | RecordedOp _ _ _ (FillRoundedRect q _ c) <- ops, c == themeAccent theme, covers (respRect r) q]+      centerY (Rect _ y _ h) = y + h / 2+  case (accentBox r1, accentBox r2) of+    (b1 : _, b2 : _) -> do+      assert failed (abs (centerY b1 - centerY (respRect r1)) <= 1.5)+      assert failed (abs (centerY b2 - centerY (respRect r2)) <= 1.5)+      -- 12px font clamps box to 18px; 24px font clamps box to 22px.+      assertGt failed (rectW b2) (rectW b1 + 2)+    other -> assertEq failed (1 :: Int, 1 :: Int) (length (fst other), length (snd other))++-- | 'fontSizeScale' scales relative to the active base font size (not a+-- hardcoded 16), composes multiplicatively, respects an explicit 'fontSize',+-- and scales unsized 'A.icon' adornments on buttons.+runFontSizeScaleRelativeTest :: Context -> IORef Int -> IO ()+runFontSizeScaleRelativeTest base failed = do+  doc <- either fail pure (parseSvg "<svg viewBox='0 0 24 24'><rect width='24' height='24'/></svg>")+  let ctx = withFontMetrics (withFontSize base 12) (monospaceMetrics 12)+      btnPlain = defaultButtonConfig {bcAdornments = A.leading (A.icon doc)}+      btnScaled = defaultButtonConfig {bcLayout = fontSizeScale 1.5, bcAdornments = A.leading (A.icon doc)}+      ui = columnWith (tight . gap 4) $ do+        labelWith (fontSizeScale 1.5) "Scaled"+        labelWith (fontSizeScale 0.5 . fontSizeScale 1.5) "Composed"+        labelWith (fontSizeScale 1.5 . fontSize 20) "Explicit"+        void (buttonConfigured' btnPlain "PlainBtn")+        void (buttonConfigured' btnScaled "ScaledBtn")+  _ <- warmup2 ctx (withInputOff 500 300) ui+  ss <- collectTextSpans ctx+  assertJust failed (spanRect "Scaled" ss) $ \r -> assertEq failed 18 (rectH r)+  assertJust failed (spanRect "Composed" ss) $ \r -> assertEq failed 9 (rectH r)+  assertJust failed (spanRect "Explicit" ss) $ \r -> assertEq failed 30 (rectH r)+  -- The two NodeImage nodes are the leading icons of PlainBtn (12 * 0.9 = 11)+  -- and ScaledBtn (18 * 0.9 = 16).+  let na = ctxNodeArena ctx+  n <- arenaCount na+  iconWs <-+    concat <$> forM [0 .. n - 1] (\i -> getNodeType na i >>= \nt -> if nt == NodeImage then (: []) . rectW <$> getNodeRect na i else pure [])+  assertEq failed [11, 16] iconWs++-- | Single-line controls (button, select, textInput, searchInput, numericInput,+-- and comboBox) share one intrinsic height across proportional and monospace fonts.+runUniformControlHeightsTest :: Context -> IORef Int -> IO ()+runUniformControlHeightsTest ctx failed = do+  sel <- newVar (0 :: Int)+  txt <- newVar ("abc" :: Text)+  qry <- newVar ("" :: Text)+  num <- newVar (42 :: Double)+  cmb <- newVar ("One" :: Text)+  let rowProp = rowWith (tight . gap 8) $ do+        rBtn <- button' "Save"+        rSel <- select' ["One", "Two"] sel+        rTxt <- textInput' txt+        rSrch <- searchInput' "Find" qry+        rNum <- numericInputConfigured' defaultNumericInputConfig {nicLayout = fixedW 90} num+        rCmb <- comboBox' "Pick" ["One", "Two"] cmb+        pure (map (rectH . respRect) [rBtn, rSel, rTxt, rSrch, rNum, rCmb])+      rowMono = rowWith (tight . gap 8) $ do+        rBtn <- buttonWith' fontMono "Save"+        rSel <- selectWith' fontMono ["One", "Two"] sel+        rTxt <- textInputConfigured' defaultTextInputConfig {ticLayout = fontMono . ticLayout defaultTextInputConfig} txt+        rSrch <- searchInputConfigured' defaultSearchInputConfig {sicLayout = fontMono . sicLayout defaultSearchInputConfig} qry+        rNum <- numericInputConfigured' defaultNumericInputConfig {nicLayout = fontMono . fixedW 90} num+        pure (map (rectH . respRect) [rBtn, rSel, rTxt, rSrch, rNum])+  (hsProp, hsMono) <- warmup2 ctx (withInputOff 900 300) $ column ((,) <$> rowProp <*> rowMono)+  case hsProp of+    h0 : rest -> assert failed (h0 > 0 && all (\h -> abs (h - h0) < 0.5) rest)+    [] -> assert failed False+  case hsMono of+    h0 : rest -> assert failed (h0 > 0 && all (\h -> abs (h - h0) < 0.5) rest)+    [] -> assert failed False++-- | 'buttonGroup' joins adjacent buttons with zero gap, outer-only rounded+-- corners, shared 1-pixel internal seams, and automatic neighbour damage when+-- a button is added or removed.+runButtonGroupTest :: Context -> IORef Int -> IO ()+runButtonGroupTest ctx failed = do+  setDrawRecordOps ctx True+  let ui showThird = columnWith (tight . gap 0) $+        buttonGroup $ do+          a <- buttonWith' (fixedW 60) "Left"+          b <- buttonWith' (fixedW 60) "Mid"+          c <- if showThird then Just <$> buttonWith' (fixedW 60) "Right" else pure Nothing+          pure (a, b, c)+  ((a, b, mc), _) <- warmupDraw ctx (withInputOff 400 200) (ui True)+  let ra = respRect a+      rb = respRect b+  assertJust failed mc $ \c -> do+    let rc = respRect c+    -- Adjacent with zero gap.+    assertEq failed (rectX ra + rectW ra) (rectX rb)+    assertEq failed (rectX rb + rectW rb) (rectX rc)+    theme <- getThemeIO ctx+    ops <- drawRecordedOps ctx+    let borderCol = styleBorder (themeButton theme)+        -- Shared internal 1px dividers sit at the left edge of Mid and Right, not Left.+        dividers = [rectX r | RecordedOp _ _ _ (FillRect r col) <- ops, col == borderCol, rectW r <= 1.5, rectH r >= rectH ra - 1]+    assert failed (any (\x -> abs (x - rectX rb) <= 0.5) dividers)+    assert failed (any (\x -> abs (x - rectX rc) <= 0.5) dividers)+    assert failed (not (any (\x -> abs (x - rectX ra) <= 0.5) dividers))+    -- Middle button's clipped rounded rect extends past both left and right edges.+    let midFills = [r | RecordedOp _ clip _ (FillRoundedRect r _ _) <- ops, clip == rb]+    assert failed (any (\r -> rectX r < rectX rb && rectX r + rectW r > rectX rb + rectW rb) midFills)+  -- Removing "Right" repaints "Mid" on a partial-damage frame because its right+  -- corners change from square to rounded.+  writeIORef (ctxPaintFull ctx) False+  _ <- runFrame ctx (withInputOff 400 200) (ui False)+  dmg <- takeDamage ctx+  assert failed (damageCovers dmg rb)+  -- A trailing select with an open dropdown (NodePopup attached to the group)+  -- keeps its outer right corners rounded.+  selV <- newVar (0 :: Int)+  let selUi = columnWith (tight . gap 0) $+        buttonGroup $ do+          _ <- buttonWith' (fixedW 60) "Left"+          selectWith' (fixedW 80) ["One", "Two"] selV+  (selR, _) <- warmupDraw ctx (withInputOff 400 200) selUi+  let sr = respRect selR+      clickPt = centerOf selR+  _ <- runClick ctx (withInput 400 200) selUi clickPt+  _ <- runFrame ctx (withInputOff 400 200) selUi+  opsOpen <- drawRecordedOps ctx+  let selFills = [r | RecordedOp _ clip _ (FillRoundedRect r _ _) <- opsOpen, clip == sr]+  -- Trailing select extends past its left edge (shared seam) but NOT past its right edge (rounded cap).+  assert failed (any (\r -> rectX r < rectX sr && rectX r + rectW r <= rectX sr + rectW sr + 0.5) selFills)++-- | 'singleLine' and ellipsis modes truncate inside a 'column' instead of wrapping;+-- 'withDefaultLayout' font modifiers inherit into all controls and 'fontProportional'+-- restores proportional text; 'colorHex'/'colorHexA' and 'Hashable Color' work;+-- 'calloutTone'/'calloutToneWith'' tint from the active theme's 'Tone'.+runSingleLineAndFontInheritanceTest :: Context -> IORef Int -> IO ()+runSingleLineAndFontInheritanceTest base failed = do+  let ctx = withFontMetrics (withFontSize base 12) (monospaceMetrics 12)+      longTxt = "Alpha Beta Gamma Delta Epsilon Zeta"+  -- In a narrow column, a plain fillW label wraps onto multiple lines, whereas+  -- singleLine / ellipsisEnd / ellipsisMiddle stay single-line and ellipsize.+  let colUi = columnWith (tight . gap 4 . fixedW 100) $ do+        rWrap <- labelWith' fillW longTxt+        rSingle <- labelWith' (fillW . singleLine) longTxt+        rEnd <- labelWith' (fillW . ellipsisEnd) longTxt+        rMid <- labelWith' (fillW . ellipsisMiddle) longTxt+        pure (rWrap, rSingle, rEnd, rMid)+  (rWrap, rSingle, rEnd, rMid) <- warmup2 ctx (withInputOff 400 300) colUi+  assertGt failed (rectH (respRect rWrap)) (rectH (respRect rSingle) * 2)+  assertEq failed (rectH (respRect rSingle)) (rectH (respRect rEnd))+  assertEq failed (rectH (respRect rSingle)) (rectH (respRect rMid))+  ss <- collectTextSpans ctx+  assert failed (any (\(_, t, _, _, _) -> "..." `T.isInfixOf` t) ss)+  -- withDefaultLayout propagates fontSizeScale and fontMono to all built-in controls;+  -- fontProportional resets the font variant inside a fontMono block.+  selV <- newVar (0 :: Int)+  chkV <- newVar False+  txtV <- newVar ("abc" :: Text)+  qryV <- newVar ("qry" :: Text)+  numV <- newVar (12 :: Double)+  tabV <- newVar ("A" :: Text)+  let inheritUi = columnWith (tight . gap 4) $ do+        bPlain <- button' "PlainBtn"+        withDefaultLayout (fontSizeScale 1.5 . fontMono . fontTabular) $ do+          bBig <- button' "BigBtn"+          cBig <- checkbox' "BigChk" chkV+          rBig <- radio' ["BigRad"] selV+          sBig <- select' ["BigSel"] selV+          tBig <- textInput' txtV+          qBig <- searchInput' "Find" qryV+          nBig <- numericInput' numV+          void (tabBar tabV [tab ("A" :: Text) "BigTab" ()])+          lMono <- label' "MonoLbl"+          lReg <- labelWith' (fontRegular . fontProportional) "RegLbl"+          pure (bPlain, bBig, cBig, rBig, sBig, tBig, qBig, nBig, lMono, lReg)+  (bPlain, bBig, _, _, _, _, _, _, lMono, lReg) <- warmup2 ctx (withInputOff 600 400) inheritUi+  assertGt failed (rectH (respRect bBig)) (rectH (respRect bPlain) + 2)+  let na = ctxNodeArena ctx+  Just idxMono <- lookupNodeByWidgetId na (respId lMono)+  Just idxReg <- lookupNodeByWidgetId na (respId lReg)+  Just idxBtn <- lookupNodeByWidgetId na (respId bBig)+  stMono <- getStyleIdx na idxMono+  stReg <- getStyleIdx na idxReg+  stBtn <- getStyleIdx na idxBtn+  assertEq failed FontMono (textNodeFontVariant (nodeFontBits NodeText stMono))+  assertEq failed FontRegular (textNodeFontVariant (nodeFontBits NodeText stReg))+  assertEq failed FontMono (textNodeFontVariant (nodeFontBits NodeButton stBtn))+  ss2 <- collectTextSpans ctx+  forM_ ["BigBtn", "BigChk", "BigRad", "BigSel", "BigTab"] $ \needle ->+    assertJust failed (spanRect needle ss2) $ \r -> assertEq failed 18 (rectH r)+  -- fontProportional overrides inherited fontTabular end-to-end.+  let propFm =+        (monospaceMetrics 12)+          { fmAdvance = \c -> case c of+              ' ' -> 4+              '1' -> 5+              '8' -> 10+              _ -> 7+          }+      tabUi = withDefaultLayout fontTabular $ columnWith (tight . gap 4) $ do+        rTab <- label' "1111"+        rProp <- labelWith' fontProportional "1111"+        pure (rTab, rProp)+  propCtx <- (`withFontMetrics` propFm) <$> newContext+  (rTab, rProp) <- warmup2 propCtx (withInputOff 300 200) tabUi+  assertGt failed (rectW (respRect rTab)) (rectW (respRect rProp) + 10)+  -- colorHex, colorHexA, and Hashable Color+  assertEq failed (colorRGBA 0x1E 0x29 0x3B 0xFF) (colorHex 0x1E293B)+  assertEq failed (colorRGBA 0x1E 0x29 0x3B 0x80) (colorHexA 0x1E293B80)+  assert failed (contentKeyOf [keyPart (colorHex 0x112233)] /= contentKeyOf [keyPart (colorHex 0x112234)])+  -- calloutTone and calloutToneWith'+  let calloutUi = columnWith (tight . gap 4 . fixedW 260) $ do+        calloutTone Warning (label "WarnMsg")+        (_, r) <- calloutToneWith' Danger (fixedH 44) (label "ErrMsg")+        pure r+  rCallout <- warmup2 ctx (withInputOff 400 300) calloutUi+  assertEq failed (260, 44) (rectW (respRect rCallout), rectH (respRect rCallout))
test/integration/Cases/Svg.hs view
@@ -1,74 +1,129 @@-module Cases.Svg-  ( runSvgRasterTest-  , runSvgIconTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Svg (tests) where +import Spec import Data.ByteString qualified as BS-import Data.IORef (IORef)-import NanoUI-import NanoUI.Svg (rasterizeSvg, svgMonochrome)-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq)-import NanoUI.Testing.Harness (drawQuads, warmupDraw, withInputOff)+import Data.Map.Strict qualified as Map+import Data.Maybe (isJust)+import NanoUI.Internal.Context (Context (..), lookupImageSize)+import NanoUI.Svg (rasterizeSvg, rasterizeSvgIn, svgMonochrome) --- | Strokes, even-odd holes and transforms rasterize where they should.+tests :: [Spec]+tests =+  [ spec "svg-raster" runSvgRasterTest+  , spec "svg-raster-cache" runSvgRasterCacheTest+  , spec "svg-fit-content" runSvgFitContentTest+  ]++parsed :: BS.ByteString -> IO Svg+parsed = either fail pure . parseSvg++square :: IO Svg+square = parsed "<svg viewBox='0 0 24 24'><rect x='2' y='2' width='20' height='20'/></svg>"++-- | The ids of the cached rasters, in key order.+svgRasters :: Context -> IO [ImageId]+svgRasters ctx = map (\(iid, _, _) -> iid) . Map.elems <$> readIORef (ctxSvgRasters ctx)++-- | Strokes, even-odd holes, transforms and arcs rasterize where they+-- should, and a document that is not SVG does not parse. runSvgRasterTest :: Context -> IORef Int -> IO () runSvgRasterTest _ failed = do-  let white = colorRGBA 255 255 255 255-      alphaAt w bytes x y = BS.index bytes ((y * w + x) * 4 + 3)-      pixelAt w bytes x y = [BS.index bytes ((y * w + x) * 4 + k) | k <- [0 .. 3]]-      clock =-        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" \-        \stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\-        \<!-- a clock --><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 6v6l4 2\"/></svg>"-  case parseSvg clock of-    Left err -> putStrLn err >> assert failed False-    Right doc -> do-      assert failed (svgMonochrome doc)-      assertEq failed (24, 24) (svgSize doc)-      let px = rasterizeSvg 48 48 white doc-      assertEq failed (48 * 48 * 4) (BS.length px)-      -- On the ring, on the hands, and in the empty face between them.-      assert failed (alphaAt 48 px 24 44 > 200)-      assert failed (alphaAt 48 px 24 18 > 200)-      assertEq failed 0 (alphaAt 48 px 24 36)-      assertEq failed 0 (alphaAt 48 px 1 1)-  let holed =-        "<svg viewBox='0 0 10 10'><path fill-rule='evenodd' fill='#ff0000' d='M0 0h10v10H0z M3 3h4v4H3z'/>\-        \<g transform='translate(5 0) scale(0.5)'><rect width='2' height='2' fill='rgb(0,0,255)'/></g></svg>"-  case parseSvg holed of-    Left err -> putStrLn err >> assert failed False-    Right doc -> do-      assert failed (not (svgMonochrome doc))-      let px = rasterizeSvg 10 10 white doc-      assertEq failed [255, 0, 0, 255] (pixelAt 10 px 1 8)-      assertEq failed 0 (alphaAt 10 px 5 5)-      assertEq failed [0, 0, 255, 255] (pixelAt 10 px 5 0)-  let arcs = "<svg viewBox='0 0 20 20'><path d='M2 10a8 8 0 1 1 16 0a8 8 0 1 1-16 0z'/></svg>"-  case parseSvg arcs of-    Left err -> putStrLn err >> assert failed False-    Right doc -> do-      let px = rasterizeSvg 20 20 white doc-      assertEq failed 255 (alphaAt 20 px 10 10)-      assertEq failed 0 (alphaAt 20 px 1 1)+  let pixelAt w bytes x y = [BS.index bytes ((y * w + x) * 4 + k) | k <- [0 .. 3]]+      alphaAt w bytes x y = last (pixelAt w bytes x y)+  clock <-+    parsed+      "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" \+      \stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\+      \<!-- a clock --><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 6v6l4 2\"/></svg>"+  let px = rasterizeSvg 48 48 colorWhite clock+  assertEq failed (True, (24, 24), 48 * 48 * 4) (svgMonochrome clock, svgSize clock, BS.length px)+  -- On the ring, on the hands, and in the empty face between them.+  assert failed (alphaAt 48 px 24 44 > 200 && alphaAt 48 px 24 18 > 200)+  assertEq failed [0, 0] [alphaAt 48 px 24 36, alphaAt 48 px 1 1]+  holed <-+    parsed+      "<svg viewBox='0 0 10 10'><path fill-rule='evenodd' fill='#ff0000' d='M0 0h10v10H0z M3 3h4v4H3z'/>\+      \<g transform='translate(5 0) scale(0.5)'><rect width='2' height='2' fill='rgb(0,0,255)'/></g></svg>"+  let hpx = rasterizeSvg 10 10 colorWhite holed+  assert failed (not (svgMonochrome holed))+  assertEq failed [[255, 0, 0, 255], [0, 0, 0, 0], [0, 0, 255, 255]] [pixelAt 10 hpx 1 8, pixelAt 10 hpx 5 5, pixelAt 10 hpx 5 0]+  arcs <- parsed "<svg viewBox='0 0 20 20'><path d='M2 10a8 8 0 1 1 16 0a8 8 0 1 1-16 0z'/></svg>"+  let apx = rasterizeSvg 20 20 colorWhite arcs+  assertEq failed [255, 0] [alphaAt 20 apx 10 10, alphaAt 20 apx 1 1]   assert failed (either (const True) (const False) (parseSvg "<nope/>")) --- | An icon draws its raster tinted with the text colour, and later frames--- reuse the raster.-runSvgIconTest :: Context -> IORef Int -> IO ()-runSvgIconTest ctx failed = do-  theme <- getTheme ctx-  doc <- either fail pure (parseSvg "<svg viewBox='0 0 24 24'><rect x='2' y='2' width='20' height='20'/></svg>")+-- | An icon's raster is tinted with the text colour and leased: kept while+-- drawn (or hidden for a frame), replaced once undrawn, remembered when too+-- big for the atlas, and made again once there is room.+runSvgRasterCacheTest :: Context -> IORef Int -> IO ()+runSvgRasterCacheTest ctx failed = do+  doc <- square+  theme <- getThemeIO ctx   let inp = withInputOff 200 120       red = colorRGBA 220 40 40 255-      ui = column $ do-        svgIcon 24 doc-        svgIconWith (fixedWH 16 16 . fontColor red) doc-  (_, draw) <- warmupDraw ctx inp ui-  quads <- drawQuads draw-  let colors = map snd quads-  assert failed (styleFg (themePanel theme) `elem` colors)-  assert failed (red `elem` colors)-  (_, draw2) <- warmupDraw ctx inp ui-  quads2 <- drawQuads draw2-  assertEq failed (length quads) (length quads2)+      icons = column (svgIcon 24 doc >> svgIconWith (fixedWH 16 16 . fontColor red) doc)+      colorsOf c ui = map snd <$> (drawQuads . snd =<< warmupDraw c inp ui)+  colors <- colorsOf ctx icons+  assert failed (styleFg (themePanel theme) `elem` colors && red `elem` colors)+  shown <- svgRasters ctx+  colorsOf ctx icons >>= assertEq failed (length colors) . length+  assertEq failed shown =<< svgRasters ctx+  lease <- newContext+  let registered iid = isJust <$> lookupImageSize lease iid+      showing ui = warmup2 lease inp (column ui)+  showing (svgIcon 16 doc)+  small <- svgRasters lease+  assertEq failed [True] =<< mapM registered small+  showing (pure ()) >> showing (svgIcon 16 doc)+  assertEq failed small =<< svgRasters lease+  showing (pure ()) >> showing (svgIcon 20 doc)+  assertEq failed 1 . length =<< svgRasters lease+  assertEq failed [False] =<< mapM registered small+  showing (svgIconWith (fixedWH 5000 10) doc)+  assert failed . elem (ImageId 0) =<< svgRasters lease+  showing (pure ()) >> showing (svgIcon 16 doc)+  assertEq failed [True] =<< mapM registered =<< svgRasters lease+  -- A shelf as tall as the atlas, then an image across the rest of its+  -- width, leave no room for another.+  full <- newContext+  let fill iid w h = registerImage full (ImageId iid) w h (BS.replicate (w * h * 4) 255)+      ui = column (svgIcon 16 doc)+  assert failed . and =<< sequence [fill 1 1 4094, fill 2 4092 17]+  _ <- warmup2 full inp ui+  assertEq failed [ImageId 0] =<< svgRasters full+  releaseImage full (ImageId 2)+  _ <- warmup2 full inp ui+  retried <- svgRasters full+  assert failed (ImageId 0 `notElem` retried)+  assertEq failed [True] =<< mapM (fmap isJust . lookupImageSize full) retried++-- | Fit and alignment place the document's own 2:1 shape, not a square raster+-- it was first letterboxed into.+runSvgFitContentTest :: Context -> IORef Int -> IO ()+runSvgFitContentTest ctx failed = do+  doc <- parsed "<svg width='20' height='10' viewBox='0 0 20 10'><rect width='20' height='10' fill='#ff0000'/></svg>"+  let alphas bytes = [BS.index bytes (i * 4 + 3) | i <- [0 .. 99]]+      opaque r = all (== 255) (alphas (rasterizeSvgIn 10 10 r colorWhite doc))+  -- Letterboxed by 'rasterizeSvg'; covering and stretched by 'rasterizeSvgIn'.+  assertEq failed 0 (BS.index (rasterizeSvg 10 10 colorWhite doc) 3)+  assert failed (opaque (Rect (-5) 0 20 10) && opaque (Rect 0 0 10 10))+  assert failed (all (== 0) (alphas (rasterizeSvgIn 10 10 (Rect 0 0 0 0) colorWhite doc)))+  let inp = withInputOff 200 200+      icon fit ax = svgIconConfigured defaultImageConfig {icLayout = fixedWH 20 20, icFit = fit, icAlignX = ax} doc+      -- After a frame without an icon, the next raster made takes the place+      -- of the last one. The key holds the content rect in eighths of a+      -- raster pixel.+      contentOf ui = do+        warmup ctx inp (column (pure ()))+        _ <- warmupDraw ctx inp ui+        let pixels v = fromIntegral v / 8 :: Float+        map (\(_, _, _, _, (x, y, w, h)) -> (pixels x, pixels y, pixels w, pixels h)) . Map.keys <$> readIORef (ctxSvgRasters ctx)+  forM_+    [ (icon FitCover AlignCenter, (-10, 0, 40, 20))+    , (icon FitCover AlignStart, (0, 0, 40, 20))+    , (icon FitFill AlignCenter, (0, 0, 20, 20))+    , (icon FitContain AlignCenter, (0, 5, 20, 10))+    , (svgIconWith (fixedWH 20 20) doc, (0, 5, 20, 10))+    ]+    $ \(ui, want) -> assertEq failed [want] =<< contentOf ui
test/integration/Cases/Table.hs view
@@ -1,718 +1,739 @@-module Cases.Table-  ( runPageWheelAboveTableTest-  , runTableCellPadTest-  , runTableColResizeDemoReproTest-  , runTableFillWidthTest-  , runTableFirstColWidthTest-  , runTableHBarReachTest-  , runTableReorderTest-  , runTableResizeOverflowTest-  , runTableScrollRevealTest-  , runTableSharedScrollMetricsTest-  , runTableSortTest-  , runTableWrapRowStretchTest-  ) where--import Control.Monad (forM, forM_, replicateM_, void, (<=<))-import Data.Bits ((.&.))-import Data.IORef (IORef)-import Data.IntMap.Strict qualified as IM-import Data.List (sortBy, sortOn, tails)-import Data.Maybe (isJust, listToMaybe)-import Data.Text (Text)-import Data.Text qualified as T-import Data.Primitive.SmallArray qualified as SA-import NanoUI-import NanoUI.Context (ctxNodeArena)-import NanoUI.Layout.Arena-  ( DirTag (..)-  , NodeIdx-  , NodeType (..)-  , NodeArena-  , findNodeM-  , foldNodesM-  , getClipRect-  , getDirection-  , getNodeType-  , getParent-  , getRect-  , getScrollContentW-  , getStyleIdx-  , getWidgetId-  )-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt, withInput)-import NanoUI.Testing.Harness-  ( clickPos-  , dragPos-  , findHeader-  , requireSpan-  , spanCenter-  , warmup2-  , withInputOff-  )-import Text.Read (readMaybe)---runTableSortTest :: Context -> IORef Int -> IO ()-runTableSortTest _ failed = do-  let-    columns = headed "Key" fst-    rows = [("b", 1), ("a", 2), ("b", 3), ("a", 4)] :: [(Text, Int)]-  assertEq-    failed-    [2, 4, 1, 3]-    (map snd (sortRows columns (SortCol 0 SortAsc) (SA.smallArrayFromList rows)))-  assertEq-    failed-    [1, 3, 2, 4]-    (map snd (sortRows columns (SortCol 0 SortDesc) rows))-  assertEq failed rows (sortRows mempty (SortCol 0 SortAsc) rows)-  assertEq failed rows (sortRows mempty (SortCol 0 SortDesc) rows)--runTableReorderTest :: Context -> IORef Int -> IO ()-runTableReorderTest ctx failed = do-  let-    input = withInputOff 500 240-    ui = simpleTable ["First", "Second", "Third"] (SA.smallArrayFromList [["a", "b", "c"], ["short"], []])-    draw inp = void (runFrame ctx inp ui)-    header name = do-      spans <- collectTextSpans ctx-      requireSpan "missing table header" (findHeader name spans)-  _ <- warmup2 ctx input ui-  first <- header "First"-  third <- header "Third"-  -- A click is not a reorder, even when its absolute x coordinate exceeds-  -- the drag threshold.-  clickPos draw input first-  clicked <- warmup2 ctx input ui-  assertEq failed [0, 1, 2] (tableColOrder clicked)-  dragPos draw input first third-  moved <- warmup2 ctx input ui-  assertEq failed [1, 0, 2] (tableColOrder moved)-  -- The released drag must not stay latched on subsequent frames.-  draw input {inputMousePos = first}-  settled <- warmup2 ctx input ui-  assertEq failed [1, 0, 2] (tableColOrder settled)---- Row label nearest the bottom edge of the body viewport.-rowLabelIndex :: T.Text -> Maybe Int-rowLabelIndex t = readMaybe (T.unpack (T.takeWhile (/= ' ') (T.drop 4 t)))---- Wheeling with the mouse parked well above a nested table must scroll the--- page scroller only. Hit rects that drift by the page's scroll offset made--- the wheel grab the table's phantom rect and scroll the table instead.-runPageWheelAboveTableTest :: Context -> IORef Int -> IO ()-runPageWheelAboveTableTest ctx failed = do-  let inp0 = withInput 320 220-      wheelAt = inp0 {inputMousePos = V2 160 80, inputScroll = V2 0 5}-      ui = scrollArea (fillW . fixedH 200 . gap 0) $ do-        mapM_ (\i -> label (T.pack ("head " <> show (i :: Int)))) [1 .. 10]-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        tableWith (fixedH 120) "people" tableScrollCols tableScrollRows tableSort-  (pageWid, _) <- warmup2 ctx inp0 ui-  _ <- runFrame ctx wheelAt ui-  _ <- runFrame ctx wheelAt ui-  pageOff <- getScrollOffset ctx pageWid-  assertGt failed pageOff 0-  spans <- collectTextSpans ctx-  let firstRowVisible = any ((== Just 1) . rowLabelIndex . sndOfSpan) spans-  assert failed firstRowVisible-  where-    sndOfSpan (_, t, _, _, _) = t--bottomRowIndex :: [(Rect, T.Text, a, b, c)] -> Maybe Int-bottomRowIndex spans =-  listToMaybe-    [ n-    | (_, t, _, _, _) <--        sortBy-          ( \(ra, _, _, _, _) (rb, _, _, _, _) ->-              compare (rectY rb) (rectY ra)-          )-          spans-    , "row-" `T.isPrefixOf` t-    , Just n <- [rowLabelIndex t]-    ]---- Scrolling must materialize the newly revealed row in the same frame the--- offset lands. The scroll offset is applied after the UI pass, so a frame--- that only translated the pre-scroll rows left the revealed strip without--- geometry (stale pixels under the damage clip).-runTableScrollRevealTest :: Context -> IORef Int -> IO ()-runTableScrollRevealTest ctx failed = do-  let inp0 = (withInput 320 220) {inputMousePos = V2 40 80}-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableWith-              (fixedH 150)-              "people"-              tableScrollCols-              tableScrollRows-              tableSort-          )-  -- A step of one line keeps the scroll below short enough that the rows it-  -- lands on are still in ascending label order (the table sorts the labels-  -- as text, so "row-2" comes after "row-19").-  setScrollTuning ctx defaultScrollTuning {scrollWheelStep = 20}-  -- Three warmups so virtualization settles on the real viewport height.-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  spans0 <- collectTextSpans ctx-  -- Scroll six wheel lines (120px, several rows): the bottom visible row must-  -- advance because the revealed rows are materialized in the same frame.-  let scrollInp = inp0 {inputScroll = V2 0 6}-  _ <- runFrame ctx scrollInp ui-  spans1 <- collectTextSpans ctx-  case (bottomRowIndex spans0, bottomRowIndex spans1) of-    (Just lo, Just hi) -> do-      assert failed (hi > lo)-      -- The revealed band must be filled with real rows, not one clipped sliver-      -- of a stale row scrolling past the top edge.-      let-        visibleRows = [r | (r, t, _, _, _) <- spans1, "row-" `T.isPrefixOf` t]-      assert failed (length visibleRows >= 3)-    _ -> assert failed False---- When one cell wraps to several lines the whole row grows; every other--- cell in the row must stretch to the same height so stripe backgrounds and--- row borders span the full row instead of leaving a gap.-runTableWrapRowStretchTest :: Context -> IORef Int -> IO ()-runTableWrapRowStretchTest ctx failed = do-  let inp0 = (withInput 700 400) {inputMousePos = V2 (-40) (-40)}-      cfg = defaultTableConfig {tableColSizes = [ColFixed 280, ColFixed 90]}-      wrapCols = headed "Name" fst <> headed "Notes" snd-      rows =-        [ ("row-" <> T.pack (show (i :: Int)), T.unwords (replicate 24 "lorem"))-        | i <- [1 .. 8]-        ]-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableConfigured-              cfg-              id-              "wrap-stretch"-              wrapCols-              rows-              tableSort-          )-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  let na = ctxNodeArena ctx-  cells <- foldNodesM na (\acc i -> do-    nt <- getNodeType na i-    if nt /= NodeText-      then pure acc-      else do-        (_, y, w, h) <- getRect na i-        -- Body cells sit below the header band and have real width (both-        -- columns are wider than 50px; the 90px Notes column wraps its long-        -- text and drives the row height).-        pure (if y > 25 && w > 50 then (y, [h]) : acc else acc)) []-  -- Cells of one row share the same top y; every row group must be uniform-  -- (all cells stretch to the row height).-  let rowBands = IM.toAscList (IM.fromListWith (++) [(round y, hs) | (y, hs) <- cells])-  forM_ rowBands $ \(_, hs) -> assert failed (length (dedup hs) == 1)-  -- And at least one row is actually wrapped (taller than the 28px minimum),-  -- otherwise the test asserts nothing.-  assert failed (any (\hs -> maximum hs > 40) (map snd rowBands))-  -- The body must start right below the header: an unconditional scrollbar-  -- lane reserve (shown even with no horizontal overflow) opens a dead gap.-  assert failed (minimum (map fst rowBands) < 40)-  where-    dedup = foldr (\x acc -> if x `elem` acc then acc else x : acc) []---- Resizing a column past the pane's right edge overflows the body. On every--- drag frame the header row must stay inside the row scroller's clip, with--- no frame where the horizontal bar lane covers the header's bottom half,--- and once the drag settles the body scroller's--- horizontal bar drags the shared offset both ways.-runTableResizeOverflowTest :: Context -> IORef Int -> IO ()-runTableResizeOverflowTest ctx failed = do-  let inp0 = (withInput 400 300) {inputMousePos = V2 30 30}-      -- Five rows put the body just inside the vertical bar's toggle band:-      -- the bar appears exactly when the header lane spacer appears, which is-      -- the sequence that could clip the header.-      rows = take 5 tableScrollRows-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableWith-              (fixedH 180)-              "resize-lane"-              tableScrollCols-              rows-              tableSort-          )-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  hdr <- headerButtonRect ctx-  case hdr of-    Nothing -> assert failed False-    Just (Rect hx hy hw hh) -> do-      let edgeX = hx + hw-          headerY = hy + hh / 2-          pressInp = inp0 {inputMousePos = V2 (edgeX - 2) headerY, inputMouseDown = True, inputMousePressed = True}-          dragInp x = inp0 {inputMousePos = V2 x headerY, inputMouseDown = True}-          -- First drag well past the pane's right edge (lane + v-bar appear),-          -- then settle back inside the vertical-bar gutter band so the-          -- scroller viewport and the stale lane flag disagree across frames.-          steps = [edgeX + 160, edgeX + 320, edgeX + 300, edgeX + 290, edgeX + 310, edgeX + 300]-      _ <- runFrame ctx pressInp ui-      forM_ steps $ \x -> do-        _ <- runFrame ctx (dragInp x) ui-        mClip <- headerScrollerClip ctx-        mHdr <- headerButtonRect ctx-        case (mClip, mHdr) of-          (Just (Rect _ cy _ ch), Just (Rect _ hy' _ hh')) -> assert failed (hy' + hh' <= cy + ch + 0.5)-          _ -> assert failed False-      -- Release the resize drag and let the layout settle.-      _ <- runFrame ctx inp0 ui-      _ <- runFrame ctx inp0 ui-      -- The bar lives at the bottom of the body scroller: pressing its track-      -- there jumps the shared horizontal offset, and dragging moves it.-      mBody <- bodyScrollerRect ctx-      case mBody of-        Nothing -> assert failed False-        Just (Rect bx by bw bh) -> do-          let barY = by + bh - scrollBarWidth / 2-              barPress = inp0 {inputMousePos = V2 (bx + bw * 0.3) barY, inputMouseDown = True, inputMousePressed = True}-              barDrag x = inp0 {inputMousePos = V2 x barY, inputMouseDown = True}-          _ <- runFrame ctx barPress ui-          V2 off1 _ <- bodyOffset ctx-          _ <- runFrame ctx (barDrag (bx + bw * 0.95)) ui-          V2 off2 _ <- bodyOffset ctx-          assertGt failed off2 off1-          _ <- runFrame ctx (barDrag (bx + bw * 0.2)) ui-          V2 off3 _ <- bodyOffset ctx-          assert failed (off3 < off2)---- | Leftmost table-header button rect.-headerButtonRect :: Context -> IO (Maybe Rect)-headerButtonRect ctx = listToMaybe <$> headerButtonRects ctx---- | Content clip of the header row scroller (the Row-direction one).-headerScrollerClip :: Context -> IO (Maybe Rect)-headerScrollerClip ctx = do-  let na = ctxNodeArena ctx-  found <- findNodeM na $ \i -> do-    nt <- getNodeType na i-    if nt == NodeScrollContainer then (== DirRow) <$> getDirection na i else pure False-  maybe (pure Nothing) (getClipRect na) found--isTableHeaderStyleIdx :: Int -> Bool-isTableHeaderStyleIdx si = si .&. 0x80000000 /= 0--tableScrollCols :: Colonnade Headed TableScrollRow T.Text-tableScrollCols =-  mconcat-    [ headed "Name" tableScrollName-    , headed "Value" tableScrollVal-    ]--data TableScrollRow = TableScrollRow-  { tableScrollName :: T.Text-  , tableScrollVal :: T.Text-  }--tableScrollRows :: [TableScrollRow]-tableScrollRows =-  [ TableScrollRow ("row-" <> T.pack (show (i :: Int))) ("val-" <> T.pack (show i))-  | i <- [1 .. 20]-  ]---- A content-sized first column fits its longest cell, and in a fit-width 2D--- table vertical overflow must not shrink it either.-runTableFirstColWidthTest :: Context -> IORef Int -> IO ()-runTableFirstColWidthTest ctx failed = do-  let inp0 = (withInput 400 200) {inputMousePos = V2 60 80}-      cfg =-        defaultTableConfig-          { tableColSizes = [ColContent, ColStretch]-          }-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableConfigured-              cfg-              id-              "people"-              tableFirstColCols-              tableFirstColRows-              tableSort-          )-  warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  let findLabel needle =-        listToMaybe [(r, t) | (r, t, _, _, _) <- spans, needle `T.isInfixOf` t]-  case (findLabel "long-first-col", findLabel "val-1") of-    (Just (Rect cn _ cw _, _), Just (Rect vx _ _ _, _)) -> do-      assertGt failed cw 50-      assert failed (vx > cn + cw - 2)-    _ -> assert failed False-  pixel <- newPixelContext-  let fitInp = (withInput 280 180) {inputMousePos = V2 40 60}-      fitUi = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableWith-              (fixedH 100 . (\l -> l {layoutWidth = Fit}))-              "people"-              tableFirstColCols-              tableFirstColRows-              tableSort-          )-  warmup2 pixel fitInp fitUi-  fitSpans <- collectTextSpans pixel-  case [r | (r, t, _, _, _) <- fitSpans, "long-first-col" `T.isInfixOf` t] of-    Rect _ _ cw ch : _ -> do-      assertGt failed cw 50-      assert failed (ch < 40)-    [] -> assert failed False--tableFirstColCols :: Colonnade Headed TableFirstColRow T.Text-tableFirstColCols =-  mconcat-    [ headed "Name" tableFirstColName-    , headed "Value" tableFirstColVal-    ]--data TableFirstColRow = TableFirstColRow-  { tableFirstColName :: T.Text-  , tableFirstColVal :: T.Text-  }--tableFirstColRows :: [TableFirstColRow]-tableFirstColRows =-  TableFirstColRow "long-first-col" "short"-    : [ TableFirstColRow ("row-" <> T.pack (show (i :: Int))) ("val-" <> T.pack (show i))-      | i <- [1 .. 8 :: Int]-      ]--runTableFillWidthTest :: Context -> IORef Int -> IO ()-runTableFillWidthTest _ failed = do-  ctx <- newContext-  let inp0 = (withInput 500 200) {inputMousePos = V2 200 80}-      cfg =-        defaultTableConfig-          { tableColSizes =-              [ ColContent-              , ColStretch-              , ColFixed 64-              , ColStretch-              , ColContent-              ]-          }-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableConfigured-              cfg-              id-              "people"-              tableFillCols-              tableFillRows-              tableSort-          )-  warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  let findLabel needle =-        listToMaybe [(r, t) | (r, t, _, _, _) <- spans, needle `T.isInfixOf` t]-  case (findLabel "Name", findLabel "David", findLabel "Role", findLabel "Manager") of-    ( Just (Rect nx _ _ _, _)-      , Just (Rect cx _ _ _, _)-      , Just (Rect rx _ rw _, _)-      , Just (Rect mx _ mw _, _)-      ) -> do-      assert failed (abs (nx - cx) <= 1)-      assertGt failed (rx + rw) 380-      assertGt failed mw 50-      assert failed (mx >= rx - 2)-    _ -> assert failed False---- Pixel host: Age (right) and City (left) must not sit on the shared grid--- line. A plain table also hands its slack to the columns, so the last one--- reaches the far side.-runTableCellPadTest :: Context -> IORef Int -> IO ()-runTableCellPadTest ctx failed = do-  let inp0 = (withInput 500 240) {inputMousePos = V2 200 80}-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void (table "people" tableFillCols tableFillRows tableSort)-  warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  let findLabel needle =-        listToMaybe [(r, t) | (r, t, _, _, _) <- spans, needle `T.isInfixOf` t]-  case (findLabel "Name", findLabel "David", findLabel "63", findLabel "Austin") of-    (Just (Rect hx _ _ _, _), Just (Rect nx _ _ _, _), Just (Rect ax _ aw _, _), Just (Rect cx _ _ _, _)) -> do-      assert failed (abs (hx - nx) <= 1)-      assertGt failed nx 4-      assertGt failed (cx - (ax + aw)) 10-    _ -> assert failed False-  -- The slack check needs all five columns in view, which the pixel font's-  -- wider glyphs do not fit in 500px; measure it on a plain host.-  plain <- newContext-  warmup2 plain ((withInput 500 200) {inputMousePos = V2 200 80}) ui-  plainSpans <- collectTextSpans plain-  case [r | (r, t, _, _, _) <- plainSpans, "Role" `T.isInfixOf` t] of-    Rect rx _ rw _ : _ -> assertGt failed (rx + rw) 420-    [] -> assert failed False--tableFillCols :: Colonnade Headed TableFillRow T.Text-tableFillCols =-  mconcat-    [ headed "Name" tableFillName-    , headed "Dept" tableFillDept-    , headed "Age" tableFillAge-    , headed "City" tableFillCity-    , headed "Role" tableFillRole-    ]--data TableFillRow = TableFillRow-  { tableFillName :: T.Text-  , tableFillDept :: T.Text-  , tableFillAge :: T.Text-  , tableFillCity :: T.Text-  , tableFillRole :: T.Text-  }--tableFillRows :: [TableFillRow]-tableFillRows =-  [ TableFillRow "David" "Eng" "63" "Austin" "Staff"-  , TableFillRow "Maya" "Ops" "41" "Tokyo" "Manager"-  , TableFillRow "Chen" "Design" "26" "Shanghai" "IC"-  ]---- The demo's page structure (page scroller, card panel, five columns). Every--- column boundary must raise the resize cursor and resize when grabbed, both--- on the header cell and down in the column body.-runTableColResizeDemoReproTest :: Context -> IORef Int -> IO ()-runTableColResizeDemoReproTest _ failed =-  forM_ [False, True] $ \inBody -> do-    ctx <- newPixelContext-    let inp0 = (withInput 700 500) {inputMousePos = V2 400 100}-        ui =-          scrollWith (tight . grow) $-            columnWith (padAll 6 . gap 6 . fillW) $-              card $ do-                (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-                void-                  ( tableWith-                      (fixedH 280)-                      "people"-                      demoPeopleCols-                      demoPeopleRows-                      tableSort-                  )-    _ <- runFrame ctx inp0 ui-    _ <- runFrame ctx inp0 ui-    bodyBot <- tableBodyBottom ctx-    hdrs0 <- headerButtonRects ctx-    forM_ (zip [0 ..] hdrs0) $ \(k, _) -> do-      hdrs <- headerButtonRects ctx-      case drop k hdrs of-        Rect hx hy hw hh : _ | bodyBot > hy + hh + 20 -> do-          let edgeX = hx + hw - 2-              grabY = if inBody then (hy + hh + bodyBot) / 2 else hy + hh / 2-              hoverInp = inp0 {inputMousePos = V2 edgeX grabY}-          _ <- runFrame ctx hoverInp ui-          kind <- uiCursorKind ctx hoverInp-          assertEq failed kind UiCursorEwResize-          let pressInp = hoverInp {inputMouseDown = True, inputMousePressed = True}-              dragInp x = inp0 {inputMousePos = V2 x grabY, inputMouseDown = True}-          before <- headerButtonRects ctx-          _ <- runFrame ctx pressInp ui-          _ <- runFrame ctx (dragInp (edgeX + 60)) ui-          _ <- runFrame ctx (dragInp (edgeX + 60)) ui-          _ <- runFrame ctx (dragInp (edgeX + 60)) ui-          after <- headerButtonRects ctx-          case (drop k before, drop k after) of-            (Rect _ _ wb _ : _, Rect _ _ wa _ : _) -> assertGt failed wa (wb + 30)-            _ -> assert failed False-        _ -> assert failed False--demoPeopleCols :: Colonnade Headed (T.Text, T.Text, T.Text, T.Text, T.Text) T.Text-demoPeopleCols =-  mconcat-    [ headed "Name" (\(a, _, _, _, _) -> a)-    , headed "Dept" (\(_, b, _, _, _) -> b)-    , headed "Age" (\(_, _, c, _, _) -> c)-    , headed "City" (\(_, _, _, d, _) -> d)-    , headed "Role" (\(_, _, _, _, e) -> e)-    ]--demoPeopleRows :: [(T.Text, T.Text, T.Text, T.Text, T.Text)]-demoPeopleRows =-  [ (T.pack n, T.pack d, T.pack (show a), T.pack c, T.pack r)-  | (n, d, a, c, r) <--      [ ("David", "Eng", 63 :: Int, "Austin", "Staff")-      , ("Ava", "Design", 34, "Berlin", "Lead")-      , ("Sonia", "Eng", 12, "Lisbon", "Intern")-      , ("Maya", "Ops", 41, "Tokyo", "Manager")-      , ("Leo", "Design", 28, "Paris", "IC")-      , ("Noah", "Eng", 37, "Seoul", "Staff")-      , ("Iris", "Ops", 19, "Austin", "IC")-      , ("Jules", "Sales", 45, "London", "Manager")-      , ("Priya", "Eng", 31, "Bengaluru", "Lead")-      , ("Chen", "Design", 26, "Shanghai", "IC")-      , ("Omar", "Ops", 52, "Cairo", "Lead")-      , ("Elena", "Sales", 39, "Madrid", "Staff")-      , ("Kai", "Eng", 23, "Oslo", "IC")-      , ("Ruth", "Ops", 47, "Boston", "Staff")-      ]-  ]---- All table-header button rects, left to right.-headerButtonRects :: Context -> IO [Rect]-headerButtonRects ctx = do-  let na = ctxNodeArena ctx-  rects <- foldNodesM na (\acc i -> do-    header <- isHeaderButton na i-    if header then (\(x, y, w, h) -> Rect x y w h : acc) <$> getRect na i else pure acc) []-  pure (sortOn rectX rects)--isHeaderButton :: NodeArena -> NodeIdx -> IO Bool-isHeaderButton na i = do-  nt <- getNodeType na i-  if nt == NodeButton then isTableHeaderStyleIdx <$> getStyleIdx na i else pure False---- | Bottom edge of the table pane: from the first header button, walk up to--- the enclosing panel and return its bottom Y.-tableBodyBottom :: Context -> IO Float-tableBodyBottom ctx = do-  let na = ctxNodeArena ctx-  let walkUp i-        | i < 0 = pure 0-        | otherwise = do-            nt <- getNodeType na i-            if nt /= NodePanel-              then getParent na i >>= walkUp-              else do-                (_, py, _, ph) <- getRect na i-                pure (py + ph)-  findNodeM na (isHeaderButton na) >>= maybe (pure 0) walkUp---- | The body (unfrozen) v-scroller: a Column-direction 2D scroller with--- style bits "both policies Auto, clamp set" (shared predicate for the--- rect / h-bar / offset helpers below).-isBodyScroller :: Context -> NodeIdx -> IO Bool-isBodyScroller ctx i = do-  let na = ctxNodeArena ctx-  nt <- getNodeType na i-  if nt /= NodeScrollContainer-    then pure False-    else do-      d <- getDirection na i-      if d /= DirColumn-        then pure False-        else do-          si <- getStyleIdx na i-          pure (si .&. 3 == 0 && (si `div` 4) .&. 3 == 0 && si .&. 16 /= 0)--bodyScrollerRect :: Context -> IO (Maybe Rect)-bodyScrollerRect ctx = do-  let na = ctxNodeArena ctx-  found <- findNodeM na (isBodyScroller ctx)-  forM found $ \i -> do-    (x, y, w, h) <- getRect na i-    pure (Rect x y w h)---- | The body scroller's 2D offset.-bodyOffset :: Context -> IO V2-bodyOffset ctx = do-  let na = ctxNodeArena ctx-  found <- findNodeM na (isBodyScroller ctx)-  maybe (pure (V2 0 0)) (getScrollOffset2D ctx <=< getWidgetId na) found---- | Horizontal reach: at the end of the horizontal scroll the last column must--- clear the vertical scrollbar lane, not stop with its right edge under the--- lane. The body scroller's own vertical bar shrinks the horizontal viewport,--- so the reachable range must subtract that lane (regression: the range used--- the full padding box, leaving the last column partly hidden).-runTableHBarReachTest :: Context -> IORef Int -> IO ()-runTableHBarReachTest ctx failed = do-  let inp0 = (withInput 700 320) {inputMousePos = V2 300 160}-      cfg = defaultTableConfig {tableColSizes = [ColFixed 500, ColFixed 500]}-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void-          ( tableConfigured-              cfg-              (fixedH 200)-              "people"-              tableScrollCols-              tableScrollRows-              tableSort-          )-  _ <- runFrame ctx inp0 ui-  _ <- runFrame ctx inp0 ui-  mBody <- bodyScrollerRect ctx-  case mBody of-    Nothing -> assert failed False-    Just (Rect bx by bw bh) -> do-      let na = ctxNodeArena ctx-      scroller <- findNodeM na (isBodyScroller ctx)-      case scroller of-        Nothing -> assert failed False-        Just i -> do-          contentW <- getScrollContentW na i-          assertGt failed contentW bw-          let wheel = inp0 {inputMousePos = spanCenter (Rect bx by bw bh), inputScroll = V2 50 0}-          replicateM_ 20 (runFrame ctx wheel ui)-          V2 offX _ <- bodyOffset ctx-          -- Reached past the naive content - viewport range: the lane's width-          -- is now part of the reachable range.-          assertGt failed offX (contentW - bw)-          -- The rightmost header cell sits fully inside the body, left of the-          -- vertical lane.-          hdrs <- headerButtonRects ctx-          case reverse hdrs of-            (Rect hx _ hw _ : _) -> do-              assert failed (hx + hw <= bx + bw + 0.5)-              assertGt failed (hx + hw) (bx + bw - 24)-            [] -> assert failed False-          -- Header and body cells scroll in lockstep.-          spans <- collectTextSpans ctx-          let xOf needle = listToMaybe [rectX r | (r, t, _, _, _) <- spans, needle `T.isInfixOf` t]-          case (xOf "Value", xOf "val-") of-            (Just headerX, Just cellX) -> assert failed (abs (headerX - cellX) <= 1)-            _ -> assert failed False---- A table with frozen columns builds two scroll nodes under one widget id.--- Only one of them may publish the body's geometry: if both did, every frame--- would rewrite the store with the other pane's viewport twice a frame, for--- as long as the table is on screen. One publishes; what it publishes is the--- body scroller, whole, and it holds still from frame to frame.-runTableSharedScrollMetricsTest :: Context -> IORef Int -> IO ()-runTableSharedScrollMetricsTest ctx failed = do-  let inp0 = (withInput 320 220) {inputMousePos = V2 40 80}-      cfg = defaultTableConfig {tableFreezeCols = 1}-      ui = do-        (tableSort, _) <- useTableSort (SortCol 0 SortAsc)-        void (tableConfigured cfg (fixedH 150) "people" tableScrollCols tableScrollRows tableSort)-  replicateM_ 3 (runFrame ctx inp0 ui)-  bodyWid <- tableBodyScrollWid ctx-  case bodyWid of-    Nothing -> assert failed False-    Just wid -> do-      before <- getScrollMetrics ctx wid-      assert failed (isJust before)-      -- The pane that owns both scrollbars, not the frozen column's sliver.-      assertEq failed (Just ScrollAxisXY) (fmap scrollAxes before)-      _ <- runFrame ctx inp0 ui-      after <- getScrollMetrics ctx wid-      assertEq failed before after---- The widget id shared by the table body's panes: the id of the first scroll--- container the arena holds that another scroll container repeats.-tableBodyScrollWid :: Context -> IO (Maybe WidgetId)-tableBodyScrollWid ctx = do-  let na = ctxNodeArena ctx-  wids <- reverse <$> foldNodesM na (\acc i -> do-    nt <- getNodeType na i-    if nt == NodeScrollContainer then (: acc) <$> getWidgetId na i else pure acc) []-  pure (listToMaybe [w | w : rest <- tails wids, w `elem` rest])-+{-# OPTIONS_GHC -O0 #-}+module Cases.Table (tests) where++import Spec+import Data.Bits ((.&.), shiftR)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.List (nub, sort, sortOn)+import Data.Ord (Down (..))+import Data.Maybe (listToMaybe, mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Primitive.SmallArray qualified as SA+import Data.String (IsString)+import NanoUI.Internal.Context (ctxNodeArena)+import NanoUI.Internal.Layout.Arena+  ( NodeIdx+  , NodeArena+  , findNodeM+  , foldNodesM+  , getClipRect+  , getDirection+  , getNodeType+  , getParent+  , getNodeRect+  , getScrollContentW+  , getStyleIdx+  , getText+  , getWidgetId+  )+import NanoUI.Testing.Sim+import Text.Read (readMaybe)++tests :: [Spec]+tests =+  [ spec "table-sort" runTableSortTest+  , spec "table-widget-cells" runTableWidgetCellsTest+  , spec "table-sort-mark-damage" runTableSortMarkDamageTest+  , spec "table-live-rows" runTableLiveRowsTest+  , spec "table-reorder" runTableReorderTest+  , spec "table-hide-columns" runTableHideColumnsTest+  , spec "table-frozen" runTableFrozenTest+  , pixelSimSpec "page-wheel-above-table" 320 220 pageAboveTableUi pageWheelAboveTable+  , pixelSpec "table-scroll-reveal" runTableScrollRevealTest+  , spec "table-wrap" runTableWrapTest+  , spec "table-column-widths" runTableColumnWidthsTest+  , spec "table-narrow-columns" runTableNarrowColumnsTest+  , spec "table-rules-tile" runTableRulesTileTest+  , pixelSpec "table-resize-overflow" runTableResizeOverflowTest+  , spec "table-col-resize" runTableColResizeTest+  , pixelSpec "table-hbar-reach" runTableHBarReachTest+  , spec "table-squeeze" runTableSqueezeTest+  , spec "table-sort-keys-and-bare" runTableSortKeysBareTest+  ]++-- | A table sorted ascending on its first column, given everything but the sort.+sortedTable :: (Var SortCol -> NanoUI ()) -> NanoUI ()+sortedTable build = build =<< useVar (SortCol 0 SortAsc)++-- | A sorted table of @rows@ with config @cfg@, laid out by @layout@.+tableOf :: ToCell c => TableConfig -> (Layout -> Layout) -> Colonnade Headed r c -> [r] -> NanoUI ()+tableOf cfg layout cols rows = sortedTable (tableConfigured cfg layout "t" cols rows)++-- | A sorted table with these column sizes.+sizedTable :: ToCell c => [ColSize] -> Colonnade Headed r c -> [r] -> NanoUI ()+sizedTable sizes = tableOf defaultTableConfig {tableColSizes = sizes} id++type Person = (Text, Text, Text, Text, Text)++-- | The first @n@ columns of the demo's people table.+peopleCols :: Int -> Colonnade Headed Person Text+peopleCols n =+  mconcat . take n $+    [ headed "Name" (\(a, _, _, _, _) -> a)+    , headed "Dept" (\(_, b, _, _, _) -> b)+    , headed "Age" (\(_, _, c, _, _) -> c)+    , headed "City" (\(_, _, _, d, _) -> d)+    , headed "Role" (\(_, _, _, _, e) -> e)+    ]++people :: [Person]+people =+  [ ("David", "Eng", "63", "Austin", "Staff")+  , ("Maya", "Ops", "41", "Tokyo", "Manager")+  , ("Chen", "Design", "26", "Shanghai", "IC")+  ]++-- | Name/value rows: @row-i@, @val-i@.+scrollCols :: Colonnade Headed (Text, Text) Text+scrollCols = headed "Name" fst <> headed "Value" snd++scrollRows :: [(Text, Text)]+scrollRows = [("row-" <> n, "val-" <> n) | i <- [1 .. 20 :: Int], let n = T.pack (show i)]++-- | Fruit names, a widget cell sorted by its count, and a button that logs+-- the fruit it eats.+mixedCols :: IORef [Text] -> Colonnade Headed (Text, Int) Cell+mixedCols eaten =+  mconcat+    [ headed "Fruit" (textCell . fst)+    , headed "Count" (\(_, n) -> cellSort (T.pack (show n)) (cellWidget (label (T.pack (show n)))))+    , headed "Button" (\(f, _) -> cellWidget (whenM (button ("Eat " <> f)) (eat f)))+    ]+  where+    eat f = liftIO (modifyIORef' eaten (f :))++fruits :: [(Text, Int)]+fruits = [("banana", 2), ("apple", 1), ("cherry", 3)]++-- | Rows sort stably by a column's text, and stay as given with no column+-- to sort by. (Widget cells sort by their key in "table-widget-cells".)+runTableSortTest :: Context -> IORef Int -> IO ()+runTableSortTest _ failed = do+  let byKey = headed "Key" fst+      rows = [("b", 1), ("a", 2), ("b", 3), ("a", 4)] :: [(Text, Int)]+  assertEq failed [2, 4, 1, 3] (map snd (sortRows byKey (SortCol 0 SortAsc) (SA.smallArrayFromList rows)))+  assertEq failed [1, 3, 2, 4] (map snd (sortRows byKey (SortCol 0 SortDesc) rows))+  forM_ [SortAsc, SortDesc] $ \dir ->+    assertEq failed rows (sortRows (mempty :: Colonnade Headed (Text, Int) Text) (SortCol 0 dir) rows)++-- | Widget cells take clicks on the row they belong to, after a sort too, and+-- carry their row's stripe in their panel's style index (even rows 1, odd 2).+runTableWidgetCellsTest :: Context -> IORef Int -> IO ()+runTableWidgetCellsTest ctx failed = do+  eaten <- newIORef []+  sortV <- newVar (SortCol 0 SortAsc)+  runSim ctx failed (withInputOff 500 300) (table "mixed" (mixedCols eaten) fruits sortV) $ do+    mapM_ expect ["Fruit", "Count", "Button", "banana", "Eat cherry"]+    let na = ctxNodeArena ctx+        stripe acc i = do+          nt <- getNodeType na i+          if nt == NodePanel then (: acc) . fromIntegral . (\si -> (si `div` 16) .&. 0x0F) <$> getStyleIdx na i else pure acc+    striped <- filter (/= 0) <$> liftIO (foldNodesM na stripe [])+    checkEq (IS.fromList [1, 2], 6) (IS.fromList striped, length striped)+    _ <- click "Eat apple"+    writeV sortV (SortCol 1 SortDesc)+    _ <- settle+    ys <- mapM (fmap rectY . rectOf) ["cherry", "banana", "apple"]+    checkEq (sort ys) ys+    _ <- click "Eat apple"+    checkEq ["apple", "apple"] =<< liftIO (readIORef eaten)++-- | A sort set from outside repaints the headers that lose and gain the mark,+-- which no rect or text change covers (an empty table has no rows to re-sort).+runTableSortMarkDamageTest :: Context -> IORef Int -> IO ()+runTableSortMarkDamageTest ctx failed = do+  sortV <- newVar (SortCol 0 SortAsc)+  let inp = withInputOff 400 240+      ui = table "marks" (peopleCols 3) ([] :: [Person]) sortV+  spans0 <- run2Frames ctx inp ui >> runFrame ctx inp ui >> collectTextSpans ctx+  writeVarIO sortV (SortCol 1 SortAsc)+  _ <- runFrame ctx inp ui+  dmg <- takeDamage ctx+  forM_ ["Name", "Dept"] $ \h ->+    assertJust failed (findHeader h spans0) $ \(V2 x y) -> assert failed (damageCovers dmg (Rect x y 1 1))++-- | A row of 'runTableLiveRowsTest'; its middle column starts numeric.+data LiveRow = LiveRow Text Text Text++-- | A table given its rows again each frame, a few changed, lays out as a+-- fresh one given the same rows: widths, row counts, a column that stops and+-- starts being numeric (and so changes font), and the order all follow.+runTableLiveRowsTest :: Context -> IORef Int -> IO ()+runTableLiveRowsTest ctx0 failed = do+  let cols = mconcat [headed h (\(LiveRow a b c) -> [a, b, c] !! k) | (k, h) <- zip [0 ..] names]+      names = ["Name", "Qty", "Note"]+      fonts c = withMonoFontMetrics c (monospaceMetrics 10)+      inp0 = (withInput 600 300) {inputMousePos = V2 590 290}+      laidOut c rows = warmup2 c inp0 (sortedTable (table "live" cols rows)) >> collectTextSpans c+      setAt i x xs = take i xs ++ x : drop (i + 1) xs+      rows0 = [LiveRow (T.pack [n]) (T.pack (show i)) "note" | (i, n) <- zip [1 :: Int ..] "dbeac"]+      edits =+        [ setAt 1 (LiveRow "a much longer name" "2" "x")+        , (++ [LiveRow "added" "40" "y"])+        , setAt 2 (LiveRow "e" "n/a" "z")+        , setAt 1 (LiveRow "b" "2" "x")+        , init+        , setAt 0 (LiveRow "zz" "1" "w")+        , setAt 2 (LiveRow "e" "3" "z")+        , setAt 3 (LiveRow "a" "n/a" "note")+        , setAt 1 (LiveRow "b" "none" "x")+        , setAt 3 (LiveRow "a" "4" "note")+        , setAt 3 (LiveRow "a" "four" "note")+        , take 1+        , (++ [LiveRow "y" "2" "note"])+        , setAt 1 (LiveRow "b" "2" "a much longer note")+        ]+      live = fonts ctx0+  void (laidOut live rows0)+  foldM_+    ( \rows edit -> do+        let rows' = edit rows+        fresh <- newContext >>= \c -> laidOut (fonts c) rows'+        laidOut live rows' >>= assertEq failed fresh+        pure rows'+    )+    rows0+    edits++-- | A header dropped on another, or on a boundary's resize zone (no resize+-- arrow while held), moves its column there. A click does not, a released+-- drag does not stay latched, and a scrim blocks reordering and resizing.+runTableReorderTest :: Context -> IORef Int -> IO ()+runTableReorderTest _ failed = do+  scrim <- newIORef False+  let ui = columnWith (fillW . fillH) $ do+        r <- simpleTable ["First", "Second", "Third"] [["a", "b", "c"], ["short"], []]+        covered <- liftIO (readIORef scrim)+        when covered (panelWith (pinAt 0 0 . pointer PointerBlock . fixedWH 500 240) (pure ()))+        pure r+      order = tableColOrder <$> settle+      onTable script = newPixelContext >>= \c -> runSim c failed (withInputOff 500 240) ui script+  onTable $ do+    first <- Within <$> rectOf "First"+    _ <- click first+    checkEq [0, 1, 2] =<< order+    third <- rectOf "Third"+    _ <- drag first (Within third) 1+    checkEq [1, 2, 0] =<< order+    _ <- moveTo first+    checkEq [1, 2, 0] =<< order+  onTable $ do+    [first, Rect sx sy sw sh, _] <- headers+    _ <- press (Within first)+    replicateM_ 2 (moveTo (at (sx + sw - 1) (sy + sh / 2)))+    check . (/= UiCursorColResize) =<< pointerCursor+    _ <- release+    checkEq [1, 0, 2] =<< order+  writeIORef scrim True+  onTable $ do+    before@(Rect fx fy fw fh : _) <- headers+    forM_ [V2 (fx + fw / 2) (fy + fh / 2), V2 (fx + fw - 1) (fy + fh / 2)] $ \p@(V2 x y) -> do+      _ <- drag (At p) (at (x + 120) y) 1+      checkEq [0, 1, 2] =<< order+      checkEq before =<< headers++-- | A right-click on a header hides its column while another stays visible,+-- whatever out-of-range indices the hidden set holds; the others share a+-- hidden stretch column's space. Side by side tables keep their own.+runTableHideColumnsTest :: Context -> IORef Int -> IO ()+runTableHideColumnsTest ctx failed = do+  let sizes = [ColStretch, ColContent, ColContent]+      cfg = defaultTableConfig {tableColSizes = sizes, tableHidden = IS.singleton 5}+      ui = tableConfigured' cfg id "hide" (peopleCols 3) people =<< useVar (SortCol 0 SortAsc)+      rightEdge = maybe 0 (\r -> rectX r + rectW r) . listToMaybe . reverse+      hideFirst = do+        first : _ <- headers+        _ <- rightClick (Within first)+        tableHiddenIndices <$> settle+  runSim ctx failed (withInputOff 500 240) ui $ do+    filled <- rightEdge <$> headers+    checkEq [0, 5] =<< hideFirst+    shared <- rightEdge <$> headers+    checkGt shared (filled - 1)+    checkEq [0, 1, 5] =<< hideFirst+    -- The last column stays.+    checkEq [0, 1, 5] =<< hideFirst+  c <- newContext+  let pair = columnWith fillW ((,) <$> simpleTable ["A", "B"] [["a1"]] <*> simpleTable ["X", "Y"] [["x1"]])+  runSim c failed (withInputOff 500 300) pair $ do+    (a, x) <- rightClick "A" >> settle+    checkEq ([0], []) (tableHiddenIndices a, tableHiddenIndices x)++-- | A sideways wheel over a frozen column scrolls the body, though the rows+-- fit and the frozen pane sharing its id has nothing to scroll. A column+-- edge scrolled under the frozen column has no resize zone there. Of the+-- two scroll nodes the table builds under one id, only the pane owning both+-- bars publishes metrics, and they hold still (two publishers rewrote the+-- store every frame).+runTableFrozenTest :: Context -> IORef Int -> IO ()+runTableFrozenTest ctx failed = do+  let cfg = defaultTableConfig {tableFreezeCols = 1, tableColSizes = map ColFixed [150, 100, 500]}+  runSim ctx failed (withInputOff 400 240) (tableOf cfg (fixedH 200) (peopleCols 3) people) $ do+    Just wid <- onContext bodyWid+    metrics <- onContext (`getScrollMetricsIO` wid)+    checkEq (Just ScrollAxisXY) (scrollAxes <$> metrics)+    checkEq metrics =<< (frame >> onContext (`getScrollMetricsIO` wid))+    Rect fx fy fw fh : _ <- headers+    _ <- wheel (at (fx + fw / 2) (fy + fh + 10)) (V2 1 0)+    V2 offX _ <- scrollOffset2DOf wid+    checkGt offX 0+    onContext (\c -> setScrollOffset2DIO c wid (V2 120 0))+    [Rect _ _ frozenW _, Rect hx hy hw hh, _] <- settle >> headers+    check (hx + hw < fx + frozenW)+    check . (/= UiCursorColResize) =<< cursorAt (at (hx + hw - 1) (hy + hh / 2))++pageAboveTableUi :: NanoUI (WidgetId, ())+pageAboveTableUi = scrollArea (fillW . fixedH 200 . gap 0) $ do+  mapM_ (\i -> label (T.pack ("head " <> show (i :: Int)))) [1 .. 10]+  tableOf defaultTableConfig (fixedH 120) scrollCols scrollRows++-- | The wheel well above a table in a page scrolls the page: hit rects that+-- drifted by the page's offset made it scroll the table's phantom rect.+pageWheelAboveTable :: Sim (WidgetId, ()) ()+pageWheelAboveTable = do+  (page, _) <- result+  replicateM_ 2 (wheel (at 160 80) (V2 0 5))+  off <- scrollOffsetOf page+  checkGt off 0+  check =<< labelShown "row-1"++-- | Scrolling builds the revealed rows in the frame the offset lands (it+-- applies after the view runs, which left the revealed strip empty).+runTableScrollRevealTest :: Context -> IORef Int -> IO ()+runTableScrollRevealTest ctx failed = do+  -- A one-line step keeps the rows the scroll lands on in ascending label+  -- order (the labels sort as text, so "row-2" comes after "row-19").+  setScrollTuningIO ctx defaultScrollTuning {scrollWheelStep = 20}+  let rowSpans = (\ss -> [(r, t) | (r, t, _, _, _) <- ss, "row-" `T.isPrefixOf` t]) <$> spans+      -- The N of the lowest "row-N" label.+      rowIndex t = readMaybe (T.unpack (T.takeWhile (/= ' ') (T.drop 4 t))) :: Maybe Int+      bottomRow = listToMaybe . mapMaybe (rowIndex . snd) . sortOn (Down . rectY . fst) <$> rowSpans+      ui = tableOf defaultTableConfig (fixedH 150) scrollCols scrollRows+  runSim ctx failed ((withInput 320 220) {inputMousePos = V2 40 80}) ui $ do+    lo <- bottomRow+    hi <- frameWith (\i -> i {inputScroll = V2 0 6}) >> bottomRow+    checkJust ((,) <$> lo <*> hi) $ \(l, h) -> checkGt h l+    -- Real rows fill the revealed band, not a sliver of a stale one.+    check . (>= 3) . length =<< rowSpans++-- | A row with a wrapping cell grows and all its cells stretch to it, right+-- below the header (no dead lane gap). A wrapping cell is as tall as the+-- lines paint draws in it: two words fit the 90px cell, not its inset.+runTableWrapTest :: Context -> IORef Int -> IO ()+runTableWrapTest ctx failed = do+  let wrapCols = headed "Name" fst <> headed "Notes" snd+      lorem = T.unwords (replicate 24 "lorem")+      na = ctxNodeArena ctx+      wrapped = [(T.pack (show i), lorem) | i <- [1 .. 8 :: Int]]+  _ <- warmup2 ctx (withInputOff 700 400) (sizedTable [ColFixed 280, ColFixed 90] wrapCols wrapped)+  -- Body cells: below the header band, and wider than 50px.+  cells <- foldNodesM na (\acc i -> do+    nt <- getNodeType na i+    Rect _ y w h <- getNodeRect na i+    pure (if nt == NodeText && y > 25 && w > 50 then (round y, [h]) : acc else acc)) []+  let rowBands = IM.toAscList (IM.fromListWith (++) cells)+  forM_ rowBands $ \(_, hs) -> assertEq failed 1 (length (nub hs))+  assert failed (any ((> 40) . maximum . snd) rowBands)+  assert failed (minimum (map fst rowBands) < 40)+  c <- newContext+  let notes = T.unwords (replicate 12 "abc")+      cna = ctxNodeArena c+  _ <- warmup2 c (withInputOff 400 400) (sizedTable [ColFixed 120, ColFixed 90] wrapCols [("row", notes)])+  ss <- collectTextSpans c+  assertJustM failed (findNodeM cna (\i -> (== notes) <$> getText cna i)) $ \cell -> do+    Rect cx cy cw ch <- getNodeRect cna cell+    let lns = [r | (r@(Rect x y _ _), t, _, _, _) <- ss, "abc" `T.isPrefixOf` t, x >= cx, x < cx + cw, y >= cy]+    assertEq failed 12 (length lns)+    assert failed (sum (map rectH lns) <= ch)++-- | The rects of the first spans holding each of @needles@ once @ui@ is laid+-- out on @ctx@ in a @w@ by @h@ window; a missing one fails the test.+spanRects :: Context -> Float -> Float -> NanoUI a -> [Text] -> IO [Rect]+spanRects ctx w h ui needles = do+  ss <- warmup2 ctx (withInput w h) {inputMousePos = V2 40 60} ui >> collectTextSpans ctx+  forM needles $ \n -> maybe (fail ("no span " <> show n)) pure (spanRect n ss)++-- | A content-sized first column fits its longest cell, in a fit-width table+-- with vertical overflow too. Mixed sizes fill the width. Age (right) and+-- City (left) keep off their shared rule, and slack goes to the columns.+runTableColumnWidthsTest :: Context -> IORef Int -> IO ()+runTableColumnWidthsTest ctx failed = do+  let firstRows = ("long-first-col", "short") : take 8 scrollRows+      firstCol = sizedTable [ColContent, ColStretch] scrollCols firstRows+  [Rect cn _ cw _, Rect vx _ _ _] <- spanRects ctx 400 200 firstCol ["long-first-col", "val-1"]+  assertGt failed cw 50+  assert failed (vx > cn + cw - 2)+  fitHost <- newPixelContext+  let fit = tableOf defaultTableConfig (fixedH 100 . (\l -> l {layoutWidth = Fit})) scrollCols firstRows+  [Rect _ _ fw fh] <- spanRects fitHost 280 180 fit ["long-first-col"]+  assertGt failed fw 50+  assert failed (fh < 40)+  fillHost <- newContext+  let filled = sizedTable [ColContent, ColStretch, ColFixed 64, ColStretch, ColContent] (peopleCols 5) people+  [Rect nx _ _ _, Rect dx _ _ _, Rect rx _ rw _, Rect mx _ mw _] <-+    spanRects fillHost 500 200 filled ["Name", "David", "Role", "Manager"]+  assert failed (abs (nx - dx) <= 1)+  assertGt failed (rx + rw) 380+  assertGt failed mw 50+  assert failed (mx >= rx - 2)+  pixel <- newPixelContext+  let plainTable = sortedTable (table "people" (peopleCols 5) people)+  [Rect hx _ _ _, Rect px _ _ _, Rect ax _ aw _, Rect tx _ _ _] <-+    spanRects pixel 500 240 plainTable ["Name", "David", "63", "Austin"]+  assert failed (abs (hx - px) <= 1)+  assertGt failed px 4+  assertGt failed (tx - (ax + aw)) 10+  -- The slack check needs all five columns in view, which the pixel font's+  -- wider glyphs do not fit in 500px.+  plain <- newContext+  [Rect lx _ lw _] <- spanRects plain 500 200 plainTable ["Role"]+  assertGt failed (lx + lw) 420++-- | A narrow header truncates with an ellipsis short of the next column, its+-- text its label alone (the sort mark's lane is an inset). A stretch column+-- flexes to its floor rather than scroll sideways, and absorbs the vertical+-- bar's lane (stronghead's leak suspects), its last column clear of it.+runTableNarrowColumnsTest :: Context -> IORef Int -> IO ()+runTableNarrowColumnsTest ctx failed = do+  let pairs a b = headed a fst <> headed b snd :: Colonnade Headed (Text, Text) Text+      truncated = sizedTable [ColFixed 140, ColFixed 100] (pairs "Long Column Title" "Next") [("val1", "val2")]+  ss <- warmup2 ctx (withInputOff 400 200) truncated >> collectTextSpans ctx+  let texts = [t | (_, t, _, _, _) <- ss]+      starting p = [r | (r, t, _, _, _) <- ss, p `T.isPrefixOf` t]+  assert failed (any ("..." `T.isInfixOf`) texts)+  assert failed ("Next" `elem` texts)+  case (starting "Long", starting "Next") of+    (Rect hx _ hw _ : _, Rect nx _ _ _ : _) -> assert failed (hx + hw <= nx)+    _ -> assert failed False+  floored <- newContext+  let stretched = sizedTable [ColStretch, ColFixed 60] (pairs "Stretch" "Fixed") [(T.replicate 400 "x", "1")]+  _ <- warmup2 floored (withInputOff 300 200) stretched+  scrolls <- nodesOfType NodeScrollContainer floored+  ranges <- mapM (fmap (fmap (v2X . scrollRange)) . getScrollMetricsIO floored . fst) scrolls+  assert failed (all (maybe True (<= 0)) ranges)+  lane <- newContext+  -- Fixed columns plus rules (403) fit the narrowed viewport; the stretch+  -- column's old 40px floor (443 in all) did not.+  let suspects =+        tableOf defaultTableConfig {tableColSizes = suspectSizes} (fixedH 267) (suspectCols textCell) $+          suspectRows 10+  _ <- warmup2 lane ((withInput 455 240) {inputMousePos = V2 200 120}) suspects+  assertJustM failed (bodyNode lane) $ \i -> do+    Rect bx _ bw _ <- getNodeRect (ctxNodeArena lane) i+    assertJustM failed (bodyMetrics lane) $ \sm -> do+      assertGt failed (v2Y (scrollRange sm)) 0+      assertEq failed 0 (v2X (scrollRange sm))+      assertJustM failed (listToMaybe . reverse <$> headerButtonRects lane) $ \(Rect hx _ hw _) -> do+        assert failed (hx + hw <= bx + rectW (scrollViewport sm) + 0.5)+        assertGt failed (hx + hw) (bx + bw - 24)++-- | The columns of stronghead's leak suspects table, each cell made by @cell@.+suspectCols :: IsString c => (Text -> c) -> Colonnade Headed (Text, Text, Text, Text) c+suspectCols cell =+  mconcat+    [ headed "leak suspect" (\(a, _, _, _) -> cell a)+    , headed "peak before" (\(_, b, _, _) -> cell b)+    , headed "peak now" (\(_, _, c, _) -> cell c)+    , headed "status" (\(_, _, _, d) -> cell d)+    ]++suspectSizes :: [ColSize]+suspectSizes = [ColStretch, ColFixed 100, ColFixed 100, ColFixed 200]++suspectRows :: Int -> [(Text, Text, Text, Text)]+suspectRows n = [(T.pack ("suspect-" <> show k), "19.1 MB", "20.0 MB", "still there") | k <- [1 .. n]]++-- | Cells and column rules tile: each child's far edge is the next one's+-- origin, at fractional scales and widths too. A cell a pixel past it paints+-- over the rule, and the grid line vanishes down the whole table.+runTableRulesTileTest :: Context -> IORef Int -> IO ()+runTableRulesTileTest _ failed =+  forM_ [(s, m, w) | s <- [1, 1.25, 1.5, 2], m <- [ColStretch, ColFixed 97.3], w <- [470, 473 .. 530]] $+    \(scale, mid, winW) -> do+      base <- newContext+      let ctx = withFontMetrics base ((monospaceMetrics 12) {fmSnapScale = scale})+          na = ctxNodeArena ctx+          merge (r1, e1) (r2, e2) = (r1 || r2, e1 ++ e2)+          sizes = [ColContent, ColFixed 61.7, mid, ColContent, ColContent]+      warmup2 ctx (withInputOff winW 240) (sizedTable sizes (peopleCols 5) people)+      -- Each parent's children as (has a rule, child extents), in one pass.+      byParent <- foldNodesM na (\acc i -> do+        parent <- getParent na i+        nt <- getNodeType na i+        Rect x _ w _ <- getNodeRect na i+        let entry = (nt == NodeSeparator, [(x, w)])+        pure (if parent < 0 then acc else IM.insertWith merge parent entry acc)) IM.empty+      rows <- filterM (fmap (== DirRow) . getDirection na) [p | (p, (True, _)) <- IM.toList byParent]+      assertGt failed (length rows) 0+      forM_ rows $ \rowIdx -> do+        let edges = sortOn fst (maybe [] snd (IM.lookup rowIdx byParent))+            gaps = [(x0, w0, x1) | ((x0, w0), (x1, _)) <- zip edges (drop 1 edges), abs (x0 + w0 - x1) > 1e-3]+        assertEq failed [] gaps++-- | A column resized past the pane's edge overflows the body: on no drag+-- frame does the bar's lane cover the header, and afterwards the body's+-- horizontal bar drags the shared offset both ways.+runTableResizeOverflowTest :: Context -> IORef Int -> IO ()+runTableResizeOverflowTest ctx failed = do+  -- Five rows put the body just inside the vertical bar's toggle band: the+  -- bar appears exactly when the header lane spacer does.+  let ui = tableOf defaultTableConfig (fixedH 180) scrollCols (take 5 scrollRows)+      offX = (\(V2 x _) -> x) <$> onContext bodyOffset+  runSim ctx failed ((withInput 400 300) {inputMousePos = V2 30 30}) ui $ do+    Rect hx hy hw hh : _ <- headers+    let edgeX = hx + hw+        headerY = hy + hh / 2+    _ <- press (at (edgeX - 2) headerY)+    -- Well past the pane's edge (lane and bar appear), then back and forth+    -- inside the bar's gutter band, where viewport and lane flag disagree.+    forM_ [160, 320, 300, 290, 310, 300] $ \dx -> do+      _ <- moveTo (at (edgeX + dx) headerY)+      Just (Rect _ cy _ ch) <- onContext headerScrollerClip+      Rect _ y _ h : _ <- headers+      check (y + h <= cy + ch + 0.5)+    _ <- release >> settle+    Just (Rect bx by bw bh) <- onContext bodyScrollerRect+    let barY = by + bh - scrollBarWidth / 2+    _ <- press (at (bx + bw * 0.3) barY)+    off1 <- offX+    off2 <- moveTo (at (bx + bw * 0.95) barY) >> offX+    checkGt off2 off1+    off3 <- moveTo (at (bx + bw * 0.2) barY) >> offX+    checkLt off3 off2++-- | The content clip of the header row's scroller (the Row-direction one).+headerScrollerClip :: Context -> IO (Maybe Rect)+headerScrollerClip ctx = do+  let na = ctxNodeArena ctx+      isRowScroller i = (== (NodeScrollContainer, DirRow)) <$> ((,) <$> getNodeType na i <*> getDirection na i)+  maybe (pure Nothing) (getClipRect na) =<< findNodeM na isRowScroller++-- | In the demo's page structure, every column boundary shows the resize+-- arrow and resizes when grabbed, on the header and in the body alike; the+-- arrow stays for the whole drag and goes on release.+runTableColResizeTest :: Context -> IORef Int -> IO ()+runTableColResizeTest _ failed = do+  forM_ [(inBody, k) | inBody <- [False, True], k <- [0 .. 4]] $ \(inBody, k) -> do+    -- A context per edge: widening earlier columns can scroll the last edge+    -- out of view, where it deliberately cannot start a resize.+    ctx <- newPixelContext+    let ui = scrollWith (tight . grow) . columnWith (padAll 6 . gap 6 . fillW) . card $+          tableOf defaultTableConfig (fixedH 280) (peopleCols 5) (take 14 (cycle people))+        widthNow = rectW . (!! k) <$> headers+    runSim ctx failed ((withInput 1200 500) {inputMousePos = V2 400 100}) ui $ do+      bodyBot <- onContext tableBodyBottom+      Rect hx hy hw hh : _ <- drop k <$> headers+      check (bodyBot > hy + hh + 20)+      let edgeX = hx + hw - 2+          grabY = if inBody then (hy + hh + bodyBot) / 2 else hy + hh / 2+      check . (/= UiCursorColResize) =<< cursorAt (at (hx + hw / 2) grabY)+      checkEq UiCursorColResize =<< cursorAt (at edgeX grabY)+      before <- widthNow+      _ <- press (at edgeX grabY)+      replicateM_ 3 (moveTo (at (edgeX + 60) grabY))+      after <- widthNow+      checkGt after (before + 30)+      checkEq UiCursorColResize =<< cursorAt (at (edgeX + 60) 490)+      _ <- release+      check . (/= UiCursorColResize) =<< pointerCursor+  -- Dragging a ColContent column narrower than its content shrinks it down to+  -- minColW (40px), and double-clicking its divider auto-fits back to content+  -- width (and a second double-click restores fill sizing).+  shrinkCtx <- newPixelContext+  let pathCols = headed "Path" fst <> headed "Note" snd :: Colonnade Headed (Text, Text) Text+      pathRows = [("src/Main/App.hs", "ok")]+      pathUi = tableOf defaultTableConfig (fixedH 140) pathCols pathRows+      firstW = maybe 0 rectW . listToMaybe <$> headers+  runSim shrinkCtx failed ((withInput 800 300) {inputMousePos = V2 400 100}) pathUi $ do+    Rect hx hy hw hh : _ <- headers+    let edgeX = hx + hw - 2+        grabY = hy + hh / 2+    -- Shrink well below content width, down toward the 40px floor.+    _ <- press (at edgeX grabY)+    replicateM_ 3 (moveTo (at (hx + 50) grabY))+    shrunk <- firstW+    checkLt shrunk 90+    checkGt shrunk 39.5+    _ <- release >> settle+    -- Double-click the divider to auto-fit to content width (wider than shrunk).+    Rect hx2 hy2 hw2 hh2 : _ <- headers+    _ <- doubleClick (at (hx2 + hw2 - 2) (hy2 + hh2 / 2)) >> settle+    fitted <- firstW+    checkGt fitted (shrunk + 80)+    checkLt fitted 320+    -- Second double-click restores default fill sizing (wider than tight content fit).+    Rect hx3 hy3 hw3 hh3 : _ <- headers+    _ <- doubleClick (at (hx3 + hw3 - 2) (hy3 + hh3 / 2)) >> settle+    restored <- firstW+    checkGt restored (fitted + 80)++-- | 'headerButtonRects' in a script.+headers :: Sim a [Rect]+headers = onContext headerButtonRects++-- | All table-header button rects, left to right.+headerButtonRects :: Context -> IO [Rect]+headerButtonRects ctx = do+  let na = ctxNodeArena ctx+      collect acc i = isHeaderButton na i >>= \h -> if h then (: acc) <$> getNodeRect na i else pure acc+  sortOn rectX <$> foldNodesM na collect []++isHeaderButton :: NodeArena -> NodeIdx -> IO Bool+isHeaderButton na i = do+  nt <- getNodeType na i+  -- ButtonTable = 3 in bits 24-27 (SB.buttonKind).+  if nt == NodeButton then (\si -> (si `shiftR` 24) .&. 0xF == 3) <$> getStyleIdx na i else pure False++-- | Bottom edge of the table pane: from the first header button, walk up to+-- the enclosing panel and return its bottom Y.+tableBodyBottom :: Context -> IO Float+tableBodyBottom ctx = do+  let na = ctxNodeArena ctx+      walkUp i+        | i < 0 = pure 0+        | otherwise = do+            nt <- getNodeType na i+            if nt /= NodePanel+              then getParent na i >>= walkUp+              else (\(Rect _ py _ ph) -> py + ph) <$> getNodeRect na i+  findNodeM na (isHeaderButton na) >>= maybe (pure 0) walkUp++-- | The body (unfrozen) v-scroller's node: a Column-direction 2D scroller+-- with style bits "both policies Auto, clamp set".+bodyNode :: Context -> IO (Maybe NodeIdx)+bodyNode ctx = findNodeM na $ \i -> do+  nt <- getNodeType na i+  d <- getDirection na i+  si <- getStyleIdx na i+  pure (nt == NodeScrollContainer && d == DirColumn && si .&. 63 == 0 && si .&. 64 /= 0)+  where+    na = ctxNodeArena ctx++bodyScrollerRect :: Context -> IO (Maybe Rect)+bodyScrollerRect ctx = traverse (getNodeRect (ctxNodeArena ctx)) =<< bodyNode ctx++bodyWid :: Context -> IO (Maybe WidgetId)+bodyWid ctx = traverse (getWidgetId (ctxNodeArena ctx)) =<< bodyNode ctx++-- | The body scroller's 2D offset.+bodyOffset :: Context -> IO V2+bodyOffset ctx = maybe (pure (V2 0 0)) (getScrollOffset2DIO ctx) =<< bodyWid ctx++-- | The body scroller's published metrics.+bodyMetrics :: Context -> IO (Maybe ScrollMetrics)+bodyMetrics ctx = maybe (pure Nothing) (getScrollMetricsIO ctx) =<< bodyWid ctx++-- | At the end of a sideways scroll the last column clears the vertical+-- bar's lane, which the reachable range counts. Header and cells move as one.+runTableHBarReachTest :: Context -> IORef Int -> IO ()+runTableHBarReachTest ctx failed = do+  let inp0 = (withInput 700 320) {inputMousePos = V2 300 160}+      ui = tableOf (wideCols False) (fixedH 200) scrollCols scrollRows+      na = ctxNodeArena ctx+  _ <- warmup2 ctx inp0 ui+  assertJustM failed (bodyNode ctx) $ \i -> do+    body@(Rect bx _ bw _) <- getNodeRect na i+    contentW <- getScrollContentW na i+    assertGt failed contentW bw+    replicateM_ 20 (runFrame ctx inp0 {inputMousePos = spanCenter body, inputScroll = V2 50 0} ui)+    V2 offX _ <- bodyOffset ctx+    assertGt failed offX (contentW - bw)+    assertJustM failed (listToMaybe . reverse <$> headerButtonRects ctx) $ \(Rect hx _ hw _) -> do+      assert failed (hx + hw <= bx + bw + 0.5)+      assertGt failed (hx + hw) (bx + bw - 24)+    ss <- collectTextSpans ctx+    let xOf needle = listToMaybe [rectX r | (r, t, _, _, _) <- ss, needle `T.isInfixOf` t]+    assertJust failed ((,) <$> xOf "Value" <*> xOf "val-") $ \(headerX, cellX) ->+      assert failed (abs (headerX - cellX) <= 1)++-- | Two 500px columns: squeezed or not.+wideCols :: Bool -> TableConfig+wideCols squeeze = defaultTableConfig {tableColSizes = [ColFixed 500, ColFixed 500], tableSqueeze = squeeze}++-- | 'tableSqueeze': fixed columns too wide for the body compress from the+-- first frame, none under the floor, until two floors and the rule no longer+-- fit. A leading stretch column stays visible, with no vertical bar when the+-- rows fit, and in a pane grid split the table clips to its pane, leaving+-- both dividers grabbable.+runTableSqueezeTest :: Context -> IORef Int -> IO ()+runTableSqueezeTest ctx failed = do+  let ui = tableOf (wideCols True) (fixedH 200) scrollCols scrollRows+      inp0 = (withInput 700 320) {inputMousePos = V2 300 160}+      rangeX c = fmap (v2X . scrollRange) <$> bodyMetrics c+  _ <- runFrame ctx inp0 ui+  -- The first frame already has the squeezed widths.+  assertEq failed 2 . length =<< headerButtonRects ctx+  assert failed . all ((<= 351) . rectW) =<< headerButtonRects ctx+  _ <- warmup2 ctx inp0 ui+  assertJustM failed (bodyScrollerRect ctx) $ \(Rect _ _ bw _) -> do+    assertEq failed (Just 0) =<< rangeX ctx+    -- The split leaves room for the vertical bar's lane, as the rows+    -- overflow, so each half is a little under half the body.+    hdrs <- headerButtonRects ctx+    assert failed (all (\r -> rectW r > bw / 2 - 12 && rectW r <= bw / 2 + 1) hdrs)+  tiny <- newContext+  _ <- warmup2 tiny ((withInput 74 120) {inputMousePos = V2 30 60}) ui+  assertJustM failed (rangeX tiny) $ \r -> assertGt failed r 0+  let cell txt = cellSort txt (cellWidget (rowWith (tight . fillW . fillH . alignMiddle) (labelWith fillW txt)))+      squeezed = defaultTableConfig {tableColSizes = suspectSizes, tableSqueeze = True}+      suspects layout n = tableOf squeezed layout (suspectCols cell) (suspectRows n)+      inPane = columnWith (fillW . gap 8) $ do+        labelWith (fontSizeScale 0.92) "Header above table"+        suspects (maxH (9 * 29 + 6)) 4+  forM_ [300, 380, 440] $ \winW -> do+    c <- newContext+    let c15 = withFontMetrics c ((ctxFontMetrics c) {fmLineHeight = 20, fmAscent = 15})+    _ <- warmup2 c15 ((withInput winW 360) {inputMousePos = V2 100 100}) inPane+    hdrs <- headerButtonRects c15+    assertEq failed 4 (length hdrs)+    assert failed (all ((> 39.5) . rectW) hdrs)+    assertJustM failed (bodyMetrics c15) $ \sm -> assertEq failed (V2 0 0) (scrollRange sm)+  -- Panes 2 (the table) and 3 below pane 1, as in stronghead's heap pane.+  pg <- newContext+  let heapTree = Split 100 AxisH 0.5 (Pane 1) (Split 101 AxisV 0.5 (Pane 2) (Pane 3))+      pane pid _ = PaneView "P" True <$ if pid == 2 then suspects (grow . tight) 30 else label "other"+      gridCfg = defaultPaneGridConfig {pgLayout = tight . fillW . fillH, pgMinSize = 40, pgSpacing = 4}+      heapPane = columnWith (tight . fillW . fillH) $+        paneGrid gridCfg {pgTree = InitialTree (Just heapTree), pgViewPane = pane}+      topOf = map (round . rectY) . take 1+  runSim pg failed ((withInput 800 600) {inputMousePos = V2 100 100}) heapPane $ do+    before <- headers+    checkEq (4, [308 :: Int]) (length before, topOf before)+    -- The vertical divider (x 400, y 450) left to x 300, then the horizontal+    -- one (x 400, y 300) down to y 400.+    _ <- drag (at 400 450) (at 300 450) 1 >> settle+    _ <- drag (at 400 300) (at 400 400) 1 >> settle+    after <- headers+    checkEq (4, [408]) (length after, topOf after)+    check (all ((> 39.5) . rectW) after)+    check (all (\r -> rectX r + rectW r <= 302) (take 1 (reverse after)))++runTableSortKeysBareTest :: Context -> IORef Int -> IO ()+runTableSortKeysBareTest ctx failed = do+  let nanVal = 0 / 0 :: Double+      numRows =+        [ ("p100" :: Text, 100.2 :: Double, 42 :: Int)+        , ("n2", -2.0, -3)+        , ("nan", nanVal, 999)+        , ("p9", 9.5, 7)+        , ("n12", -12.5, -50)+        , ("z0", 0.0, 0)+        ]+      cols =+        headed "Id" (\(k, _, _) -> textCell k)+          <> headed "Num" (\(_, d, _) -> cellSortNum d (textCell (T.pack (show d))))+          <> headed "Int" (\(_, _, n) -> cellSortInt n (textCell (T.pack (show n))))+  sortVar <- newVar (SortCol 1 SortAsc)+  let bareCfg = defaultTableConfig {tableBare = True}+      ui = column (tableConfigured bareCfg (fixedWH 360 240) "nums" cols numRows sortVar)+  _ <- warmup2 ctx (withInputOff 400 280) ui+  ss <- collectTextSpans ctx+  let orderOf names = [t | (_, t, _, _, _) <- ss, t `elem` names]+      rowIds = ["p100", "n2", "nan", "p9", "n12", "z0"]+  assertEq failed ["n12", "n2", "z0", "p9", "p100", "nan"] (orderOf rowIds)+  writeVarIO sortVar (SortCol 2 SortDesc)+  _ <- warmup2 ctx (withInputOff 400 280) ui+  ss2 <- collectTextSpans ctx+  assertEq failed ["nan", "p100", "p9", "z0", "n2", "n12"] [t | (_, t, _, _, _) <- ss2, t `elem` rowIds]
test/integration/Cases/Tabs.hs view
@@ -1,388 +1,441 @@-module Cases.Tabs-  ( runTabsClosableTest-  , runTabsDisabledTest-  , runTabsDamageTest-  , runTabsEmitTest-  , runTabsLazinessTest-  , runTabsScrollTest-  , runTabsStatePersistenceTest-  , runPanelBodySwapDamageTest-  , runTabResponseForwardingTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Tabs (tests) where -import Control.Monad (forM, forM_, replicateM)-import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Spec+import Data.Hashable (Hashable (..)) import Data.Maybe (isJust) import Data.Text qualified as T-import Data.Sequence qualified as Seq-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, run2Frames, withInput)-import NanoUI.Testing.Harness-  ( assertSpansHas-  , clickPair-  , drawQuads-  , hasText-  , keyInp-  , runClick-  , spanCenter-  , warmup2-  , withInputOff+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena+  ( NodeArena+  , NodeIdx+  , arenaCount+  , findNodeM+  , getNodeFontSize+  , getNodeRect+  , getParent+  , getText+  , getWidgetId   )-import NanoUI.Context (Context (..))-import NanoUI.Emit qualified as Emit-import NanoUI.Layout.Arena (arenaCount, findNodeM, getRect, getText, getWidgetId)+import NanoUI.Testing.Sim +tests :: [Spec]+tests =+  [ spec "tabs-scroll" runTabsScrollTest+  , simSpec "tabs-scroll-close-button" 900 120 closeButtonsUi tabsScrollCloseButton+  , simSpec "tabs-strip-in-page" 240 120 stripInPageUi tabsStripInPage+  , spec "tabs-bodies" runTabsBodiesTest+  , spec "tabs-keyed-reorder-state" runTabsKeyedReorderTest+  , spec "tabs-missing-key" runTabsMissingKeyTest+  , simSpec "tabs-close" 300 100 closingUi tabsClose+  , spec "tabs-disabled" runTabsDisabledTest+  , spec "tabs-contained-body-damage" runTabsContainedBodyDamageTest+  , spec "panel-body-swap-damage" runPanelBodySwapDamageTest+  , spec "tabs-badge-size" runTabsBadgeSizeTest+  , spec "tabs-drag-lifecycle" runTabDragLifecycleTest+  , spec "drag-escape-ownership" runDragEscapeOwnershipTest+  , spec "tabs-drag-reorder" runTabDragReorderTest+  , spec "tabs-drop-bounds" runTabsDropBoundsTest+  ]+ data DummyTab = TabA | TabB | TabC-  deriving (Eq, Show)+  deriving (Eq, Show, Enum) -fullWindowRect :: Input -> Rect-fullWindowRect inp =-  let Size w h = inputWindowSize inp-   in Rect 0 0 w h+instance Hashable DummyTab where+  hashWithSalt salt = hashWithSalt salt . fromEnum --- Content replacement inside a floating window must repaint every pixel of--- the new body: a clip that skipped any incoming row would leave the pane--- rendering stale pixels from the previous body ("ghosting"). The stable--- content slot and the incoming key rects (diffNew) must together cover all--- five rows.-runPanelBodySwapDamageTest :: Context -> IORef Int -> IO ()-runPanelBodySwapDamageTest ctx failed = do-  let inp0 = withInput 400 300-      uiA = window True "TabWin" (columnWith (fixedH 300) (label "WIDE BODY ROW ONE"))-      uiB = window True "TabWin" (columnWith (fixedH 300) (column (replicateM 5 (label "row line") >> pure ())))-  _ <- warmup2 ctx inp0 uiA-  _ <- runFrame ctx inp0 uiA-  _ <- takeDamage ctx-  _ <- runFrame ctx inp0 uiB-  dmg <- takeDamage ctx-  assert failed (not (damageIsEmpty dmg))-  let dmgR = case dmg of-        DamageFull -> fullWindowRect inp0-        DamageClip r -> r-      Rect ddx ddy ddw ddh = dmgR-  spans <- collectOverlayTextSpans ctx inp0-  let rows = [(r, t) | (r, t, _, _, _) <- spans, "row line" `T.isInfixOf` t]-  assert failed (length rows == 5)-  forM_ rows $ \(Rect rx ry rw rh, _) -> do-    assert failed (rx >= ddx && ry >= ddy && rx + rw <= ddx + ddw && ry + rh <= ddy + ddh)+-- | Headers that overflow a 240px strip.+overflowLabels :: [T.Text]+overflowLabels = ["Controls", "Graphics", "Typography", "Diagnostics", "LongestTabName"] -runTabsLazinessTest :: Context -> IORef Int -> IO ()-runTabsLazinessTest ctx failed = do-  evalCountA <- newIORef (0 :: Int)-  evalCountB <- newIORef (0 :: Int)-  evalCountC <- newIORef (0 :: Int)-  let inp = withInput 200 100-      ui = tabs TabB $ Seq.fromList-        [ tab TabA "A" (uiIO (modifyIORef' evalCountA (+ 1)) >> label "Body A")-        , tab TabB "B" (uiIO (modifyIORef' evalCountB (+ 1)) >> label "Body B")-        , tab TabC "C" (uiIO (modifyIORef' evalCountC (+ 1)) >> label "Body C")-        ]-  _ <- runFrame ctx inp ui-  cntA <- readIORef evalCountA-  cntB <- readIORef evalCountB-  cntC <- readIORef evalCountC-  assertEq failed cntA 0-  assertEq failed cntB 1-  assertEq failed cntC 0+-- | A strip of @labels@ keyed by @keys@, all plain tabs.+strip :: Var Int -> [Int] -> [T.Text] -> NanoUI (TabResponse Int)+strip active keys labels = tabBar' active [tab k l () | (k, l) <- zip keys labels] -data TabMsg = MsgSelect DummyTab | MsgClose DummyTab-  deriving (Eq, Show)+-- | What @get@ reads off each node whose text is @txt@, in arena order.+nodesTexted :: T.Text -> (NodeArena -> NodeIdx -> IO b) -> Sim a [b]+nodesTexted txt get = onContext $ \ctx -> do+  let na = ctxNodeArena ctx+  n <- arenaCount na+  filterM (fmap (== txt) . getText na) [0 .. n - 1] >>= mapM (get na) -runTabsEmitTest :: Context -> IORef Int -> IO ()-runTabsEmitTest ctx failed = do-  let inp0 = withInput 300 100-      ui curTab = Emit.tabs curTab-        [ tab TabA "Alpha" (label "Body A")-        , tab TabB "Beta" (label "Body B")-        ]-        MsgSelect-  _ <- runFrame ctx inp0 (ui TabA)-  spans <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans, "Beta" `T.isInfixOf` txt] of-    (r : _) -> do-      let (press, release) = clickPair inp0 (spanCenter r)-      _ <- runFrame ctx press (ui TabA)-      (_, msgs, _, _) <- runFrame ctx release (ui TabA)-      assertEq failed (decodeMessages msgs :: [TabMsg]) [MsgSelect TabB]-    [] -> assert failed False+-- | The close buttons' rects, in order.+closeRects :: Sim a [Rect]+closeRects = nodesTexted "\215" getNodeRect --- Composite responses expose every flag of their widget response--- (regression: TabResponse dropped respSubmitted).-runTabResponseForwardingTest :: Context -> IORef Int -> IO ()-runTabResponseForwardingTest _ failed = do-  let inner = mempty {rawRespSubmitted = True, rawRespRightPressed = True, rawRespChanged = True}-      tabResp = TabResponse inner Nothing TabA-      tableResp = TableResponse inner (SortCol 0 SortAsc) [] mempty-  assert failed (respSubmitted tabResp && respRightPressed tabResp && respChanged tabResp)-  assert failed (respSubmitted tableResp && respRightPressed tableResp && respChanged tableResp)+-- | Whether the strip's paging arrows show.+hasArrows :: Sim a Bool+hasArrows = any (\(_, t, _, _, _) -> T.any (`elem` ['\8249', '\8250']) t) <$> spans -runTabsClosableTest :: Context -> IORef Int -> IO ()-runTabsClosableTest ctx failed = do-  let inp0 = withInput 300 100-      ui curTab = tabs' curTab-        [ closableTab TabA "Alpha" (label "Body A")-        , closableTab TabB "Beta" (label "Body B")-        ]-  _ <- runFrame ctx inp0 (ui TabA)-  mClose <- findCloseButtonRect ctx-  case mClose of-    Just r -> do-      tResp <- runClick ctx inp0 (ui TabA) (spanCenter r)-      assertEq failed (tabClosed tResp) (Just TabA)-      assertEq failed (tabActive tResp) TabA-    Nothing -> assert failed False+-- | The first span holding @ch@.+arrowRect :: Char -> Sim a Rect+arrowRect ch = do+  found : _ <- (\ss -> [r | (r, t, _, _, _) <- ss, T.any (== ch) t]) <$> spans+  pure found -findCloseButtonRect :: Context -> IO (Maybe Rect)-findCloseButtonRect ctx = do-  let na = ctxNodeArena ctx-  found <- findNodeM na (fmap ("\215" `T.isInfixOf`) . getText na)-  forM found $ \i -> do-    (x, y, w, h) <- getRect na i-    pure (Rect x y w h)+-- | A too-wide strip scrolls, paged by its arrows, either wheel (clamped) and+-- a fraction of a notch, with no well or bar behind the headers. The arrows+-- go once the headers fit the bar, and a tab selected through the Var, or+-- appended and selected at once, comes into view.+runTabsScrollTest :: Context -> IORef Int -> IO ()+runTabsScrollTest ctx failed = do+  labelsRef <- newIORef overflowLabels+  active <- newVar 0+  let ui = column $ do+        _ <- strip active [0 ..] =<< liftIO (readIORef labelsRef)+        label "Below"+      setLabels = liftIO . writeIORef labelsRef+  runSim ctx failed (withInput 900 120) ui $ do+    mapM_ (check <=< textShown) overflowLabels+    check . not =<< hasArrows+    [Rect x0 _ _ _] <- nodesTexted "Controls" getNodeRect+    [Rect lx _ lw _] <- nodesTexted "LongestTabName" getNodeRect+    -- The frame a strip first measures an overflow publishes its range. That+    -- is layout, not a scroll: the resize still repaints the whole window.+    modifyInput (\i -> i {inputWindowSize = Size 240 120})+    _ <- frame+    checkEq DamageFull =<< frameDamage+    _ <- settle+    check =<< textShown "Controls"+    check . not =<< textShown "LongestTabName"+    theme <- liftIO (readIORef (ctxTheme ctx))+    inp <- getInput+    (_, dd, _) <- liftIO (run2Frames ctx inp ui)+    quads <- liftIO (drawQuads dd)+    let well = themeInput theme+        forbidden =+          styleBg well : styleBorder well : map (\f -> f well theme) [scrollBarTrackColor, scrollBarThumbColor]+    check (null [c | (r, c) <- quads, isJust (rectIntersect r (Rect 0 0 240 34)), c `elem` forbidden])+    -- The right arrow is pinned to the bar's far edge. Paging repaints the+    -- left one, whose muted look no rect or text change covers.+    left <- arrowRect '\8249'+    right <- arrowRect '\8250'+    checkGt (rectX right + rectW right) 200+    _ <- click (Within right) >> frame+    check . not =<< textShown "Controls"+    check . (`damageCovers` left) =<< frameDamage+    _ <- click (Within left) >> frame+    check =<< textShown "Controls"+    controls <- rectOf "Controls"+    _ <- wheel (Within controls) (V2 0 0.3) >> frame+    scrolled <- rectOf "Controls"+    checkLt (rectX scrolled) (rectX controls)+    forM_ [(V2 0 20, False), (V2 10 0, False), (V2 (-100) 0, True), (V2 (-100) 0, True)] $ \(d, shown) -> do+      _ <- wheel (Within controls) d >> frame+      checkEq shown =<< textShown "Controls"+    -- One header fits the window, two would not fit between the arrows.+    setLabels ["Controls"] >> void settle+    check =<< textShown "Controls"+    check . not =<< hasArrows+    setLabels overflowLabels >> void settle+    check =<< hasArrows+    check . not =<< textShown "LongestTabName"+    -- The headers' extent and the floatingWindow's padding on both sides: less+    -- spare room than the two arrows take.+    _ <- resize (lx + lw + x0 + 10) 120+    mapM_ (check <=< textShown) overflowLabels+    check . not =<< hasArrows+    _ <- resize 240 120+    forM_ [(4, "LongestTabName"), (0, "Controls")] $ \(k, l) -> do+      writeV active k+      check =<< (settle >> textShown l)+    setLabels (overflowLabels ++ ["Appended"]) >> writeV active 5+    check =<< (settle >> textShown "Appended") --- The public disabled flag covers both the header and its close control,--- including retained keyboard focus when an enabled tab becomes disabled.-runTabsDisabledTest :: Context -> IORef Int -> IO ()-runTabsDisabledTest _ failed = forM_ [TabTop, TabLeft] $ \orientation -> do-  ctx <- newContext-  let inp = withInputOff 400 240-      ui disabled = tabsConfigured' defaultTabsConfig {tabsOrientation = orientation} TabA-        [ (closableTab TabB "Disabled" (label "Body B")) {tabDisabled = disabled}-        , tab TabA "Enabled" (label "Body A")-        ]-      check response = do-        assertEq failed (tabActive response) TabA-        assertEq failed (tabClosed response) Nothing-        assert failed (not (respClicked response) && not (respChanged response))-  _ <- warmup2 ctx inp (ui False)-  let arena = ctxNodeArena ctx-  n <- arenaCount arena-  headers <- mapM (\i -> (,) <$> getText arena i <*> getWidgetId arena i) [0 .. n - 1]-  _ <- warmup2 ctx inp (ui True)-  spans <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans, txt == "Disabled"] of-    r : _ -> check =<< runClick ctx inp (ui True) (spanCenter r)-    [] -> assert failed False-  closeRect <- findCloseButtonRect ctx-  case closeRect of-    Just r -> check =<< runClick ctx inp (ui True) (spanCenter r)-    Nothing -> assert failed False-  forM_ [wid | (txt, wid) <- headers, txt == "Disabled" || txt == "\215"] $ \wid -> do-    writeIORef (ctxFocusId ctx) wid-    (result, _, _, _) <- runFrame ctx (keyInp KeyEnter inp) (ui True)-    check result-  -- Re-enabling the same header preserves its identity and restores activation.-  _ <- warmup2 ctx inp (ui False)-  spansEnabled <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spansEnabled, txt == "Disabled"] of-    r : _ -> do-      response <- runClick ctx inp (ui False) (spanCenter r)-      assertEq failed (tabActive response) TabB-    [] -> assert failed False+-- | A strip whose last close button runs past the bar overflows, though every+-- header's main button fits: the range counts each header's close button.+tabsScrollCloseButton :: Sim (TabResponse Int) ()+tabsScrollCloseButton = do+  [Rect x0 _ _ _] <- nodesTexted "Controls" getNodeRect+  closes <- closeRects+  checkEq 3 (length closes)+  -- The last close button's right edge, less a little, and the floatingWindow's+  -- right padding: only that button runs past the bar.+  _ <- resize (maximum [rectX r + rectW r | r <- closes] - 4 + x0) 120+  check =<< hasArrows -runTabsStatePersistenceTest :: Context -> IORef Int -> IO ()-runTabsStatePersistenceTest ctx failed = do-  let inp0 = withInput 300 100-      ui curTab = tabs curTab-        [ tab TabA "A" $-            withKey ("tab-a" :: T.Text) $-              withKey ("flag" :: T.Text) $ do-                (flag, setFlag) <- useFlag False-                whenM (button "ToggleA") (setFlag (not flag))-                label (if flag then "FlagIsOn" else "FlagIsOff")-        , tab TabB "B" (label "OtherTab")-        ]-  _ <- runFrame ctx inp0 (ui TabA)-  spans0 <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans0, "ToggleA" `T.isInfixOf` txt] of-    (r : _) -> do-      _ <- runClick ctx inp0 (ui TabA) (spanCenter r)-      _ <- runFrame ctx inp0 (ui TabA)-      spans1 <- collectTextSpans ctx-      assertSpansHas failed "FlagIsOn" spans1+closeButtonsUi :: NanoUI (TabResponse Int)+closeButtonsUi =+  tabBar' (constVar 0) (zipWith (\i l -> closableTab i l ()) [0 ..] ["Controls", "Graphics", "Typography"]) -      _ <- runFrame ctx inp0 (ui TabB)-      spans2 <- collectTextSpans ctx-      assertSpansHas failed "OtherTab" spans2-      assert failed (not (hasText "FlagIsOn" spans2))+-- | A strip brings its active tab into view whatever its key, 0 too, and the+-- vertical wheel over it pages the strip alone, not the page round it.+tabsStripInPage :: Sim (WidgetId, ()) ()+tabsStripInPage = do+  (page, _) <- result+  longest <- rectOf "LongestTabName"+  forM_ [(V2 0 (-20), True), (V2 0 20, False)] $ \(d, first) -> do+    _ <- wheel (Within longest) d >> frame+    checkEq first =<< textShown "Controls"+    checkEq 0 =<< scrollOffsetOf page -      _ <- runFrame ctx inp0 (ui TabA)-      spans3 <- collectTextSpans ctx-      assertSpansHas failed "FlagIsOn" spans3-    [] -> assert failed False+stripInPageUi :: NanoUI (WidgetId, ())+stripInPageUi = scrollArea (tight . grow) $ do+  _ <- strip (constVar 0) [4, 3 .. 0] overflowLabels+  replicateM_ 20 (label "line") -runTabsDamageTest :: Context -> IORef Int -> IO ()-runTabsDamageTest ctx failed = do-  let inp0 = withInputOff 300 100-      ui curTab = tabs' curTab-        [ tab TabA "Alpha" (label "Body A with some text")-        , tab TabB "Beta" (label "Body B different widgets")-        ]-      covers dmg (Rect rx ry rw rh) = case dmg of-        DamageFull -> True-        DamageClip (Rect dx dy dw dh) -> rx >= dx && ry >= dy && rx + rw <= dx + dw && ry + rh <= dy + dh-  _ <- runFrame ctx inp0 (ui TabA)-  _ <- takeDamage ctx-  _ <- runFrame ctx inp0 (ui TabA)-  dIdle <- takeDamage ctx-  assert failed (dIdle /= DamageFull)-  spansIdle <- collectTextSpans ctx-  assertSpansHas failed "Body A" spansIdle+-- | Only the active body runs. Bodies keep separate state, even at the same+-- position, while hidden too. A header click switches tabs and repaints the+-- new body in its own frame, leaving the frames after it nothing whole.+runTabsBodiesTest :: Context -> IORef Int -> IO ()+runTabsBodiesTest ctx failed = do+  ran <- newIORef []+  active <- newVar TabA+  let body name = do+        liftIO (modifyIORef' ran (name :))+        flagVar <- useVar False+        flag <- readVar flagVar+        whenM (button ("Toggle" <> name)) (writeVar flagVar (not flag))+        label (name <> if flag then "On" else "Off")+      ui = tabs' active [tab TabA "A" (body "A"), tab TabB "B" (body "B"), tab TabC "C" (body "C")]+  runSim ctx failed (withInputOff 300 100) ui $ do+    check . all (== "A") =<< liftIO (readIORef ran)+    check . (/= DamageFull) =<< frameDamage+    _ <- click "ToggleA" >> settle+    expect "AOn"+    switched <- click "B"+    check (respChanged switched && tabActive switched == TabB)+    expect "BOff"+    expectNot "AOn"+    bodyB <- rectOf "BOff"+    check . (`damageCovers` bodyB) =<< frameDamage+    replicateM_ 2 (frame >> (check . (/= DamageFull) =<< frameDamage))+    _ <- click "A" >> settle+    expect "AOn" -  spans <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans, "Beta" `T.isInfixOf` txt] of-    (beta : _) -> do-      let (press, release) = clickPair inp0 (spanCenter beta)-      _ <- runFrame ctx press (ui TabA)-      (resp, _, _, _) <- runFrame ctx release (ui TabA)-      assert failed (respChanged resp && tabActive resp == TabB)-      spansSwitch <- collectTextSpans ctx-      assertSpansHas failed "Body B" spansSwitch-      assert failed (not (hasText "Body A" spansSwitch))-      let bodyB = [r | (r, txt, _, _, _) <- spansSwitch, "Body B" `T.isInfixOf` txt]-      dSwitch <- takeDamage ctx-      assert failed (not (null bodyB) && all (covers dSwitch) bodyB)+data Seen = Seen Int (Var Int) WidgetId -      _ <- runFrame ctx inp0 (ui TabB)-      dTabB <- takeDamage ctx-      assert failed (all (covers dTabB) bodyB)+-- | Header focus and body-local state follow the key, not the list position.+runTabsKeyedReorderTest :: Context -> IORef Int -> IO ()+runTabsKeyedReorderTest ctx failed = do+  seen <- newIORef Nothing+  let inp = withInputOff 500 250+      body key = do+        nVar <- useVar (0 :: Int)+        n <- readVar nVar+        (field, _) <- withValue (T.pack (show key)) textInput'+        liftIO (writeIORef seen (Just (Seen n nVar (respId field))))+      ui active order = tabs' (constVar active) [tab key (T.pack (show key)) (body key) | key <- order]+      readBody = atomicModifyIORef' seen (Nothing,) >>= maybe (fail "tab body did not run") pure+  original <- warmup2 ctx inp (ui TabB [TabA, TabB, TabC])+  Seen _ nVar fieldId <- readBody+  runNanoUI ctx inp (writeVar nVar 7)+  setFocus ctx fieldId+  forM_ [[TabC, TabA, TabB], [TabB, TabC], [TabC, TabB]] $ \order -> do+    moved <- warmup2 ctx inp (ui TabB order)+    Seen n _ fieldId' <- readBody+    assertEq failed (7, fieldId) (n, fieldId')+    assertEq failed fieldId =<< getFocusId ctx+    forM_ order $ \key ->+      assertEq failed (respId <$> lookup key (tabHeaders original)) (respId <$> lookup key (tabHeaders moved))+  forM_ [(TabC, 0), (TabB, 7)] $ \(key, want) -> do+    _ <- warmup2 ctx inp (ui key [TabC, TabB])+    Seen n _ _ <- readBody+    assertEq failed want n -      _ <- runFrame ctx inp0 (ui TabB)-      dSettled <- takeDamage ctx-      assert failed (dSettled /= DamageFull)-    [] -> assert failed False+-- | An active key no tab has shows the first tab, its header and body alike,+-- and reports it.+runTabsMissingKeyTest :: Context -> IORef Int -> IO ()+runTabsMissingKeyTest ctx failed = do+  active <- newVar (3 :: Int)+  let ui = tabs' active [tab k l (label ("Body " <> l)) | (k, l) <- [(1, "one"), (2, "two")]]+  r <- warmup2 ctx (withInputOff 300 100) ui+  assertEq failed 1 (tabActive r)+  assertEq failed 1 =<< readVarIO active+  assertEq failed [1, 0] =<< buttonValues ctx+  assert failed . hasText "Body one" =<< collectTextSpans ctx --- Too-wide tab strips scroll instead of overflowing. The framework scroll--- container owns the clip, the offset and the damage; the strip adds--- chevron buttons on the left and right and pages the same offset with--- them. Acceptance: scrolling left and right works (buttons, up/down wheel--- notches mapped onto the horizontal offset) as well as left+right--- (horizontal wheel, applied by the framework scroller itself); the tab--- headers look exactly as they did before the strip could scroll (no--- scroller well behind them); and no scrollbar appears.-runTabsScrollTest :: Context -> IORef Int -> IO ()-runTabsScrollTest _ failed = do-  let labels = ["Controls", "Graphics", "Typography", "Diagnostics", "LongestTabName"]-      mkTabs cur = tabBar cur [tab (i :: Int) l () | (i, l) <- zip [0 ..] labels]-      arrowRect ctx ch = do-        spans <- collectTextSpans ctx-        pure [r | (r, t, _, _, _) <- spans, T.any (== ch) t]-      chevrons = ['\8250', '\8249']+-- | A close button reports its tab closed and keeps the active one. A click+-- just left of one selects its tab: the close button does not take the press.+tabsClose :: Sim (TabResponse DummyTab) ()+tabsClose = do+  [closeA, Rect bx by _ bh] <- closeRects+  closed <- click (Within closeA)+  checkEq (Just TabA, TabA) (tabClosed closed, tabActive closed)+  beside <- click (at (bx - 3) (by + bh / 2))+  checkEq (Nothing, TabB) (tabClosed beside, tabActive beside) -  -- Wide bar: everything fits and no arrows are drawn.-  wide <- newContext-  let wideInp = withInput 900 120-  _ <- runFrame wide wideInp (mkTabs 0)-  _ <- runFrame wide wideInp (mkTabs 0)-  wideSpans <- collectTextSpans wide-  forM_ labels $ \l -> assert failed (hasText l wideSpans)-  assert failed (not (T.any (`elem` chevrons) (T.concat [t | (_, t, _, _, _) <- wideSpans])))+closingUi :: NanoUI (TabResponse DummyTab)+closingUi = tabs' (constVar TabA) [closableTab k (T.pack (show k)) (label "Body") | k <- [TabA, TabB]] +-- | A disabled header ignores clicks on it and its close control, and Enter+-- with focus kept from before; re-enabled, it activates again.+runTabsDisabledTest :: Context -> IORef Int -> IO ()+runTabsDisabledTest _ failed = forM_ [TabTop, TabLeft] $ \orientation -> do   ctx <- newContext-  let inp = withInput 240 120-  _ <- runFrame ctx inp (mkTabs 0)-  _ <- runFrame ctx inp (mkTabs 0)-  -- The strip only pulls in its scroller once it has measured an overflow, so-  -- the arrow buttons show from the third frame on.-  _ <- runFrame ctx inp (mkTabs 0)-  spans0 <- collectTextSpans ctx-  assert failed (hasText "Controls" spans0)-  assert failed (not (hasText "LongestTabName" spans0))+  disabledRef <- newIORef False+  let ui = do+        disabled <- liftIO (readIORef disabledRef)+        tabsConfigured' defaultTabsConfig {tabsOrientation = orientation} (constVar TabA)+          [ (closableTab TabB "Disabled" (label "Body B")) {tabDisabled = disabled}+          , tab TabA "Enabled" (label "Body A")+          ]+      inert r = checkEq (TabA, Nothing, False, False) (tabActive r, tabClosed r, respClicked r, respChanged r)+      disable b = liftIO (writeIORef disabledRef b) >> void settle+  runSim ctx failed (withInputOff 400 240) ui $ do+    wids <- (++) <$> nodesTexted "Disabled" getWidgetId <*> nodesTexted "\215" getWidgetId+    checkEq 2 (length wids)+    disable True+    inert =<< click "Disabled"+    [close] <- closeRects+    inert =<< click (Within close)+    forM_ wids $ \wid -> do+      focusOn wid+      inert =<< pressKey KeyEnter+    disable False+    checkEq TabB . tabActive =<< click "Disabled" -  -- No scroller well: while the strip is scrollable it must not paint the-  -- input background, the input border, or any scrollbar track or thumb-  -- behind the headers. Only the tab buttons themselves (and the arrows)-  -- may paint in the bar. The checked region is the full window width and-  -- the bar's height (header 28 + 4 slack + 2 slop), derived from the input-  -- so a resize of the test window cannot silently shrink coverage.-  theme <- readIORef (ctxTheme ctx)-  (_, _, dd, _) <- run2Frames ctx inp (mkTabs 0)-  quads <- drawQuads dd-  let Size winW _ = inputWindowSize inp-      bar = Rect 0 0 winW 34-      inputSurface = themeInput theme-      forbidden =-        [ styleBg inputSurface-        , styleBorder inputSurface-        , scrollBarTrackColor inputSurface theme-        , scrollBarThumbColor inputSurface theme-        ]-      inBar = [(r, c) | (r, c) <- quads, isJust (rectIntersect r bar), c `elem` forbidden]-  assert failed (null inBar)+-- | A contained body that shrinks repaints where its own bottom border was.+runTabsContainedBodyDamageTest :: Context -> IORef Int -> IO ()+runTabsContainedBodyDamageTest ctx failed = do+  let inp0 = withInputOff 300 300+      ui txt = tabsConfigured' defaultTabsConfig {tabsStyle = TabContained} (constVar TabA)+        [tab TabA "Alpha" (labelWith fillW txt), tab TabB "Beta" (label "Body B")]+      long = T.unwords (replicate 30 "body")+      na = ctxNodeArena ctx+      -- The body is the column round the tab's label.+      bodyText = findNodeM na (fmap (`elem` [long, "body"]) . getText na)+      bodyRect = traverse (getNodeRect na <=< getParent na) =<< bodyText+  _ <- run2Frames ctx inp0 (ui long) >> runFrame ctx inp0 (ui long)+  mTall <- bodyRect+  _ <- runFrame ctx inp0 (ui "body")+  dShrink <- takeDamage ctx+  mShort <- bodyRect+  assertJust failed ((,) <$> mTall <*> mShort) $ \(tall, short) -> do+    assert failed (rectH short < rectH tall)+    assert failed (damageCovers dShrink tall) -  -- Left and right buttons page the strip; the right arrow is pinned to the-  -- bar's far edge rather than trailing the last visible tab.-  mRight <- arrowRect ctx '\8250'-  case mRight of-    (r : _) -> do-      assert failed (rectX r + rectW r > 200)-      _ <- runClick ctx inp (mkTabs 0) (spanCenter r)-      _ <- runFrame ctx inp (mkTabs 0)-      spans1 <- collectTextSpans ctx-      assert failed (not (hasText "Controls" spans1))-      mLeft <- arrowRect ctx '\8249'-      case mLeft of-        (left : _) -> do-          _ <- runClick ctx inp (mkTabs 0) (spanCenter left)-          _ <- runFrame ctx inp (mkTabs 0)-          spans2 <- collectTextSpans ctx-          assert failed (hasText "Controls" spans2)-        _ -> assert failed False-    _ -> assert failed False+-- | A body swapped inside a floating window repaints every row of the new+-- one, or stale pixels of the old body show through.+runPanelBodySwapDamageTest :: Context -> IORef Int -> IO ()+runPanelBodySwapDamageTest ctx failed = do+  let inp0 = withInput 400 300+      win body = floatingWindow' (constVar True) "TabWin" (columnWith (fixedH 300) body)+      uiA = win (label "WIDE BODY ROW ONE")+  _ <- run2Frames ctx inp0 uiA >> runFrame ctx inp0 uiA+  _ <- runFrame ctx inp0 (win (column (replicateM_ 5 (label "row line"))))+  dmg <- takeDamage ctx+  ss <- collectOverlayTextSpans ctx inp0+  let rows = [r | (r, t, _, _, _) <- ss, "row line" `T.isInfixOf` t]+  assertEq failed 5 (length rows)+  assert failed (not (damageIsEmpty dmg) && all (damageCovers dmg) rows) -  -- Wheel up/down over the bar pages the window too (the strip maps the-  -- notches onto the horizontal offset).-  spans3 <- collectTextSpans ctx-  case [r | (r, t, _, _, _) <- spans3, "Controls" `T.isInfixOf` t] of-    (Rect cx cy cw ch : _) -> do-      let wheelDown = inp {inputMousePos = spanCenter (Rect cx cy cw ch), inputScroll = V2 0 20}-      _ <- runFrame ctx wheelDown (mkTabs 0)-      _ <- runFrame ctx inp (mkTabs 0)-      spans4 <- collectTextSpans ctx-      assert failed (not (hasText "Controls" spans4))+-- | A badge is smaller than its header's text, whatever the base font size.+runTabsBadgeSizeTest :: Context -> IORef Int -> IO ()+runTabsBadgeSizeTest ctx0 failed = do+  let ctx = withFontSize ctx0 10+      na = ctxNodeArena ctx+  let inbox = (tab (1 :: Int) "Inbox" ()) {tabBadge = Just "3"}+  _ <- warmup2 ctx (withInputOff 300 100) (tabBar' (constVar 1) [inbox])+  badge <- findNodeM na (fmap (== "3") . getText na)+  assertJust failed badge $ \i -> assertEq failed (10 * 0.78) =<< getNodeFontSize na i -      -- Left+right wheel over the bar scrolls the same offset through the-      -- framework scroller. The vertical wheel pinned the offset at max, so-      -- wheeling right stays put (clamped at the end); wheeling left runs-      -- back to the start and re-shows the first tab, and further left-      -- notches clamp at zero instead of running past it. The deltas are-      -- coupled to the framework wheel step (scrollLineFor, 20px per notch-      -- on window hosts): V2 0 20 saturates at max, and +/-100 notches-      -- crosses the whole range regardless of the exact step.-      let wheelX d = inp {inputMousePos = spanCenter (Rect cx cy cw ch), inputScroll = V2 d 0}-      _ <- runFrame ctx (wheelX 10) (mkTabs 0)-      _ <- runFrame ctx inp (mkTabs 0)-      spans5 <- collectTextSpans ctx-      assert failed (not (hasText "Controls" spans5))-      _ <- runFrame ctx (wheelX (-100)) (mkTabs 0)-      _ <- runFrame ctx inp (mkTabs 0)-      spans6 <- collectTextSpans ctx-      assert failed (hasText "Controls" spans6)-      _ <- runFrame ctx (wheelX (-100)) (mkTabs 0)-      _ <- runFrame ctx inp (mkTabs 0)-      spans7 <- collectTextSpans ctx-      assert failed (hasText "Controls" spans7)-    _ -> assert failed False+-- | A header drag starts past the threshold, keeps its payload while the+-- headers reorder, and ends released or cancelled: by Escape, by a release+-- the window never saw, or by its source going away.+runTabDragLifecycleTest :: Context -> IORef Int -> IO ()+runTabDragLifecycleTest ctx failed = do+  dragHandle <- newDrag+  let inp = withInput 400 200+      ui order = do+        r <- tabBar' (constVar TabA) [tab k (T.pack (show k)) () | k <- order]+        (,) (tabHeaders r) <$> useDrag dragHandle (tabHeaders r)+      keys = [TabA, TabB, TabC]+      phase i order = fmap (\d -> (dragPayload d, dragPhase d)) . snd <$> evalUi ctx i (ui order)+  (_, first) : _ <- fst <$> warmup2 ctx inp (ui keys)+  let V2 x y = centerOf first+      down = pressAt inp (V2 x y)+      moved = holdAt down (V2 (x + 20) y)+  assertEq failed Nothing =<< phase down keys+  assertEq failed Nothing =<< phase (holdAt down (V2 (x + 3) y)) keys+  assertEq failed (Just (TabA, DragStarted)) =<< phase moved keys+  assertEq failed (Just (TabA, Dragging)) =<< phase moved [TabC, TabB, TabA]+  assertEq failed (Just (TabA, DragReleased)) =<< phase (releaseAt moved) keys+  assertEq failed Nothing =<< phase inp keys+  forM_ [(keyInp KeyEscape moved, keys), (inp, keys), (moved, [TabB, TabC])] $ \(cancel, remaining) -> do+    mapM_ (`phase` keys) [down, moved]+    assertEq failed (Just DragCancelled) . fmap snd =<< phase cancel remaining+    assertEq failed Nothing =<< phase (releaseAt moved) keys+    void (warmup2 ctx inp (ui keys)) -  -- Tab-list changes recompute the reachable range: shrinking back under-  -- the width drops the scroller and both arrows; growing past it again-  -- re-engages them and re-clips the tail. (One header fits the 240-wide-  -- window; two would still overflow the ~180px viewport between arrows.)-  let shortLabels = ["Controls"]-      mkShort cur = tabBar cur [tab (i :: Int) l () | (i, l) <- zip [0 ..] shortLabels]-  _ <- runFrame ctx inp (mkShort 0)-  _ <- runFrame ctx inp (mkShort 0)-  _ <- runFrame ctx inp (mkShort 0)-  spansS <- collectTextSpans ctx-  forM_ shortLabels $ \l -> assert failed (hasText l spansS)-  mRightS <- arrowRect ctx '\8250'-  mLeftS <- arrowRect ctx '\8249'-  assert failed (null mRightS && null mLeftS)-  _ <- runFrame ctx inp (mkTabs 0)-  _ <- runFrame ctx inp (mkTabs 0)-  _ <- runFrame ctx inp (mkTabs 0)-  spansG <- collectTextSpans ctx-  mRightG <- arrowRect ctx '\8250'-  assert failed (not (null mRightG))-  assert failed (not (hasText "LongestTabName" spansG))+-- | Escape taken before the drag sees it leaves the drag going; untaken, it+-- cancels the drag, and nothing after it sees the key, the dialog included.+runDragEscapeOwnershipTest :: Context -> IORef Int -> IO ()+runDragEscapeOwnershipTest ctx failed = do+  handle <- newDrag+  let inp = withInputOff 400 200+      ui takeFirst = modalPanel' (constVar True) $ do+        when takeFirst (void takeEscape)+        source <- button' "Drag"+        gesture <- useDrag handle [((), source)]+        later <- takeEscape+        pure (source, gesture, later)+  (_, body) <- warmup2 ctx inp (ui False)+  assertJust failed body $ \(source, _, _) -> do+    let p@(V2 x y) = centerOf source+        down = pressAt inp p+        moved = holdAt down (V2 (x + 15) y)+        escape = keyInp KeyEscape moved+        seen (_, gesture, later) = (dragPhase <$> gesture, later)+    mapM_ (\i -> evalUi ctx i (ui False)) [down, moved]+    assertEq failed (Just (Just Dragging, False)) . fmap seen . snd =<< evalUi ctx escape (ui True)+    (dialog, cancelled) <- evalUi ctx escape (ui False)+    assertEq failed (Just (Just DragCancelled, False)) (seen <$> cancelled)+    assertEq failed False (respClicked dialog)++-- | A close button and a disabled header start no drag. A header dropped on+-- the far edge of the last one moves there, on the release and not before.+runTabDragReorderTest :: Context -> IORef Int -> IO ()+runTabDragReorderTest ctx failed = do+  dragHandle <- newDrag+  orderRef <- newIORef [TabA, TabB, TabC]+  let header k = (if k == TabA then closableTab else tab) k (T.pack (show k)) ()+      ui = do+        order <- liftIO (readIORef orderRef)+        r <- tabBar' (constVar TabA) [(header k) {tabDisabled = k == TabC} | k <- order]+        gesture <- useDrag dragHandle (tabHeaders r)+        forM_ gesture $ \d -> when (dragPhase d == DragReleased) $ do+          let rest = filter ((/= dragPayload d) . fst) (tabHeaders r)+          forM_ (insertionIndex DragAxisX (tabStripRect r) (map (respRect . snd) rest) (dragAt d)) $ \i -> do+            let (before, after) = splitAt i (map fst rest)+            liftIO (writeIORef orderRef (before ++ dragPayload d : after))+        pure (r, gesture)+      currentOrder = liftIO (readIORef orderRef)+  runSim ctx failed (withInput 400 200) ui $ do+    [close] <- closeRects+    disabled <- rectOf "TabC"+    forM_ [close, disabled] $ \r -> do+      let V2 x y = spanCenter r+      _ <- press (Within r)+      checkEq Nothing . snd =<< moveTo (at (x + 20) y)+      release+    Just third <- lookup TabC . tabHeaders . fst <$> result+    let Rect x y w h = respRect third+    _ <- press "TabA"+    _ <- moveTo (at (x + w - 1) (y + h / 2))+    checkEq [TabA, TabB, TabC] =<< currentOrder+    _ <- release+    checkEq [TabB, TabC, TabA] =<< currentOrder+    checkEq [TabB, TabC, TabA] . map fst . tabHeaders . fst =<< frame++-- | A strip's drop bounds are where it is drawn: inside its padded panel, and+-- cut to the pane it is clipped to, in either orientation.+runTabsDropBoundsTest :: Context -> IORef Int -> IO ()+runTabsDropBoundsTest ctx failed = do+  let inp = withInput 400 200+      bar orientation n = tabBarConfigured' (TabsConfig TabUnderline orientation (pure ())) (constVar TabA) $+        take n [tab TabA "Alpha" (), tab TabB "Beta" (), tab TabC "Gamma" ()]+  r <- warmup2 ctx inp (panelWith (padAll 40 . fillW . fillH) (bar TabLeft 2))+  let bounds = tabStripRect r+  assert failed (rectX bounds >= 40 && rectY bounds >= 40)+  assertEq failed Nothing (insertionIndex DragAxisY bounds (map (respRect . snd) (tabHeaders r)) (V2 10 10))+  stripRect <- newIORef (Rect 0 0 0 0)+  forM_ [TabTop, TabLeft] $ \orientation -> do+    let pane _ _ = do+          s <- panelWith (fixedW 600) (bar orientation 3)+          liftIO (writeIORef stripRect (tabStripRect s))+          pure (PaneView "Tabs" False)+    c <- newContext+    _ <- warmup2 c inp (paneGrid defaultPaneGridConfig {pgLayout = fixedWH 200 60, pgViewPane = pane})+    Rect _ _ w h <- readIORef stripRect+    assert failed (w > 0 && w <= 200 && h > 0 && h <= 60)
+ test/integration/Cases/Tasks.hs view
@@ -0,0 +1,359 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Tasks (tests) where++import Spec+import Control.Concurrent (newEmptyMVar, putMVar, readMVar, takeMVar, threadDelay, tryPutMVar)+import Control.Exception (AsyncException (StackOverflow), ErrorCall, displayException, finally, onException, throwIO, try)+import Data.List (isInfixOf)+import Data.Function (fix)+import Data.Maybe (isJust)+import GHC.Conc (getUncaughtExceptionHandler, setUncaughtExceptionHandler)+import NanoUI.Internal.Context (Context (ctxWakeLoop), wakeFromThread)+import System.Timeout (timeout)++tests :: [Spec]+tests =+  [ spec "task-result-after-wake" runTaskResultTest+  , spec "task-key-change" runTaskKeyChangeTest+  , spec "task-starts" runTaskStartsTest+  , spec "task-lease" runTaskLeaseTest+  , spec "task-failure" runTaskFailureTest+  , spec "task-shutdown" runTaskShutdownTest+  , spec "burst-costs-one-frame" runBurstTest+  , spec "wake-delivery" runWakeDeliveryTest+  , spec "stream-lifecycle" runStreamLifecycleTest+  ]++inp :: Input+inp = withDelta 200 100 0.016++-- | Run a frame after each wake until the result passes @ok@. 'Nothing' if+-- two seconds pass without a wake.+frameUntil :: (Int -> IO Bool) -> Context -> NanoUI a -> (a -> Bool) -> IO (Maybe a)+frameUntil wait ctx ui ok = go (50 :: Int)+  where+    go n = do+      a <- evalUi ctx inp ui+      if ok a+        then pure (Just a)+        else do+          woke <- wait 2000000+          if woke && n > 0 then go (n - 1) else pure Nothing++-- | Whether the counter reaches @n@ within two seconds.+reaches :: IORef Int -> Int -> IO Bool+reaches ref n = isJust <$> timeout 2000000 (fix (\go -> readIORef ref >>= \v -> unless (v == n) (threadDelay 10000 >> go)))++tick :: IORef Int -> IO ()+tick ref = atomicModifyIORef' ref (\n -> (n + 1, ()))++-- | A job that sleeps until killed, an action that waits for it to start,+-- and a wait of up to @us@ for its kill. A job killed before its thread first+-- runs never runs its handler, so a test that kills a job at once must wait+-- for it to start.+sleeper :: IO (IO (), IO (), Int -> IO Bool)+sleeper = do+  started <- newEmptyMVar+  killed <- newEmptyMVar+  pure+    ( (void (tryPutMVar started ()) >> threadDelay 10000000) `onException` putMVar killed ()+    , takeMVar started+    , \us -> isJust <$> timeout us (takeMVar killed)+    )++-- | A box that shows @on@ only through its colour, which rect and text diffs+-- miss.+lamp :: Bool -> NanoUI ()+lamp on = box (fixedWH 20 20) (if on then colorRGBA 40 200 80 255 else colorRGBA 90 90 90 255)++-- | The next frame shows @v@ and requests no further frame.+settled :: (Eq a, Show a) => Context -> IORef Int -> NanoUI a -> a -> IO ()+settled ctx failed ui v = do+  (a, _, dirty) <- runFrame ctx inp ui+  assertEq failed (v, False) (a, dirty)++-- | The frame that picks up a job's result shows @v@ and repaints the widget+-- that shows it, not the whole window. The next frame is idle.+takesNews :: (Eq a, Show a) => Context -> IORef Int -> NanoUI a -> a -> IO ()+takesNews ctx failed ui v = do+  assertEq failed v =<< evalUi ctx inp ui+  assert failed . (\d -> d /= DamageFull && not (damageIsEmpty d)) =<< takeDamage ctx+  settled ctx failed ui v+  assert failed . damageIsEmpty =<< takeDamage ctx++-- | The hook returns 'Nothing' while the job runs. A running job neither+-- requests frames nor wakes the loop until it ends.+runTaskResultTest :: Context -> IORef Int -> IO ()+runTaskResultTest ctx failed = do+  job <- newTask+  wait <- newWakeSignal ctx+  gate <- newEmptyMVar+  let ui = useTask job ("answer" :: String) (takeMVar gate >> pure (42 :: Int)) >>= \a -> a <$ lamp (isJust a)+  _ <- warmup2 ctx inp ui+  settled ctx failed ui Nothing+  assertEq failed 0 =<< getWakeAt ctx+  _ <- wait 0+  assert failed . not =<< wait 50000+  putMVar gate ()+  assert failed =<< wait 2000000+  takesNews ctx failed ui (Just 42)++-- | A new key kills the old job and starts a new one; until it finishes,+-- 'useTask' returns the previous key's result, and 'useTaskStatus' reports+-- running, then done or failed, carrying it.+runTaskKeyChangeTest :: Context -> IORef Int -> IO ()+runTaskKeyChangeTest ctx failed = do+  job <- newTask+  wait <- newWakeSignal ctx+  (sleep, _, killedIn) <- sleeper+  gate <- newEmptyMVar+  keyRef <- newIORef (1 :: Int)+  let ui = liftIO (readIORef keyRef) >>= \k -> useTask job k (if k == 2 then sleep >> pure k else takeMVar gate >> pure (k * 10))+  assertEq failed Nothing =<< evalUi ctx inp ui+  putMVar gate ()+  assertEq failed (Just (Just 10)) =<< frameUntil wait ctx ui isJust+  forM_ [2, 3] $ \k -> writeIORef keyRef k >> (assertEq failed (Just 10) =<< evalUi ctx inp ui)+  assert failed =<< killedIn 2000000+  _ <- wait 0+  putMVar gate ()+  assertEq failed (Just (Just 30)) =<< frameUntil wait ctx ui (== Just 30)+  statusJob <- newTask+  writeIORef keyRef 1+  let status = do+        k <- liftIO (readIORef keyRef)+        s <- useTaskStatus statusJob k (takeMVar gate >> if k == 1 then pure ("one" :: String) else ioError (userError "two"))+        pure $ case s of+          TaskRunning prev -> ("running" :: String, prev)+          TaskDone a -> ("done", Just a)+          TaskFailed _ prev -> ("failed", prev)+  assertEq failed ("running", Nothing) =<< evalUi ctx inp status+  putMVar gate ()+  assertEq failed (Just ("done", Just "one")) =<< frameUntil wait ctx status ((== "done") . fst)+  writeIORef keyRef 2+  assertEq failed ("running", Just "one") =<< evalUi ctx inp status+  putMVar gate ()+  assertEq failed (Just ("failed", Just "one")) =<< frameUntil wait ctx status ((== "failed") . fst)+  settled ctx failed status ("failed", Just "one")+  cancelTasks ctx++-- | Switching typed owners at the same view position carries no result over+-- (a handle's result type itself cannot change). The same input runs again+-- under a new attempt count. A frame that runs the view twice after a hook+-- write starts its job once.+runTaskStartsTest :: Context -> IORef Int -> IO ()+runTaskStartsTest ctx failed = do+  intJob <- newTask+  stringJob <- newTask+  wait <- newWakeSignal ctx+  gate <- newEmptyMVar+  let asInt = useTask intJob ("same" :: String) (pure (1 :: Int))+      asString = useTask stringJob ("same" :: String) (readMVar gate >> pure ("one" :: String))+  assertEq failed (Just (Just 1)) =<< frameUntil wait ctx asInt isJust+  assertEq failed Nothing =<< evalUi ctx inp asString+  putMVar gate ()+  assertEq failed (Just (Just "one")) =<< frameUntil wait ctx asString isJust+  retried <- newTask+  starts <- newIORef 0+  attempt <- newIORef (0 :: Int)+  let ui = liftIO (readIORef attempt) >>= \n -> useTask retried ("same input" :: String, n) (tick starts >> readIORef starts)+  assertEq failed (Just (Just 1)) =<< frameUntil wait ctx ui isJust+  assertEq failed (Just 1) =<< evalUi ctx inp ui+  writeIORef attempt 1+  assertEq failed (Just (Just 2)) =<< frameUntil wait ctx ui (== Just 2)+  assertEq failed 2 =<< readIORef starts+  once <- newTask+  onceStarts <- newIORef 0+  let twoPasses = do+        nVar <- useVar (0 :: Int)+        n <- readVar nVar+        _ <- useTask once ("once" :: String) (tick onceStarts >> threadDelay 10000000)+        n <$ when (n == 0) (writeVar nVar 1)+  assertEq failed 1 =<< evalUi ctx inp twoPasses+  assert failed =<< reaches onceStarts 1+  threadDelay 20000+  assertEq failed 1 =<< readIORef onceStarts+  cancelTasks ctx++-- | A job lives while the view calls its hook. The first frame without the+-- call kills it without requesting a frame, and only that hook's job: the+-- other keeps its job until a frame skips it too. A later call starts anew.+runTaskLeaseTest :: Context -> IORef Int -> IO ()+runTaskLeaseTest ctx failed = do+  jobA <- newTask+  jobB <- newTask+  starts <- newIORef 0+  (sleepA, _, killedA) <- sleeper+  (sleepB, startedB, killedB) <- sleeper+  let ui showA showB = do+        scope (when showA (void (useTask jobA ("a" :: String) (tick starts >> sleepA))))+        scope (when showB (void (useTask jobB ("b" :: String) sleepB)))+        label "lease"+  replicateM_ 3 (runFrame ctx inp (ui True True))+  assert failed =<< reaches starts 1+  startedB+  assert failed . not =<< killedA 20000+  settled ctx failed (ui False True) ()+  replicateM_ 2 (runFrame ctx inp (ui False True))+  assert failed =<< killedA 2000000+  assert failed . not =<< killedB 20000+  _ <- runFrame ctx inp (ui True False)+  assert failed =<< reaches starts 2+  assert failed =<< killedB 2000000+  cancelTasks ctx++-- | A job that throws, returns a value that throws when forced, or meets an+-- asynchronous exception other than the hook's kill (a stack overflow)+-- fails with it and wakes the loop. Nothing reaches the uncaught handler,+-- and 'useTask' keeps its last result.+runTaskFailureTest :: Context -> IORef Int -> IO ()+runTaskFailureTest ctx failed = do+  [thrownJob, lazyJob, overflowJob, plainJob] <- replicateM 4 newTask+  wait <- newWakeSignal ctx+  gate <- newEmptyMVar+  uncaught <- newIORef 0+  handler <- getUncaughtExceptionHandler+  setUncaughtExceptionHandler (\_ -> tick uncaught)+  flip finally (setUncaughtExceptionHandler handler) $ do+    let ui =+          (,)+            <$> mapM+              (\(job, k, act) -> useTaskStatus job (k :: String) (readMVar gate >> act))+              [ (thrownJob, "thrown", ioError (userError "boom") :: IO Int)+              , (lazyJob, "lazy", pure (error "lazy"))+              , (overflowJob, "overflow", throwIO StackOverflow)+              ]+            <*> useTask plainJob ("thrown too" :: String) (readMVar gate >> ioError (userError "boom"))+        failure = \case+          TaskFailed e Nothing -> Just (displayException e)+          _ -> Nothing+    _ <- runFrame ctx inp ui+    _ <- wait 0+    putMVar gate ()+    Just (statuses, plain) <- frameUntil wait ctx ui (all (isJust . failure) . fst)+    let says s msg = maybe False (msg `isInfixOf`) (failure s)+    assert failed (and (zipWith says statuses ["boom", "lazy"]))+    assertEq failed Nothing plain+    threadDelay 20000+    assertEq failed 0 =<< readIORef uncaught+  cancelTasks ctx++-- | 'cancelTasks' (run at session end) kills jobs still running and returns+-- once their cleanup has run. After it nothing wakes the loop.+runTaskShutdownTest :: Context -> IORef Int -> IO ()+runTaskShutdownTest ctx failed = do+  job <- newTask+  (sleep, started, killedIn) <- sleeper+  cleaned <- newIORef False+  wakes <- newIORef 0+  setWakeLoop ctx (tick wakes)+  _ <- runFrame ctx inp (useTask job ("shutdown" :: String) (sleep `finally` writeIORef cleaned True))+  started+  cancelTasks ctx+  assert failed =<< readIORef cleaned+  assert failed =<< killedIn 2000000+  before <- readIORef wakes+  wakeFromThread ctx+  assertEq failed before =<< readIORef wakes++-- | A producer that runs its step for 1 to 1000 once let go, then idles, and+-- the action that lets it go and waits for the burst to end.+burster :: IO ((Int -> IO ()) -> IO (), IO ())+burster = do+  go <- newEmptyMVar+  done <- newEmptyMVar+  let produce step = takeMVar go >> mapM_ step [1 .. 1000] >> putMVar done () >> takeMVar go+  pure (produce, putMVar go () >> takeMVar done)++-- | A burst faster than the frame rate costs one frame showing the last+-- value: from an app thread that writes state and wakes the loop with+-- 'askWake', and from stream updates folded into the hook's state.+runBurstTest :: Context -> IORef Int -> IO ()+runBurstTest _ failed = do+  job <- newTask+  stream <- newStream+  latest <- newIORef 0+  (produceA, letGoA) <- burster+  (produceB, letGoB) <- burster+  let woken = do+        wake <- askWake+        _ <- useTask job ("stream" :: String) (produceA (\i -> writeIORef latest i >> wake))+        n <- liftIO (readIORef latest)+        n <$ lamp (n > 0)+      streamed = do+        n <- useStream stream ("stream" :: String) 0 (\update -> produceB (update . (+)))+        n <$ lamp (n > 0)+  forM_ [(woken, letGoA, 1000), (streamed, letGoB, 500500)] $ \(ui, letGo, final) -> do+    ctx <- newContext+    wait <- newWakeSignal ctx+    _ <- warmup2 ctx inp ui+    settled ctx failed ui 0+    _ <- wait 0+    letGo+    assertEq failed [True, False] =<< replicateM 2 (wait 0)+    takesNews ctx failed ui final+    cancelTasks ctx++-- | A wake the action could not deliver (a full event queue), or made with+-- no action installed, does not leave the next wake waiting on it; once one+-- gets through, the rest wait for the loop to take it. A wake drained with+-- @wait 0@ and no frame after it does not swallow the job's wake after it.+runWakeDeliveryTest :: Context -> IORef Int -> IO ()+runWakeDeliveryTest ctx failed = do+  writeIORef (ctxWakeLoop ctx) Nothing+  wakeFromThread ctx+  runs <- newIORef (0 :: Int)+  delivers <- newIORef False+  setWakeLoopChecked ctx (tick runs >> readIORef delivers)+  replicateM_ 2 (wakeFromThread ctx)+  assertEq failed 2 =<< readIORef runs+  writeIORef delivers True+  replicateM_ 2 (wakeFromThread ctx)+  assertEq failed 3 =<< readIORef runs+  drained <- newContext+  wait <- newWakeSignal drained+  markDirty drained+  assert failed =<< wait 0+  wakeFromThread drained+  assert failed =<< wait 0++-- | A new key kills the old producer and restarts from the initial state,+-- dropping the old one's late updates. An update whose function throws+-- leaves the state as it was: the producer gets the exception and goes on.+-- An update to a stream whose hook stopped running wakes nothing: a thread+-- that kept its @update@ once woke the loop, repainting whole, for good.+runStreamLifecycleTest :: Context -> IORef Int -> IO ()+runStreamLifecycleTest ctx failed = do+  stream <- newStream+  wait <- newWakeSignal ctx+  (sleep, _, killedIn) <- sleeper+  keyRef <- newIORef (1 :: Int)+  let ui = liftIO (readIORef keyRef) >>= \k -> useStream stream k [] (\update -> update (k :) >> sleep)+  assertEq failed (Just [1]) =<< frameUntil wait ctx ui (not . null)+  writeIORef keyRef 2+  -- The new producer may already have run before the view reads it.+  assert failed . (`elem` [[], [2]]) =<< evalUi ctx inp ui+  assert failed =<< killedIn 2000000+  assertEq failed (Just [2]) =<< frameUntil wait ctx ui (not . null)+  throwing <- newStream+  (sleepT, _, _) <- sleeper+  let produce update = do+        update (const 1)+        _ <- try @ErrorCall (update (\_ -> error "boom"))+        _ <- try @ErrorCall (update (+ 10))+        sleepT+  assertEq failed (Just 11) =<< frameUntil wait ctx (useStream throwing () (0 :: Int) produce) (>= 10)+  cancelTasks ctx+  fresh <- newContext+  waitFresh <- newWakeSignal fresh+  released <- newStream+  (sleepR, started, killedR) <- sleeper+  kept <- newEmptyMVar+  let shownIf shown = when shown (void (useStream released () (0 :: Int) (\update -> putMVar kept update >> sleepR)))+  _ <- runFrame fresh inp (shownIf True)+  update <- takeMVar kept+  started+  _ <- runFrame fresh inp (shownIf False)+  assert failed =<< killedR 2000000+  _ <- waitFresh 0+  update (+ 1)+  assert failed . not =<< waitFresh 0
test/integration/Cases/TextInput.hs view
@@ -1,1188 +1,593 @@-module Cases.TextInput-  ( runTextInputClickSelectTest-  , runTextInputClipboardTest-  , runTextInputPasswordTest-  , runTextInputCursorTest-  , runTextAreaCutClearsSelectionTest-  , runTextInputCutClearsSelectionTest-  , runTextInputDirtyTest-  , runTextInputFocusSdlTest-  , runTextInputMenuTest-  , runTextInputMouseSelectionTest-  , runTextInputSelectionTest-  , runTextInputFfCaretTest-  , runTextInputScrollTest-  , runTextInputWordKeysTest-  , runTextInputBatchTest-  , runTextUndoTest-  , runTextAreaWidthTrackingTest-  , runTextAreaScrollWheelTest-  , runTextAreaZoomScrollTest-  , runTextAreaScrollDragTest-  , runTextAreaCursorOnScrollBarTest-  , runTextAreaHScrollWheelTest-  , runTextAreaHScrollDragTest-  , runTextArea2DScrollTest-  , runTextAreaScrollCursorLeavesViewportTest-  , runRefreshRedrawTest-  , runTextAreaMenuPulseTest-  , runTextCommandFocusTest-  , runTextAreaRemountScrollTest-  )-where--import Control.Monad (forM_, replicateM, replicateM_, when)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.IntMap.Strict qualified as IM-import Data.Text qualified as T-import NanoUI-import NanoUI.Context (intKey)-import NanoUI.Frame.TextEdit-  ( TextAreaHit (..)-  , TextAreaScrollBarLayouts (..)-  , resolveTextAreaFont-  , textAreaContentMetrics-  , textAreaBarLane-  , textAreaLineHeight-  , textAreaHScrollBarLayout-  , textAreaHitForWidget-  , textAreaScrollBarLayout-  , textAreaScrollBarLayouts-  )-import NanoUI.Store-  ( WidgetStore (..)-  , Slot (..)-  , slotKey-  )-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt, withInput)-import NanoUI.Testing.Harness-  ( assertSpansHas-  , centerOf-  , clickPair-  , held-  , keyInp-  , spanCenter-  , tabInp-  , warmup2-  )-import NanoUI.Widgets.TextArea-  ( buffer-  , loadTextAreaState-  , selectionAnchor-  )-import NanoUI.Widgets.TextBuffer-  ( fromText-  , getCursor-  , toLines-  , toText-  )--runTextInputBatchTest :: Context -> IORef Int -> IO ()-runTextInputBatchTest ctx failed = do-  let-    inp = withInput 320 120-    ui = column (textInput' "aOLDz")-    left = keyInp KeyLeft inp-    step event = runFrame ctx event ui-  (resp, _) <- warmup2 ctx inp ui-  _ <- step (tabInp inp)-  _ <- step left-  replicateM_ 3 (step (left {inputModifiers = Modifiers True False False}))-  let-    checkSelection cursor anchor = do-      store <- getStore ctx-      let-        key = intKey (respId resp)-      assertEq-        failed-        (IM.lookup (slotKey SlotCursor key) (storeInt store))-        (Just cursor)-      assertEq-        failed-        (IM.lookup (slotKey SlotAnchor key) (storeInt store))-        (Just anchor)-  checkSelection 1 4-  -- An event filtered to nothing must not delete the current selection.-  ((_, unchanged), _, _, _) <- step (inp {inputChars = "\n\t"})-  assertEq failed unchanged "aOLDz"-  checkSelection 1 4-  -- Navigation follows text insertion within a frame.-  ((_, committed), _, _, _) <- step (left {inputChars = "é\n世界\t"})-  assertEq failed committed "aé世界z"-  checkSelection 3 3---- | Caption-less text area with a separate label above it (the old labelled--- field kept the label span and geometry the tests assert against).-labeledArea :: T.Text -> T.Text -> NanoUI (Response, T.Text)-labeledArea lbl initial = do-  label lbl-  textArea' initial--labeledInput :: Ui :> es => T.Text -> T.Text -> Eff es (Response, T.Text)-labeledInput lbl initial = do-  label lbl-  textInputConfigured' defaultTextInputConfig {ticPlaceholder = "Enter " <> lbl} initial--runTextInputCursorTest :: Context -> IORef Int -> IO ()-runTextInputCursorTest ctx failed = do-  let-    inp0 = withInput 320 120-    ui = column (labeledInput "Name" "")-  _ <- warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  let-    labelPos =-      [ (rectX r + rectW r / 2, rectY r + 0.5)-      | (r, txt, _, _, _) <- spans-      , txt == "Name"-      ]-    fieldPos =-      [ (rectX r + rectW r / 2, rectY r + 0.5)-      | (r, txt, _, _, _) <- spans-      , "Enter" `T.isInfixOf` txt-      ]-  case (labelPos, fieldPos) of-    ([(lx, ly)], [(fx, fy)]) -> do-      let-        labelHover = inp0 {inputMousePos = V2 lx ly}-      _ <- runFrame ctx labelHover ui-      labelKind <- uiCursorKind ctx labelHover-      assertEq failed labelKind UiCursorDefault-      let-        fieldHover = inp0 {inputMousePos = V2 fx fy}-      _ <- runFrame ctx fieldHover ui-      fieldKind <- uiCursorKind ctx fieldHover-      assertEq failed fieldKind UiCursorText-      let-        click =-          fieldHover-            { inputMouseDown = True-            , inputMousePressed = True-            , inputMouseReleased = False-            }-      _ <- runFrame ctx click ui-      clickKind <- uiCursorKind ctx click-      assertEq failed clickKind UiCursorText-    _ -> assert failed False--runTextInputCutClearsSelectionTest :: Context -> IORef Int -> IO ()-runTextInputCutClearsSelectionTest ctx failed = do-  textRef <- newIORef "hello"-  (ctx', clipRef) <- memoryClipboard Nothing ctx-  let-    inp0 = withInput 320 120-    ui = column (held textRef textInput')-  _ <- warmup2 ctx' inp0 ui-  _ <- runFrame ctx' (tabInp inp0) ui-  let-    shiftLeft =-      inp0-        { inputKeys = inputKeysFromList [KeyLeft]-        , inputModifiers = Modifiers True False False-        }-  _ <- runFrame ctx' shiftLeft ui-  _ <--    runFrame-      ctx'-      (inp0 {inputChars = "x", inputModifiers = Modifiers False True False})-      ui-  clip <- readIORef clipRef-  assertEq failed clip (Just "o")-  ((_, val), _, _, _) <- runFrame ctx' (inp0 {inputChars = "z"}) ui-  assertEq failed val "hellz"---- Word-wise editing keys (Ctrl or Alt + Backspace/Delete/Left/Right) work in--- the single-line text input like they do in the text area.-runTextInputWordKeysTest :: Context -> IORef Int -> IO ()-runTextInputWordKeysTest ctx failed = do-  textRef <- newIORef "hello world"-  let-    inp0 = withInput 320 120-    ui = column (held textRef textInput')-    ctrlMods = Modifiers False True False-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  -- Ctrl+Backspace deletes the word before the cursor ("world").-  _ <--    runFrame-      ctx-      (inp0 {inputKeys = inputKeysFromList [KeyBackspace], inputModifiers = ctrlMods})-      ui-  ((_, v1), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed v1 "hello "-  -- Nothing right of the cursor at end of text: Ctrl+Delete is a no-op.-  _ <--    runFrame-      ctx-      (inp0 {inputKeys = inputKeysFromList [KeyDelete], inputModifiers = ctrlMods})-      ui-  ((_, v2), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed v2 "hello "-  -- Ctrl+Left jumps to the start; typing there proves the cursor moved.-  _ <--    runFrame-      ctx-      (inp0 {inputKeys = inputKeysFromList [KeyLeft], inputModifiers = ctrlMods})-      ui-  ((_, v3), _, _, _) <- runFrame ctx (inp0 {inputChars = "X"}) ui-  assertEq failed v3 "Xhello "-  -- Ctrl+Delete removes the word after the cursor ("hello").-  _ <--    runFrame-      ctx-      (inp0 {inputKeys = inputKeysFromList [KeyDelete], inputModifiers = ctrlMods})-      ui-  ((_, v4), _, _, _) <- runFrame ctx inp0 ui-  assertEq failed v4 "X "--runTextAreaCutClearsSelectionTest :: Context -> IORef Int -> IO ()-runTextAreaCutClearsSelectionTest ctx failed = do-  (ctx', clipRef) <- memoryClipboard Nothing ctx-  textRef <- newIORef "hello"-  let-    inp0 = withInput 320 220-    ui = column (label "Notes" >> held textRef textArea')-  _ <- warmup2 ctx' inp0 ui-  _ <- runFrame ctx' (tabInp inp0) ui-  _ <--    runFrame-      ctx'-      (inp0 {inputChars = "\x01", inputModifiers = Modifiers False True False})-      ui-  ((_, cutVal), _, _, _) <--    runFrame-      ctx'-      (inp0 {inputChars = "x", inputModifiers = Modifiers False True False})-      ui-  clip <- readIORef clipRef-  assertEq failed clip (Just "hello")-  assertEq failed cutVal ""-  ((_, val), _, _, _) <- runFrame ctx' (inp0 {inputChars = "z"}) ui-  assertEq failed val "z"--runTextInputSelectionTest :: Context -> IORef Int -> IO ()-runTextInputSelectionTest ctx failed = do-  textRef <- newIORef "hello"-  let-    inp0 = withInput 320 120-    ui = column (button "Other" >> held textRef textInput')-  _ <- warmup2 ctx inp0 ui-  _ <- runFrame ctx (tabInp inp0) ui-  _ <- runFrame ctx (tabInp inp0) ui-  let-    shiftLeft =-      inp0-        { inputKeys = inputKeysFromList [KeyLeft]-        , inputModifiers = Modifiers True False False-        }-  _ <- warmup2 ctx shiftLeft ui-  ((_, valReplace), _, _, _) <- runFrame ctx (inp0 {inputChars = "X"}) ui-  assertEq failed valReplace "helX"-  -- Ctrl+A selects all whether it arrives as 'a' or as the \x01 control char.-  forM_ ["\x01", "a"] $ \selectAll -> do-    _ <- runFrame ctx (inp0 {inputChars = "abc"}) ui-    _ <--      runFrame-        ctx-        (inp0 {inputChars = selectAll, inputModifiers = Modifiers False True False})-        ui-    ((_, valClear), _, _, _) <--      runFrame ctx (keyInp KeyBackspace inp0) ui-    assertEq failed valClear ""--runTextInputMouseSelectionTest :: Context -> IORef Int -> IO ()-runTextInputMouseSelectionTest ctx failed = do-  let-    inp0 = withInput 320 120-    ui = column (textInput' "hello")-  _ <- warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans, txt == "hello"] of-    (Rect fx fy fw fh : _) -> do-      let-        fieldY = fy + fh / 2-      _ <--        runFrame-          ctx-          ( inp0-              { inputMousePos = V2 (fx + 1) fieldY-              , inputMouseDown = True-              , inputMousePressed = True-              }-          )-          ui-      _ <--        runFrame-          ctx-          (inp0 {inputMousePos = V2 (fx + fw - 1) fieldY, inputMouseDown = True})-          ui-      _ <--        runFrame-          ctx-          ( inp0-              { inputMousePos = V2 (fx + fw - 1) fieldY-              , inputMouseDown = False-              , inputMouseReleased = True-              }-          )-          ui-      ((_, val), _, _, _) <- runFrame ctx (inp0 {inputChars = "z"}) ui-      assertEq failed val "z"-    _ -> assert failed False---- Double-click selects a word and triple-click the whole line.-runTextInputClickSelectTest :: Context -> IORef Int -> IO ()-runTextInputClickSelectTest ctx failed = do-  allCtx <- newContext-  let-    inp0 = withInput 320 120-    -- Click n times at the start of the field showing txt, then Backspace.-    clicksThenBackspace c txt n = do-      let-        ui = column (textInput' txt)-      _ <- warmup2 c inp0 ui-      spans <- collectTextSpans c-      case [r | (r, t, _, _, _) <- spans, t == txt] of-        (Rect fx fy _ fh : _) -> do-          let-            pos = V2 (fx + 1) (fy + fh / 2)-          forM_ [1 .. n] $ \k ->-            runFrame-              c-              ( inp0-                  { inputMousePos = pos-                  , inputMouseDown = True-                  , inputMousePressed = True-                  , inputMouseClicks = k-                  }-              )-              ui-          ((_, val), _, _, _) <--            runFrame c (keyInp KeyBackspace inp0) ui-          pure (Just val)-        _ -> pure Nothing-  word <- clicksThenBackspace ctx "hello world" 2-  assertEq failed word (Just " world")-  line <- clicksThenBackspace allCtx "hello" 3-  assertEq failed line (Just "")--runTextInputClipboardTest :: Context -> IORef Int -> IO ()-runTextInputClipboardTest ctx failed = do-  textRef <- newIORef "hello"-  (ctx', clipRef) <- memoryClipboard Nothing ctx-  let-    inp0 = withInput 320 120-    ui = column (held textRef textInput')-  _ <- warmup2 ctx' inp0 ui-  _ <- runFrame ctx' (tabInp inp0) ui-  let-    selectAll = inp0 {inputChars = "a", inputModifiers = Modifiers False True False}-    copy = inp0 {inputChars = "c", inputModifiers = Modifiers False True False}-    clear = keyInp KeyBackspace inp0-    paste = inp0 {inputChars = "v", inputModifiers = Modifiers False True False}-  _ <- runFrame ctx' selectAll ui-  _ <- runFrame ctx' copy ui-  clip <- readIORef clipRef-  assertEq failed clip (Just "hello")-  _ <- runFrame ctx' selectAll ui >> runFrame ctx' clear ui-  ((_, val), _, _, _) <- runFrame ctx' paste ui-  assertEq failed val "hello"---- A password field displays one mask character per character, and Ctrl+C--- leaves the clipboard untouched while the field keeps its real value.-runTextInputPasswordTest :: Context -> IORef Int -> IO ()-runTextInputPasswordTest ctx failed = do-  (ctx', clipRef) <- memoryClipboard Nothing ctx-  let-    inp0 = withInput 320 120-    ui = column (textInputConfigured' defaultTextInputConfig {ticPassword = True} "hunter2")-  _ <- warmup2 ctx' inp0 ui-  spans <- collectTextSpans ctx'-  assert failed (not (any (\(_, txt, _, _, _) -> "hunter2" `T.isInfixOf` txt) spans))-  assertSpansHas failed "*******" spans-  _ <- runFrame ctx' (tabInp inp0) ui-  let-    selectAll = inp0 {inputChars = "a", inputModifiers = Modifiers False True False}-    copy = inp0 {inputChars = "c", inputModifiers = Modifiers False True False}-  _ <- runFrame ctx' selectAll ui-  ((_, val), _, _, _) <- runFrame ctx' copy ui-  clip <- readIORef clipRef-  assertEq failed clip Nothing-  assertEq failed val "hunter2"---- The text input's context menu offers Paste even while unfocused, and its--- Paste and Cut entries edit the field through the clipboard. The menu edits--- the field between frames, so each edit must survive the caller passing back--- the result of the frame before it.-runTextInputMenuTest :: Context -> IORef Int -> IO ()-runTextInputMenuTest ctx failed = do-  textRef <- newIORef "hello"-  (ctx', clipRef) <- memoryClipboard (Just "pasted") ctx-  let-    inp0 = withInput 320 160-    ui = column (held textRef textInput')-  _ <- warmup2 ctx' inp0 ui-  spans <- collectTextSpans ctx'-  case [r | (r, txt, _, _, _) <- spans, txt == "hello"] of-    (Rect fx fy _ fh : _) -> do-      let-        menuOpen =-          inp0-            { inputMousePos = V2 (fx + 1) (fy + fh / 2)-            , inputMouseRightDown = True-            , inputMouseRightPressed = True-            }-        pick entry = do-          _ <- runFrame ctx' menuOpen ui-          overlays <- collectOverlayTextSpans ctx' menuOpen-          case [r | (r, txt, _, _, _) <- overlays, txt == entry] of-            (r : _) -> do-              let-                (pickPress, pickRelease) = clickPair inp0 (spanCenter r)-              _ <- runFrame ctx' pickPress ui >> runFrame ctx' pickRelease ui-              ((_, val), _, _, _) <- runFrame ctx' inp0 ui-              pure (Just val)-            _ -> pure Nothing-      pasted <- pick "Paste"-      assertEq failed pasted (Just "hellopasted")-      cut <- pick "Cut"-      clip <- readIORef clipRef-      assertEq failed clip (Just "hellopasted")-      assertEq failed cut (Just "")-      overlaysAfter <- collectOverlayTextSpans ctx' inp0-      assert failed (not (any (\(_, txt, _, _, _) -> txt == "Cut") overlaysAfter))-    _ -> assert failed False--runTextInputFocusSdlTest :: Context -> IORef Int -> IO ()-runTextInputFocusSdlTest ctx failed = do-  let-    inp0 = withInput 320 120-    ui = column (labeledInput "Name" "")-  (resp, _) <- warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  case [ (rectX r + rectW r / 2, rectY r + 0.5)-       | (r, txt, _, _, _) <- spans-       , "Enter" `T.isInfixOf` txt-       ] of-    [(fx, fy)] -> do-      let-        inp1 =-          inp0 {inputMousePos = V2 fx fy, inputMouseDown = True, inputMousePressed = True}-      _ <- runFrame ctx inp1 ui-      focus <- getFocusId ctx-      assertEq failed focus (respId resp)-      let-        idle = inp0 {inputMousePos = V2 fx fy}-      samples <- replicateM 5 (runFrame ctx idle ui >> getFocusId ctx)-      assertEq failed samples (replicate 5 (respId resp))-    _ -> assert failed False--runTextInputDirtyTest :: Context -> IORef Int -> IO ()-runTextInputDirtyTest ctx failed = do-  let-    ui = column (textInput' "")-    inp0 = (withInput 200 100) {inputMousePos = V2 20 20}-  (resp, _) <- warmup2 ctx inp0 ui-  let-    Rect rx ry _ _ = respRect resp-    (press, release) = clickPair inp0 (V2 (rx + 1) (ry + 0.5))-  _ <- runFrame ctx press ui-  _ <- runFrame ctx release ui-  let-    idle = release {inputMouseReleased = False, inputDeltaTime = 1}-  _ <- runFrame ctx idle ui-  needFocus <- needsRedraw ctx idle idle-  assert failed needFocus--runTextInputFfCaretTest :: Context -> IORef Int -> IO ()-runTextInputFfCaretTest ctx failed = do-  let-    fm = ctxFontMetrics ctx-    fs = T.replicate 6 "f"-    adv = fmAdvance fm 'f'-  assertEq failed (lineWidth fm fs) (6 * adv)-  assertEq failed (textIndexAtX fm fs (lineWidth fm fs)) 6-  assertEq failed (textIndexAtX fm fs (lineWidth fm (T.take 3 fs))) 3-  let-    inp0 = withInput 320 120-    ui = column (textInput' fs)-  _ <- warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  assertSpansHas failed fs spans-  case [r | (r, txt, _, _, _) <- spans, txt == fs] of-    (Rect fx fy _ fh : _) -> do-      let-        pos = V2 (fx + lineWidth fm (T.take 3 fs)) (fy + fh / 2)-        (press, release) = clickPair inp0 pos-      _ <- runFrame ctx press ui-      _ <- runFrame ctx release ui-      ((_, val), _, _, _) <--        runFrame ctx (inp0 {inputMousePos = pos, inputChars = "x"}) ui-      assertEq failed val "fffxfff"-    _ -> assert failed False--runTextInputScrollTest :: Context -> IORef Int -> IO ()-runTextInputScrollTest ctx failed = do-  let-    longText = "VeryLongTextEnteredIntoTheFieldThatExceedsTheWidth"-    inp0 = withInput 200 120-    ui = column (textInput' longText)-  (resp, _) <- warmup2 ctx inp0 ui-  spans0 <- collectTextSpans ctx-  case [r | (r, txt, _, _, _) <- spans0, txt == longText] of-    (Rect fx fy _ fh : _) -> do-      let-        pos = V2 (fx + 50) (fy + fh / 2)-        (press, release) = clickPair inp0 pos-      _ <- runFrame ctx press ui-      _ <- runFrame ctx release ui-      let-        atEnd = keyInp KeyEnd inp0-      _ <- runFrame ctx atEnd ui-      store <- getStore ctx-      let-        key = intKey (respId resp)-        scrollEnd = IM.findWithDefault 0 (slotKey SlotTextInputScroll key) (storeFloat store)-      assert failed (scrollEnd > 0)-      let-        atHome = keyInp KeyHome inp0-      _ <- runFrame ctx atHome ui-      storeHome <- getStore ctx-      let-        scrollHome = IM.findWithDefault 0 (slotKey SlotTextInputScroll key) (storeFloat storeHome)-      assertEq failed scrollHome 0-    _ -> assert failed False--runTextAreaScrollWheelTest :: Context -> IORef Int -> IO ()-runTextAreaScrollWheelTest ctx failed = do-  let-    longText = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" longText)-    uiShort = column (keyed (1 :: Int) (labeledArea "Short" "Line 1\nLine 2"))-    fieldCenter = pure . spanCenter-  -- Text that fits the viewport does not wheel-scroll.-  (respShort, _) <- warmup2 ctx inp0 uiShort-  mRectShort <- getPrevRect ctx (respId respShort)-  case mRectShort of-    Just r -> do-      pos <- fieldCenter r-      _ <- runFrame ctx (inp0 {inputMousePos = pos, inputScroll = V2 0 1}) uiShort-      offShort <- getScrollOffset ctx (respId respShort)-      assertEq failed offShort 0-    _ -> assert failed False-  (resp, _) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx (respId resp)-  case mRect of-    Just r -> do-      pos <- fieldCenter r-      let-        wheelDown = inp0 {inputMousePos = pos, inputScroll = V2 0 1}-      off0 <- getScrollOffset ctx (respId resp)-      assertEq failed off0 0-      -- Scroll down 1 notch-      _ <- runFrame ctx wheelDown ui-      off1 <- getScrollOffset ctx (respId resp)-      assertGt failed off1 off0-      -- Scroll down 3 more notches-      let-        wheelDownMore = inp0 {inputMousePos = pos, inputScroll = V2 0 3}-      _ <- runFrame ctx wheelDownMore ui-      off2 <- getScrollOffset ctx (respId resp)-      assertGt failed off2 off1-      -- Scroll up beyond top to check clamping to 0-      let-        wheelUp = inp0 {inputMousePos = pos, inputScroll = V2 0 (-10)}-      _ <- runFrame ctx wheelUp ui-      off3 <- getScrollOffset ctx (respId resp)-      assertEq failed off3 0-      -- Text buffer should remain completely unmodified-      store <- getStore ctx-      let-        key = intKey (respId resp)-        st = loadTextAreaState store key longText-      assertEq failed (toText (buffer st)) longText-    _ -> assert failed False--runTextAreaZoomScrollTest :: Context -> IORef Int -> IO ()-runTextAreaZoomScrollTest ctx failed = do-  let-    longText = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]-    inp0 = withInput 320 220-    ui = column $ textAreaWith' (fontSize 32) longText-  (resp, _) <- warmup2 ctx inp0 ui-  mHit <- textAreaHitForWidget ctx (respId resp)-  case mHit of-    Nothing -> assert failed False-    Just hit -> do-      fm <- resolveTextAreaFont ctx (tahNodeIdx hit)-      let-        field = tahFieldRect hit-        lineH = tahLineH hit-        lineCount = max 1 (length (toLines (fromText longText)))-        contentH = fromIntegral lineCount * lineH-        contentW = maximum (0 : [lineWidth fm l | l <- T.lines longText])-        (ix, iy) = widgetContentInset fm-        innerW = rectW field - 2 * ix-        innerH = rectH field - 2 * iy-        barLaneW = textAreaBarLane-        barLaneH = textAreaBarLane-        hasV0 = contentH > innerH-        hasH = contentW > (if hasV0 then max 0 (innerW - barLaneW) else innerW)-        availH = if hasH then max 0 (innerH - barLaneH) else innerH-        expectedMaxY = max 0 (contentH - availH)-        pos = V2 (rectX field + rectW field / 2) (rectY field + rectH field / 2)-        wheelDown = inp0 {inputMousePos = pos, inputScroll = V2 0 100}-      _ <- runFrame ctx wheelDown ui-      off <- getScrollOffset ctx (respId resp)-      assert failed (abs (off - expectedMaxY) < 0.5)--runTextAreaScrollDragTest :: Context -> IORef Int -> IO ()-runTextAreaScrollDragTest ctx failed = do-  let-    longText = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" longText)-  (resp, _) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx (respId resp)-  case mRect of-    Just (Rect rx ry rw rh) -> do-      let-        fm = ctxFontMetrics ctx-        field = Rect rx ry rw rh-        contentH = 40 * textAreaLineHeight fm-      off0 <- getScrollOffset ctx (respId resp)-      assertEq failed off0 0-      case textAreaScrollBarLayout fm field contentH off0 of-        Nothing -> assert failed False-        Just layout -> do-          let-            thumb = sbThumb layout-            thumbCenter = V2 (rectX thumb + rectW thumb / 2) (rectY thumb + rectH thumb / 2)-            press =-              inp0-                { inputMousePos = thumbCenter-                , inputMouseDown = True-                , inputMousePressed = True-                }-          _ <- runFrame ctx press ui-          -- Drag the thumb down by 30 pixels-          let-            drag =-              press-                { inputMousePressed = False-                , inputMousePos = V2 (v2X thumbCenter) (v2Y thumbCenter + 30)-                }-          _ <- runFrame ctx drag ui-          off1 <- getScrollOffset ctx (respId resp)-          assertGt failed off1 off0-          -- Release the mouse-          let-            release = drag {inputMouseDown = False, inputMouseReleased = True}-          _ <- runFrame ctx release ui-          -- Clicking/dragging scrollbar must not initiate text selection or alter buffer-          store <- getStore ctx-          let-            key = intKey (respId resp)-            st = loadTextAreaState store key longText-          assertEq failed (toText (buffer st)) longText-          assert failed (selectionAnchor st == getCursor (buffer st))-    _ -> assert failed False--runTextAreaCursorOnScrollBarTest :: Context -> IORef Int -> IO ()-runTextAreaCursorOnScrollBarTest ctx failed = do-  let-    longText = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" longText)-  (resp, _) <- warmup2 ctx inp0 ui-  spans <- collectTextSpans ctx-  let-    labelPos =-      [ (rectX r + rectW r / 2, rectY r + 0.5)-      | (r, txt, _, _, _) <- spans-      , txt == "Notes"-      ]-  mRect <- getPrevRect ctx (respId resp)-  case (labelPos, mRect) of-    ([(lx, ly)], Just (Rect rx ry rw rh)) -> do-      let-        fm = ctxFontMetrics ctx-        field = Rect rx ry rw rh-        contentH = 40 * textAreaLineHeight fm-      -- Hover over label -> UiCursorDefault-      let-        labelHover = inp0 {inputMousePos = V2 lx ly}-      _ <- runFrame ctx labelHover ui-      labelKind <- uiCursorKind ctx labelHover-      assertEq failed labelKind UiCursorDefault--      -- Hover over text field area (left side) -> UiCursorText-      let-        textHover = inp0 {inputMousePos = V2 (rectX field + 20) (rectY field + 20)}-      _ <- runFrame ctx textHover ui-      textKind <- uiCursorKind ctx textHover-      assertEq failed textKind UiCursorText--      -- Hover over scrollbar thumb -> UiCursorGrab-      case textAreaScrollBarLayout fm field contentH 0 of-        Nothing -> assert failed False-        Just layout -> do-          let-            thumb = sbThumb layout-            thumbCenter = V2 (rectX thumb + rectW thumb / 2) (rectY thumb + rectH thumb / 2)-            thumbHover = inp0 {inputMousePos = thumbCenter}-          _ <- runFrame ctx thumbHover ui-          thumbKind <- uiCursorKind ctx thumbHover-          assertEq failed thumbKind UiCursorGrab--          -- Press down on scrollbar thumb -> UiCursorGrabbing-          let-            thumbPress = thumbHover {inputMouseDown = True, inputMousePressed = True}-          _ <- runFrame ctx thumbPress ui-          grabbing <- cursorKindIs ctx thumbPress UiCursorGrabbing-          assert failed grabbing-    _ -> assert failed False--runTextAreaHScrollWheelTest :: Context -> IORef Int -> IO ()-runTextAreaHScrollWheelTest ctx failed = do-  let-    longLine = T.replicate 15 "0123456789"-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" longLine)-  (resp, _) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx (respId resp)-  case mRect of-    Just (Rect rx ry rw rh) -> do-      let-        fm = ctxFontMetrics ctx-        field = Rect rx ry rw rh-        pos = V2 (rectX field + rectW field / 2) (rectY field + rectH field / 2)-        wheelRight = inp0 {inputMousePos = pos, inputScroll = V2 1 0}-      V2 offX0 offY0 <- getScrollOffset2D ctx (respId resp)-      assertEq failed offX0 0-      assertEq failed offY0 0-      _ <- runFrame ctx wheelRight ui-      V2 offX1 offY1 <- getScrollOffset2D ctx (respId resp)-      assertGt failed offX1 offX0-      assertEq failed offY1 0-      let-        wheelRightMore = inp0 {inputMousePos = pos, inputScroll = V2 3 0}-      _ <- runFrame ctx wheelRightMore ui-      V2 offX2 _ <- getScrollOffset2D ctx (respId resp)-      assertGt failed offX2 offX1-      -- A click in the scrolled text lands on the column under the pointer,-      -- counting the horizontal offset.-      let-        (ix, iy) = widgetContentInset fm-        clickX = 30-        textClick =-          inp0-            { inputMousePos = V2 (rectX field + ix + clickX) (rectY field + iy + 5)-            , inputMouseDown = True-            , inputMousePressed = True-            }-      _ <- runFrame ctx textClick ui-      _ <- runFrame ctx textClick {inputMouseDown = False, inputMousePressed = False, inputMouseReleased = True} ui-      store <- getStore ctx-      let-        key = intKey (respId resp)-        Cursor _ col = getCursor (buffer (loadTextAreaState store key longLine))-      assert failed (abs (fromIntegral col - (offX2 + clickX) / fmAdvance fm '0') <= 1)-      let-        wheelLeft = inp0 {inputMousePos = pos, inputScroll = V2 (-10) 0}-      _ <- runFrame ctx wheelLeft ui-      V2 offX3 _ <- getScrollOffset2D ctx (respId resp)-      assertEq failed offX3 0-      -- The horizontal thumb shows the grab cursors.-      case textAreaHScrollBarLayout fm field (lineWidth fm longLine) 0 of-        Nothing -> assert failed False-        Just layout -> do-          let-            thumb = sbThumb layout-            thumbHover = inp0 {inputMousePos = V2 (rectX thumb + rectW thumb / 2) (rectY thumb + rectH thumb / 2)}-          _ <- runFrame ctx thumbHover ui-          thumbKind <- uiCursorKind ctx thumbHover-          assertEq failed thumbKind UiCursorGrab-          let-            thumbPress = thumbHover {inputMouseDown = True, inputMousePressed = True}-          _ <- runFrame ctx thumbPress ui-          grabbing <- cursorKindIs ctx thumbPress UiCursorGrabbing-          assert failed grabbing-    _ -> assert failed False--runTextAreaHScrollDragTest :: Context -> IORef Int -> IO ()-runTextAreaHScrollDragTest ctx failed = do-  let-    longLine = T.replicate 15 "0123456789"-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" longLine)-  (resp, _) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx (respId resp)-  case mRect of-    Just (Rect rx ry rw rh) -> do-      let-        fm = ctxFontMetrics ctx-        field = Rect rx ry rw rh-        contentW = lineWidth fm longLine-      V2 offX0 _ <- getScrollOffset2D ctx (respId resp)-      assertEq failed offX0 0-      case textAreaHScrollBarLayout fm field contentW offX0 of-        Nothing -> assert failed False-        Just layout -> do-          let-            thumb = sbThumb layout-            thumbCenter = V2 (rectX thumb + rectW thumb / 2) (rectY thumb + rectH thumb / 2)-            press =-              inp0-                { inputMousePos = thumbCenter-                , inputMouseDown = True-                , inputMousePressed = True-                }-          _ <- runFrame ctx press ui-          let-            drag =-              press-                { inputMousePressed = False-                , inputMousePos = V2 (v2X thumbCenter + 30) (v2Y thumbCenter)-                }-          _ <- runFrame ctx drag ui-          V2 offX1 _ <- getScrollOffset2D ctx (respId resp)-          assertGt failed offX1 offX0-          let-            release = drag {inputMouseDown = False, inputMouseReleased = True}-          _ <- runFrame ctx release ui-          store <- getStore ctx-          let-            key = intKey (respId resp)-            st = loadTextAreaState store key longLine-          assertEq failed (toText (buffer st)) longLine-          assert failed (selectionAnchor st == getCursor (buffer st))-    _ -> assert failed False--runTextArea2DScrollTest :: Context -> IORef Int -> IO ()-runTextArea2DScrollTest ctx failed = do-  let-    lines2D =-      [ T.pack (show (i :: Int)) <> " - " <> T.replicate 10 "abcdefghij"-      | i <- [1 .. 40]-      ]-    text2D = T.unlines lines2D-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" text2D)-  (resp, _) <- warmup2 ctx inp0 ui-  mRect <- getPrevRect ctx (respId resp)-  case mRect of-    Just (Rect rx ry rw rh) -> do-      let-        fm = ctxFontMetrics ctx-        field = Rect rx ry rw rh-        contentH = 40 * textAreaLineHeight fm-        contentW = maximum (0 : [lineWidth fm l | l <- lines2D])-        barLaneW = textAreaBarLane-        barLaneH = textAreaBarLane-        layouts = textAreaScrollBarLayouts fm field contentW contentH 0 0-      case (tasbVertical layouts, tasbHorizontal layouts) of-        (Just vLayout, Just hLayout) -> do-          let-            vTrack = sbTrack vLayout-            hTrack = sbTrack hLayout-          assert-            failed-            (rectY vTrack + rectH vTrack <= rectY field + rectH field - barLaneH + 1)-          assert-            failed-            (rectX hTrack + rectW hTrack <= rectX field + rectW field - barLaneW + 1)-          let-            pos = V2 (rectX field + rectW field / 2) (rectY field + rectH field / 2)-            wheel2D = inp0 {inputMousePos = pos, inputScroll = V2 2 3}-          _ <- runFrame ctx wheel2D ui-          V2 offX offY <- getScrollOffset2D ctx (respId resp)-          assertGt failed offX 0-          assertGt failed offY 0-        _ -> assert failed False-    _ -> assert failed False--runTextAreaScrollCursorLeavesViewportTest :: Context -> IORef Int -> IO ()-runTextAreaScrollCursorLeavesViewportTest ctx failed = do-  let-    longText = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]-    inp0 = withInput 320 220-    ui = column (labeledArea "Notes" longText)-  (resp, _) <- warmup2 ctx inp0 ui-  -- Focus the textarea via Tab-  _ <- runFrame ctx (tabInp inp0) ui-  mRect <- getPrevRect ctx (respId resp)-  case mRect of-    Just (Rect rx ry rw rh) -> do-      let-        field = Rect rx ry rw rh-        pos = V2 (rectX field + rectW field / 2) (rectY field + rectH field / 2)-        key = intKey (respId resp)--      -- Verify cursor is at top (line 0, col 0) and scroll is 0-      store0 <- getStore ctx-      let-        st0 = loadTextAreaState store0 key longText-        Cursor r0 c0 = getCursor (buffer st0)-      assertEq failed (r0, c0) (0, 0)-      off0 <- getScrollOffset ctx (respId resp)-      assertEq failed off0 0--      -- Scroll down while focused: caret stays at line 0, but viewport scrolls down-      let-        wheelDown = inp0 {inputMousePos = pos, inputScroll = V2 0 5}-      _ <- runFrame ctx wheelDown ui-      off1 <- getScrollOffset ctx (respId resp)-      assertGt failed off1 0--      -- Run an idle frame while textarea remains focused to ensure scroll offset does not snap back!-      _ <- runFrame ctx inp0 ui-      offIdle <- getScrollOffset ctx (respId resp)-      assertEq failed offIdle off1--      -- Verify caret in buffer is still at (0, 0) even though viewport scrolled down-      store1 <- getStore ctx-      let-        st1 = loadTextAreaState store1 key longText-        Cursor r1 c1 = getCursor (buffer st1)-      assertEq failed (r1, c1) (0, 0)--      -- Now send keyboard input: typing or navigating MUST bring the cursor back into view!-      let-        typeChar = inp0 {inputChars = "!"}-      _ <- runFrame ctx typeChar ui-      offAfterKey <- getScrollOffset ctx (respId resp)-      -- Cursor is at (0, 1), so ensureCaretVisible brings scroll offset back to 0-      assertEq failed offAfterKey 0-      store2 <- getStore ctx-      let-        st2 = loadTextAreaState store2 key longText-        Cursor r2 c2 = getCursor (buffer st2)-      assertEq failed (r2, c2) (0, 1)-    _ -> assert failed False---- | A backend-requested redraw (expose/restore, dialog-completion wake) must--- request a frame even though no user input changed. Regression: the file--- dialog's completion wake was skipped, so the result waited for the next--- unrelated event before it painted.-runRefreshRedrawTest :: Context -> IORef Int -> IO ()-runRefreshRedrawTest ctx failed = do-  let-    idle = emptyInput {inputWindowSize = Size 320 200}-    refreshed = idle {inputWindowRedraw = True}-  need <- needsRedraw ctx idle refreshed-  assert failed need---- | A context-menu Cut/Paste edits the document without any keys or chars on--- the frame, so the change must surface as a 'respChanged' pulse through the--- text-area store flag, or callers (the notepad's dirty tracking) never learn--- the document changed. Covers the hadInput guard in 'textAreaWith'. The--- caller holds the text, so the cut must also survive the--- release frame, where the caller still passes back the pre-cut result.-runTextAreaMenuPulseTest :: Context -> IORef Int -> IO ()-runTextAreaMenuPulseTest ctx failed = do-  textRef <- newIORef "abc"-  let-    inp0 = withInput 320 220-    ui = column (held textRef (textAreaWith' grow))-  (resp0, initial) <- warmup2 ctx inp0 ui-  assertEq failed initial "abc"-  mHit <- textAreaHitForWidget ctx (respId resp0)-  case mHit of-    Nothing -> assert failed False-    Just hit -> do-      let-        field = tahFieldRect hit-        mid = V2 (rectX field + rectW field / 2) (rectY field + rectH field / 2)-      -- Focus the editor, as a menu pick would.-      let-        (focusPress, focusRelease) = clickPair inp0 mid-      _ <- runFrame ctx focusPress ui >> runFrame ctx focusRelease ui-      -- Selection-only actions do not pulse: no text delta.-      _ <- runFrame ctx inp0 (runTextCommand (respId resp0) SelectAll)-      ((respSel, valSel), _, _, _) <- runFrame ctx inp0 ui-      assert failed (not (respChanged respSel))-      assertEq failed valSel "abc"-      let-        menuOpen =-          inp0-            { inputMousePos = mid-            , inputMouseRightDown = True-            , inputMouseRightPressed = True-            }-      _ <- runFrame ctx menuOpen ui-      overlays <- collectOverlayTextSpans ctx menuOpen-      case [r | (r, txt, _, _, _) <- overlays, txt == "Cut"] of-        (r : _) -> do-          -- The Cut runs through the field's command path on the press-          -- frame; the very next frame (release) must deliver the pulse and-          -- the emptied text, then go quiet again.-          let-            (pickPress, pickRelease) = clickPair inp0 (spanCenter r)-          _ <- runFrame ctx pickPress ui-          ((resp, val), _, _, _) <- runFrame ctx pickRelease ui-          assert failed (respChanged resp)-          assertEq failed val ""-          ((respIdle, valIdle), _, _, _) <- runFrame ctx inp0 ui-          assert failed (not (respChanged respIdle))-          assertEq failed valIdle ""-        _ -> assert failed False---- | A command run from a button elsewhere (an app's Edit menu) focuses the--- field it edits, so Select All followed by typing replaces the text.--- Regression: the press on the button cleared focus and 'runTextCommand' no--- longer restored it, so the typing went nowhere.-runTextCommandFocusTest :: Context -> IORef Int -> IO ()-runTextCommandFocusTest ctx failed = do-  ref <- newIORef "abc"-  let-    inp = withInput 320 220-    ui = column $ do-      (area, _) <- held ref (textAreaWith' (fixedH 80))-      selectAll <- button' "Select All"-      when (respClicked selectAll) (runTextCommand (respId area) SelectAll)-      pure selectAll-  selectAll <- warmup2 ctx inp ui-  let-    (press, release) = clickPair inp (centerOf selectAll)-  mapM_ (\i -> runFrame ctx i ui) [press, release, inp, inp {inputChars = "Z"}, inp]-  assertEq failed "Z" =<< readIORef ref---- | After the editor is remounted under a new key (the notepad remounts on file--- load), wheel-on-hover with no focus must still scroll. Regression: the--- remounted editor could not be scrolled until it was focused.-runTextAreaRemountScrollTest :: Context -> IORef Int -> IO ()-runTextAreaRemountScrollTest ctx failed = do-  let-    longText = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]-    inp0 = withInput 320 220-    mkUi k = column $ keyed k $ textAreaWith' grow longText-  _ <- warmup2 ctx inp0 (mkUi (1 :: Int))-  (resp, _) <- warmup2 ctx inp0 (mkUi (2 :: Int))-  mHit <- textAreaHitForWidget ctx (respId resp)-  case mHit of-    Nothing -> assert failed False-    Just hit -> do-      let-        field = tahFieldRect hit-        pos = V2 (rectX field + rectW field / 2) (rectY field + rectH field / 2)-        -- Large delta so hover animations settle within the warm-up frames-        -- and the idle frame below reports no damage of its own.-        settleDt = 1.0-        hover = inp0 {inputMousePos = pos, inputDeltaTime = settleDt}-        warmupFrames = 4 :: Int-      -- Park the pointer over the editor first, so the wheel frame does not-      -- also change the hot widget (whose damage would mask a missing scroll-      -- repaint).-      replicateM_ warmupFrames (runFrame ctx hover (mkUi (2 :: Int)))-      dmgIdle <- takeDamage ctx-      assert failed (damageIsEmpty dmgIdle)-      off0 <- getScrollOffset ctx (respId resp)-      _ <- runFrame ctx hover {inputScroll = V2 0 1} (mkUi (2 :: Int))-      off1 <- getScrollOffset ctx (respId resp)-      assertGt failed off1 off0-      -- The scroll offset must also damage the editor, or nothing repaints.-      dmg <- takeDamage ctx-      assert failed (not (damageIsEmpty dmg))---- | Ctrl+Z and Ctrl+Shift+Z undo and redo typing in a field; commands run from--- outside the frame edit it and pulse 'respChanged'; replacing the value the--- field is passed clears its history.-runTextUndoTest :: Context -> IORef Int -> IO ()-runTextUndoTest ctx failed = do-  ref <- newIORef ""-  commands <- newIORef []-  let-    inp = withInput 320 120-    -- Commands queued by the test run after the field, as an app's menu-    -- would; the field's undo state is read the same way.-    ui = column $ do-      (resp, _) <- held ref textInput'-      pending <- uiIO (readIORef commands)-      uiIO (writeIORef commands [])-      mapM_ (runTextCommand (respId resp)) pending-      (,) resp <$> textCanUndo (respId resp)-    ctrl = Modifiers False True False-    ctrlShift = Modifiers True True False-    frame i = (\(a, _, _, _) -> a) <$> runFrame ctx i ui-  _ <- warmup2 ctx inp ui-  _ <- frame (tabInp inp)-  mapM_ (\c -> frame inp {inputChars = T.singleton c}) ("red fox" :: String)-  assertEq failed "red fox" =<< readIORef ref-  (_, canUndo) <- frame inp-  assert failed canUndo-  _ <- frame inp {inputChars = "z", inputModifiers = ctrl}-  assertEq failed "red " =<< readIORef ref-  _ <- frame inp {inputChars = "z", inputModifiers = ctrl}-  assertEq failed "" =<< readIORef ref-  _ <- frame inp {inputChars = "z", inputModifiers = ctrlShift}-  assertEq failed "red " =<< readIORef ref-  _ <- frame inp {inputChars = "y", inputModifiers = ctrl}-  assertEq failed "red fox" =<< readIORef ref-  -- A command from outside the field's frame edits it and pulses it once.-  writeIORef commands [InsertText "!"]-  _ <- frame inp-  (pulsed, _) <- frame inp-  assert failed (respChanged pulsed)-  assertEq failed "red fox!" =<< readIORef ref-  (quiet, _) <- frame inp-  assert failed (not (respChanged quiet))-  writeIORef commands [Undo]-  _ <- frame inp-  _ <- frame inp-  assertEq failed "red fox" =<< readIORef ref-  -- The caller replacing the value drops the history recorded against the-  -- old text.-  writeIORef ref "something else"-  _ <- frame inp-  (_, stillUndoable) <- frame inp-  assert failed (not stillUndoable)---- | The content width a text area keeps up to date line by line matches a--- fresh measurement after edits that widen, move and shorten its widest line.-runTextAreaWidthTrackingTest :: Context -> IORef Int -> IO ()-runTextAreaWidthTrackingTest ctx failed = do-  ref <- newIORef (T.intercalate "\n" (replicate 200 "short line" ++ ["the widest line of them all"] ++ replicate 200 "short line"))-  let-    inp = withInput 400 300-    ui = column (held ref (textAreaWith' grow))-    frame i = (\(a, _, _, _) -> a) <$> runFrame ctx i ui-    ctrl = Modifiers False True False-    check = do-      (resp, _) <- frame inp-      mHit <- textAreaHitForWidget ctx (respId resp)-      case mHit of-        Nothing -> assert failed False-        Just hit -> do-          (tracked, _) <- textAreaContentMetrics ctx (tahNodeIdx hit)-          text <- readIORef ref-          fm <- resolveTextAreaFont ctx (tahNodeIdx hit)-          widths <- mapM (lineWidthIO fm) (T.splitOn "\n" text)-          assertEq failed (maximum widths) tracked-  _ <- warmup2 ctx inp ui-  _ <- frame (tabInp inp)-  check-  -- Widen a short line past the widest.-  mapM_ (\_ -> frame (keyInp KeyDown inp)) [1 .. 10 :: Int]-  mapM_ (\c -> frame inp {inputChars = T.singleton c}) (replicate 40 'x')-  check-  -- Shorten it again, so the old widest line wins.-  mapM_ (\_ -> frame (keyInp KeyBackspace inp)) [1 .. 40 :: Int]-  check-  -- Delete the widest line itself.-  mapM_ (\_ -> frame (keyInp KeyDown inp)) [1 .. 190 :: Int]-  _ <- frame inp {inputKeys = inputKeysFromList [KeyHome, KeyEnd], inputModifiers = Modifiers True False False}-  _ <- frame (keyInp KeyBackspace inp)-  check-  -- Undo brings it back.-  _ <- frame inp {inputChars = "z", inputModifiers = ctrl}-  check---- | The context with a clipboard kept in memory, starting with @initial@, and--- a reference to its contents.-memoryClipboard :: Maybe T.Text -> Context -> IO (Context, IORef (Maybe T.Text))-memoryClipboard initial ctx = do-  clipRef <- newIORef initial-  pure (withClipboard ctx (readIORef clipRef) (\s -> writeIORef clipRef (Just s) >> pure True), clipRef)+{-# OPTIONS_GHC -O0 #-}+module Cases.TextInput (tests) where++import Spec+import Data.Text qualified as T+import GHC.Stack (HasCallStack)+import NanoUI.Internal.Context (Context (..), intKey)+import NanoUI.Internal.Frame.TextArea+  ( TextAreaBars (..)+  , TextAreaHit (..)+  , resolveTextAreaFont+  , textAreaBarLane+  , textAreaBarLayouts+  , textAreaBars+  , textAreaContentMetrics+  , textAreaHitForWidget+  , textAreaLineHeight+  )+import NanoUI.Internal.Input (onMac)+import NanoUI.Internal.Widgets.TextArea (TextAreaState, loadTextAreaState, tasBuffer)+import NanoUI.Shortcut+import NanoUI.Testing.Sim+import NanoUI.Widgets.TextBuffer (fromText, getCursor, lineAt, toLines)++tests :: [Spec]+tests =+  [ spec "text-edits" runEditsTest+  , pixelSimSpec "text-input-press-focus" 320 120 pressFocusUi fieldPressFocus+  , spec "text-input-search-clear" runSearchClearTest+  , spec "text-input-menu-clipboard" runMenuClipboardTest+  , simSpec "text-idle" 320 220 textIdleUi textIdle+  , spec "text-input-scroll" runFieldScrollTest+  , varSimSpec "text-undo" 320 120 "" undoField textUndo+  , spec "text-area-document" runTextAreaDocumentTest+  , spec "text-area-width-tracking" runTextAreaWidthTrackingTest+  , pixelSpec "text-area-scrolling" runTextAreaScrollingTest+  , pixelSpec "text-area-zoom-scroll" runTextAreaZoomScrollTest+  , pixelSpec "text-area-remount-scroll" runTextAreaRemountScrollTest+  , pixelSpec "text-area-menu" runTextAreaMenuTest+  , pixelSpec "text-area-caret-in-view" runCaretInViewTest+  , spec "text-area-font" runTextAreaFontTest+  ]++type Field = (Response, T.Text)++-- | Each case puts its text in a fresh field, whose clipboard holds "clip",+-- and runs its steps, which check the value and clipboard as they go.+editCases :: [(Var T.Text -> NanoUI Response, T.Text, [Sim Field Field])]+editCases =+  [ -- Shift+Left selects back from the caret, typing replaces the selection,+    -- Cut leaves none, and Select All types nothing though the backend also+    -- sends its letter as text.+    ( textInput'+    , "hello"+    , [ tabKey, shiftLeft, shiftLeft, typeText "X", is "helX"+      , shiftLeft, command 'x', clipIs "X", typeText "z", is "helz"+      , chordTyping (cmdOrCtrl <> key 'a') "a", command 'c', clipIs "helz", is "helz"+      , pressKey KeyBackspace, is "", command 'v', is "helz"+      ]+    )+  , -- An event filtered to nothing keeps the selection, and navigation+    -- follows text inserted in the same frame.+    ( textInput'+    , "aOLDz"+    , [ tabKey, pressKey KeyLeft, shiftLeft, shiftLeft, shiftLeft, typeText "\n\t", is "aOLDz"+      , frameWith (\i -> (keyInp KeyLeft i) {inputChars = "é\n世界\t"}), is "aé世界z"+      , typeText "X", is "aé世X界z"+      ]+    )+  , -- Word-wise keys, as in the text area: Option on macOS, Ctrl elsewhere.+    ( textInput'+    , "hello world"+    , [ tabKey, chord (jump <> key KeyBackspace), is "hello ", chord (jump <> key KeyDelete), is "hello "+      , chord (jump <> key KeyLeft), typeText "X", is "Xhello "+      , chord (jump <> key KeyDelete), is "X "+      ]+    )+  , -- A value holding a line break keeps its caret as an offset into the+    -- whole value, and Select All selects every character.+    ( textInput'+    , "ab\ncd"+    , [tabKey, pressKey KeyLeft, typeText "X", is "ab\ncXd", command 'a', typeText "Y", is "Y"]+    )+  , -- A Windows line end stays two characters: a key that edits nothing+    -- reports no change.+    ( textInput'+    , "ab\r\ncd"+    , [tabKey, changes False (pressKey KeyLeft), is "ab\r\ncd", typeText "X", is "ab\r\ncXd"]+    )+  , -- A character typed with a command modifier, Alt (Command with Option on+    -- macOS), is the shortcut's, also a frame after the press. AltGr+    -- (Ctrl+Alt) and Option on macOS type, as does X11's AltGr reported as Alt+    -- alone when the character is not its key's.+    ( textInput'+    , "ab"+    , [ tabKey, chordTyping (commandMods <> key 'f') "f", is "ab", chordTyping commandMods "f", is "ab"+      , chordTyping ((if onMac then alt else ctrl <> alt) <> key 'f') "@", is "ab@"+      , chordTyping (alt <> key 'q') "@", is "ab@@"+      ]+    )+  , -- A drag across the text selects it, a double click a word and a triple+    -- click the line.+    (textInput', "hello", [dragAcross "hello", typeText "z", is "z"])+  , (textInput', "hello world", [clicksAtStart 2 "hello world", pressKey KeyBackspace, is " world"])+  , (textInput', "hello", [clicksAtStart 3 "hello", pressKey KeyBackspace, is ""])+  , -- A press lands on the glyph boundary under it in a run of f's.+    (textInput', "ffffff", [clickCells 3 "ffffff", typeText "x", is "fffxfff"])+  , -- Tab focus stores no caret, which reads as the text's end: a press+    -- elsewhere collapses onto it, so Tab back and typing appends.+    (textInput', "hello", [tabKey, click (At (V2 390 190)), tabKey, typeText "X", is "helloX"])+  , -- A password field shows a mask and copies nothing.+    ( textInputConfigured' defaultTextInputConfig {ticPassword = True}+    , "hunter2"+    , [ expectNot "hunter2" >> expect "*******" >> tabKey+      , command 'a', command 'c', clipIs "clip", is "hunter2"+      ]+    )+  , -- The edit menu offers Paste unfocused, and its Paste and Cut edit through+    -- the clipboard, surviving the caller passing back the frame before's value.+    -- A row picks on its release, after the field drew, so the field shows+    -- the edit on the frame after.+    ( textInput'+    , "hello"+    , [ rightClick "hello", settle, click "Paste", frame, is "helloclip"+      , rightClick "helloclip", settle, click "Cut", frame, is "", clipIs "helloclip"+      , frame, expectNot "Cut" >> result+      ]+    )+  , -- A text area reports an edit as 'respChanged', not a caret move or a+    -- selection, and Cut leaves no selection.+    ( textArea'+    , "hello"+    , [ tabKey, changes False (pressKey KeyLeft), changes False (command 'a'), command 'x'+      , clipIs "hello", is "", changes True (typeText "z"), is "z"+      ]+    )+  ]+  where+    tabKey = pressKey KeyTab+    shiftLeft = chord (shift <> key KeyLeft)+    commandMods = if onMac then super <> alt else alt+    jump = if onMac then alt else ctrl++runEditsTest :: Context -> IORef Int -> IO ()+runEditsTest _ failed = forM_ editCases $ \(widget, initial, steps) -> do+  clip <- newIORef (Just "clip")+  ctx <- (\c -> withClipboard c (readIORef clip) (\t -> writeIORef clip (Just t) >> pure True)) <$> newContext+  ref <- newVar initial+  runSim ctx failed (withInput 400 200) (column (held ref widget)) (sequence_ steps)++-- | The field's value is @want@.+is :: HasCallStack => T.Text -> Sim Field Field+is want = result >>= \r -> r <$ checkEq want (snd r)++-- | The clipboard holds @want@.+clipIs :: HasCallStack => T.Text -> Sim a a+clipIs want = do+  checkEq (Just want) =<< onContext ctxClipboardGet+  result++-- | Run the step and check whether it reported a change.+changes :: HasCallStack => Bool -> Sim Field Field -> Sim Field Field+changes want step = step >>= \r -> r <$ checkEq want (respChanged (fst r))++-- | Ctrl+@c@, Command+@c@ on macOS.+command :: Char -> Sim a a+command c = chord (cmdOrCtrl <> key c)++-- | 'chord', typing @txt@ on the same frame.+chordTyping :: Shortcut -> T.Text -> Sim a a+chordTyping s txt = do+  mods <- inputModifiers <$> getInput+  a <- frameWith (\i -> (chordInp s i) {inputChars = txt})+  a <$ modifyInput (\i -> i {inputModifiers = mods})++-- | Drag from the first to the last character of the visible text.+dragAcross :: T.Text -> Sim a a+dragAcross txt = do+  Rect x y w h <- rectOf txt+  drag (At (V2 (x + 1) (y + h / 2))) (At (V2 (x + w - 1) (y + h / 2))) 1++-- | @n@ quick clicks at the start of the visible text.+clicksAtStart :: Int -> T.Text -> Sim a a+clicksAtStart n txt = do+  Rect x y _ h <- rectOf txt+  forM_ [1 .. n] $ \k ->+    frameWith (\i -> (pressAt i (V2 (x + 1) (y + h / 2))) {inputMouseClicks = k}) >> release+  result++-- | Click the visible text @n@ characters in, measured as a run.+clickCells :: Int -> T.Text -> Sim a a+clickCells n txt = do+  fm <- ctxFontMetrics <$> simContext+  Rect x y _ h <- rectOf txt+  click (At (V2 (x + lineWidth fm (T.take n txt)) (y + h / 2)))++-- | A text area under a separate label.+labeledArea :: T.Text -> T.Text -> NanoUI (Response, T.Text)+labeledArea lbl initial = label lbl >> withValue initial textArea'++-- | Forty numbered lines, taller than a text area.+fortyLines :: T.Text+fortyLines = T.unlines ["Line " <> T.pack (show (i :: Int)) | i <- [1 .. 40]]++textAreaState :: WidgetId -> Sim a TextAreaState+textAreaState wid = onContext (fmap (`loadTextAreaState` intKey wid) . getStore)++pressFocusUi :: NanoUI (Response, T.Text)+pressFocusUi = column (label "Name" >> withValue "" (textInputConfigured' config))+  where+    config = defaultTextInputConfig {ticPlaceholder = "Enter Name"}++-- | A press near the top of a field focuses it, and it stays focused.+fieldPressFocus :: Sim (Response, T.Text) ()+fieldPressFocus = do+  wid <- respId . fst <$> result+  Rect x y w _ <- rectOf "Enter Name"+  checkEq wid =<< (press (At (V2 (x + w / 2) (y + 0.5))) >> focusedId)+  checkEq (replicate 5 wid) =<< (release >> replicateM 5 (frame >> focusedId))++-- | Emptying a search field from the keyboard, or by its clear button,+-- reports the change on that frame and only that one, rather than after the+-- debounce, and keeps focus. The clear button repaints a clip, not the+-- window.+runSearchClearTest :: Context -> IORef Int -> IO ()+runSearchClearTest _ failed =+  forM_ [selectAllDelete, clearButton] $ \empty -> do+    ctx <- newContext+    ref <- newVar "abc"+    runSim ctx failed (withInput 320 120) (column (fst <$> held ref (searchInput' "Search"))) $ do+      resp <- click . On =<< result+      check . respChanged =<< empty resp+      checkEq "" =<< readV ref+      checkEq (respId resp) =<< focusedId+      check . not . respChanged =<< frame+  where+    selectAllDelete _ = command 'a' >> pressKey KeyBackspace+    clearButton resp = do+      fm <- onContext (pure . ctxFontMetrics)+      let Rect x y w h = respRect resp+          iconW = max 12 (min 15 (fmLineHeight fm * 0.8))+      cleared <- click (At (V2 (x + w - fst (widgetContentInset fm) - iconW / 2) (y + h / 2)))+      cleared <$ (check . (/= DamageFull) =<< frameDamage)++-- | An open edit menu paints and hovers its Paste row without reading the+-- clipboard, a round trip to its owner on X11. A press on a row that cannot+-- run (nothing to undo) closes the menu.+runMenuClipboardTest :: Context -> IORef Int -> IO ()+runMenuClipboardTest base failed = do+  clipReads <- newIORef (0 :: Int)+  let ctx = withClipboard base (Nothing <$ modifyIORef' clipReads (+ 1)) (\_ -> pure True)+  runSim ctx failed (withInput 320 160) (column (withValue "hello" textInput')) $ do+    _ <- rightClick "hello" >> settle+    Rect px py pw ph <- rectOf "Paste"+    mapM_ (\x -> moveTo (At (V2 x (py + ph / 2)))) [px + 2, px + pw / 2]+    checkEq 0 =<< liftIO (readIORef clipReads)+    _ <- click "Undo" >> frame+    expectNot "Undo"++-- | Text widgets let the loop sleep: a focused field asks for no frame or+-- wake (its caret does not blink) until input or a redraw request arrives. A+-- selection drag held still past the field's edge keeps waking, so the text+-- scrolls under it, until the button comes up. A button held still in a text+-- area after a click selects nothing new and asks for nothing.+textIdleUi :: NanoUI (Field, Field)+textIdleUi = column ((,) <$> withValue "some text to select" textInput' <*> withValue "some\ntext" textArea')++textIdle :: Sim (Field, Field) ()+textIdle = do+  ((field, _), (area, _)) <- result+  let Rect fx fy fw _ = respRect field+      grab = At (V2 (fx + 4) (fy + 4))+      grabArea = At (V2 (rectX (respRect area) + 20) (rectY (respRect area) + 10))+  _ <- click grab+  modifyInput (\i -> i {inputDeltaTime = 1})+  _ <- settle+  check . not =<< wouldRedraw id+  checkEq 0 =<< wakeTime+  check =<< wouldRedraw (\i -> i {inputChars = "x"})+  check =<< wouldRedraw (\i -> i {inputWindowRedraw = True})+  _ <- press grab >> frame+  checkEq 0 =<< wakeTime+  _ <- moveTo (At (V2 (fx + fw + 40) (fy + 4)))+  checkLt 0 =<< wakeTime+  _ <- release >> frame+  checkEq 0 =<< wakeTime+  _ <- drag grabArea grabArea 1 >> frame >> frame+  _ <- targetPoint grabArea >>= \p -> frameWith (`holdAt` p)+  check . not =<< wantsFrame+  checkEq 0 =<< wakeTime++-- | End scrolls a long field's text to show its caret, and Home scrolls it+-- back. A+-- field in its own font lays out by that font: its text, caret and hit tests+-- start at its content inset (30 px in for 24 px cells, so a press just past+-- the start of the "c" puts the caret before it, not a cell later), and 17+-- cells end its caret 408 px in, past the 300 px field, where the 12 px base+-- font would not scroll.+runFieldScrollTest :: Context -> IORef Int -> IO ()+runFieldScrollTest _ failed = do+  pixel <- newPixelContext+  sized <- withMonospaceFonts 12 24 <$> newContext+  let big = defaultTextInputConfig {ticLayout = fontSize 24 . fixedW 300 . ticLayout defaultTextInputConfig}+      -- Where the field's text starts, scrolled.+      textX = rectX <$> (rectOf . snd =<< result)+      -- End scrolls the text more than @past@ left of @x0@, Home back to it.+      scrollsBack :: Float -> Float -> Sim (Response, T.Text) ()+      scrollsBack x0 past = do+        checkGt (x0 - past) =<< (pressKey KeyEnd >> textX)+        checkEq x0 =<< (pressKey KeyHome >> textX)+      long = "VeryLongTextEnteredIntoTheFieldThatExceedsTheWidth"+  runSim pixel failed (withInput 200 200) (column (withValue long textInput')) $ do+    x0 <- textX+    _ <- click . On . fst =<< result+    scrollsBack x0 0+  ref <- newVar "abcdef"+  runSim sized failed (withInputOff 400 200) (column (held ref (textInputConfigured' big))) $ do+    (resp, _) <- result+    Rect penX penY _ penH <- rectOf "abcdef"+    checkEq (rectX (respRect resp) + 24 * 1.25) penX+    _ <- click (At (V2 (penX + 2 * 24 + 4) (penY + penH / 2)))+    checkEq "abXcdef" . snd =<< typeText "X"+    _ <- pressKey KeyEnd >> typeText "ghijklmnop"+    scrollsBack penX (408 - 300)++-- | Ctrl+Z and Ctrl+Shift+Z or Ctrl+Y (Command on macOS) undo and redo typing;+-- commands run from outside the frame edit the field and pulse 'respChanged'+-- once; replacing the value the field is passed clears its history.+undoField :: Var T.Text -> NanoUI (Response, Bool)+undoField ref = column (held ref textInput' >>= \(r, _) -> (,) r <$> textCanUndo (respId r))++textUndo :: Var T.Text -> Sim (Response, Bool) ()+textUndo ref = do+  let afterChord c = chord (cmdOrCtrl <> c) >> readV ref+      runCommand c = result >>= afterView . (`runTextCommand` c) . respId . fst+  pressTab 1+  mapM_ (typeText . T.singleton) ("red fox" :: String)+  check . snd =<< frame+  checkEq ["red ", "", "red ", "red fox"] =<< mapM afterChord [key 'z', key 'z', shift <> key 'z', key 'y']+  runCommand (InsertText "!")+  checkEq [True, False] =<< replicateM 2 (respChanged . fst <$> frame)+  checkEq "red fox!" =<< readV ref+  runCommand Undo+  checkEq "red fox" =<< (frame >> readV ref)+  writeV ref "something else"+  check . not . snd =<< (frame >> frame)++-- | A text area over a 'TextDocument' hands back the document it was given+-- while nothing edits it (a caret move included) and a new one on edits, with+-- undo, and replacing the document clears its history. A caller that builds+-- an equal document every frame lets the loop sleep.+runTextAreaDocumentTest :: Context -> IORef Int -> IO ()+runTextAreaDocumentTest ctx failed = do+  let original = T.intercalate "\n" ["line " <> T.pack (show i) | i <- [0 .. 999 :: Int]]+  ref <- newVar (textDocument original)+  let ui = column (held ref textAreaDocument' >>= \(r, doc) -> (,) (r, doc) <$> textCanUndo (respId r))+      -- Whether the step reported a change and handed back the same document.+      edit step = do+        before <- readV ref+        ((r, after), undoable) <- step+        pure ((respChanged r, sameDocument before after, undoable), after)+      quiet step = checkEq (False, True) . (\((c, s, _), _) -> (c, s)) =<< edit step+  runSim ctx failed (withInput 320 220) ui $ do+    pressTab 1 >> quiet frame >> quiet (pressKey KeyDown)+    (flags, typed) <- edit (typeText "x")+    checkEq ((True, False, True), "xline 1", 1000) (flags, documentLine 1 typed, documentLineCount typed)+    check . (\((_, s, _), _) -> s) =<< edit frame+    _ <- chord (cmdOrCtrl <> key 'z')+    checkEq original . documentText =<< readV ref+    writeV ref (textDocument "fresh")+    ((_, _, undoable), fresh) <- frame >> edit frame+    checkEq (textDocument "fresh", False) (fresh, undoable)+  copyCtx <- newContext+  source <- newIORef original+  -- Split inside the frame, so each frame passes a new copy.+  let copies = column (textAreaDocument . constVar =<< liftIO (textDocument <$> readIORef source))+      idle = (withInput 320 220) {inputDeltaTime = 1}+  _ <- warmup2 copyCtx idle copies >> warmup2 copyCtx idle copies+  assert failed . not =<< needsRedraw copyCtx idle idle++-- | The content width a text area keeps up to date line by line matches a+-- fresh measurement after edits that widen, move and shorten its widest line.+runTextAreaWidthTrackingTest :: Context -> IORef Int -> IO ()+runTextAreaWidthTrackingTest ctx failed = do+  let shorts = replicate 200 "short line"+  ref <- newVar (T.intercalate "\n" (shorts ++ ["the widest line of them all"] ++ shorts))+  runSim ctx failed (withInput 400 300) (column (held ref (textAreaWith' grow))) $ do+    let widthsMatch = do+          (resp, text) <- frame+          onContext (`textAreaHitForWidget` respId resp) >>= (`checkJust` \hit -> do+            (tracked, _) <- liftIO (textAreaContentMetrics ctx (tahNodeIdx hit))+            fm <- liftIO (resolveTextAreaFont ctx (tahNodeIdx hit))+            widths <- liftIO (mapM (lineWidthIO fm) (T.splitOn "\n" text))+            checkEq (maximum widths) tracked)+    pressTab 1 >> widthsMatch+    -- Widen a short line past the widest, then shorten it again.+    replicateM_ 10 (pressKey KeyDown) >> replicateM_ 40 (typeText "x") >> widthsMatch+    replicateM_ 40 (pressKey KeyBackspace) >> widthsMatch+    -- Delete the widest line itself, then undo.+    replicateM_ 190 (pressKey KeyDown) >> chord (shift <> key KeyEnd) >> pressKey KeyBackspace >> widthsMatch+    chord (cmdOrCtrl <> key 'z') >> widthsMatch++-- | The pointer shows the text cursor over a text area's text, not its label,+-- and grab cursors on its thumbs, whose bars keep out of each other's corner.+-- Dragging a thumb or turning the wheel scrolls the area, clamped at the+-- start, without moving its caret, selecting or touching its text, and an idle+-- frame does not snap back. Typing brings the caret back into view, and a+-- click in scrolled text lands on the column under the pointer. Text that+-- fits does not scroll.+runTextAreaScrollingTest :: Context -> IORef Int -> IO ()+runTextAreaScrollingTest ctx failed = do+  let rows = [T.pack (show i) <> " - " <> T.replicate 10 "abcdefghij" | i <- [1 .. 40 :: Int]]+      txt = T.unlines rows+      fm = ctxFontMetrics ctx+  runSim ctx failed (withInput 320 220) (column (labeledArea "Notes" txt)) $ do+    (resp, _) <- result+    let field = respRect resp+        offsets = scrollOffset2DOf (respId resp)+        wheelBy d = wheel (Within field) d >> offsets+        bars = textAreaBars fm field (maximum (map (lineWidth fm) rows)) (40 * textAreaLineHeight fm)+        caret = getCursor . tasBuffer <$> textAreaState (respId resp)+        V2 _ rangeY = tabRange bars+    checkEq UiCursorDefault =<< cursorAt "Notes"+    checkEq UiCursorText =<< cursorAt (At (V2 (rectX field + 20) (rectY field + 20)))+    checkJust (uncurry (liftA2 (,)) (textAreaBarLayouts field bars 0 0)) $ \(v, h) -> do+      check (rectY (sbTrack v) + rectH (sbTrack v) <= rectY field + rectH field - textAreaBarLane + 1)+      check (rectX (sbTrack h) + rectW (sbTrack h) <= rectX field + rectW field - textAreaBarLane + 1)+      forM_ [(v, v2Y, V2 0 30), (h, v2X, V2 30 0)] $ \(bar, along, V2 dx dy) -> do+        let V2 cx cy = spanCenter (sbThumb bar)+        checkEq UiCursorGrab =<< cursorAt (At (V2 cx cy))+        checkEq UiCursorGrabbing =<< (press (At (V2 cx cy)) >> pointerCursor)+        before <- along <$> offsets+        checkLt before . along =<< (moveTo (At (V2 (cx + dx) (cy + dy))) >> offsets)+        void release+    -- Scrolled to the end, the thumb meets the end of its track.+    checkJust (fst (textAreaBarLayouts field bars 0 rangeY)) $ \end -> do+      let Rect _ ty _ th = sbTrack end+          Rect _ my _ mh = sbThumb end+      checkEq rangeY (sbMaxOff end)+      check (abs (ty + th - (my + mh)) < 0.01)+    pressTab 1+    checkEq (V2 0 0) =<< wheelBy (V2 (-10) (-10))+    V2 x0 y0 <- wheelBy (V2 2 3)+    check (x0 > 0 && y0 > 0)+    checkEq (V2 0 0) =<< wheelBy (V2 (-10) (-10))+    V2 x1 y1 <- wheelBy (V2 0 1)+    check (x1 == 0 && y1 > 0)+    checkEq (V2 0 y1) =<< (frame >> offsets)+    checkLt y1 . v2Y =<< wheelBy (V2 0 3)+    -- The caret at the start and no selection: typing inserts there.+    checkEq (V2 0 0, "!" <> txt) =<< (typeText "!" >> (,) <$> offsets <*> (snd <$> result))+    V2 x2 y2 <- wheelBy (V2 1 0)+    check (x2 > 0 && y2 == 0)+    V2 x3 _ <- wheelBy (V2 3 0)+    checkGt x3 x2+    let (ix, iy) = widgetContentInset fm+    Cursor _ col <- click (At (V2 (rectX field + ix + 30) (rectY field + iy + 5))) >> caret+    check (abs (fromIntegral col - (x3 + 30) / fmAdvance fm '0') <= 1)+    checkEq 0 . v2X =<< wheelBy (V2 (-10) 0)+  short <- newPixelContext+  runSim short failed (withInput 320 220) (column (labeledArea "Short" "Line 1\nLine 2")) $ do+    (resp, _) <- result+    checkEq 0 =<< (wheel (On resp) (V2 0 1) >> scrollOffsetOf (respId resp))++-- | A text area in its own font size scrolls as far as that font's content+-- needs, short of each bar's lane.+runTextAreaZoomScrollTest :: Context -> IORef Int -> IO ()+runTextAreaZoomScrollTest ctx failed =+  runSim ctx failed (withInput 320 220) (column (withValue fortyLines (textAreaWith' (fontSize 32)))) $ do+    (resp, _) <- result+    onContext (`textAreaHitForWidget` respId resp) >>= (`checkJust` \hit -> do+      fm <- liftIO (resolveTextAreaFont ctx (tahNodeIdx hit))+      let field = tahFieldRect hit+          contentH = fromIntegral (max 1 (length (toLines (fromText fortyLines)))) * tahLineH hit+          contentW = maximum (0 : [lineWidth fm l | l <- T.lines fortyLines])+          (ix, iy) = widgetContentInset fm+          innerW = rectW field - 2 * ix+          innerH = rectH field - 2 * iy+          hasH = contentW > (if contentH > innerH then max 0 (innerW - textAreaBarLane) else innerW)+          availH = if hasH then max 0 (innerH - textAreaBarLane) else innerH+      off <- wheel (Within field) (V2 0 100) >> scrollOffsetOf (respId resp)+      check (abs (off - max 0 (contentH - availH)) < 0.5))++-- | An editor mounted under a fresh key scrolls on wheel hover without+-- focus, and the scroll damages it so it repaints.+runTextAreaRemountScrollTest :: Context -> IORef Int -> IO ()+runTextAreaRemountScrollTest ctx failed = do+  keyRef <- newIORef (1 :: Int)+  let ui = column (liftIO (readIORef keyRef) >>= \k -> withKey k (withValue fortyLines (textAreaWith' grow)))+  runSim ctx failed (withInput 320 220) ui $ do+    liftIO (writeIORef keyRef 2)+    (resp, _) <- settle+    -- Settle hover animations in 1 s frames, or a hot-widget change on the+    -- wheel frame would damage the area and mask a missing scroll repaint.+    modifyInput (\i -> i {inputDeltaTime = 1})+    _ <- moveTo (On resp) >> replicateM_ 3 frame+    check . damageIsEmpty =<< frameDamage+    _ <- frameWith (\i -> i {inputScroll = V2 0 1})+    checkLt 0 =<< scrollOffsetOf (respId resp)+    check . not . damageIsEmpty =<< frameDamage++-- | The edit menu edits a text area with no key or text on the frame. Select+-- All keeps the whole document selected once the button comes up (the+-- gesture moves no caret and starts no drag), so Cut empties it, pulsing+-- 'respChanged' once, on the frame after its release, the first the field+-- draws after the pick. A command that only selects pulses nothing.+runTextAreaMenuTest :: Context -> IORef Int -> IO ()+runTextAreaMenuTest ctx failed = do+  let original = T.intercalate "\n" ["line " <> T.pack (show i) | i <- [0 .. 200 :: Int]]+  ref <- newVar original+  runSim ctx failed (withInput 400 300) (column (held ref (textAreaWith' grow))) $ do+    (resp, _) <- result+    let Rect x y w h = respRect resp+        mid = At (V2 (x + w / 3) (y + h / 3))+        pick entry = rightClick mid >> settle >> click entry+        changedValue (r, v) = (respChanged r, v)+    _ <- click mid+    afterView (runTextCommand (respId resp) SelectAll)+    checkEq (False, original) . changedValue =<< frame+    checkEq (True, "") . changedValue =<< (pick "Select All" >> pick "Cut" >> frame)+    checkEq (False, "") . changedValue =<< frame++-- | A text area keeps its caret in view: typing past its right edge scrolls+-- across, and Home back; the caret moved to the last row sits above the+-- horizontal bar's lane; and keys follow the rows as painted on the device+-- pixel grid, 12.8 px apart for a 13 px font at 125%, not 13.+runCaretInViewTest :: Context -> IORef Int -> IO ()+runCaretInViewTest base failed = do+  let area ctx ref widget script =+        runSim ctx failed (withInput 320 220) (column (fst <$> held ref widget)) $ do+          wid <- respId <$> result+          pressTab 1+          script (onContext (`caretInView` wid)) (scrollOffset2DOf wid)+  follow <- newPixelContext+  typed <- newVar ""+  area follow typed (textAreaWith' (fixedW 200)) $ \inView offsets -> do+    check . and =<< replicateM 60 (typeText "x" >> inView)+    checkEq 60 . T.length =<< readV typed+    checkLt 0 . v2X =<< offsets+    checkEq 0 . v2X =<< (pressKey KeyHome >> offsets)+  wide <- newPixelContext+  wideRef <- newVar (T.replicate 30 "wide " <> "\n" <> fortyLines)+  area wide wideRef textArea' $ \inView _ -> command 'a' >> frame >> (check =<< inView)+  let fm = (monospaceMetrics 13) {fmSnapScale = 1.25}+      measure _ _ _ _ t = pure (13 * fromIntegral (T.length t), 13)+      snapped = withFontResolver base (\_ _ _ _ -> pure (fm, False)) measure+  blank <- newVar (T.replicate 59 "\n")+  area snapped blank (textAreaWith' (fontSize 13)) $ \inView _ ->+    check . and =<< mapM (\k -> pressKey k >> inView) (replicate 59 KeyDown ++ replicate 20 KeyUp)++-- | Whether text area @wid@'s caret, at its stored scroll, lies inside the+-- clip its rows are painted in: its content box, short of the lane of each+-- scrollbar that shows.+caretInView :: Context -> WidgetId -> IO Bool+caretInView ctx wid = do+  st <- (`loadTextAreaState` intKey wid) <$> getStore ctx+  V2 sx sy <- getScrollOffset2DIO ctx wid+  textAreaHitForWidget ctx wid >>= \case+    Nothing -> pure False+    Just (TextAreaHit idx field lineH) -> do+      fm <- resolveTextAreaFont ctx idx+      (contentW, contentH) <- textAreaContentMetrics ctx idx+      let+        bars = textAreaBars fm field contentW contentH+        (ix, iy) = widgetContentInset fm+        lane shown = if shown then textAreaBarLane else 0+        viewW = rectW field - 2 * ix - lane (tabVertical bars)+        viewH = rectH field - 2 * iy - lane (tabHorizontal bars)+        Cursor caretRow caretCol = getCursor (tasBuffer st)+        left = lineWidth fm (T.take caretCol (lineAt caretRow (tasBuffer st))) - sx+        top = fromIntegral caretRow * lineH - sy+      pure (left >= -0.5 && left + 1 <= viewW + 0.5 && top >= -0.5 && top + lineH <= viewH + 0.5)++-- | A text area sets its rows in the face its layout names, not only the+-- size, and in its font colour, which the caret takes too. A change of face+-- measures the lines again.+runTextAreaFontTest :: Context -> IORef Int -> IO ()+runTextAreaFontTest base failed = do+  let+    ctx = withMonoFontMetrics base (monospaceMetrics 20)+    red = colorRGBA 255 0 0 255+    inp0 = withInput 320 220+    ui f = column (fst <$> withValue "code" (textAreaWith' f))+    widest resp =+      textAreaHitForWidget ctx (respId resp) >>= traverse (fmap fst . textAreaContentMetrics ctx . tahNodeIdx)+  resp <- warmup2 ctx inp0 (ui (fontMono . fontColor red))+  (_, draw, _) <- runFrame ctx (tabInp inp0) (ui (fontMono . fontColor red))+  assertJustM failed (textAreaHitForWidget ctx (respId resp)) $ \hit -> do+    assertEq failed 20 (tahLineH hit)+    assertEq failed 20 . fmLineHeight =<< resolveTextAreaFont ctx (tahNodeIdx hit)+  assert failed . elem red . fillsIn (respRect resp) =<< drawQuads draw+  assertEq failed (Just 80) =<< widest resp+  assertEq failed (Just 48) =<< widest =<< warmup2 ctx inp0 (ui id)
+ test/integration/Cases/Theming.hs view
@@ -0,0 +1,207 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Theming (tests) where++import Spec+import Data.Text (Text)+import Data.Maybe (isNothing)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (arenaCount, getNodeType, getStyleIdx)++tests :: [Spec]+tests =+  [ spec "popup-style" runPopupStyleTest+  , spec "warning-tone" runWarningToneTest+  , spec "theme-values" runThemeValuesTest+  , spec "follow-system-theme" runFollowSystemThemeTest+  , spec "view-picks-theme" runViewPicksThemeTest+  ]++inp :: Input+inp = withInput 400 300++-- | The foreground of the span showing @txt@.+spanFg :: Text -> [(Rect, Text, Color, Color, Rect)] -> Maybe Color+spanFg txt spans = lookup txt [(t, fg) | (_, t, fg, _, _) <- spans]++-- | The last of @n@ frames of @ui@: its result, the quads drawn, and the text spans.+frames :: Int -> Context -> NanoUI a -> IO (a, [(Rect, Color)], [DemoSpan])+frames n ctx ui = do+  replicateM_ (n - 1) (warmup ctx inp ui)+  (a, draw, _) <- runFrame ctx inp ui+  (,,) a <$> drawQuads draw <*> collectTextSpans ctx++-- | Tones colour text, rich text pieces and buttons from the theme, fading when+-- disabled; a tone combines with a face in either order, stored apart in the node.+runWarningToneTest :: Context -> IORef Int -> IO ()+runWarningToneTest ctx failed = do+  theme <- getThemeIO ctx+  let amber = themeWarning theme+      warned = labelWith (fontTone Warning)+      own = colorRGBA 1 2 3 255+  ((w, d, p), quads, spans) <- frames 2 ctx . column $ do+    warned "Careful" >> danger "Broken" >> disabledWhen True (warned "Faded")+    labelWith (fontMono . fontTone Warning) "mono warning"+    labelWith (fontTone Warning . fontMono) "warning mono"+    labelWith fontMuted "muted"+    labelWith fontDanger "danger tone"+    labelWith (fontTone Danger . fontColor own) "own colour"+    (,,) <$> styled warning (button' "Warn") <*> styled destructive (button' "Delete") <*> button' "Plain"+  let fills r = fillsIn (respRect r) quads+      faded = themeWarning (disabledTheme theme)+      fgs =+        [ ("Careful", amber), ("Broken", themeDanger theme), ("Faded", faded), ("mono warning", amber)+        , ("warning mono", amber), ("muted", themeMuted theme), ("danger tone", themeDanger theme)+        , ("own colour", own)+        ]+      regular = (,) FontRegular . Just+      faces = map regular [Warning, Danger, Warning] ++ replicate 2 (FontMono, Just Warning)+        ++ map regular [Muted, Danger, Danger]+  assertJust failed (spanRectOf "Careful" spans) $ \r -> assert failed (amber `elem` fillsIn r quads)+  assert failed (amber `notElem` [themeDanger theme, faded])+  assertEq failed (map (Just . snd) fgs) (map ((`spanFg` spans) . fst) fgs)+  let na = ctxNodeArena ctx+  n <- arenaCount na+  styles <- forM [0 .. n - 1] $ \i -> (,) <$> getNodeType na i <*> getStyleIdx na i+  assertEq failed faces [(textNodeFontVariant si, textNodeFontTone si) | (NodeText, si) <- styles]+  assertEq failed [True, True, False] [elem amber (fills w), elem (themeDanger theme) (fills d), elem amber (fills p)]+  assertEq failed (Just (readableOn theme amber), amber) $+    (spanFg "Warn" spans, styleBg (themeButton (warning theme)))+  offTheme <- warmup2 ctx inp (column (disabledWhen True (styled warning uiTheme)))+  assertEq failed (styleBg (themeButton offTheme)) (styleBg (themeButton (disabledTheme (warning theme))))+  let richCases = [(["Plain text"], False), (["Plain ", inlineWith (fontTone Warning) "text"], True)]+  forM_ richCases $ \(pieces, warns) -> do+    (_, rich, _) <- frames 2 ctx (column (richText pieces))+    assertEq failed warns (amber `elem` map snd rich)++-- | The built-in themes, by name.+builtInThemes :: [(String, Theme)]+builtInThemes =+  [ ("default", defaultTheme)+  , ("default light", defaultLightTheme)+  , ("tomorrow night", tomorrowNightMinDarkTheme)+  , ("tomorrow light", tomorrowMinLightTheme)+  , ("tomorrow midnight", tomorrowMidnightMinDarkTheme)+  , ("base16 night", themeFromBase16 base16TomorrowNight)+  , ("base16 light", themeFromBase16 base16TomorrowLight)+  ]++-- | Built-in themes' tones reach 4.5:1 contrast, and their page sets light or dark.+-- The page is the window unless set; 'lightDark' picks dark for an unknown system.+runThemeValuesTest :: Context -> IORef Int -> IO ()+runThemeValuesTest _ failed = do+  forM_ builtInThemes $ \(name, t) -> do+    let amber = themeWarning t+        readable c = contrastRatio c (pageBackground t) >= 4.5+        readable' c = contrastRatio (readableOn t c) c >= 4.5+    assertEq failed (name, True, True) (name, all readable [themeSuccess t, amber, themeDanger t], readable' amber)+    assertEq failed (name, True, True) (name, amber /= themeDanger t, themeSuccess t /= themeDanger t)+  assertEq failed [dark, light, dark, light, dark, dark, light] (map (themeAppearance . snd) builtInThemes)+  let t = tomorrowMinLightTheme+  assert failed (styleBg (themeButton (tone Danger t)) == themeDanger t)+  assert failed (and [toneColor (disabledTheme t) c /= toneColor t c | c <- [Success, Warning, Danger]])+  let panelBg = styleBg (themePanel defaultTheme)+      red = colorRGBA 1 2 3 255+  forM_+    [ (themeWindow defaultTheme, id)+    , (panelBg, panelPage)+    , (red, pageColor red)+    , (panelBg, panelPage . pageColor red)+    , -- A translucent panel surface leaves an unset page alone.+      (themeWindow defaultTheme, panelStyle (background colorTransparent))+    ]+    $ \(want, f) -> assertEq failed want (pageBackground (f defaultTheme))+  let picks = [Just light, Just dark, Nothing]+      picked = map (lightDark defaultLightTheme defaultTheme) picks+  assertEq failed [defaultLightTheme, defaultTheme, defaultTheme] picked+  assertEq failed picked (map defaultThemeFor picks)+  where+    (dark, light) = (AppearanceDark, AppearanceLight)++-- | Following the system switches and restyles on a change, waking the loop; a repeat+-- does nothing. After 'setTheme', a switch keeps the theme but still repaints.+runFollowSystemThemeTest :: Context -> IORef Int -> IO ()+runFollowSystemThemeTest ctx failed = do+  let ui = column $ do+        labelWith (fontTone Warning) "Careful"+        (,) <$> button' "Go" <*> styled warning (button' "Warn")+      painted theme ((go, warn), quads, spans) = do+        assertEq failed (Just (themeWarning theme)) (spanFg "Careful" spans)+        assert failed (styleBg (themeButton theme) `elem` fillsIn (respRect go) quads)+        assert failed (themeWarning theme `elem` fillsIn (respRect warn) quads)+        pure quads+  setSystemAppearance ctx (Just AppearanceLight)+  followSystemThemeIO ctx (lightDark defaultLightTheme defaultTheme)+  getThemeIO ctx >>= assertEq failed defaultLightTheme+  _ <- frames 2 ctx ui >>= painted defaultLightTheme+  wakes <- newIORef (0 :: Int)+  setWakeLoop ctx (modifyIORef' wakes (+ 1))+  setSystemAppearance ctx (Just AppearanceDark)+  getThemeIO ctx >>= assertEq failed defaultTheme+  getSystemAppearance ctx >>= assertEq failed (Just AppearanceDark)+  readIORef wakes >>= assert failed . (> 0)+  checkIdleFullDamage failed ctx inp inp ui+  quads <- frames 1 ctx ui >>= painted defaultTheme+  assert failed (themeWarning defaultLightTheme `notElem` map snd quads)+  writeIORef wakes 0+  setSystemAppearance ctx (Just AppearanceDark)+  isDirty ctx >>= assert failed . not+  readIORef wakes >>= assertEq failed 0+  -- Back to light, then to an unknown appearance, for which 'lightDark' picks dark.+  setSystemAppearance ctx (Just AppearanceLight)+  getThemeIO ctx >>= assertEq failed defaultLightTheme+  setSystemAppearance ctx (Just AppearanceLight) >> setSystemAppearance ctx Nothing+  getThemeIO ctx >>= assertEq failed defaultTheme+  setThemeIO ctx tomorrowMidnightMinDarkTheme+  warmup ctx inp ui+  setSystemAppearance ctx (Just AppearanceLight)+  getThemeIO ctx >>= assertEq failed tomorrowMidnightMinDarkTheme+  checkIdleFullDamage failed ctx inp inp ui++-- | A view sees an appearance change next frame; setting its theme from it every frame+-- (twice, or over a context following the system) settles a frame after a switch.+runViewPicksThemeTest :: Context -> IORef Int -> IO ()+runViewPicksThemeTest ctx failed = do+  let shown = maybe "unknown" (\a -> if a == AppearanceDark then "dark" else "light")+      picking extra = column $ do+        appearance <- systemAppearance+        label (shown appearance)+        setTheme (lightDark defaultLightTheme defaultTheme appearance)+        extra >> button "Go"+      settles ui = do+        warmup ctx inp ui+        isDirty ctx >>= assert failed . not+        takeDamage ctx >>= assert failed . damageIsEmpty+      switchTo appearance theme extra = do+        setSystemAppearance ctx (Just appearance)+        needsRedraw ctx inp inp >>= assert failed+        _ <- warmup2 ctx inp (picking extra)+        collectTextSpans ctx >>= assertSpansHas failed (shown (Just appearance))+        getThemeIO ctx >>= assertEq failed theme+        settles (picking extra)+  warmup ctx inp (picking (pure ()))+  collectTextSpans ctx >>= assertSpansHas failed "unknown"+  switchTo AppearanceLight defaultLightTheme (pure ())+  switchTo AppearanceDark defaultTheme (pure ())+  -- Two themes per frame: the last wins, with one repaint.+  _ <- warmup2 ctx inp (picking (setTheme tomorrowMinLightTheme))+  getThemeIO ctx >>= assertEq failed tomorrowMinLightTheme+  settles (picking (setTheme tomorrowMinLightTheme))+  -- A view's theme overrides following the system.+  followSystemThemeIO ctx (lightDark defaultLightTheme defaultTheme)+  _ <- warmup2 ctx inp (setTheme tomorrowMinLightTheme >> button "Go")+  setSystemAppearance ctx (Just AppearanceLight)+  getThemeIO ctx >>= assertEq failed tomorrowMinLightTheme+  readIORef (ctxThemeFor ctx) >>= assert failed . isNothing++-- | 'popupStyle' colours a modal's surface and not the panels inside it.+runPopupStyleTest :: Context -> IORef Int -> IO ()+runPopupStyleTest ctx failed = do+  let sea = colorRGBA 12 60 90 255+      ui = styled (popupStyle (background sea)) $ do+        let body = panelWith (fixedWH 120 40 . tight) (snd <$> mouseArea (fillW . fillH) (pure ()))+        fmap respRect . snd <$> modal' (constVar True) "Dialog" body+  (inner, draw) <- warmupDraw ctx inp ui+  quads <- drawQuads draw+  panelBg <- styleBg . themePanel <$> getThemeIO ctx+  assert failed (sea `elem` map snd quads)+  assertJust failed inner $ \r -> assert failed (panelBg `elem` fillsIn r quads)
test/integration/Cases/Tooltip.hs view
@@ -1,113 +1,73 @@-module Cases.Tooltip-  ( runTooltipHoverTest-  , runTooltipIdStableTest-  , runTooltipScrollPosTest-  ) where--import Control.Monad (void)-import Data.IORef (IORef)-import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, evalUi, withInput)-import NanoUI.Testing.Harness-  ( centerOf-  , hasText-  , spanCenter-  , warmup2-  )+{-# OPTIONS_GHC -O0 #-}+module Cases.Tooltip (tests) where --- Hovering shows a text tooltip, and a widget tooltip only evaluates its body--- while hovered.-runTooltipHoverTest :: Context -> IORef Int -> IO ()-runTooltipHoverTest ctx failed = do-  let inp0 = withInput 640 480-      ui = rowWith fillW $ do-        help <- button' "Help Target"-        tooltip help "Helpful advice here"-        _ <- spacer (Grow 1) Fit-        rich <- button' "Rich Info"-        body <- tooltipWidget rich $ do-          row $ do-            void (label "[Icon]")-            label "Rich tooltip body text"-        pure (help, rich, body)+import Spec+import NanoUI.Internal.Context (getFocusables)+import NanoUI.Testing.Sim -  -- Unhovered: no tooltip overlay, and the widget body is not evaluated-  (help, rich, body0) <- warmup2 ctx inp0 ui-  spans0 <- collectOverlayTextSpans ctx inp0-  assert failed (not (hasText "Helpful advice" spans0))-  assert failed (case body0 of Nothing -> True; _ -> False)+tests :: [Spec]+tests =+  [ simSpec "tooltip-targets" 400 300 targetsUi tooltipTargets+  , spec "tooltip-passthrough" runTooltipPassThroughTest+  ] -  -- Hovered: tooltip overlay present-  let hoverHelp = inp0 {inputMousePos = centerOf help}-  _ <- runFrame ctx hoverHelp ui-  _ <- runFrame ctx hoverHelp ui-  spans1 <- collectOverlayTextSpans ctx hoverHelp-  assert failed (hasText "Helpful advice" spans1)+now :: TooltipConfig+now = defaultTooltipConfig {tooltipDelay = 0} -  let hoverRich = inp0 {inputMousePos = centerOf rich}-  _ <- runFrame ctx hoverRich ui-  ((_, _, body1), _, _, _) <- runFrame ctx hoverRich ui-  assert failed (case body1 of Just _ -> True; Nothing -> False)+targetsUi :: NanoUI (Response, Response, Response)+targetsUi = columnWith tight $ do+  off <- disabledWhen True (buttonWith' (fixedWH 200 40) "Off")+  tooltipConfigured now off "Why it is off"+  _ <- buttonWith' (pinAt 150 0 . fixedWH 40 40) "cover"+  near <- buttonWith' (fixedWH 100 30) "Near"+  tooltipConfigured now {tooltipGap = 4} near "Near tip"+  far <- buttonWith' (fixedWH 100 30) "Far"+  tooltipWidgetConfigured now {tooltipGap = 20} far (label "Far tip")+  pure (off, near, far) -runTooltipIdStableTest :: Context -> IORef Int -> IO ()-runTooltipIdStableTest ctx failed = do-  let inp0 = withInput 640 480-      ui = column $ do-        a <- button' "Help Target"-        tooltip a "tip"-        b <- button' "After"-        pure (a, b)-  (a0, b0) <- evalUi ctx inp0 ui-  let hoverInp = inp0 {inputMousePos = centerOf a0}-  _ <- runFrame ctx hoverInp ui-  ((_, b1), _, _, _) <- runFrame ctx hoverInp ui-  assert failed (respId b0 == respId b1)+-- | A disabled widget shows its tooltip where the pointer is on it uncovered,+-- though it reports no hover. 'tooltipGap' sets the space below the target,+-- and a widget tooltip evaluates its body only while shown.+tooltipTargets :: Sim (Response, Response, Response) ()+tooltipTargets = do+  (_, near, far) <- result+  let offTip p = do+        (off, _, _) <- moveTo (At p) >> settle+        shown <- labelShown "Why it is off"+        farShown <- labelShown "Far tip"+        pure (respHovered off, farShown, shown)+      gapUnder r tip = do+        _ <- moveTo (On r) >> settle+        farShown <- labelShown "Far tip"+        (\t -> (farShown, rectY t - rectY (respRect r) - rectH (respRect r))) <$> rectOf tip+  checkEq [(False, False, True), (False, False, False), (False, False, False)]+    =<< mapM offTip [V2 60 20, V2 170 20, V2 300 150]+  (farNear, g4) <- gapUnder near "Near tip"+  (farFar, g20) <- gapUnder far "Far tip"+  checkEq (False, True, 16) (farNear, farFar, g20 - g4) -runTooltipScrollPosTest :: Context -> IORef Int -> IO ()-runTooltipScrollPosTest ctx failed = do-  let inp0 = withInput 200 200-      ui =-        scrollArea (fillW . fixedH 80) $-          column $ do-            mapM_ (\_ -> void (label "pad line")) [(1 :: Int) .. 40]-            btn <- button' "Tip Target"-            tooltip btn "Scrolled tip text"-            mapM_ (\_ -> void (label "tail line")) [(1 :: Int) .. 12]-            pure btn-  (sid, _) <- warmup2 ctx inp0 ui-  mScroll <- getPrevRect ctx sid-  case mScroll of-    Nothing -> assert failed False-    Just scrollRect@(Rect _ sy _ sh) -> do-      let hover = inp0 {inputMousePos = spanCenter scrollRect}-          wheel = hover {inputScroll = V2 0 1}-          inView btn =-            let y = rectY (respRect btn)-                h = rectH (respRect btn)-             in y >= sy + 4 && y + h + 16 <= sy + sh-          pump = do-            before <- getScrollOffset ctx sid-            _ <- runFrame ctx wheel ui-            after <- getScrollOffset ctx sid-            ((_, btn), _, _, _) <- runFrame ctx hover ui-            if inView btn || after <= before then pure (after, btn) else pump-      (off, btn1) <- pump-      assert failed (off > 0)-      let hoverInp = inp0 {inputMousePos = centerOf btn1}-          visualBottom = rectY (respRect btn1) + rectH (respRect btn1)-          layoutBottom = visualBottom + off-      _ <- runFrame ctx hoverInp ui-      _ <- runFrame ctx hoverInp ui-      spans <- collectOverlayTextSpans ctx hoverInp-      let ys =-            [ rectY r-            | (r, txt, _, _, _) <- spans-            , "Scrolled tip" `T.isInfixOf` txt-            ]-      case ys of-        [] -> assert failed False-        (tipY : _) -> do-          assert failed (abs (tipY - visualBottom) <= 16)-          assert failed (abs (tipY - visualBottom) < abs (tipY - layoutBottom))+-- | A rich tooltip passes pointer events through to widgets underneath and+-- keeps controls inside its body inert (outside the keyboard focus order).+runTooltipPassThroughTest :: Context -> IORef Int -> IO ()+runTooltipPassThroughTest ctx failed = do+  tipClicks <- newIORef (0 :: Int)+  underClicks <- newIORef (0 :: Int)+  let ui = columnWith (tight . gap 4) $ do+        top <- buttonWith' (fixedWH 140 30) "Top"+        under <- buttonWith' (fixedWH 140 30) "Underneath"+        when (respClicked under) (liftIO (modifyIORef' underClicks (+ 1)))+        tooltipWidgetConfigured now {tooltipGap = 4} top $ do+          tipBtn <- buttonWith' (fixedWH 140 30) "TipBtn"+          when (respClicked tipBtn) (liftIO (modifyIORef' tipClicks (+ 1)))+        pure (top, under)+  runSim ctx failed (withInput 400 200) ui $ do+    (top, under) <- result+    -- Hover "Top" so the tooltip opens directly over "Underneath".+    _ <- moveTo (On top) >> settle+    check =<< labelShown "TipBtn"+    -- Focusables must include only "Top" and "Underneath", never "TipBtn".+    focs <- onContext getFocusables+    checkEq [respId top, respId under] focs+    -- Clicking over "Underneath" (covered visually by the tooltip) reaches "Underneath".+    _ <- click (On under) >> settle+    checkEq (0, 1) =<< liftIO ((,) <$> readIORef tipClicks <*> readIORef underClicks)
+ test/integration/Cases/TooltipDelay.hs view
@@ -0,0 +1,204 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.TooltipDelay (tests) where++import Control.Concurrent (threadDelay)+import Data.IntMap.Strict qualified as IM+import Data.Text qualified as T+import GHC.Clock (getMonotonicTime)+import NanoUI.Testing.Sim+import Spec++tests :: [Spec]+tests =+  [ spec "tooltip-delay" runTooltipDelayTest+  , simSpec "tooltip-grace" 400 300 (tipRow [cfg 0 0.3, cfg 10 5, cfg 10 0]) graceOpens+  , simSpec "tooltip-grace-after-rest" 400 300 (tipRow [cfg 10 0.1, cfg 0.05 0.1, cfg 10 0.1]) graceAfterRest+  , simSpec "tooltip-target-not-widget" 400 300 notWidgetUi tooltipTargetNotWidget+  , simSpec "tooltip-follow-cursor" 400 260 followUi tooltipFollowCursor+  ]++cfg :: Double -> Double -> TooltipConfig+cfg d g = defaultTooltipConfig {tooltipDelay = d, tooltipGrace = g}++-- | The text of each tooltip the last frame drew.+tips :: Sim a [T.Text]+tips = (\ss -> filter (`hasText` ss) names) <$> spans+  where+    names = ["Tip text", "Alpha tip", "Bravo tip", "Charlie tip", "Label tip", "Box tip"]++-- | The tooltips drawn by the frames of @act@.+tipsAfter :: Sim a b -> Sim a [T.Text]+tipsAfter act = act >> tips++sleep :: Double -> Sim a ()+sleep s = liftIO (threadDelay (round (s * 1e6)))++away :: Target+away = At (V2 390 290)++-- | Rects of all floating panels, i.e. the open tooltips.+tipRects :: Sim a [Rect]+tipRects = onContext (fmap IM.elems . floatingPanelRects)++-- | Whether a pointer moving to @p@ from where it is would need a frame.+redrawsFor :: V2 -> Sim a Bool+redrawsFor p = wouldRedraw (\i -> i {inputMousePos = p})++-- | A button with a tooltip declared while the ref holds its delay, and the+-- next button's id (which changes if the tooltip shifts sibling ids).+tipView :: IORef (Maybe Double) -> NanoUI (Response, WidgetId)+tipView ref = column $ do+  delay <- liftIO (readIORef ref)+  target <- button' "Tip Target"+  forM_ delay $ \d -> tooltipConfigured (cfg d 0) target "Tip text"+  (target,) . respId <$> button' "After"++-- | Hovering waits for the delay with one wake and no frames; the first frame+-- after opens and repaints the tooltip. Leaving, any button press or a wheel+-- turn closes and repaints it, with no wake while a button is held. Omitting+-- the tooltip for a frame resets its delay.+runTooltipDelayTest :: Context -> IORef Int -> IO ()+runTooltipDelayTest ctx failed = do+  ref <- newIORef (Just 10)+  runSim ctx failed (withInput 400 300) (tipView ref) $ do+    (target, after0) <- result+    let waking yes = check . (if yes then (> 0) else (== 0)) =<< wakeTime+        none act = checkEq [] =<< tipsAfter act+        declare = liftIO . writeIORef ref+        -- Past the 0.05 s delay.+        wait = sleep 0.06+        opens = wait >> (checkEq ["Tip text"] =<< tipsAfter frame)+        settles = do+          (_, after1) <- frame >> frame+          again <- wantsFrame+          checkEq (False, after0) (again, after1)+          check . not =<< redrawsFor . inputMousePos =<< getInput+        V2 cx cy = centerOf target+    -- The long frame time finishes the hover animation.+    modifyInput (\i -> i {inputDeltaTime = 1})+    before <- liftIO getMonotonicTime+    none (moveTo (On target))+    w <- wakeTime+    check (w >= before + 10 && w < before + 11)+    settles+    none (moveTo (At (V2 (cx + 6) (cy + 2))))+    checkEq w =<< wakeTime+    declare (Just 0.05)+    none (moveTo away >> moveTo (On target))+    _ <- frameDamage+    opens+    dmg <- frameDamage+    up <- tipRects+    check (not (null up) && all (damageCovers dmg) up)+    checkEq 0 =<< wakeTime+    settles+    checkEq ["Tip text"] =<< tips+    none (moveTo away)+    check . (\d -> all (damageCovers d) up) =<< frameDamage+    waking False+    forM_ [MouseLeft, MouseMiddle, MouseBack, MouseForward] $ \b -> do+      none (moveTo (On target))+      opens+      none (pressButton b (On target))+      none frame+      waking False+      wait >> none frame+      none (releaseButton b)+      waking True+    opens+    none (frameWith (\i -> i {inputScroll = V2 0 1}))+    waking True+    opens+    -- Omitted for a frame while pending, then declared again on the target.+    none (moveTo away >> moveTo (On target))+    declare Nothing >> none frame+    declare (Just 0.05) >> wait >> none frame+    opens++-- | Buttons Alpha, Bravo and Charlie with tooltips "Alpha tip", etc.+tipRow :: [TooltipConfig] -> NanoUI [Response]+tipRow cfgs = row . forM (zip ["Alpha", "Bravo", "Charlie"] cfgs) $ \(name, c) -> do+  r <- button' name+  r <$ tooltipConfigured c r (name <> " tip")++-- | A tooltip opens immediately within its grace period after another one+-- closes; without a grace period, or after a press, it waits.+graceOpens :: Sim [Response] ()+graceOpens = do+  [a, b, c] <- map On <$> result+  let steps = [moveTo a, moveTo c, moveTo a, moveTo b, moveTo a, press a, moveTo b, release]+      shown = [["Alpha tip"], [], ["Alpha tip"], ["Bravo tip"], ["Alpha tip"], [], [], []]+  checkEq shown =<< mapM tipsAfter steps++-- | The grace period starts when a tooltip closes, whether the next tooltip+-- is declared before or after it. Once it expires, the next one waits again.+graceAfterRest :: Sim [Response] ()+graceAfterRest = do+  [a, b, c] <- map On <$> result+  -- Longer than the grace period, with no frames run.+  let rest = sleep 0.15+      steps =+        [ (moveTo b, [])+        , (sleep 0.06 >> frame, ["Bravo tip"])+        , (rest >> moveTo c, ["Charlie tip"])+        , (rest >> moveTo b, ["Bravo tip"])+        , (rest >> moveTo away, [])+        , (rest >> moveTo a, [])+        ]+  forM_ steps $ \(act, want) -> checkEq want =<< tipsAfter act+  check . (> 0) =<< wakeTime++notWidgetUi :: NanoUI Response+notWidgetUi = column $ do+  l <- labelWith' (fixedW 200) "Label target"+  tooltipConfigured (cfg 0.05 0.3) l "Label tip"+  -- A container, as 'withTooltip' wraps its target in, with a short delay.+  (_, holder) <- columnWith' (fixedW 200 . fixedH 60) (label "Container target")+  l <$ tooltipWidgetConfigured (cfg 0.05 0.3) holder (label "Box tip")++-- | Entering or leaving a label or container with a tooltip needs a frame,+-- though the hover probe finds no widget there; moving within it does not.+tooltipTargetNotWidget :: Sim Response ()+tooltipTargetNotWidget = do+  V2 lx ly <- centerOf <$> result+  onBox <- spanCenter <$> rectOf "Container target"+  _ <- moveTo away+  check =<< redrawsFor (V2 lx ly)+  checkEq [] =<< tipsAfter (moveTo (At (V2 lx ly)))+  check . not =<< redrawsFor (V2 (lx + 5) ly)+  checkEq ["Label tip"] =<< tipsAfter (sleep 0.06 >> frame)+  check =<< redrawsFor (V2 390 290)+  checkEq [] =<< tipsAfter (moveTo away)+  check =<< redrawsFor onBox+  checkEq ["Box tip"] =<< tipsAfter (moveTo (At onBox) >> sleep 0.06 >> frame)+  check =<< redrawsFor (V2 390 290)++-- | A large button with an immediate tooltip placed at the pointer.+followUi :: NanoUI Response+followUi = column $ do+  target <- buttonWith' (fixedW 360 . fixedH 240) "Canvas"+  target <$ tooltipConfigured (cfg 0 0.3) {tooltipPlacement = PlacementAtCursor} target "Follow tip"++-- | A pointer-placed tooltip sits below the pointer and follows it (moves+-- need frames), repainting old and new rects. A pointer on the tooltip still+-- counts as over the target, and the tooltip moves out from under it. Near+-- the bottom it flips above the pointer to stay in the window.+tooltipFollowCursor :: Sim Response ()+tooltipFollowCursor = do+  modifyInput (\i -> i {inputDeltaTime = 1})+  Rect tx ty tw th <- respRect <$> result+  let tipAt p = moveTo (At p) >> tipRects+      below (V2 px py) (Rect x y _ _) = checkEq (px, py + 20) (x, y)+      p1 = V2 (tx + 40) (ty + 40)+      p2 = V2 (tx + 120) (ty + 90)+  [r1] <- tipAt p1 >> tipAt p1+  below p1 r1+  checkEq [False, True] =<< mapM redrawsFor [p1, p2]+  [r2] <- tipAt p2+  below p2 r2+  dmg <- frameDamage+  check (damageCovers dmg r1 && damageCovers dmg r2)+  [r3] <- tipAt (spanCenter r2)+  below (spanCenter r2) r3+  [Rect x4 y4 w4 h4] <- tipAt (V2 (tx + tw - 2) (ty + th - 2))+  check (x4 >= 0 && x4 + w4 <= 400 && y4 >= 0 && y4 + h4 <= ty + th - 2)
+ test/integration/Cases/ViewApi.hs view
@@ -0,0 +1,328 @@+{-# OPTIONS_GHC -O0 #-}+-- | The view API a widget that works out its own input leans on: where it+-- was laid out, the keyboard, pointer frames, content keys, scrolling, and+-- pane grids.+module Cases.ViewApi (tests) where++import Spec+import Data.IntMap.Strict qualified as IM+import Data.Text (Text)+import Data.Text qualified as T+import Control.Exception (ErrorCall (..), throwIO)+import NanoUI.Monad (catchView, focusedWidget, releaseFocus)+import NanoUI.Testing.Sim++tests :: [Spec]+tests =+  [ spec "hold-focus" runHoldFocusTest+  , spec "pointer-track" runPointerTrackTest+  , spec "content-key-of" runContentKeyOfTest+  , spec "layout-variants" runLayoutVariantsTest+  , spec "pane-grid-initial" runPaneGridInitialTest+  , spec "scroll-ui" runScrollUiTest+  , simSpec "take-escape" 400 300 escapeUi takeEscapeOnce+  , simSpec "catch-view-restores-build" 400 300 catchUi catchRestores+  , spec "disclosure-and-scroll-prime" runDisclosureAndScrollPrimeTest+  ]++-- | After a part of the view throws from inside a row, the handler and what+-- follows are laid out where they are declared: in the outer column, below+-- the row, not inside it.+catchUi :: NanoUI ()+catchUi = column $ do+  label "before"+  catchView (row (label "inner" >> liftIO (throwIO (ErrorCall "boom")))) $ \(ErrorCall _) -> label "fallback"+  label "after"++catchRestores :: Sim () ()+catchRestores = do+  Rect bx _ _ _ <- rectOf "before"+  Rect _ by _ bh <- rectOf "inner"+  Rect fx fy _ fh <- rectOf "fallback"+  Rect ax ay _ _ <- rectOf "after"+  checkEq (bx, bx) (fx, ax)+  check (fy >= by + bh && ay >= fy + fh)++-- | A custom widget of a fixed size, focusable or not.+sizedWidget :: Float -> Float -> Bool -> CustomWidgetSpec ()+sizedWidget w h focusable =+  defaultCustomWidgetSpec {widgetLayout = fixedWH w h, widgetFocusable = focusable}++data FocusMode = Holding | Free | Releasing+  deriving (Eq)++-- | 'holdFocus' keeps the keyboard, ringless, through a Tab (no other widget+-- gets it even for a frame); let go, Tab moves on. 'releaseFocus' frees only+-- the widget named. A holder behind an open modal leaves the modal's focus.+runHoldFocusTest :: Context -> IORef Int -> IO ()+runHoldFocusTest ctx failed = do+  modeVar <- newVar Holding+  let inp = withInput 400 300+      ui = do+        wid <- nextId+        mode <- readVar modeVar+        when (mode == Holding) (holdFocus wid)+        when (mode == Releasing) (releaseFocus wid)+        _ <- customWidgetWithId wid (sizedWidget 100 30 True)+        other <- nextId+        when (mode == Holding) (releaseFocus other)+        _ <- customWidgetWithId other (sizedWidget 100 30 True)+        (wid,) <$> focusedWidget+  runSim ctx failed inp ui $ do+    (wid, held') <- result+    checkEq wid held'+    check . not =<< focusRing+    checkEq wid =<< (pressTab 1 >> focusedId)+    check . not =<< focusRing+    writeV modeVar Free+    moved <- pressTab 1 >> focusedId+    check (moved /= wid && moved /= WidgetId 0)+    writeV modeVar Holding+    checkEq wid . snd =<< settle+    writeV modeVar Releasing+    checkEq (WidgetId 0) . snd =<< settle+  behind <- newContext+  let page = do+        p <- nextId+        holdFocus p+        _ <- customWidgetWithId p (sizedWidget 100 30 False)+        p <$ modal' (constVar True) "Dialog" (customWidget (sizedWidget 100 30 True))+  runSim behind failed inp page $ do+    p <- result+    inModal <- pressTab 1 >> focusedId+    check (inModal /= WidgetId 0 && inModal /= p)+    checkEq inModal =<< (settle >> focusedId)++-- | A pointer that moves within one widget runs no frame, unless that widget+-- tracks the pointer; one that moves onto another widget always does.+runPointerTrackTest :: Context -> IORef Int -> IO ()+runPointerTrackTest ctx failed = do+  let ui = rowWith (tight . gap 0) $ do+        _ <- customWidget (sizedWidget 100 100 False) {widgetTrackPointer = True}+        void (customWidget (sizedWidget 100 100 False))+      pt x y = (withInput 400 300) {inputMousePos = V2 x y}+      -- Hover fades run out first, so what is left is the move's own ask.+      settleAt from n = do+        void (runFrame ctx from {inputDeltaTime = 0.1} ui)+        busy <- needsRedraw ctx from from+        when (busy && n > (0 :: Int)) (settleAt from (n - 1))+      needsAfter from to = warmup2 ctx from ui >> settleAt from 50 >> needsRedraw ctx from to+  assert failed =<< needsAfter (pt 20 50) (pt 30 50)+  assertEq failed False =<< needsAfter (pt 120 50) (pt 130 50)+  assert failed =<< needsAfter (pt 120 50) (pt 20 50)++-- | 'contentKeyOf' tells apart what 'contentKey' would round together, keeps+-- the order of its parts, and never gives the "no key" 0.+runContentKeyOfTest :: Context -> IORef Int -> IO ()+runContentKeyOfTest _ failed = do+  let big = 2 ^ (40 :: Int) :: Int+      ints :: [Int] -> Int+      ints xs = contentKeyOf (map keyPart xs)+      texts :: [Text] -> Int+      texts xs = contentKeyOf (map keyPart xs)+  assert failed (ints [big] /= ints [big + 1])+  assert failed (ints [1, 2] /= ints [2, 1])+  assert failed (texts ["ab", "c"] /= texts ["a", "bc"])+  assert failed (contentKeyOf [keyPart (0.1 :: Double)] /= contentKeyOf [keyPart (0.1 + 1e-12 :: Double)])+  assert failed (contentKeyOf [] /= 0)++-- | The modal @With@ variants apply their layout: a sized modal whose filling+-- body gets the inside, and a bare modal panel, which Escape dismisses.+runLayoutVariantsTest :: Context -> IORef Int -> IO ()+runLayoutVariantsTest _ failed = do+  let sim :: Float -> Float -> NanoUI a -> Sim a () -> IO ()+      sim w h ui script = newContext >>= \c -> runSim c failed (withInput w h) ui script+      filler = respRect . fst <$> customWidget defaultCustomWidgetSpec {widgetLayout = fillW . fillH}+  sim 800 600 (modalWith' (fixedWH 500 400) (constVar True) "Sized" (columnWith (fillW . fillH . tight) filler)) $ do+    result >>= \(_, inside) -> checkJust inside $ \(Rect x _ w h) -> do+      -- Inside the panel's padding and title bar, and most of it.+      check (w > 440 && w <= 500 && h > 300 && h <= 400)+      check (abs (x + w / 2 - 400) <= 12)+  sim 800 600 (modalPanelWith' (fixedWH 500 400) (constVar True) filler) $ do+    result >>= \(_, inside) -> checkJust inside $ \(Rect x y w h) -> do+      checkEq (500, 400) (w, h)+      check (abs (x + w / 2 - 400) <= 1 && abs (y + h / 2 - 300) <= 1)+    check . respClicked . fst =<< pressKey KeyEscape++-- | A grid given 'pgTree' lays its split out from the first frame, numbers+-- later panes above it, and pins at the width the ratio first gave. The seed+-- takes once: closing every pane leaves an empty grid. An unfocusable grid+-- is no Tab stop.+runPaneGridInitialTest :: Context -> IORef Int -> IO ()+runPaneGridInitialTest ctx failed = do+  rects <- newIORef IM.empty+  -- What each pane's body was laid out at the first time it was.+  firstLaid <- newIORef IM.empty+  splitIt <- newIORef False+  let ui =+        paneGrid+          defaultPaneGridConfig+            { pgLayout = fillW . fillH+            , pgMinSize = 40+            , pgSpacing = 4+            , pgFixedPanes = (== 10)+            , pgTree = InitialTree (Just (Split 30 AxisV 0.25 (Pane 10) (Pane 20)))+            , pgViewPane = \pid pctx -> do+                liftIO (modifyIORef' rects (IM.insert (fromIntegral pid) (pgcRect pctx)))+                body <- nextId+                laid <- lastRect body+                liftIO (forM_ laid (modifyIORef' firstLaid . IM.insertWith (\_ old -> old) (fromIntegral pid)))+                _ <- customWidgetWithId body defaultCustomWidgetSpec {widgetLayout = fillW . fillH}+                wantSplit <- liftIO (readIORef splitIt)+                when (wantSplit && pid == 20) $ do+                  liftIO (writeIORef splitIt False)+                  void (pgcSplit pctx AxisH)+                pure (PaneView "P" False)+            }+      widthsAfter w = do+        writeIORef rects IM.empty+        replicateM_ 3 (runFrame ctx (withInput w 400) ui)+        IM.map (round . rectW) <$> readIORef rects+  -- A 16px gutter (4 drawn, 6 of leeway each side) leaves 584 of 600 to+  -- share: a quarter is 146. The very first frame, before the grid has a+  -- rect of its own, lays the split out at its ratio too.+  assertEq failed (IM.fromList [(10, 146), (20, 438 :: Int)]) =<< widthsAfter 600+  assertEq failed (Just (146 :: Int)) . fmap (round . rectW) . IM.lookup 10 =<< readIORef firstLaid+  -- Pinned from the first size it had, not from before it had one.+  assertEq failed (IM.fromList [(10, 146), (20, 738)]) =<< widthsAfter 900+  writeIORef splitIt True+  panes <- pgrPanes <$> evalUi ctx (withInput 900 400) ui+  assertEq failed 3 (length panes)+  assert failed (all (\p -> p `elem` [10, 20] || p > 30) panes)+  once <- newContext+  closing <- newIORef False+  let inp = withInput 600 400+      seeded = fmap pgrPanes . paneGrid $+        defaultPaneGridConfig+          { pgLayout = fillW . fillH+          , pgTree = InitialTree (Just (Split 30 AxisV 0.5 (Pane 10) (Pane 20)))+          , pgViewPane = \_ pctx -> do+              close <- liftIO (readIORef closing)+              when close (pgcClose pctx)+              pure (PaneView "P" False)+          }+  assertEq failed [10, 20] =<< warmup2 once inp seeded+  writeIORef closing True+  replicateM_ 3 (runFrame once inp seeded)+  writeIORef closing False+  assertEq failed [[], []] =<< replicateM 2 (evalUi once inp seeded)+  tabbed <- newContext+  let grids focusable =+        paneGrid defaultPaneGridConfig {pgLayout = fillW . fillH, pgFocusable = focusable} >> focusedWidget+  _ <- warmup2 tabbed inp (grids False)+  _ <- runFrame tabbed (tabInp inp) (grids False)+  assertEq failed (WidgetId 0) =<< evalUi tabbed inp (grids False)+  _ <- runFrame tabbed (tabInp inp) (grids True)+  assert failed . (/= WidgetId 0) =<< evalUi tabbed inp (grids True)++-- | A scroll offset set from a view past the content is held to it. A view+-- reading 'getScrollMetrics' gets a frame when a resize changes them, and no+-- more.+runScrollUiTest :: Context -> IORef Int -> IO ()+runScrollUiTest ctx failed = do+  let inp = withInput 400 300+      tall = void (customWidget (sizedWidget 180 1000 False))+      ui = do+        (sid, bottomId) <- scrollArea (fixedWH 200 200 . tight . gap 0) $ do+          tall+          respId <$> button' "Bottom"+        (sid, bottomId,) <$> getScrollMetrics sid+  runSim ctx failed inp ui $ do+    (sid, bottomId, m0) <- result+    checkEq (Just 0) (v2Y . scrollOffset <$> m0)+    (_, _, m) <- afterView (setScrollOffset sid (V2 0 5000)) >> settle+    checkJust m $ \m' -> checkEq (v2Y (scrollRange m')) (v2Y (scrollOffset m'))+    (_, _, mStart) <- afterView (scrollToStart sid ScrollInstant) >> settle+    checkEq (Just 0) (v2Y . scrollOffset <$> mStart)+    (_, _, mEnd) <- afterView (scrollToEnd sid ScrollInstant) >> settle+    checkJust mEnd $ \m' -> checkEq (v2Y (scrollRange m')) (v2Y (scrollOffset m'))+    _ <- afterView (scrollToStart sid ScrollInstant) >> settle+    (_, _, mInto) <- afterView (scrollIntoView sid bottomId ScrollNearest ScrollInstant) >> settle+    checkJust mInto $ \m' -> checkGt (v2Y (scrollOffset m')) 700+  reader <- newContext+  let rows = do+        sid <- currentId+        m <- getScrollMetrics sid+        _ <- scrollArea (fillW . fillH) tall+        pure (fmap (rectH . scrollViewport) m)+      dirtyAfter h = (\(_, _, d) -> d) <$> runFrame reader (withInput 400 h) rows+  replicateM_ 3 (runFrame reader inp rows)+  assertEq failed [False, True, False] =<< mapM dirtyAfter [300, 200, 200]++escapeUi :: NanoUI (Response, Bool, Bool)+escapeUi = do+  (resp, _) <- withValue ("query" :: Text) textInput'+  (,,) resp <$> takeEscape <*> takeEscape++-- | 'takeEscape' is the view's when nothing else took it, is taken once, and+-- is not the view's while a text field's menu is open.+takeEscapeOnce :: Sim (Response, Bool, Bool) ()+takeEscapeOnce = do+  (field, none, _) <- result+  check (not none)+  (_, first, again) <- pressKey KeyEscape+  checkEq (True, False) (first, again)+  _ <- rightClick (On field) >> frame+  (_, forMenu, _) <- pressKey KeyEscape+  check (not forMenu)++-- | 'selectableRow*' clicks on background/label without stealing child button+-- clicks; 'collapsing*' toggles on header and chevron clicks while keeping+-- sibling state intact; 'scrollWith''/'scroll2DWith''/'scrollConfigured'' and+-- 'floatingWindowWith'' return valid geometry and ids.+runDisclosureAndScrollPrimeTest :: Context -> IORef Int -> IO ()+runDisclosureAndScrollPrimeTest ctx failed = do+  rowClicks <- newIORef (0 :: Int)+  btnClicks <- newIORef (0 :: Int)+  openVar <- newVar False+  let disclosureUi = columnWith (tight . gap 6 . fixedW 260) $ do+        (btnResp, rowResp) <- selectableRow' True $ do+          label "RowLabel"+          flex+          button' "RowAction"+        when (respClicked rowResp) (liftIO (modifyIORef' rowClicks (+ 1)))+        when (respClicked btnResp) (liftIO (modifyIORef' btnClicks (+ 1)))+        collapsing "Details" openVar $+          label "HiddenBody"+        sib <- useVar (0 :: Int)+        whenM (button "BumpSib") (modifyVar sib (+ 1))+        n <- readVar sib+        label ("Sib=" <> T.pack (show n))+        pure (rowResp, btnResp)+  runSim ctx failed (withInput 400 300) disclosureUi $ do+    (rowResp, btnResp) <- result+    -- Clicking the row label clicks the row, not the child button.+    _ <- click "RowLabel" >> settle+    checkEq (1, 0) =<< liftIO ((,) <$> readIORef rowClicks <*> readIORef btnClicks)+    -- Clicking the child button fires the button and NOT the enclosing row.+    _ <- click (On btnResp) >> settle+    checkEq (1, 1) =<< liftIO ((,) <$> readIORef rowClicks <*> readIORef btnClicks)+    -- Pointer hover over the row reports UiCursorPointer.+    checkEq UiCursorPointer =<< cursorAt (At (V2 (rectX (respRect rowResp) + 12) (rectY (respRect rowResp) + rectH (respRect rowResp) / 2)))+    -- Sibling state persists across collapsing toggles; clicking title opens, clicking chevron closes.+    _ <- click "BumpSib" >> settle+    expect "Sib=1"+    expectNot "HiddenBody"+    _ <- click "Details" >> settle+    expect "HiddenBody"+    expect "Sib=1"+    -- Click the chevron area just left of the "Details" title text.+    detR <- rectOf "Details"+    _ <- click (at (rectX detR - 10) (rectY detR + rectH detR / 2)) >> settle+    expectNot "HiddenBody"+    expect "Sib=1"+  -- scrollWith', scroll2DWith', scrollConfigured', and floatingWindowWith'+  c2 <- newContext+  let primeUi = columnWith (tight . gap 4) $ do+        (v1, sr1) <- scrollWith' (fixedWH 120 60) (label "S1" >> pure (1 :: Int))+        (v2, sr2) <- scroll2DWith' (fixedWH 140 70) (label "S2" >> pure (2 :: Int))+        (v3, sr3) <- scrollConfigured' defaultScrollConfig (fixedWH 160 80) (label "S3" >> pure (3 :: Int))+        (winR, _) <- floatingWindowWith' (fixedWH 320 200) (constVar True) "SizedWin" (label "WinBody")+        pure (v1, sr1, v2, sr2, v3, sr3, winR)+  (v1, sr1, v2, sr2, v3, sr3, winR) <- warmup2 c2 (withInput 600 400) primeUi+  assertEq failed (1, 2, 3) (v1, v2, v3)+  assertEq failed (120, 60) (rectW (respRect sr1), rectH (respRect sr1))+  assertEq failed (140, 70) (rectW (respRect sr2), rectH (respRect sr2))+  assertEq failed (160, 80) (rectW (respRect sr3), rectH (respRect sr3))+  assertEq failed (320, 200) (rectW (respRect winR), rectH (respRect winR))+  assert failed (all ((/= WidgetId 0) . respId) [sr1, sr2, sr3, winR])
+ test/integration/Cases/Visibility.hs view
@@ -0,0 +1,335 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.Visibility (tests) where++import Spec+import Control.Concurrent (threadDelay)+import GHC.Stack (HasCallStack)++tests :: [Spec]+tests =+  [ spec "visibility-initial" runInitialTest+  , spec "visibility-scroll" runScrollTest+  , spec "visibility-nested-scroll" runNestedScrollTest+  , spec "visibility-clipped" runClippedTest+  , spec "visibility-anticipate" runAnticipateTest+  , spec "visibility-removed" runRemovedTest+  , spec "visibility-tabs" runTabsTest+  , spec "visibility-use-visibility" runUseVisibilityTest+  , spec "visibility-layout-change" runLayoutChangeTest+  , spec "visibility-delay" runDelayTest+  , spec "visibility-shared-id" runSharedIdTest+  ]++inp :: Input+inp = withInputOff 300 200++-- | Run a frame; return the view's result and whether it asked for a follow-up frame.+step :: Context -> Input -> NanoUI a -> IO (a, Bool)+step ctx i ui = (\(a, _, follow) -> (a, follow)) <$> runFrame ctx i ui++settle :: Context -> Input -> NanoUI a -> Int -> IO ()+settle ctx i ui n = replicateM_ n (step ctx i ui)++-- | A sensor's visibility and event.+type State = (Bool, Maybe VisibilityEvent)++off, on, cameIn, wentOut :: State+off = (False, Nothing)+on = (True, Nothing)+cameIn = (True, Just BecameVisible)+wentOut = (False, Just BecameHidden)++hidden :: Visibility+hidden = Visibility False Nothing (Rect 0 0 0 0) (Rect 0 0 0 0)++-- | A report minus 'visBounds', which a hidden widget still has.+reported :: Visibility -> (Bool, Maybe VisibilityEvent, Rect)+reported v = (visVisible v, visEvent v, visRect v)++-- | Check what sensors report; a hidden one has an empty rect.+expectVis :: HasCallStack => IORef Int -> [State] -> [Visibility] -> IO ()+expectVis failed want vs = do+  assertEq failed want [(visVisible v, visEvent v) | v <- vs]+  forM_ vs $ \v -> unless (visVisible v) (assertEq failed (Rect 0 0 0 0) (visRect v))++-- | Run one frame per expected (report, follow-up) pair, checking sensor @sel@.+frames ::+  HasCallStack => IORef Int -> Context -> Input -> NanoUI a -> (a -> Visibility) -> [(State, Bool)] -> IO [a]+frames failed ctx i ui sel = mapM $ \(want, wantFollow) -> do+  (a, follow) <- step ctx i ui+  expectVis failed [want] [sel a]+  a <$ assertEq failed wantFollow follow++grey :: Color+grey = colorRGBA 90 90 90 255++-- | A 40-pixel row.+bar :: NanoUI ()+bar = box (fixedH 40 . fillW) grey++-- | A scroller @h@ pixels tall over a column without gaps.+scrollCol :: Float -> NanoUI a -> NanoUI (WidgetId, a)+scrollCol h = scrollArea (fixedH h . fillW) . columnWith (tight . gap 0 . fillW)++-- | Twenty rows in a 100-pixel scroller; row 10 (400 pixels down) is a sensor.+rows :: NanoUI (WidgetId, Visibility)+rows = scrollCol 100 (replicateM_ 10 bar *> (fst <$> sensorWith fillW bar) <* replicateM_ 9 bar)++-- An on-screen sensor reports once, on the follow-up frame the first requests.+-- A sensor takes as many ids as a column, so swapping them keeps sibling ids.+runInitialTest :: Context -> IORef Int -> IO ()+runInitialTest ctx failed = do+  let watched = column (fst <$> sensor (label "watched"))+  [_, v, _] <- frames failed ctx inp watched id [(off, True), (cameIn, False), (on, False)]+  assert failed (rectW (visRect v) > 0 && rectH (visRect v) > 0)+  let after enclose n = column (enclose (replicateM_ n (label "item")) >> respId <$> button' "After")+  plain <- evalUi ctx inp (after column 2)+  forM_ [0, 2, 5] $ \n -> evalUi ctx inp (after (fmap snd . sensor) n) >>= assertEq failed plain++-- Scrolling a row in and out reports each change once; 'visRect' is its+-- visible part, and 'visBounds' the whole row, which a hidden row keeps.+runScrollTest :: Context -> IORef Int -> IO ()+runScrollTest ctx failed = do+  let go = frames failed ctx inp rows snd+  -- Nothing on screen changes and nothing read the layout, so the first+  -- frame asks for no second.+  (sid, _) : _ <- go (replicate 4 (off, False))+  -- Row 10 now starts 70 pixels down the 100-pixel viewport.+  setScrollOffsetIO ctx sid 330+  [_, (_, v2)] <- go [(off, True), (cameIn, False)]+  -- The view shows nothing new for the event, so that frame repaints nothing.+  assert failed . damageIsEmpty =<< takeDamage ctx+  assert failed (rectH (visRect v2) > 0 && rectH (visRect v2) < 40)+  assertEq failed (40, Just (visRect v2)) (rectH (visBounds v2), rectIntersect (visBounds v2) (visRect v2))+  assertJustM failed (getPrevRect ctx sid) $ \viewport ->+    assertEq failed (rectIntersect viewport (visRect v2)) (Just (visRect v2))+  -- Moving within view updates the rect next frame without requesting one.+  setScrollOffsetIO ctx sid 320+  [_, (_, v4)] <- go [(on, False), (on, False)]+  assertEq failed (rectY (visRect v4)) (rectY (visRect v2) + 10)+  takeDamage ctx >>= assert failed . (/= DamageFull)+  setScrollOffsetIO ctx sid 0+  [_, (_, gone), _] <- go [(on, True), (wentOut, False), (off, False)]+  assertEq failed 40 (rectH (visBounds gone))+  setScrollOffsetIO ctx sid 380+  [_, (_, v)] <- go [(off, True), (cameIn, False)]+  assertEq failed 40 (rectH (visRect v))++-- A button in an inner scroller is visible and live only inside both viewports, even+-- disjoint ones; outside the inner but inside the outer it is hidden and inert.+runNestedScrollTest :: Context -> IORef Int -> IO ()+runNestedScrollTest ctx failed = do+  let filler h = spacer (Fixed 10) (Fixed h)+      ui = scrollCol 100 $ do+        filler 150+        inner <- scrollArea (fixedH 30 . fillW) . column $ sensor (button' "Deep") <* filler 200+        inner <$ filler 300+      go = void . frames failed ctx inp ui (fst . snd . snd)+      look i = snd . snd <$> evalUi ctx i ui+      -- The sensor report, and whether the button hovers, presses and clicks.+      probe = do+        (vis, deep) <- look inp+        let over = inp {inputMousePos = centerOf deep}+            (press, release) = clickPair over (centerOf deep)+        void (look over)+        flags <- forM [(over, respHovered), (press, respPressed), (release, respClicked)] $ \(i, f) ->+          f . snd <$> look i+        pure (vis, respRect deep, flags)+  (outer, (inner, _)) <- evalUi ctx inp ui+  -- Inner scrolled by 100: the button is above the inner viewport, at about y 50.+  setScrollOffsetIO ctx inner 100 >> settle ctx inp ui 3 >> go [(off, False)]+  (vis1, Rect _ by _ bh, flags1) <- probe+  assert failed (by >= 0 && by + bh < 100)+  assertEq failed (reported hidden, [False, False, False]) (reported vis1, flags1)+  -- Unscrolled, it is below the outer viewport.+  setScrollOffsetIO ctx inner 0 >> settle ctx inp ui 3 >> go [(off, False)]+  setScrollOffsetIO ctx outer 150 >> go [(off, True), (cameIn, False)]+  (vis2, _, flags2) <- probe+  assertEq failed (True, [True, True, True]) (visVisible vis2, flags2)+  setScrollOffsetIO ctx inner 100 >> go [(on, True), (wentOut, False)]++-- Sensors clipped by a panel, or in a zero-height container, are hidden. One in a+-- window declared in scrolled-out content is visible, and so is one pinned out of a+-- sizeless or scrolled-out container, which is drawn.+runClippedTest :: Context -> IORef Int -> IO ()+runClippedTest ctx failed = do+  let box20 = box (fixedH 20 . fillW) grey+      ui = column $ do+        inPanel <- panelWith (fixedH 30 . fillW . tight . gap 0) $+          box (fixedH 40 . fillW) grey >> fst <$> sensorWith (fixedH 10 . fillW) (pure ())+        inEmpty <- columnWith (fixedH 0 . fillW . tight) (fst <$> sensorWith fillW box20)+        shown <- fst <$> sensorWith fillW box20+        pure [inPanel, inEmpty, shown]+  settle ctx inp ui 3+  (vs, follow) <- step ctx inp ui+  expectVis failed [off, off, on] vs >> assert failed (not follow)+  let floating = scrollArea (fixedH 100 . fixedW 60) . columnWith (tight . gap 0 . fillW) $ do+        replicateM_ 10 bar+        (_, inWindow) <- floatingWindow' (constVar True) "Panel" (fst <$> sensor (label "in window"))+        (,) inWindow . fst <$> sensor bar+  c <- newContext+  settle c (withInput 400 300) floating 2+  ((_, (inWindow, below)), follow') <- step c (withInput 400 300) floating+  assertEq failed (visVisible <$> inWindow, reported below, follow') (Just True, reported hidden, False)+  let (red, blue) = (colorRGBA 200 40 40 255, colorRGBA 40 40 200 255)+      pinned = columnWith (tight . gap 0 . fillW) $ do+        (inStack, _) <- layersWith tight (sensorWith (pinAt 10 10) (box (fixedWH 20 20) red))+        (sid, (hanging, _)) <- scrollCol 100 $+          columnWith (tight . fixedH 10 . fillW) (sensorWith (pinAt 0 150) (box (fixedWH 20 20) blue))+            <* box (fixedH 400 . fillW) grey+        pure (sid, [inStack, hanging])+  p <- newContext+  (sid, _) <- evalUi p inp pinned+  -- The strip is above the viewport; its pinned box is 50 pixels into it.+  setScrollOffsetIO p sid 100 >> settle p inp pinned 3+  ((_, pvs), draw, pfollow) <- runFrame p inp pinned+  colours <- map snd <$> drawQuads draw+  assertEq failed ([True, True], False) (map (`elem` colours) [red, blue], pfollow)+  expectVis failed [on, on] pvs+  assertEq failed [(20, 20), (20, 20)] [(w, h) | Rect _ _ w h <- map visRect pvs]++-- An anticipate margin reports a row visible before it scrolls in; a zero-height+-- marker in view is visible.+runAnticipateTest :: Context -> IORef Int -> IO ()+runAnticipateTest ctx failed = do+  let ui = scrollCol 100 $ do+        marker <- fst <$> sensorWith (fixedH 0 . fillW) (pure ())+        replicateM_ 3 bar+        -- Row 3 starts about 25 pixels below the viewport.+        sensed <- rowWith (tight . gap 0 . fillW) . forM [40, 0] $ \margin ->+          fst <$> sensorConfigured defaultSensorConfig {sensorAnticipate = margin, sensorLayout = fillW} bar+        (marker : sensed) <$ replicateM_ 10 bar+  (sid, vs@[_, near, _]) <- warmup2 ctx inp ui+  expectVis failed [cameIn, cameIn, off] vs+  assertEq failed (visRect near) (Rect 0 0 0 0)+  setScrollOffsetIO ctx sid 30 >> settle ctx inp ui 1+  expectVis failed [wentOut, on, cameIn] . snd =<< evalUi ctx inp ui++-- An unbuilt sensor is forgotten: no frames while gone, a fresh report on+-- return, and stable ids after it; also beside sensors sharing an id, and+-- when swapped for another sensor in one frame.+runRemovedTest :: Context -> IORef Int -> IO ()+runRemovedTest _ failed = do+  shownRef <- newIORef True+  let shown = liftIO (readIORef shownRef)+      watched = fst <$> sensor (label "watched")+      maybeWatched = shown >>= \s -> scope (if s then watched else pure hidden)+      ui = column ((,) <$> maybeWatched <*> (respId <$> button' "After"))+      twins = column (replicateM_ 2 (withKey (0 :: Int) (sensor (label "twin"))) >> maybeWatched)+      swapped = column (shown >>= \s -> withKey s watched)+      reports = [(off, True), (cameIn, False)]+      hideAndShow :: NanoUI a -> (a -> Visibility) -> [(State, Bool)] -> IO [a]+      hideAndShow view sel whileHidden = do+        ctx <- newContext+        writeIORef shownRef True+        a <- frames failed ctx inp view sel reports+        b <- writeIORef shownRef False >> frames failed ctx inp view sel whileHidden+        c <- writeIORef shownRef True >> frames failed ctx inp view sel reports+        pure (a ++ b ++ c)+  ids <- map snd <$> hideAndShow ui fst [(off, False), (off, False)]+  assert failed (and (zipWith (==) ids (drop 1 ids)))+  void (hideAndShow twins id [(off, False)])+  void (hideAndShow swapped id reports)++-- Watches sharing an id are one sensor: the last watch is measured, and the+-- first read takes the event.+runSharedIdTest :: Context -> IORef Int -> IO ()+runSharedIdTest ctx failed = do+  let ui = scrollCol 100 $ do+        shown <- respId <$> button' "Shown"+        replicateM_ 5 bar+        below <- respId <$> button' "Below"+        forM [below, shown] (withKey (0 :: Int) . useVisibility defaultSensorConfig)+  ((_, first), follow) <- step ctx inp ui+  expectVis failed [off, off] first >> assert failed follow+  ((_, second), _) <- step ctx inp ui+  expectVis failed [cameIn, on] second++-- A sensor in a hidden tab's body is forgotten while another tab shows.+runTabsTest :: Context -> IORef Int -> IO ()+runTabsTest ctx failed = do+  activeRef <- newIORef (0 :: Int)+  eventsRef <- newIORef []+  let watched = sensor (label "in tab A") >>= \(vis, _) ->+        forM_ (visEvent vis) (liftIO . modifyIORef' eventsRef . (:))+      ui = do+        active <- liftIO (readIORef activeRef)+        void (tabs' (constVar active) [tab 0 "A" watched, tab 1 "B" (label "in tab B")])+  settle ctx inp ui 3+  writeIORef activeRef 1 >> settle ctx inp ui 3+  (_, follow) <- step ctx inp ui+  assert failed (not follow)+  writeIORef activeRef 0 >> settle ctx inp ui 3+  readIORef eventsRef >>= assertEq failed [BecameVisible, BecameVisible]++-- 'useVisibility' watches an earlier widget, takes one id, and reports its removal once.+runUseVisibilityTest :: Context -> IORef Int -> IO ()+runUseVisibilityTest ctx failed = do+  shownRef <- newIORef True+  targetRef <- newIORef (WidgetId 0)+  let ui = scrollCol 100 $ do+        replicateM_ 5 bar+        shown <- liftIO (readIORef shownRef)+        scope . when shown $ liftIO . writeIORef targetRef . respId =<< button' "Target"+        target <- liftIO (readIORef targetRef)+        vis <- useVisibility defaultSensorConfig target+        after <- button' "After"+        (vis, target, respId after) <$ replicateM_ 5 bar+      go = frames failed ctx inp ui (\(_, (v, _, _)) -> v)+  [(sid, (_, target0, after0))] <- go [(off, False)]+  setScrollOffsetIO ctx sid 180+  [_, (_, (v, target, after))] <- go [(off, True), (cameIn, False)]+  assertJustM failed (getPrevRect ctx target) $ \r ->+    assertEq failed (rectIntersect r (visRect v)) (Just (visRect v))+  assertEq failed (target, after) (target0, after0)+  writeIORef shownRef False+  void $ go [(on, True), (wentOut, False)]++-- Shrinking the window hides a sensor on the follow-up frame and growing it back+-- shows it; content growing above two sensors hides both on one follow-up frame.+runLayoutChangeTest :: Context -> IORef Int -> IO ()+runLayoutChangeTest ctx failed = do+  let ui = column (box (fixedH 150 . fillW) grey >> fst <$> sensorWith fillW bar)+      go h = void . frames failed ctx (withInput 300 h) ui id+  settle ctx (withInput 300 300) ui 3+  go 300 [(on, False)]+  go 100 [(on, True), (wentOut, False), (off, False)]+  go 300 [(off, True), (cameIn, False)]+  countRef <- newIORef (0 :: Int)+  shifting <- newContext+  let growing = scrollCol 100 $ do+        n <- liftIO (readIORef countRef)+        scope (replicateM_ n bar)+        replicateM 2 (fst <$> sensorWith fillW bar)+  settle shifting inp growing 3+  ((_, before), follow1) <- step shifting inp growing+  writeIORef countRef 3+  (_, follow2) <- step shifting inp growing+  ((_, after), follow3) <- step shifting inp growing+  expectVis failed [on, on, wentOut, wentOut] (before ++ after)+  assertEq failed [False, True, False] [follow1, follow2, follow3]++-- With a delay, a sensor reports visible only after staying in view that long,+-- woken rather than by follow-up frames; hiding is immediate.+runDelayTest :: Context -> IORef Int -> IO ()+runDelayTest ctx failed = do+  let cfg = defaultSensorConfig {sensorDelay = 0.03}+      ui = scrollCol 100 (replicateM_ 10 bar *> (fst <$> sensorConfigured cfg bar) <* replicateM_ 9 bar)+      report = do+        ((_, v), _) <- step ctx inp ui+        pure (visVisible v, visEvent v)+  (sid, _) <- evalUi ctx inp ui+  settle ctx inp ui 2+  -- Row 10 is in view, but not yet for long enough.+  setScrollOffsetIO ctx sid 380+  settle ctx inp ui 2+  report >>= assertEq failed off+  assert failed . (> 0) =<< getWakeAt ctx+  threadDelay 50000+  -- The woken frame measures it visible; the next frame reports it.+  _ <- step ctx inp ui+  report >>= assertEq failed cameIn+  setScrollOffsetIO ctx sid 0+  _ <- step ctx inp ui+  report >>= assertEq failed wentOut+  assertEq failed 0 =<< getWakeAt ctx
+ test/integration/Cases/WidgetIdIndex.hs view
@@ -0,0 +1,82 @@+{-# OPTIONS_GHC -O0 #-}+module Cases.WidgetIdIndex (tests) where++import Spec+import Data.Primitive.PrimVar (readPrimVar, writePrimVar)+import Data.Text qualified as T+import NanoUI.Internal.Context (Context (..), DamageState (..), PrevFrame (..), getsDamage)+import NanoUI.Internal.Layout.Arena (NodeArena (..), getWidgetId, lookupNodeByWidgetId)+import NanoUI.Internal.Store (ptrEq)++tests :: [Spec]+tests =+  [ spec "shared-key-prev-rects" runSharedKeyPrevRectsTest+  , spec "widget-id-index-lookups" runWidgetIdIndexLookupsTest+  , spec "widget-id-index-epoch-wrap" runWidgetIdIndexEpochWrapTest+  , spec "width-memo-frame-tag-wrap" runWidthMemoFrameTagWrapTest+  ]++inp :: Input+inp = withInputOff 320 300++-- | With a table shown, with or without a frozen column (two panes under one+-- id), an unchanged frame reuses last frame's rect map, and a label removed+-- after the table repaints its old area and drops out of the previous rects.+runSharedKeyPrevRectsTest :: Context -> IORef Int -> IO ()+runSharedKeyPrevRectsTest _ failed = forM_ [0, 1] $ \freeze -> do+  ctx <- newContext+  Just resp <- last <$> replicateM 3 (evalUi ctx inp (tableAndLabel freeze True))+  let old = respRect resp+      frameRects = runFrame ctx inp (tableAndLabel freeze True) >> getsDamage ctx (pfRects . dsPrev)+  assert failed (rectW old > 0 && rectH old > 0)+  !before <- frameRects+  !after <- frameRects+  assert failed (not (null before) && ptrEq before after)+  _ <- runFrame ctx inp (tableAndLabel freeze False)+  assert failed . (`damageCovers` old) =<< takeDamage ctx+  assertEq failed Nothing =<< getPrevRect ctx (respId resp)++-- | Every widget resolves to its own node, beyond the index's initial size,+-- and a widget left out next frame resolves to nothing.+runWidgetIdIndexLookupsTest :: Context -> IORef Int -> IO ()+runWidgetIdIndexLookupsTest ctx failed = do+  let na = ctxNodeArena ctx+      ui n = column (forM [1 .. n :: Int] (\i -> withKey i (button' "b")))+      resolvesToItself r = maybe (pure False) (fmap (== respId r) . getWidgetId na) =<< lookupNodeByWidgetId na (respId r)+  resps <- evalUi ctx inp (ui 3000)+  assertEq failed 3000 (length resps)+  assert failed . and =<< mapM resolvesToItself resps+  _ <- runFrame ctx inp (ui 10)+  assert failed . and =<< mapM resolvesToItself (take 10 resps)+  assert failed . all null =<< mapM (lookupNodeByWidgetId na . respId) (drop 10 resps)++-- | A wrapping frame epoch does not revive entries from the previous lap.+runWidgetIdIndexEpochWrapTest :: Context -> IORef Int -> IO ()+runWidgetIdIndexEpochWrapTest ctx failed = do+  let na = ctxNodeArena ctx+  writePrimVar (naEpoch na) maxBound+  gone <- evalUi ctx inp (withKey (1 :: Int) (button' "gone"))+  assert failed . not . null =<< lookupNodeByWidgetId na (respId gone)+  writePrimVar (naEpoch na) maxBound+  _ <- runFrame ctx inp (withKey (2 :: Int) (label "other"))+  assertEq failed 1 =<< readPrimVar (naEpoch na)+  assertEq failed Nothing =<< lookupNodeByWidgetId na (respId gone)++-- | A wrapping frame tag does not revive width memo entries from the+-- previous lap: text at the same node and width measures afresh.+runWidthMemoFrameTagWrapTest :: Context -> IORef Int -> IO ()+runWidthMemoFrameTagWrapTest ctx failed = do+  let ui = columnWith tight . labelWith (\l -> l {layoutWidth = Fixed 100})+      lapFrame txt = writePrimVar (naFrameTag (ctxNodeArena ctx)) maxBound >> runFrame ctx inp (ui txt) >> arenaRects ctx+  _ <- lapFrame "a long label that wraps onto several lines"+  lapped <- lapFrame "a\nb"+  fresh <- newContext+  expected <- runFrame fresh inp (ui "a\nb") >> arenaRects fresh+  assertEq failed expected lapped++-- | A table with @freeze@ frozen columns, and a label after it while @showLabel@.+tableAndLabel :: Int -> Bool -> NanoUI (Maybe Response)+tableAndLabel freeze showLabel = column $ do+  let rows = [(n, n) | n <- map (T.pack . show) [1 .. 20 :: Int]]+  _ <- tableConfigured' defaultTableConfig {tableFreezeCols = freeze} (fixedH 150) "people" (headed "Name" fst <> headed "Value" snd) rows (constVar (SortCol 0 SortAsc))+  if showLabel then Just <$> label' "bye" else pure Nothing
test/integration/Cases/Window.hs view
@@ -1,504 +1,411 @@-module Cases.Window-  ( runFitHeaderNoShrinkTest-  , runOverlayClickThroughTest-  , runOverlayPanelLiveTest-  , runOverlaySiblingStateTest-  , runSeparatorSpanTest-  , runWindowCloseDamageTest-  , runWindowDragTest-  , runWindowOverlayTest-  , runWindowResizeHaloHitTest-  , runWindowResizeTest-  , runWindowScrollGutterTest-  , runPageWindowScrollTest-  , runWindowScrollOnlyDamageTest-  , runWindowContentChurnTest-  , runScrolledDebugToggleTest-  , runHeadingMonoTruncateTest-  ) where+{-# OPTIONS_GHC -O0 #-}+module Cases.Window (tests) where -import Control.Monad (forM_, replicateM, void, when)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Spec+import Control.Exception (evaluate) import Data.IntMap.Strict qualified as IM+import Data.Maybe (isJust, isNothing, listToMaybe)+import Data.Text (Text) import Data.Text qualified as T-import NanoUI-import NanoUI.Testing-import NanoUI.Testing.Assert (assert, assertEq, assertGt, assertLt, withInput)-import NanoUI.Testing.Harness-  ( assertWheelTitlePinned-  , centerOf-  , clickPair-  , dragWindowEdge-  , keyInp-  , runClick-  , runDragFrom-  , spanYOf-  , warmup2-  , windowTitleGrab-  , withInputOff-  )+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena (LayoutCache (..))+import NanoUI.Testing.Sim+import System.Mem.StableName (makeStableName) -runWindowScrollGutterTest :: Context -> IORef Int -> IO ()-runWindowScrollGutterTest ctx failed = do-  let inp0 = withInput 640 360-      long = T.pack (replicate 48 'M')-      ui = window True "GutterWin" $ do-        wide <- labelWith' fillW "WWWW"-        kv "Key" long-        mapM_ (\i -> label (T.pack ("line " <> show (i :: Int)))) [1 .. 24]-        pure wide-  (win, mwide) <- warmup2 ctx inp0 ui-  let Rect wx _ ww _ = respRect win-      -- The body's content keeps the window's side padding before the bar.-      contentRight = wx + ww - padR windowPad - scrollBarGutter ScrollBarWindow 0-  spans <- collectOverlayTextSpans ctx inp0-  let titleYs = [rectY r | (r, txt, _, _, _) <- spans, "GutterWin" `T.isInfixOf` txt]-  assert failed (not (null titleYs))-  case mwide of-    Nothing -> assert failed False-    Just wide -> do-      let Rect cx _ cw _ = respRect wide-      assert failed (cx + cw >= contentRight - 0.5 && cx + cw <= contentRight + 0.01)+tests :: [Spec]+tests =+  [ spec "fit-header-no-shrink" runFitHeaderNoShrinkTest+  , pixelSimSpec "window-scroll-gutter" 640 360 gutterUi windowScrollGutter+  , simSpec "window-fit-scroll-gutter" 1200 300 fitGutterUi windowFitScrollGutter+  , simSpec "heading-mono-truncate" 1600 600 monoUi headingMonoTruncate+  , spec "window-overlay" runWindowOverlayTest+  , spec "overlay-sibling-state" runOverlaySiblingStateTest+  , spec "window-damage" runWindowDamageTest+  , simSpec "window-drag" 640 400 (fst <$> floatingWindow' (constVar True) "Debug" (label "Body")) windowDrag+  , simSpec "window-resize" 640 400 resizeUi windowResize+  , simSpec "window-resize-halo-scrolled" 640 400 haloUi haloScrolled+  , spec "window-layout-reuse" runWindowLayoutReuseTest+  , spec "window-custom-measure-placement" runWindowCustomMeasurePlacementTest+  , spec "page-window-scroll" runPageWindowScrollTest+  , simSpec "scrolled-debug-toggle" 640 400 debugToggleUi $+      click "Debug" >> expect "fps" >> frame >> expect "fps"+  , spec "span-beside-window" runSpanBesideWindowTest+  , spec "caption-drag-spans" runDragSpansTest+  , simSpec "caption-buttons" 400 200 captionUi captionButtonsClose+  ] -runWindowCloseDamageTest :: Context -> IORef Int -> IO ()-runWindowCloseDamageTest ctx failed = do-  let ui open = void (window open "Debug" (label "Body"))-      inp0 = withInput 640 400-  _ <- warmup2 ctx inp0 (ui True)-  _ <- runFrame ctx inp0 (ui False)-  dmg <- takeDamage ctx-  assertEq failed dmg DamageFull-  need <- needsRedraw ctx inp0 (inp0 {inputDeltaTime = 1})-  assert failed need+-- | Drag from @a@ to @b@, settle, and give @wid@'s rect.+dragRect :: WidgetId -> V2 -> V2 -> Sim a Rect+dragRect wid a b = drag (At a) (At b) 1 >> settle >> prevRect wid -runOverlayPanelLiveTest :: Context -> IORef Int -> IO ()-runOverlayPanelLiveTest _ failed = do-  let inp = withInputOff 320 240-      checkStatic ui = do-        ctx <- newContext-        _ <- warmup2 ctx inp ui-        need <- needsRedraw ctx inp inp-        assert failed (not need)-        _ <- runFrame ctx inp ui-        dmg <- takeDamage ctx-        assert failed (damageIsEmpty dmg)-      checkDirtyWake ui = do-        ctx <- newContext-        _ <- runFrame ctx inp ui-        markDirty ctx-        need <- needsRedraw ctx inp inp-        assert failed need-        _ <- runFrame ctx inp ui-        dmg <- takeDamage ctx-        assertEq failed dmg DamageFull-  checkStatic (void (window True "Debug" (label "fps 0")))-  checkStatic (void (modal True "About" (label "body")))-  checkDirtyWake (void (modal True "About" (label "body")))+rightOf :: Rect -> Float+rightOf (Rect x _ w _) = x + w --- Opening a modal or window must not shift the ids, and so the stored state,--- of the widgets after it.-runOverlaySiblingStateTest :: Context -> IORef Int -> IO ()-runOverlaySiblingStateTest _ failed = do-  let inp = withInput 640 400-      ui overlay open edit = do-        _ <- overlay open "About" (label "body")-        (txt, setTxt) <- useText "start"-        when edit (setTxt "edited")-        textInput txt-  forM_ [modal, window] $ \overlay -> do-    ctx <- newContext-    _ <- runFrame ctx inp (ui overlay False True)-    closed <- warmup2 ctx inp (ui overlay False False)-    assertEq failed closed "edited"-    opened <- warmup2 ctx inp (ui overlay True False)-    assertEq failed opened "edited"+-- | Labels "line 1" to "line n".+numbered :: Int -> NanoUI ()+numbered n = forM_ [1 .. n] $ \i -> label (T.pack ("line " <> show i)) +openWindow :: Text -> NanoUI a -> NanoUI (Response, Maybe a)+openWindow = floatingWindow' (constVar True)++-- | A fit-height header keeps its height when a scroller below takes the rest. runFitHeaderNoShrinkTest :: Context -> IORef Int -> IO () runFitHeaderNoShrinkTest ctx failed = do   let header = panelWith (padXY 16 12 . fillW) (label' "nano-ui SDL3 demo")-      only = columnWith (padAll 12 . grow) header-      withBody = columnWith (padAll 12 . gap 8 . grow) $ do-        h <- header-        scrollWith (tight . grow) $-          columnWith fillW (mapM_ (label . T.pack . show) [1 .. 40 :: Int])-        pure h-      tall = withInput 400 800-      short = withInput 400 200-  _ <- runFrame ctx tall only-  (r0, _, _, _) <- runFrame ctx tall only-  _ <- runFrame ctx short withBody-  (r1, _, _, _) <- runFrame ctx short withBody-  assert failed (rectH (respRect r1) + 0.5 >= rectH (respRect r0))+      withBody = columnWith (padAll 12 . gap 8 . grow) $+        header <* scrollWith (tight . grow) (columnWith fillW (numbered 40))+  alone <- warmup2 ctx (withInput 400 800) (columnWith (padAll 12 . grow) header)+  squeezed <- warmup2 ctx (withInput 400 200) withBody+  assert failed (rectH (respRect squeezed) + 0.5 >= rectH (respRect alone)) +gutterUi :: NanoUI (Response, Maybe Response)+gutterUi = openWindow "GutterWin" $ do+  wide <- labelWith' fillW "WWWW"+  kv "Key" (T.replicate 48 "M")+  wide <$ numbered 24++-- | A scrolling floatingWindow's body keeps the floatingWindow's side padding before the bar.+windowScrollGutter :: Sim (Response, Maybe Response) ()+windowScrollGutter = do+  (win, mwide) <- result+  ctx <- simContext+  failed <- simFailures+  checkJust mwide $ \wide -> liftIO $+    assertScrollGutterPad failed ctx (respId win) wide (scrollBarGutter ScrollBarWindow 0) (padR windowPad)++fitGutterUi :: NanoUI Response+fitGutterUi = fmap fst . openWindow "Debug" . columnWith (tight . gap 4 . minW 300 . fillW) $+  forM_ [1 .. 30 :: Int] $ \i -> kvMono (T.pack ("row " <> show i)) (T.pack ("value" <> show i))++-- | A scrolling window fitted to a minimum-width body ends right-aligned values before its bar.+windowFitScrollGutter :: Sim Response ()+windowFitScrollGutter = do+  win <- respRect <$> result+  values <- (\ss -> [rightOf r | (r, t, _, _, _) <- ss, "value" `T.isPrefixOf` t]) <$> spans+  let contentRight = rightOf win - padR windowPad - scrollBarGutter ScrollBarWindow 0+  check (not (null values) && all (<= contentRight + 0.5) values)++longPath :: Text+longPath = "C:\\Users\\zach\\AppData\\Local\\Microsoft\\Windows\\Fonts\\JetBrainsMono-Regular.ttf"++monoUi :: NanoUI Response+monoUi = fst <$> openWindow "Debug" (heading "Draw" >> label "NormalLabel" >> kvMono "font" longPath)++-- | A long mono value is cut with "..." at the content edge, and whole there once widened.+headingMonoTruncate :: Sim Response ()+headingMonoTruncate = do+  let fontSpan = do+        ss <- spans+        case [(r, t) | (r, t, _, _, _) <- ss, "JetBrainsMono" `T.isInfixOf` t || "..." `T.isInfixOf` t] of+          [found] -> pure found+          other -> fail ("font spans: " <> show other)+      contentRight r = rightOf r - padR windowPad+  win <- result+  r0@(Rect x0 y0 _ h0) <- prevRect (respId win)+  (f0, t0) <- fontSpan+  check ("..." `T.isSuffixOf` t0 && abs (rightOf f0 - contentRight r0) < 2)+  r1 <- dragRect (respId win) (V2 (x0 - 4) (y0 + h0 / 2)) (V2 (x0 - 1100) (y0 + h0 / 2))+  checkGt (rectW r1) (rectW r0 + 800)+  (f1, t1) <- fontSpan+  checkEq longPath t1+  check (abs (rightOf f1 - contentRight r1) < 2)++-- | A point inside @cover@ below its title bar and clear of @kids@.+safePoint :: Rect -> [Rect] -> Maybe V2+safePoint cover@(Rect x y w h) kids =+  listToMaybe [p | p <- candidates, rectContains cover p, not (any (`rectContains` p) kids)]+  where+    candidates =+      [V2 (x + 6) (y + h * 0.72), V2 (x + w - 6) (y + h * 0.72), V2 (x + w / 2) (y + h - 6)]+        ++ [V2 (x + 6) (y + h - 6), V2 (x + w - 6) (y + 46)]++-- | An open window shows its title and body, leaves the page clickable, ignores+-- Escape and reports its close button; a closed one draws nothing. A press on a+-- window never reaches a lower window; its own button clicks. runWindowOverlayTest :: Context -> IORef Int -> IO () runWindowOverlayTest ctx failed = do-  let inp0 = withInput 640 400-      ui = do+  openRef <- newIORef False+  let ui = do         outside <- button' "Outside"-        (win, mBody) <- window True "Debug" (label "Body")-        pure (outside, win, mBody)-      closedUi = do-        _ <- button "Outside"-        (win, mBody) <- window False "Debug" (label "Body")-        pure (win, mBody)-  do-    ((win, mBody), _, _, _) <- runFrame ctx inp0 closedUi-    assert failed (not (respClicked win))-    assert failed (case mBody of Nothing -> True; _ -> False)-    closedSpans <- collectOverlayTextSpans ctx inp0-    assert failed (not (any (\(_, txt, _, _, _) -> "Debug" `T.isInfixOf` txt) closedSpans))-  (outside0, win0, mBody0) <- warmup2 ctx inp0 ui-  panels <- floatingPanelRects ctx-  overlays <- collectOverlayTextSpans ctx inp0-  assert failed (any (\(_, txt, _, _, _) -> "Debug" `T.isInfixOf` txt) overlays)-  assert failed (any (\(_, txt, _, _, _) -> "Body" `T.isInfixOf` txt) overlays)-  assert failed (not (any (\(_, txt, _, _, _) -> T.strip txt == "X") overlays))-  let Rect wx wy ww wh = respRect win0-  assert failed (ww >= 100 && wh >= 20)-  assert failed (case mBody0 of Just _ -> True; _ -> False)-  let (pressOut, releaseOut) = clickPair inp0 (V2 (rectX (respRect outside0) + 8) (rectY (respRect outside0) + 8))-  _ <- runFrame ctx pressOut ui-  ((outsideHit, _, _), _, _, _) <- runFrame ctx releaseOut ui-  assert failed (respClicked outsideHit)-  let (clickWin, _) = clickPair inp0 (V2 (wx + ww / 2) (wy + wh * 0.7))-  ((outsideMid, _, _), _, _, _) <- runFrame ctx clickWin ui-  assert failed (not (respClicked outsideMid))-  let esc = keyInp KeyEscape inp0-  ((_, winEsc, _), _, _, _) <- runFrame ctx esc ui-  assert failed (not (respClicked winEsc))-  let Rect px py pw _ =-        case map snd (IM.toList panels) of-          (r : _) -> r-          _ -> respRect win0-      closeAt = V2 (px + pw - padR windowPad - 12.5) (py + padT windowPad + 19.5)-      (clickClose, releaseClose) = clickPair inp0 closeAt-  _ <- runFrame ctx clickClose ui-  ((_, winClose, _), _, _, _) <- runFrame ctx releaseClose ui-  assert failed (respClicked winClose)+        open <- liftIO (readIORef openRef)+        (win, body) <- floatingWindow' (constVar open) "Debug" (label "Body")+        pure (outside, win, body)+  runSim ctx failed (withInput 640 400) ui $ do+    (_, closed, noBody) <- result+    check (not (respClicked closed) && isNothing noBody)+    expectNot "Debug"+    liftIO (writeIORef openRef True)+    (_, win, body) <- settle+    expect "Debug" >> expect "Body"+    checkEq Nothing =<< findSpan "X"+    check (rectW (respRect win) >= 100 && rectH (respRect win) >= 20 && isJust body)+    (outsideHit, _, _) <- click "Outside"+    check (respClicked outsideHit)+    (_, afterEsc, _) <- pressKey KeyEscape+    check (not (respClicked afterEsc))+    Rect px py pw _ <- maybe (respRect win) fst . IM.minView <$> liftIO (floatingPanelRects ctx)+    (_, closing, _) <- click (at (px + pw - padR windowPad - 12.5) (py + padT windowPad + 19.5))+    check (respClicked closing)+  let stacked = do+        (_, lo) <- openWindow "Low" (button' "LowBtn")+        (hi, hiBtn) <- openWindow "High" (button' "HighBtn")+        pure (lo, hi, hiBtn)+  c <- newContext+  runSim c failed (withInput 300 220) stacked $ do+    (lo, cover, inside) <- result+    checkJust ((,) <$> lo <*> inside) $ \(low, btn) -> do+      checkJust (safePoint (respRect cover) [respRect btn, respRect low]) $ \p -> do+        (through, _, _) <- click (At p)+        check (not (maybe False respClicked through))+      (_, _, hit) <- click (On btn)+      check (maybe False respClicked hit) -runOverlayClickThroughTest :: Context -> IORef Int -> IO ()-runOverlayClickThroughTest ctx failed = do-  let-    inp0 = withInput 300 220-    windowUi = do-      outsides <- column (replicateM 10 (button' "Outside"))-      (win, mInside) <--        window True "Cover" $ do-          button' "Inside"-      pure (outsides, win, mInside)-    modalUi = do-      outsides <- column (replicateM 10 (button' "Outside"))-      (dlg, mInside) <--        modal True "Cover" $ do-          button' "Inside"-      pure (outsides, dlg, mInside)-    stackedUi = do-      (lo, mLo) <- window True "Low" (button' "LowBtn")-      (hi, mHi) <- window True "High" (button' "HighBtn")-      pure (lo, mLo, hi, mHi)-    childSafePoint cover childRects =-      let-        Rect x y w h = cover-        titleSkip = 40-        cands =-          [ V2 (x + 6) (y + h * 0.72)-          , V2 (x + w - 6) (y + h * 0.72)-          , V2 (x + w / 2) (y + h - 6)-          , V2 (x + 6) (y + h - 6)-          , V2 (x + w - 6) (y + titleSkip + 6)-          ]-        inCover p = rectContains cover p-        missesKids p = not (any (`rectContains` p) childRects)-       in-        case filter (\p -> inCover p && missesKids p) cands of-          (p : _) -> Just p-          [] -> Nothing-    clickNone clicked u pos = do-      let (press, release) = clickPair inp0 pos-      _ <- runFrame ctx press u-      runFrame ctx release u >>= \(hit, _, _, _) -> assert failed (not (clicked hit))-    runCovered u = do-      _ <- warmup2 ctx inp0 u-      ((_, cover0, mInside0), _, _, _) <- runFrame ctx inp0 u-      let coverRect = respRect cover0-      assert failed (rectW coverRect > 0 && rectH coverRect > 0)-      case mInside0 of-        Nothing -> assert failed False-        Just inside0 -> do-          let kids = [respRect inside0]-          case childSafePoint coverRect kids of-            Nothing -> assert failed False-            Just pos -> do-              let (press, release) = clickPair inp0 pos-              _ <- runFrame ctx press u-              ((outsidesHit, _, _), _, _, _) <- runFrame ctx release u-              assert failed (not (any respClicked outsidesHit))-          let ir = respRect inside0-              ip = V2 (rectX ir + rectW ir / 2) (rectY ir + rectH ir / 2)-          assert failed (rectW ir > 0 && rectH ir > 0)-          let (ipress, irelease) = clickPair inp0 ip-          _ <- runFrame ctx ipress u-          ((_, _, mInsideHit), _, _, _) <- runFrame ctx irelease u-          assert failed (maybe False respClicked mInsideHit)-    runStacked = do-      _ <- warmup2 ctx inp0 stackedUi-      ((_, mLo0, hi0, mHi0), _, _, _) <- runFrame ctx inp0 stackedUi-      case (mLo0, mHi0) of-        (Just loBtn, Just hiBtn) -> do-          let cover = respRect hi0-              kids = [respRect loBtn, respRect hiBtn]-          assert failed (rectW cover > 0 && rectH cover > 0)-          case childSafePoint cover kids of-            Nothing -> assert failed False-            Just pos -> clickNone (\(_, loHit, _, _) -> maybe False respClicked loHit) stackedUi pos-          let hp = V2 (rectX (respRect hiBtn) + rectW (respRect hiBtn) / 2) (rectY (respRect hiBtn) + rectH (respRect hiBtn) / 2)-              (hpress, hrelease) = clickPair inp0 hp-          _ <- runFrame ctx hpress stackedUi-          ((_, _, _, mHiHit), _, _, _) <- runFrame ctx hrelease stackedUi-          assert failed (maybe False respClicked mHiHit)-        _ -> assert failed False-  runCovered windowUi-  runCovered modalUi-  runStacked+-- | Opening a modal or window keeps the ids, and so the state, of later widgets.+runOverlaySiblingStateTest :: Context -> IORef Int -> IO ()+runOverlaySiblingStateTest _ failed = do+  let inp = withInput 640 400+      ui overlay open edit = do+        _ <- overlay (constVar open) "About" (label "body")+        txtVar <- useVar ("start" :: Text)+        when edit (writeVar txtVar "edited")+        readVar txtVar+  forM_ [modal, floatingWindow] $ \overlay -> do+    ctx <- newContext+    _ <- runFrame ctx inp (ui overlay False True)+    forM_ [False, True] $ \open -> assertEq failed "edited" =<< warmup2 ctx inp (ui overlay open False) -runWindowDragTest :: Context -> IORef Int -> IO ()-runWindowDragTest ctx failed = do+-- | Static overlays repaint nothing; closing one or a dirtied modal repaints all, a+-- scroll repaints a clip over the window, and churning content less than all.+runWindowDamageTest :: Context -> IORef Int -> IO ()+runWindowDamageTest _ failed = do+  let inp = withInputOff 640 400+      debug open body = fst <$> floatingWindow' (constVar open) "Debug" body+      about = void (modal' (constVar True) "About" (label "body"))+      fresh ui = newContext >>= \ctx -> (,) ctx <$> warmup2 ctx inp ui+      damageOf ctx i ui = runFrame ctx i ui >> takeDamage ctx+  forM_ [void (debug True (label "fps 0")), about] $ \ui -> do+    (ctx, _) <- fresh ui+    assert failed . not =<< needsRedraw ctx inp inp+    assert failed . damageIsEmpty =<< damageOf ctx inp ui+  (closing, _) <- fresh (debug True (label "Body"))+  assertEq failed DamageFull =<< damageOf closing inp (debug False (label "Body"))+  assert failed =<< needsRedraw closing inp inp {inputDeltaTime = 1}+  dirtied <- newContext+  _ <- runFrame dirtied inp about+  markDirty dirtied+  assert failed =<< needsRedraw dirtied inp inp+  assert failed . damageIsEmpty =<< damageOf dirtied inp about+  let scrolling = debug True (column (numbered 30))+      visible (Rect _ _ w h) = w > 0 && h > 0+  (scrolled, win) <- fresh scrolling+  damageOf scrolled inp {inputMousePos = centerOf win, inputScroll = V2 0 1} scrolling >>= \case+    DamageClip r -> assert failed (maybe False visible (rectIntersect r (respRect win)))+    _ -> assert failed False+  let churn k = button "Outside" >> debug True (columnWith (tight . gap 4 . minW 300 . fillW) $ do+        label (T.replicate (1 + k `mod` 9) "M")+        label "static row")+  (churning, _) <- fresh (churn 0)+  forM_ [1 .. 30 :: Int] $ \k -> assert failed . (/= DamageFull) =<< damageOf churning inp (churn k)++-- | A title drag moves the window; held still past the left edge it stops there, idle.+windowDrag :: Sim Response ()+windowDrag = do+  r0 <- respRect <$> result+  let V2 gx gy = windowTitleGrab r0+  _ <- press (at gx gy) >> moveTo (at (gx - 50) (gy + 30))+  checkEq DamageFull =<< frameDamage+  r1 <- respRect <$> (release >> settle)+  check (rectX r1 < rectX r0 - 10 && rectY r1 > rectY r0 + 10)+  let V2 hx hy = windowTitleGrab r1+      edge = at (hx - rectX r1 - 50) hy+  _ <- press (at hx hy) >> moveTo edge >> moveTo edge+  checkEq 0 . rectX . respRect =<< moveTo edge+  check . not =<< wantsFrame++resizeUi :: NanoUI (Response, Response)+resizeUi = (,) <$> button' "Hit" <*> (fst <$> openWindow "Resize" (label "Body"))++-- | A floatingWindow's margins, out to a halo and in to its edges, show resize cursors and+-- drag to resize it, down to its title bar. A page button in the halo keeps its cursor.+windowResize :: Sim (Response, Response) ()+windowResize = do+  (btn, win) <- result+  Rect x0 y0 w0 h0 <- prevRect (respId win)+  let (r, b, cx, cy) = (x0 + w0, y0 + h0, x0 + w0 / 2, y0 + h0 / 2)+      edge = dragRect (respId win)+  forM_+    [ (UiCursorNwseResize, [(r + 4, b + 4), (x0 - 4, y0 - 4), (r - 5, b - 5), (x0 + 5, y0 + 5), (x0 - 4, y0 + 8)])+    , (UiCursorNeswResize, [(r + 4, y0 - 4), (x0 - 4, b + 4), (x0 + 5, b - 5)])+    , (UiCursorNsResize, [(cx, y0 - 4), (cx, b + 4), (cx, b - 5), (cx, y0 + 3)])+    , (UiCursorEwResize, [(x0 - 4, cy), (r + 4, cy), (r - 5, cy), (x0 + 5, cy)])+    ]+    $ \(kind, ps) -> forM_ ps $ \(x, y) -> checkEq ((x, y), kind) . (,) (x, y) =<< cursorAt (at x y)+  check . (/= UiCursorNsResize) =<< cursorAt (at cx (y0 + 20))+  check . (/= UiCursorEwResize) =<< cursorAt (at (r - padR windowPad - 4) cy)+  Rect x1 y1 w1 h1 <- edge (V2 (r + 4) (b + 4)) (V2 (r + 40) (b + 30))+  check (w1 > w0 + 20 && h1 > h0 + 15)+  Rect xw yw ww hw <- edge (V2 (x1 - 4) (y1 + h1 / 2)) (V2 (x1 - 36) (y1 + h1 / 2))+  check (ww > w1 + 15 && xw < x1 - 10)+  Rect xn yn wn hn <- edge (V2 (xw + ww / 2) (yw - 4)) (V2 (xw + ww / 2) (yw - 20))+  check (hn > hw + 8 && yn < yw - 5)+  Rect xs ys ws hs <- edge (V2 (xn + wn / 2) (yn + hn + 4)) (V2 (xn + wn / 2) (yn + 4))+  check (hs + 0.01 >= 39 + padT windowPad + padB windowPad)+  -- A press in the left margin, inside the window, resizes.+  Rect xi yi wi _ <- edge (V2 (xs + 5) (ys + hs / 2)) (V2 (xs - 25) (ys + hs / 2))+  check (wi > ws + 20 && xi < xs - 20)+  -- Dragged by its title to 4 px right of the page button, its halo covers the button.+  let Rect bx by bw bh = respRect btn+      destX = bx + bw + 4+      hit@(V2 hx hy) = V2 (bx + bw - 2) (by + bh - 2)+  Rect x2 y2 _ h2 <- edge (V2 (xi + 24) (yi + 22)) (V2 (destX + 24) (yi + 22))+  check (abs (x2 - destX) <= 8 && hx < x2 && hx >= x2 - 12 && hy >= y2 - 12 && hy <= y2 + h2 + 12)+  kind <- cursorAt (At hit)+  check (kind `notElem` [UiCursorEwResize, UiCursorNsResize, UiCursorNwseResize, UiCursorNeswResize])++haloUi :: NanoUI WidgetId+haloUi = do+  (page, ()) <- scrollArea (fillW . fillH) . columnWith fillW $ do+    spacer Fit (Fixed 400)+    replicateM_ 10 (buttonWith (fillW . fixedH 100) "Page")+  page <$ floatingWindow (constVar True) "Tool" (label "Body")++-- | A page button in a floatingWindow's halo keeps the press, hit where the scrolled page draws it.+haloScrolled :: Sim WidgetId ()+haloScrolled = do+  let windows = map snd <$> onContext (nodesOfType NodeWindow)+  page <- result+  onContext (\c -> setScrollOffsetIO c page 400)+  before <- settle >> windows+  checkJust (listToMaybe before) $ \(Rect x y _ h) -> do+    _ <- drag (at (x - 6) (y + h / 2)) (at (x - 60) (y + h / 2)) 1+    checkEq before =<< (settle >> windows)++-- | Reusing the layout cache with floating panels open lays out as a fresh solve: still,+-- with a popup moving in the window, mid-drag, resized, at another size, under a modal.+runWindowLayoutReuseTest :: Context -> IORef Int -> IO ()+runWindowLayoutReuseTest ctx failed = do+  fresh <- newContext   let inp0 = withInput 640 400-      ui = fmap fst (window True "Debug" (label "Body"))-  win0 <- warmup2 ctx inp0 ui-  let r0 = respRect win0-      x0 = rectX r0-      y0 = rectY r0-      dest = V2 (x0 + 24 - 50) (y0 + 22 + 30)-  runDragFrom ctx inp0 ui (windowTitleGrab r0) dest-  dmg <- takeDamage ctx-  assertEq failed dmg DamageFull-  (win1, _, _, _) <- runFrame ctx (inp0 {inputMousePos = dest}) ui-  let Rect x1 y1 _ _ = respRect win1-  assert failed (x1 < x0 - 10)-  assert failed (y1 > y0 + 10)+      ui modalOpen anchor = do+        column $ forM_ [1 .. 20 :: Int] $ \i -> void (button (T.pack ("row " <> show i)))+        win <- fmap fst $ openWindow "Tools" $ columnWith (maxW 260) $ do+          forM_ [1 .. 12 :: Int] $ \i -> labelWith fillW (T.replicate i "wrapping words ")+          void (button "ok")+          let cfg = (defaultPopupConfig (AnchorPoint anchor)) {popupDismissable = False}+          void (popup' (constVar True) cfg (label "tip"))+        void (modal' (constVar modalOpen) "Note" (label (T.replicate 12 "a note that wraps ")))+        pure win+      -- A frame on this context, which reuses what it placed, and on one that never does.+      same i u = respRect <$> sameAsFreshSolve failed fresh ctx i u+      still = ui False (V2 100 100)+  r0 <- same inp0 still >> same inp0 still+  -- The window and the popup in it are both kept for the next frame.+  _ <- same inp0 still+  cache <- readIORef (ctxLayoutCache ctx)+  assertEq failed 2 . IM.size =<< maybe (pure IM.empty) (\(c, _, _) -> readIORef (lcPlaced c)) cache+  forM_ [1 .. 3 :: Int] $ \k -> forM_ [0, 3] $ \d ->+    same inp0 (ui False (V2 (100 + 7 * fromIntegral k + d) 120))+  let V2 gx gy = windowTitleGrab r0+  _ <- same (pressAt inp0 (V2 gx gy)) still+  forM_ [1 .. 4 :: Int] $ \k ->+    same (holdAt inp0 (V2 (gx - 20 * fromIntegral k) (gy + 10 * fromIntegral k))) still+  r1@(Rect x1 y1 w1 h1) <- same (releaseAt inp0 {inputMousePos = V2 (gx - 80) (gy + 40)}) still+  assert failed (x1 < rectX r0 - 40 && y1 > rectY r0)+  let edgeAt = V2 (x1 + w1 + 4) (y1 + h1 / 2)+      dest = v2Add edgeAt (V2 30 0)+  mapM_ (`same` still) [pressAt inp0 edgeAt, holdAt inp0 dest, inp0 {inputMousePos = dest}]+  r2 <- same inp0 {inputMousePos = dest} still+  assertGt failed (rectW r2) (rectW r1 + 20)+  let small = withInput 520 360+  forM_ [(small, still), (small, ui True (V2 100 100))] $ \(i, u) -> replicateM_ 3 (same i u) --- Wheeling over a window's body scrolls the window, not the page, whether the--- window is declared inside a page scroll area or beside one.+-- | A custom widget's measure changing only at a floatingWindow's inner width reuses the root+-- solve and re-places the window instead of keeping its cached placement.+runWindowCustomMeasurePlacementTest :: Context -> IORef Int -> IO ()+runWindowCustomMeasurePlacementTest ctx failed = do+  let inp = withInput 640 400+      ui h = column $ fmap snd $ openWindow "Tools" $ column $ do+        spacer (Fixed 240) (Fixed 1)+        fst <$> customWidget defaultCustomWidgetSpec+          { widgetMeasure = Just (\_ (w, _) -> if w >= 1e8 then (100, 20) else (w, h))+          , widgetLayout = fillW+          }+      heightOf = maybe 0 (rectH . respRect)+      cacheName = readIORef (ctxLayoutCache ctx) >>= evaluate >>= makeStableName+  assertEq failed 30 . heightOf =<< warmup2 ctx inp (ui 30)+  cache <- cacheName+  _ <- runFrame ctx inp (ui 60)+  assert failed . (== cache) =<< cacheName+  -- A window keeps the size it was first solved at, so the fresh solve+  -- runs after the same frames.+  fresh <- newContext+  _ <- warmup2 fresh inp (ui 30)+  _ <- runFrame fresh inp (ui 60)+  assertEq failed 60 . heightOf =<< sameAsFreshSolve failed fresh ctx inp (ui 60)++-- | The wheel over a window scrolls it, not the page, declared in a page scroller or beside. runPageWindowScrollTest :: Context -> IORef Int -> IO () runPageWindowScrollTest _ failed = do-  let line1 = T.pack "line 1"-      title = T.pack "Debug"-      debugWindow =-        fmap fst $-          window True "Debug" $-            column $-              mapM_ (\i -> label (T.pack ("line " <> show (i :: Int)))) [1 .. 30]-      nested = do-        (_, win) <- scrollArea (tight . grow) $ do-          void (button "OK")-          debugWindow-        pure win-      sibling = do-        scrollWith (tight . grow) $ void (label "page")-        debugWindow-  forM_ [(withInput 320 220, nested), (withInput 640 400, sibling)] $ \(inp0, ui) -> do+  let debugWindow = fst <$> openWindow "Debug" (column (numbered 30))+      nested = snd <$> scrollArea (tight . grow) (button "OK" >> debugWindow)+      sibling = scrollWith (tight . grow) (label "page") >> debugWindow+  forM_ [(withInput 320 220, nested), (withInput 640 400, sibling)] $ \(inp, ui) -> do     ctx <- newContext-    win <- warmup2 ctx inp0 ui-    let Rect wx _ ww _ = respRect win-    spans0 <- collectOverlayTextSpans ctx inp0-    case spanYOf line1 spans0 of+    Rect wx _ ww _ <- respRect <$> warmup2 ctx inp ui+    spanYOf "line 1" <$> collectOverlayTextSpans ctx inp >>= \case+      y : _ -> assertWheelTitlePinned failed ctx inp ui "Debug" "line 1" (V2 (wx + ww / 2) (y + 2))       [] -> assert failed False-      b0 : _ -> do-        let wheelAt = V2 (wx + ww / 2) (b0 + 2)-        assertWheelTitlePinned failed ctx inp0 ui title line1 wheelAt Nothing -runWindowScrollOnlyDamageTest :: Context -> IORef Int -> IO ()-runWindowScrollOnlyDamageTest ctx failed = do-  let inp0 = withInput 640 400-      ui =-        fmap fst $-          window True "Debug" $-            column $-              mapM_ (\i -> label (T.pack ("line " <> show (i :: Int)))) [1 .. 30]-  win <- warmup2 ctx inp0 ui-  let wheel =-        inp0-          { inputMousePos = centerOf win-          , inputScroll = V2 0 1-          }-  _ <- runFrame ctx wheel ui-  dmg <- takeDamage ctx-  case dmg of-    DamageClip r ->-      assert failed (maybe False (\i -> rectW i > 0 && rectH i > 0) (rectIntersect r (respRect win)))-    _ -> assert failed False--runWindowContentChurnTest :: Context -> IORef Int -> IO ()-runWindowContentChurnTest ctx failed = do-  let inp0 = withInput 640 400-      ui k = do-        _ <- button "Outside"-        fst <$> window True "Debug" (columnWith (tight . gap 4 . minW 300 . fillW) $ do-          void $ label (T.pack (replicate (1 + (k `mod` 9)) 'M'))-          void $ label "static row"-          )-  _ <- warmup2 ctx inp0 (ui 0)-  counter <- newIORef (1 :: Int)-  allClip <- replicateM 30 $ do-    k <- readIORef counter-    writeIORef counter (k + 1)-    _ <- runFrame ctx inp0 (ui k)-    dmg <- takeDamage ctx-    case dmg of-      DamageClip _ -> pure True-      _ -> pure False-  assert failed (and allClip)--runScrolledDebugToggleTest :: Context -> IORef Int -> IO ()-runScrolledDebugToggleTest ctx failed = do-  let inp0 = withInput 640 400-      title = T.pack "Debug"-      ui = do-        (open, setOpen) <- useFlag False-        (_, dbgBtn) <- scrollArea (tight . grow) $ do-          b <- button' "Debug"-          when (respClicked b) (setOpen (not open))-          pure b-        when open $ void (window True "Debug" (label "fps"))-        pure dbgBtn-  dbgBtn <- warmup2 ctx inp0 ui-  let pos = centerOf dbgBtn-  _ <- runClick ctx inp0 ui pos-  spans <- collectOverlayTextSpans ctx inp0-  let titles = [t | (_, t, _, _, _) <- spans, title `T.isInfixOf` t]-  assert failed (not (null titles))-  _ <- runFrame ctx inp0 ui-  spansAfter <- collectOverlayTextSpans ctx inp0-  let titlesAfter = [t | (_, t, _, _, _) <- spansAfter, title `T.isInfixOf` t]-  assert failed (not (null titlesAfter))+-- | A button in a page scroller opens a window that stays open.+debugToggleUi :: NanoUI ()+debugToggleUi = do+  openVar <- useVar False+  open <- readVar openVar+  scrollWith (tight . grow) (whenM (button "Debug") (writeVar openVar (not open)))+  when open (void (openWindow "Debug" (label "fps"))) -runWindowResizeTest :: Context -> IORef Int -> IO ()-runWindowResizeTest ctx failed = do-  let inp0 = withInput 640 400-      ui = fmap fst (window True "Resize" (label "Body"))-  _ <- runFrame ctx inp0 ui-  (win0, _, _, _) <- runFrame ctx inp0 ui-  mrect0 <- getPrevRect ctx (respId win0)-  case mrect0 of-    Nothing -> assert failed False-    Just (Rect x0 y0 w0 h0) -> do-      assert failed (w0 > 0 && h0 > 0)-      let hoverAt p = inp0 {inputMousePos = p}-          expectCursor p kind = do-            k <- uiCursorKind ctx (hoverAt p)-            assertEq failed k kind-      expectCursor (V2 (x0 + w0 + 4) (y0 + h0 + 4)) UiCursorNwseResize-      expectCursor (V2 (x0 - 4) (y0 - 4)) UiCursorNwseResize-      expectCursor (V2 (x0 + w0 + 4) (y0 - 4)) UiCursorNeswResize-      expectCursor (V2 (x0 - 4) (y0 + h0 + 4)) UiCursorNeswResize-      expectCursor (V2 (x0 + w0 / 2) (y0 - 4)) UiCursorNsResize-      expectCursor (V2 (x0 + w0 / 2) (y0 + h0 + 4)) UiCursorNsResize-      expectCursor (V2 (x0 - 4) (y0 + h0 / 2)) UiCursorEwResize-      expectCursor (V2 (x0 + w0 + 4) (y0 + h0 / 2)) UiCursorEwResize-      expectCursor (V2 (x0 + w0 - 5) (y0 + h0 / 2)) UiCursorEwResize-      insideKind <- uiCursorKind ctx (hoverAt (V2 (x0 + w0 - padR windowPad - 4) (y0 + h0 / 2)))-      assert failed (insideKind /= UiCursorEwResize)-      mSe <- dragWindowEdge ctx inp0 ui (V2 (x0 + w0 + 4) (y0 + h0 + 4)) (V2 (x0 + w0 + 40) (y0 + h0 + 30))-      case mSe of-        Nothing -> assert failed False-        Just (Rect x1 y1 w1 h1) -> do-          assertGt failed w1 (w0 + 20)-          assertGt failed h1 (h0 + 15)-          mW <- dragWindowEdge ctx inp0 ui (V2 (x1 - 4) (y1 + h1 / 2)) (V2 (x1 - 36) (y1 + h1 / 2))-          case mW of-            Nothing -> assert failed False-            Just (Rect xw yw ww hw) -> do-              assertGt failed ww (w1 + 15)-              assertLt failed xw (x1 - 10)-              mN <- dragWindowEdge ctx inp0 ui (V2 (xw + ww / 2) (yw - 4)) (V2 (xw + ww / 2) (yw - 20))-              case mN of-                Nothing -> assert failed False-                Just (Rect xn yn wn hn) -> do-                  assertGt failed hn (hw + 8)-                  assertLt failed yn (yw - 5)-                  let minTitleH = 39 + padT windowPad + padB windowPad-                  mShort <- dragWindowEdge ctx inp0 ui (V2 (xn + wn / 2) (yn + hn + 4)) (V2 (xn + wn / 2) (yn + 4))-                  case mShort of-                    Nothing -> assert failed False-                    Just (Rect _ _ _ hMin) -> assert failed (hMin + 0.01 >= minTitleH)+-- | A span beside a window, even an empty field's, is kept whether the window is open or not.+runSpanBesideWindowTest :: Context -> IORef Int -> IO ()+runSpanBesideWindowTest ctx failed = do+  let inp = withInput 640 400+      ui open = do+        columnWith (padXY 20 320) (void (withValue "" textInput))+        void (floatingWindow' (constVar open) "Elsewhere" (label "Body"))+      emptySpans = (\ss -> [(r, clip) | (r, t, _, _, clip) <- ss, T.null t]) <$> collectTextSpans ctx+  closed <- warmup2 ctx inp (ui False) >> emptySpans+  opened <- warmup2 ctx inp (ui True) >> emptySpans+  panels <- IM.elems <$> floatingPanelRects ctx+  assertEq failed 1 (length closed)+  assert failed (not (null panels) && and [isNothing (rectIntersect p clip) | p <- panels, (_, clip) <- closed])+  assertEq failed closed opened -runWindowResizeHaloHitTest :: Context -> IORef Int -> IO ()-runWindowResizeHaloHitTest ctx failed = do-  let inp0 = withInput 640 400-      ui = do-        btn <- button' "Hit"-        (win, _) <- window True "Resize" (label "Body")-        pure (btn, win)-  (btn0, win0) <- warmup2 ctx inp0 ui-  let Rect bx by bw bh = respRect btn0-      Rect x0 y0 _ _ = respRect win0-      grab = V2 (x0 + 24) (y0 + 22)-      destX = bx + bw + 4-      press = inp0 {inputMousePos = grab, inputMouseDown = True, inputMousePressed = True}-  _ <- runFrame ctx press ui-  let moved = press {inputMousePos = V2 (destX + 24) (y0 + 22), inputMousePressed = False}-  _ <- runFrame ctx moved ui-  ((_, win1), _, _, _) <- runFrame ctx (inp0 {inputMousePos = V2 destX (y0 + 22)}) ui-  let Rect x1 y1 _ h1 = respRect win1-      hit = V2 (bx + bw - 2) (by + bh - 2)-      inHalo = let s = 12-                in (v2X hit < x1 && v2X hit >= x1 - s)-                    && v2Y hit >= y1 - s-                    && v2Y hit <= y1 + h1 + s-      isResize k = k == UiCursorEwResize || k == UiCursorNsResize || k == UiCursorNwseResize || k == UiCursorNeswResize-  kind <- uiCursorKind ctx (inp0 {inputMousePos = hit})-  assert failed (abs (x1 - destX) <= 8)-  assert failed inHalo-  assert failed (not (isResize kind))+-- | A title bar drags by the gaps between its widgets, in any order, overlapping or not.+runDragSpansTest :: Context -> IORef Int -> IO ()+runDragSpansTest _ failed = do+  let bar = Rect 0 0 400 30+      menus = Rect 0 0 100 30+      buttons = Rect 280 0 120 30+  forM_+    [ (bar, [menus, buttons], [Rect 100 0 180 30])+    , (bar, [buttons, menus], [Rect 100 0 180 30])+    , (bar, [], [bar])+    , (bar, [menus, Rect 150 4 50 22, buttons], [Rect 100 0 50 30, Rect 200 0 80 30])+    , (bar, [Rect 0 0 200 30, Rect 100 0 150 30], [Rect 250 0 150 30])+    , (bar, [Rect 0 0 400 30], [])+    , (bar, [Rect 150 40 50 20], [bar])+    , (Rect 100 0 300 30, [Rect 0 0 60 30], [Rect 100 0 300 30])+    ]+    $ \(b, taken, want) -> assertEq failed want (dragSpans b taken) -runSeparatorSpanTest :: Context -> IORef Int -> IO ()-runSeparatorSpanTest ctx failed = do-  let inp = withInput 200 120-      ui = columnWith fillW $ do-        label "A"-        sid <- currentId-        separator-        label "B"-        pure sid-  _ <- runFrame ctx inp ui-  (sid, _, _, _) <- runFrame ctx inp ui-  mRect <- getPrevRect ctx sid-  case mRect of-    Just (Rect _ _ w h) -> do-      assert failed (w >= 100)-      assert failed (h <= 2)-    Nothing -> assert failed False+captionUi :: NanoUI (Maybe CaptionAction, Rect)+captionUi = rowWith (tight . fillW . fixedH captionBarHeight) (flex >> captionButtons False) -runHeadingMonoTruncateTest :: Context -> IORef Int -> IO ()-runHeadingMonoTruncateTest ctx failed = do-  let inp = withInput 1600 600-      longPath = T.pack "C:\\Users\\zach\\AppData\\Local\\Microsoft\\Windows\\Fonts\\JetBrainsMono-Regular.ttf"-      ui = fst <$> window True "Debug" (do-        heading "Draw"-        _ <- label "NormalLabel"-        kvMono "font" longPath)-  win <- warmup2 ctx inp ui-  let Rect wx wy ww wh = respRect win-      contentRight = wx + ww - padR windowPad-  spans <- collectOverlayTextSpans ctx inp-  let fontSpans = [(r, t) | (r, t, _, _, _) <- spans, "JetBrainsMono" `T.isInfixOf` t || "..." `T.isInfixOf` t]-  case fontSpans of-    [(Rect fx _ fw _, t)] -> do-      assert failed ("..." `T.isSuffixOf` t)-      assert failed (abs (fx + fw - contentRight) < 2.0)-    _ -> assert failed False-  mWide <- dragWindowEdge ctx inp ui (V2 (wx - 4) (wy + wh / 2)) (V2 (wx - 1100) (wy + wh / 2))-  case mWide of-    Nothing -> assert failed False-    Just (Rect wxWide _ wwWide _) -> do-      assertGt failed wwWide (ww + 800)-      spansWide <- collectOverlayTextSpans ctx inp-      let fontSpansWide = [(r, t) | (r, t, _, _, _) <- spansWide, "JetBrainsMono" `T.isInfixOf` t || "..." `T.isInfixOf` t]-      case fontSpansWide of-        [(Rect fx2 _ fw2 _, t2)] -> do-          assert failed (t2 == longPath)-          assert failed (not ("..." `T.isSuffixOf` t2))-          let contentRightWide = wxWide + wwWide - padR windowPad-          assert failed (abs (fx2 + fw2 - contentRightWide) < 2.0)-        _ -> assert failed False+-- | The caption buttons' rect spans all three at the right end; the last one closes.+captionButtonsClose :: Sim (Maybe CaptionAction, Rect) ()+captionButtonsClose = do+  (action, Rect bx by bw bh) <- result+  let closeW = capButtonW defaultCaptionConfig+  checkEq Nothing action+  check (bw >= 3 * closeW && bx > 0 && bx + bw <= 400)+  checkEq (capButtonH defaultCaptionConfig) bh+  checkEq (Just CaptionClose) . fst =<< click (Within (Rect (bx + bw - closeW) by closeW bh))
test/integration/Main.hs view
@@ -1,300 +1,125 @@+{-# OPTIONS_GHC -O0 #-} module Main (main) where -import Cases-import Cases.Animation-import Cases.Atlas-import Cases.Cache-import Cases.Combo-import Cases.ContextMenu-import Cases.CustomWidget-import Cases.Damage-import Cases.Demo-import Cases.Grid-import Cases.HostDraw-import Cases.Keyboard-import Cases.Modal-import Cases.NoThunks-import Cases.NumericInput-import Cases.PointerRelease-import Cases.RichText-import Cases.Runner-import Cases.SIMD-import Cases.Scroll-import Cases.Select-import Cases.Shaping-import Cases.State-import Cases.Styling-import Cases.Svg-import Cases.Table-import Cases.Tabs-import Cases.TextInput-import Cases.Tooltip-import Cases.Window-import Data.IORef (IORef)-import NanoUI.Testing (Context, newContext, newPixelContext)+import BackendApi (backendApiCheck)+import Cases.Adornment qualified+import Cases.Animation qualified+import Cases.ApiSmoke qualified+import Cases.Atlas qualified+import Cases.Cache qualified+import Cases.Combo qualified+import Cases.ContextMenu qualified+import Cases.Cursors qualified+import Cases.CustomWidget qualified+import Cases.Damage qualified+import Cases.DamageProps qualified+import Cases.Demo qualified+import Cases.Explain qualified+import Cases.Focus qualified+import Cases.Grid qualified+import Cases.HostDraw qualified+import Cases.Images qualified+import Cases.Ime qualified+import Cases.Keyboard qualified+import Cases.Labels qualified+import Cases.LayoutFlow qualified+import Cases.LayoutProps qualified+import Cases.LayoutReuse qualified+import Cases.Modal qualified+import Cases.NativeWindow qualified+import Cases.NoThunks qualified+import Cases.NumericInput qualified+import Cases.PaneGrid qualified+import Cases.Passes qualified+import Cases.Paths qualified+import Cases.PointerExtra qualified+import Cases.PointerOwnership qualified+import Cases.PointerRelease qualified+import Cases.Reorder qualified+import Cases.RichText qualified+import Cases.Runner qualified+import Cases.SIMD qualified+import Cases.Scroll qualified+import Cases.Select qualified+import Cases.Shader qualified+import Cases.Shaping qualified+import Cases.Shortcut qualified+import Cases.SimFuzz qualified+import Cases.State qualified+import Cases.Styling qualified+import Cases.Svg qualified+import Cases.Table qualified+import Cases.Tabs qualified+import Cases.Tasks qualified+import Cases.TextInput qualified+import Cases.Theming qualified+import Cases.Tooltip qualified+import Cases.TooltipDelay qualified+import Cases.ViewApi qualified+import Cases.Visibility qualified+import Cases.WidgetIdIndex qualified+import Cases.Window qualified import NanoUI.Testing.Runner (runTests) -data TestSpec-  = TestSpec-  { specName :: String-  , specSdl :: Bool-  , specRun :: Context -> IORef Int -> IO ()-  }- main :: IO ()-main =-  runTests-    [ (specName, if specSdl then newPixelContext else newContext, specRun)-    | TestSpec {specName, specSdl, specRun} <- testSpecs+main = do+  backendApiCheck+  runTests . concat $+    [ Cases.Adornment.tests+    , Cases.Animation.tests+    , Cases.ApiSmoke.tests+    , Cases.Atlas.tests+    , Cases.Cache.tests+    , Cases.Combo.tests+    , Cases.ContextMenu.tests+    , Cases.Cursors.tests+    , Cases.CustomWidget.tests+    , Cases.Damage.tests+    , Cases.DamageProps.tests+    , Cases.Demo.tests+    , Cases.Explain.tests+    , Cases.Focus.tests+    , Cases.Grid.tests+    , Cases.HostDraw.tests+    , Cases.Images.tests+    , Cases.Ime.tests+    , Cases.Keyboard.tests+    , Cases.Labels.tests+    , Cases.LayoutFlow.tests+    , Cases.LayoutProps.tests+    , Cases.LayoutReuse.tests+    , Cases.Modal.tests+    , Cases.NativeWindow.tests+    , Cases.NoThunks.tests+    , Cases.NumericInput.tests+    , Cases.PaneGrid.tests+    , Cases.Passes.tests+    , Cases.Paths.tests+    , Cases.PointerExtra.tests+    , Cases.PointerOwnership.tests+    , Cases.PointerRelease.tests+    , Cases.Reorder.tests+    , Cases.RichText.tests+    , Cases.Runner.tests+    , Cases.SIMD.tests+    , Cases.Scroll.tests+    , Cases.Select.tests+    , Cases.Shader.tests+    , Cases.Shaping.tests+    , Cases.Shortcut.tests+    , Cases.SimFuzz.tests+    , Cases.State.tests+    , Cases.Styling.tests+    , Cases.Svg.tests+    , Cases.Table.tests+    , Cases.Tabs.tests+    , Cases.Tasks.tests+    , Cases.TextInput.tests+    , Cases.Theming.tests+    , Cases.Tooltip.tests+    , Cases.TooltipDelay.tests+    , Cases.ViewApi.tests+    , Cases.Visibility.tests+    , Cases.WidgetIdIndex.tests+    , Cases.Window.tests     ]--testSpecs :: [TestSpec]-testSpecs =-  -- Runner, state and messages-  [ TestSpec "session-loop" False runSessionLoopTest-  , TestSpec "drawing-lock" False runDrawingLockTest-  , TestSpec "simd-writes" False runSimdWritesTest-  , TestSpec "no-thunks" False runNoThunksTest-  , TestSpec "controlled-state" False runControlledStateTest-  , TestSpec "controlled-inputs" False runControlledInputsTest-  , TestSpec "hook-state" False runHookStateTest-  , TestSpec "collection-api" False runCollectionApiTest-  , TestSpec "embed-state" False runEmbedStateTest-  , TestSpec "host-slot" False runHostSlotTest-  , TestSpec "reduce-messages" False runReduceMessagesTest-  , TestSpec "reduce-click" False runReduceClickTest-  , TestSpec "widget-no-string-emit" False runWidgetNoStringEmitTest-  -- Ids, layout and caches-  , TestSpec "id-keyed-list" False runIdKeyedListTest-  , TestSpec "fit-muted-width" False runFitMutedWidthTest-  , TestSpec "fit-header-no-shrink" False runFitHeaderNoShrinkTest-  , TestSpec "layout-reuse" False runLayoutReuseTest-  , TestSpec "metric-cache-invalidation" False runMetricCacheInvalidationTest-  , TestSpec "widget-placement-cache" False runWidgetPlacementCacheTest-  , TestSpec "layout-cache-paint-state" False runLayoutPaintStateTest-  , TestSpec "deep-nesting" False runDeepNestingTest-  , TestSpec "grow-split" False runGrowSplitTest-  , TestSpec "percent-gap-shrink" False runPercentGapShrinkTest-  , TestSpec "aspect-layout" False runAspectLayoutTest-  , TestSpec "label-align-end" True runLabelAlignEndTest-  , TestSpec "responsive-wrap" True runResponsiveWrapTest-  , TestSpec "kv-multiline-height" True runKvMultilineHeightTest-  , TestSpec "separator-span" False runSeparatorSpanTest-  , TestSpec "panel-paints" False runPanelPaintsTest-  , TestSpec "grid-columns-font-color" False runGridColumnsWithFontColorTest-  , TestSpec "grid-nested" False runNestedGridTest-  , TestSpec "stale-font-color" False runStaleFontColorTest-  , TestSpec "font-composition" True runFontCompositionTest-  , TestSpec "align-baseline" True runAlignBaselineTest-  -- Drawing-  , TestSpec "draw-square-geometry" False runSquareGeometryTest-  , TestSpec "draw-external-text" False runExternalTextTest-  , TestSpec "draw-concentric-circles" False runConcentricCirclesTest-  , TestSpec "drawing" False runDrawingTest-  , TestSpec "image" False runImageTest-  , TestSpec "rich-text-wrap" False runRichTextWrapTest-  , TestSpec "rich-text-link" False runRichTextLinkTest-  , TestSpec "bidi-runs" False runBidiRunsTest-  , TestSpec "shaped-carets" False runShapedCaretTest-  , TestSpec "svg-raster" False runSvgRasterTest-  , TestSpec "svg-icon" False runSvgIconTest-  , TestSpec "empty-frame" False runEmptyFrameTest-  , TestSpec "image-swap-damage" False runImageSwapDamageTest-  , TestSpec "atlas-growth" False runAtlasGrowthTest-  -- Pointer, redraw and damage-  , TestSpec "pointer-cursor" False runPointerCursorTest-  , TestSpec "hover-damage" False runHoverDamageTest-  , TestSpec "damage-bounds-resolution" False runDamageBoundsResolutionTest-  , TestSpec "damage-widget-explicit" False runExplicitDamageWidgetTest-  , TestSpec "damage-queue-cleared" False runDamageQueueClearedPerFrameTest-  , TestSpec "damage-state-change" False runStateChangeDamageTest-  , TestSpec "damage-orphan-anim-settles" False runOrphanAnimationDamageSettlesTest-  , TestSpec "versioned-drawing-damage" False runVersionedDrawingDamageTest-  , TestSpec "clip-frame-backdrop" False runClipFrameBackdropTest-  , TestSpec "textarea-select-all-damage" False runTextAreaSelectAllDamageTest-  , TestSpec "panel-body-swap-damage" False runPanelBodySwapDamageTest-  , TestSpec "refresh-forces-redraw" False runRefreshRedrawTest-  -- Animation-  , TestSpec "animation-settle" False runAnimationSettleTest-  , TestSpec "animation-damage" False runAnimationDamageTest-  , TestSpec "animation-stagger" False runAnimationStaggerTest-  , TestSpec "animation-bezier" False runAnimationBezierTest-  , TestSpec "animation-spring-retarget" False runAnimationSpringRetargetTest-  , TestSpec "animation-spring-dt" False runAnimationSpringDtTest-  , TestSpec-      "composite-animation-isolation"-      False-      runCompositeAnimationIsolationTest-  , TestSpec "button-hover-anim" False runButtonHoverAnimTest-  , TestSpec "spinner" False runSpinnerTest-  -- Keyboard-  , TestSpec "keyboard-disabled" False runKeyboardDisabledTest-  , TestSpec "disabled-pointer" False runDisabledPointerTest-  , TestSpec "disabled-focus-order" False runDisabledFocusOrderTest-  , TestSpec "disabled-look" False runDisabledLookTest-  , TestSpec "styled-paint" False runStyledPaintTest-  , TestSpec "styled-nesting" False runStyledNestingTest-  , TestSpec "styled-damage" False runStyledDamageTest-  , TestSpec "text-undo" False runTextUndoTest-  , TestSpec "text-area-width-tracking" False runTextAreaWidthTrackingTest-  , TestSpec "keyboard-modal-eligibility" False runKeyboardModalEligibilityTest-  , TestSpec "keyboard-focus-ring" False runKeyboardFocusRingTest-  , TestSpec "keyboard-button" False runKeyboardButtonTest-  , TestSpec "keyboard-checkbox" False runKeyboardCheckboxTest-  , TestSpec "keyboard-slider" True runKeyboardSliderTest-  , TestSpec "keyboard-radio" False runKeyboardRadioTest-  , TestSpec "keyboard-toggle" False runKeyboardToggleTest-  , TestSpec "keyboard-tab-header" False runKeyboardTabHeaderTest-  -- Controls-  , TestSpec "checkbox-initial" False runCheckboxInitialTest-  , TestSpec "slider-cursor" True runSliderCursorTest-  , TestSpec "slider-fill-width" True runSliderFillWidthTest-  , TestSpec "search-field-clear" False runSearchFieldClearTest-  , TestSpec "search-field-debounce" False runSearchFieldDebounceTest-  , TestSpec "select-drag-to-select" False runSelectDragToSelectTest-  , TestSpec "select-keyboard" False runSelectKeyboardTest-  , TestSpec "select-change-once" False runSelectChangeOnceTest-  , TestSpec "select-close-keeps-focus" False runSelectCloseKeepsFocusTest-  , TestSpec "select-overlay-damage" False runSelectOverlayDamageTest-  , TestSpec "tree-select" False runTreeSelectTest-  , TestSpec "tree-keyboard" False runTreeKeyboardTest-  , TestSpec "combo-filter" False runComboFilterTest-  , TestSpec "combo-keyboard-pick" False runComboKeyboardPickTest-  , TestSpec "combo-mouse-pick" False runComboMousePickTest-  , TestSpec "combo-blur-commit" False runComboBlurCommitTest-  , TestSpec "combo-escape-revert" False runComboEscapeRevertTest-  , TestSpec "combo-hover-highlight" False runComboHoverHighlightTest-  , TestSpec "combo-scrollbar-drag" False runComboScrollbarDragTest-  , TestSpec "combo-wheel-scroll" False runComboWheelScrollTest-  , TestSpec "color-picker-commit" True runColorPickerCommitTest-  , TestSpec "color-picker-rgba" True runColorPickerRgbaTest-  , TestSpec "color-picker-edit" True runColorPickerEditTest-  , TestSpec "color-picker-change-once" True runColorPickerChangeOnceTest-  , TestSpec "color-picker-bar-keys" True runColorPickerBarKeysTest-  , TestSpec "color-picker-drag-after-field" True runColorPickerDragAfterFieldTest-  , TestSpec "controls-tab-height" True runControlsTabHeightTest-  , TestSpec "bounded-radio-offset" True runBoundedRadioTest-  -- Text input and text area-  , TestSpec "text-input-cursor" False runTextInputCursorTest-  , TestSpec "text-input-batch" False runTextInputBatchTest-  , TestSpec "text-input-selection" False runTextInputSelectionTest-  , TestSpec "text-input-mouse-selection" False runTextInputMouseSelectionTest-  , TestSpec "text-input-click-select" False runTextInputClickSelectTest-  , TestSpec "text-input-word-keys" False runTextInputWordKeysTest-  , TestSpec-      "text-input-cut-clears-selection"-      False-      runTextInputCutClearsSelectionTest-  , TestSpec "text-input-clipboard" False runTextInputClipboardTest-  , TestSpec "text-input-password" False runTextInputPasswordTest-  , TestSpec "numeric-input" False runNumericInputTest-  , TestSpec "numeric-input-hex" False runNumericInputHexTest-  , TestSpec "text-input-menu" False runTextInputMenuTest-  , TestSpec "text-input-ff-caret" False runTextInputFfCaretTest-  , TestSpec "text-input-focus-sdl" True runTextInputFocusSdlTest-  , TestSpec "text-input-scroll" True runTextInputScrollTest-  , TestSpec "text-input-dirty" False runTextInputDirtyTest-  , TestSpec-      "text-area-cut-clears-selection"-      False-      runTextAreaCutClearsSelectionTest-  , TestSpec "text-area-scroll-wheel" True runTextAreaScrollWheelTest-  , TestSpec "text-area-zoom-scroll" True runTextAreaZoomScrollTest-  , TestSpec "text-area-remount-scroll" True runTextAreaRemountScrollTest-  , TestSpec "text-area-menu-pulse" True runTextAreaMenuPulseTest-  , TestSpec "text-command-focus" False runTextCommandFocusTest-  , TestSpec "text-area-scroll-drag" True runTextAreaScrollDragTest-  , TestSpec "text-area-cursor-on-scrollbar" True runTextAreaCursorOnScrollBarTest-  , TestSpec "text-area-hscroll-wheel" True runTextAreaHScrollWheelTest-  , TestSpec "text-area-hscroll-drag" True runTextAreaHScrollDragTest-  , TestSpec "text-area-2d-scroll" True runTextArea2DScrollTest-  , TestSpec-      "text-area-scroll-cursor-leaves-viewport"-      True-      runTextAreaScrollCursorLeavesViewportTest-  -- Scrolling-  , TestSpec "scroll-thumb-cursor" False runScrollThumbCursorTest-  , TestSpec "scroll-bar-gutter" True runScrollBarGutterTest-  , TestSpec "window-scroll-gutter" True runWindowScrollGutterTest-  , TestSpec "scroll-damage" False runScrollDamageTest-  , TestSpec "scroll-top-clip" True runScrollTopClipTest-  , TestSpec "nested-scroll" False runNestedScrollTest-  , TestSpec "nested-scroll-focus" False runNestedScrollFocusTest-  , TestSpec "scroll-hover-clip" False runScrollHoverClipTest-  , TestSpec "scroll-button-click" False runScrollButtonClickTest-  , TestSpec "scroll-scrolled-out" False runScrolledOutImmunityTest-  , TestSpec "scroll-lockstep-probe" False runScrollLockstepProbeTest-  , TestSpec "scroll-2d-grow-min-width" False runScroll2DGrowMinWidthTest-  , TestSpec "page-scroll-backdrop-coverage" False runPageScrollBackdropCoverageTest-  , TestSpec "scroll-2d-pad-fill-overflow" True run2DPadFillOverflowTest-  , TestSpec "scroll-2d-pad-overflow-scrolls" True run2DPadOverflowScrollsTest-  , TestSpec "scroll-step" True runScrollStepTest-  , TestSpec "scroll-smooth" True runScrollSmoothTest-  , TestSpec "scroll-metrics" True runScrollMetricsTest-  , TestSpec "scroll-into-view" True runScrollIntoViewTest-  , TestSpec "scroll-glide-clamp" True runScrollGlideClampTest-  -- Tables-  , TestSpec "table-sort" False runTableSortTest-  , TestSpec "table-reorder" True runTableReorderTest-  , TestSpec "table-scroll-reveal" True runTableScrollRevealTest-  , TestSpec "table-shared-scroll-metrics" True runTableSharedScrollMetricsTest-  , TestSpec "page-wheel-above-table" True runPageWheelAboveTableTest-  , TestSpec "table-wrap-row-stretch" True runTableWrapRowStretchTest-  , TestSpec "table-first-col" False runTableFirstColWidthTest-  , TestSpec "table-fill-width" False runTableFillWidthTest-  , TestSpec "table-cell-pad" True runTableCellPadTest-  , TestSpec "table-resize-overflow" True runTableResizeOverflowTest-  , TestSpec "table-col-resize-body" False runTableColResizeDemoReproTest-  , TestSpec "table-hbar-reach" True runTableHBarReachTest-  -- Tabs-  , TestSpec "tabs-laziness" False runTabsLazinessTest-  , TestSpec "tabs-emit" False runTabsEmitTest-  , TestSpec "tabs-closable" False runTabsClosableTest-  , TestSpec "tabs-disabled" True runTabsDisabledTest-  , TestSpec "tabs-scroll" False runTabsScrollTest-  , TestSpec "tabs-state-persistence" False runTabsStatePersistenceTest-  , TestSpec "tabs-damage" False runTabsDamageTest-  , TestSpec "tab-response-forwarding" False runTabResponseForwardingTest-  -- Modals, windows and panes-  , TestSpec "modal-overlay" False runModalOverlayTest-  , TestSpec "modal-fits-text" False runModalFitsTextTest-  , TestSpec "modal-no-phantom-scroll" False runModalNoPhantomScrollTest-  , TestSpec "modal-close-damage" False runModalCloseDamageTest-  , TestSpec "modal-fractional-scale-no-scroll" False runModalFractionalScaleNoScrollTest-  , TestSpec "modal-fill-label-fits" False runModalFillLabelFitsTest-  , TestSpec "window-overlay" False runWindowOverlayTest-  , TestSpec "overlay-sibling-state" False runOverlaySiblingStateTest-  , TestSpec "overlay-click-through" False runOverlayClickThroughTest-  , TestSpec "overlay-panel-live" False runOverlayPanelLiveTest-  , TestSpec "window-drag" False runWindowDragTest-  , TestSpec "window-close-damage" False runWindowCloseDamageTest-  , TestSpec "page-window-scroll" False runPageWindowScrollTest-  , TestSpec "window-scroll-only-damage" False runWindowScrollOnlyDamageTest-  , TestSpec "window-content-churn" False runWindowContentChurnTest-  , TestSpec "scrolled-debug-toggle" False runScrolledDebugToggleTest-  , TestSpec "window-resize" False runWindowResizeTest-  , TestSpec "window-resize-halo-hit" False runWindowResizeHaloHitTest-  , TestSpec "heading-mono-truncate" False runHeadingMonoTruncateTest-  , TestSpec "pane-grid-mixed-drag" False runPaneGridMixedDragTest-  , TestSpec "pane-grid-clipped-control" False runPaneGridClippedControlTest-  -- Context menus and tooltips-  , TestSpec "context-menu-open" False runContextMenuOpenTest-  , TestSpec "context-menu-scroll-pos" False runContextMenuScrollPosTest-  , TestSpec "context-menu-disabled-row" False runContextMenuDisabledRowTest-  , TestSpec "release-elsewhere" False runReleaseElsewhereTest-  , TestSpec "right-release-elsewhere" False runRightReleaseElsewhereTest-  , TestSpec "release-returns" False runReleaseReturnsTest-  , TestSpec "overlap-press" False runOverlapPressTest-  , TestSpec "tooltip-hover" False runTooltipHoverTest-  , TestSpec "tooltip-id-stable" False runTooltipIdStableTest-  , TestSpec "tooltip-scroll-pos" False runTooltipScrollPosTest-  -- Custom widgets-  , TestSpec "custom-widget-measure" False runCustomWidgetMeasureTest-  , TestSpec "custom-widget-cursor" False runCustomWidgetCursorTest-  , TestSpec "custom-widget-interaction" False runCustomWidgetInteractionTest-  , TestSpec "custom-widget-queued-click" False runCustomWidgetQueuedClickTest-  , TestSpec "custom-widget-content-damage" False runCustomWidgetContentDamageTest-  , TestSpec "custom-widget-content-key" False runCustomWidgetContentKeyTest-  , TestSpec "custom-widget-knob" False runReferenceKnobTest-  , TestSpec "drop-target" False runDropTargetTest-  ]
+ test/integration/Spec.hs view
@@ -0,0 +1,191 @@+{-# OPTIONS_GHC -O0 #-}+-- | What every integration test module imports: the library, the test+-- harness and assertions, and the shape of a test with its two helpers.+module Spec+  ( Spec+  , spec+  , pixelSpec+  , simSpec+  , pixelSimSpec+  , varSimSpec+  , propSpec+  , everyControl+  , arenaRects+  , nodeLayout+  , sameAsFreshSolve+  , fillsIn+  , buttonValues+  , widgetValue+  , assertPaintedLines+  , withMonospaceFonts+  , module Control.Monad+  , module Data.IORef+  , module NanoUI+  , module NanoUI.Backend+  , module NanoUI.Chrome+  , module NanoUI.Shader.Raw+  , module NanoUI.Testing+  , module NanoUI.Testing.Assert+  , module NanoUI.Testing.Harness+  , module NanoUI.Themes+  , module NanoUI.Widgets.Custom+  , module NanoUI.Widgets.PaneGrid+  , module NanoUI.Widgets.TextDocument+  , anyButtonPressed+  , anyButtonReleased+  , nextId+  , module TestSupport+  ) where++import Control.Monad+import Data.IORef+import Data.Text qualified as T+import GHC.Stack (HasCallStack, withFrozenCallStack)+import NanoUI+import NanoUI.Backend+import NanoUI.Chrome+import NanoUI.Input (anyButtonPressed, anyButtonReleased)+import NanoUI.Monad (nextId)+import NanoUI.Shader.Raw+import NanoUI.Testing+import NanoUI.Testing.Assert+import NanoUI.Testing.Harness+import NanoUI.Themes+import NanoUI.Widgets.Custom+import NanoUI.Widgets.PaneGrid+import NanoUI.Widgets.TextDocument+import TestSupport+import NanoUI.Testing.Sim (Sim, runSim)+import Test.QuickCheck (Args (..), Testable, isSuccess, quickCheckWithResult, stdArgs)+import Test.QuickCheck qualified as QC+import Test.QuickCheck.Random (mkQCGen)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Internal.Layout.Arena+  ( arenaCount+  , getNodeRect+  , getNodeType+  , getNodeValue+  , getScrollContentW+  , isScrollNode+  , lookupNodeByWidgetId+  )++-- | A test's name, the context it runs on, and the test, which bumps the+-- failure counter for each failed check.+type Spec = (String, IO Context, Context -> IORef Int -> IO ())++-- | A test on a headless context, and one on a pixel-snapped context.+spec, pixelSpec :: String -> (Context -> IORef Int -> IO ()) -> Spec+spec name run = (name, newContext, run)+pixelSpec name run = (name, newPixelContext, run)++-- | A 'NanoUI.Testing.Sim' script against @view@ in a @w@ x @h@ window, on a+-- headless or a pixel-snapped context.+simSpec, pixelSimSpec :: String -> Float -> Float -> NanoUI a -> Sim a () -> Spec+simSpec name w h view script = spec name (\ctx failed -> runSim ctx failed (withInput w h) view script)+pixelSimSpec name w h view script = pixelSpec name (\ctx failed -> runSim ctx failed (withInput w h) view script)++-- | 'simSpec' on a 'Var' holding @initial@, which the view and the script+-- share.+varSimSpec :: String -> Float -> Float -> v -> (Var v -> NanoUI a) -> (Var v -> Sim a ()) -> Spec+varSimSpec name w h initial view script =+  spec name (\ctx failed -> newVar initial >>= \v -> runSim ctx failed (withInput w h) (view v) (script v))++-- | A QuickCheck property checked on @n@ cases generated from @seed@, so a+-- run is the same every time. A failure prints QuickCheck's shrunk+-- counterexample and counts once.+propSpec :: Testable p => String -> Int -> Int -> p -> Spec+propSpec name seed n p = spec name $ \_ failed -> do+  r <- quickCheckWithResult stdArgs {replay = Just (mkQCGen seed, 0), maxSuccess = n, chatty = False} p+  unless (isSuccess r) $ putStrLn (QC.output r) >> modifyIORef' failed (+ 1)++-- | One of each control a user can focus and work, with its value shown, for+-- the properties every control has: focus from code, no keys while+-- disabled, no pointer through an overlay.+everyControl :: [(String, NanoUI (Response, String))]+everyControl =+  [ ("button", (,"") <$> button' "Go")+  , ("checkbox", shown (withValue False (checkbox' "Check")))+  , ("toggle", shown (withValue False (toggleSwitchWith' id)))+  , ("slider", shown (withValue 50 (slider' 0 100)))+  , ("knob", shown (withValue 50 (knobWith' id 36 0 100)))+  , ("radio", shown (withValue 0 (radio' ["one", "two", "three"])))+  , ("select", shown (withValue 0 (selectWith' fillW ["a", "b", "c"])))+  , ("text input", shown (withValue "some text" textInput'))+  , ("search input", shown (withValue "some text" (searchInput' "Search")))+  , ("numeric input", shown (withValue 5 numericInput'))+  , ("combo box", shown (withValue "a" (comboBox' "Choose" ["a", "b"])))+  , ("text area", shown (withValue (T.unlines (replicate 30 "a line")) (textAreaWith' (fixedH 120))))+  , ("color picker", shown (withValue (colorRGBA 200 40 40 255) colorPicker'))+  ]+  where+    shown :: Show v => NanoUI (Response, v) -> NanoUI (Response, String)+    shown = fmap (fmap show)++-- | @base@ with a monospace base font of @baseCell@ px cells, and+-- @sizedCell@ px cells for text given a font size of its own, so a test can+-- tell which font measured or drew something.+withMonospaceFonts :: Float -> Float -> Context -> Context+withMonospaceFonts baseCell sizedCell base =+  withFontResolver+    (withFontMetrics base (monospaceMetrics baseCell))+    (\_ _ _ _ -> pure (monospaceMetrics sizedCell, False))+    (\_ _ _ _ txt -> pure (sizedCell * fromIntegral (T.length txt), sizedCell))++-- | The colours of the quads that overlap @r@.+fillsIn :: Rect -> [(Rect, Color)] -> [Color]+fillsIn r quads = [c | (q, c) <- quads, rectIntersect q r /= Nothing]++-- | Every node's laid-out rect, in arena order.+arenaRects :: Context -> IO [Rect]+arenaRects ctx = do+  n <- arenaCount (ctxNodeArena ctx)+  mapM (getNodeRect (ctxNodeArena ctx)) [0 .. n - 1]++-- | Every node's rect and each scroll container's content extents.+nodeLayout :: Context -> IO [(Rect, Maybe (Float, Float))]+nodeLayout ctx = do+  let na = ctxNodeArena ctx+      scrollOf i = getNodeType na i >>= \nt ->+        if isScrollNode nt+          then Just <$> ((,) <$> getNodeValue na i <*> getScrollContentW na i)+          else pure Nothing+  n <- arenaCount na+  forM [0 .. n - 1] $ \i -> (,) <$> getNodeRect na i <*> scrollOf i++-- | Run a frame on @ctx@, which reuses what its last solve placed, and on+-- @fresh@ with its layout cache dropped, so it solves from scratch, and+-- check the two lay out the same ('nodeLayout'). The result on @ctx@.+sameAsFreshSolve :: HasCallStack => IORef Int -> Context -> Context -> Input -> NanoUI a -> IO a+sameAsFreshSolve failed fresh ctx inp ui = do+  (a, _, _) <- runFrame ctx inp ui+  writeIORef (ctxLayoutCache fresh) Nothing+  _ <- runFrame fresh inp ui+  expected <- nodeLayout fresh+  withFrozenCallStack (assertEq failed expected) =<< nodeLayout ctx+  pure a++-- | The value of every button in arena order: which of a group's options,+-- rows or headers is marked selected, in a view of that group alone.+buttonValues :: Context -> IO [Float]+buttonValues ctx = do+  let na = ctxNodeArena ctx+  n <- arenaCount na+  fmap concat . forM [0 .. n - 1] $ \i -> do+    nt <- getNodeType na i+    if nt == NodeButton then pure <$> getNodeValue na i else pure []++-- | The value of widget @wid@'s node this frame, such as whether a checkbox+-- is drawn checked.+widgetValue :: Context -> WidgetId -> IO (Maybe Float)+widgetValue ctx wid = lookupNodeByWidgetId (ctxNodeArena ctx) wid >>= traverse (getNodeValue (ctxNodeArena ctx))++-- | Check that paint wrapped a label's text where the solve placed it: the+-- frame's text spans other than @others@ are as many lines as the label's+-- rect @r@ is tall, none wider than it. The headless font's glyphs are as+-- wide as its 12 px line is tall.+assertPaintedLines :: IORef Int -> Context -> [T.Text] -> Rect -> IO ()+assertPaintedLines failed ctx others r = do+  lns <- (\spans -> [t | (_, t, _, _, _) <- spans, t `notElem` others]) <$> collectTextSpans ctx+  assertEq failed (rectH r) (12 * fromIntegral (length lns))+  forM_ lns $ \t -> assert failed (12 * fromIntegral (T.length t) <= rectW r)
+ test/integration/TestSupport.hs view
@@ -0,0 +1,106 @@+-- | Regression helpers specific to nano-ui's own integration test suite.+module TestSupport+  ( assertScrollGutterPad+  , assertWheelTitlePinned+  , checkLabelAlignEndInk+  , checkIdleFullDamage+  , windowTitleGrab+  , scrollArea+  , scrollArea2D+  , scrollAreaConfigured+  ) where++import Control.Monad (forM_, when)+import Data.IORef (IORef)+import Data.Maybe (listToMaybe)+import Data.Text qualified as T+import GHC.Stack (HasCallStack)+import NanoUI+import NanoUI.Backend+import NanoUI.Testing+import NanoUI.Testing.Assert (assert, assertEq, assertJustM, assertLt, bump)+import NanoUI.Testing.Harness (spanYOf)++-- | Check that a child's right edge ends at the scroller's content edge,+-- given gutter width and end padding in logical pixels.+assertScrollGutterPad ::+  HasCallStack+  => IORef Int+  -> Context+  -> WidgetId+  -> Response+  -> Float+  -> Float+  -> IO ()+assertScrollGutterPad failed ctx sid child gutter endPad =+  assertJustM failed (getPrevRect ctx sid) $ \(Rect sx _ sw _) -> do+    let Rect cx _ cw _ = respRect child+        contentRight = sx + sw - endPad - gutter+    assert failed (cx + cw >= contentRight - 0.5)+    assert failed (cx + cw <= contentRight + 0.01)++-- | Scroll an overlay by one wheel step and require its title to stay fixed+-- while its first body line moves upward (if it is still shown).+assertWheelTitlePinned ::+  HasCallStack+  => IORef Int+  -> Context+  -> Input+  -> NanoUI a+  -> T.Text+  -> T.Text+  -> V2+  -> IO ()+assertWheelTitlePinned failed ctx inp0 ui title line1 wheelAt = do+  let wheel = inp0 {inputMousePos = wheelAt, inputScroll = V2 0 1}+  spans0 <- collectOverlayTextSpans ctx inp0+  _ <- runFrame ctx wheel ui+  spans1 <- collectOverlayTextSpans ctx wheel+  case (spanYOf title spans0, spanYOf title spans1, spanYOf line1 spans0) of+    (y0 : _, y1 : _, b0 : _) -> do+      assertEq failed y1 y0+      forM_ (listToMaybe (spanYOf line1 spans1)) $ \b1 -> assertLt failed b1 b0+    _ -> assert failed False++-- | Require the transition to idle input to need a frame, then require that+-- frame's damage to cover the whole window.+checkIdleFullDamage ::+  HasCallStack => IORef Int -> Context -> Input -> Input -> NanoUI a -> IO ()+checkIdleFullDamage failed ctx inpAfter inpIdle ui = do+  need <- needsRedraw ctx inpAfter inpIdle+  assert failed need+  _ <- runFrame ctx inpIdle ui+  dmg <- takeDamage ctx+  assert failed (dmg == DamageFull)++-- | Check that right-aligned labels share an ink edge despite different glyph advances.+checkLabelAlignEndInk :: IORef Int -> IO ()+checkLabelAlignEndInk failed =+  forM_ ["10", "1i", "1."] $ \txt -> do+    let (tx, _) = alignedTextPen AlignEnd 0 boxW 0 fm txt+    when (abs (tx + textInkEnd fm txt - boxW) > 0.01) $ bump failed+  where+    boxW = 100+    glyph xoff gw = Just (GlyphQuad xoff 0 gw 10 0 0 1 1)+    fm =+      (monospaceMetrics 10)+        { fmAdvance = \c -> if c == 'i' || c == '.' || c == ' ' then 4 else 10+        , fmGlyph = \c -> case c of+            'i' -> glyph 0.5 3+            '.' -> glyph 1 1+            _ -> glyph 1 8+        }++-- | Point inside the standard floating-window title bar, away from its close button.+windowTitleGrab :: Rect -> V2+windowTitleGrab (Rect x0 y0 _ _) = V2 (x0 + 24) (y0 + padT windowPad + 19.5)++-- | Adapter for integration tests written against the pre-0.2 @(WidgetId, a)@ tuple.+scrollArea :: LayoutModifier -> NanoUI a -> NanoUI (WidgetId, a)+scrollArea f body = (\(a, r) -> (respId r, a)) <$> scrollWith' f body++scrollArea2D :: LayoutModifier -> NanoUI a -> NanoUI (WidgetId, a)+scrollArea2D f body = (\(a, r) -> (respId r, a)) <$> scroll2DWith' f body++scrollAreaConfigured :: ScrollConfig -> LayoutModifier -> NanoUI a -> NanoUI (WidgetId, a)+scrollAreaConfigured cfg f body = (\(a, r) -> (respId r, a)) <$> scrollConfigured' cfg f body
+ test/style-bits/StyleBitsSpec.hs view
@@ -0,0 +1,43 @@+-- | Checks the style-index layout in "NanoUI.Internal.StyleBits": within each+-- node type's fields no two share a bit, every field fits in 64 bits, and a+-- button's label font has room for a whole text font packing.+module Main (main) where++import Control.Monad (unless)+import Data.Bits ((.&.))+import NanoUI.Internal.StyleBits+import System.Exit (exitFailure)++main :: IO ()+main = do+  let problems = concatMap layoutProblems styleLayouts <> labelFontProblems <> flagProblems+  mapM_ putStrLn problems+  unless (null problems) exitFailure+  putStrLn ("style-bits-spec: " <> show (length styleLayouts) <> " layouts checked")++layoutProblems :: (String, [(String, BitField)]) -> [String]+layoutProblems (node, fields) =+  [ node <> ": " <> name <> " " <> show f <> " does not fit in 64 bits"+  | (name, f) <- fields+  , bfShift f < 0 || bfWidth f < 1 || fieldEnd f > 64+  ]+    <> [ node <> ": " <> a <> " and " <> b <> " share bits"+       | ((a, fa), i) <- zip fields [0 :: Int ..]+       , ((b, fb), j) <- zip fields [0 ..]+       , i < j+       , fieldMask fa .&. fieldMask fb /= 0+       ]++labelFontProblems :: [String]+labelFontProblems =+  [ "labelFont is " <> show (bfWidth labelFont) <> " bits wide, too narrow for " <> name+  | (name, f) <- textFontFields+  , fieldEnd f > bfWidth labelFont+  ]++flagProblems :: [String]+flagProblems =+  [ name <> " is a flag but " <> show (bfWidth f) <> " bits wide"+  | (name, f) <- [("inputSearch", inputSearch), ("inputSelectable", inputSelectable), ("inputPassword", inputPassword), ("inputNumeric", inputNumeric)]+  , bfWidth f /= 1+  ]