diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 82d07f52..7dec2d92 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -5,6 +5,10 @@ on: pull_request: branches: [master] +defaults: + run: + shell: bash + jobs: build: strategy: @@ -54,22 +58,58 @@ jobs: if: matrix.emscripten uses: mymindstorm/setup-emsdk@v14 + - name: Install DirectX shader compiler + if: matrix.build_flags == '-d:useDirectX' + shell: pwsh + run: | + $archive = Join-Path $env:RUNNER_TEMP 'dxc.zip' + $tools = Join-Path $env:RUNNER_TEMP 'dxc' + Invoke-WebRequest 'https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2609/dxc_2026_09_29.zip' -OutFile $archive + if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne 'ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1') { throw 'DXC archive checksum mismatch' } + Expand-Archive $archive -DestinationPath $tools + $compiler = Join-Path $tools 'bin/x64/dxc.exe' + "SHADY_HLSL_COMPILER=$compiler" >> $env:GITHUB_ENV + & $compiler --version + if ($LASTEXITCODE -ne 0) { throw 'DXC did not start' } + + - name: Install SPIR-V shader compiler + if: matrix.build_flags == '-d:useVulkan' + shell: pwsh + run: | + $archive = Join-Path $env:RUNNER_TEMP 'glslang.zip' + $tools = Join-Path $env:RUNNER_TEMP 'glslang' + Invoke-WebRequest 'https://github.com/KhronosGroup/glslang/releases/download/16.6.0/glslang-16.6.0-windows-x86_64-release.zip' -OutFile $archive + if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne '82bf434e69b9bb4829de7e2b4bc2c5e7a7861e53d66cf75e5cc70f5f694a8d9b') { throw 'glslang archive checksum mismatch' } + Expand-Archive $archive -DestinationPath $tools + $compiler = Join-Path $tools 'bin/glslang.exe' + "SHADY_SPIRV_COMPILER=$compiler" >> $env:GITHUB_ENV + & $compiler --version + if ($LASTEXITCODE -ne 0) { throw 'glslang did not start' } + - name: Run unit tests if: ${{ !matrix.emscripten }} run: | nim r tests/test_textboxes.nim nim r ${{ matrix.build_flags }} tests/test_richtextboxes.nim nim r -d:silkyTesting -d:nimTypeNames tests/test_inputs.nim - nim r -d:silkyTesting tests/test_rendering.nim nim r -d:silkyTesting tests/test_buttons.nim nim r -d:silkyTesting tests/test_focus.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_secure_inputs.nim + 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_rendering.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim + nim r tests/test_retina_atlas.nim nim r tests/test_shader_codegen.nim nim r ${{ matrix.build_flags }} tests/test_density.nim nim r ${{ matrix.build_flags }} tests/test_decorations.nim nim r ${{ matrix.build_flags }} tests/test_rules.nim nim r ${{ matrix.build_flags }} tests/test_quotes.nim + nim r ${{ matrix.build_flags }} tests/test_richimages.nim nim r ${{ matrix.build_flags }} tests/test_button_vertices.nim nim r -d:silkyTesting tests/test_layout.nim nim r -d:silkyTesting tests/test_layout_regressions.nim diff --git a/docs/ios.md b/docs/ios.md new file mode 100644 index 00000000..09e63db4 --- /dev/null +++ b/docs/ios.md @@ -0,0 +1,136 @@ +# iOS Metal integration + +The iOS drawer uses the same Nim `silkyVert` and `silkyFrag` shader procedures +as the other backends. Shady translates them to MSL during the Nim build, and +Metal compiles the generated source when the drawer is created. Select this +drawer with `-d:useMetal4` and compile for iOS with `--os:ios --cpu:arm64`. + +The `windy-ios`, `silky-ios`, `shady-ios`, and `metal4-ios` worktrees must be +on the Nim import path. Use `--skipParentCfg` when a parent Nim configuration +points at desktop checkouts. No Shady source changes are required for the +current Silky shaders. + +## Application setup + +Create the Windy window in its `runApplication` startup callback. Create +Silky in the first `window.onFrame` callback, after the native Metal view +exists. Run `beginUI(window, window.size)` and `endUI()` once per frame. +UIKit drives the event loop. There is no `pollEvents` loop or OpenGL buffer +swap in an iOS application. + +Windy's iOS platform owns the UIKit app and scene delegates, MetalKit view +and input callbacks. These are implemented in Nim using Windy's shared Apple +Objective-C runtime bindings. A small C entry point starts Nim, and a tiny +Objective-C bridge references the SDK protocol metadata. GLFM is a design +reference only; it is not compiled or linked into the app. + +Windy reports drawable sizes and pointer positions in pixels. Set +`sk.uiScale = window.contentScale` before `beginUI` for a point-sized UI, +and use `sk.size` for the resulting logical layout dimensions. Account for +the device's safe area when positioning controls. + +Touch presses resolve against the previous displayed frame's hit rectangles, +including layer order and clipping, so controls need no preceding hover event. +Call `resetInteractions` when replacing a modal or reorganizing controls. + +Generate the atlas on the host and bundle its PNG with the application. +The PNG includes the font metrics and sprite metadata, so the device does +not need the original fonts or skin files. For the example skin, add +`examples/basicwindow/data/` with that directory as the removed prefix, +then add `IBMPlexSans-Regular.ttf` as `Default` and `H1` before writing the +atlas. `newSilky(window, atlasPngPath)` loads the packaged atlas. + +Pass `pixelScale = 2` or `pixelScale = 3` to `addFont` when generating +Retina atlases. Font size, advances, kerning and line metrics stay in +logical points, while glyph pixels are rasterized at the requested +density. Select the matching atlas for the window's content scale and +keep `sk.uiScale = window.contentScale`. The text renderer uses physical +atlas coordinates and snaps glyph origins to that raster's pixel grid. +Older atlas files without density metadata continue to use 1x glyphs. +Raster image and button skin assets have their own density requirements. + +## Shader bindings + +The generated entry points are `vertexMain` and `fragmentMain`. Vertex +buffer 0 contains two `Vec2` uniforms: viewport size at byte 0 and atlas +size at byte 8. Vertex buffer 1 contains packed 48-byte `DrawerVertex` +values. Attributes 0 through 5 are position, UV, color, clip position, +clip size, and mask UV. The color attribute uses `UChar4Normalized`; the +other attributes use `Float2`. The atlas texture and sampler use fragment +index 0. The final `uint32` is a CPU texture handle used for batching; +it is not a shader attribute. Zero selects the atlas. Each contiguous +texture batch receives the bound texture's size in the uniform buffer. + +Positions and atlas coordinates stay in pixels until the generated shader +transforms them. This also applies to tint-mask coordinates. The fragment +shader uses interpolated pixel positions for clipping. + +## Current scope + +The drawer renders atlas images, independent images, text, clipping, tint +masks, rich documents, and Silky controls. It uses the ordinary Metal API exposed by the `metal4` Nim +package, without requiring Apple's newer Metal 4 GPU features. + +Each frame waits for GPU completion before reusing the shared vertex +buffer. This keeps the first port correct and reports command errors, but +does not overlap CPU and GPU work. A bounded set of buffers can replace +this synchronization after profiling. Runtime atlas changes are uploaded +through `uploadAtlas`, or `uploadAtlasRegion` for a changed rectangle. + +Use `allocateTexture`, `uploadTextureRows`, `drawTexture` and `deleteTexture` +for images that should not consume font atlas space. Upload all image rows +before drawing the texture. Batches preserve the original layer and draw +order, including when atlas controls and independent images alternate. +Call the drawer's `close` after rendering has stopped to release its GPU +resources. Closing a drawer does not destroy Windy's UIKit view. + +`drawer.maxTextureSize` reports the active device's 2D texture limit. +Simulator exposes Apple family 2 capabilities with an 8192-pixel limit; +newer physical devices can support larger textures. Repack the atlas within +this bound before uploading it. Oversized textures raise `SilkyError` +before reaching Metal's descriptor assertions. + +Atlas icons and skins accept an integer `pixelScale` through `addImage`, +`addDir` and `addDirRecursive`. Their physical texture sizes remain intact; +layout uses the corresponding logical dimensions. + +Silky accepts Windy's text commits and range-based native edits, and publishes +focused text, selection and caret geometry through `TextInputState`. The +platform owns the software keyboard and composition interface. Accessibility, +multitouch gestures and remote development transport remain separate Windy +and application milestones. + +## Verification + +The native UIKit simulator demo verified Retina rendering, button taps, +software keyboard presentation, text insertion, single-character deletion, +keyboard dismissal and portrait/landscape resizing at 3x scale. Signed arm64 +builds passed strict code signature verification. Background/resume kept the +same process and preserved edited text and the counter. Both native demos +are signed and installed on an iPhone 14 Pro. The locked phone blocked +launch, so native device runtime verification awaits an unlocked device. +The earlier prototype's rendering, touch and Retina text were verified on +that phone. + +`tests/test_shader_codegen.nim` checks generated MSL resource slots and +uniform layout alongside the existing GLSL and HLSL checks. +`tests/test_metal_shader_pixels.nim` compiles the generated shaders on +macOS, links the pipeline with Silky's packed vertex layout, renders to an +offscreen texture, and verifies colors, tint masks, and clipping by pixel +readback. This host test uses Metal's runtime compiler and does not need +the optional Xcode MetalToolchain download. + +`tests/test_metal_texture_pixels.nim`, built with `-d:silkyMetalTesting`, +exercises the production drawer's allocation, row uploads, atlas rectangles, +texture growth, batching, stale handles, clipping and tint masks. It renders +offscreen on macOS or iOS Simulator and checks the actual GPU pixels. The +Simulator build uses `--os:ios --cpu:arm64 --noMain -d:iosSimulator` with the +Simulator SDK and target flags; run it with `simctl spawn`. It also asserts +the detected 8192-pixel texture limit. `test_inputs`, +`test_cursor_scroll` and `test_rendering`, built with `-d:silkyTesting`, cover +native edit ordering, parent scrolling and on-demand frame scheduling. + +`tests/test_retina_atlas.nim` checks unchanged logical metrics at 1x, 2x +and 3x, compares 3x glyph pixels against a physical-size reference, +roundtrips density metadata, loads old metadata and checks that runtime +atlas additions preserve the full glyph rectangles. diff --git a/docs/text_inputs.md b/docs/text_inputs.md index 33cee172..cfa0786f 100644 --- a/docs/text_inputs.md +++ b/docs/text_inputs.md @@ -32,3 +32,53 @@ state. No browser-specific input setup is needed. Run `nim r tests/manual_inputs.nim` from the repository root to try single-line, password, and multiline fields with a keyboard display. Hold keys outside the fields to highlight them, then click a field and type to check suppression. + +## Navigating rich text inside a scrolling frame + +A rich text box scrolls its own content when the cursor moves. If the box is +sized to the full document height, the enclosing frame owns scrolling instead. +After drawing the box, `state.cursorNavigated` reports whether it consumed an +arrow, Home, End, Page Up, or Page Down press. This includes repeated presses and +Shift selections, even when the cursor is already at a document boundary. +The flag resets on each widget draw. Clicking, copying, Select All, and streamed +text changes do not set it. + +Use `revealScroll` to calculate the enclosing frame's scroll position. It accepts +the scroll used to place the target, the complete content size, and the viewport +and target rectangles in the same window coordinates. It supports all four +stack directions and clamps to the content bounds. Its optional margin defaults +to four layout units. Apply the result after the frame finishes laying out and +processing its scrollbars. + +```nim +# Save this before drawing the enclosing frame. +let previousScroll = frameStates["history"].scrollPos +var + revealCursor = false + caret: Rect + +# Inside the frame, after placing the full-height reply. +let textOrigin = sk.at + vec2(sk.theme.padding.float32) +sk.richTextBox(window, "reply", text, replyWidth, replyHeight) +let state = richTextBoxStates["reply"] +if state.cursorNavigated: + let local = state.editor.locationRect(state.editor.cursor) + caret = rect(textOrigin + local.xy - state.editor.scrollPos, local.wh) + revealCursor = true + +# After the frame or UI finishes drawing. +if revealCursor: + frameStates["history"].scrollPos = revealScroll( + previousScroll, + contentSize, + viewport, + caret, + BottomToTop + ) +``` + +Apply this only while the window is focused and no modal control owns input. +When using on-demand rendering, request another frame if the scroll changed. +Apps that skip invisible messages must still draw the focused rich text widget +so it can consume navigation keys. Do not call `revealScroll` unconditionally +each frame, or ordinary wheel scrolling will keep returning to the cursor. diff --git a/nimby.lock b/nimby.lock index 22999c53..2f36585b 100644 --- a/nimby.lock +++ b/nimby.lock @@ -1,19 +1,19 @@ -shady 0.1.5 https://github.com/treeform/shady f9ab26d946c32cd9da7c04394a1353a375a9dba5 +shady 0.1.5 https://github.com/treeform/shady c899f7cd17dbe7021d6e3aa2908e6de6549c47f1 vmath 2.0.1 https://github.com/treeform/vmath ddfcd738578c47ed3330b917f5efecf5a15128b2 pixie 5.1.0 https://github.com/treeform/pixie 5eda4949a3c8bea318cfac8e42060a8f90f3f35d chroma 1.0.0 https://github.com/treeform/chroma 2381748f92e5ea16cb2403ff7e20c6dd5443a59d -zippy 0.10.16 https://github.com/guzba/zippy a99f6a7d8a8e3e0213b3cad0daf0ea974bf58e3f +zippy 0.10.16 https://github.com/treeform/zippy a99f6a7d8a8e3e0213b3cad0daf0ea974bf58e3f flatty 0.3.4 https://github.com/treeform/flatty 05d878b397933331966a7f80dd0c55664559201f -nimsimd 1.3.2 https://github.com/guzba/nimsimd 3f6b2668ffb0867d0bf786a658b817763e611350 +nimsimd 1.3.2 https://github.com/treeform/nimsimd 3f6b2668ffb0867d0bf786a658b817763e611350 bumpy 1.1.3 https://github.com/treeform/bumpy dc9a3d6d15680ec7f603959d65ba8ee4f1ddbc72 -crunchy 0.1.11 https://github.com/guzba/crunchy 98eb6526982bb8aae8eec6e8781f4539fa19e049 +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 8e1e2499a050bcbb1546f239b8c3a8b1b16748c0 +windy 0.5.0 https://github.com/treeform/windy bf6b93d872de6826a69b34752c6d766e46204530 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 jsony 1.1.6 https://github.com/treeform/jsony bb647e1ca21af25ffdc423bcb96feeeeae963ca2 dx12 0.1.0 https://github.com/treeform/dx12 2b50efe4211d0df41237d3b1d121566ccdea2d15 -metal4 0.1.0 https://github.com/treeform/metal4 2ee853339f6444a8844a5e4156e726ee52530bef +metal4 0.1.0 https://github.com/treeform/metal4 eaec6cef21c446d512bbf18e6fa949eeae47a583 vk14 0.1.0 https://github.com/treeform/vk14 545a3b1516234ab4471c8f4c7b59b378c2de2c2c fluffy 1.0.0 https://github.com/treeform/fluffy 2012906732cc104dc08fb80a3cec976ddfd9a98a diff --git a/src/silky/atlas.nim b/src/silky/atlas.nim index cfe83e60..8389e8f0 100644 --- a/src/silky/atlas.nim +++ b/src/silky/atlas.nim @@ -80,6 +80,13 @@ proc skipHook*(T: typedesc[FontAtlasObject], key: static string): bool = ## Skips runtime-only lookup tables during atlas JSON serialization. key == "lookup" +proc rasterScale*(fontAtlas: FontAtlas): float32 {.inline.} = + ## Returns physical glyph density while accepting legacy atlas metadata. + if fontAtlas.pixelScale > 0: + fontAtlas.pixelScale + else: + 1.0'f + proc kerningKey(left, right: Rune): uint64 {.inline.} = ## Packs two Unicode scalar values into one table key. (uint64(uint32(int32(left))) shl 32) or uint64(uint32(int32(right))) @@ -439,6 +446,7 @@ proc addFont*( fontAtlas.ascent = typeface.ascent * logicalScale fontAtlas.descent = typeface.descent * logicalScale fontAtlas.lineGap = typeface.lineGap * logicalScale + fontObj.size = size * density # If subpixelSteps > 0, generates multiple versions of each glyph shifted by 1/subpixelSteps pixels. # For example, subpixelSteps=10 generates 10 versions per glyph at 0.0, 0.1, 0.2, ... 0.9 pixel offsets. let numVariants = if subpixelSteps > 0: subpixelSteps else: 1 @@ -447,7 +455,7 @@ proc addFont*( let rune = glyphStr.runeAt(0) glyphPath = typeface.getGlyphPath(rune) - scale = logicalScale * density + scale = fontObj.scale scaleMat = scale(vec2(scale)) baseBounds = glyphPath.computeBounds(scaleMat).snapToPixels().finiteBounds() advance = typeface.getAdvance(rune) * logicalScale diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index d463d645..a918c247 100644 --- a/src/silky/contexts.nim +++ b/src/silky/contexts.nim @@ -1,10 +1,10 @@ import std/[algorithm, tables, unicode, times], pixie, vmath, windy, bumpy, - silky/[atlas, clips, frames, layout, profiles], + silky/[atlas, clips, common, frames, interactions, scrolls, layout, profiles], silky/internal/inputs -export frames, layout, profiles +export frames, interactions, scrolls, layout, profiles when defined(useDirectX): import silky/drawers/dx12 @@ -69,13 +69,6 @@ type menuPopupHoverColor*: ColorRGBX = rgbx(80, 80, 100, 255) menuPopupSelectedColor*: ColorRGBX = rgbx(60, 60, 80, 255) - Interactor* = object - ## Solve which widget the mouse is interacting with. - currentId*: int = -1 - warmId*: int = -1 - warmLayer*: int = -1 - hotId*: int = -1 - Silky* = ref object ## Main Silky context shared across rendering backends. inFrame: bool = false @@ -119,6 +112,9 @@ type frameTime*: float64 avgFrameTime*: float64 interactor*: Interactor + touchScroll*: TouchScroll + touchOrigin*: Vec2 + ## Logical window offset applied when the app removes safe-area insets. window: Window proc currentDrawLayer*(sk: Silky): int = @@ -133,7 +129,7 @@ proc renderMode*(sk: Silky): RenderMode = sk.frames.mode proc requestFrame*(sk: Silky, delayMs = 0) = - ## Invalidates app data or schedules a visible animation on the UI thread. + ## Invalidates data or schedules an animation frame on the UI thread. sk.frames.requestFrame(delayMs) proc `renderMode=`*(sk: Silky, mode: RenderMode) = @@ -357,19 +353,27 @@ proc shouldShowTooltip*(sk: Silky): bool = sk.hover and sk.mouseIdleTime >= sk.tooltipThreshold proc resetInteractions*(sk: Silky) = - ## Clear all interaction state. - sk.interactor.hotId = -1 - sk.interactor.warmId = -1 - sk.interactor.warmLayer = -1 + ## Invalidates cached pointer targets. + sk.interactor.resetInteractions() + sk.touchScroll.resetTouchScroll() proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = ## Starts a frame and updates the shared UI state. + sk.cursor = Cursor(kind: ArrowCursor) if sk.frames.mode == OnDemandRender: sk.frameHadInput = sk.frameInput.inputChanged( window, sk.inputs.hasPendingEvents() ) sk.frames.beginFrame() - sk.cursor = Cursor(kind: ArrowCursor) + sk.touchScroll.beginTouchFrame( + window.pointerSource == TouchPointer, + window.buttonPressed[MouseLeft], window.buttonDown[MouseLeft], + window.buttonReleased[MouseLeft], window.focused, + window.mousePos.vec2 / sk.uiScale, + window.mouseDelta.vec2 / sk.uiScale, + velocity = window.pointerVelocity / sk.uiScale, + interrupted = window.scrollDelta != vec2(0) + ) sk.inputs.beginInputFrame(window) beginProfileFrame() @@ -404,19 +408,14 @@ proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = proc clear*(sk: Silky) -proc endInteractions(interactor: var Interactor) = - ## Commit warm state and resets per-frame counters. - interactor.hotId = interactor.warmId - interactor.warmId = -1 - interactor.warmLayer = -1 - interactor.currentId = -1 - proc endUiShared*(sk: Silky) = ## Ends a frame after the backend has finished drawing. if sk.frames.mode == OnDemandRender: if sk.frameHadInput or sk.interactor.hotId != sk.interactor.warmId: sk.requestFrame() - if sk.window.buttonDown[MouseLeft]: + if sk.touchScroll.momentumActive(): + sk.requestFrame() + elif sk.window.buttonDown[MouseLeft]: sk.requestFrame(16) let previousCursor = sk.window.cursor if previousCursor.kind != sk.cursor.kind or @@ -424,9 +423,8 @@ proc endUiShared*(sk: Silky) = (previousCursor.image != sk.cursor.image or previousCursor.hotspot != sk.cursor.hotspot)): sk.window.cursor = sk.cursor - if sk.window.buttonReleased[MouseLeft]: - sk.resetInteractions() sk.interactor.endInteractions() + sk.touchScroll.endTouchFrame() sk.clear() sk.popLayout() sk.popClipRect() @@ -543,6 +541,29 @@ proc drawQuad*( maskUv: m3 )) +proc drawTexture*( + sk: Silky, + texture: uint32, + pos, size, pixels: Vec2, + color = rgbx(255, 255, 255, 255) +) = + ## Queues an independent image with ordinary clipping and layer ordering. + if texture == 0 or size.x <= 0 or size.y <= 0: + return + when not defined(useDirectX) and + not defined(useVulkan) and + not defined(useCpu): + let + layer = sk.drawer.currentLayer + first = sk.drawer.layers[layer].len + sk.drawQuad(pos, size, vec2(0), pixels, color) + for i in first ..< sk.drawer.layers[layer].len: + sk.drawer.layers[layer][i].texture = texture + else: + raise newException( + SilkyError, "Independent image textures require the OpenGL or Metal drawer." + ) + proc drawTriangle*( sk: Silky, positions: array[3, Vec2], @@ -810,10 +831,50 @@ proc uploadAtlas*(sk: Silky) = ## Push the current CPU atlas image to the GPU drawer. when not defined(useDirectX) and not defined(useVulkan) and - not defined(useMetal4) and not defined(useCpu): sk.drawer.uploadAtlas(sk.image) +proc uploadAtlasRegion*(sk: Silky, x, y, width, height: int) = + ## Uploads a changed atlas rectangle without replacing the whole texture. + when not defined(useDirectX) and + not defined(useVulkan) and + not defined(useCpu): + sk.drawer.uploadAtlasRegion(sk.image, x, y, width, height) + +proc allocateTexture*(sk: Silky, width, height: int): uint32 = + ## Reserves independent image storage without changing the font atlas. + when not defined(useDirectX) and + not defined(useVulkan) and + not defined(useCpu): + sk.drawer.allocateTexture(width, height) + else: + raise newException( + SilkyError, "Independent image textures require the OpenGL or Metal drawer." + ) + +proc uploadTextureRows*( + sk: Silky, + texture: uint32, + image: Image, + firstRow, rowCount: int +) = + ## Uploads selected image rows for incremental preparation across frames. + when not defined(useDirectX) and + not defined(useVulkan) and + not defined(useCpu): + sk.drawer.uploadTextureRows(texture, image, firstRow, rowCount) + else: + raise newException( + SilkyError, "Independent image textures require the OpenGL or Metal drawer." + ) + +proc deleteTexture*(sk: Silky, texture: uint32) = + ## Releases independent image storage after its last queued frame. + when not defined(useDirectX) and + not defined(useVulkan) and + not defined(useCpu): + sk.drawer.deleteTexture(texture) + proc addAtlasImage*(sk: Silky, name: string, image: Image) = ## Pack an image into the runtime atlas and reupload the GPU texture. if sk.builder == nil: @@ -903,21 +964,14 @@ proc draw9Patch*( rightS = right * scale * density bottomS = bottom * scale * density leftS = left * scale * density - l = (left * scale).float32 - r = (right * scale).float32 - u = (top * scale).float32 - d = (bottom * scale).float32 displayScale = max(sk.uiScale, 0.001'f) - alignedPos = - if density > 1: - alignPixels(pos, displayScale) - else: - pos - alignedSize = - if density > 1: - alignPixels(pos + size, displayScale) - alignedPos - else: - size + l = round((left * scale).float32 * displayScale) / displayScale + r = round((right * scale).float32 * displayScale) / displayScale + u = round((top * scale).float32 * displayScale) / displayScale + d = round((bottom * scale).float32 * displayScale) / displayScale + alignedPos = alignPixels(pos, displayScale) + # Size must not change as the position crosses a pixel boundary. + alignedSize = alignPixels(size, displayScale) srcXOffsets = [0.int, leftS, uv.width - rightS] srcWidths = [leftS, uv.width - leftS - rightS, rightS] srcYOffsets = [0.int, topS, uv.height - bottomS] @@ -1104,15 +1158,21 @@ proc endUi*(sk: Silky) = proc buttonDown*(sk: Silky): ButtonView = ## Returns held buttons, excluding keyboard keys during text entry. - sk.inputs.filterButtons(sk.window.buttonDown) + result = sk.inputs.filterButtons(sk.window.buttonDown) + if sk.touchScrolling: + result = ButtonView(set[Button](result) - {MouseLeft}) proc buttonPressed*(sk: Silky): ButtonView = ## Returns pressed buttons, excluding keyboard keys during text entry. - sk.inputs.filterButtons(sk.window.buttonPressed) + result = sk.inputs.filterButtons(sk.window.buttonPressed) + if sk.touchScrolling: + result = ButtonView(set[Button](result) - {MouseLeft}) proc buttonReleased*(sk: Silky): ButtonView = ## Returns released buttons, excluding keyboard keys during text entry. - sk.inputs.filterButtons(sk.window.buttonReleased) + result = sk.inputs.filterButtons(sk.window.buttonReleased) + if sk.touchScrolling: + result = ButtonView(set[Button](result) - {MouseLeft}) when not defined(useDirectX) and not defined(useVulkan) and diff --git a/src/silky/drawers/metal4.nim b/src/silky/drawers/metal4.nim index dbd8d125..9d6b121e 100644 --- a/src/silky/drawers/metal4.nim +++ b/src/silky/drawers/metal4.nim @@ -1,11 +1,16 @@ -when not defined(macosx): - {.error: "The Silky Metal 4 backend requires macOS.".} +when not (defined(macosx) or defined(ios)): + {.error: "The Silky Metal backend requires macOS or iOS.".} import - pixie, vmath, windy, pkg/metal4 + std/tables, + pixie, shady, vmath, windy, pkg/metal4, + ../common, shader const InitialVertexCapacity = 4096 + VertexBufferIndex = 1 + VertexShaderSource = toMSL(silkyVert, shaderVertex) + FragmentShaderSource = toMSL(silkyFrag, shaderFragment) type DrawerVertex* {.packed.} = object @@ -16,6 +21,17 @@ type clipPos*: Vec2 clipSize*: Vec2 maskUv*: Vec2 + texture*: uint32 + + DrawerTexture = object + ## A logical image handle owns a native texture and its pixel dimensions. + texture: MTLTexture + size: IVec2 + + ShaderUniforms = object + ## Matches the Shady vertex shader's constant buffer layout. + viewportSize: Vec2 + atlasSize: Vec2 Drawer* = ref object ## Metal 4-backed drawer state. @@ -27,160 +43,250 @@ type vertexBufferPtr: pointer maxVertexCount: int viewportSize: IVec2 + atlasSize: IVec2 + textureLimit: int + textures: Table[uint32, DrawerTexture] + nextTexture: uint32 clearColor: MTLClearColor + when defined(silkyMetalTesting): + ownsTestDevice: bool layers*: array[2, seq[DrawerVertex]] currentLayer*: int layerStack*: seq[int] +static: + doAssert sizeof(DrawerVertex) == 48 + doAssert sizeof(ShaderUniforms) == 16 + doAssert offsetOf(ShaderUniforms, viewportSize) == 0 + doAssert offsetOf(ShaderUniforms, atlasSize) == 8 + +objc: + proc supportsFamily(self: MTLDevice, x: int): bool + +proc textureSizeLimit(device: MTLDevice): int = + ## Reads Metal's family-specific 2D texture limit, including Simulator. + # https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf + # Simulator exposes Apple2 even when its host supports newer families. + if device.supportsFamily(1010): # MTLGPUFamilyApple10. + 32768 + elif device.supportsFamily(1003) or # MTLGPUFamilyApple3. + device.supportsFamily(2001) or # MTLGPUFamilyMac1. + device.supportsFamily(2002): # MTLGPUFamilyMac2. + 16384 + else: + 8192 + +proc maxTextureSize*(drawer: Drawer): int = + ## Returns the active GPU's maximum 2D texture width and height. + drawer.textureLimit + proc clampViewport(size: IVec2): IVec2 = ## Clamps the viewport to valid drawable dimensions. ivec2(max(1'i32, size.x), max(1'i32, size.y)) -proc normalizeVertices( - vertices: var seq[DrawerVertex], - viewportSize: IVec2, - atlasSize: Vec2 +proc close*(drawer: Drawer) = + ## Releases all drawer-owned Metal resources after its synchronous frames. + if drawer.isNil: + return + for texture in drawer.textures.values: + texture.texture.release() + drawer.textures.clear() + drawer.texture.release() + drawer.texture = 0.MTLTexture + drawer.sampler.release() + drawer.sampler = 0.MTLSamplerState + drawer.pipelineState.release() + drawer.pipelineState = 0.MTLRenderPipelineState + drawer.vertexBuffer.release() + drawer.vertexBuffer = 0.MTLBuffer + drawer.vertexBufferPtr = nil + drawer.maxVertexCount = 0 + when defined(silkyMetalTesting): + if drawer.ownsTestDevice: + drawer.ctx.device.release() + drawer.ownsTestDevice = false + drawer.ctx.destroy() + +proc newTexture(state: Drawer, width, height: int): MTLTexture = + ## Allocates a shader-readable texture using the supported 2D size limit. + if width <= 0 or height <= 0: + raise newException(SilkyError, "Image texture dimensions must be positive.") + if width > state.textureLimit or height > state.textureLimit: + raise newException(SilkyError, + "Image texture " & $width & "x" & $height & + " exceeds this Metal device's " & $state.textureLimit & + " pixel size limit.") + let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( + MTLPixelFormatRGBA8Unorm, + width.uint, + height.uint, + false + ) + descriptor.setUsage(MTLTextureUsageShaderRead) + result = state.ctx.device.newTextureWithDescriptor(descriptor) + if result.isNil: + raise newException(SilkyError, "Could not allocate a Metal image texture.") + +proc uploadRegion( + texture: MTLTexture, + image: Image, + x, y, width, height: int ) = - ## Converts queued pixel-space vertices to clip-space and normalized UVs. - let - width = max(1.0'f, viewportSize.x.float32) - height = max(1.0'f, viewportSize.y.float32) - for i in 0 ..< vertices.len: - let p = vertices[i].pos - vertices[i].pos = vec2( - (p.x / width) * 2.0'f - 1.0'f, - 1.0'f - (p.y / height) * 2.0'f - ) - vertices[i].uv = vertices[i].uv / atlasSize + ## Uploads image pixels with their original row stride into a texture region. + texture.replaceRegion( + MTLRegion( + origin: MTLOrigin(x: x.uint, y: y.uint, z: 0), + size: MTLSize(width: width.uint, height: height.uint, depth: 1) + ), + 0, + unsafeAddr image.data[y * image.width + x], + (image.width * sizeof(ColorRGBX)).uint + ) proc createVertexBuffer(state: Drawer, maxVertexCount: int) = ## Creates or replaces the persistently mapped vertex buffer. - state.vertexBuffer = state.ctx.device.newBufferWithLength( + let buffer = state.ctx.device.newBufferWithLength( (maxVertexCount * sizeof(DrawerVertex)).uint, 0 ) - checkNil(state.vertexBuffer, "Could not create a Metal vertex buffer") - state.vertexBufferPtr = state.vertexBuffer.contents() - checkNil(state.vertexBufferPtr, "Could not map the Metal vertex buffer") + checkNil(buffer, "Could not create a Metal vertex buffer") + let bufferPtr = buffer.contents() + checkNil(bufferPtr, "Could not map the Metal vertex buffer") + state.vertexBuffer.release() + state.vertexBuffer = buffer + state.vertexBufferPtr = bufferPtr state.maxVertexCount = maxVertexCount proc uploadTexture(state: Drawer, image: Image) = ## Uploads the atlas image into one Metal texture. - let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( - MTLPixelFormatRGBA8Unorm, - image.width.uint, - image.height.uint, - false + if image.isNil: + raise newException(SilkyError, "Cannot upload an empty atlas image.") + if state.texture.isNil or + state.atlasSize != ivec2(image.width.int32, image.height.int32): + let texture = state.newTexture(image.width, image.height) + state.texture.release() + state.texture = texture + state.texture.uploadRegion(image, 0, 0, image.width, image.height) + state.atlasSize = ivec2(image.width.int32, image.height.int32) + +proc allocateTexture*(drawer: Drawer, width, height: int): uint32 = + ## Allocates a separate image texture, reserving handle zero for the atlas. + if drawer.nextTexture == high(uint32): + raise newException(SilkyError, "Image texture handles are exhausted.") + let texture = drawer.newTexture(width, height) + inc drawer.nextTexture + result = drawer.nextTexture + drawer.textures[result] = DrawerTexture( + texture: texture, + size: ivec2(width.int32, height.int32) ) - descriptor.setUsage(MTLTextureUsageShaderRead) - state.texture = state.ctx.device.newTextureWithDescriptor(descriptor) - checkNil(state.texture, "Could not create the atlas texture") - state.texture.replaceRegion( - MTLRegion( - origin: MTLOrigin(x: 0, y: 0, z: 0), - size: MTLSize( - width: image.width.uint, - height: image.height.uint, - depth: 1 - ) - ), - 0, - unsafeAddr image.data[0], - (image.width * 4).uint - ) +proc uploadTextureRows*( + drawer: Drawer, + texture: uint32, + image: Image, + firstRow, rowCount: int +) = + ## Uploads a bounded set of full-width rows into a separate image texture. + if texture notin drawer.textures or image.isNil: + raise newException(SilkyError, "Cannot upload an unknown image texture.") + let target = drawer.textures[texture] + if target.size != ivec2(image.width.int32, image.height.int32) or + firstRow < 0 or rowCount < 0 or firstRow > image.height or + rowCount > image.height - firstRow: + raise newException(SilkyError, "Image texture upload bounds are invalid.") + if rowCount == 0: + return + target.texture.uploadRegion(image, 0, firstRow, image.width, rowCount) + +proc deleteTexture*(drawer: Drawer, texture: uint32) = + ## Releases an independent image texture; deleting a missing handle is safe. + if texture notin drawer.textures: + return + drawer.textures[texture].texture.release() + drawer.textures.del(texture) + +proc uploadAtlasRegion*( + drawer: Drawer, + image: Image, + x, y, width, height: int +) = + ## Refreshes changed atlas pixels, replacing the texture after atlas growth. + if width <= 0 or height <= 0: + return + if image.isNil: + raise newException(SilkyError, "Cannot upload an empty atlas image.") + if drawer.atlasSize != ivec2(image.width.int32, image.height.int32): + drawer.uploadTexture(image) + return + let + left = clamp(x, 0, image.width) + top = clamp(y, 0, image.height) + right = clamp(x.int64 + width.int64, 0'i64, image.width.int64).int + bottom = clamp(y.int64 + height.int64, 0'i64, image.height.int64).int + if right <= left or bottom <= top: + return + drawer.texture.uploadRegion(image, left, top, right - left, bottom - top) proc initRenderer(state: Drawer, image: Image, size: IVec2) = ## Creates the Metal pipeline, atlas texture, and dynamic buffers. - const ShaderSource = """ -#include -using namespace metal; - -struct DrawerVertex { - packed_float2 pos; - packed_float2 uv; - uchar4 color; - packed_float2 clipPos; - packed_float2 clipSize; - packed_float2 maskUv; -}; - -struct VertexOut { - float4 position [[position]]; - float2 uv; - float4 color; - float2 clipPos; - float2 clipSize; - float2 maskUv; -}; - -vertex VertexOut vertexMain( - uint vertexId [[vertex_id]], - constant DrawerVertex *vertices [[buffer(0)]] -) { - VertexOut out; - DrawerVertex inVertex = vertices[vertexId]; - out.position = float4(float2(inVertex.pos), 0.0, 1.0); - out.uv = float2(inVertex.uv); - out.color = float4(inVertex.color) / 255.0; - out.clipPos = float2(inVertex.clipPos); - out.clipSize = float2(inVertex.clipSize); - out.maskUv = float2(inVertex.maskUv); - return out; -} - -fragment float4 fragmentMain(VertexOut in [[stage_in]]) { - if (in.position.x < in.clipPos.x || - in.position.y < in.clipPos.y || - in.position.x > in.clipPos.x + in.clipSize.x || - in.position.y > in.clipPos.y + in.clipSize.y) { - discard_fragment(); - } - return float4(1.0); -} - -fragment float4 texturedFragmentMain( - VertexOut in [[stage_in]], - texture2d tex [[texture(0)]], - sampler texSampler [[sampler(0)]] -) { - // Fetch before clipping so discarded neighbors keep valid derivatives. - float4 base = tex.sample(texSampler, in.uv); - float4 shaded = base * in.color; - if (in.maskUv.x >= 0.0) { - float maskR = tex.sample(texSampler, in.maskUv).r; - shaded = float4(base.rgb * mix(float3(1.0), in.color.rgb, maskR), base.a * in.color.a); - } - if (in.position.x < in.clipPos.x || - in.position.y < in.clipPos.y || - in.position.x > in.clipPos.x + in.clipSize.x || - in.position.y > in.clipPos.y + in.clipSize.y) { - discard_fragment(); - } - return shaded; -} -""" - + state.textureLimit = state.ctx.device.textureSizeLimit() var error: NSError - let library = state.ctx.device.newLibraryWithSource( - @ShaderSource, + let vertexLibrary = state.ctx.device.newLibraryWithSource( + @VertexShaderSource, 0.ID, error.addr ) - checkNSError(error, "Could not compile the Metal shaders") - checkNil(library, "Metal shader library was nil") - - let vertexFunction = library.newFunctionWithName(@"vertexMain") - checkNil(vertexFunction, "Could not load Metal shader entry point: vertexMain") + checkNSError(error, "Could not compile the Shady Metal vertex shader") + checkNil(vertexLibrary, "Metal vertex library was nil") + defer: vertexLibrary.release() - let fragmentFunction = library.newFunctionWithName(@"texturedFragmentMain") - checkNil( - fragmentFunction, - "Could not load Metal shader entry point: texturedFragmentMain" + error = 0.NSError + let fragmentLibrary = state.ctx.device.newLibraryWithSource( + @FragmentShaderSource, + 0.ID, + error.addr ) + checkNSError(error, "Could not compile the Shady Metal fragment shader") + checkNil(fragmentLibrary, "Metal fragment library was nil") + defer: fragmentLibrary.release() + + let + vertexFunction = vertexLibrary.newFunctionWithName(@"vertexMain") + fragmentFunction = fragmentLibrary.newFunctionWithName(@"fragmentMain") + checkNil(vertexFunction, "Could not load Shady's Metal vertex entry point") + checkNil(fragmentFunction, "Could not load Shady's Metal fragment entry point") + defer: vertexFunction.release() + defer: fragmentFunction.release() + + let vertexDescriptor = MTLVertexDescriptor.alloc().init() + checkNil(vertexDescriptor, "Could not create a Metal vertex descriptor") + defer: vertexDescriptor.release() + const Offsets = [ + offsetOf(DrawerVertex, pos), + offsetOf(DrawerVertex, uv), + offsetOf(DrawerVertex, color), + offsetOf(DrawerVertex, clipPos), + offsetOf(DrawerVertex, clipSize), + offsetOf(DrawerVertex, maskUv) + ] + for i, offset in Offsets: + let attribute = vertexDescriptor.attributes().objectAtIndexedSubscript( + i.uint + ) + attribute.setFormat( + if i == 2: MTLVertexFormatUChar4Normalized else: MTLVertexFormatFloat2 + ) + attribute.setOffset(offset.uint) + attribute.setBufferIndex(VertexBufferIndex) + vertexDescriptor.layouts().objectAtIndexedSubscript( + VertexBufferIndex + ).setStride(sizeof(DrawerVertex).uint) let pipelineDescriptor = MTLRenderPipelineDescriptor.alloc().init() checkNil(pipelineDescriptor, "Could not create a pipeline descriptor") + defer: pipelineDescriptor.release() + pipelineDescriptor.setVertexDescriptor(vertexDescriptor) let colorAttachment = pipelineDescriptor.colorAttachments().objectAtIndexedSubscript(0) pipelineDescriptor.setVertexFunction(vertexFunction) @@ -208,6 +314,7 @@ fragment float4 texturedFragmentMain( let samplerDescriptor = MTLSamplerDescriptor.alloc().init() checkNil(samplerDescriptor, "Could not create a sampler descriptor") + defer: samplerDescriptor.release() samplerDescriptor.setMinFilter(MTLSamplerMinMagFilterLinear) samplerDescriptor.setMagFilter(MTLSamplerMinMagFilterLinear) samplerDescriptor.setMipFilter(MTLSamplerMipFilterNotMipmapped) @@ -222,6 +329,10 @@ fragment float4 texturedFragmentMain( state.createVertexBuffer(InitialVertexCapacity) state.uploadTexture(image) +proc uploadAtlas*(drawer: Drawer, image: Image) = + ## Replaces the atlas texture after runtime glyph or image additions. + drawer.uploadTexture(image) + proc newDrawer*(window: Window, image: Image): Drawer = ## Creates a new Metal drawer and eagerly initializes its resources. let safeSize = clampViewport(window.size) @@ -233,8 +344,12 @@ proc newDrawer*(window: Window, image: Image): Drawer = ) result.layers[0] = @[] result.layers[1] = @[] - result.ctx = newMetalContext(window) - result.initRenderer(image, safeSize) + try: + result.ctx = newMetalContext(window) + result.initRenderer(image, safeSize) + except: + result.close() + raise proc beginFrame*(drawer: Drawer, window: Window, size: IVec2) = ## Prepares the Metal drawer for a new frame. @@ -261,37 +376,88 @@ proc ensureVertexCapacity(state: Drawer, vertexCount: int) = newCapacity *= 2 state.createVertexBuffer(newCapacity) -proc recordDraw(state: Drawer, vertexCount: int) = - ## Records the Metal draw pass for the current frame. - let drawable = state.ctx.currentDrawable() - if drawable.isNil: - return - - let - commandBuffer = state.ctx.newCommandBuffer() - renderPass = state.ctx.clearPass(drawable, state.clearColor) - encoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPass) - checkNil(encoder, "Could not create a Metal render encoder") +proc encodeDraw( + state: Drawer, + encoder: MTLRenderCommandEncoder, + width, height: float64, + vertexCount: int +) = + ## Encodes contiguous texture batches without reordering layers or clipping. encoder.setRenderPipelineState(state.pipelineState) encoder.setViewport( MTLViewport( originX: 0, originY: 0, - width: state.ctx.layer.drawableSize().width, - height: state.ctx.layer.drawableSize().height, + width: width, + height: height, znear: 0, zfar: 1 ) ) encoder.setCullMode(MTLCullModeNone) - encoder.setVertexBuffer(state.vertexBuffer, 0, 0) - encoder.setFragmentTexture(state.texture, 0) + encoder.setVertexBuffer(state.vertexBuffer, 0, VertexBufferIndex) encoder.setFragmentSamplerState(state.sampler, 0) - if vertexCount > 0: - encoder.drawPrimitives(MTLPrimitiveTypeTriangle, 0, vertexCount.uint) + let vertices = cast[ptr UncheckedArray[DrawerVertex]](state.vertexBufferPtr) + var first = 0 + while first < vertexCount: + let textureId = vertices[first].texture + var last = first + 1 + while last < vertexCount and vertices[last].texture == textureId: + inc last + var target = DrawerTexture(texture: state.texture, size: state.atlasSize) + if textureId != 0: + if textureId notin state.textures: + first = last + continue + target = state.textures[textureId] + var uniforms = ShaderUniforms( + viewportSize: state.viewportSize.vec2, + atlasSize: target.size.vec2 + ) + encoder.setVertexBytes(uniforms.addr, sizeof(uniforms).uint, 0) + encoder.setFragmentTexture(target.texture, 0) + encoder.drawPrimitives( + MTLPrimitiveTypeTriangle, + first.uint, + (last - first).uint + ) + first = last + +proc recordDraw(state: Drawer, vertexCount: int) = + ## Records the Metal draw pass for the current frame. + let drawable = state.ctx.currentDrawable() + if drawable.isNil: + return + let + commandBuffer = state.ctx.newCommandBuffer() + renderPass = state.ctx.clearPass(drawable, state.clearColor) + encoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPass) + size = state.ctx.layer.drawableSize() + checkNil(encoder, "Could not create a Metal render encoder") + state.encodeDraw(encoder, size.width, size.height, vertexCount) encoder.endEncoding() commandBuffer.presentDrawable(drawable) commandBuffer.commit() + # Keep the shared vertex buffer available for the next CPU frame. + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "Metal failed to render the Silky frame") + +proc uploadVertices( + drawer: Drawer, + image: Image, + vertices: pointer, + vertexCount: int +) = + ## Updates the atlas and shared vertex buffer before a render pass. + if drawer.atlasSize != ivec2(image.width.int32, image.height.int32): + drawer.uploadTexture(image) + drawer.ensureVertexCapacity(vertexCount) + if vertexCount > 0: + copyMem( + drawer.vertexBufferPtr, + vertices, + vertexCount * sizeof(DrawerVertex) + ) proc endFrame*( drawer: Drawer, @@ -302,22 +468,85 @@ proc endFrame*( ) = ## Flushes the queued quads through Metal 4. discard size - let - atlasSize = vec2(image.width.float32, image.height.float32) - vertexCount = quadCount - drawer.ensureVertexCapacity(vertexCount) - - var vertices = newSeqOfCap[DrawerVertex](vertexCount) - let quadsArr = cast[ptr UncheckedArray[DrawerVertex]](quads) - for i in 0 ..< quadCount: - vertices.add(quadsArr[i]) - vertices.normalizeVertices(drawer.viewportSize, atlasSize) - - if vertexCount > 0: - copyMem( - drawer.vertexBufferPtr, - unsafeAddr vertices[0], - vertexCount * sizeof(DrawerVertex) + drawer.uploadVertices(image, quads, quadCount) + drawer.recordDraw(quadCount) + +when defined(silkyMetalTesting): + objc: + proc setStorageMode(self: MTLTextureDescriptor, x: uint) + proc getBytes( + self: MTLTexture, + x: pointer, + bytesPerRow: uint, + fromRegion: MTLRegion, + mipmapLevel: uint ) - drawer.recordDraw(vertexCount) + proc newOffscreenDrawerForTesting*(image: Image, size: IVec2): Drawer = + ## Creates the production drawer without a window for GPU pixel tests. + result = Drawer( + clearColor: MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1) + ) + try: + result.ctx.device = MTLCreateSystemDefaultDevice() + checkNil(result.ctx.device, "The pixel test requires a Metal device") + result.ownsTestDevice = true + result.ctx.commandQueue = result.ctx.device.newCommandQueue() + checkNil(result.ctx.commandQueue, "Could not create the test queue") + result.initRenderer(image, size) + except: + result.close() + raise + + proc renderPixelsForTesting*( + drawer: Drawer, + image: Image, + vertices: openArray[DrawerVertex] + ): Image = + ## Renders through the production batching code and reads its output pixels. + let + width = drawer.viewportSize.x.int + height = drawer.viewportSize.y.int + descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( + MTLPixelFormatBGRA8Unorm, + width.uint, + height.uint, + false + ) + descriptor.setUsage(MTLTextureUsageRenderTarget) + descriptor.setStorageMode(0) # Shared storage allows synchronized CPU reads. + let target = drawer.ctx.device.newTextureWithDescriptor(descriptor) + checkNil(target, "Could not create the pixel test render target") + defer: target.release() + drawer.uploadVertices( + image, + if vertices.len > 0: unsafeAddr vertices[0] else: nil, + vertices.len + ) + let + commandBuffer = drawer.ctx.newCommandBuffer() + renderPass = MTLRenderPassDescriptor.renderPassDescriptor() + attachment = renderPass.colorAttachments().objectAtIndexedSubscript(0) + attachment.setTexture(target) + attachment.setLoadAction(MTLLoadActionClear) + attachment.setStoreAction(MTLStoreActionStore) + attachment.setClearColor(drawer.clearColor) + let encoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPass) + checkNil(encoder, "Could not create the pixel test render encoder") + drawer.encodeDraw(encoder, width.float64, height.float64, vertices.len) + encoder.endEncoding() + commandBuffer.commit() + commandBuffer.waitUntilCompleted() + checkNSError(commandBuffer.error(), "Metal failed to render test pixels") + result = newImage(width, height) + target.getBytes( + result.data[0].addr, + (width * sizeof(ColorRGBX)).uint, + MTLRegion( + origin: MTLOrigin(x: 0, y: 0, z: 0), + size: MTLSize(width: width.uint, height: height.uint, depth: 1) + ), + 0 + ) + for pixel in result.data.mitems: + swap(pixel.r, pixel.b) diff --git a/src/silky/drawers/ogl.nim b/src/silky/drawers/ogl.nim index 254300f4..6b6ce70d 100644 --- a/src/silky/drawers/ogl.nim +++ b/src/silky/drawers/ogl.nim @@ -1,7 +1,7 @@ import - std/[strformat, strutils], + std/[strformat, strutils, tables], pixie, opengl, shady, vmath, windy, - silky/drawers/shader + silky/common, silky/drawers/shader type BufferKind* = enum @@ -40,6 +40,11 @@ type clipPos*: Vec2 clipSize*: Vec2 maskUv*: Vec2 + texture*: uint32 + + DrawerTexture = object + id: GLuint + size: IVec2 Drawer* = ref object ## OpenGL-backed drawer state. @@ -47,6 +52,9 @@ type vao: GLuint instanceVbo: GLuint atlasTexture: GLuint + atlasSize: IVec2 + textures: Table[uint32, DrawerTexture] + nextTexture: uint32 layers*: array[2, seq[DrawerVertex]] currentLayer*: int layerStack*: seq[int] @@ -479,6 +487,225 @@ proc uploadAtlas*(drawer: Drawer, image: Image) = cast[pointer](image.data[0].addr) ) glGenerateMipmap(GL_TEXTURE_2D) + drawer.atlasSize = ivec2(image.width.int32, image.height.int32) + +proc allocateTexture*(drawer: Drawer, width, height: int): uint32 = + ## Allocates an independent image texture without growing the font atlas. + if width <= 0 or height <= 0: + raise newException(SilkyError, "Image texture dimensions must be positive.") + var maximum: GLint + glGetIntegerv(GL_MAX_TEXTURE_SIZE, maximum.addr) + if width > maximum or height > maximum: + raise newException(SilkyError, "Image texture exceeds the GPU size limit.") + var + texture, unpackBuffer: GLint + id: GLuint + allocated = false + glGetIntegerv(GL_TEXTURE_BINDING_2D, texture.addr) + glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, unpackBuffer.addr) + defer: + glBindTexture(GL_TEXTURE_2D, texture.GLuint) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBuffer.GLuint) + if not allocated and id != 0: + glDeleteTextures(1, id.addr) + glGenTextures(1, id.addr) + glBindTexture(GL_TEXTURE_2D, id) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE.GLint) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE.GLint) + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA8.GLint, + width.GLsizei, + height.GLsizei, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + nil + ) + inc drawer.nextTexture + result = drawer.nextTexture + drawer.textures[result] = DrawerTexture( + id: id, size: ivec2(width.int32, height.int32) + ) + allocated = true + +proc uploadTextureRows*( + drawer: Drawer, + texture: uint32, + image: Image, + firstRow, rowCount: int +) = + ## Transfers a bounded set of image rows without touching other textures. + if texture notin drawer.textures or image == nil: + raise newException(SilkyError, "Cannot upload an unknown image texture.") + let target = drawer.textures[texture] + if target.size != ivec2(image.width.int32, image.height.int32) or + firstRow < 0 or rowCount < 0 or firstRow > image.height or + rowCount > image.height - firstRow: + raise newException(SilkyError, "Image texture upload bounds are invalid.") + if rowCount == 0: + return + var + boundTexture, alignment, rowLength, skipRows, skipPixels: GLint + unpackBuffer: GLint + glGetIntegerv(GL_TEXTURE_BINDING_2D, boundTexture.addr) + glGetIntegerv(GL_UNPACK_ALIGNMENT, alignment.addr) + glGetIntegerv(GL_UNPACK_ROW_LENGTH, rowLength.addr) + glGetIntegerv(GL_UNPACK_SKIP_ROWS, skipRows.addr) + glGetIntegerv(GL_UNPACK_SKIP_PIXELS, skipPixels.addr) + glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, unpackBuffer.addr) + defer: + glBindTexture(GL_TEXTURE_2D, boundTexture.GLuint) + glPixelStorei(GL_UNPACK_ALIGNMENT, alignment) + glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength) + glPixelStorei(GL_UNPACK_SKIP_ROWS, skipRows) + glPixelStorei(GL_UNPACK_SKIP_PIXELS, skipPixels) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBuffer.GLuint) + glBindTexture(GL_TEXTURE_2D, target.id) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) + glPixelStorei(GL_UNPACK_ALIGNMENT, 4) + glPixelStorei(GL_UNPACK_ROW_LENGTH, image.width.GLint) + glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) + glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) + glTexSubImage2D( + GL_TEXTURE_2D, + 0, + 0, + firstRow.GLint, + image.width.GLsizei, + rowCount.GLsizei, + GL_RGBA, + GL_UNSIGNED_BYTE, + cast[pointer](image.data[firstRow * image.width].addr) + ) + +proc deleteTexture*(drawer: Drawer, texture: uint32) = + ## Releases an independent texture once its queued draws are finished. + if texture notin drawer.textures: + return + var id = drawer.textures[texture].id + glDeleteTextures(1, id.addr) + drawer.textures.del(texture) + +proc uploadAtlasRegion*( + drawer: Drawer, + image: Image, + x, y, width, height: int +) = + ## Updates changed atlas pixels and only their dependent mipmap rectangles. + if width <= 0 or height <= 0: + return + if drawer.atlasSize != ivec2(image.width.int32, image.height.int32) or + (image.width and (image.width - 1)) != 0 or + (image.height and (image.height - 1)) != 0: + drawer.uploadAtlas(image) + return + var + left = clamp(x, 0, image.width) + top = clamp(y, 0, image.height) + right = clamp(x + width, 0, image.width) + bottom = clamp(y + height, 0, image.height) + if right <= left or bottom <= top: + return + var + alignment, rowLength, skipRows, skipPixels, unpackBuffer: GLint + readFramebuffer, drawFramebuffer: GLint + framebuffers: array[2, GLuint] + glGetIntegerv(GL_UNPACK_ALIGNMENT, alignment.addr) + glGetIntegerv(GL_UNPACK_ROW_LENGTH, rowLength.addr) + glGetIntegerv(GL_UNPACK_SKIP_ROWS, skipRows.addr) + glGetIntegerv(GL_UNPACK_SKIP_PIXELS, skipPixels.addr) + glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, unpackBuffer.addr) + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, readFramebuffer.addr) + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, drawFramebuffer.addr) + let scissor = glIsEnabled(GL_SCISSOR_TEST) + defer: + glPixelStorei(GL_UNPACK_ALIGNMENT, alignment) + glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength) + glPixelStorei(GL_UNPACK_SKIP_ROWS, skipRows) + glPixelStorei(GL_UNPACK_SKIP_PIXELS, skipPixels) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, unpackBuffer.GLuint) + glBindFramebuffer(GL_READ_FRAMEBUFFER, readFramebuffer.GLuint) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFramebuffer.GLuint) + if scissor.bool: + glEnable(GL_SCISSOR_TEST) + glDeleteFramebuffers(2, framebuffers[0].addr) + glActiveTexture(GL_TEXTURE0) + glBindTexture(GL_TEXTURE_2D, drawer.atlasTexture) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) + glPixelStorei(GL_UNPACK_ALIGNMENT, 4) + glPixelStorei(GL_UNPACK_ROW_LENGTH, image.width.GLint) + glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) + glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) + glTexSubImage2D( + GL_TEXTURE_2D, + 0, + left.GLint, + top.GLint, + (right - left).GLsizei, + (bottom - top).GLsizei, + GL_RGBA, + GL_UNSIGNED_BYTE, + cast[pointer](image.data[top * image.width + left].addr) + ) + glDisable(GL_SCISSOR_TEST) + glGenFramebuffers(2, framebuffers[0].addr) + glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffers[0]) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffers[1]) + glReadBuffer(GL_COLOR_ATTACHMENT0) + var attachment = GL_COLOR_ATTACHMENT0 + glDrawBuffers(1, attachment.addr) + var + level = 0 + levelWidth = image.width + levelHeight = image.height + while levelWidth > 1 or levelHeight > 1: + let + nextLeft = left div 2 + nextTop = top div 2 + nextRight = (right + 1) div 2 + nextBottom = (bottom + 1) div 2 + glFramebufferTexture2D( + GL_READ_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + drawer.atlasTexture, + level.GLint + ) + glFramebufferTexture2D( + GL_DRAW_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + drawer.atlasTexture, + (level + 1).GLint + ) + if glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE or + glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: + glGenerateMipmap(GL_TEXTURE_2D) + return + glBlitFramebuffer( + (nextLeft * 2).GLint, + (nextTop * 2).GLint, + min(nextRight * 2, levelWidth).GLint, + min(nextBottom * 2, levelHeight).GLint, + nextLeft.GLint, + nextTop.GLint, + nextRight.GLint, + nextBottom.GLint, + GL_COLOR_BUFFER_BIT, + GL_LINEAR.GLenum + ) + left = nextLeft + top = nextTop + right = nextRight + bottom = nextBottom + levelWidth = max(1, levelWidth div 2) + levelHeight = max(1, levelHeight div 2) + inc level proc newDrawer*(window: Window, image: Image): Drawer = ## Creates a new OpenGL drawer and eagerly uploads its resources. @@ -633,17 +860,31 @@ proc endFrame*( glUseProgram(drawer.shader.programId) drawer.shader.setUniform("viewportSize", size) - drawer.shader.setUniform( - "atlasSize", - vec2(image.width.float32, image.height.float32) - ) glActiveTexture(GL_TEXTURE0) - glBindTexture(GL_TEXTURE_2D, drawer.atlasTexture) drawer.shader.setUniform("atlasSampler", 0) - drawer.shader.bindUniforms() - glBindVertexArray(drawer.vao) - glDrawArrays(GL_TRIANGLES, 0, quadCount.GLsizei) + let vertices = cast[ptr UncheckedArray[DrawerVertex]](quads) + var first = 0 + while first < quadCount: + let texture = vertices[first].texture + var last = first + 1 + while last < quadCount and vertices[last].texture == texture: + inc last + if texture == 0: + glBindTexture(GL_TEXTURE_2D, drawer.atlasTexture) + drawer.shader.setUniform( + "atlasSize", vec2(image.width.float32, image.height.float32) + ) + elif texture in drawer.textures: + let target = drawer.textures[texture] + glBindTexture(GL_TEXTURE_2D, target.id) + drawer.shader.setUniform("atlasSize", target.size.vec2) + else: + first = last + continue + drawer.shader.bindUniforms() + glDrawArrays(GL_TRIANGLES, first.GLint, (last - first).GLsizei) + first = last glBindVertexArray(0) glUseProgram(0) diff --git a/src/silky/dsl.nim b/src/silky/dsl.nim index 632854c6..4df28cee 100644 --- a/src/silky/dsl.nim +++ b/src/silky/dsl.nim @@ -512,7 +512,24 @@ proc pushChildrenLayout(sk: Silky, node: DslNode) = if node.id notin frameStates: frameStates[node.id] = FrameState() node.frameState = frameStates[node.id] - let clipRect = rect(r.x + 1, r.y + 1, max(0.0'f, r.w - 2), max(0.0'f, r.h - 2)) + # Clip on the same pixel grid as the frame's independently snapped bounds. + let + pixelScale = max(sk.uiScale, 0.001'f) + origin = vec2(round(r.x * pixelScale), round(r.y * pixelScale)) / + pixelScale + size = vec2(round(r.w * pixelScale), round(r.h * pixelScale)) / + pixelScale + inset = + if node.patch.name.len > 0: + round(pixelScale) / pixelScale + else: + 0.0'f + clipRect = rect( + origin.x + inset, + origin.y + inset, + max(0.0'f, size.x - inset * 2), + max(0.0'f, size.y - inset * 2) + ) sk.pushClipRect(clipRect) node.pushedClip = true node.frameOrigin = r.xy + dslVec2(node.horizontalPadding, node.verticalPadding) @@ -891,7 +908,7 @@ template onDown*(body: untyped) = template onClick*(body: untyped) = block: let interaction = sk.nodeInteraction(current) - if interaction == Released: + if interaction.isReleased(window): sk.hover = true sk.mouseConsumed = true body diff --git a/src/silky/frames.nim b/src/silky/frames.nim index 7f300361..6dadbc7b 100644 --- a/src/silky/frames.nim +++ b/src/silky/frames.nim @@ -29,8 +29,7 @@ proc requestFrame*( delayMs = 0, nowMs = frameMilliseconds() ) = - ## Requests an immediate or timed redraw from the owning UI thread. - ## Timed requests keep the earliest deadline; visible animations renew them. + ## Requests a redraw on the UI thread, immediately or after a delay. let dirty = schedule.dirty deadline = schedule.deadline diff --git a/src/silky/interactions.nim b/src/silky/interactions.nim new file mode 100644 index 00000000..2cd9095c --- /dev/null +++ b/src/silky/interactions.nim @@ -0,0 +1,68 @@ +import + vmath, bumpy + +type + HitRegion = object + bounds, clip: Rect + layer: int + + Interactor* = object + ## Resolves pointer targets against the last displayed frame. + currentId*: int = -1 + warmId*: int = -1 + warmLayer*: int = -1 + hotId*: int = -1 + previous, current: seq[HitRegion] + invalidated: bool + +proc resetInteractions*(interactor: var Interactor) = + ## Invalidates the previous targets without discarding this frame's regions. + interactor.hotId = -1 + interactor.warmId = -1 + interactor.warmLayer = -1 + interactor.previous.setLen(0) + if interactor.currentId >= 0: + interactor.invalidated = true + +proc endInteractions*(interactor: var Interactor) = + ## Retains displayed hit regions and reuses the other frame's storage. + interactor.hotId = interactor.warmId + interactor.warmId = -1 + interactor.warmLayer = -1 + interactor.currentId = -1 + if interactor.invalidated: + interactor.previous.setLen(0) + interactor.invalidated = false + else: + swap(interactor.previous, interactor.current) + interactor.current.setLen(0) + +proc mouseHover*( + interactor: var Interactor, + mousePos: Vec2, + clipRect: Rect, + 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. + interactor.hotId = -1 + var hotLayer = -1 + for id, region in interactor.previous: + if region.layer >= hotLayer and mousePos.overlaps(region.bounds) and + mousePos.overlaps(region.clip): + interactor.hotId = id + hotLayer = region.layer + inc interactor.currentId + let + region = HitRegion(bounds: widgetRect, clip: clipRect, layer: layer) + hovering = mousePos.overlaps(widgetRect) and mousePos.overlaps(clipRect) + interactor.current.add(region) + if hovering and layer >= interactor.warmLayer: + interactor.warmLayer = layer + interactor.warmId = interactor.currentId + # A moved, replaced, or newly clipped target must not inherit a stale hit. + interactor.hotId == interactor.currentId and hovering and + interactor.currentId < interactor.previous.len and + interactor.previous[interactor.currentId] == region diff --git a/src/silky/internal/inputs.nim b/src/silky/internal/inputs.nim index 12935a5c..4f248ec4 100644 --- a/src/silky/internal/inputs.nim +++ b/src/silky/internal/inputs.nim @@ -26,7 +26,9 @@ type TextInputs* = ref object onEvent*: proc() - ## Wakes an on-demand UI after editor input has been queued. + ## Wakes an on-demand UI after native text input has been queued. + onPaste*: proc(id: string): bool + ## Returns true to consume a paste for the active editable field. events: seq[InputEvent] active: bool editable: bool @@ -116,6 +118,11 @@ proc installPress(inputs: TextInputs, window: Window) = inputs.consumedKeys.incl(button) if inputs.editable and button == KeyV and (event.super or (event.control and not event.alt)): + let epoch = inputs.epoch + if inputs.onPaste != nil and inputs.onPaste(inputs.id): + return + if not inputs.active or not inputs.editable or inputs.epoch != epoch: + return event.kind = TextCommit event.text = getClipboardString() if event.text.len > 0: diff --git a/src/silky/layout.nim b/src/silky/layout.nim index 1ded3afc..0f5c6489 100644 --- a/src/silky/layout.nim +++ b/src/silky/layout.nim @@ -43,6 +43,44 @@ proc dirSigns*(direction: StackDirection): Vec2 = of LeftToRight: vec2(1, 1) of RightToLeft: vec2(-1, 1) +proc revealScroll*( + scroll, contentSize: Vec2, + viewport, target: Rect, + direction = TopToBottom, + margin = 4.0'f +): Vec2 {.raises: [].} = + ## Returns scroll that reveals a window-space target in any stack direction. + ## Use the scroll that placed the target and apply after frame layout. + let + signs = dirSigns(direction) + viewportPos = viewport.xy + viewportSize = viewport.wh + targetPos = target.xy + targetSize = target.wh + result = scroll + for axis in 0 .. 1: + if viewportSize[axis] <= 0: + continue + let + inset = min( + max(0.0'f, margin), + max(0.0'f, (viewportSize[axis] - targetSize[axis]) / 2) + ) + near = viewportPos[axis] + inset + far = viewportPos[axis] + viewportSize[axis] - inset + var delta = 0.0'f + if targetSize[axis] > viewportSize[axis]: + delta = targetPos[axis] - viewportPos[axis] + elif targetPos[axis] < near: + delta = targetPos[axis] - near + elif targetPos[axis] + targetSize[axis] > far: + delta = targetPos[axis] + targetSize[axis] - far + result[axis] = clamp( + scroll[axis] + signs[axis] * delta, + 0.0'f, + max(0.0'f, contentSize[axis] - viewportSize[axis]) + ) + proc originCorner*(regionPos, regionSize, signs: Vec2): Vec2 = ## The corner σ points away from (A2). result = regionPos diff --git a/src/silky/richtextboxes.nim b/src/silky/richtextboxes.nim index 5d76987d..b15c5db0 100644 --- a/src/silky/richtextboxes.nim +++ b/src/silky/richtextboxes.nim @@ -1,5 +1,5 @@ import - std/[tables, unicode, times], + std/[algorithm, tables, unicode, times], vmath, bumpy, chroma, silky/atlas, silky/internal/inputs, silky/textboxes @@ -14,6 +14,8 @@ const Tab = Rune(9) DoubleClickTime = 0.4 SelectionColor = rgbx(30, 60, 130, 128) + MaxRunRunes = 128 + MaxTableColumns = 128 when defined(macos): const TextBoxScrollSpeed = 10.0f @@ -31,10 +33,29 @@ type linkId*: int ## Matching positive IDs group the styled parts of one hoverable link. + TableAlignment* = enum + TableLeft, TableCenter, TableRight + + TextCell* = object + ## One table cell over the document's shared rune offsets. + first*, last*: int + alignment*: TableAlignment + font*: string + TextBlock* = object ## A styled block over a half-open range of shared rune offsets. first*, last*: int font*: string + noWrap*: bool + ## Keeps preformatted rows intact inside an otherwise wrapped document. + image*: string + imageTexture*: uint32 + ## Independent texture used instead of an atlas sprite when nonzero. + imageSize*, imagePixels*: Vec2 + ## Logical image bounds and optional cropped atlas pixel dimensions. + imagePlaceholderPatch*: string + imagePlaceholderBorder*: int = 8 + ## Native themed surface shown until an image sprite becomes available. padding*: Vec2 spacing*: float32 patch*: string @@ -50,20 +71,48 @@ type quoteIndent*: float32 = 16 quoteColor*: ColorRGBX quoteThickness*: float32 = 2 + tableColumns*: int + tableCells*: seq[TextCell] + tableHeaderFont*: string + tableHeaderColor*, tableBorderColor*: ColorRGBX + tablePadding*: Vec2 = vec2(10.0'f, 8.0'f) + tableBorderWidth*: float32 = 1 + + TableRowLayout = object + top, bottom: float32 + + CellLayout = object + first, last: int + bounds: Rect + top, bottom: float32 BlockLayout = object bounds: Rect ruleBounds: Rect + imageBounds: Rect quoteBounds: Rect - labelPosition: Vec2 + labelBounds: Rect labelFont: string + tableBounds: Rect + tableColumns: seq[float32] + tableRows: seq[TableRowLayout] + tableFirst, tableLast: int + top, bottom: float32 TextRun = object text: string font: string position: Vec2 bounds: Rect + decorationRight: float32 + clip: Rect + clipped: bool span: int + top, bottom: float32 + + TextLine = object + first, last: int + top, bottom: float32 RichTextBoxState* = ref object ## Read-only styled content with one shared plain-text selection state. @@ -72,14 +121,25 @@ type blocks*: seq[TextBlock] activatedSpan*: int = -1 hoveredSpan*: int = -1 + cursorNavigated*: bool + ## Reports consumed navigation keys during the latest widget draw. runeSpans: seq[int] runs: seq[TextRun] blockLayouts: seq[BlockLayout] + cellLayouts: seq[CellLayout] + lines: seq[TextLine] + contentWidth: float32 + renderMargin: float32 lastFont: string focusEpoch: uint64 pressedSpan: int = -1 pressPosition: Vec2 spanDragged: bool + when defined(silkyTesting): + renderedRuns*: int + renderedBlocks*: int + renderedSelectionRects*: int + renderedTableRows*: int var richTextBoxStates*: Table[string, RichTextBoxState] @@ -96,8 +156,11 @@ proc getText*(state: RichTextBoxState): string = state.editor.getText() proc sameText*(state: RichTextBoxState, text: string): bool = - ## Compares the selectable text without allocating. - state.editor.sameText(text) + ## Compares cached UTF-8 bytes after native text edits invalidate the cache. + if state.editor.password: + state.editor.sameText(text) + else: + state.editor.displayText() == text proc setText*( state: RichTextBoxState, @@ -111,6 +174,189 @@ proc innerHeight*(state: RichTextBoxState): float32 = ## Returns the measured height of the complete styled document. state.editor.innerHeight +when defined(silkyTesting): + proc runDecorationBounds*(state: RichTextBoxState): seq[Rect] = + ## Exposes cached decoration geometry without a native drawing context. + for run in state.runs: + result.add(rect( + run.bounds.xy, + vec2(run.decorationRight - run.bounds.x, run.bounds.h) + )) + +proc imageBounds*(state: RichTextBoxState, index: int): Rect = + ## Returns one image's document coordinates for native hit testing. + if index >= 0 and index < state.blockLayouts.len: + result = state.blockLayouts[index].imageBounds + +proc alignImageBounds*(bounds: Rect, pixelScale: float32): Rect = + ## Snaps position and size independently so scrolling never resizes pixels. + let + scale = max(pixelScale, 0.001'f) + left = round(bounds.x * scale) / scale + top = round(bounds.y * scale) / scale + width = round(bounds.w * scale) / scale + height = round(bounds.h * scale) / scale + rect(left, top, max(0.0'f, width), max(0.0'f, height)) + +proc blockBounds*(state: RichTextBoxState, index: int): Rect = + ## Returns one block's document coordinates for clipped lazy content. + if index >= 0 and index < state.blockLayouts.len: + result = state.blockLayouts[index].bounds + +proc tableCellBounds*( + state: RichTextBoxState, + blockIndex, cellIndex: int +): Rect = + ## Returns one table cell's document bounds without exposing layout storage. + if blockIndex >= 0 and blockIndex < state.blockLayouts.len: + let + blockLayout = state.blockLayouts[blockIndex] + index = blockLayout.tableFirst + cellIndex + if cellIndex >= 0 and index < blockLayout.tableLast: + result = state.cellLayouts[index].bounds + +proc horizontalScrollbarHeight*( + state: RichTextBoxState, + width: float32 +): float32 = + ## Returns the space needed beneath overflowing preformatted content. + if state.contentWidth <= max(0.0'f, width) + 0.001'f: + return 0 + if not state.editor.wordWrap: + return 10 + for item in state.blocks: + if item.noWrap: + return 10 + +proc visibleRange[T](items: openArray[T], top, bottom: float32): Slice[int] = + ## Finds a bounded interval in cached, vertically ordered layout records. + var + first = 0 + last = items.len + while first < last: + let middle = (first + last) div 2 + if items[middle].bottom < top: + first = middle + 1 + else: + last = middle + result.a = first + last = items.len + while first < last: + let middle = (first + last) div 2 + if items[middle].top <= bottom: + first = middle + 1 + else: + last = middle + result.b = first - 1 + +proc cacheGeometry(state: RichTextBoxState) = + ## Stores width and line ranges once so clipping never scans the document. + state.contentWidth = 0 + state.lines.setLen(0) + for i, bounds in state.editor.layout: + state.contentWidth = max(state.contentWidth, bounds.x + bounds.w) + if state.lines.len > 0 and state.lines[^1].top == bounds.y and + i > 0 and state.editor.runes[i - 1] notin [Tab, LF] and + bounds.x >= state.editor.layout[i - 1].x: + state.lines[^1].last = i + 1 + state.lines[^1].bottom = max( + state.lines[^1].bottom, bounds.y + bounds.h + ) + else: + state.lines.add(TextLine( + first: i, + last: i + 1, + top: bounds.y, + bottom: bounds.y + bounds.h + )) + var ordered = true + for i in 1 ..< state.lines.len: + if state.lines[i].top < state.lines[i - 1].top: + ordered = false + break + if not ordered: + state.lines.sort(proc(a, b: TextLine): int = + ## Orders visual fragments while retaining their logical rune ranges. + result = cmp(a.top, b.top) + if result == 0: + result = cmp(a.first, b.first) + ) + ordered = true + for i in 1 ..< state.runs.len: + if state.runs[i].bounds.y < state.runs[i - 1].bounds.y: + ordered = false + break + if not ordered: + state.runs.sort(proc(a, b: TextRun): int = + ## Keeps drawing and clipping independent of row-major cell text order. + result = cmp(a.bounds.y, b.bounds.y) + if result == 0: + result = cmp(a.bounds.x, b.bounds.x) + ) + var bottom = 0.0'f + for line in state.lines.mitems: + bottom = max(bottom, line.bottom) + line.bottom = bottom + bottom = 0.0'f + for run in state.runs.mitems: + run.top = run.bounds.y + bottom = max(bottom, run.bounds.y + run.bounds.h) + run.bottom = bottom + bottom = 0.0'f + for i, layout in state.blockLayouts.mpairs: + layout.top = layout.bounds.y + bottom = max( + bottom, + layout.bounds.y + layout.bounds.h + max(0.0'f, state.blocks[i].spacing) + ) + layout.bottom = bottom + +proc cacheRuns( + state: RichTextBoxState, + fonts: openArray[FontAtlas], + names: openArray[string], + baseline: float32 +) = + ## Splits measured lines into bounded native text draws without reflowing. + state.runs.setLen(0) + var i = 0 + while i < state.editor.runes.len: + if state.editor.runes[i] in [LF, Tab]: + inc i + continue + let + first = i + span = state.runeSpans[i] + font = fonts[span + 1] + bounds = state.editor.layout[i] + var text = "" + while i < state.editor.runes.len and + i - first < MaxRunRunes and + state.editor.runes[i] notin [LF, Tab] and + state.runeSpans[i] == span and state.editor.layout[i].y == bounds.y: + text.add($state.editor.runes[i]) + inc i + let + last = state.editor.layout[i - 1] + continues = i - first == MaxRunRunes and + i < state.editor.runes.len and + state.editor.runes[i] notin [LF, Tab] and + state.runeSpans[i] == span and + state.editor.layout[i].y == bounds.y + decorationRight = + if continues: state.editor.layout[i].x + else: last.x + last.w + state.runs.add(TextRun( + text: text, + font: names[span + 1], + position: vec2(bounds.x, bounds.y + baseline - font.ascent), + bounds: rect( + bounds.x, bounds.y, last.x + last.w - bounds.x, bounds.h + ), + decorationRight: decorationRight, + span: state.runeSpans[first] + )) + proc computeLayout*( state: RichTextBoxState, fonts: Table[string, FontAtlas], @@ -118,6 +364,203 @@ proc computeLayout*( maxWidth: float32 ) +proc computeTable( + state: RichTextBoxState, + item: TextBlock, + fonts: Table[string, FontAtlas], + baseFont: string, + origin: Vec2, + width: float32 +): BlockLayout = + ## Fits styled cells to shared columns and keeps their logical text order. + let + columns = item.tableColumns + firstBound = clamp(item.first, 0, state.editor.runes.len) + lastBound = clamp(item.last, firstBound, state.editor.runes.len) + count = ((item.tableCells.len + columns - 1) div columns) * columns + paddingY = max(0.0'f, item.tablePadding.y) + requestedPadding = max(0.0'f, item.tablePadding.x) + var + locals = newSeq[RichTextBoxState](count) + indices = newSeq[seq[int]](count) + cells = newSeq[TextCell](count) + preferred = newSeq[float32](columns) + widths = newSeq[float32](columns) + covered = firstBound + for i in 0 ..< count: + var cell = + if i < item.tableCells.len: item.tableCells[i] + else: TextCell(first: item.last, last: item.last) + cell.first = clamp(cell.first, covered, lastBound) + cell.last = clamp(cell.last, cell.first, lastBound) + covered = cell.last + cells[i] = cell + locals[i] = RichTextBoxState( + editor: TextBoxState( + runes: state.editor.runes[cell.first ..< cell.last], + wordWrap: false, enabled: false + ), + spans: @[TextSpan()] + ) + indices[i] = @[-1] + for index, span in state.spans: + if span.last <= firstBound or span.first >= lastBound: + continue + var + first = 0 + last = cells.len + while first < last: + let middle = (first + last) div 2 + if cells[middle].last <= span.first: + first = middle + 1 + else: + last = middle + while first < cells.len and cells[first].first < span.last: + let cell = cells[first] + if cell.last > cell.first: + var relative = span + relative.first = max(cell.first, span.first) - cell.first + relative.last = min(cell.last, span.last) - cell.first + locals[first].spans.add(relative) + indices[first].add(index) + inc first + var total = 0.0'f + for i, local in locals: + let + cell = cells[i] + font = + if cell.font in fonts: cell.font + elif i < columns and item.tableHeaderFont in fonts: + item.tableHeaderFont + elif item.font in fonts: item.font + else: baseFont + column = i mod columns + local.computeLayout(fonts, font, float32.high) + preferred[column] = max( + preferred[column], + min(width, max(32.0'f, local.editor.innerWidth + requestedPadding * 2)) + ) + for value in preferred: + total += value + if total <= width: + for i in 0 ..< columns: + widths[i] = preferred[i] + (width - total) / columns.float32 + else: + var + minimum = 0.0'f + demand = 0.0'f + for i in 0 ..< columns: + widths[i] = min(preferred[i], 128.0'f) + minimum += widths[i] + demand += preferred[i] - widths[i] + for i in 0 ..< columns: + if minimum > width: + widths[i] *= width / minimum + elif demand > 0: + widths[i] += (width - minimum) * (preferred[i] - widths[i]) / demand + result.tableBounds = rect(origin, vec2(width, 0)) + result.tableFirst = state.cellLayouts.len + # Keep edge storage fixed while reading previous column positions. + result.tableColumns = newSeq[float32](columns + 1) + result.tableColumns[0] = origin.x + for i, columnWidth in widths: + result.tableColumns[i + 1] = result.tableColumns[i] + columnWidth + result.tableColumns[^1] = origin.x + width + var + top = origin.y + previous = rect(origin, vec2(0, state.editor.lineHeight)) + copied = firstBound + for row in 0 ..< count div columns: + var height = 0.0'f + for column in 0 ..< columns: + let + i = row * columns + column + local = locals[i] + paddingX = min(requestedPadding, widths[column] / 4) + available = max(0.0'f, widths[column] - paddingX * 2) + font = local.lastFont + local.editor.wordWrap = true + local.computeLayout(fonts, font, available) + height = max(height, local.innerHeight + paddingY * 2) + result.tableRows.add(TableRowLayout(top: top, bottom: top + height)) + for column in 0 ..< columns: + let + i = row * columns + column + cell = cells[i] + local = locals[i] + paddingX = min(requestedPadding, widths[column] / 4) + available = max(0.0'f, widths[column] - paddingX * 2) + cellOrigin = vec2( + result.tableColumns[column] + paddingX, + top + paddingY + ) + bounds = rect(result.tableColumns[column], top, widths[column], height) + state.cellLayouts.add(CellLayout( + first: cell.first, last: cell.last, bounds: bounds, + top: top, bottom: top + height + )) + var offsets = newSeq[float32](local.lines.len) + for lineIndex, line in local.lines: + var lineWidth = 0.0'f + for j in line.first ..< line.last: + let glyph = local.editor.layout[j] + lineWidth = max(lineWidth, glyph.x + glyph.w) + let spare = max(0.0'f, available - lineWidth) + offsets[lineIndex] = + case cell.alignment + of TableLeft: 0.0'f + of TableCenter: spare / 2 + of TableRight: spare + for j in line.first ..< line.last: + local.editor.layout[j].x += offsets[lineIndex] + for j in copied ..< cell.first: + state.editor.layout[j] = previous + for j, glyph in local.editor.layout: + var shifted = rect(cellOrigin + glyph.xy, glyph.wh) + shifted.x = min(shifted.x, bounds.x + bounds.w) + shifted.w = min(shifted.w, max(0.0'f, bounds.x + bounds.w - shifted.x)) + state.editor.layout[cell.first + j] = shifted + let span = local.runeSpans[j] + if span >= 0: + state.runeSpans[cell.first + j] = indices[i][span] + for run in local.runs.mitems: + var shift = cellOrigin + var + firstLine = 0 + lastLine = local.lines.len + while firstLine < lastLine: + let middle = (firstLine + lastLine) div 2 + if local.lines[middle].top < run.bounds.y: + firstLine = middle + 1 + else: + lastLine = middle + if firstLine < offsets.len: + shift.x += offsets[firstLine] + run.position += shift + run.bounds.x += shift.x + run.bounds.y += shift.y + run.decorationRight += shift.x + run.clip = bounds + run.clipped = true + if run.span >= 0: + run.span = indices[i][run.span] + state.runs.add(run) + previous = rect(cellOrigin, vec2(0, local.editor.lineHeight)) + if local.editor.layout.len > 0: + let last = state.editor.layout[cell.last - 1] + previous = rect(last.x + last.w, last.y, 0, last.h) + # A tab or newline after an empty cell is its selectable caret position. + if cell.first == cell.last and cell.last < state.editor.layout.len: + state.editor.layout[cell.last] = previous + copied = cell.last + state.renderMargin = max(state.renderMargin, local.renderMargin) + top += height + for i in copied ..< lastBound: + state.editor.layout[i] = previous + result.tableBounds.h = top - origin.y + result.tableLast = state.cellLayouts.len + state.editor.layoutCursor = previous + proc computeBlocks( state: RichTextBoxState, fonts: Table[string, FontAtlas], @@ -132,6 +575,7 @@ proc computeBlocks( state.runeSpans.setLen(state.editor.runes.len) state.runs.setLen(0) state.blockLayouts.setLen(0) + state.cellLayouts.setLen(0) state.editor.layoutHeight = 0 for index in state.runeSpans.mitems: index = -1 @@ -158,6 +602,28 @@ proc computeBlocks( blockWidth = width - quoteInset for i in covered ..< first: state.editor.layout[i] = previousEnd + if item.tableColumns in 1 .. MaxTableColumns and item.tableCells.len > 0: + var measured = state.computeTable( + item, fonts, baseFont, + vec2(quoteInset + padding.x, state.editor.layoutHeight + padding.y), + max(0.0'f, blockWidth - padding.x * 2) + ) + let height = measured.tableBounds.h + padding.y * 2 + measured.bounds = rect( + quoteInset, + state.editor.layoutHeight, + blockWidth, + height + ) + measured.quoteBounds = rect( + padding.x, state.editor.layoutHeight, max(0.0'f, width - padding.x * 2), + height + ) + state.blockLayouts.add(move(measured)) + state.editor.layoutHeight += height + max(0.0'f, item.spacing) + previousEnd = state.editor.layoutCursor + covered = last + continue if first == last and item.ruleThickness > 0: let origin = vec2( @@ -196,17 +662,34 @@ proc computeBlocks( baseFont labelHeight = if item.label.len > 0: - fonts[labelFont].lineHeight + max(0.0'f, item.labelSpacing) + let label = TextBoxState(wordWrap: true) + label.setText(item.label) + label.computeLayout( + fonts[labelFont], max(0.0'f, blockWidth - padding.x * 2) + ) + label.innerHeight + max(0.0'f, item.labelSpacing) + else: + 0.0'f + imageScale = + if item.imageSize.x > 0 and item.imageSize.y > 0: + min(1.0'f, max(0.0'f, blockWidth - padding.x * 2) / + item.imageSize.x) + else: + 0.0'f + imageSize = item.imageSize * imageScale + imageHeight = + if imageSize.y > 0: + imageSize.y + 8 else: 0.0'f origin = vec2( quoteInset + padding.x, - state.editor.layoutHeight + padding.y + labelHeight + state.editor.layoutHeight + padding.y + labelHeight + imageHeight ) local = RichTextBoxState( editor: TextBoxState( runes: state.editor.runes[first ..< last], - wordWrap: state.editor.wordWrap, + wordWrap: state.editor.wordWrap and not item.noWrap, enabled: false ), spans: @[TextSpan()] @@ -220,6 +703,7 @@ proc computeBlocks( local.spans.add(relative) spanIndices.add(index) local.computeLayout(fonts, font, max(0.0'f, blockWidth - padding.x * 2)) + state.renderMargin = max(state.renderMargin, local.renderMargin) var contentHeight = local.editor.lineHeight for i, bounds in local.editor.layout: state.editor.layout[first + i] = rect(origin + bounds.xy, bounds.wh) @@ -230,6 +714,7 @@ proc computeBlocks( run.position += origin run.bounds.x += origin.x run.bounds.y += origin.y + run.decorationRight += origin.x if run.span >= 0: run.span = spanIndices[run.span] state.runs.add(run) @@ -252,15 +737,30 @@ proc computeBlocks( contentHeight += local.editor.lineHeight state.editor.layoutCursor.x = origin.x state.editor.layoutCursor.y += local.editor.lineHeight - let height = contentHeight + padding.y * 2 + labelHeight + let + height = contentHeight + padding.y * 2 + labelHeight + imageHeight + surfaceWidth = + if item.noWrap: + max(blockWidth, local.editor.innerWidth + padding.x * 2) + else: + blockWidth state.blockLayouts.add(BlockLayout( - bounds: rect(quoteInset, state.editor.layoutHeight, blockWidth, height), + bounds: rect(quoteInset, state.editor.layoutHeight, surfaceWidth, height), + imageBounds: rect( + quoteInset + padding.x, + state.editor.layoutHeight + padding.y + labelHeight, + imageSize.x, + imageSize.y + ), quoteBounds: rect( padding.x, state.editor.layoutHeight, max(0.0'f, width - padding.x * 2), height ), - labelPosition: vec2( - quoteInset + padding.x, state.editor.layoutHeight + padding.y + labelBounds: rect( + quoteInset + padding.x, + state.editor.layoutHeight + padding.y, + max(0.0'f, blockWidth - padding.x * 2), + max(0.0'f, labelHeight - max(0.0'f, item.labelSpacing)) ), labelFont: labelFont )) @@ -279,17 +779,23 @@ proc computeLayout*( ) = ## Lays out styled text with the same glyph positions used for selection. state.lastFont = baseFont + state.renderMargin = fonts[baseFont].lineHeight if state.blocks.len > 0: state.computeBlocks(fonts, baseFont, maxWidth) + state.cacheGeometry() return state.editor.positionedLayout = false state.editor.layoutCursor = rect(0, 0, 0, 0) state.blockLayouts.setLen(0) + state.cellLayouts.setLen(0) state.editor.layoutHeight = 0 if state.spans.len == 0: - state.runeSpans.setLen(0) - state.runs.setLen(0) state.editor.computeLayout(fonts[baseFont], maxWidth) + state.runeSpans.setLen(state.editor.runes.len) + for index in state.runeSpans.mitems: + index = -1 + state.cacheRuns([fonts[baseFont]], [baseFont], fonts[baseFont].ascent) + state.cacheGeometry() return let base = fonts[baseFont] var @@ -325,6 +831,7 @@ proc computeLayout*( state.editor.lineHeight, baseline - descent + lineGap ) + state.renderMargin = state.editor.lineHeight var advances = newSeq[float32](state.editor.runes.len) kernings = newSeq[float32](state.editor.runes.len) @@ -377,48 +884,100 @@ proc computeLayout*( position.x, position.y, advances[i], state.editor.lineHeight )) position.x += advances[i] + kernings[i] - var i = 0 - while i < state.editor.runes.len: - if state.editor.runes[i] in [LF, Tab]: - inc i - continue - let - first = i - span = state.runeSpans[i] - font = resolvedFonts[span + 1] - bounds = state.editor.layout[i] - var text = "" - while i < state.editor.runes.len and - state.editor.runes[i] notin [LF, Tab] and - state.runeSpans[i] == span and state.editor.layout[i].y == bounds.y: - text.add($state.editor.runes[i]) - inc i - let last = state.editor.layout[i - 1] - state.runs.add(TextRun( - text: text, - font: fontNames[span + 1], - position: vec2(bounds.x, bounds.y + baseline - font.ascent), - bounds: rect( - bounds.x, bounds.y, last.x + last.w - bounds.x, bounds.h - ), - span: state.runeSpans[first] - )) + state.cacheRuns(resolvedFonts, fontNames, baseline) state.editor.dirty = false + state.cacheGeometry() proc spanAt(state: RichTextBoxState, position: Vec2): int = ## Finds a formatted span only when the pointer touches its glyph bounds. - for i, bounds in state.editor.layout: - if position.overlaps(bounds) and i < state.runeSpans.len: - return state.runeSpans[i] + let lines = visibleRange(state.lines, position.y, position.y) + for line in lines: + for i in state.lines[line].first ..< state.lines[line].last: + if position.overlaps(state.editor.layout[i]) and i < state.runeSpans.len: + return state.runeSpans[i] -1 proc drawSpanBackgrounds(sk: Silky, state: RichTextBoxState, origin: Vec2) = ## Draws inline backgrounds before the native selection highlight. - for run in state.runs: + if sk.clipRect.w <= 0 or sk.clipRect.h <= 0: + return + let visible = visibleRange( + state.runs, sk.clipRect.y - origin.y, + sk.clipRect.y + sk.clipRect.h - origin.y + ) + for i in visible: + let + run = state.runs[i] + bounds = rect( + origin + run.bounds.xy, + vec2(run.decorationRight - run.bounds.x, run.bounds.h) + ) + if not bounds.overlaps(sk.clipRect): + continue if run.span >= 0: let color = state.spans[run.span].background if color.a > 0: - sk.drawRect(origin + run.bounds.xy, run.bounds.wh, color) + if run.clipped: + sk.pushClipRect(rect(origin + run.clip.xy, run.clip.wh)) + sk.drawRect(bounds.xy, bounds.wh, color) + if run.clipped: + sk.popClipRect() + +proc drawTable( + sk: Silky, + state: RichTextBoxState, + item: TextBlock, + layout: BlockLayout, + origin: Vec2 +) = + ## Draws only visible row borders with physical-pixel-aligned grid edges. + if layout.tableRows.len == 0 or layout.tableBounds.w <= 0: + return + let + rows = visibleRange( + layout.tableRows, sk.clipRect.y - origin.y, + sk.clipRect.y + sk.clipRect.h - origin.y + ) + scale = max(sk.uiScale, 0.001'f) + thickness = max(1.0'f, round(item.tableBorderWidth * scale)) / scale + left = round((origin.x + layout.tableBounds.x) * scale) / scale + right = round((origin.x + layout.tableBounds.x + layout.tableBounds.w) * + scale) / scale + top = round((origin.y + layout.tableBounds.y) * scale) / scale + bottom = round((origin.y + layout.tableBounds.y + layout.tableBounds.h) * + scale) / scale + if right <= left: + return + if rows.a == 0 and item.tableHeaderColor.a > 0: + let headerBottom = round((origin.y + layout.tableRows[0].bottom) * scale) / + scale + sk.drawRect(vec2(left, top), vec2(right - left, headerBottom - top), + item.tableHeaderColor) + if item.tableBorderColor.a == 0 or item.tableBorderWidth <= 0: + return + for i in rows: + let y = round((origin.y + layout.tableRows[i].top) * scale) / scale + sk.drawRect(vec2(left, y), vec2(right - left, thickness), + item.tableBorderColor) + when defined(silkyTesting): + inc state.renderedTableRows + if bottom >= sk.clipRect.y and bottom <= sk.clipRect.y + sk.clipRect.h: + sk.drawRect(vec2(left, bottom - thickness), vec2(right - left, thickness), + item.tableBorderColor) + let + visibleTop = max(top, sk.clipRect.y) + visibleBottom = min(bottom, sk.clipRect.y + sk.clipRect.h) + if visibleBottom <= visibleTop: + return + for i, edge in layout.tableColumns: + let x = + if i == layout.tableColumns.high: right - thickness + else: round((origin.x + edge) * scale) / scale + sk.drawRect( + vec2(x, visibleTop), + vec2(thickness, visibleBottom - visibleTop), + item.tableBorderColor + ) proc drawBlocks( sk: Silky, @@ -427,8 +986,19 @@ proc drawBlocks( defaultColor: ColorRGBX ) = ## Draws native block surfaces, borders, rules, and captions. - for i, bounds in state.blockLayouts: + if sk.clipRect.w <= 0 or sk.clipRect.h <= 0: + return + let visible = visibleRange( + state.blockLayouts, sk.clipRect.y - origin.y, + sk.clipRect.y + sk.clipRect.h - origin.y + ) + for i in visible: + let bounds = state.blockLayouts[i] + when defined(silkyTesting): + inc state.renderedBlocks let item = state.blocks[i] + if bounds.tableRows.len > 0: + sk.drawTable(state, item, bounds, origin) if item.patch.len > 0: sk.draw9Patch( item.patch, @@ -436,6 +1006,42 @@ proc drawBlocks( origin + bounds.bounds.xy, bounds.bounds.wh ) + if bounds.imageBounds.w > 0 and bounds.imageBounds.h > 0: + let aligned = alignImageBounds( + rect(origin + bounds.imageBounds.xy, bounds.imageBounds.wh), + sk.uiScale + ) + if item.imageTexture != 0: + sk.drawTexture( + item.imageTexture, + aligned.xy, + aligned.wh, + item.imagePixels + ) + elif item.image in sk.atlas.entries: + let + entry = sk.atlas.entries[item.image] + pixels = + if item.imagePixels.x > 0 and item.imagePixels.y > 0: + min(item.imagePixels, vec2( + entry.width.float32, entry.height.float32 + )) + else: + vec2(entry.width.float32, entry.height.float32) + sk.drawQuad( + aligned.xy, + aligned.wh, + vec2(entry.x.float32, entry.y.float32), + pixels, + rgbx(255, 255, 255, 255) + ) + elif item.imagePlaceholderPatch in sk.atlas.entries: + sk.draw9Patch( + item.imagePlaceholderPatch, + item.imagePlaceholderBorder, + aligned.xy, + aligned.wh + ) if item.quoteDepth > 0 and item.quoteThickness > 0 and item.quoteColor.a > 0 and bounds.quoteBounds.w > 0: let @@ -489,9 +1095,11 @@ proc drawBlocks( discard sk.drawText( bounds.labelFont, item.label, - origin + bounds.labelPosition, + origin + bounds.labelBounds.xy, color, - maxWidth = max(0.0'f, bounds.bounds.w - item.padding.x * 2) + maxWidth = bounds.labelBounds.w, + maxHeight = bounds.labelBounds.h, + wordWrap = true ) proc drawSpans( @@ -501,12 +1109,28 @@ proc drawSpans( defaultColor: ColorRGBX ) = ## Draws cached runs at their measured positions without wrapping again. - for run in state.runs: + if sk.clipRect.w <= 0 or sk.clipRect.h <= 0: + return + let + margin = state.renderMargin + visible = visibleRange( + state.runs, sk.clipRect.y - origin.y - margin, + sk.clipRect.y + sk.clipRect.h - origin.y + margin + ) + for i in visible: + let run = state.runs[i] + if run.bounds.x + run.bounds.w + origin.x + margin < sk.clipRect.x or + run.bounds.x + origin.x - margin > sk.clipRect.x + sk.clipRect.w: + continue + when defined(silkyTesting): + inc state.renderedRuns let color = if run.span >= 0 and state.spans[run.span].color.a > 0: state.spans[run.span].color else: defaultColor + if run.clipped: + sk.pushClipRect(rect(origin + run.clip.xy, run.clip.wh)) discard sk.drawText( run.font, run.text, origin + run.position, color, clip = false ) @@ -520,8 +1144,7 @@ proc drawSpans( font = sk.atlas.fonts[run.font] scale = max(sk.uiScale, 0.001'f) left = round((origin.x + run.bounds.x) * scale) / scale - right = round((origin.x + run.bounds.x + run.bounds.w) * scale) / - scale + right = round((origin.x + run.decorationRight) * scale) / scale baseline = origin.y + run.position.y + font.ascent thickness = max(1.0'f, round(scale)) / scale if span.strikethrough: @@ -530,6 +1153,104 @@ proc drawSpans( if underline: let top = round((baseline + 1) * scale) / scale sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) + if run.clipped: + sk.popClipRect() + +proc drawSelection( + sk: Silky, + state: RichTextBoxState, + origin: Vec2 +) = + ## Draws selected visible lines without walking the offscreen selection. + if sk.clipRect.w <= 0 or sk.clipRect.h <= 0: + return + let + selection = state.editor.selection + visible = visibleRange( + state.lines, sk.clipRect.y - origin.y, + sk.clipRect.y + sk.clipRect.h - origin.y + ) + for index in visible: + let + line = state.lines[index] + first = max(selection.a, line.first) + last = min(selection.b, line.last) + var rectangles: seq[Rect] + for i in first ..< last: + let bounds = state.editor.layout[i] + if rectangles.len > 0 and rectangles[^1].y == bounds.y and + rectangles[^1].h == bounds.h and + bounds.x >= rectangles[^1].x and + bounds.x - rectangles[^1].x < rectangles[^1].w * 2: + rectangles[^1].w = bounds.x - rectangles[^1].x + bounds.w + else: + rectangles.add(bounds) + for bounds in rectangles: + if not rect(origin + bounds.xy, bounds.wh).overlaps(sk.clipRect): + continue + sk.drawRect(origin + bounds.xy, bounds.wh, SelectionColor) + when defined(silkyTesting): + inc state.renderedSelectionRects + +proc mouseAction( + state: RichTextBoxState, + position: Vec2, + click = true, + shift = false +) = + ## Keeps empty-cell and short-cell clicks within the intended table column. + let visible = visibleRange(state.cellLayouts, position.y, position.y) + for index in visible: + let cell = state.cellLayouts[index] + if not position.overlaps(cell.bounds): + continue + let editor = state.editor + var + cursor = cell.first + nearestY = float32.high + nearestX = float32.high + for i in cell.first ..< cell.last: + let + bounds = editor.layout[i] + distanceY = max(0.0'f, + max(bounds.y - position.y, position.y - bounds.y - bounds.h)) + distanceX = abs(position.x - bounds.x - bounds.w / 2) + if distanceY < nearestY or + (distanceY == nearestY and distanceX < nearestX): + nearestY = distanceY + nearestX = distanceX + cursor = i + if position.x > bounds.x + bounds.w / 2 and editor.runes[i] != LF: + inc cursor + editor.cursor = cursor + editor.savedX = position.x + if click and not shift: + editor.selector = cursor + editor.scrollToCursor() + editor.resetBlink() + return + state.editor.mouseAction(position, click, shift) + +proc selectWord(state: RichTextBoxState, position: Vec2) = + ## Expands a cell-aware caret through one native whitespace-delimited word. + state.mouseAction(position) + let editor = state.editor + while editor.cursor > 0 and + not editor.runes[editor.cursor - 1].isWhiteSpace(): + dec editor.cursor + while editor.selector < editor.runes.len and + not editor.runes[editor.selector].isWhiteSpace(): + inc editor.selector + +proc selectParagraph(state: RichTextBoxState, position: Vec2) = + ## Selects one logical paragraph or table row from the clicked cell. + state.mouseAction(position) + let editor = state.editor + while editor.cursor > 0 and editor.runes[editor.cursor - 1] != LF: + dec editor.cursor + while editor.selector < editor.runes.len and + editor.runes[editor.selector] != LF: + inc editor.selector proc richTextBox*( sk: Silky, @@ -547,9 +1268,15 @@ proc richTextBox*( state = richTextBoxStates[id] editor = state.editor inputs = sk.textInputs + when defined(silkyTesting): + state.renderedRuns = 0 + state.renderedBlocks = 0 + state.renderedSelectionRects = 0 + state.renderedTableRows = 0 editor.enabled = false state.activatedSpan = -1 state.hoveredSpan = -1 + state.cursorNavigated = false if editor.focused and state.focusEpoch != inputs.focusEpoch: editor.focused = false editor.dragging = false @@ -568,14 +1295,20 @@ proc richTextBox*( let padding = sk.theme.padding.float32 outerRect = rect(sk.at, vec2(boxWidth, boxHeight)) - innerRect = rect( - sk.at.x + padding, sk.at.y + padding, - boxWidth - padding * 2, boxHeight - padding * 2 - ) - editor.boxSize = innerRect.wh + var innerRect = rect( + sk.at.x + padding, + sk.at.y + padding, + boxWidth - padding * 2, + boxHeight - padding * 2 + ) if editor.dirty or editor.lastMaxWidth != innerRect.w or state.lastFont != sk.textStyle: state.computeLayout(sk.atlas.fonts, sk.textStyle, innerRect.w) + let scrollbarHeight = state.horizontalScrollbarHeight(innerRect.w) + innerRect.h = max(0.0'f, innerRect.h - scrollbarHeight) + if abs(innerRect.h - editor.innerHeight) < 0.001'f: + innerRect.h = editor.innerHeight + editor.boxSize = innerRect.wh let shift = window.buttonDown[KeyLeftShift] or window.buttonDown[KeyRightShift] @@ -583,7 +1316,13 @@ proc richTextBox*( mouseInside = mouseVec.overlaps(outerRect) and mouseVec.overlaps(sk.clipRect) onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) - if window.buttonPressed[MouseLeft]: + if sk.touchScrolling: + if editor.dragging: + editor.selector = editor.cursor + editor.dragging = false + state.pressedSpan = -1 + state.spanDragged = true + if sk.buttonPressed[MouseLeft]: state.pressedSpan = -1 if mouseInside and not onScrollbar: editor.focused = true @@ -597,16 +1336,16 @@ proc richTextBox*( editor.lastClickTime = now case editor.clickCount of 1: - editor.mouseAction(localMouse, click = true, shift = shift) + 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: - editor.selectWord(localMouse) + state.selectWord(localMouse) of 3: - editor.selectParagraph(localMouse) + state.selectParagraph(localMouse) else: editor.selectAll() elif not mouseInside: @@ -627,26 +1366,27 @@ proc richTextBox*( elif not window.buttonDown[MouseLeft]: state.pressedSpan = -1 if editor.dragging and not editor.scrollingX and not editor.scrollingY: - if window.buttonDown[MouseLeft] and not window.buttonPressed[MouseLeft]: + if sk.buttonDown[MouseLeft] and not sk.buttonPressed[MouseLeft]: let localMouse = mouseVec - innerRect.xy + editor.scrollPos - editor.mouseAction(localMouse, click = false, shift = true) + state.mouseAction(localMouse, click = false, shift = true) if window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]: editor.dragging = false inputs.submitInput(window, "rich-textbox:" & id, editor.focused, false) if editor.focused: state.focusEpoch = inputs.focusEpoch - editor.handleSelectionInput(inputs) + state.cursorNavigated = editor.handleSelectionInput(inputs) let maxScrollY = max(0.0'f, editor.innerHeight - innerRect.h) editor.scrollPos.y = clamp(editor.scrollPos.y, 0.0'f, maxScrollY) - if editor.wordWrap: - editor.scrollPos.x = 0 - else: - editor.scrollPos.x = max(0.0'f, editor.scrollPos.x) + let maxScrollX = + if scrollbarHeight > 0: + max(0.0'f, state.contentWidth - innerRect.w) + else: + 0.0'f + editor.scrollPos.x = clamp(editor.scrollPos.x, 0.0'f, maxScrollX) let overVerticalBar = editor.innerHeight > innerRect.h and mouseVec.x >= outerRect.x + outerRect.w - 10 - overHorizontalBar = not editor.wordWrap and - editor.innerWidth > innerRect.w and + overHorizontalBar = scrollbarHeight > 0 and mouseVec.y >= outerRect.y + outerRect.h - 10 if mouseInside and mouseVec.overlaps(innerRect) and not editor.scrollingX and not editor.scrollingY and @@ -666,33 +1406,36 @@ proc richTextBox*( if state.spans.len > 0: sk.drawSpanBackgrounds(state, textOrigin) if editor.cursor != editor.selector: - let selection = editor.selection - for bounds in getSelectionRects(editor.layout, selection.a, selection.b): - sk.drawRect( - textOrigin + bounds.xy, bounds.wh, SelectionColor - ) - if state.spans.len > 0 or state.blocks.len > 0: - sk.drawSpans(state, textOrigin, textColor) - else: - discard sk.drawText( - sk.textStyle, - editor.displayText, - textOrigin, - textColor, - maxWidth = innerRect.w, - wordWrap = editor.wordWrap, - clip = false - ) + sk.drawSelection(state, textOrigin) + sk.drawSpans(state, textOrigin, textColor) sk.requestCursorFrame(window, editor, innerRect, state.focusEpoch) if editor.focused and editor.cursorVisible: let cursor = editor.locationRect(editor.cursor) sk.drawRect(textOrigin + cursor.xy, cursor.wh, textColor) sk.popClipRect() - sk.drawScrollbars( - editor, window, outerRect, innerRect, sk.mousePos, sk.clipRect - ) - if mouseInside and window.scrollDelta.y != 0: - editor.scrollBy(window.scrollDelta.y * TextBoxScrollSpeed, innerRect.h) + block: + let wordWrap = editor.wordWrap + editor.wordWrap = scrollbarHeight == 0 + defer: + editor.wordWrap = wordWrap + sk.drawScrollbars( + editor, window, outerRect, innerRect, sk.mousePos, sk.clipRect, + measuredWidth = state.contentWidth + ) + if mouseInside: + let horizontal = + if shift and window.scrollDelta.x == 0: + window.scrollDelta.y + else: + window.scrollDelta.x + if horizontal != 0 and maxScrollX > 0: + editor.scrollPos.x = clamp( + editor.scrollPos.x + horizontal * TextBoxScrollSpeed, + 0.0'f, + maxScrollX + ) + if not shift and window.scrollDelta.y != 0: + editor.scrollBy(window.scrollDelta.y * TextBoxScrollSpeed, innerRect.h) sk.advance(vec2(boxWidth, boxHeight)) template richTextBox*( diff --git a/src/silky/scrolls.nim b/src/silky/scrolls.nim new file mode 100644 index 00000000..761dd0bf --- /dev/null +++ b/src/silky/scrolls.nim @@ -0,0 +1,338 @@ +import + std/[math, monotimes], + vmath, bumpy + +const + TouchPanThreshold = 6.0'f + TouchScrollbarWidth = 28.0'f + # UIKit's normal rate, applied per millisecond of elapsed time. + ScrollDeceleration* = 0.998 + MinimumFlingSpeed = 50.0 + ScrollStopSpeed = 5.0 + MaximumFrameGap = 250.0 + +type + TouchBlocker = object + bounds, clip: Rect + layer: int + + ScrollRegion = object + target: pointer + bounds, clip: Rect + tracks, thumbs: array[2, Rect] + position, maximum, signs: Vec2 + layer, depth: int + apply: proc(position: Vec2) + + TouchScroll* = object + ## Captures one finger gesture against the last displayed scroll regions. + previous, current: seq[ScrollRegion] + previousBlockers, currentBlockers: seq[TouchBlocker] + start, last: Vec2 + target: pointer + axis: int + offset: float32 + coastPosition, coastVelocity, coastTime: float64 + coasting, consumeTap: bool + pending, dragging, scrollbar, cancelled, invalidated, tap: bool + suppress*, touchInput*: bool + +proc scrollMilliseconds*(): float64 {.raises: [].} = + ## Reads monotonic time without quantizing high-refresh animation frames. + getMonoTime().ticks.float64 / 1_000_000 + +proc momentumActive*(touch: TouchScroll): bool = + ## Reports whether another animation frame is needed after finger release. + touch.coasting + +proc stopMomentum(touch: var TouchScroll) = + ## Releases an inertial target without changing its current scroll position. + touch.coasting = false + touch.coastVelocity = 0 + touch.target = nil + +proc component(value: Vec2, axis: int): float32 = + ## Selects a horizontal or vertical component. + if axis == 0: value.x else: value.y + +proc setComponent(value: var Vec2, axis: int, amount: float32) = + ## Changes one component without moving the other axis. + if axis == 0: value.x = amount + else: value.y = amount + +proc rebaseMomentum*(touch: var TouchScroll, target: pointer, position: Vec2) = + ## Preserves velocity when content anchoring intentionally moves the viewport. + if touch.coasting and touch.target == target: + touch.coastPosition = component(position, touch.axis).float64 + +proc preferred(region, other: ScrollRegion): bool = + ## Prefers the top layer and then the deepest nested scrollable widget. + region.layer > other.layer or + (region.layer == other.layer and region.depth >= other.depth) + +proc trackHit(region: ScrollRegion, axis: int, point: Vec2): bool = + ## Widens the invisible hit corridor inward while retaining clipping. + if component(region.maximum, axis) <= 0: + return false + var hit = region.tracks[axis] + if axis == 0: + hit.y -= max(0.0'f, TouchScrollbarWidth - hit.h) + hit.h = TouchScrollbarWidth + else: + hit.x -= max(0.0'f, TouchScrollbarWidth - hit.w) + hit.w = TouchScrollbarWidth + point.overlaps(hit) and point.overlaps(region.bounds) and + point.overlaps(region.clip) + +proc beginTouchFrame*( + touch: var TouchScroll, + isTouch, pressed, down, released, focused: bool, + point, motion: Vec2, + velocity: Vec2 = vec2(0), + nowMs: float64 = scrollMilliseconds(), + interrupted = false +) = + ## Resolves ownership before widgets draw or virtualize their contents. + touch.suppress = false + touch.touchInput = isTouch + touch.tap = false + if not isTouch or not focused or point.x < 0 or point.y < 0 or interrupted: + touch.pending = false + touch.dragging = false + touch.cancelled = false + touch.consumeTap = false + touch.stopMomentum() + return + if touch.cancelled: + touch.suppress = true + if released or not down: + touch.cancelled = false + return + var barrier = 0 + let hitPoint = if pressed: point - motion else: touch.start + if pressed: + touch.consumeTap = false + if touch.coasting: + for region in touch.previous: + if region.target == touch.target: + touch.consumeTap = hitPoint.overlaps(region.bounds) and + hitPoint.overlaps(region.clip) + break + touch.stopMomentum() + elif touch.coasting: + let elapsed = nowMs - touch.coastTime + if elapsed < 0 or elapsed > MaximumFrameGap: + touch.stopMomentum() + return + var found = false + for region in touch.previous: + if region.target != touch.target: + continue + found = true + # Respect an application scroll jump instead of pulling it back. + if component(region.position, touch.axis) != touch.coastPosition.float32: + touch.stopMomentum() + break + let + maximum = component(region.maximum, touch.axis).float64 + remainingMs = max(0.0, ln(ScrollStopSpeed / + abs(touch.coastVelocity)) / ln(ScrollDeceleration)) + duration = min(elapsed, remainingMs) + decay = pow(ScrollDeceleration, duration) + # Preserves the projection Apple published in WWDC 2018 session 803. + distance = touch.coastVelocity / 1000 * ScrollDeceleration / + (1 - ScrollDeceleration) * (1 - decay) + nextPosition = clamp(touch.coastPosition + distance, 0.0, maximum) + var position = region.position + position.setComponent(touch.axis, nextPosition.float32) + region.apply(position) + touch.coastPosition = nextPosition + touch.coastVelocity *= decay + touch.coastTime = nowMs + touch.suppress = true + if elapsed >= remainingMs or nextPosition <= 0 or + nextPosition >= maximum: + touch.stopMomentum() + break + if not found: + touch.stopMomentum() + return + for blocker in touch.previousBlockers: + if hitPoint.overlaps(blocker.bounds) and hitPoint.overlaps(blocker.clip): + barrier = max(barrier, blocker.layer) + if pressed: + # Native motion excludes the initial jump to the finger-down position. + touch.start = hitPoint + touch.last = hitPoint + touch.pending = true + touch.dragging = false + touch.scrollbar = false + touch.target = nil + var candidate = -1 + for i, region in touch.previous: + for axis in 0 .. 1: + if region.layer >= barrier and region.trackHit(axis, hitPoint) and + (candidate < 0 or region.preferred(touch.previous[candidate])): + candidate = i + touch.axis = axis + if candidate >= 0: + let region = touch.previous[candidate] + touch.target = region.target + touch.scrollbar = true + touch.dragging = true + let thumb = region.thumbs[touch.axis] + touch.offset = + if component(hitPoint, touch.axis) >= component(thumb.xy, touch.axis) and + component(hitPoint, touch.axis) <= + component(thumb.xy + thumb.wh, touch.axis): + component(hitPoint - thumb.xy, touch.axis) + else: + component(thumb.wh, touch.axis) / 2 + let distance = point - touch.start + touch.suppress = touch.consumeTap and touch.pending + if touch.pending and not touch.dragging and + max(abs(distance.x), abs(distance.y)) >= TouchPanThreshold: + touch.axis = if abs(distance.x) > abs(distance.y): 0 else: 1 + var candidate = -1 + for i, region in touch.previous: + if region.layer >= barrier and + component(region.maximum, touch.axis) > 0 and + touch.start.overlaps(region.bounds) and + touch.start.overlaps(region.clip) and + (candidate < 0 or region.preferred(touch.previous[candidate])): + candidate = i + if candidate >= 0: + touch.target = touch.previous[candidate].target + touch.dragging = true + if touch.dragging: + touch.suppress = true + for region in touch.previous: + if region.target != touch.target: + continue + var position = region.position + let maximum = component(region.maximum, touch.axis) + if touch.scrollbar: + let + track = region.tracks[touch.axis] + thumb = region.thumbs[touch.axis] + travel = component(track.wh - thumb.wh, touch.axis) + if travel > 0: + var fraction = clamp( + (component(point - track.xy, touch.axis) - touch.offset) / travel, + 0.0'f, 1.0'f + ) + if component(region.signs, touch.axis) < 0: + fraction = 1 - fraction + position.setComponent(touch.axis, fraction * maximum) + else: + let delta = component(point - touch.last, touch.axis) + position.setComponent(touch.axis, clamp( + component(position, touch.axis) - + component(region.signs, touch.axis) * delta, + 0.0'f, maximum + )) + region.apply(position) + if released and not touch.scrollbar: + let speed = -component(region.signs, touch.axis).float64 * + component(velocity, touch.axis).float64 + if classify(speed) notin {fcNan, fcInf, fcNegInf} and + abs(speed) >= MinimumFlingSpeed and + ((speed > 0 and component(position, touch.axis) < maximum) or + (speed < 0 and component(position, touch.axis) > 0)): + touch.coasting = true + touch.coastVelocity = speed + touch.coastPosition = component(position, touch.axis).float64 + touch.coastTime = nowMs + break + touch.last = point + if released or not down: + touch.tap = touch.pending and not touch.dragging and not touch.consumeTap and + max(abs(distance.x), abs(distance.y)) < TouchPanThreshold + touch.pending = false + touch.dragging = false + touch.consumeTap = false + if not touch.coasting: + touch.target = nil + +proc resetTouchScroll*(touch: var TouchScroll) = + ## Invalidates scroll targets when the application replaces its scene. + touch.cancelled = touch.pending or touch.dragging + touch.pending = false + touch.dragging = false + touch.consumeTap = false + touch.stopMomentum() + touch.previous.setLen(0) + touch.previousBlockers.setLen(0) + touch.invalidated = true + +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) + +proc endTouchFrame*(touch: var TouchScroll) = + ## Retains displayed geometry and releases callbacks for vanished widgets. + if touch.invalidated: + touch.previous.setLen(0) + touch.previousBlockers.setLen(0) + touch.invalidated = false + else: + swap(touch.previous, touch.current) + swap(touch.previousBlockers, touch.currentBlockers) + touch.current.setLen(0) + touch.currentBlockers.setLen(0) + if touch.coasting: + var found = false + for region in touch.previous: + if region.target == touch.target: + found = true + break + if not found: + touch.stopMomentum() + +proc touchScrolling*(sk: auto): bool = + ## Reports a captured pan or scrollbar, including its final release frame. + sk.touchScroll.suppress + +proc registerTouchBlocker*(sk: auto, bounds: Rect) = + ## Keeps popup controls from passing gestures into lower visual layers. + if sk.currentDrawLayer <= 0: + return + var blocker = TouchBlocker( + bounds: bounds, clip: sk.clipRect, layer: sk.currentDrawLayer + ) + blocker.bounds.x += sk.touchOrigin.x + blocker.bounds.y += sk.touchOrigin.y + blocker.clip.x += sk.touchOrigin.x + blocker.clip.y += sk.touchOrigin.y + sk.touchScroll.currentBlockers.add(blocker) + +proc registerTouchScroll*( + sk: auto, + target: pointer, + bounds: Rect, + position, maximum, signs: Vec2, + tracks, thumbs: array[2, Rect], + depth: int, + apply: proc(position: Vec2) +) = + ## Registers a clipped scroll target in window coordinates, including insets. + if (maximum.x <= 0 and maximum.y <= 0) or + sk.mousePos.x <= -1000 or sk.mousePos.y <= -1000: + return + var region = ScrollRegion( + target: target, bounds: bounds, clip: sk.clipRect, + position: position, maximum: maximum, signs: signs, + tracks: tracks, thumbs: thumbs, + layer: sk.currentDrawLayer, depth: depth, apply: apply + ) + region.bounds.x += sk.touchOrigin.x + region.bounds.y += sk.touchOrigin.y + region.clip.x += sk.touchOrigin.x + region.clip.y += sk.touchOrigin.y + for axis in 0 .. 1: + region.tracks[axis].x += sk.touchOrigin.x + region.tracks[axis].y += sk.touchOrigin.y + region.thumbs[axis].x += sk.touchOrigin.x + region.thumbs[axis].y += sk.touchOrigin.y + sk.touchScroll.current.add(region) diff --git a/src/silky/semantics.nim b/src/silky/semantics.nim index 8de545ae..adc8eb71 100644 --- a/src/silky/semantics.nim +++ b/src/silky/semantics.nim @@ -3,12 +3,12 @@ import std/[algorithm, strutils, tables, unicode, times], vmath, bumpy, chroma, pixie, - silky/[atlas, clips, frames, layout], testwindow, + silky/[atlas, clips, common, frames, interactions, scrolls, layout], testwindow, silky/internal/inputs from windy/common import Button, CursorKind, Cursor -export frames, layout +export frames, interactions, scrolls, layout const LineFeedRune = Rune(10) @@ -267,13 +267,6 @@ type clipPos*: Vec2 clipSize*: Vec2 - Interactor* = object - ## Solve which widget the mouse is interacting with. - currentId*: int = -1 - warmId*: int = -1 - warmLayer*: int = -1 - hotId*: int = -1 - Silky* = ref object ## Main Silky context for testing mode without GPU. inFrame: bool = false @@ -306,6 +299,8 @@ type lastMousePos*: Vec2 tooltipThreshold*: float64 = 0.5 atlas*: SilkyAtlas + textures: Table[uint32, IVec2] + nextTexture: uint32 layers*: array[2, seq[SilkyVertex]] currentLayer*: int layerStack*: seq[int] @@ -315,6 +310,10 @@ type avgFrameTime*: float64 semantic*: SemanticCapture interactor*: Interactor + touchScroll*: TouchScroll + touchTimeMs*: float64 = -1 + touchOrigin*: Vec2 + ## Logical window offset applied when the app removes safe-area insets. window*: Window proc currentDrawLayer*(sk: Silky): int = @@ -329,7 +328,7 @@ proc renderMode*(sk: Silky): RenderMode = sk.frames.mode proc requestFrame*(sk: Silky, delayMs = 0) = - ## Invalidates app data or schedules a visible animation on the UI thread. + ## Invalidates data or schedules an animation frame on the UI thread. sk.frames.requestFrame(delayMs) proc `renderMode=`*(sk: Silky, mode: RenderMode) = @@ -560,6 +559,41 @@ proc drawQuad*(sk: Silky, pos: Vec2, size: Vec2, uvPos: Vec2, uvSize: Vec2, colo ## Stub for drawing a textured quad. discard +proc allocateTexture*(sk: Silky, width, height: int): uint32 = + ## Records independent image storage without allocating GPU resources. + if width <= 0 or height <= 0: + raise newException(SilkyError, "Image texture dimensions must be positive.") + inc sk.nextTexture + result = sk.nextTexture + sk.textures[result] = ivec2(width.int32, height.int32) + +proc uploadTextureRows*( + sk: Silky, + texture: uint32, + image: Image, + firstRow, rowCount: int +) = + ## Validates incremental image transfers without touching a GPU. + if texture notin sk.textures or image == nil: + raise newException(SilkyError, "Cannot upload an unknown image texture.") + if sk.textures[texture] != ivec2(image.width.int32, image.height.int32) or + firstRow < 0 or rowCount < 0 or firstRow > image.height or + rowCount > image.height - firstRow: + raise newException(SilkyError, "Image texture upload bounds are invalid.") + +proc deleteTexture*(sk: Silky, texture: uint32) = + ## Releases a semantic texture record while leaving other images intact. + sk.textures.del(texture) + +proc drawTexture*( + sk: Silky, + texture: uint32, + pos, size, pixels: Vec2, + color = rgbx(255, 255, 255, 255) +) = + ## Preserves the native image API during semantic tests without GPU draws. + discard + proc drawImage*( sk: Silky, name: string, @@ -660,12 +694,22 @@ proc newSilky*(window: Window, atlasPngPath: string): Silky = proc beginUi*(sk: Silky, window: auto, size: IVec2) = ## Begins a new UI frame. + sk.cursor = Cursor(kind: ArrowCursor) if sk.frames.mode == OnDemandRender: sk.frameHadInput = sk.frameInput.inputChanged( window, sk.inputs.hasPendingEvents() ) sk.frames.beginFrame() - sk.cursor = Cursor(kind: ArrowCursor) + sk.touchScroll.beginTouchFrame( + window.pointerSource == TouchPointer, + window.buttonPressed[MouseLeft], window.buttonDown[MouseLeft], + window.buttonReleased[MouseLeft], window.focused, + window.mousePos.vec2 / sk.uiScale, + window.mouseDelta.vec2 / sk.uiScale, + velocity = window.pointerVelocity / sk.uiScale, + nowMs = (if sk.touchTimeMs >= 0: sk.touchTimeMs else: scrollMilliseconds()), + interrupted = window.scrollDelta != vec2(0) + ) sk.inputs.beginInputFrame(window) sk.tooltipActive = sk.showTooltip sk.showTooltip = false @@ -690,23 +734,19 @@ proc beginUi*(sk: Silky, window: auto, size: IVec2) = sk.pushClipRect(rect(0, 0, sk.size.x, sk.size.y)) sk.semantic.reset() -proc endInteractions(interactor: var Interactor) = - ## Commit warm state and resets per-frame counters. - interactor.hotId = interactor.warmId - interactor.warmId = -1 - interactor.warmLayer = -1 - interactor.currentId = -1 - proc resetInteractions*(sk: Silky) = - ## Clear all interaction state. - sk.interactor.hotId = -1 + ## Invalidates cached pointer targets. + sk.interactor.resetInteractions() + sk.touchScroll.resetTouchScroll() proc endUi*(sk: Silky) = ## Ends the current UI frame. if sk.frames.mode == OnDemandRender: if sk.frameHadInput or sk.interactor.hotId != sk.interactor.warmId: sk.requestFrame() - if sk.window.buttonDown[MouseLeft]: + if sk.touchScroll.momentumActive(): + sk.requestFrame() + elif sk.window.buttonDown[MouseLeft]: sk.requestFrame(16) let previousCursor = sk.window.cursor if previousCursor.kind != sk.cursor.kind or @@ -715,6 +755,7 @@ proc endUi*(sk: Silky) = previousCursor.hotspot != sk.cursor.hotspot)): sk.window.cursor = sk.cursor sk.interactor.endInteractions() + sk.touchScroll.endTouchFrame() sk.clear() sk.popLayout() sk.popClipRect() @@ -725,15 +766,21 @@ proc endUi*(sk: Silky) = proc buttonDown*(sk: Silky): array[Button, bool] = ## Returns held buttons, excluding keyboard keys during text entry. - sk.inputs.filterButtons(sk.window.buttonDown) + result = sk.inputs.filterButtons(sk.window.buttonDown) + if sk.touchScrolling: + result[MouseLeft] = false proc buttonPressed*(sk: Silky): array[Button, bool] = ## Returns pressed buttons, excluding keyboard keys during text entry. - sk.inputs.filterButtons(sk.window.buttonPressed) + result = sk.inputs.filterButtons(sk.window.buttonPressed) + if sk.touchScrolling: + result[MouseLeft] = false proc buttonReleased*(sk: Silky): array[Button, bool] = ## Returns released buttons, excluding keyboard keys during text entry. - sk.inputs.filterButtons(sk.window.buttonReleased) + result = sk.inputs.filterButtons(sk.window.buttonReleased) + if sk.touchScrolling: + result[MouseLeft] = false proc beginWidget*(sk: Silky, kind: string, name = "", text = "", rect = rect(0f, 0f, 0f, 0f)) {.inline.} = ## Begins a new semantic widget node. diff --git a/src/silky/testwindow.nim b/src/silky/testwindow.nim index a4279c6e..8bf1cea4 100644 --- a/src/silky/testwindow.nim +++ b/src/silky/testwindow.nim @@ -4,10 +4,10 @@ import std/unicode, vmath from windy/common import - Button, CursorKind, Cursor, TextInputState, TextInputEdit, + Button, PointerSource, CursorKind, Cursor, TextInputState, TextInputEdit, TextInputEditKind, TextInputEditCallback export - Button, CursorKind, Cursor, unicode, TextInputState, TextInputEdit, + Button, PointerSource, CursorKind, Cursor, unicode, TextInputState, TextInputEdit, TextInputEditKind, TextInputEditCallback type Window* = ref object @@ -21,6 +21,8 @@ type Window* = ref object buttonPressed*: array[Button, bool] buttonReleased*: array[Button, bool] scrollDelta*: Vec2 + pointerSource*: PointerSource + pointerVelocity*: Vec2 ## Starts true so `while not window.closeRequested` loops exit immediately in tests. closeRequested*: bool = true cursor*: Cursor = Cursor(kind: ArrowCursor) @@ -92,6 +94,9 @@ proc resetInputState*(w: Window) = proc pressButton*(w: Window, button: Button) = ## Simulates pressing a button, including repeated presses. + if button == MouseLeft and w.pointerSource == TouchPointer: + w.mouseDelta = ivec2(0, 0) + w.pointerVelocity = vec2(0) w.buttonDown[button] = true w.buttonPressed[button] = true if w.onButtonPress != nil: @@ -137,7 +142,10 @@ proc moveMouse*(w: Window, x, y: int) = ## Moves the simulated mouse cursor to the given position. let newPos = ivec2(x.int32, y.int32) w.mousePrevPos = w.mousePos - w.mouseDelta = newPos - w.mousePos + if w.pointerSource == TouchPointer: + w.mouseDelta += newPos - w.mousePos + else: + w.mouseDelta = newPos - w.mousePos w.mousePos = newPos template mousePos*(w: Window): Vec2 = diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index 3c5adc3c..2661df62 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -50,6 +50,8 @@ else: type TextBoxState* = ref object ## State for a multi-line text box widget. + onInput*: proc(state: TextBoxState, event: InputEvent): bool + ## Returns true to consume an ordered editable input event. runes*: seq[Rune] cursor*: int selector*: int @@ -312,11 +314,13 @@ proc getSelectionRects*(layout: seq[Rect], start, stop: int): seq[Rect] = result.add selectRect proc innerHeight*(state: TextBoxState): float32 = - ## Returns the total content height. + ## Returns the total content height, including the final empty editable line. if state.positionedLayout: return state.layoutHeight if state.layout.len > 0: let lastPos = state.layout[^1] + if not state.singleLine and state.runes.len > 0 and state.runes[^1] == LF: + return lastPos.y + lastPos.h + state.lineHeight return lastPos.y + lastPos.h return state.lineHeight @@ -891,12 +895,12 @@ proc handleKey(state: TextBoxState, event: InputEvent) = if ctrl: state.selectAll() of KeyC: - if ctrl: + if ctrl and not state.password: let copied = state.copyText() if copied.len > 0: setClipboardString(copied) of KeyX: - if ctrl: + if ctrl and not state.password: let cut = state.cutText() if cut.len > 0: setClipboardString(cut) @@ -917,8 +921,9 @@ proc handleKey(state: TextBoxState, event: InputEvent) = else: discard -proc handleSelectionInput*(state: TextBoxState, inputs: TextInputs) = - ## Drains read-only navigation and copy events without accepting edits. +proc handleSelectionInput*(state: TextBoxState, inputs: TextInputs): bool + {.discardable.} = + ## Drains read-only input and reports navigation for parent scrolling. assert not state.enabled let epoch = inputs.focusEpoch @@ -928,6 +933,11 @@ proc handleSelectionInput*(state: TextBoxState, inputs: TextInputs) = break if event.kind == InputKind.KeyDown: state.handleKey(event) + if event.button in { + KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, + KeyPageUp, KeyPageDown + }: + result = true if events.len > 0: state.scrollToCursor() @@ -947,6 +957,11 @@ proc handleInput( for event in events: if inputs.focusEpoch != epoch: break + let handled = state.onInput != nil and state.onInput(state, event) + if inputs.focusEpoch != epoch: + break + if handled: + continue case event.kind of TextInput: state.typeCharacter(event.rune) @@ -978,22 +993,25 @@ proc handleInput( state.computeLayout(fontData, maxWidth) state.scrollToCursor() -proc drawScrollbars*(sk: Silky, state: TextBoxState, window: Window, - outerRect, innerRect: Rect, mouseVec: Vec2, clipRect: Rect) = +proc drawScrollbars*( + sk: Silky, + state: TextBoxState, + window: Window, + outerRect, innerRect: Rect, + mouseVec: Vec2, + clipRect: Rect, + measuredWidth = -1.0'f +) = ## Draws scrollbar tracks and handles, and processes drag interaction. let contentH = state.innerHeight - let contentW = state.innerWidth + let contentW = + if measuredWidth >= 0: measuredWidth + else: state.innerWidth let scrollMaxY = max(0.0f, contentH - innerRect.h) let scrollMaxX = max(0.0f, contentW - innerRect.w) let hasScrollY = contentH > innerRect.h let hasScrollX = not state.wordWrap and contentW > innerRect.w - # Release scrollbar drag when mouse released. - if state.scrollingY and - (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): - state.scrollingY = false - if state.scrollingX and - (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): - state.scrollingX = false + var tracks, thumbs: array[2, Rect] # Y scrollbar. if hasScrollY: let trackRect = rect( @@ -1003,23 +1021,28 @@ proc drawScrollbars*(sk: Silky, state: TextBoxState, window: Window, innerRect.h - 4 - (if hasScrollX: 10.0f else: 0.0f) ) sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, trackRect.xy, trackRect.wh) - let posPct = if scrollMaxY > 0: state.scrollPos.y / scrollMaxY else: 0.0f - let sizePct = innerRect.h / contentH + let + posPct = if scrollMaxY > 0: state.scrollPos.y / scrollMaxY else: 0.0f + thumbHeight = min(trackRect.h, + max(16.0'f, trackRect.h * innerRect.h / contentH)) let handleRect = rect( trackRect.x, - trackRect.y + (trackRect.h - trackRect.h * sizePct) * posPct, + trackRect.y + (trackRect.h - thumbHeight) * posPct, 8, - trackRect.h * sizePct + thumbHeight ) + tracks[1] = trackRect + thumbs[1] = handleRect if state.scrollingY: let relY = mouseVec.y - state.scrollDragOffset.y - trackRect.y let availH = trackRect.h - handleRect.h if availH > 0: state.scrollPos.y = clamp(relY / availH, 0.0f, 1.0f) * scrollMaxY - elif mouseVec.overlaps(handleRect) and mouseVec.overlaps(clipRect): - if window.buttonPressed[MouseLeft]: - state.scrollingY = true - state.scrollDragOffset.y = mouseVec.y - handleRect.y + elif window.pointerSource != TouchPointer and + mouseVec.overlaps(handleRect) and mouseVec.overlaps(clipRect): + 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) # X scrollbar. if hasScrollX: @@ -1030,25 +1053,45 @@ proc drawScrollbars*(sk: Silky, state: TextBoxState, window: Window, 8 ) sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, trackRect.xy, trackRect.wh) - let posPct = if scrollMaxX > 0: state.scrollPos.x / scrollMaxX else: 0.0f - let sizePct = innerRect.w / contentW + let + posPct = if scrollMaxX > 0: state.scrollPos.x / scrollMaxX else: 0.0f + thumbWidth = min(trackRect.w, + max(16.0'f, trackRect.w * innerRect.w / contentW)) let handleRect = rect( - trackRect.x + (trackRect.w - trackRect.w * sizePct) * posPct, + trackRect.x + (trackRect.w - thumbWidth) * posPct, trackRect.y, - trackRect.w * sizePct, + thumbWidth, 8 ) + tracks[0] = trackRect + thumbs[0] = handleRect if state.scrollingX: let relX = mouseVec.x - state.scrollDragOffset.x - trackRect.x let availW = trackRect.w - handleRect.w if availW > 0: state.scrollPos.x = clamp(relX / availW, 0.0f, 1.0f) * scrollMaxX - elif mouseVec.overlaps(handleRect) and mouseVec.overlaps(clipRect): - if window.buttonPressed[MouseLeft]: - state.scrollingX = true - state.scrollDragOffset.x = mouseVec.x - handleRect.x + elif window.pointerSource != TouchPointer and + mouseVec.overlaps(handleRect) and mouseVec.overlaps(clipRect): + 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) + # Release scrollbar drag when mouse released. + if state.scrollingY and + (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): + state.scrollingY = false + if state.scrollingX and + (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): + state.scrollingX = false + sk.registerTouchScroll( + cast[pointer](state), outerRect, state.scrollPos, + vec2(if hasScrollX: scrollMaxX else: 0.0'f, scrollMaxY), + vec2(1, 1), tracks, thumbs, sk.layoutStack.len + 1, + proc(position: Vec2) = + state.scrollPos = position + ) + proc textBox*( sk: Silky, window: Window, @@ -1124,7 +1167,11 @@ proc textBox*( let mouseInside = mouseVec.overlaps(outerRect) and mouseVec.overlaps(sk.clipRect) let onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) - if window.buttonPressed[MouseLeft]: + if sk.touchScrolling: + if state.dragging: + state.selector = state.cursor + state.dragging = false + if sk.buttonPressed[MouseLeft]: if mouseInside and not onScrollbar: state.focused = true let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -1147,7 +1194,7 @@ proc textBox*( if not enabled: state.selector = state.cursor if state.dragging and not state.scrollingX and not state.scrollingY: - if window.buttonDown[MouseLeft] and not window.buttonPressed[MouseLeft]: + if sk.buttonDown[MouseLeft] and not sk.buttonPressed[MouseLeft]: let localMouse = mouseVec - innerRect.xy + state.scrollPos state.mouseAction(localMouse, click = false, shift = true) if window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]: @@ -1210,7 +1257,7 @@ proc textBox*( window.scrollDelta.y != 0: state.scrollBy( window.scrollDelta.y * TextBoxScrollSpeed, innerRect.h) - if state.focused and enabled and not password: + if state.focused and enabled and (not password or defined(ios)): let selection = state.selection var visibleStart = state.runes.len @@ -1233,7 +1280,8 @@ proc textBox*( visibleStart: visibleStart, visibleEnd: visibleEnd, bounds: rect(innerRect.xy * sk.uiScale, innerRect.wh * sk.uiScale), - multiline: not singleLine + multiline: not singleLine, + password: password ), textLayer, firstVertex) sk.advance(vec2(boxWidth, boxHeight)) diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index 344711c4..bb5c515b 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -56,24 +56,6 @@ var scrubberStates*: Table[string, ScrubberState] dropDownStates*: Table[uint, DropDownState] -proc mouseHover( - interactor: var Interactor, - mousePos: Vec2, - clipRect: Rect, - layer: int, - widgetRect: Rect -): bool = - ## Resolve mouse hovering by taking information from the last frame. - inc interactor.currentId - - let hovering = mousePos.overlaps(widgetRect) and mousePos.overlaps(clipRect) - - if hovering and layer >= interactor.warmLayer: - interactor.warmLayer = layer - interactor.warmId = interactor.currentId - - return interactor.hotId == interactor.currentId and hovering - proc mouseHover*(sk: Silky, window: Window, r: Rect): bool = discard window let hit = sk.interactor.mouseHover(sk.mousePos, sk.clipRect, sk.currentDrawLayer, r) @@ -86,6 +68,7 @@ proc interact*( isError: bool = false ): Interaction = ## Determine the interaction given mouse and widget states. + sk.registerTouchBlocker(widgetRect) let hover = sk.interactor.mouseHover(sk.mousePos, sk.clipRect, sk.currentDrawLayer, widgetRect) pressed = sk.buttonPressed[MouseLeft] @@ -96,6 +79,9 @@ proc interact*( return Disabled if isError: return Error + if released and sk.touchScroll.touchInput and + not sk.touchTap(widgetRect): + return ReleasedOutside if not hover and released: return ReleasedOutside if not hover: @@ -108,6 +94,11 @@ proc interact*( return Released return Hovered +proc isReleased*(interaction: Interaction, window: Window): bool = + ## Includes a complete press and release delivered before one UI frame. + interaction == Released or + (interaction == Pressed and window.buttonReleased[MouseLeft]) + proc vec2(v: SomeNumber): Vec2 = ## Create a Vec2 from a number. vec2(v.float32, v.float32) @@ -170,7 +161,7 @@ proc subWindowStart*( sk.draw9Patch("header.9patch", sk.theme.headerPatch, sk.pos, sk.size) of Pressed: subWindowState.dragOffset = sk.mousePos - subWindowState.pos - subWindowState.dragging = true + subWindowState.dragging = window.buttonDown[MouseLeft] sk.draw9Patch("header.dragging.9patch", sk.theme.headerPatch, sk.pos, sk.size) of Held: discard @@ -250,7 +241,7 @@ proc subWindowEnd*(sk: Silky, window: Window, subWindowState: SubWindowState) = case resizeHandleInteraction of Pressed: - subWindowState.resizing = true + subWindowState.resizing = window.buttonDown[MouseLeft] subWindowState.resizeOffset = sk.mousePos - subWindowState.size of Hovered, Released, ReleasedOutside: subWindowState.resizing = false @@ -322,12 +313,8 @@ proc frameScrollbars*( ## overflow. At rest (t = 0) the origin edge is pinned: a bottom-origin ## frame rests scrolled to the bottom, and its thumb rests at the ## bottom of the track, moving away from the origin as t grows. - if frameState.scrollingY and - (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): - frameState.scrollingY = false - if frameState.scrollingX and - (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): - frameState.scrollingX = false + const MinThumbSize = 16.0'f + var tracks, thumbs: array[2, Rect] let scrollMax = max(contentSize - frameRect.wh, vec2(0, 0)) @@ -362,9 +349,12 @@ proc frameScrollbars*( frameRect.x + frameRect.w - 10, frameRect.y + 2, 8, - frameRect.h - 4 - 10 + max(0.0'f, frameRect.h - 4 - 10) + ) + thumbH = min( + track.h, + max(MinThumbSize, track.h * (frameRect.h / contentSize.y)) ) - thumbH = track.h * (frameRect.h / contentSize.y) travel = track.h - thumbH sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, track.xy, track.wh) @@ -376,6 +366,7 @@ proc frameScrollbars*( offsetFrac = if signs.y >= 0: frac else: 1.0'f - frac rect(track.x, track.y + travel * offsetFrac, 8, thumbH) + tracks[1] = track if frameState.scrollingY: if travel > 0: let rel = sk.mousePos.y - frameState.scrollDragOffset.y - track.y @@ -385,10 +376,12 @@ proc frameScrollbars*( frameState.scrollPos.y = frac * scrollMax.y else: let thumb = thumbRectY() - if sk.interact(thumb, true) == Pressed: - frameState.scrollingY = true - frameState.scrollDragOffset.y = sk.mousePos.y - thumb.y + if sk.interact(thumb, true) == Pressed and + window.pointerSource != TouchPointer: + frameState.scrollingY = window.buttonDown[MouseLeft] + 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) # X scrollbar. @@ -397,10 +390,13 @@ proc frameScrollbars*( track = rect( frameRect.x + 2, frameRect.y + frameRect.h - 10, - frameRect.w - 4 - 10, + max(0.0'f, frameRect.w - 4 - 10), 8 ) - thumbW = track.w * (frameRect.w / contentSize.x) + thumbW = min( + track.w, + max(MinThumbSize, track.w * (frameRect.w / contentSize.x)) + ) travel = track.w - thumbW sk.draw9Patch("scrollbar.track.9patch", sk.theme.scrollbarTrackPatch, track.xy, track.wh) @@ -412,6 +408,7 @@ proc frameScrollbars*( offsetFrac = if signs.x >= 0: frac else: 1.0'f - frac rect(track.x + travel * offsetFrac, track.y, thumbW, 8) + tracks[0] = track if frameState.scrollingX: if travel > 0: let rel = sk.mousePos.x - frameState.scrollDragOffset.x - track.x @@ -421,12 +418,28 @@ proc frameScrollbars*( frameState.scrollPos.x = frac * scrollMax.x else: let thumb = thumbRectX() - if sk.interact(thumb, true) == Pressed: - frameState.scrollingX = true - frameState.scrollDragOffset.x = sk.mousePos.x - thumb.x + if sk.interact(thumb, true) == Pressed and + window.pointerSource != TouchPointer: + frameState.scrollingX = window.buttonDown[MouseLeft] + 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 frameState.scrollingY and + (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): + frameState.scrollingY = false + if frameState.scrollingX and + (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): + frameState.scrollingX = false + + sk.registerTouchScroll( + cast[pointer](frameState), frameRect, frameState.scrollPos, scrollMax, + signs, tracks, thumbs, sk.layoutStack.len, + proc(position: Vec2) = + frameState.scrollPos = position + ) + proc frameEnd*(sk: Silky, window: Window, frameState: FrameState, originPos: Vec2) = ## Finish a scrollable frame and handle scrollbars. # stretchAt is in scrolled coordinates; add scrollPos back and 16 for @@ -498,7 +511,7 @@ template sizedButton( sk.draw9Patch(patch, sk.theme.buttonPatch, buttonOrigin, buttonSize) - if interaction == Released: + if interaction.isReleased(window): body when defined(silkyTesting): @@ -573,6 +586,8 @@ template iconButton*(image: string, body) = sk.hover = true sk.tooltipAnchor = buttonRect patch = "button.down.9patch" + if interaction.isReleased(window): + body of Released: sk.hover = false body @@ -608,7 +623,10 @@ template clickableIcon*(image: string, on: bool, body) = if sk.hover: sk.tooltipAnchor = iconRect - if interaction == Pressed: + if window.pointerSource == TouchPointer: + if interaction.isReleased(window) and sk.touchTap(iconRect): + body + elif interaction == Pressed: body sk.drawImage(image, sk.at, color) @@ -629,7 +647,7 @@ template radioButton*[T](label: string, variable: var T, value: T) = let interaction = sk.interact(hitRect, true) - if interaction == Released: + if interaction.isReleased(window): variable = value let @@ -669,7 +687,7 @@ template checkBox*(label: string, value: var bool) = let interaction = sk.interact(hitRect, true) - if interaction == Released: + if interaction.isReleased(window): value = not value let @@ -721,7 +739,7 @@ template dropDown*[T](selected: var T, options: openArray[T]) = if interaction == Pressed: state.pressed = true if window.buttonReleased[MouseLeft]: - if state.pressed and interaction == Released: + if state.pressed and interaction.isReleased(window): state.open = not state.open state.pressed = false @@ -767,7 +785,7 @@ template dropDown*[T](selected: var T, options: openArray[T]) = if interaction == Pressed: state.pressedOption = i - if interaction == Released and state.pressedOption == i: + if interaction.isReleased(window) and state.pressedOption == i: selected = opt state.open = false @@ -813,7 +831,7 @@ template listBox*[T](id: string, items: seq[T], selectedIndex: var int) = interaction = sk.interact(rowRect, true) rowHover = interaction in [Pressed, Held, Hovered] - if interaction == Released: + if interaction.isReleased(window): selectedIndex = i if rowHover: @@ -983,7 +1001,7 @@ template scrubber*[T, U](id: string, value: var T, minVal: T, maxVal: U, label: let t = clamp((sk.mousePos.x - trackStart) / travelSafe, 0f, 1f) value = (minF + t * range).T elif pressed: - scrubState.dragging = true + scrubState.dragging = window.buttonDown[MouseLeft] let t = clamp((sk.mousePos.x - trackStart) / travelSafe, 0f, 1f) value = (minF + t * range).T diff --git a/tests/metal_shader_pixels.m b/tests/metal_shader_pixels.m new file mode 100644 index 00000000..805ad825 --- /dev/null +++ b/tests/metal_shader_pixels.m @@ -0,0 +1,181 @@ +// Invoked by test_metal_shader_pixels.nim with its generated shader directory. +#import +#import + +typedef struct __attribute__((packed)) { + float pos[2], uv[2]; + uint8_t color[4]; + float clipPos[2], clipSize[2], maskUv[2]; +} SilkyVertex; + +// Compiles the generated shaders and checks pixels from four clipped quads. +int main(int argc, const char **argv) { + @autoreleasepool { + if (argc != 2) { + NSLog(@"Expected the generated shader directory"); + return 1; + } + id device = MTLCreateSystemDefaultDevice(); + if (!device) { + NSLog(@"No Metal device"); + return 1; + } + NSError *error = nil; + NSString *directory = [NSString stringWithUTF8String:argv[1]]; + NSString *vertexSource = [NSString + stringWithContentsOfFile: + [directory stringByAppendingPathComponent:@"vertex.metal"] + encoding:NSUTF8StringEncoding error:&error]; + NSString *fragmentSource = [NSString + stringWithContentsOfFile: + [directory stringByAppendingPathComponent:@"fragment.metal"] + encoding:NSUTF8StringEncoding error:&error]; + if (!vertexSource || !fragmentSource) { + NSLog(@"Cannot read generated shaders: %@", error); + return 1; + } + id vertexLibrary = [device + newLibraryWithSource:vertexSource options:nil error:&error]; + if (!vertexLibrary) { + NSLog(@"Vertex shader failed: %@", error); + return 2; + } + id fragmentLibrary = [device + newLibraryWithSource:fragmentSource options:nil error:&error]; + if (!fragmentLibrary) { + NSLog(@"Fragment shader failed: %@", error); + return 3; + } + + MTLRenderPipelineDescriptor *descriptor = + [MTLRenderPipelineDescriptor new]; + descriptor.vertexFunction = + [vertexLibrary newFunctionWithName:@"vertexMain"]; + descriptor.fragmentFunction = + [fragmentLibrary newFunctionWithName:@"fragmentMain"]; + descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + MTLVertexDescriptor *vertices = [MTLVertexDescriptor vertexDescriptor]; + NSUInteger offsets[] = {0, 8, 16, 20, 28, 36}; + for (NSUInteger i = 0; i < 6; ++i) { + vertices.attributes[i].format = i == 2 ? + MTLVertexFormatUChar4Normalized : MTLVertexFormatFloat2; + vertices.attributes[i].offset = offsets[i]; + vertices.attributes[i].bufferIndex = 1; + } + vertices.layouts[1].stride = 44; + vertices.layouts[1].stepFunction = MTLVertexStepFunctionPerVertex; + descriptor.vertexDescriptor = vertices; + id pipeline = [device + newRenderPipelineStateWithDescriptor:descriptor error:&error]; + if (!pipeline) { + NSLog(@"Pipeline link failed: %@", error); + return 4; + } + _Static_assert(sizeof(SilkyVertex) == 44, "Unexpected vertex size"); + + MTLTextureDescriptor *targetDescriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:16 height:8 mipmapped:NO]; + targetDescriptor.storageMode = MTLStorageModeShared; + targetDescriptor.usage = MTLTextureUsageRenderTarget; + id target = [device newTextureWithDescriptor:targetDescriptor]; + MTLTextureDescriptor *atlasDescriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:4 height:1 mipmapped:NO]; + atlasDescriptor.storageMode = MTLStorageModeShared; + atlasDescriptor.usage = MTLTextureUsageShaderRead; + id atlas = [device newTextureWithDescriptor:atlasDescriptor]; + uint8_t atlasPixels[] = { + 255, 255, 255, 255, + 255, 255, 255, 255, + 128, 128, 128, 255, + 0, 0, 0, 255 + }; + [atlas replaceRegion:MTLRegionMake2D(0, 0, 4, 1) mipmapLevel:0 + withBytes:atlasPixels bytesPerRow:16]; + MTLSamplerDescriptor *samplerDescriptor = [MTLSamplerDescriptor new]; + samplerDescriptor.minFilter = MTLSamplerMinMagFilterNearest; + samplerDescriptor.magFilter = MTLSamplerMinMagFilterNearest; + samplerDescriptor.normalizedCoordinates = YES; + samplerDescriptor.sAddressMode = MTLSamplerAddressModeClampToEdge; + samplerDescriptor.tAddressMode = MTLSamplerAddressModeClampToEdge; + id sampler = + [device newSamplerStateWithDescriptor:samplerDescriptor]; + + // Raw atlas pixels exercise shader normalization, including mask UVs. + SilkyVertex vertexData[24] = {0}; + float corners[6][2] = { + {0, 0}, {4, 0}, {4, 8}, {0, 0}, {4, 8}, {0, 8} + }; + uint8_t colors[4][4] = { + {0, 0, 255, 255}, {0, 255, 0, 255}, + {255, 0, 0, 255}, {255, 0, 0, 255} + }; + for (int quad = 0; quad < 4; ++quad) { + for (int i = 0; i < 6; ++i) { + SilkyVertex *vertex = &vertexData[quad * 6 + i]; + vertex->pos[0] = quad * 4 + corners[i][0]; + vertex->pos[1] = corners[i][1]; + vertex->uv[0] = 0.5; + vertex->uv[1] = 0.5; + memcpy(vertex->color, colors[quad], 4); + vertex->clipSize[0] = 16; + vertex->clipSize[1] = 4; + vertex->maskUv[0] = quad == 0 ? -1 : quad + 0.5; + vertex->maskUv[1] = quad == 0 ? -1 : 0.5; + } + } + float uniforms[4] = {16, 8, 4, 1}; + MTLRenderPassDescriptor *pass = + [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = target; + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + pass.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1); + id queue = [device newCommandQueue]; + id command = [queue commandBuffer]; + id encoder = + [command renderCommandEncoderWithDescriptor:pass]; + [encoder setRenderPipelineState:pipeline]; + [encoder setVertexBytes:uniforms length:sizeof(uniforms) atIndex:0]; + [encoder setVertexBytes:vertexData length:sizeof(vertexData) atIndex:1]; + [encoder setFragmentTexture:atlas atIndex:0]; + [encoder setFragmentSamplerState:sampler atIndex:0]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:0 vertexCount:24]; + [encoder endEncoding]; + [command commit]; + [command waitUntilCompleted]; + if (command.error) { + NSLog(@"Offscreen render failed: %@", command.error); + return 5; + } + + // BGRA samples verify blue, green, half-masked red, and uncolored white. + uint8_t pixels[16 * 8 * 4]; + [target getBytes:pixels bytesPerRow:64 + fromRegion:MTLRegionMake2D(0, 0, 16, 8) mipmapLevel:0]; + uint8_t expected[4][4] = { + {255, 0, 0, 255}, {0, 255, 0, 255}, + {127, 127, 255, 255}, {255, 255, 255, 255} + }; + for (int quad = 0; quad < 4; ++quad) { + uint8_t *rendered = &pixels[(2 * 16 + quad * 4 + 2) * 4]; + uint8_t *clipped = &pixels[(6 * 16 + quad * 4 + 2) * 4]; + for (int channel = 0; channel < 4; ++channel) { + if (abs(rendered[channel] - expected[quad][channel]) > 1) { + NSLog(@"Quad %d channel %d: %d != %d", quad, channel, + rendered[channel], expected[quad][channel]); + return 6; + } + if (clipped[channel] != (channel == 3 ? 255 : 0)) { + NSLog(@"Clipping failed for quad %d, channel %d", quad, channel); + return 7; + } + } + } + NSLog(@"Silky Metal pixels passed: normalized colors, pixel mask UVs, " + "zero/half/full masks, uniforms, and clipping"); + } + return 0; +} diff --git a/tests/test_button_vertices.nim b/tests/test_button_vertices.nim index fcce423e..93646013 100644 --- a/tests/test_button_vertices.nim +++ b/tests/test_button_vertices.nim @@ -3,6 +3,8 @@ import bumpy, pixie, vmath, windy, silky, silky/internal/inputs +privateAccess(Silky) + const FontPath = "tests/data/IBMPlexSans-Regular.ttf" proc close(a, b: float32): bool = @@ -11,7 +13,6 @@ proc close(a, b: float32): bool = proc fixture(builder: AtlasBuilder, density: float32): Silky = ## Queues native button vertices without a platform window or GPU. - privateAccess(Silky) result = Silky( atlas: builder.atlas, image: builder.atlasImage, @@ -45,6 +46,7 @@ block: doAssert builder.addImage("button.9patch", newImage(24, 24)) let sk = fixture(builder, density) + window = sk.window reference = fixture(builder, density) origin = vec2(20.17'f, 30.29'f) textSize = sk.getTextSize("Default", "W") diff --git a/tests/test_cursor_scroll.nim b/tests/test_cursor_scroll.nim new file mode 100644 index 00000000..18f096d9 --- /dev/null +++ b/tests/test_cursor_scroll.nim @@ -0,0 +1,335 @@ +import + std/strutils, + bumpy, pixie, vmath, + silky, silky/layout + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +const + Viewport = rect(20, 30, 320, 180) + TextWidth = 308.0'f + LeadingHeight = 400.0'f + TrailingHeight = 200.0'f + Spacing = 10.0'f + +type Fixture = object + harness: TestHarness + frameId, replyId, text: string + direction: StackDirection + height: float32 + content, origin: Vec2 + caret: Rect + navigated: bool + +var + atlas: SilkyAtlas + nextId: int + +proc checkVec(actual, expected: Vec2) = + ## Compares scrolling coordinates without discarding fractional positions. + doAssert abs(actual.x - expected.x) < 0.01, $actual & " != " & $expected + doAssert abs(actual.y - expected.y) < 0.01, $actual & " != " & $expected + +block: + echo "Testing reveal margins, clamping, and all stack directions" + let + viewport = rect(20, 30, 200, 100) + content = vec2(1000, 1000) + scroll = vec2(100, 100) + for direction in StackDirection: + let signs = direction.dirSigns + checkVec( + revealScroll(scroll, content, viewport, rect(0, 10, 10, 10), direction), + scroll + signs * vec2(-24, -24) + ) + checkVec( + revealScroll( + scroll, content, viewport, rect(220, 130, 10, 10), direction + ), + scroll + signs * vec2(14, 14) + ) + checkVec( + revealScroll(scroll, content, viewport, rect(25, 35, 10, 10), direction), + scroll + ) + checkVec( + revealScroll( + scroll, content, viewport, rect(22.5, 32.5, 10, 10), direction + ), + scroll + signs * vec2(-1.5, -1.5) + ) + checkVec( + revealScroll( + scroll, content, viewport, rect(20, 30, 10, 10), direction, -5 + ), + scroll + ) + checkVec( + revealScroll( + scroll, content, rect(20, 30, 10, 10), rect(20, 30, 8, 8), + direction, 20 + ), + scroll - signs + ) + for target in [rect(-2000, -2000, 10, 10), rect(2000, 2000, 10, 10)]: + let expected = vec2( + if (target.x < 0) == (signs.x > 0): 0 else: 800, + if (target.y < 0) == (signs.y > 0): 0 else: 900 + ) + checkVec( + revealScroll(scroll, content, viewport, target, direction), expected + ) + checkVec( + revealScroll(scroll, vec2(20, 20), viewport, viewport, direction), + vec2(0, 0) + ) + + echo "Testing oversized targets stay aligned in ", direction + let + target = rect(40, 50, 300, 180) + moved = revealScroll(scroll, content, viewport, target, direction) + shifted = rect(target.xy - signs * (moved - scroll), target.wh) + checkVec(moved, scroll + signs * vec2(20, 20)) + checkVec(shifted.xy, viewport.xy) + checkVec(revealScroll(moved, content, viewport, shifted, direction), moved) + + checkVec( + revealScroll(scroll, content, rect(20, 30, 0, 100), rect(0, 10, 10, 10)), + vec2(100, 76) + ) + checkVec( + revealScroll(scroll, content, rect(20, 30, 200, 0), rect(0, 10, 10, 10)), + vec2(76, 100) + ) + +block: + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Wide", 30) + for name in [ + "textbox.disabled.9patch", "scrollbar.track.9patch", "scrollbar.9patch" + ]: + doAssert builder.addImage(name, newImage(16, 16)) + atlas = builder.atlas + +proc state(f: Fixture): RichTextBoxState = + ## Returns the document state owned by the actual rich textbox widget. + richTextBoxStates[f.replyId] + +proc frameState(f: Fixture): FrameState = + ## Returns the surrounding frame's persistent scroll state. + frameStates[f.frameId] + +proc fixture(direction: StackDirection, scale: float32): Fixture = + ## Creates a rich document taller than its scrolling parent viewport. + inc nextId + result.frameId = "cursor frame " & $nextId + result.replyId = "cursor reply " & $nextId + result.direction = direction + result.harness = newTestHarness(atlas) + result.harness.sk.theme.padding = 0 + result.harness.sk.uiScale = scale + result.text = "Heading\n" & repeat( + "Wrapped document text with several words on each line.\n", 30 + ) + let state = newRichTextBoxState(result.text) + state.blocks = @[ + TextBlock(first: 0, last: 7, font: "Wide", spacing: 8), + TextBlock(first: 8, last: result.text.len) + ] + state.computeLayout(atlas.fonts, "Default", TextWidth) + richTextBoxStates[result.replyId] = state + result.height = state.innerHeight + result.content = vec2( + Viewport.w, LeadingHeight + result.height + TrailingHeight + Spacing * 3 + ) + let initial = + if direction == BottomToTop: + LeadingHeight + Spacing + result.height - Viewport.h + 4 + else: + LeadingHeight + Spacing - 4 + frameStates[result.frameId] = FrameState(scrollPos: vec2(0, initial)) + +proc frame(f: var Fixture) = + ## Draws the real frame and reveals the caret only after keyboard navigation. + let + sk = f.harness.sk + window = f.harness.window + baseline = f.frameState.scrollPos + state = f.state + f.harness.beginFrame() + ui: + frame f.frameId: + box Viewport + patch "" + layout f.direction + horizontalPadding 0 + verticalPadding 0 + itemSpacing Spacing + group "leading": + size TextWidth, LeadingHeight + group "reply": + size TextWidth, f.height + layout TopToBottom + horizontalPadding 0 + verticalPadding 0 + itemSpacing 0 + sk.startCurrentChildren() + f.origin = sk.at + sk.richTextBox( + window, f.replyId, f.text, TextWidth, f.height, + blocks = state.blocks + ) + f.navigated = state.cursorNavigated + let caret = state.editor.locationRect(state.editor.cursor) + f.caret = rect( + f.origin + caret.xy - state.editor.scrollPos, caret.wh + ) + group "trailing": + size TextWidth, TrailingHeight + f.harness.endFrame() + if f.navigated: + f.frameState.scrollPos = revealScroll( + baseline, f.content, Viewport, f.caret, f.direction + ) + window.resetInputState() + +proc settle(f: var Fixture) = + ## Checks the next idle frame preserves scrolling and shows the whole caret. + let scroll = f.frameState.scrollPos + f.frame() + doAssert not f.navigated + checkVec(f.frameState.scrollPos, scroll) + doAssert f.caret.y >= Viewport.y - 0.01 + doAssert f.caret.y + f.caret.h <= Viewport.y + Viewport.h + 0.01 + doAssert f.state.editor.scrollPos.y == 0 + +proc focus(f: var Fixture) = + ## Clicks the first glyph through the window's normal input callbacks. + f.frame() + let + window = f.harness.window + point = ( + f.origin + f.state.editor.layout[0].xy + vec2(2, 4) + ) * f.harness.sk.uiScale + window.moveMouse(point.x.int, point.y.int) + window.pressButton(MouseLeft) + window.releaseButton(MouseLeft) + f.frame() + doAssert f.state.editor.focused + doAssert not f.navigated + f.state.editor.cursor = 0 + f.state.editor.selector = 0 + f.state.editor.savedX = 0 + +proc tap(window: Window, key: Button) = + ## Delivers a complete key event through Silky's installed callbacks. + window.pressButton(key) + window.releaseButton(key) + +proc shortcut(window: Window, key: Button) = + ## Delivers an application shortcut using the platform's usual modifier. + let modifier = + when defined(macosx): + KeyLeftSuper + else: + KeyLeftControl + window.pressButton(modifier) + window.tap(key) + window.releaseButton(modifier) + +proc testDocument(direction: StackDirection, scale: float32) = + ## Exercises real keyboard, selection, scrolling, and idle widget frames. + echo "Testing rich cursor following in ", direction, " at scale ", scale + var f = fixture(direction, scale) + defer: + frameStates.del(f.frameId) + richTextBoxStates.del(f.replyId) + let + window = f.harness.window + editor = f.state.editor + f.focus() + let initial = f.frameState.scrollPos.y + for i in 0 ..< 18: + window.pressButton(KeyDown) + f.frame() + doAssert f.navigated + f.settle() + window.releaseButton(KeyDown) + doAssert (f.frameState.scrollPos.y - initial) * direction.dirSigns.y > 0 + + let anchor = editor.cursor + window.pressButton(KeyLeftShift) + for i in 0 ..< 8: + window.pressButton(KeyDown) + f.frame() + doAssert f.navigated + doAssert editor.selector == anchor + f.settle() + doAssert editor.copyText().len > 0 + window.releaseButton(KeyDown) + window.releaseButton(KeyLeftShift) + let lower = f.frameState.scrollPos.y + for i in 0 ..< 24: + window.pressButton(KeyUp) + f.frame() + doAssert f.navigated + f.settle() + window.releaseButton(KeyUp) + doAssert (f.frameState.scrollPos.y - lower) * direction.dirSigns.y < 0 + + echo "Testing wheel, copy, and Select All do not reveal the cursor" + let + beforeWheel = f.frameState.scrollPos + pointer = vec2(Viewport.x + 30, Viewport.y + 60) * scale + window.moveMouse(pointer.x.int, pointer.y.int) + window.scrollDelta = vec2(0, 3) + f.frame() + doAssert not f.navigated + let expected = vec2( + beforeWheel.x, + clamp( + beforeWheel.y + direction.dirSigns.y * 3 * ScrollSpeed, + 0.0'f, + f.content.y - Viewport.h + ) + ) + checkVec(f.frameState.scrollPos, expected) + f.frame() + checkVec(f.frameState.scrollPos, expected) + for key in [KeyA, KeyC]: + window.shortcut(key) + f.frame() + doAssert not f.navigated + checkVec(f.frameState.scrollPos, expected) + doAssert getClipboardString() == f.text + + echo "Testing navigation reveals an offscreen caret even at the text boundary" + editor.cursor = 0 + editor.selector = 0 + f.frameState.scrollPos.y = + if direction == BottomToTop: + 0.0'f + else: + f.content.y - Viewport.h + f.frame() + doAssert editor.focused + doAssert not f.navigated + doAssert f.caret.y + f.caret.h < Viewport.y + window.tap(KeyUp) + f.frame() + doAssert f.navigated and editor.cursor == 0 + f.settle() + + for key in [KeyRight, KeyLeft, KeyEnd, KeyHome, KeyPageDown, KeyPageUp]: + window.tap(key) + f.frame() + doAssert f.navigated + f.settle() + +for direction in [TopToBottom, BottomToTop]: + for scale in [1.0'f, 1.5'f, 2.0'f]: + testDocument(direction, scale) + +echo "All cursor scrolling tests passed." diff --git a/tests/test_decorations.nim b/tests/test_decorations.nim index b287c8fa..be1b7acf 100644 --- a/tests/test_decorations.nim +++ b/tests/test_decorations.nim @@ -3,6 +3,8 @@ import bumpy, pixie, vmath, windy, silky, silky/internal/inputs +privateAccess(Silky) + const FontPath = "tests/data/IBMPlexSans-Regular.ttf" TextColor = rgbx(90, 150, 220, 255) @@ -13,13 +15,13 @@ proc close(a, b: float32): bool = proc fixture(builder: AtlasBuilder, density: float32): Silky = ## Queues native widget vertices without a platform window or GPU. - privateAccess(Silky) result = Silky( atlas: builder.atlas, image: builder.atlasImage, uiScale: density, inFrame: true, - inputs: TextInputs() + inputs: TextInputs(), + window: Window() ) new(result.drawer) result.theme.padding = 0 @@ -63,14 +65,13 @@ proc transition( sk.drawer.layers[NormalLayer].setLen(0) sk.at = vec2(10.17'f, 20.29'f) sk.richTextBox( - Window(), "transitions", text, 180, 160, + sk.window, "transitions", text, 180, 160, wrapWords = true, blocks = blocks ) result = richTextBoxStates["transitions"] block: echo "Testing native strikethrough wrapping, hover, and pixel alignment" - let window = Window() for density in [1.0'f, 1.25'f, 1.5'f, 2.0'f]: let builder = newAtlasBuilder(256, 2) @@ -85,6 +86,7 @@ block: doAssert builder.addImage("textbox.disabled.9patch", newImage(16, 16)) let sk = fixture(builder, density) + window = sk.window text = "WW WW WW" var spans = @[ TextSpan( diff --git a/tests/test_first_touch.nim b/tests/test_first_touch.nim new file mode 100644 index 00000000..4106d6fe --- /dev/null +++ b/tests/test_first_touch.nim @@ -0,0 +1,183 @@ +import + std/[os, options], + bumpy, pixie, vmath, + silky + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +const DataDirectory = currentSourcePath().parentDir / "data" + +type Control = object + bounds, clip: Rect + layer: int + enabled: bool = true + +var + atlas: SilkyAtlas + counts: array[4, int] + controls: seq[Control] + origin: Vec2 + invalidateOnPress: bool + selected: int + showWindow = true + +block: + let builder = newAtlasBuilder(1024, 4) + builder.addDir(DataDirectory, DataDirectory & DirSep) + builder.addFont(DataDirectory / "IBMPlexSans-Regular.ttf", "Default", 18) + doAssert builder.addImage("tap", newImage(24, 24)) + doAssert builder.addImage("droparrow", newImage(8, 8)) + atlas = builder.atlas + +proc drawIcons(sk: Silky, window: Window) = + ## Draws actual press-triggered icons in a viewport adjusted for safe areas. + sk.mousePos -= origin + for i in 0 ..< 2: + sk.at = vec2((40 + i * 80).float32, 40) + clickableIcon("tap", false): + inc counts[i] + +proc drawControls(sk: Silky, window: Window) = + ## Registers overlapping candidates in explicit draw order and layers. + for i, control in controls: + sk.pushLayer(control.layer) + sk.pushRawClipRect(control.clip) + if sk.interact(control.bounds, control.enabled) == Pressed: + inc counts[i] + if invalidateOnPress: + sk.resetInteractions() + sk.popClipRect() + sk.popLayer() + +proc drawDropdown(sk: Silky, window: Window) = + ## Exercises a press-owned control and a release-triggered button. + sk.pushLayout(vec2(40, 40), vec2(240, 200)) + dropDown selected, [0, 1, 2] + sk.at = vec2(40, 250) + button("Button"): + inc counts[0] + sk.popLayout() + +proc drawSubwindow(sk: Silky, window: Window) = + ## Exercises a title-bar press that is released before the frame starts. + let state = sk.subWindowStart( + window, "First touch", showWindow, + some(vec2(100, 100)), some(vec2(300, 200)) + ) + sk.subWindowEnd(window, state) + +proc tap( + harness: var TestHarness, + draw: proc(sk: Silky, window: Window), + position: Vec2, + coalesced = false +) = + ## Sends pointer movement with the press, without a hover-only frame. + let pixels = ((position + origin) * harness.sk.uiScale).ivec2 + harness.window.moveMouse(pixels.x, pixels.y) + harness.window.pressButton(MouseLeft) + if coalesced: + harness.window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + if not coalesced: + harness.window.releaseButton(MouseLeft) + discard harness.pumpFrame(draw) + +block: + echo "Testing first-touch icons without hover frames at Retina scales" + for scale in [1.0'f, 1.5'f, 3.0'f]: + for safeOrigin in [vec2(0), vec2(0, 62)]: + counts = default(typeof(counts)) + origin = safeOrigin + var harness = newTestHarness(atlas) + harness.sk.uiScale = scale + discard harness.pumpFrame(drawIcons) + harness.tap(drawIcons, vec2(132, 52)) + doAssert counts[1] == 1 and counts[0] == 0 + harness.tap(drawIcons, vec2(52, 52), coalesced = true) + doAssert counts[0] == 1 and counts[1] == 1 + discard harness.pumpFrame(drawIcons) + doAssert counts[0] == 1 and counts[1] == 1 + origin = vec2(0) + +block: + echo "Testing popup layers, draw order, disabled blockers and clipping" + let + bounds = rect(40, 40, 80, 80) + fullClip = rect(0, 0, 400, 400) + for mode in 0 ..< 4: + counts = default(typeof(counts)) + controls = @[ + Control(bounds: bounds, clip: fullClip), + Control(bounds: bounds, clip: fullClip) + ] + case mode + of 0: + discard # Later controls win within the same layer. + of 1: + controls[0].layer = PopupsLayer + of 2: + controls[1].enabled = false + else: + controls[1].clip = rect(90, 90, 20, 20) + var harness = newTestHarness(atlas) + discard harness.pumpFrame(drawControls) + harness.tap(drawControls, vec2(52, 52)) + case mode + of 0: doAssert counts[0] == 0 and counts[1] == 1 + of 1, 3: doAssert counts[0] == 1 and counts[1] == 0 + else: doAssert counts[0] == 0 and counts[1] == 0 + +block: + echo "Testing moved geometry and explicit invalidation reject stale hits" + counts = default(typeof(counts)) + controls = @[Control(bounds: rect(40, 40, 80, 80), + clip: rect(0, 0, 400, 400))] + var harness = newTestHarness(atlas) + discard harness.pumpFrame(drawControls) + controls[0].bounds.x += 1 + harness.tap(drawControls, vec2(52, 52)) + doAssert counts[0] == 0 + harness.tap(drawControls, vec2(52, 52)) + doAssert counts[0] == 1 + harness.sk.resetInteractions() + harness.tap(drawControls, vec2(52, 52)) + doAssert counts[0] == 1 + controls.add(controls[0]) + invalidateOnPress = true + harness.tap(drawControls, vec2(52, 52)) + doAssert counts[0] == 2 and counts[1] == 0 + invalidateOnPress = false + +block: + echo "Testing first-tap dropdowns and complete taps in one frame" + for coalesced in [false, true]: + counts = default(typeof(counts)) + selected = 0 + dropDownStates.clear() + var harness = newTestHarness(atlas) + discard harness.pumpFrame(drawDropdown) + let bounds = harness.findByText("0", "DropDown").rect + harness.tap(drawDropdown, bounds.xy + vec2(20, bounds.h / 2), coalesced) + doAssert dropDownStates[cast[uint](addr selected)].open + harness.tap(drawDropdown, bounds.xy + vec2(20, bounds.h * 2.5), coalesced) + doAssert selected == 1 + doAssert not dropDownStates[cast[uint](addr selected)].open + discard harness.pumpFrame(drawDropdown) + harness.tap(drawDropdown, vec2(60, 265), coalesced) + doAssert counts[0] == 1 + +block: + echo "Testing a coalesced title-bar tap cannot latch dragging" + subWindowStates.clear() + var harness = newTestHarness(atlas) + discard harness.pumpFrame(drawSubwindow) + harness.tap(drawSubwindow, vec2(150, 115), coalesced = true) + let state = subWindowStates["First touch"] + doAssert not state.dragging and not state.resizing + harness.window.moveMouse(500, 400) + discard harness.pumpFrame(drawSubwindow) + doAssert state.pos == vec2(100, 100) + +echo "First-touch hit resolution tests passed." diff --git a/tests/test_input_hooks.nim b/tests/test_input_hooks.nim new file mode 100644 index 00000000..96fdd17e --- /dev/null +++ b/tests/test_input_hooks.nim @@ -0,0 +1,177 @@ +import + std/unicode, + silky, silky/semantics, silky/internal/inputs + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +type Fixture = object + harness: TestHarness + id: string + text: string + enabled: bool + +var + atlas: SilkyAtlas + nextId: int + +block: + let builder = newAtlasBuilder(1024, 4) + builder.addDir("tests/data/", "tests/data/") + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + atlas = builder.atlas + +proc frame(fixture: var Fixture) = + ## Draws one real textbox through the normal ordered input pipeline. + fixture.harness.beginFrame() + fixture.harness.sk.textBox( + fixture.harness.window, + fixture.id, + fixture.text, + 240, + 120, + wrapWords = true, + enabled = fixture.enabled + ) + fixture.harness.endFrame() + fixture.harness.window.resetInputState() + +proc state(fixture: Fixture): TextBoxState = + ## Looks up the editor owned by the fixture's textbox. + textBoxStates[fixture.id] + +proc newFixture(text: string, enabled = true): Fixture = + ## Creates and focuses one textbox with a distinct identity. + inc nextId + result.id = "input-hook-" & $nextId + result.text = text + result.enabled = enabled + result.harness.window = newWindow() + result.harness.sk = newSilky(result.harness.window, atlas) + result.frame() + let state = result.state() + state.focus(result.harness.sk, result.harness.window, result.id) + state.cursor = state.runes.len + state.selector = state.cursor + +proc tap(window: Window, button: Button) = + ## Delivers a complete keyboard event pair between UI frames. + window.pressButton(button) + window.releaseButton(button) + +block: + echo "Testing hooks observe edits and consume arrows in event order" + var + fixture = newFixture("draft") + kinds: seq[InputKind] + contents: seq[string] + cursors: seq[int] + let + state = fixture.state() + window = fixture.harness.window + state.onInput = proc(editor: TextBoxState, event: InputEvent): bool = + ## Observes prior edits before replacing a consumed history arrow. + kinds.add(event.kind) + contents.add(editor.getText()) + cursors.add(editor.cursor) + if event.kind == InputKind.KeyDown and event.button == KeyUp: + editor.setText("old\nhistory") + editor.cursor = editor.runes.len + editor.selector = editor.cursor + return true + window.onTextInput("!") + window.tap(KeyUp) + window.onTextEdit(TextInputEdit( + kind: ReplaceText, start: 0, length: 3, text: "NEW" + )) + window.onRune(Rune('?')) + fixture.frame() + doAssert kinds == @[ + TextCommit, InputKind.KeyDown, InputKind.KeyUp, NativeEdit, TextInput + ] + doAssert contents == @[ + "draft", "draft!", "old\nhistory", "old\nhistory", "NEW\nhistory" + ] + doAssert cursors[2] == "old\nhistory".len + doAssert cursors[3] == "old\nhistory".len + doAssert fixture.text == "NEW?\nhistory" + doAssert state.cursor == 4 and state.selector == 4 + doAssert not state.dirty + doAssert state.layout.len == fixture.text.runeLen + state.onInput = nil + +block: + echo "Testing declined events preserve navigation and ordinary editing" + var + observed = newFixture("abc") + plain = newFixture("abc") + calls = 0 + observed.state().onInput = proc( + editor: TextBoxState, event: InputEvent + ): bool = + ## Counts events without replacing normal textbox behavior. + inc calls + false + for fixture in [addr observed, addr plain]: + let window = fixture[].harness.window + window.tap(KeyLeft) + window.onTextInput("x") + fixture[].frame() + doAssert calls == 3 + doAssert observed.text == "abxc" + doAssert observed.text == plain.text + doAssert observed.state().cursor == plain.state().cursor + doAssert observed.state().selector == plain.state().selector + doAssert observed.state().layout == plain.state().layout + observed.state().onInput = nil + +block: + echo "Testing readonly input never invokes the editable hook" + var + fixture = newFixture("Read only", enabled = false) + calls = 0 + let window = fixture.harness.window + fixture.state().onInput = proc( + editor: TextBoxState, event: InputEvent + ): bool = + ## Counts unexpected callbacks from read-only selection handling. + inc calls + true + window.tap(KeyLeft) + window.onTextInput("ignored") + window.onTextEdit(TextInputEdit( + kind: ReplaceText, start: 0, length: 4, text: "ignored" + )) + fixture.frame() + doAssert calls == 0 + doAssert fixture.text == "Read only" + doAssert fixture.state().cursor == "Read only".len - 1 + fixture.state().onInput = nil + +block: + echo "Testing callback focus changes discard the entire stale remainder" + for handled in [false, true]: + var + fixture = newFixture("original") + calls = 0 + let + state = fixture.state() + window = fixture.harness.window + inputs = fixture.harness.sk.textInputs + state.onInput = proc(editor: TextBoxState, event: InputEvent): bool = + ## Changes focus before the original event can modify this editor. + inc calls + inputs.submitInput(window, "another editor", true, true) + handled + window.onTextInput("stale") + window.tap(KeyBackspace) + window.onTextEdit(TextInputEdit( + kind: ReplaceText, start: 0, length: 8, text: "stale native edit" + )) + fixture.frame() + doAssert calls == 1 + doAssert fixture.text == "original" + doAssert state.getText() == "original" + state.onInput = nil + +echo "All ordered input hook tests passed." diff --git a/tests/test_metal_shader_pixels.nim b/tests/test_metal_shader_pixels.nim new file mode 100644 index 00000000..eb3ae90d --- /dev/null +++ b/tests/test_metal_shader_pixels.nim @@ -0,0 +1,34 @@ +## Runs an offscreen Metal regression with Silky's Shady-generated shaders. +## Run on a Mac with Xcode and a Metal device: +## nim r tests/test_metal_shader_pixels.nim + +when defined(macosx) and not defined(ios): + import std/[os, osproc, tempfiles] + import shady, silky/drawers/shader + + const + VertexSource = toMSL(silkyVert, shaderVertex) + FragmentSource = toMSL(silkyFrag, shaderFragment) + HelperSource = currentSourcePath().parentDir / "metal_shader_pixels.m" + + let directory = createTempDir("silky-metal-pixels-", "") + try: + writeFile(directory / "vertex.metal", VertexSource) + writeFile(directory / "fragment.metal", FragmentSource) + let + executable = directory / "metal_shader_pixels" + compilation = execCmdEx( + "xcrun --sdk macosx clang -fobjc-arc -framework Foundation " & + "-framework Metal " & quoteShell(HelperSource) & + " -o " & quoteShell(executable) + ) + doAssert compilation.exitCode == 0, compilation.output + let rendering = execCmdEx( + quoteShell(executable) & " " & quoteShell(directory) + ) + doAssert rendering.exitCode == 0, rendering.output + stdout.write(rendering.output) + finally: + removeDir(directory) +else: + echo "Skipped offscreen Metal pixels: requires macOS with a Metal device." diff --git a/tests/test_metal_texture_pixels.nim b/tests/test_metal_texture_pixels.nim new file mode 100644 index 00000000..864af280 --- /dev/null +++ b/tests/test_metal_texture_pixels.nim @@ -0,0 +1,246 @@ +## Exercises the production Metal drawer with an offscreen render target. +## Run on macOS with nim r -d:silkyMetalTesting tests/test_metal_texture_pixels.nim. +## iOS Simulator builds use --noMain so Windy's native entry initializes Nim. + +when defined(macosx) or defined(ios): + when not defined(silkyMetalTesting): + {.error: "Build this test with -d:silkyMetalTesting.".} + + import + pixie, vmath, + silky/common, silky/drawers/metal4 + + const + White = ColorRGBX(r: 255, g: 255, b: 255, a: 255) + Red = ColorRGBX(r: 255, g: 0, b: 0, a: 255) + Green = ColorRGBX(r: 0, g: 255, b: 0, a: 255) + Blue = ColorRGBX(r: 0, g: 0, b: 255, a: 255) + Yellow = ColorRGBX(r: 255, g: 255, b: 0, a: 255) + Viewport = ivec2(32, 24) + + proc solidImage(width, height: int, color: ColorRGBX): Image = + ## Creates a premultiplied solid image for a texture upload. + result = newImage(width, height) + result.fill(color) + + proc addQuad( + vertices: var seq[DrawerVertex], + texture: uint32, + pos, size, uv: Vec2, + color = White, + clipPos = vec2(0, 0), + clipSize = Viewport.vec2, + maskUv = vec2(-1, -1) + ) = + ## Adds a quad sampling one texel center, avoiding filtered boundaries. + const Corners = [ + vec2(0, 0), vec2(1, 0), vec2(1, 1), + vec2(0, 0), vec2(1, 1), vec2(0, 1) + ] + for corner in Corners: + vertices.add(DrawerVertex( + pos: pos + corner * size, + uv: uv, + color: color, + clipPos: clipPos, + clipSize: clipSize, + maskUv: maskUv, + texture: texture + )) + + proc checkPixel( + image: Image, + x, y: int, + expected: ColorRGBX, + message: string + ) = + ## Checks GPU output with one byte of permitted rounding per channel. + let actual = image[x, y] + doAssert abs(actual.r.int - expected.r.int) <= 1 and + abs(actual.g.int - expected.g.int) <= 1 and + abs(actual.b.int - expected.b.int) <= 1 and + abs(actual.a.int - expected.a.int) <= 1, + message & ": got " & $actual & ", expected " & $expected + + template expectSilkyError(body: untyped) = + ## Checks that invalid input fails before issuing native Metal operations. + block: + var raised = false + try: + body + except SilkyError: + raised = true + doAssert raised, "Expected SilkyError for invalid texture input." + + proc checkBatchOrder() = + ## Verifies alternating texture batches, dimensions, and painter's order. + let + atlas = solidImage(8, 8, White) + drawer = newOffscreenDrawerForTesting(atlas, Viewport) + horizontal = solidImage(4, 2, Red) + vertical = solidImage(2, 4, Blue) + first = drawer.allocateTexture(4, 2) + second = drawer.allocateTexture(2, 4) + defer: drawer.close() + doAssert first != 0 and second != 0 and first != second + for y in 0 ..< horizontal.height: + for x in 2 ..< horizontal.width: + horizontal[x, y] = Green + for y in 2 ..< vertical.height: + for x in 0 ..< vertical.width: + vertical[x, y] = Yellow + drawer.uploadTextureRows(first, horizontal, 0, horizontal.height) + drawer.uploadTextureRows(second, vertical, 0, vertical.height) + + var vertices: seq[DrawerVertex] + vertices.addQuad(0, vec2(0, 0), Viewport.vec2, vec2(0.5, 0.5)) + vertices.addQuad(first, vec2(0, 0), vec2(24, 24), vec2(3.5, 0.5)) + vertices.addQuad(0, vec2(4, 4), vec2(16, 16), vec2(0.5, 0.5), Red) + vertices.addQuad(second, vec2(8, 8), vec2(12, 12), vec2(0.5, 3.5)) + vertices.addQuad(0, vec2(12, 12), vec2(4, 4), vec2(0.5, 0.5), Blue) + let pixels = drawer.renderPixelsForTesting(atlas, vertices) + pixels.checkPixel(1, 1, Green, "First dynamic texture dimensions") + pixels.checkPixel(5, 5, Red, "Atlas batch over first dynamic texture") + pixels.checkPixel(9, 9, Yellow, "Second dynamic texture dimensions") + pixels.checkPixel(13, 13, Blue, "Final atlas batch remains on top") + pixels.checkPixel(30, 20, White, "Untouched atlas background") + + drawer.deleteTexture(first) + drawer.deleteTexture(first) + drawer.deleteTexture(0) + let replacement = drawer.allocateTexture(4, 2) + doAssert replacement != first, "Deleted texture handles must stay stale." + drawer.uploadTextureRows(replacement, horizontal, 0, horizontal.height) + vertices.setLen(0) + vertices.addQuad(0, vec2(0, 0), Viewport.vec2, vec2(0.5, 0.5)) + vertices.addQuad(first, vec2(0, 0), Viewport.vec2, vec2(3.5, 0.5)) + let deletedPixels = drawer.renderPixelsForTesting(atlas, vertices) + deletedPixels.checkPixel(10, 10, White, "Deleted textures are skipped") + + proc checkRowUploads() = + ## Verifies partial texture uploads preserve rows outside the update. + let + atlas = solidImage(8, 8, White) + drawer = newOffscreenDrawerForTesting(atlas, Viewport) + image = solidImage(4, 4, Red) + texture = drawer.allocateTexture(4, 4) + defer: drawer.close() + drawer.uploadTextureRows(texture, image, 0, image.height) + image.fill(Green) + drawer.uploadTextureRows(texture, image, 1, 2) + drawer.uploadTextureRows(texture, image, image.height, 0) + var vertices: seq[DrawerVertex] + for row in 0 ..< image.height: + vertices.addQuad( + texture, + vec2(0, row.float32 * 6), + vec2(32, 6), + vec2(1.5, row.float32 + 0.5) + ) + let pixels = drawer.renderPixelsForTesting(atlas, vertices) + pixels.checkPixel(16, 3, Red, "First row remains unchanged") + pixels.checkPixel(16, 9, Green, "First uploaded row") + pixels.checkPixel(16, 15, Green, "Second uploaded row") + pixels.checkPixel(16, 21, Red, "Last row remains unchanged") + + expectSilkyError: + discard drawer.allocateTexture(0, 1) + expectSilkyError: + discard drawer.allocateTexture(1, -1) + doAssert drawer.maxTextureSize in [8192, 16384, 32768] + when defined(iosSimulator): + doAssert drawer.maxTextureSize == 8192 + expectSilkyError: + discard drawer.allocateTexture(drawer.maxTextureSize + 1, 1) + expectSilkyError: + discard drawer.allocateTexture(1, drawer.maxTextureSize + 1) + expectSilkyError: + drawer.uploadAtlas(newImage(drawer.maxTextureSize + 1, 1)) + expectSilkyError: + drawer.uploadTextureRows(0, image, 0, 1) + expectSilkyError: + drawer.uploadTextureRows(texture, nil, 0, 1) + expectSilkyError: + drawer.uploadTextureRows(texture, newImage(2, 4), 0, 1) + expectSilkyError: + drawer.uploadTextureRows(texture, image, -1, 1) + expectSilkyError: + drawer.uploadTextureRows(texture, image, 0, -1) + expectSilkyError: + drawer.uploadTextureRows(texture, image, 5, 0) + expectSilkyError: + drawer.uploadTextureRows(texture, image, 3, 2) + + proc checkAtlasUpdates() = + ## Verifies clipped atlas regions, unchanged texels, and atlas resizing. + let + atlas = solidImage(8, 8, White) + drawer = newOffscreenDrawerForTesting(atlas, Viewport) + defer: drawer.close() + atlas.fill(Red) + drawer.uploadAtlasRegion(atlas, 2, 2, 2, 2) + var vertices: seq[DrawerVertex] + vertices.addQuad(0, vec2(0, 0), vec2(16, 24), vec2(0.5, 0.5)) + vertices.addQuad(0, vec2(16, 0), vec2(16, 24), vec2(2.5, 2.5)) + let firstPixels = drawer.renderPixelsForTesting(atlas, vertices) + firstPixels.checkPixel(8, 12, White, "Atlas texels outside update") + firstPixels.checkPixel(24, 12, Red, "Atlas region upload") + + atlas.fill(Green) + drawer.uploadAtlasRegion(atlas, -2, -2, 4, 4) + drawer.uploadAtlasRegion(atlas, 40, 40, 2, 2) + drawer.uploadAtlasRegion(atlas, 2, 2, 0, 2) + let clippedPixels = drawer.renderPixelsForTesting(atlas, vertices) + clippedPixels.checkPixel(8, 12, Green, "Clipped atlas update") + clippedPixels.checkPixel(24, 12, Red, "Clipped update preserves neighbors") + + let resized = solidImage(4, 4, Blue) + drawer.uploadAtlasRegion(resized, 0, 0, 1, 1) + let resizedPixels = drawer.renderPixelsForTesting(resized, vertices) + resizedPixels.checkPixel(8, 12, Blue, "Resized atlas uploads completely") + resizedPixels.checkPixel(24, 12, Blue, "Resized atlas far texels") + resized.fill(Yellow) + drawer.uploadAtlas(resized) + let replacedPixels = drawer.renderPixelsForTesting(resized, vertices) + replacedPixels.checkPixel(8, 12, Yellow, "Full atlas replacement") + + proc checkMasksAndClipping() = + ## Verifies atlas mask and clip state after switching from an image batch. + let + atlas = solidImage(8, 8, White) + drawer = newOffscreenDrawerForTesting(atlas, Viewport) + image = solidImage(2, 2, Green) + texture = drawer.allocateTexture(2, 2) + defer: drawer.close() + atlas[6, 6] = rgbx(128, 128, 128, 255) + drawer.uploadAtlasRegion(atlas, 6, 6, 1, 1) + drawer.uploadTextureRows(texture, image, 0, image.height) + var vertices: seq[DrawerVertex] + vertices.addQuad(texture, vec2(0, 0), Viewport.vec2, vec2(0.5, 0.5)) + vertices.addQuad( + 0, + vec2(0, 0), + Viewport.vec2, + vec2(0.5, 0.5), + Red, + clipPos = vec2(8, 4), + clipSize = vec2(16, 16), + maskUv = vec2(6.5, 6.5) + ) + let pixels = drawer.renderPixelsForTesting(atlas, vertices) + pixels.checkPixel(16, 12, rgbx(255, 127, 127, 255), "Atlas tint mask") + pixels.checkPixel(4, 12, Green, "Left clipping edge") + pixels.checkPixel(28, 12, Green, "Right clipping edge") + pixels.checkPixel(16, 2, Green, "Top clipping edge") + pixels.checkPixel(16, 22, Green, "Bottom clipping edge") + + checkBatchOrder() + checkRowUploads() + checkAtlasUpdates() + checkMasksAndClipping() + echo "Metal texture pixels passed: batches, uploads, atlas, masks, clipping." + when defined(ios): + # Complete the headless test before Windy's entry starts UIKit. + quit(0) +else: + echo "Skipped Metal texture pixels: requires a macOS or iOS Metal device." diff --git a/tests/test_quotes.nim b/tests/test_quotes.nim index 1409f5e9..95862a1e 100644 --- a/tests/test_quotes.nim +++ b/tests/test_quotes.nim @@ -3,6 +3,8 @@ import bumpy, pixie, vmath, windy, silky, silky/internal/inputs +privateAccess(Silky) + const FontPath = "tests/data/IBMPlexSans-Regular.ttf" QuoteColor = rgbx(90, 150, 220, 255) @@ -15,13 +17,13 @@ proc close(a, b: float32): bool = proc fixture(builder: AtlasBuilder, density: float32): Silky = ## Queues native widget vertices without a platform window or GPU. - privateAccess(Silky) result = Silky( atlas: builder.atlas, image: builder.atlasImage, uiScale: density, inFrame: true, - inputs: TextInputs() + inputs: TextInputs(), + window: Window() ) new(result.drawer) result.theme.padding = 0 @@ -39,7 +41,7 @@ proc render( richTextBoxStates.del("quotes") sk.at = vec2(10.17'f, 20.29'f) sk.richTextBox( - Window(), "quotes", source, width, 220, + sk.window, "quotes", source, width, 220, wrapWords = true, blocks = blocks ) result = richTextBoxStates["quotes"] diff --git a/tests/test_retina_atlas.nim b/tests/test_retina_atlas.nim new file mode 100644 index 00000000..c8d6db41 --- /dev/null +++ b/tests/test_retina_atlas.nim @@ -0,0 +1,114 @@ +import + std/[json, math, os, tables, tempfiles, unicode], + pixie, jsony, + silky/atlas + +const + FontPath = "tests/data/IBMPlexSans-Regular.ttf" + Glyphs = @["A", "V", "g", " "] + +proc overlaps(a, b: Entry): bool = + ## Returns whether two atlas rectangles share pixels. + a.x < b.x + b.width and b.x < a.x + a.width and + a.y < b.y + b.height and b.y < a.y + a.height + +proc checkRetinaAtlas() = + ## Checks physical raster density without changing logical font layout. + let builder = newAtlasBuilder(512, 2) + builder.addFont(FontPath, "1x", 18, Glyphs) + builder.addFont(FontPath, "2x", 18, Glyphs, pixelScale = 2) + builder.addFont(FontPath, "3x", 18, Glyphs, pixelScale = 3) + builder.addFont(FontPath, "54px", 54, Glyphs) + let + base = builder.atlas.fonts["1x"] + retina = builder.atlas.fonts["3x"] + large = builder.atlas.fonts["54px"] + for name in ["2x", "3x"]: + let font = builder.atlas.fonts[name] + doAssert font.size == base.size + doAssert font.ascent == base.ascent + doAssert font.descent == base.descent + doAssert font.lineHeight == base.lineHeight + doAssert font.lineGap == base.lineGap + for glyph in Glyphs: + let + normal = base.entries[glyph][0] + dense = font.entries[glyph][0] + doAssert dense.advance == normal.advance + doAssert dense.kerning == normal.kerning + doAssert abs(dense.boundsWidth - normal.boundsWidth) <= 1 + doAssert abs(dense.boundsHeight - normal.boundsHeight) <= 1 + + doAssert retina.lookupKerning(Rune('A'), Rune('V')) == + base.lookupKerning(Rune('A'), Rune('V')) + for glyph in Glyphs: + let + dense = retina.entries[glyph][0] + physical = large.entries[glyph][0] + width = round(dense.boundsWidth * retina.rasterScale).int + height = round(dense.boundsHeight * retina.rasterScale).int + doAssert width == physical.boundsWidth.int + doAssert height == physical.boundsHeight.int + doAssert abs(dense.boundsX * 3 - physical.boundsX) < 0.0001 + doAssert abs(dense.boundsY * 3 - physical.boundsY) < 0.0001 + for y in 0 ..< height: + for x in 0 ..< width: + doAssert builder.atlasImage[dense.x + x, dense.y + y] == + builder.atlasImage[physical.x + x, physical.y + y] + + let directory = createTempDir("silky-retina-", "") + defer: removeDir(directory) + let path = directory / "atlas.png" + builder.write(path) + let loaded = readAtlas(path) + doAssert loaded.atlas.fonts["3x"].rasterScale == 3 + doAssert loaded.atlas.fonts["3x"].size == 18 + doAssert loaded.atlas.fonts["3x"].lookupKerning(Rune('A'), Rune('V')) == + retina.lookupKerning(Rune('A'), Rune('V')) + + let live = newAtlasBuilderFromAtlas(loaded.atlas, loaded.image, 2) + for i in 0 ..< 12: + let name = "new" & $i + doAssert live.addImage(name, newImage(28, 16)) + let added = live.atlas.entries[name] + for font in live.atlas.fonts.values: + for variants in font.entries.values: + for glyph in variants: + let occupied = Entry( + x: glyph.x, + y: glyph.y, + width: round(glyph.boundsWidth * font.rasterScale).int, + height: round(glyph.boundsHeight * font.rasterScale).int + ) + if occupied.width > 0 and occupied.height > 0: + doAssert not overlaps(added, occupied) + + let + legacy = newAtlasBuilder(128, 2) + legacyPath = directory / "legacy.png" + legacy.addFont(FontPath, "Default", 18, Glyphs) + var metadata = parseJson(legacy.atlas.toJson()) + metadata["fonts"]["Default"].delete("pixelScale") + writePng(legacyPath, $metadata, legacy.atlasImage) + let oldFont = readAtlasFromPng(legacyPath).fonts["Default"] + doAssert oldFont.rasterScale == 1 + doAssert oldFont.entries["A"][0] == legacy.atlas.fonts["Default"].entries["A"][0] + doAssert FontAtlas().rasterScale == 1 + + let subpixel = newAtlasBuilder(512, 2) + subpixel.addFont(FontPath, "3x", 18, @["A"], 4, 3) + let variants = subpixel.atlas.fonts["3x"].entries["A"] + doAssert variants.len == 4 + doAssert abs(variants[1].boundsWidth - variants[0].boundsWidth - 1.0 / 3) < 0.0001 + doAssert variants[1].advance == variants[0].advance + + for invalid in [0.0'f, -1.0'f, Inf.float32, NaN.float32]: + var rejected = false + try: + builder.addFont(FontPath, "Invalid", 18, Glyphs, pixelScale = invalid) + except SilkyAtlasError: + rejected = true + doAssert rejected + +checkRetinaAtlas() +echo "Retina atlas metrics, pixels, roundtrip and packing tests passed." diff --git a/tests/test_richimages.nim b/tests/test_richimages.nim new file mode 100644 index 00000000..f3349409 --- /dev/null +++ b/tests/test_richimages.nim @@ -0,0 +1,76 @@ +import + std/[importutils, tables], + bumpy, pixie, vmath, windy, + silky, silky/internal/inputs + +privateAccess(Silky) + +proc fixture(builder: AtlasBuilder): Silky = + ## Queues native image and text vertices without opening a platform window. + result = Silky( + atlas: builder.atlas, + image: builder.atlasImage, + uiScale: 2, + inFrame: true, + inputs: TextInputs(), + window: Window() + ) + new(result.drawer) + result.theme.padding = 0 + result.mousePos = vec2(-1) + result.pushLayout(vec2(0), vec2(600)) + result.pushClipRect(rect(0, 0, 600, 600)) + +block: + echo "Testing native rich images preserve aspect, cropping and selection" + let builder = newAtlasBuilder(1024, 2) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + for name in [ + "textbox.disabled.9patch", "scrollbar.track.9patch", "scrollbar.9patch" + ]: + doAssert builder.addImage(name, newImage(16, 16)) + doAssert builder.addImage("picture", newImage(512, 512)) + let + sk = fixture(builder) + state = newRichTextBoxState("An image\n\nAfter the image.") + state.blocks = @[ + TextBlock( + first: 0, + last: 8, + image: "picture", + imageSize: vec2(320, 180), + imagePixels: vec2(320, 180), + padding: vec2(12, 6), + spacing: 8 + ), + TextBlock(first: 10, last: 26, padding: vec2(12, 6)) + ] + state.computeLayout(builder.atlas.fonts, "Default", 184) + let bounds = state.imageBounds(0) + doAssert bounds == rect(12, 6, 160, 90) + doAssert state.editor.layout[0].y == bounds.y + bounds.h + 8 + doAssert state.editor.layout[10].y > state.editor.layout[0].y + doAssert state.imageBounds(1).w == 0 + state.editor.selectAll() + doAssert state.editor.copyText() == "An image\n\nAfter the image." + richTextBoxStates["images"] = state + sk.richTextBox( + sk.window, "images", state.getText(), 184, state.innerHeight, + blocks = state.blocks + ) + let + sprite = sk.atlas.entries["picture"] + vertices = sk.drawer.layers[NormalLayer] + var found = false + for i in countup(0, vertices.high, 6): + if vertices[i].uv == vec2(sprite.x.float32, sprite.y.float32): + doAssert not found + found = true + doAssert vertices[i].pos == bounds.xy + doAssert vertices[i + 2].pos - vertices[i].pos == bounds.wh + doAssert vertices[i + 2].uv - vertices[i].uv == vec2(320, 180) + doAssert found + doAssert state.editor.scrollPos == vec2(0) + richTextBoxStates.del("images") + +echo "All native rich image tests passed." diff --git a/tests/test_richtextboxes.nim b/tests/test_richtextboxes.nim index 68260dfd..d344d34e 100644 --- a/tests/test_richtextboxes.nim +++ b/tests/test_richtextboxes.nim @@ -221,4 +221,35 @@ block: doAssert s.editor.cursor >= bodyStart and s.editor.cursor < codeStart doAssert s.editor.selector == codeStart +block: + echo "Testing preformatted rows stay intact beside wrapped prose" + const + Prose = "A paragraph that wraps over several narrow lines." + Row = "Name | Count | Description" + Sample = Prose & "\n" & Row & "\n" & Row + Start = Prose.len + 1 + let state = newState(Sample, 100) + state.blocks = @[ + TextBlock(first: 0, last: Prose.len, padding: vec2(6)), + TextBlock( + first: Start, + last: Sample.len, + noWrap: true, + padding: vec2(6) + ) + ] + state.computeLayout(silkyAtlas.fonts, "Default", 100) + doAssert state.editor.layout[Prose.high].y > state.editor.layout[0].y + let firstRow = state.editor.layout[Start ..< Start + Row.len] + for i, bounds in firstRow: + doAssert bounds.y == firstRow[0].y + doAssert bounds.x == state.editor.layout[Start + Row.len + 1 + i].x + doAssert state.editor.innerWidth > 100 + doAssert state.horizontalScrollbarHeight(100) == 10 + state.editor.selectAll() + doAssert state.editor.copyText() == Sample + state.computeLayout(silkyAtlas.fonts, "Default", 600) + doAssert state.horizontalScrollbarHeight(600) == 0 + doAssert state.editor.wordWrap + echo "All rich textbox layout tests passed." diff --git a/tests/test_rules.nim b/tests/test_rules.nim index bc7789eb..fdef3583 100644 --- a/tests/test_rules.nim +++ b/tests/test_rules.nim @@ -3,6 +3,8 @@ import bumpy, pixie, vmath, windy, silky, silky/internal/inputs +privateAccess(Silky) + const FontPath = "tests/data/IBMPlexSans-Regular.ttf" RuleColor = rgbx(90, 150, 220, 255) @@ -13,13 +15,13 @@ proc close(a, b: float32): bool = proc fixture(builder: AtlasBuilder, density: float32): Silky = ## Queues native widget vertices without a platform window or GPU. - privateAccess(Silky) result = Silky( atlas: builder.atlas, image: builder.atlasImage, uiScale: density, inFrame: true, - inputs: TextInputs() + inputs: TextInputs(), + window: Window() ) new(result.drawer) result.theme.padding = 0 @@ -48,14 +50,13 @@ proc rules(sk: Silky, clip: Rect): seq[Rect] = block: echo "Testing rule-only blocks have no text or implicit font line" privateAccess(RichTextBoxState) - let - builder = newAtlasBuilder(1024, 2) - window = Window() + let builder = newAtlasBuilder(1024, 2) builder.addFont(FontPath, "Default", 18) doAssert builder.addImage("textbox.disabled.9patch", newImage(16, 16)) for density in [1.0'f, 1.25'f, 1.5'f, 2.0'f]: let sk = fixture(builder, density) + window = sk.window origin = vec2(10.17'f, 20.29'f) rule = TextBlock( first: 0, diff --git a/tests/test_scroll_momentum.nim b/tests/test_scroll_momentum.nim new file mode 100644 index 00000000..bfe0c430 --- /dev/null +++ b/tests/test_scroll_momentum.nim @@ -0,0 +1,382 @@ +import + std/[math, os], + bumpy, pixie, vmath, + silky, silky/scrolls + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +const + NormalDeceleration = 0.998 + ReleaseTime = 100.0 + +type + Position = ref object + value: Vec2 + + Target = object + state: Position + bounds: Rect + maximum, signs: Vec2 + depth: int + + Scene = ref object + touchScroll: TouchScroll + touchOrigin, mousePos: Vec2 + clipRect: Rect + currentDrawLayer: int + time: float64 + targets: seq[Target] + +proc near(actual, expected: float64, tolerance = 0.02) = + ## Checks positions without hiding fractional drift across frame rates. + doAssert abs(actual - expected) < tolerance, + $actual & " != " & $expected + +proc expectedDistance(velocity, milliseconds: float64): float64 = + ## Uses Apple's published velocity projection with normal deceleration. + velocity / 1000 * NormalDeceleration / (1 - NormalDeceleration) * + (1 - pow(NormalDeceleration, milliseconds)) + +proc register(scene: Scene, target: Target) = + ## Publishes displayed geometry while retaining the owner's mutable position. + var tracks, thumbs: array[2, Rect] + let + state = target.state + bounds = target.bounds + if target.maximum.x > 0: + tracks[0] = rect(bounds.x, bounds.y + bounds.h - 8, bounds.w, 8) + let fraction = state.value.x / target.maximum.x + thumbs[0] = rect( + bounds.x + (bounds.w - 20) * fraction, + tracks[0].y, + 20, + 8 + ) + if target.maximum.y > 0: + tracks[1] = rect(bounds.x + bounds.w - 8, bounds.y, 8, bounds.h) + let fraction = state.value.y / target.maximum.y + thumbs[1] = rect( + tracks[1].x, + bounds.y + (bounds.h - 20) * fraction, + 8, + 20 + ) + scene.registerTouchScroll( + cast[pointer](state), + bounds, + state.value, + target.maximum, + target.signs, + tracks, + thumbs, + target.depth, + proc(position: Vec2) = + ## Applies input to the retained viewport position. + state.value = position + ) + +proc tick( + scene: Scene, + milliseconds: float64, + point = vec2(100, 100), + motion = vec2(0), + velocity = vec2(0), + pressed = false, + down = false, + released = false, + focused = true, + isTouch = true, + interrupted = false, + showTargets = true +) = + ## Advances one deterministic input frame and refreshes visible targets. + scene.mousePos = point + scene.time = milliseconds + scene.touchScroll.beginTouchFrame( + isTouch, + pressed, + down, + released, + focused, + point, + motion, + velocity, + milliseconds, + interrupted + ) + if showTargets: + for target in scene.targets: + scene.register(target) + scene.touchScroll.endTouchFrame() + +proc setup( + position = vec2(0, 1000), + maximum = vec2(0, 10000), + signs = vec2(1) +): Scene = + ## Starts with displayed scroll regions and no gesture in progress. + result = Scene( + clipRect: rect(0, 0, 800, 600), + targets: @[ + Target( + state: Position(value: position), + bounds: rect(0, 0, 300, 200), + maximum: maximum, + signs: signs + ) + ] + ) + result.tick(0) + +proc fling(scene: Scene, velocity = vec2(0, -1000)): Vec2 = + ## Delivers a complete finger gesture, including release, in one frame. + scene.tick( + ReleaseTime, + point = vec2(100, 100), + motion = vec2(0, -40), + velocity = velocity, + pressed = true, + released = true + ) + scene.targets[0].state.value + +proc advance(scene: Scene, until: float64, step = 10.0) = + ## Drives animation deadlines without sleeping or consulting a wall clock. + var time = scene.time + while time < until: + time = min(until, time + step) + scene.tick(time) + +block: + echo "Testing normal iOS deceleration against the published projection" + let scene = setup() + let released = scene.fling() + doAssert scene.touchScroll.momentumActive + scene.advance(ReleaseTime + 1000) + near(scene.targets[0].state.value.y.float64 - released.y.float64, + expectedDistance(1000, 1000)) + doAssert scene.touchScroll.momentumActive + scene.advance(ReleaseTime + 4000) + doAssert not scene.touchScroll.momentumActive + let stopped = scene.targets[0].state.value + scene.tick(ReleaseTime + 5000) + doAssert scene.targets[0].state.value == stopped + +block: + echo "Testing equal elapsed motion at 60 Hz, 120 Hz and uneven frame times" + var positions: seq[float64] + for rate in [60, 120]: + let scene = setup() + let released = scene.fling() + for frame in 1 .. rate: + scene.tick(ReleaseTime + frame.float64 * 1000 / rate.float64) + positions.add(scene.targets[0].state.value.y.float64 - released.y.float64) + let scene = setup() + let released = scene.fling() + var + time = ReleaseTime + frame = 0 + while time < ReleaseTime + 1000: + let delta = [5.0, 23.0, 11.0, 31.0, 9.0][frame mod 5] + time = min(ReleaseTime + 1000, time + delta) + scene.tick(time) + inc frame + positions.add(scene.targets[0].state.value.y.float64 - released.y.float64) + for position in positions: + near(position, expectedDistance(1000, 1000)) + near(position, positions[0]) + +block: + echo "Testing both scroll bounds stop momentum without overshoot" + for direction in [-1.0'f, 1.0'f]: + let scene = setup(position = vec2(0, 60), maximum = vec2(0, 120)) + discard scene.fling(velocity = vec2(0, direction * 1000)) + scene.advance(ReleaseTime + 1000) + near(scene.targets[0].state.value.y.float64, + if direction < 0: 120.0 else: 0.0) + doAssert not scene.touchScroll.momentumActive + +block: + echo "Testing a stopping touch is consumed, then the next tap works" + let scene = setup() + discard scene.fling() + scene.tick(ReleaseTime + 16) + let stopped = scene.targets[0].state.value + scene.tick(ReleaseTime + 24, pressed = true, down = true) + doAssert not scene.touchScroll.momentumActive + doAssert scene.touchScrolling + scene.tick(ReleaseTime + 40, released = true) + doAssert not scene.touchTap(rect(0, 0, 300, 200)) + doAssert scene.targets[0].state.value == stopped + scene.tick(ReleaseTime + 60, pressed = true, released = true) + doAssert scene.touchTap(rect(0, 0, 300, 200)) + let outside = setup() + discard outside.fling() + outside.tick(ReleaseTime + 24, point = vec2(400, 100), + pressed = true, released = true) + doAssert not outside.touchScroll.momentumActive + doAssert outside.touchTap(rect(350, 60, 100, 80)) + +block: + echo "Testing scrollbar thumb drags never start momentum" + let scene = setup(position = vec2(0, 1000), maximum = vec2(0, 2000)) + scene.tick( + ReleaseTime, + point = vec2(285, 145), + motion = vec2(0, 45), + velocity = vec2(0, 2000), + pressed = true, + released = true + ) + let released = scene.targets[0].state.value + doAssert released.y > 1000 + doAssert not scene.touchScroll.momentumActive + scene.advance(ReleaseTime + 300) + doAssert scene.targets[0].state.value == released + +block: + echo "Testing a stationary release and cancelled gestures do not fling" + for mode in 0 ..< 4: + let scene = setup() + scene.tick(10, point = vec2(100, 140), pressed = true, down = true) + scene.tick(30, point = vec2(100, 100), down = true) + let position = scene.targets[0].state.value + case mode + of 0: + scene.tick(ReleaseTime, velocity = vec2(0), released = true) + of 1: + scene.tick(ReleaseTime, point = vec2(-1), released = true, + velocity = vec2(0, -1000)) + of 2: + scene.tick(ReleaseTime, focused = false, released = true, + velocity = vec2(0, -1000)) + else: + scene.touchScroll.resetTouchScroll() + scene.tick(ReleaseTime, released = true, velocity = vec2(0, -1000)) + doAssert not scene.touchScroll.momentumActive + scene.tick(ReleaseTime + 100) + doAssert scene.targets[0].state.value == position + +block: + echo "Testing interruptions, focus loss and vanished targets stop coasting" + for mode in 0 ..< 7: + let scene = setup() + discard scene.fling() + scene.tick(ReleaseTime + 16) + case mode + of 0: + scene.tick(ReleaseTime + 24, interrupted = true) + of 1: + scene.tick(ReleaseTime + 24, focused = false) + of 2: + scene.tick(ReleaseTime + 24, isTouch = false) + of 3: + scene.touchScroll.resetTouchScroll() + scene.tick(ReleaseTime + 24) + of 4: + scene.tick(ReleaseTime + 24, showTargets = false) + scene.tick(ReleaseTime + 32, showTargets = false) + of 5: + scene.targets[0].state.value.y += 200 + for target in scene.targets: + scene.register(target) + scene.touchScroll.endTouchFrame() + scene.tick(ReleaseTime + 24) + else: + scene.tick(ReleaseTime + 1000) + doAssert not scene.touchScroll.momentumActive + let position = scene.targets[0].state.value + scene.tick(ReleaseTime + 100) + doAssert scene.targets[0].state.value == position + +block: + echo "Testing nested axes and bottom-origin momentum ownership" + for bottomOrigin in [false, true]: + let scene = setup(signs = vec2(1, if bottomOrigin: -1 else: 1)) + let child = Position(value: vec2(1000, 0)) + scene.targets.add(Target( + state: child, + bounds: rect(40, 20, 180, 170), + maximum: vec2(10000, 0), + signs: vec2(1), + depth: 1 + )) + scene.tick(1) + let released = scene.fling() + scene.advance(ReleaseTime + 100) + near(scene.targets[0].state.value.y.float64 - released.y.float64, + expectedDistance(if bottomOrigin: -1000.0 else: 1000.0, 100)) + near(child.value.x.float64, 1000) + let scene = setup() + let child = Position(value: vec2(1000, 0)) + scene.targets.add(Target( + state: child, + bounds: rect(40, 20, 180, 170), + maximum: vec2(10000, 0), + signs: vec2(1), + depth: 1 + )) + scene.tick(1) + scene.tick(ReleaseTime, point = vec2(100, 100), motion = vec2(-40, 0), + velocity = vec2(-1000, -800), pressed = true, released = true) + let released = child.value + scene.advance(ReleaseTime + 100) + near(child.value.x.float64 - released.x.float64, + expectedDistance(1000, 100)) + near(scene.targets[0].state.value.y.float64, 1000) + +var atlas: SilkyAtlas + +block: + let + data = currentSourcePath().parentDir / "data" + builder = newAtlasBuilder(1024, 4) + builder.addDir(data, data & DirSep) + builder.addFont(data / "IBMPlexSans-Regular.ttf", "Default", 18) + atlas = builder.atlas + +proc drawViewport(sk: Silky, window: Window) = + ## Exercises the normal frame pipeline with a scrollable rendered viewport. + ui: + frame "momentum viewport": + box 20, 30, 300, 200 + patch "" + horizontalPadding 0 + verticalPadding 0 + itemSpacing 0 + layout TopToBottom + group "document": + size 280, 10000 + +block: + echo "Testing native velocity conversion at 1x and 3x Retina scale" + var positions: seq[float64] + for scale in [1, 3]: + frameStates.clear() + var h = newTestHarness(atlas, 400 * scale, 400 * scale) + h.sk.uiScale = scale.float32 + h.sk.touchTimeMs = 0 + h.window.pointerSource = TouchPointer + discard h.pumpFrame(drawViewport) + frameStates["momentum viewport"].scrollPos.y = 1000 + discard h.pumpFrame(drawViewport) + h.window.moveMouse(100 * scale, 150 * scale) + h.window.pressButton(MouseLeft) + h.window.moveMouse(100 * scale, 110 * scale) + h.window.pointerVelocity = vec2(0, (-1000 * scale).float32) + h.window.releaseButton(MouseLeft) + h.sk.touchTimeMs = ReleaseTime + discard h.pumpFrame(drawViewport) + let released = frameStates["momentum viewport"].scrollPos.y + doAssert h.sk.touchScroll.momentumActive + for frame in 1 .. 50: + h.sk.touchTimeMs = ReleaseTime + frame.float64 * 10 + discard h.pumpFrame(drawViewport) + positions.add(frameStates["momentum viewport"].scrollPos.y.float64 - + released.float64) + for position in positions: + near(position, expectedDistance(1000, 500)) + near(position, positions[0]) + +echo "Scroll momentum tests passed." diff --git a/tests/test_secure_inputs.nim b/tests/test_secure_inputs.nim new file mode 100644 index 00000000..027fab7c --- /dev/null +++ b/tests/test_secure_inputs.nim @@ -0,0 +1,124 @@ +import + std/os, + silky, silky/semantics + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +const DataDirectory = currentSourcePath().parentDir / "data" + +type Fixture = object + harness: TestHarness + id: string + text: string + password: bool + +var + atlas: SilkyAtlas + nextId: int + +block: + let builder = newAtlasBuilder(1024, 4) + builder.addDir(DataDirectory, DataDirectory & DirSep) + builder.addFont(DataDirectory / "IBMPlexSans-Regular.ttf", "Default", 18) + atlas = builder.atlas + +proc frame(fixture: var Fixture) = + ## Draws and commits native state through the real ordered editor pipeline. + fixture.harness.beginFrame() + fixture.harness.sk.textBox( + fixture.harness.window, + fixture.id, + fixture.text, + 240, + 80, + wrapWords = false, + singleLine = true, + password = fixture.password + ) + fixture.harness.endFrame() + fixture.harness.window.resetInputState() + +proc state(fixture: Fixture): TextBoxState = + ## Returns the editor owned by this field. + textBoxStates[fixture.id] + +proc newFixture(text: string, password: bool): Fixture = + ## Creates and focuses one editable field without a native window. + inc nextId + result.id = "secure-input-" & $nextId + result.text = text + result.password = password + result.harness.window = newWindow() + result.harness.sk = newSilky(result.harness.window, atlas) + result.frame() + result.state.focus(result.harness.sk, result.harness.window, result.id) + result.state.selectAll() + result.frame() + +proc shortcut(window: Window, key, modifier: Button) = + ## Queues one complete hardware keyboard shortcut between frames. + window.pressButton(modifier) + window.pressButton(key) + window.releaseButton(key) + window.releaseButton(modifier) + +block: + echo "Testing hardware copy and cut preserve secure fields and clipboard" + for modifier in [KeyLeftSuper, KeyLeftControl]: + var fixture = newFixture("hidden 雪", password = true) + let originalSelection = fixture.state.selection + setClipboardString("unrelated clipboard") + for key in [KeyC, KeyX]: + fixture.harness.window.shortcut(key, modifier) + fixture.frame() + doAssert fixture.text == "hidden 雪" + doAssert fixture.state.selection == originalSelection + doAssert getClipboardString() == "unrelated clipboard" + fixture.harness.window.shortcut(KeyV, modifier) + fixture.frame() + doAssert fixture.text == "unrelated clipboard" + +block: + echo "Testing ordinary fields retain copy and cut" + var fixture = newFixture("ordinary text", password = false) + setClipboardString("old clipboard") + fixture.harness.window.shortcut(KeyC, KeyLeftSuper) + fixture.frame() + doAssert getClipboardString() == "ordinary text" + fixture.harness.window.shortcut(KeyX, KeyLeftSuper) + fixture.frame() + doAssert fixture.text.len == 0 + doAssert getClipboardString() == "ordinary text" + +block: + echo "Testing native secure-state publication and range edits" + var fixture = newFixture("secret 雪", password = true) + let window = fixture.harness.window + when defined(ios): + doAssert window.textInput.id == fixture.id + doAssert window.textInput.password + doAssert window.textInput.text == fixture.text + doAssert window.textInput.selectionEnd == fixture.text.runeLen + else: + doAssert window.textInput.id.len == 0 + doAssert window.textInput.text.len == 0 + window.onTextEdit(TextInputEdit( + kind: ReplaceText, start: 7, length: 1, text: "日" + )) + fixture.frame() + doAssert fixture.text == "secret 日" + fixture.password = false + fixture.frame() + doAssert window.textInput.id == fixture.id + doAssert not window.textInput.password + doAssert window.textInput.text == fixture.text + fixture.password = true + fixture.frame() + when defined(ios): + doAssert window.textInput.password + else: + doAssert window.textInput.id.len == 0 + doAssert window.textInput.text.len == 0 + +echo "All secure input tests passed." diff --git a/tests/test_shader_codegen.nim b/tests/test_shader_codegen.nim index 2d7b7ed2..48a68ce2 100644 --- a/tests/test_shader_codegen.nim +++ b/tests/test_shader_codegen.nim @@ -1,4 +1,4 @@ -import strutils, shady, silky/drawers/shader +import std/[strutils, tables], shady, silky/drawers/shader proc checkSampleOrder(source, base, mask: string) = ## Keeps texture derivatives valid at fragment clipping boundaries. @@ -85,4 +85,28 @@ block: "atlasSampler.sample(atlasSamplerSampler, fragmentMaskUv)" ) +block: + let + vertex = toMSL(silkyVert, shaderVertex) + uniforms = metalUniformLayout(vertex) + doAssert uniforms.size == 16 + doAssert uniforms.offsets["viewportSize"] == 0 + doAssert uniforms.offsets["atlasSize"] == 8 + doAssert "vertex VertexOut vertexMain(" in vertex + doAssert "constant ShadyUniforms0 &shadyUniforms0 [[buffer(0)]]" in vertex + doAssert "float2 pos [[attribute(0)]];" in vertex + doAssert "float4 color [[attribute(2)]];" in vertex + doAssert "float2 maskUv [[attribute(5)]];" in vertex + doAssert "fragmentMaskUv = maskUv / atlasSize;" in vertex + doAssert "output.fragmentPos = fragmentPos;" in vertex + + let fragment = toMSL(silkyFrag, shaderFragment) + doAssert "fragment float4 fragmentMain(" in fragment + doAssert "texture2d atlasSampler [[texture(0)]]" in fragment + doAssert "sampler atlasSamplerSampler [[sampler(0)]]" in fragment + doAssert "float2 fragmentPos = input.fragmentPos;" in fragment + doAssert "discard_fragment();" in fragment + doAssert "atlasSampler.sample(atlasSamplerSampler, fragmentUv)" in fragment + doAssert "atlasSampler.sample(atlasSamplerSampler, fragmentMaskUv)" in fragment + echo "Silky Shady shader codegen tests passed" diff --git a/tests/test_textboxes.nim b/tests/test_textboxes.nim index 8a374265..ecc2a39b 100644 --- a/tests/test_textboxes.nim +++ b/tests/test_textboxes.nim @@ -660,7 +660,7 @@ block: doAssert s.innerHeight == lh, "Empty text should have lineHeight" doAssert s.innerWidth == 0 let s2 = newState("\n") - doAssert s2.innerHeight == lh, "Single newline char is on line 0" + doAssert s2.innerHeight == lh * 2, "A trailing newline opens an empty line" doAssert s2.innerWidth == 0, "Single newline has zero width" let s3 = newState("abc") doAssert s3.innerHeight == lh diff --git a/tests/test_touch_scroll.nim b/tests/test_touch_scroll.nim new file mode 100644 index 00000000..09c3a447 --- /dev/null +++ b/tests/test_touch_scroll.nim @@ -0,0 +1,283 @@ +import + std/[os, strutils], + pixie, vmath, bumpy, + silky + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +var + atlas: SilkyAtlas + mode, clicks: int + popup: bool + editorText = "Editable text" + +block: + let + data = currentSourcePath().parentDir / "data" + builder = newAtlasBuilder(1024, 4) + builder.addDir(data, data & DirSep) + builder.addFont(data / "IBMPlexSans-Regular.ttf", "Default", 18) + doAssert builder.addImage("touch-icon", newImage(24, 24)) + atlas = builder.atlas + +proc draw(sk: Silky, window: Window) = + ## Exercises real nested text, icons, and scrollbars. + ui: + frame "touch parent": + box 20, 30, 320, 180 + patch "" + layout TopToBottom + horizontalPadding 0 + verticalPadding 0 + itemSpacing 0 + group "document": + size 300, (if mode in [1, 4]: 120 else: 500) + sk.startCurrentChildren() + if mode == 2: + clickableIcon("touch-icon", false): + inc clicks + elif mode == 3: + sk.textBox(window, "touch editable", editorText, 300, 120, wrapWords = true) + else: + let text = + if mode == 1: "Line of text\n".repeat(80) + else: ("Wide line ".repeat(30) & "\n").repeat(6) + sk.richTextBox(window, "touch rich", text, 300, + (if mode in [1, 4]: 120 else: 500), wrapWords = false) + group "spacer": + size 300, 500 + if popup: + sk.pushLayer(PopupsLayer) + discard sk.interact(rect(50, 60, 180, 120), true) + sk.popLayer() + +proc drawButtons(sk: Silky, window: Window) = + ## Exercises release-triggered controls without any scrollable overflow. + for i in 0 ..< 2: + let interaction = sk.interact(rect((20 + i * 100).float32, 30, 80, 40), true) + if interaction.isReleased(window): + inc clicks + +proc tick(h: var TestHarness) = + ## Draws a frame and resets native transient input. + discard h.pumpFrame(draw) + +proc setup(): TestHarness = + ## Starts from displayed geometry without requiring a hover frame. + frameStates.clear() + richTextBoxStates.clear() + textBoxStates.clear() + result = newTestHarness(atlas) + result.window.pointerSource = TouchPointer + result.tick() + +proc press(h: var TestHarness, x, y: int) = + ## Starts a finger gesture at a logical coordinate. + h.window.moveMouse(x, y) + h.window.pressButton(MouseLeft) + h.tick() + +proc release(h: var TestHarness, x, y: int) = + ## Delivers final movement and release in the same frame. + h.window.moveMouse(x, y) + h.window.releaseButton(MouseLeft) + h.tick() + +proc near(actual, expected: float32) = + ## Checks logical deltas without rounding away fractional positions. + doAssert abs(actual - expected) < 0.01, $actual & " != " & $expected + +block: + echo "Testing nested horizontal pan leaves history unchanged" + var h = setup() + h.press(170, 110) + h.window.moveMouse(110, 112) + h.tick() + near(frameStates["touch parent"].scrollPos.y, 0) + near(richTextBoxStates["touch rich"].editor.scrollPos.x, 60) + h.release(100, 112) + near(richTextBoxStates["touch rich"].editor.scrollPos.x, 70) + +block: + echo "Testing deepest vertical viewport owns a pan" + mode = 1 + var h = setup() + h.press(120, 90) + h.window.moveMouse(120, 55) + h.tick() + near(frameStates["touch parent"].scrollPos.y, 0) + near(richTextBoxStates["touch rich"].editor.scrollPos.y, 35) + h.release(120, 45) + near(richTextBoxStates["touch rich"].editor.scrollPos.y, 45) + +block: + echo "Testing forgiving scrollbar grab and coalesced track taps" + mode = 0 + var h = setup() + let state = frameStates["touch parent"] + h.press(318, 35) + near(state.scrollPos.y, 0) + h.window.moveMouse(318, 80) + h.tick() + doAssert state.scrollPos.y > 100 + h.release(318, 95) + let position = state.scrollPos.y + h.window.moveMouse(100, 150) + h.tick() + near(state.scrollPos.y, position) + doAssert not state.scrollingY + state.scrollPos.y = 0 + h.tick() + h.window.moveMouse(318, 150) + h.window.pressButton(MouseLeft) + h.window.releaseButton(MouseLeft) + h.tick() + doAssert state.scrollPos.y > 300 and not state.scrollingY + +block: + echo "Testing cancellation preserves position and accepts a fresh gesture" + var h = setup() + let state = frameStates["touch parent"] + h.press(100, 140) + h.window.moveMouse(100, 100) + h.tick() + near(state.scrollPos.y, 40) + h.release(-1, -1) + near(state.scrollPos.y, 40) + h.press(100, 140) + h.window.moveMouse(100, 100) + h.tick() + near(state.scrollPos.y, 80) + +block: + echo "Testing swipe cancels a touch icon and tap activates once" + mode = 2 + var h = setup() + h.press(30, 40) + doAssert clicks == 0 + h.release(30, 80) + doAssert clicks == 0 + h.press(30, 40) + h.release(30, 40) + doAssert clicks == 1 + h.tick() + doAssert clicks == 1 + +block: + echo "Testing editable tap still starts native keyboard input" + mode = 3 + var h = setup() + h.press(80, 60) + h.release(80, 60) + doAssert h.window.runeInputEnabled + doAssert textBoxStates["touch editable"].focused + +block: + echo "Testing desktop wheel still scrolls without capturing a pan" + mode = 0 + var h = setup() + h.window.pointerSource = MousePointer + h.window.moveMouse(100, 100) + h.window.scrollDelta = vec2(0, if ScrollSpeed > 0: 3 else: -3) + h.tick() + near(frameStates["touch parent"].scrollPos.y, 3 * abs(ScrollSpeed)) + doAssert not h.sk.touchScrolling + +block: + echo "Testing a horizontal track tap stays in the nested editor" + mode = 4 + var h = setup() + h.press(210, 135) + h.release(210, 135) + doAssert richTextBoxStates["touch rich"].editor.scrollPos.x > 100 + near(frameStates["touch parent"].scrollPos.y, 0) + +block: + echo "Testing popup controls block underlying viewport pans" + mode = 0 + popup = true + var h = setup() + h.press(100, 140) + h.release(100, 90) + near(frameStates["touch parent"].scrollPos.y, 0) + doAssert not h.sk.touchScrolling + popup = false + +block: + echo "Testing reset and cancellation do not poison the next gesture" + var h = setup() + h.press(100, 140) + h.sk.resetInteractions() + h.release(-1, -1) + h.tick() + h.press(100, 140) + h.release(100, 90) + near(frameStates["touch parent"].scrollPos.y, 50) + +block: + echo "Testing panning preserves an unrelated editable selection" + mode = 3 + var h = setup() + let editor = textBoxStates["touch editable"] + editor.cursor = 8 + editor.selector = 2 + h.press(100, 180) + h.release(100, 140) + doAssert editor.cursor == 8 and editor.selector == 2 + +block: + echo "Testing a complete coalesced pan ignores the prior hover position" + mode = 0 + for scale in [1, 3]: + var h = setup() + h.sk.uiScale = scale.float32 + h.tick() + h.window.moveMouse(700 * scale, 400 * scale) + h.window.moveMouse(120 * scale, 150 * scale) + h.window.pressButton(MouseLeft) + h.window.moveMouse(120 * scale, 130 * scale) + h.window.moveMouse(120 * scale, 95 * scale) + h.window.releaseButton(MouseLeft) + h.tick() + near(frameStates["touch parent"].scrollPos.y, 55) + doAssert h.sk.touchScrolling + h.tick() + doAssert not h.sk.touchScrolling + near(frameStates["touch parent"].scrollPos.y, 55) + +block: + echo "Testing a coalesced thumb drag uses the original grab offset" + var h = setup() + h.window.moveMouse(700, 400) + h.window.moveMouse(318, 35) + h.window.pressButton(MouseLeft) + h.window.moveMouse(318, 60) + h.window.moveMouse(318, 95) + h.window.releaseButton(MouseLeft) + h.tick() + let position = frameStates["touch parent"].scrollPos.y + doAssert position > 200 and h.sk.touchScrolling + h.tick() + near(frameStates["touch parent"].scrollPos.y, position) + doAssert not frameStates["touch parent"].scrollingY + +block: + echo "Testing a drag across buttons without overflow cannot activate either" + clicks = 0 + var h = newTestHarness(atlas) + h.window.pointerSource = TouchPointer + discard h.pumpFrame(drawButtons) + h.window.moveMouse(40, 45) + h.window.pressButton(MouseLeft) + discard h.pumpFrame(drawButtons) + h.window.moveMouse(140, 45) + h.window.releaseButton(MouseLeft) + discard h.pumpFrame(drawButtons) + doAssert clicks == 0 + h.window.pressButton(MouseLeft) + h.window.releaseButton(MouseLeft) + discard h.pumpFrame(drawButtons) + doAssert clicks == 1 + +echo "Touch scrolling tests passed."