nano-ui-0.2.0.0: test/integration/Cases/Shortcut.hs
{-# 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]