nano-ui-0.2.0.0: examples/Profile.hs
module Main (main) where
import Control.Exception (evaluate)
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, 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)
-- Enough frames for a stable time profile without an interactive window.
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 =
columnWith
(grow . gap 8)
( do
replicateM_ 12 $
gridWith 8 (gap 8) $
replicateM_ 8 (void (button "OK"))
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) = runCanvasFor cdc $ do
let side = 32 :: Int
cw = w / fromIntegral side
ch = h / fromIntegral side
accent = themeAccent (cdcTheme cdc)
forM_ [0 .. side - 1] $ \i ->
forM_ [0 .. side - 1] $ \j -> do
let fx = x + fromIntegral i * cw
fy = y + fromIntegral j * ch
tint = fromIntegral ((i * side + j) `mod` 255) / 255
drawRect (Rect fx fy (cw - 1) (ch - 1)) (lerpColor accent (colorRGBA 255 255 255 255) tint)
-- | 'canvasOps', counting the frames that actually build the ops. The count
-- says which path a scene took: one build for a keyed widget the frames reuse,
-- one per frame for an unkeyed one.
{-# NOINLINE countedCanvasOps #-}
countedCanvasOps :: CustomDrawContext -> Rect -> SmallArray DrawOp
countedCanvasOps cdc rect = unsafePerformIO $ do
modifyIORef' buildCount (+ 1)
pure (canvasOps cdc rect)
{-# NOINLINE buildCount #-}
buildCount :: IORef Int
buildCount = unsafePerformIO (newIORef 0)
-- | An op-heavy custom widget. Pass 0 for the unkeyed path, which rebuilds and
-- compares its ops every frame, or a content key, which reuses them while it
-- is unchanged.
canvasScene :: Int -> NanoUI ()
canvasScene key =
void $
customWidget
defaultCustomWidgetSpec
{ 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 :: Var TextDocument -> NanoUI ()
textAreaScene doc = column (textAreaDocumentWith grow doc)
-- | '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 :: 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>"
longDocument :: Text
longDocument = T.intercalate "\n" [T.pack ("line " ++ show i ++ " of a long document") | i <- [1 .. 100000 :: Int]]
main :: IO ()
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
-- and a large size; a varying size keeps each raster from being shared.
let parsed = mapM parseSvg [clockIcon, starIcon]
case parsed of
Left err -> fail err
Right docs ->
forM_ [1 .. 500 :: Int] $ \i ->
forM_ docs $ \doc -> do
let white = colorRGBA 255 255 255 255
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
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
, 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
putStrLn ("profiled " ++ show iterations ++ " " ++ name ++ " frames, op builds: " ++ show builds)