diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7c04477d..9bf7971c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -94,6 +94,7 @@ jobs: nim r -d:silkyTesting -d:nimTypeNames tests/test_inputs.nim nim r -d:silkyTesting tests/test_buttons.nim nim r -d:silkyTesting tests/test_focus.nim + nim r -d:silkyTesting tests/test_text_menus.nim nim r -d:silkyTesting tests/test_cursor_scroll.nim nim r -d:silkyTesting tests/test_input_hooks.nim nim r -d:silkyTesting tests/test_paste_hooks.nim @@ -101,9 +102,11 @@ jobs: nim r -d:silkyTesting tests/test_first_touch.nim nim r -d:silkyTesting tests/test_touch_scroll.nim nim r -d:silkyTesting tests/test_scroll_momentum.nim + nim r -d:silkyTesting tests/test_scroll_indicators.nim nim r -d:silkyTesting tests/test_rendering.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim + nim r tests/test_atlas_paths.nim nim r tests/test_retina_atlas.nim nim r tests/test_shader_codegen.nim nim r ${{ matrix.build_flags }} tests/test_density.nim diff --git a/nimby.lock b/nimby.lock index 2f36585b..a0839aca 100644 --- a/nimby.lock +++ b/nimby.lock @@ -8,7 +8,7 @@ nimsimd 1.3.2 https://github.com/treeform/nimsimd 3f6b2668ffb0867d0bf786a658b817 bumpy 1.1.3 https://github.com/treeform/bumpy dc9a3d6d15680ec7f603959d65ba8ee4f1ddbc72 crunchy 0.1.11 https://github.com/treeform/crunchy 98eb6526982bb8aae8eec6e8781f4539fa19e049 bitty 0.1.4 https://github.com/treeform/bitty/ c40e81277c04befa37234cba5052f58648bef895 -windy 0.5.0 https://github.com/treeform/windy bf6b93d872de6826a69b34752c6d766e46204530 +windy 0.5.0 https://github.com/treeform/windy 021664d11beeeab3999f375a6881d145a630fd8a opengl 1.2.9 https://github.com/nim-lang/opengl 8e2e098f82dc5eefd874488c37b5830233cd18f4 urlly 1.1.1 https://github.com/treeform/urlly 99784779f05649df25fd9c33003d8ef6de027345 ws 0.5.0 https://github.com/treeform/ws cbb8f763b436669392d10baec2a45778395395cc diff --git a/src/silky/atlas.nim b/src/silky/atlas.nim index 8389e8f0..89e025b3 100644 --- a/src/silky/atlas.nim +++ b/src/silky/atlas.nim @@ -383,12 +383,13 @@ proc addDir*( pixelScale: int = 1 ) = ## Add all images in the given directory to the atlas. + let prefix = removePrefix.replace("\\", "/") for file in walkDir(path): if file.path.endsWith(".png"): let image = readImage(file.path) var key = file.path.replace("\\", "/") - if removePrefix.len > 0: - key.removePrefix(removePrefix) + if prefix.len > 0: + key.removePrefix(prefix) key.removeSuffix(".png") if not builder.addImage(key, image, pixelScale): raise newException( diff --git a/src/silky/interactions.nim b/src/silky/interactions.nim index 2cd9095c..c2701168 100644 --- a/src/silky/interactions.nim +++ b/src/silky/interactions.nim @@ -13,6 +13,7 @@ type warmLayer*: int = -1 hotId*: int = -1 previous, current: seq[HitRegion] + resolvedMouse: Vec2 invalidated: bool proc resetInteractions*(interactor: var Interactor) = @@ -44,9 +45,10 @@ proc mouseHover*( layer: int, widgetRect: Rect ): bool = - ## Resolves a new pointer position before its first press is consumed. - if interactor.currentId == -1: - # Applications may adjust the pointer for safe areas after beginUi. + ## Resolves pointer changes without renumbering this frame's hit regions. + if interactor.currentId == -1 or mousePos != interactor.resolvedMouse: + # Applications may mask background input before drawing a popup. + interactor.resolvedMouse = mousePos interactor.hotId = -1 var hotLayer = -1 for id, region in interactor.previous: diff --git a/src/silky/internal/inputs.nim b/src/silky/internal/inputs.nim index 4f248ec4..0e1074e1 100644 --- a/src/silky/internal/inputs.nim +++ b/src/silky/internal/inputs.nim @@ -1,6 +1,6 @@ import std/unicode, - vmath, + vmath, bumpy, silky/common when defined(silkyTesting): @@ -42,6 +42,13 @@ type releaseCallback: proc(button: Button) pendingText: TextInputState placementSerial, placementLayer, placementVertex: int + when defined(ios) or defined(silkyTesting): + menuPending, menuVisible: bool + menuBounds: Rect + menuActions: set[TextEditAction] + menuId: string + menuEpoch, menuGeneration: uint64 + menuSerial, menuLayer, menuVertex: int proc identity[T](callback: T): CallbackIdentity = ## Identifies a callback without retaining its closure environment. @@ -72,8 +79,18 @@ else: else: buttons +proc dismissInputMenu(inputs: TextInputs, window: Window) = + ## Invalidates actions belonging to a menu that no longer owns focus. + when defined(ios) or defined(silkyTesting): + inc inputs.menuGeneration + inputs.menuPending = false + if inputs.menuVisible: + window.dismissTextEditMenu() + inputs.menuVisible = false + proc stopInput*(inputs: TextInputs, window: Window) = ## Ends text capture and discards input for the previous field. + inputs.dismissInputMenu(window) if inputs.active: inc inputs.epoch inputs.active = false @@ -81,9 +98,9 @@ proc stopInput*(inputs: TextInputs, window: Window) = inputs.id.setLen(0) inputs.events.setLen(0) inputs.pendingText = TextInputState() - window.setTextInputState(TextInputState()) if window.runeInputEnabled: window.runeInputEnabled = false + window.setTextInputState(TextInputState()) proc modifiers(inputs: TextInputs, window: Window): InputEvent = ## Captures modifier state at the time of a callback. @@ -111,6 +128,7 @@ proc installPress(inputs: TextInputs, window: Window) = let previousPress = window.onButtonPress window.onButtonPress = proc(button: Button) = let window = cast[Window](windowPointer) + inputs.dismissInputMenu(window) if inputs.active and button >= Key0: var event = inputs.modifiers(window) event.kind = KeyDown @@ -254,6 +272,8 @@ proc beginInputFrame*(inputs: TextInputs, window: Window) = inputs.consumed = false inputs.pendingText = TextInputState() inputs.placementSerial = 0 + when defined(ios) or defined(silkyTesting): + inputs.menuPending = false proc textPlacementMark*(inputs: TextInputs): int = ## Marks the start of a deferred layout containing a focused editor. @@ -269,11 +289,32 @@ proc publishTextInput*( inputs.placementVertex = firstVertex inc inputs.placementSerial +proc publishTextMenu*( + inputs: TextInputs, id: string, bounds: Rect, + actions: set[TextEditAction], layer, firstVertex: int +) = + ## Defers a native menu until the owning widget's final placement is known. + when defined(ios) or defined(silkyTesting): + if inputs.active and inputs.id == id and actions != {}: + inc inputs.placementSerial + inputs.menuPending = true + inputs.menuId = id + inputs.menuEpoch = inputs.epoch + inputs.menuBounds = bounds + inputs.menuActions = actions + inputs.menuSerial = inputs.placementSerial + inputs.menuLayer = layer + inputs.menuVertex = firstVertex + proc translateTextInput*(inputs: TextInputs, first: int, offset: Vec2) = ## Moves an editor published inside a deferred layout span. if inputs != nil and inputs.placementSerial > first: inputs.pendingText.bounds.x += offset.x inputs.pendingText.bounds.y += offset.y + when defined(ios) or defined(silkyTesting): + if inputs != nil and inputs.menuPending and inputs.menuSerial > first: + inputs.menuBounds.x += offset.x + inputs.menuBounds.y += offset.y proc translateTextInputVertices*( inputs: TextInputs, layer, first: int, offset: Vec2 @@ -283,11 +324,23 @@ proc translateTextInputVertices*( inputs.placementLayer == layer and inputs.placementVertex >= first: inputs.pendingText.bounds.x += offset.x inputs.pendingText.bounds.y += offset.y + when defined(ios) or defined(silkyTesting): + if inputs != nil and inputs.menuPending and inputs.menuLayer == layer and + inputs.menuVertex >= first: + inputs.menuBounds.x += offset.x + inputs.menuBounds.y += offset.y proc moveTextInputBehind*( inputs: TextInputs, layer, spanStart, chromeStart, total: int ) = ## Preserves the editor's vertex position when parent chrome is reordered. + when defined(ios) or defined(silkyTesting): + if inputs != nil and inputs.menuPending and inputs.menuLayer == layer and + inputs.menuVertex >= spanStart and inputs.menuVertex < total: + if inputs.menuVertex < chromeStart: + inputs.menuVertex += total - chromeStart + else: + inputs.menuVertex -= chromeStart - spanStart if inputs == nil or inputs.placementSerial == 0: return if inputs.placementLayer != layer or @@ -310,6 +363,7 @@ proc submitInput*( inputs.stopInput(window) return if not inputs.active or inputs.id != id: + inputs.dismissInputMenu(window) inputs.events.setLen(0) inc inputs.epoch inputs.id = id @@ -332,6 +386,50 @@ proc takeInput*(inputs: TextInputs): seq[InputEvent] = inputs.consumed = true swap(result, inputs.events) +when defined(ios) or defined(silkyTesting): + proc showInputMenu(inputs: TextInputs, window: Window) = + ## Allocates a native action callback only when a menu is requested. + let + id = inputs.menuId + epoch = inputs.menuEpoch + actions = inputs.menuActions + generation = inputs.menuGeneration + 1 + inputs.menuGeneration = generation + inputs.menuVisible = window.showTextEditMenu( + inputs.menuBounds, actions, + proc(action: TextEditAction) = + ## Routes native actions through the current field's input hooks. + if not inputs.active or inputs.id != id or + inputs.epoch != epoch or inputs.menuGeneration != generation or + action notin actions: + return + inputs.menuVisible = false + inc inputs.menuGeneration + if action == PasteTextAction: + if not inputs.editable: + return + if inputs.onPaste != nil and inputs.onPaste(id): + if inputs.onEvent != nil: + inputs.onEvent() + return + if not inputs.active or inputs.id != id or + not inputs.editable or inputs.epoch != epoch: + return + let text = getClipboardString() + if text.len > 0: + inputs.addEvent(InputEvent(kind: TextCommit, text: text)) + else: + let button = + case action + of CopyTextAction: KeyC + of CutTextAction: KeyX + of SelectAllTextAction: KeyA + of PasteTextAction: KeyV + inputs.addEvent(InputEvent( + kind: KeyDown, button: button, control: true + )) + ) + proc endInputFrame*(inputs: TextInputs, window: Window) = ## Ends capture when the active field was not submitted this frame. if not inputs.submitted: @@ -340,3 +438,8 @@ proc endInputFrame*(inputs: TextInputs, window: Window) = window.setTextInputState(inputs.pendingText) else: window.setTextInputState(TextInputState()) + + when defined(ios) or defined(silkyTesting): + if inputs.menuPending and inputs.active and inputs.submitted and + inputs.id == inputs.menuId and inputs.epoch == inputs.menuEpoch: + inputs.showInputMenu(window) diff --git a/src/silky/internal/textpresses.nim b/src/silky/internal/textpresses.nim new file mode 100644 index 00000000..71d9d60e --- /dev/null +++ b/src/silky/internal/textpresses.nim @@ -0,0 +1,41 @@ +import vmath + +const + TextPressDelay* = 500.0 + TextPressSlop = 6.0'f + +type + TextPressResult* = enum + NoTextPress, WaitingTextPress, HeldTextPress, ReleasedTextPress + + TextPress* = object + active*: bool + preserve*: bool + position*: Vec2 + started*: float64 + +proc beginTextPress*(position: Vec2, nowMs: float64, preserve: bool): TextPress = + ## Records a stationary touch without discarding an existing selection. + TextPress(active: true, position: position, started: nowMs, preserve: preserve) + +proc updateTextPress*( + press: var TextPress, point: Vec2, down, released, cancelled: bool, + nowMs: float64 +): TextPressResult = + ## Recognizes a hold while rejecting pans and interrupted gestures. + if not press.active: + return NoTextPress + let distance = point - press.position + if cancelled or max(abs(distance.x), abs(distance.y)) >= TextPressSlop: + press.active = false + return NoTextPress + if released: + press.active = false + return ReleasedTextPress + if not down: + press.active = false + return NoTextPress + if nowMs - press.started >= TextPressDelay: + press.active = false + return HeldTextPress + WaitingTextPress diff --git a/src/silky/richtextboxes.nim b/src/silky/richtextboxes.nim index b15c5db0..65163efc 100644 --- a/src/silky/richtextboxes.nim +++ b/src/silky/richtextboxes.nim @@ -1,7 +1,7 @@ import std/[algorithm, tables, unicode, times], vmath, bumpy, chroma, - silky/atlas, silky/internal/inputs, silky/textboxes + silky/atlas, silky/internal/[inputs, textpresses], silky/textboxes when defined(silkyTesting): import silky/[semantics, testing, profiles] @@ -1280,6 +1280,7 @@ proc richTextBox*( if editor.focused and state.focusEpoch != inputs.focusEpoch: editor.focused = false editor.dragging = false + editor.touchPress = TextPress() editor.selector = editor.cursor if state.spans != spans: state.spans = spans @@ -1293,6 +1294,8 @@ proc richTextBox*( if not state.sameText(text): state.setText(text, preserveSelection = true) let + firstVertex = sk.vertexMark() + textLayer = sk.currentDrawLayer() padding = sk.theme.padding.float32 outerRect = rect(sk.at, vec2(boxWidth, boxHeight)) var innerRect = rect( @@ -1316,6 +1319,22 @@ proc richTextBox*( mouseInside = mouseVec.overlaps(outerRect) and mouseVec.overlaps(sk.clipRect) onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) + touchPointer = + when defined(ios) or defined(silkyTesting): + sk.touchScroll.touchInput + else: + false + localMouse = mouseVec - innerRect.xy + editor.scrollPos + var + openMenu = false + textHit = false + if touchPointer and mouseInside and not onScrollbar and + (sk.buttonPressed[MouseLeft] or editor.touchPress.active): + textHit = editor.glyphContains(localMouse) + for layout in state.blockLayouts: + if localMouse.overlaps(layout.imageBounds): + textHit = false + break if sk.touchScrolling: if editor.dragging: editor.selector = editor.cursor @@ -1327,31 +1346,51 @@ proc richTextBox*( if mouseInside and not onScrollbar: editor.focused = true let - localMouse = mouseVec - innerRect.xy + editor.scrollPos + preserve = touchPointer and editor.selectionContains(localMouse) now = epochTime() + if touchPointer and textHit: + editor.touchPress = beginTextPress( + mouseVec - window.mouseDelta.vec2 / sk.uiScale, + scrollMilliseconds(), preserve + ) if now - editor.lastClickTime < DoubleClickTime: inc editor.clickCount else: editor.clickCount = 1 editor.lastClickTime = now - case editor.clickCount - of 1: - state.mouseAction(localMouse, click = true, shift = shift) - editor.dragging = true - if not shift: - state.pressedSpan = state.spanAt(localMouse) - state.pressPosition = mouseVec - state.spanDragged = false - of 2: - state.selectWord(localMouse) - of 3: - state.selectParagraph(localMouse) - else: - editor.selectAll() + if not preserve: + case editor.clickCount + of 1: + state.mouseAction(localMouse, click = true, shift = shift) + editor.dragging = not touchPointer + if not shift: + state.pressedSpan = state.spanAt(localMouse) + state.pressPosition = mouseVec + state.spanDragged = false + of 2: + state.selectWord(localMouse) + of 3: + state.selectParagraph(localMouse) + else: + editor.selectAll() elif not mouseInside: editor.focused = false editor.dragging = false editor.selector = editor.cursor + case editor.touchMenu(sk, window, mouseInside and not onScrollbar and textHit) + of HeldTextPress: + if editor.cursor == editor.selector: + state.selectWord(localMouse) + editor.dragging = false + state.pressedSpan = -1 + state.spanDragged = true + openMenu = true + sk.resetInteractions() + of ReleasedTextPress: + if editor.touchPress.preserve: + state.mouseAction(localMouse) + else: + discard if state.pressedSpan >= 0: let distance = mouseVec - state.pressPosition if distance.x * distance.x + distance.y * distance.y > 9: @@ -1436,6 +1475,16 @@ proc richTextBox*( ) if not shift and window.scrollDelta.y != 0: editor.scrollBy(window.scrollDelta.y * TextBoxScrollSpeed, innerRect.h) + when defined(ios) or defined(silkyTesting): + if openMenu: + let anchor = rect( + (mouseVec - vec2(1, editor.lineHeight)) * sk.uiScale, + vec2(2, editor.lineHeight) * sk.uiScale + ) + inputs.publishTextMenu( + "rich-textbox:" & id, anchor, editor.textMenuActions(), + textLayer, firstVertex + ) sk.advance(vec2(boxWidth, boxHeight)) template richTextBox*( diff --git a/src/silky/scrolls.nim b/src/silky/scrolls.nim index 761dd0bf..dfdcff1b 100644 --- a/src/silky/scrolls.nim +++ b/src/silky/scrolls.nim @@ -10,8 +10,15 @@ const MinimumFlingSpeed = 50.0 ScrollStopSpeed = 5.0 MaximumFrameGap = 250.0 + ScrollIndicatorDelay* = 150.0 + ScrollIndicatorFade* = 250.0 type + ScrollIndicator* = object + ## Retains only user scrolling activity for one viewport's fading bars. + shown*: bool + lastActivity*: float64 + TouchBlocker = object bounds, clip: Rect layer: int @@ -30,6 +37,7 @@ type previousBlockers, currentBlockers: seq[TouchBlocker] start, last: Vec2 target: pointer + activityTarget: pointer axis: int offset: float32 coastPosition, coastVelocity, coastTime: float64 @@ -41,6 +49,41 @@ proc scrollMilliseconds*(): float64 {.raises: [].} = ## Reads monotonic time without quantizing high-refresh animation frames. getMonoTime().ticks.float64 / 1_000_000 +proc indicatorOpacity*( + indicator: var ScrollIndicator, scrolling: bool, + nowMs: float64 = scrollMilliseconds() +): float32 = + ## Shows scrolling immediately, then fades after a short release delay. + if scrolling: + indicator.shown = true + indicator.lastActivity = nowMs + if not indicator.shown: + return 0 + let elapsed = max(0.0, nowMs - indicator.lastActivity) + if elapsed >= ScrollIndicatorDelay + ScrollIndicatorFade: + indicator.shown = false + return 0 + (1.0 - max(0.0, elapsed - ScrollIndicatorDelay) / + ScrollIndicatorFade).float32 + +proc scrollbarOpacity*( + sk: auto, indicator: var ScrollIndicator, target: pointer, + scrolling = false, nowMs: float64 = scrollMilliseconds() +): float32 = + ## Schedules fading mobile bars while preserving always visible desktop bars. + let transient = + when defined(ios): true + elif defined(silkyTesting): sk.touchScroll.touchInput + else: false + if not transient: + return 1 + result = indicator.indicatorOpacity( + scrolling or sk.touchScroll.activityTarget == target, nowMs + ) + if result > 0: + let untilFade = ScrollIndicatorDelay - (nowMs - indicator.lastActivity) + sk.requestFrame(if untilFade > 0: max(1, int(ceil(untilFade))) else: 16) + proc momentumActive*(touch: TouchScroll): bool = ## Reports whether another animation frame is needed after finger release. touch.coasting @@ -94,6 +137,7 @@ proc beginTouchFrame*( ) = ## Resolves ownership before widgets draw or virtualize their contents. touch.suppress = false + touch.activityTarget = nil touch.touchInput = isTouch touch.tap = false if not isTouch or not focused or point.x < 0 or point.y < 0 or interrupted: @@ -146,6 +190,7 @@ proc beginTouchFrame*( var position = region.position position.setComponent(touch.axis, nextPosition.float32) region.apply(position) + touch.activityTarget = region.target touch.coastPosition = nextPosition touch.coastVelocity *= decay touch.coastTime = nowMs @@ -232,6 +277,7 @@ proc beginTouchFrame*( 0.0'f, maximum )) region.apply(position) + touch.activityTarget = region.target if released and not touch.scrollbar: let speed = -component(region.signs, touch.axis).float64 * component(velocity, touch.axis).float64 @@ -256,6 +302,7 @@ proc beginTouchFrame*( proc resetTouchScroll*(touch: var TouchScroll) = ## Invalidates scroll targets when the application replaces its scene. + touch.activityTarget = nil touch.cancelled = touch.pending or touch.dragging touch.pending = false touch.dragging = false @@ -265,10 +312,13 @@ proc resetTouchScroll*(touch: var TouchScroll) = touch.previousBlockers.setLen(0) touch.invalidated = true +proc touchTap*(sk: auto): bool = + ## Reports a completed tap without accepting a pan or cancellation. + sk.touchScroll.tap and not sk.touchScrolling + proc touchTap*(sk: auto, bounds: Rect): bool = ## Accepts a touch release only in the control where the tap began. - sk.touchScroll.tap and not sk.touchScrolling and - (sk.touchScroll.start - sk.touchOrigin).overlaps(bounds) + sk.touchTap() and (sk.touchScroll.start - sk.touchOrigin).overlaps(bounds) proc endTouchFrame*(touch: var TouchScroll) = ## Retains displayed geometry and releases callbacks for vanished widgets. diff --git a/src/silky/testwindow.nim b/src/silky/testwindow.nim index 8bf1cea4..03439c21 100644 --- a/src/silky/testwindow.nim +++ b/src/silky/testwindow.nim @@ -2,13 +2,13 @@ import std/unicode, - vmath + vmath, bumpy from windy/common import Button, PointerSource, CursorKind, Cursor, TextInputState, TextInputEdit, - TextInputEditKind, TextInputEditCallback + TextInputEditKind, TextInputEditCallback, TextEditAction export Button, PointerSource, CursorKind, Cursor, unicode, TextInputState, TextInputEdit, - TextInputEditKind, TextInputEditCallback + TextInputEditKind, TextInputEditCallback, TextEditAction type Window* = ref object ## Test window that simulates a windy Window. @@ -31,6 +31,11 @@ type Window* = ref object onTextInput*: proc(text: string) onTextEdit*: TextInputEditCallback textInput*: TextInputState + textInputKeyboardEnabled*: bool + editMenuBounds*: Rect + editMenuActions*: set[TextEditAction] + editMenuCallback*: proc(action: TextEditAction) + editMenuShows*: int onButtonPress*: proc(button: Button) onButtonRelease*: proc(button: Button) onFocusChange*: proc() @@ -41,6 +46,23 @@ var clipboard: string proc setTextInputState*(window: Window, state: TextInputState) = ## Records the editor exposed to native text services. window.textInput = state + window.textInputKeyboardEnabled = window.runeInputEnabled + +proc showTextEditMenu*( + window: Window, bounds: Rect, actions: set[TextEditAction], + callback: proc(action: TextEditAction) +): bool {.discardable.} = + ## Records a native menu request without changing keyboard ownership. + window.editMenuBounds = bounds + window.editMenuActions = actions + window.editMenuCallback = callback + inc window.editMenuShows + true + +proc dismissTextEditMenu*(window: Window) = + ## Dismisses a simulated native menu and invalidates its actions. + window.editMenuActions = {} + window.editMenuCallback = nil proc newWindow*(width = 800, height = 600): Window = ## Creates a new test window with the given dimensions. diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index 2661df62..046a8e3a 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -1,7 +1,7 @@ import std/[tables, unicode, times], vmath, bumpy, chroma, - silky/atlas, silky/internal/inputs + silky/atlas, silky/internal/[inputs, textpresses] ## Multi-line text box widget. ## @@ -56,9 +56,12 @@ type cursor*: int selector*: int scrollPos*: Vec2 + scrollIndicator*: ScrollIndicator savedX*: float32 focused*: bool focusEpoch: uint64 + touchBlur: bool + touchPress*: TextPress layout*: seq[Rect] positionedLayout*: bool ## Selection geometry may have variable line heights and gaps. @@ -120,6 +123,8 @@ proc focus*(state: TextBoxState, sk: Silky, window: Window, id: string) = state.focused = true state.focusEpoch = inputs.focusEpoch state.dragging = false + state.touchBlur = false + state.touchPress = TextPress() state.resetBlink() sk.requestFrame() @@ -809,6 +814,48 @@ proc selectParagraph*(state: TextBoxState, mousePos: Vec2) = state.runes[state.selector] != LF: inc state.selector +proc selectionContains*(state: TextBoxState, point: Vec2): bool = + ## Tests actual selected glyph rectangles instead of nearby whitespace. + let selected = state.selection + for i in selected.a ..< min(selected.b, state.layout.len): + if point.overlaps(state.layout[i]): + return true + +proc glyphContains*(state: TextBoxState, point: Vec2): bool = + ## Reports whether a touch is over a laid-out text glyph. + for bounds in state.layout: + if point.overlaps(bounds): + return true + +proc textMenuActions*(state: TextBoxState): set[TextEditAction] = + ## Exposes only operations allowed by this field's editing policy. + if state.enabled: + result.incl(PasteTextAction) + if not state.password: + if state.cursor != state.selector: + result.incl(CopyTextAction) + if state.enabled: + result.incl(CutTextAction) + if state.runes.len > 0: + result.incl(SelectAllTextAction) + +proc touchMenu*( + state: TextBoxState, sk: Silky, window: Window, inside: bool +): TextPressResult = + ## Advances a text hold without letting scrolling or hidden widgets claim it. + when defined(ios) or defined(silkyTesting): + result = state.touchPress.updateTextPress( + sk.mousePos, window.buttonDown[MouseLeft], + window.buttonReleased[MouseLeft], + not inside or not window.focused or not state.focused or + sk.touchScrolling or window.scrollDelta != vec2(0), + scrollMilliseconds() + ) + if result == WaitingTextPress: + sk.requestFrame(max(1, int( + TextPressDelay - (scrollMilliseconds() - state.touchPress.started) + ))) + proc scrollBy*(state: TextBoxState, amount, viewportHeight: float32) = ## Scrolls the text box vertically by the given amount. state.scrollPos.y += amount @@ -1011,6 +1058,17 @@ proc drawScrollbars*( let scrollMaxX = max(0.0f, contentW - innerRect.w) let hasScrollY = contentH > innerRect.h let hasScrollX = not state.wordWrap and contentW > innerRect.w + let + wheel = mouseVec.overlaps(outerRect) and mouseVec.overlaps(clipRect) and + ((hasScrollX and window.scrollDelta.x != 0) or + (hasScrollY and window.scrollDelta.y != 0) or + (hasScrollX and window.scrollDelta.y != 0 and + (window.buttonDown[KeyLeftShift] or window.buttonDown[KeyRightShift]))) + opacity = sk.scrollbarOpacity( + state.scrollIndicator, cast[pointer](state), + wheel or state.scrollingX or state.scrollingY + ) + scrollbarColor = rgbx(255, 255, 255, (opacity * 255).uint8) var tracks, thumbs: array[2, Rect] # Y scrollbar. if hasScrollY: @@ -1020,7 +1078,9 @@ proc drawScrollbars*( 8, innerRect.h - 4 - (if hasScrollX: 10.0f else: 0.0f) ) - sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, trackRect.xy, trackRect.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, + trackRect.xy, trackRect.wh, scrollbarColor) let posPct = if scrollMaxY > 0: state.scrollPos.y / scrollMaxY else: 0.0f thumbHeight = min(trackRect.h, @@ -1043,7 +1103,9 @@ proc drawScrollbars*( if window.buttonPressed[MouseLeft]: state.scrollingY = window.buttonDown[MouseLeft] state.scrollDragOffset.y = mouseVec.y - handleRect.y - sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, handleRect.xy, handleRect.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, + handleRect.xy, handleRect.wh, scrollbarColor) # X scrollbar. if hasScrollX: let trackRect = rect( @@ -1052,7 +1114,9 @@ proc drawScrollbars*( innerRect.w - 4 - (if hasScrollY: 10.0f else: 0.0f), 8 ) - sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, trackRect.xy, trackRect.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, + trackRect.xy, trackRect.wh, scrollbarColor) let posPct = if scrollMaxX > 0: state.scrollPos.x / scrollMaxX else: 0.0f thumbWidth = min(trackRect.w, @@ -1075,7 +1139,9 @@ proc drawScrollbars*( if window.buttonPressed[MouseLeft]: state.scrollingX = window.buttonDown[MouseLeft] state.scrollDragOffset.x = mouseVec.x - handleRect.x - sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, handleRect.xy, handleRect.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, + handleRect.xy, handleRect.wh, scrollbarColor) # Release scrollbar drag when mouse released. if state.scrollingY and @@ -1127,6 +1193,8 @@ proc textBox*( let inputs = sk.textInputs if state.focused and state.focusEpoch != inputs.focusEpoch: state.focused = false + state.touchBlur = false + state.touchPress = TextPress() state.dragging = false if not enabled: state.selector = state.cursor @@ -1166,33 +1234,69 @@ proc textBox*( let mouseVec = sk.mousePos let mouseInside = mouseVec.overlaps(outerRect) and mouseVec.overlaps(sk.clipRect) - let onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) + let + onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) + touchPointer = + when defined(ios) or defined(silkyTesting): + sk.touchScroll.touchInput + else: + false + localMouse = mouseVec - innerRect.xy + state.scrollPos + var openMenu = false if sk.touchScrolling: if state.dragging: state.selector = state.cursor state.dragging = false if sk.buttonPressed[MouseLeft]: + state.touchBlur = sk.touchScroll.touchInput and state.focused and + not mouseInside if mouseInside and not onScrollbar: state.focused = true - let localMouse = mouseVec - innerRect.xy + state.scrollPos + let preserve = touchPointer and state.selectionContains(localMouse) + if touchPointer: + state.touchPress = beginTextPress( + mouseVec - window.mouseDelta.vec2 / sk.uiScale, + scrollMilliseconds(), preserve + ) let now = epochTime() if now - state.lastClickTime < DoubleClickTime: inc state.clickCount else: state.clickCount = 1 state.lastClickTime = now - case state.clickCount: - of 1: - state.mouseAction(localMouse, click = true, shift = shift) - state.dragging = true - of 2: state.selectWord(localMouse) - of 3: state.selectParagraph(localMouse) - else: state.selectAll() - elif not mouseInside: - state.focused = false - state.dragging = false - if not enabled: - state.selector = state.cursor + if not preserve: + case state.clickCount: + of 1: + state.mouseAction(localMouse, click = true, shift = shift) + state.dragging = not touchPointer + of 2: state.selectWord(localMouse) + of 3: state.selectParagraph(localMouse) + else: state.selectAll() + case state.touchMenu(sk, window, mouseInside and not onScrollbar) + of HeldTextPress: + if state.cursor == state.selector and not state.password: + state.selectWord(localMouse) + state.dragging = false + openMenu = true + sk.resetInteractions() + of ReleasedTextPress: + if state.touchPress.preserve: + state.mouseAction(localMouse) + else: + discard + let + outsidePress = sk.buttonPressed[MouseLeft] and + not sk.touchScroll.touchInput + outsideTap = sk.buttonReleased[MouseLeft] and + state.touchBlur and sk.touchTap() + if window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]: + state.touchBlur = false + if not mouseInside and (outsidePress or outsideTap): + # Keep keyboard-driven layout stable until a finger finishes its tap. + state.focused = false + state.dragging = false + if not enabled: + state.selector = state.cursor if state.dragging and not state.scrollingX and not state.scrollingY: if sk.buttonDown[MouseLeft] and not sk.buttonPressed[MouseLeft]: let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -1283,6 +1387,15 @@ proc textBox*( multiline: not singleLine, password: password ), textLayer, firstVertex) + when defined(ios) or defined(silkyTesting): + if openMenu: + let anchor = rect( + (mouseVec - vec2(1, state.lineHeight)) * sk.uiScale, + vec2(2, state.lineHeight) * sk.uiScale + ) + inputs.publishTextMenu( + id, anchor, state.textMenuActions(), textLayer, firstVertex + ) sk.advance(vec2(boxWidth, boxHeight)) template textBox*( diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index bb5c515b..fabf0dba 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -28,6 +28,7 @@ type FrameState* = ref object scrollPos*: Vec2 + scrollIndicator*: ScrollIndicator scrollingX*: bool scrollingY*: bool scrollDragOffset*: Vec2 @@ -342,6 +343,16 @@ proc frameScrollbars*( 0.0, scrollMax.x ) + let + wheel = sk.mouseOverlap(window, frameRect) and + ((scrollMax.x > 0 and window.scrollDelta.x != 0) or + (scrollMax.y > 0 and window.scrollDelta.y != 0)) + opacity = sk.scrollbarOpacity( + frameState.scrollIndicator, cast[pointer](frameState), + wheel or frameState.scrollingX or frameState.scrollingY + ) + scrollbarColor = rgbx(255, 255, 255, (opacity * 255).uint8) + # Y scrollbar. if contentSize.y > frameRect.h: let @@ -356,7 +367,9 @@ proc frameScrollbars*( max(MinThumbSize, track.h * (frameRect.h / contentSize.y)) ) travel = track.h - thumbH - sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, track.xy, track.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, + track.xy, track.wh, scrollbarColor) proc thumbRectY(): Rect = let @@ -382,7 +395,9 @@ proc frameScrollbars*( frameState.scrollDragOffset.y = sk.mousePos.y - thumb.y let thumb = thumbRectY() thumbs[1] = thumb - sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, thumb.xy, thumb.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, + thumb.xy, thumb.wh, scrollbarColor) # X scrollbar. if contentSize.x > frameRect.w: @@ -398,7 +413,9 @@ proc frameScrollbars*( max(MinThumbSize, track.w * (frameRect.w / contentSize.x)) ) travel = track.w - thumbW - sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, track.xy, track.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, + track.xy, track.wh, scrollbarColor) proc thumbRectX(): Rect = let @@ -424,7 +441,9 @@ proc frameScrollbars*( frameState.scrollDragOffset.x = sk.mousePos.x - thumb.x let thumb = thumbRectX() thumbs[0] = thumb - sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, thumb.xy, thumb.wh) + if opacity > 0: + sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, + thumb.xy, thumb.wh, scrollbarColor) if frameState.scrollingY and (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): diff --git a/tests/test_atlas_paths.nim b/tests/test_atlas_paths.nim new file mode 100644 index 00000000..6b4ba7ed --- /dev/null +++ b/tests/test_atlas_paths.nim @@ -0,0 +1,30 @@ +import + std/[os, strutils, tables, tempfiles], + pixie, + silky/atlas + +block: + echo "Testing atlas prefixes with native and mixed path separators" + let directory = createTempDir("silky-atlas-paths-", "") + defer: + removeDir(directory) + createDir(directory / "nested") + newImage(8, 8).writeFile(directory / "close.png") + newImage(4, 4).writeFile(directory / "nested" / "inside.png") + for prefix in [ + directory & DirSep, + directory.replace('\\', '/') & "/", + directory.replace('/', '\\') & "\\" + ]: + let builder = newAtlasBuilder(64, 2) + builder.addDir(directory, prefix, pixelScale = 2) + doAssert "close" in builder.atlas.entries, prefix + doAssert builder.atlas.entries.len == 2 + doAssert builder.atlas.entries["close"].pixelScale == 2 + let recursive = newAtlasBuilder(64, 2) + recursive.addDirRecursive(directory, prefix) + doAssert "close" in recursive.atlas.entries, prefix + doAssert "nested/inside" in recursive.atlas.entries, prefix + doAssert recursive.atlas.entries.len == 3 + +echo "Atlas path checks passed." diff --git a/tests/test_first_touch.nim b/tests/test_first_touch.nim index 4106d6fe..5c949f94 100644 --- a/tests/test_first_touch.nim +++ b/tests/test_first_touch.nim @@ -21,6 +21,8 @@ var invalidateOnPress: bool selected: int showWindow = true + modalOpen = true + maskBackground = true block: let builder = newAtlasBuilder(1024, 4) @@ -67,6 +69,27 @@ proc drawSubwindow(sk: Silky, window: Window) = ) sk.subWindowEnd(window, state) +proc drawModal(sk: Silky, window: Window) = + ## Masks background input before restoring the pointer for popup controls. + let mouse = sk.mousePos + if modalOpen and maskBackground: + sk.mousePos = vec2(-1000) + let background = sk.interact(rect(20, 20, 360, 280), true) + if background.isReleased(window): + inc counts[0] + sk.mousePos = mouse + if modalOpen: + sk.pushLayer(PopupsLayer) + discard sk.interact(rect(40, 40, 240, 200), true) + sk.at = vec2(60, 100) + radioButton("Allow edits", selected, 1) + sk.at = vec2(240, 60) + clickableIcon("close", true): + inc counts[1] + modalOpen = false + sk.resetInteractions() + sk.popLayer() + proc tap( harness: var TestHarness, draw: proc(sk: Silky, window: Window), @@ -180,4 +203,26 @@ block: discard harness.pumpFrame(drawSubwindow) doAssert state.pos == vec2(100, 100) +block: + echo "Testing masked background preserves popup radio and close targets" + for source in [TouchPointer, MousePointer]: + for coalesced in [false, true]: + for masked in [false, true]: + counts = default(typeof(counts)) + selected = 0 + modalOpen = true + maskBackground = masked + var harness = newTestHarness(atlas) + harness.window.pointerSource = source + discard harness.pumpFrame(drawModal) + harness.tap(drawModal, vec2(70, 110), coalesced) + doAssert selected == 1 and modalOpen, + $source & " coalesced=" & $coalesced & " masked=" & $masked + doAssert counts == [0, 0, 0, 0] + harness.tap(drawModal, vec2(248, 68), coalesced) + doAssert not modalOpen + doAssert counts == [0, 1, 0, 0] + discard harness.pumpFrame(drawModal) + doAssert counts == [0, 1, 0, 0] + echo "First-touch hit resolution tests passed." diff --git a/tests/test_focus.nim b/tests/test_focus.nim index 701529f5..a0592fb1 100644 --- a/tests/test_focus.nim +++ b/tests/test_focus.nim @@ -1,6 +1,6 @@ import std/unicode, - vmath, + vmath, bumpy, silky, silky/semantics, silky/internal/inputs when not defined(silkyTesting): @@ -116,4 +116,140 @@ block: textBoxStates.del(oldId) textBoxStates.del(newId) -echo "All programmatic focus tests passed." +block: + echo "Testing touch actions keep keyboard layout until release" + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + for source in [TouchPointer, MousePointer]: + for coalesced in [false, true]: + let id = "keyboard-layout-" & $source & $coalesced + var + harness = newTestHarness(builder.atlas) + draft = "Send this once" + sent = 0 + let window = harness.window + window.pointerSource = source + + proc draw(sk: Silky, window: Window) = + ## Models a composer whose send action moves with the keyboard inset. + let actionY = if window.runeInputEnabled: 180.0'f else: 380.0'f + sk.at = vec2(20, 20) + sk.textBox(window, id, draft, 240, 64, wrapWords = true) + let interaction = sk.interact(rect(280, actionY, 44, 44), true) + if interaction.isReleased(window): + inc sent + + discard harness.pumpFrame(draw) + textBoxStates[id].focus(harness.sk, window, id) + discard harness.pumpFrame(draw) + window.moveMouse(300, 200) + window.pressButton(MouseLeft) + if not coalesced: + discard harness.pumpFrame(draw) + doAssert window.runeInputEnabled == (source == TouchPointer) + doAssert sent == 0 + discard harness.pumpFrame(draw) + window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + doAssert not window.runeInputEnabled + doAssert sent == (if source == TouchPointer or coalesced: 1 else: 0) + discard harness.pumpFrame(draw) + doAssert sent <= 1 + textBoxStates.del(id) + +block: + echo "Testing outside pans, cancellation, and replacement focus" + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + for gesture in 0 .. 2: + let + id = "touch-preserve-" & $gesture + replacementId = id & "-replacement" + var + harness = newTestHarness(builder.atlas) + draft = "Keep this draft" + replacement = "Rename" + showReplacement = false + let window = harness.window + window.pointerSource = TouchPointer + + proc draw(sk: Silky, window: Window) = + ## Draws a focused editor and a popup installed during a held touch. + sk.at = vec2(20, 20) + sk.textBox(window, id, draft, 240, 64, wrapWords = true) + if showReplacement: + sk.at = vec2(20, 120) + sk.textBox(window, replacementId, replacement, 240, 64, + wrapWords = true) + + discard harness.pumpFrame(draw) + textBoxStates[id].focus(harness.sk, window, id) + discard harness.pumpFrame(draw) + window.moveMouse(300, 200) + window.pressButton(MouseLeft) + discard harness.pumpFrame(draw) + doAssert window.runeInputEnabled + case gesture + of 0: + window.moveMouse(300, 260) + of 1: + window.moveMouse(-1, -1) + else: + let editor = TextBoxState() + editor.setText(replacement) + textBoxStates[replacementId] = editor + editor.focus(harness.sk, window, replacementId) + showReplacement = true + window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + let owner = if showReplacement: replacementId else: id + doAssert textBoxStates[owner].focused + doAssert window.runeInputEnabled + doAssert window.textInput.id == owner + doAssert draft == "Keep this draft" + textBoxStates.del(id) + textBoxStates.del(replacementId) + +block: + echo "Testing keyboard is disabled before clearing native state on blur" + let + id = "resume-composer" + builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + var + harness = newTestHarness(builder.atlas) + draft = "Preserved café draft" + proc draw(sk: Silky, window: Window) = + ## Republishes the composer across repeated application focus changes. + sk.at = vec2(20, 20) + sk.textBox(window, id, draft, 240, 80, wrapWords = true) + discard harness.pumpFrame(draw) + let + window = harness.window + state = textBoxStates[id] + for i in 0 ..< 3: + state.focus(harness.sk, window, id) + discard harness.pumpFrame(draw) + doAssert window.textInputKeyboardEnabled + let + before = draft + selection = state.selection + window.focused = false + window.changeFocus() + doAssert window.textInput.id.len == 0 + doAssert not window.runeInputEnabled + doAssert not window.textInputKeyboardEnabled, + "Clearing an editor must never re-request the old keyboard." + window.focused = true + window.changeFocus() + discard harness.pumpFrame(draw) + doAssert draft == before and state.selection == selection + state.focus(harness.sk, window, id) + discard harness.pumpFrame(draw) + doAssert window.runeInputEnabled and window.textInput.id == id + window.typeRune(Rune('x')) + discard harness.pumpFrame(draw) + doAssert draft.runeLen == before.runeLen + 1 + textBoxStates.del(id) + +echo "All focus tests passed." diff --git a/tests/test_scroll_indicators.nim b/tests/test_scroll_indicators.nim new file mode 100644 index 00000000..babc5de7 --- /dev/null +++ b/tests/test_scroll_indicators.nim @@ -0,0 +1,180 @@ +import + std/os, + pixie, vmath, bumpy, + silky, silky/scrolls + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +type + Position = ref object + value: Vec2 + + Scene = ref object + touchScroll: TouchScroll + touchOrigin, mousePos: Vec2 + clipRect: Rect + currentDrawLayer: int + delays: seq[int] + position: Position + +proc drawWidgets(sk: Silky, window: Window) = + ## Exercises a real frame with overflow and its retained scrollbar. + ui: + frame "indicator frame": + box 20, 30, 320, 180 + patch "" + layout TopToBottom + horizontalPadding 0 + verticalPadding 0 + itemSpacing 0 + group "content": + size 300, 800 + +proc requestFrame(scene: Scene, delayMs = 0) = + ## Records redraw deadlines requested by a transient indicator. + scene.delays.add(delayMs) + +proc near(actual, expected: float32) = + ## Checks opacity without depending on floating-point rounding. + doAssert abs(actual - expected) < 0.001'f, $actual & " != " & $expected + +proc register(scene: Scene) = + ## Publishes one retained viewport with a visible scrollbar track. + let position = scene.position + var tracks, thumbs: array[2, Rect] + tracks[1] = rect(192, 0, 8, 200) + thumbs[1] = rect(192, position.value.y / 10, 8, 20) + scene.registerTouchScroll( + cast[pointer](position), rect(0, 0, 200, 200), position.value, + vec2(0, 2000), vec2(1), tracks, thumbs, 0, + proc(value: Vec2) = + ## Applies captured gestures to the retained viewport. + position.value = value + ) + +proc setup(): Scene = + ## Creates displayed scroll geometry without starting a gesture. + result = Scene( + position: Position(), clipRect: rect(0, 0, 400, 400), + mousePos: vec2(100, 100) + ) + result.register() + result.touchScroll.endTouchFrame() + +proc tick( + scene: Scene, time: float64, point: Vec2, + pressed = false, down = false, released = false, + velocity = vec2(0), isTouch = true +) = + ## Advances input while retaining final-release activity for drawing. + scene.mousePos = point + scene.touchScroll.beginTouchFrame( + isTouch, pressed, down, released, true, point, vec2(0), velocity, time + ) + scene.register() + scene.touchScroll.endTouchFrame() + +block: + echo "Testing scroll indicator timing and renewed activity" + var indicator: ScrollIndicator + near(indicator.indicatorOpacity(false, 100), 0) + near(indicator.indicatorOpacity(true, 100), 1) + near(indicator.indicatorOpacity(false, 250), 1) + near(indicator.indicatorOpacity(false, 375), 0.5) + near(indicator.indicatorOpacity(false, 500), 0) + near(indicator.indicatorOpacity(false, 1000), 0) + near(indicator.indicatorOpacity(true, 1100), 1) + near(indicator.indicatorOpacity(false, 1400), 0.4) + near(indicator.indicatorOpacity(true, 1401), 1) + +block: + echo "Testing fade redraw deadlines and desktop visibility" + let scene = setup() + var indicator: ScrollIndicator + scene.tick(0, vec2(100, 100)) + let target = cast[pointer](scene.position) + near(scene.scrollbarOpacity(indicator, target, nowMs = 0), 0) + doAssert scene.delays.len == 0 + near(scene.scrollbarOpacity(indicator, target, true, 100), 1) + doAssert scene.delays[^1] == ScrollIndicatorDelay.int + near(scene.scrollbarOpacity(indicator, target, false, 300), 0.8) + doAssert scene.delays[^1] == 16 + let before = scene.delays.len + near(scene.scrollbarOpacity(indicator, target, false, 500), 0) + doAssert scene.delays.len == before + scene.tick(600, vec2(100, 100), isTouch = false) + near(scene.scrollbarOpacity(indicator, target, nowMs = 600), 1) + doAssert scene.delays.len == before + +block: + echo "Testing only the dragged viewport remains visible on release" + let scene = setup() + var active, other: ScrollIndicator + let target = cast[pointer](scene.position) + scene.tick(0, vec2(100, 150), pressed = true, down = true) + near(scene.scrollbarOpacity(active, target, nowMs = 0), 0) + scene.tick(20, vec2(100, 100), down = true) + doAssert scene.position.value.y == 50 + near(scene.scrollbarOpacity(active, target, nowMs = 20), 1) + near(scene.scrollbarOpacity(other, cast[pointer](1), nowMs = 20), 0) + scene.tick(40, vec2(100, 80), released = true) + near(scene.scrollbarOpacity(active, target, nowMs = 40), 1) + doAssert active.lastActivity == 40 + scene.tick(41, vec2(100, 80)) + near(scene.scrollbarOpacity(active, target, nowMs = 41), 1) + doAssert active.lastActivity == 40 + scene.tick(440, vec2(100, 80)) + near(scene.scrollbarOpacity(active, target, nowMs = 440), 0) + +block: + echo "Testing momentum keeps its indicator visible through the final frame" + let scene = setup() + var indicator: ScrollIndicator + let target = cast[pointer](scene.position) + scene.tick(0, vec2(100, 150), pressed = true, down = true) + scene.tick(20, vec2(100, 100), down = true) + scene.tick(40, vec2(100, 80), released = true, velocity = vec2(0, -400)) + doAssert scene.touchScroll.momentumActive() + var time = 40.0 + while scene.touchScroll.momentumActive(): + time += 100 + scene.tick(time, vec2(100, 80)) + near(scene.scrollbarOpacity(indicator, target, nowMs = time), 1) + doAssert indicator.lastActivity == time + doAssert time < 10000 + scene.tick(time + 1, vec2(100, 80)) + near(scene.scrollbarOpacity(indicator, target, nowMs = time + 1), 1) + doAssert indicator.lastActivity == time + scene.tick(time + 400, vec2(100, 80)) + near(scene.scrollbarOpacity(indicator, target, nowMs = time + 400), 0) + +block: + echo "Testing hidden real frame scrollbars still accept thumb dragging" + let + data = currentSourcePath().parentDir / "data" + builder = newAtlasBuilder(1024, 4) + builder.addDir(data, data & DirSep) + builder.addFont(data / "IBMPlexSans-Regular.ttf", "Default", 18) + frameStates.clear() + var h = newTestHarness(builder.atlas) + h.window.pointerSource = TouchPointer + discard h.pumpFrame(drawWidgets) + let state = frameStates["indicator frame"] + doAssert not state.scrollIndicator.shown + h.window.moveMouse(318, 35) + h.window.pressButton(MouseLeft) + discard h.pumpFrame(drawWidgets) + h.window.moveMouse(318, 80) + discard h.pumpFrame(drawWidgets) + doAssert state.scrollPos.y > 100 + doAssert state.scrollIndicator.shown + h.window.releaseButton(MouseLeft) + discard h.pumpFrame(drawWidgets) + let position = state.scrollPos.y + state.scrollIndicator.lastActivity = scrollMilliseconds() - 500 + discard h.pumpFrame(drawWidgets) + doAssert not state.scrollIndicator.shown + near(state.scrollPos.y, position) + +echo "All scroll indicator tests passed." diff --git a/tests/test_text_menus.nim b/tests/test_text_menus.nim new file mode 100644 index 00000000..a5dd6fea --- /dev/null +++ b/tests/test_text_menus.nim @@ -0,0 +1,230 @@ +import + std/unicode, + vmath, bumpy, + silky, silky/semantics, silky/internal/[inputs, textpresses] + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +block: + echo "Testing stationary text hold timing and cancellation" + var press = beginTextPress(vec2(10, 20), 100, true) + doAssert press.updateTextPress(vec2(10, 20), true, false, false, 599) == + WaitingTextPress + doAssert press.updateTextPress(vec2(10, 20), true, false, false, 600) == + HeldTextPress + doAssert press.updateTextPress(vec2(10, 20), false, true, false, 601) == + NoTextPress + for mode in 0 .. 2: + press = beginTextPress(vec2(10, 20), 0, true) + doAssert press.updateTextPress( + (if mode == 0: vec2(16, 20) else: vec2(10, 20)), + mode != 1, false, mode == 2, 501 + ) == NoTextPress + +let builder = newAtlasBuilder(1024, 4) +builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) +var + harness = newTestHarness(builder.atlas) + value = "café 世界 copy" + editable = true + password = false + rich = false + hidden = false + offset = vec2(0) + spans: seq[TextSpan] + blocks: seq[TextBlock] + +proc draw(sk: Silky, window: Window) = + ## Draws one real text widget with optionally deferred screen placement. + if hidden: + return + sk.at = vec2(20, 20) + let mark = sk.textInputs.textPlacementMark() + if rich: + sk.richTextBox(window, "menu-rich", value, 320, 180, + spans = spans, blocks = blocks) + else: + sk.textBox(window, "menu-edit", value, 320, 180, + wrapWords = true, enabled = editable, password = password) + sk.textInputs.translateTextInput(mark, offset) + +proc editor(): TextBoxState = + ## Returns the currently displayed field state. + if rich: richTextBoxStates["menu-rich"].editor + else: textBoxStates["menu-edit"] + +proc setup() = + ## Starts a fresh displayed editor without a previous menu or gesture. + textBoxStates.clear() + richTextBoxStates.clear() + harness = newTestHarness(builder.atlas) + harness.window.pointerSource = TouchPointer + discard harness.pumpFrame(draw) + +proc pressGlyph(index = 1) = + ## Presses the center of a real laid-out glyph. + let box = editor().layout[index] + harness.window.moveMouse( + int(20 + harness.sk.theme.padding.float32 + box.x + box.w / 2), + int(20 + harness.sk.theme.padding.float32 + box.y + box.h / 2) + ) + harness.window.pressButton(MouseLeft) + discard harness.pumpFrame(draw) + +proc hold() = + ## Advances the gesture clock without blocking the test process. + editor().touchPress.started -= TextPressDelay + 1 + discard harness.pumpFrame(draw) + harness.window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + +block: + echo "Testing selected text remains selected through a hold" + for readOnly in [false, true]: + rich = readOnly + setup() + editor().cursor = 4 + editor().selector = 0 + pressGlyph() + doAssert editor().cursor == 4 and editor().selector == 0 + hold() + doAssert editor().selection == (0 .. 4) + doAssert harness.window.editMenuShows == 1 + doAssert harness.window.runeInputEnabled == not readOnly + doAssert CopyTextAction in harness.window.editMenuActions + doAssert (PasteTextAction in harness.window.editMenuActions) == not readOnly + harness.window.editMenuCallback(CopyTextAction) + discard harness.pumpFrame(draw) + doAssert getClipboardString() == "café" + +block: + echo "Testing paste hooks, replacement undo, and readonly select all" + rich = false + setup() + editor().selectAll() + pressGlyph() + hold() + setClipboardString("✓ café") + harness.window.editMenuCallback(PasteTextAction) + discard harness.pumpFrame(draw) + doAssert value == "✓ café" + editor().undo() + doAssert editor().getText() == "café 世界 copy" + value = editor().getText() + setup() + var + pasteCalls = 0 + pasteWakeups = 0 + harness.sk.textInputs.onEvent = proc() = + ## Records repaint requests for native actions without keyboard events. + inc pasteWakeups + harness.sk.textInputs.onPaste = proc(id: string): bool = + ## Models Runway consuming an image paste without inserting text. + doAssert id == "menu-edit" + inc pasteCalls + true + pressGlyph() + hold() + harness.window.editMenuCallback(PasteTextAction) + discard harness.pumpFrame(draw) + doAssert pasteCalls == 1 + doAssert pasteWakeups == 1 + doAssert value == "café 世界 copy" + rich = true + setup() + pressGlyph() + hold() + harness.window.editMenuCallback(SelectAllTextAction) + discard harness.pumpFrame(draw) + doAssert editor().selection == (0 .. value.runeLen) + doAssert not harness.window.runeInputEnabled + +block: + echo "Testing blank and password fields expose only safe actions" + rich = false + value = "" + setup() + harness.window.moveMouse(45, 45) + harness.window.pressButton(MouseLeft) + discard harness.pumpFrame(draw) + hold() + doAssert harness.window.editMenuActions == {PasteTextAction} + value = "secret" + password = true + setup() + pressGlyph() + hold() + doAssert harness.window.editMenuActions == {PasteTextAction} + password = false + +block: + echo "Testing short taps, scroll motion, and stale actions" + value = "café 世界 copy" + setup() + editor().selectAll() + pressGlyph() + harness.window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + doAssert editor().cursor == editor().selector + doAssert harness.window.editMenuShows == 0 + setup() + pressGlyph() + editor().touchPress.started -= TextPressDelay + 1 + harness.window.moveMouse(harness.window.mousePos.x + 6, + harness.window.mousePos.y) + discard harness.pumpFrame(draw) + doAssert harness.window.editMenuShows == 0 + harness.window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + setup() + harness.window.moveMouse(40, 40) + harness.window.pressButton(MouseLeft) + harness.window.moveMouse(55, 40) + discard harness.pumpFrame(draw) + doAssert not editor().touchPress.active + hold() + doAssert harness.window.editMenuShows == 0 + setup() + pressGlyph() + hold() + let callback = harness.window.editMenuCallback + hidden = true + discard harness.pumpFrame(draw) + callback(CutTextAction) + hidden = false + discard harness.pumpFrame(draw) + doAssert value == "café 世界 copy" + +block: + echo "Testing hold suppresses link release and translates its menu" + rich = true + offset = vec2(13, 45) + spans = @[TextSpan(first: 0, last: 4, linkId: 1)] + setup() + pressGlyph() + let point = harness.window.mousePos.vec2 + hold() + doAssert richTextBoxStates["menu-rich"].activatedSpan == -1 + doAssert abs(harness.window.editMenuBounds.x - point.x + 1 - offset.x) < 0.01 + doAssert abs(harness.window.editMenuBounds.y - point.y + + editor().lineHeight - offset.y) < 0.01 + doAssert harness.window.editMenuShows == 1 + +block: + echo "Testing image blocks cannot claim a text menu" + offset = vec2(0) + spans = @[] + blocks = @[TextBlock(first: 0, last: 0, image: "missing-image", + imageSize: vec2(100, 100))] + setup() + harness.window.moveMouse(60, 60) + harness.window.pressButton(MouseLeft) + discard harness.pumpFrame(draw) + doAssert not editor().touchPress.active + hold() + doAssert harness.window.editMenuShows == 0 + +textBoxStates.clear() +richTextBoxStates.clear() +echo "Text menu checks passed"