From fdd8706ebb0c90bdc7d49506bbbbd96e7324e152 Mon Sep 17 00:00:00 2001 From: treeform Date: Wed, 4 Nov 2026 12:19:25 -0800 Subject: [PATCH 01/16] fix: stop subwindow dragging on outside release [verified] --- .github/workflows/build.yml | 1 + src/silky/widgets.nim | 5 ++- tests/test_subwindow.nim | 67 +++++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 tests/test_subwindow.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3229351d..605a63cb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,6 +59,7 @@ jobs: run: | nim r tests/test_textboxes.nim nim r -d:silkyTesting -d:nimTypeNames tests/test_inputs.nim + nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim nim r -d:silkyTesting tests/test_layout.nim nim r -d:silkyTesting tests/test_layout_regressions.nim diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index 4f70fd5c..53423eec 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -163,7 +163,10 @@ proc subWindowStart*( titleBarInteraction = sk.interact(titleBarRect, true) case titleBarInteraction - of Disabled, None, Error, ReleasedOutside: + of Disabled, None, Error: + sk.draw9Patch("header.9patch", sk.theme.headerPatch, sk.pos, sk.size) + of ReleasedOutside: + subWindowState.dragging = false sk.draw9Patch("header.9patch", sk.theme.headerPatch, sk.pos, sk.size) of Pressed: subWindowState.dragOffset = sk.mousePos - subWindowState.pos diff --git a/tests/test_subwindow.nim b/tests/test_subwindow.nim new file mode 100644 index 00000000..9eff4e62 --- /dev/null +++ b/tests/test_subwindow.nim @@ -0,0 +1,67 @@ +import + std/options, + vmath, + silky + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +let builder = newAtlasBuilder(1024, 4) +builder.addDir("tests/data/", "tests/data/") +builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18.0) + +var show = true + +proc drawSubwindow(sk: Silky, window: Window) = + ## Exercise the real title-bar interaction and balanced window layout. + let state = sk.subWindowStart( + window, "Drag regression", show, some(vec2(100, 100)), some(vec2(300, 200)) + ) + sk.subWindowEnd(window, state) + +block: + subWindowStates.clear() + var harness = newTestHarness(builder.atlas) + let window = harness.window + window.moveMouse(150, 110) + discard harness.pumpFrame(drawSubwindow, 2) + let state = subWindowStates["Drag regression"] + window.pressButton(MouseLeft) + discard harness.pumpFrame(drawSubwindow) + doAssert state.dragging, "Pressing the header must start dragging" + doAssert state.pos == vec2(100, 100) + + # A held drag must keep working even when the pointer leaves the old header. + window.moveMouse(210, 160) + discard harness.pumpFrame(drawSubwindow) + doAssert state.dragging + doAssert state.pos == vec2(160, 150) + let heldPosition = state.pos + + # Release well outside the current header before another frame is drawn. + window.moveMouse(450, 350) + window.releaseButton(MouseLeft) + discard harness.pumpFrame(drawSubwindow) + doAssert not state.dragging, "Releasing outside the header must end dragging" + doAssert state.pos == heldPosition, "A released drag must not move the window" + + window.moveMouse(600, 450) + discard harness.pumpFrame(drawSubwindow, 2) + doAssert state.pos == heldPosition, + "Pointer movement after an outside release must not drag the window" + + # A new drag starts from the last held position, not a stale drag offset. + window.moveMouse(230, 160) + discard harness.pumpFrame(drawSubwindow, 2) + window.pressButton(MouseLeft) + discard harness.pumpFrame(drawSubwindow) + doAssert state.dragging and state.pos == heldPosition + window.moveMouse(260, 180) + discard harness.pumpFrame(drawSubwindow) + doAssert state.pos == heldPosition + vec2(30, 20) + discard harness.pumpFrame(drawSubwindow, 2) + window.releaseButton(MouseLeft) + discard harness.pumpFrame(drawSubwindow) + doAssert not state.dragging, "Releasing over the header must still end dragging" + + echo "Subwindow outside release stops dragging and the next drag starts cleanly" From 614e84bc22415239e0a0a3cf98d407c156ccde73 Mon Sep 17 00:00:00 2001 From: treeform Date: Tue, 10 Nov 2026 16:42:15 -0800 Subject: [PATCH 02/16] add native chat text and input --- .github/workflows/build.yml | 7 + nimby.lock | 2 +- src/silky/atlas.nim | 112 ++++-- src/silky/clips.nim | 1 + src/silky/contexts.nim | 124 ++++-- src/silky/drawers/metal4.nim | 14 +- src/silky/drawers/shader.nim | 18 +- src/silky/dsl.nim | 32 ++ src/silky/internal/inputs.nim | 103 ++++- src/silky/semantics.nim | 21 +- src/silky/testwindow.nim | 29 +- src/silky/textboxes.nim | 696 +++++++++++++++++++++++++++++++-- src/silky/widgets.nim | 69 +++- tests/test_button_vertices.nim | 85 ++++ tests/test_buttons.nim | 128 ++++++ tests/test_decorations.nim | 118 ++++++ tests/test_density.nim | 315 +++++++++++++++ tests/test_inputs.nim | 641 +++++++++++++++++++++++++++++- tests/test_quotes.nim | 225 +++++++++++ tests/test_rules.nim | 141 +++++++ tests/test_shader_codegen.nim | 33 ++ tests/test_textboxes.nim | 189 +++++++++ 22 files changed, 2969 insertions(+), 134 deletions(-) create mode 100644 tests/test_button_vertices.nim create mode 100644 tests/test_buttons.nim create mode 100644 tests/test_decorations.nim create mode 100644 tests/test_density.nim create mode 100644 tests/test_quotes.nim create mode 100644 tests/test_rules.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 605a63cb..b29fa861 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,8 +59,15 @@ jobs: run: | nim r tests/test_textboxes.nim nim r -d:silkyTesting -d:nimTypeNames tests/test_inputs.nim + nim r -d:silkyTesting tests/test_buttons.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.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_button_vertices.nim nim r -d:silkyTesting tests/test_layout.nim nim r -d:silkyTesting tests/test_layout_regressions.nim nim r ${{ matrix.build_flags }} tests/test_layout_clips.nim diff --git a/nimby.lock b/nimby.lock index cec4b918..22999c53 100644 --- a/nimby.lock +++ b/nimby.lock @@ -8,7 +8,7 @@ nimsimd 1.3.2 https://github.com/guzba/nimsimd 3f6b2668ffb0867d0bf786a658b817763 bumpy 1.1.3 https://github.com/treeform/bumpy dc9a3d6d15680ec7f603959d65ba8ee4f1ddbc72 crunchy 0.1.11 https://github.com/guzba/crunchy 98eb6526982bb8aae8eec6e8781f4539fa19e049 bitty 0.1.4 https://github.com/treeform/bitty/ c40e81277c04befa37234cba5052f58648bef895 -windy 0.5.0 https://github.com/treeform/windy d3d92f5decf22f98c61d198d6285427c83f67b60 +windy 0.5.0 https://github.com/treeform/windy 8e1e2499a050bcbb1546f239b8c3a8b1b16748c0 opengl 1.2.9 https://github.com/nim-lang/opengl 8e2e098f82dc5eefd874488c37b5830233cd18f4 urlly 1.1.1 https://github.com/treeform/urlly 99784779f05649df25fd9c33003d8ef6de027345 ws 0.5.0 https://github.com/treeform/ws cbb8f763b436669392d10baec2a45778395395cc diff --git a/src/silky/atlas.nim b/src/silky/atlas.nim index 75fd9f24..cfe83e60 100644 --- a/src/silky/atlas.nim +++ b/src/silky/atlas.nim @@ -24,6 +24,8 @@ type y*: int width*: int height*: int + pixelScale*: int = 1 + ## The number of texture pixels per logical pixel. LetterEntry* = object ## The position and size of a letter in the font atlas. @@ -53,6 +55,8 @@ type ascent*: float32 lineGap*: float32 subpixelSteps*: int + pixelScale*: float32 = 1 + ## The glyph raster density; font metrics remain logical. entries*: Table[string, seq[LetterEntry]] lookup*: GlyphLookup @@ -291,9 +295,12 @@ proc writePng*(path, json: string, image: Image) = proc addImage*( builder: AtlasBuilder, name: string, - image: Image + image: Image, + pixelScale: int = 1 ): bool = ## Pack one image into the atlas. False when the atlas is full. + if pixelScale < 1: + raise newException(SilkyAtlasError, "Image pixel scale must be positive") let allocation = builder.allocator.allocate(image.width, image.height) if not allocation.success: return false @@ -306,7 +313,8 @@ proc addImage*( x: allocation.x, y: allocation.y, width: image.width, - height: image.height + height: image.height, + pixelScale: pixelScale ) true @@ -340,8 +348,9 @@ proc newAtlasBuilderFromAtlas*( for variants in fontAtlas.entries.values: for letter in variants: let - w = letter.boundsWidth.ceil.int - h = letter.boundsHeight.ceil.int + density = max(fontAtlas.pixelScale, 0.001'f) + w = (letter.boundsWidth * density).ceil.int + h = (letter.boundsHeight * density).ceil.int if w > 0 and h > 0: result.markOccupiedEntry(letter.x, letter.y, w, h) @@ -360,7 +369,12 @@ proc growAtlas*(builder: AtlasBuilder, newSize: int) = builder.allocator = newSkylineAllocator(newSize, builder.margin) builder.allocator.markRegion(0, 0, oldSize, oldSize) -proc addDir*(builder: AtlasBuilder, path: string, removePrefix: string = "") = +proc addDir*( + builder: AtlasBuilder, + path: string, + removePrefix: string = "", + pixelScale: int = 1 +) = ## Add all images in the given directory to the atlas. for file in walkDir(path): if file.path.endsWith(".png"): @@ -369,19 +383,24 @@ proc addDir*(builder: AtlasBuilder, path: string, removePrefix: string = "") = if removePrefix.len > 0: key.removePrefix(removePrefix) key.removeSuffix(".png") - if not builder.addImage(key, image): + if not builder.addImage(key, image, pixelScale): raise newException( ValueError, "Failed to allocate space for " & file.path & "\n" & "You need to increase the size of the atlas" ) -proc addDirRecursive*(builder: AtlasBuilder, path: string, removePrefix: string = "") = +proc addDirRecursive*( + builder: AtlasBuilder, + path: string, + removePrefix: string = "", + pixelScale: int = 1 +) = ## Add all images in the given directory and its subdirectories to the atlas. - builder.addDir(path, removePrefix) + builder.addDir(path, removePrefix, pixelScale) for entry in walkDir(path): if entry.kind == pcDir: - builder.addDirRecursive(entry.path, removePrefix) + builder.addDirRecursive(entry.path, removePrefix, pixelScale) proc finiteBounds(bounds: Rect): Rect = ## Glyphs with no outline (such as space) compute to infinite/NaN bounds, @@ -393,18 +412,33 @@ proc finiteBounds(bounds: Rect): Rect = else: rect(0, 0, 0, 0) -proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, chars: seq[string] = AsciiGlyphs, subpixelSteps: int = 0) = - ## Add a font to the atlas. - let fontAtlas = FontAtlas() +proc addFont*( + builder: AtlasBuilder, + typeface: Typeface, + name: string, + size: float32, + chars: seq[string] = AsciiGlyphs, + subpixelSteps: int = 0, + pixelScale: float32 = 1 +) = + ## Rasterizes a font at pixelScale with logical layout metrics. + if pixelScale <= 0 or + pixelScale.classify notin {fcNormal, fcSubnormal}: + raise newException(SilkyAtlasError, "Font pixel scale must be positive") + let + density = pixelScale.float32 + fontAtlas = FontAtlas() fontAtlas.size = size fontAtlas.subpixelSteps = subpixelSteps - let typeface = readTypeface(path) - var fontObj = newFont(typeface) + fontAtlas.pixelScale = pixelScale + let fontObj = newFont(typeface) fontObj.size = size - fontAtlas.lineHeight = (typeface.ascent - typeface.descent + typeface.lineGap) * fontObj.scale - fontAtlas.ascent = typeface.ascent * fontObj.scale - fontAtlas.descent = typeface.descent * fontObj.scale - fontAtlas.lineGap = typeface.lineGap * fontObj.scale + let logicalScale = fontObj.scale + fontAtlas.lineHeight = + (typeface.ascent - typeface.descent + typeface.lineGap) * logicalScale + fontAtlas.ascent = typeface.ascent * logicalScale + fontAtlas.descent = typeface.descent * logicalScale + fontAtlas.lineGap = typeface.lineGap * logicalScale # 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 @@ -413,10 +447,10 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, let rune = glyphStr.runeAt(0) glyphPath = typeface.getGlyphPath(rune) - scale = fontObj.scale + scale = logicalScale * density scaleMat = scale(vec2(scale)) baseBounds = glyphPath.computeBounds(scaleMat).snapToPixels().finiteBounds() - advance = typeface.getAdvance(rune) * scale + advance = typeface.getAdvance(rune) * logicalScale fontAtlas.entries[glyphStr] = @[] for variant in 0 ..< numVariants: let @@ -441,7 +475,7 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, let allocation = builder.allocator.allocate(glyphImage.width, glyphImage.height) if not allocation.success: raise newException( - ValueError, + SilkyAtlasError, "Failed to allocate space for glyph: " & glyphStr & " variant " & $variant & "\n" & "You need to increase the size of the atlas" ) @@ -453,20 +487,20 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, fontAtlas.entries[glyphStr].add(LetterEntry( x: allocation.x, y: allocation.y, - boundsX: baseBounds.x + subpixelOffset.floor, - boundsY: baseBounds.y, - boundsWidth: offsetBounds.w.ceil, - boundsHeight: offsetBounds.h.ceil, + boundsX: (baseBounds.x + subpixelOffset.floor) / density, + boundsY: baseBounds.y / density, + boundsWidth: offsetBounds.w.ceil / density, + boundsHeight: offsetBounds.h.ceil / density, advance: advance )) else: fontAtlas.entries[glyphStr].add(LetterEntry( x: 0, y: 0, - boundsX: baseBounds.x, - boundsY: baseBounds.y, - boundsWidth: baseBounds.w, - boundsHeight: baseBounds.h, + boundsX: baseBounds.x / density, + boundsY: baseBounds.y / density, + boundsWidth: baseBounds.w / density, + boundsHeight: baseBounds.h / density, advance: advance )) # Kerning only needs to be stored once per base glyph (variant 0). @@ -474,10 +508,28 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, let rune2 = glyphStr2.runeAt(0) let kerning = typeface.getKerningAdjustment(rune, rune2) if kerning != 0: - fontAtlas.entries[glyphStr][0].kerning[glyphStr2] = kerning * scale + fontAtlas.entries[glyphStr][0].kerning[glyphStr2] = + kerning * logicalScale fontAtlas.rebuildGlyphLookups() builder.atlas.fonts[name] = fontAtlas +proc addFont*( + builder: AtlasBuilder, + path: string, + name: string, + size: float32, + chars: seq[string] = AsciiGlyphs, + subpixelSteps: int = 0, + pixelScale: float32 = 1 +) = + ## Loads a font file and rasterizes it at the requested pixel density. + try: + builder.addFont( + readTypeface(path), name, size, chars, subpixelSteps, pixelScale + ) + except PixieError as error: + raise newException(SilkyAtlasError, "Could not load font: " & error.msg) + proc write*(builder: AtlasBuilder, outputPngPath: string) = ## Write atlas image and JSON metadata into a single PNG. writePng(outputPngPath, builder.atlas.toJson(), builder.atlasImage) diff --git a/src/silky/clips.nim b/src/silky/clips.nim index 14ae5cf6..5653d4f5 100644 --- a/src/silky/clips.nim +++ b/src/silky/clips.nim @@ -18,6 +18,7 @@ type ## Vertex and clip boundaries for a deferred layout on both layers. marks*: array[2, int] clipMark*: int + textMark*: int proc intersectClips(a, b: Rect): Rect = ## Intersects clip bounds while keeping empty intersections empty. diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 0f79620c..0532a675 100644 --- a/src/silky/contexts.nim +++ b/src/silky/contexts.nim @@ -236,6 +236,7 @@ proc vertexMark*(sk: Silky): int = proc beginVertexSpan*(sk: Silky): VertexSpan = ## Captures vertices and original clips until a layout is placed. result.clipMark = sk.clipStack.regions.len + result.textMark = sk.inputs.textPlacementMark() for layer in 0 ..< result.marks.len: result.marks[layer] = sk.drawer.layers[layer].len sk.vertexClips[layer].setLen(result.marks[layer]) @@ -243,11 +244,20 @@ proc beginVertexSpan*(sk: Silky): VertexSpan = proc endVertexSpan*(sk: Silky, span: VertexSpan, offset: Vec2) = ## Places a deferred span and resolves clips against fixed ancestors. + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2( + round(offset.x * scale) / scale, + round(offset.y * scale) / scale + ) + # Deferred placement must preserve the pixel grid used by text and images. + # Layout and clipping retain their exact logical positions. sk.clipStack.translateClips(span.clipMark, offset) + sk.inputs.translateTextInput(span.textMark, paintOffset * scale) for layer in 0 ..< span.marks.len: for i in span.marks[layer] ..< sk.drawer.layers[layer].len: let clip = sk.clipStack.regions[sk.vertexClips[layer][i]].visible - sk.drawer.layers[layer][i].pos += offset + sk.drawer.layers[layer][i].pos += paintOffset sk.drawer.layers[layer][i].clipPos = clip.xy sk.drawer.layers[layer][i].clipSize = clip.wh dec sk.clipStack.captures @@ -257,6 +267,7 @@ proc moveVerticesBehind*(sk: Silky, layer, spanStart, chromeStart: int) = ## span so late-drawn parent chrome renders behind its children (T2). let total = sk.drawer.layers[layer].len if chromeStart > spanStart and chromeStart < total: + sk.inputs.moveTextInputBehind(ord(layer), spanStart, chromeStart, total) sk.drawer.layers[layer].rotateLeft( spanStart ..< total, chromeStart - spanStart ) @@ -270,16 +281,23 @@ proc translateVertices*(sk: Silky, layer, spanStart: int, offset: Vec2) = ## whose position is only known at scope close (T6). if offset == vec2(0, 0): return + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2( + round(offset.x * scale) / scale, + round(offset.y * scale) / scale + ) + sk.inputs.translateTextInputVertices(ord(layer), spanStart, paintOffset * scale) for i in spanStart ..< sk.drawer.layers[layer].len: - sk.drawer.layers[layer][i].pos += offset + sk.drawer.layers[layer][i].pos += paintOffset proc getImageSize*(sk: Silky, image: string): Vec2 = - ## Returns the size of an atlas image in pixels. + ## Returns the logical size of an atlas image. if image notin sk.atlas.entries: echo "[Warning] Image not found in atlas: " & image return vec2(0, 0) let uv = sk.atlas.entries[image] - vec2(uv.width.float32, uv.height.float32) + vec2(uv.width.float32, uv.height.float32) / max(uv.pixelScale, 1).float32 proc nextRune(text: string, i: var int): Rune {.inline.} = ## Reads one UTF-8 rune and advances the byte index. @@ -305,6 +323,7 @@ proc resetInteractions*(sk: Silky) = proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = ## Starts a frame and updates the shared UI state. + sk.cursor = Cursor(kind: ArrowCursor) sk.inputs.beginInputFrame(window) beginProfileFrame() @@ -348,6 +367,12 @@ proc endInteractions(interactor: var Interactor) = proc endUiShared*(sk: Silky) = ## Ends a frame after the backend has finished drawing. + let previousCursor = sk.window.cursor + if previousCursor.kind != sk.cursor.kind or + (sk.cursor.kind == CustomCursor and + (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() @@ -527,6 +552,8 @@ proc drawText*( let fontData = sk.atlas.fonts[font] + density = max(fontData.pixelScale, 0.001'f) + displayScale = max(sk.uiScale, 0.001'f) maxPos = pos + vec2(maxWidth, maxHeight) hasSubpixel = fontData.subpixelSteps > 0 layer = sk.drawer.currentLayer @@ -551,9 +578,9 @@ proc drawText*( of LeftAlign: 0.0'f of CenterAlign: - floor((maxWidth - lineWidth) * 0.5) + floor((maxWidth - lineWidth) * 0.5 * displayScale) / displayScale of RightAlign: - floor(maxWidth - lineWidth) + floor((maxWidth - lineWidth) * displayScale) / displayScale if dx != 0: for j in lineStartIdx ..< sk.drawer.layers[layer].len: sk.drawer.layers[layer][j].pos.x += dx @@ -597,7 +624,9 @@ proc drawText*( let variant = if hasSubpixel: - let frac = currentPos.x - currentPos.x.floor + let + rasterX = currentPos.x * density + frac = rasterX - rasterX.floor (frac * fontData.subpixelSteps.float32).int mod fontData.subpixelSteps else: @@ -626,15 +655,24 @@ proc drawText*( break if entry.boundsWidth > 0 and entry.boundsHeight > 0: - let glyphPos = vec2( - floor(currentPos.x) + entry.boundsX, - round(currentPos.y + entry.boundsY) - ) + let + glyphX = + if hasSubpixel: + floor(currentPos.x * density) / density + entry.boundsX + else: + floor((currentPos.x + entry.boundsX) * displayScale) / + displayScale + # Keep every glyph on one baseline, including mismatched atlas scales. + glyphPos = vec2( + glyphX, + round(currentPos.y * displayScale) / displayScale + entry.boundsY + ) + glyphSize = vec2(entry.boundsWidth, entry.boundsHeight) sk.drawQuad( glyphPos, - vec2(entry.boundsWidth, entry.boundsHeight), + glyphSize, vec2(entry.x.float32, entry.y.float32), - vec2(entry.boundsWidth, entry.boundsHeight), + glyphSize * density, color ) @@ -657,9 +695,9 @@ proc drawText*( of TopAlign: 0.0'f of MiddleAlign: - floor((maxHeight - textHeight) * 0.5) + floor((maxHeight - textHeight) * 0.5 * displayScale) / displayScale of BottomAlign: - floor(maxHeight - textHeight) + floor((maxHeight - textHeight) * displayScale) / displayScale if dy != 0: for j in textStartIdx ..< sk.drawer.layers[layer].len: sk.drawer.layers[layer][j].pos.y += dy @@ -744,6 +782,10 @@ proc addAtlasImage*(sk: Silky, name: string, image: Image) = sk.atlas = sk.builder.atlas sk.uploadAtlas() +proc alignPixels(pos: Vec2, scale: float32): Vec2 = + ## Aligns a logical point to the framebuffer's pixel grid. + vec2(round(pos.x * scale), round(pos.y * scale)) / scale + proc drawImage*( sk: Silky, name: string, @@ -755,7 +797,15 @@ proc drawImage*( if name notin sk.atlas.entries: echo "[Warning] Sprite not found in atlas: " & name return - let uv = sk.atlas.entries[name] + let + uv = sk.atlas.entries[name] + density = max(uv.pixelScale, 1).float32 + displayScale = max(sk.uiScale, 0.001'f) + alignedPos = + if density > 1: + alignPixels(pos, displayScale) + else: + pos var mPos = vec2(-1, -1) mSize = vec2(0, 0) @@ -764,8 +814,8 @@ proc drawImage*( mPos = vec2(m.x.float32, m.y.float32) mSize = vec2(m.width.float32, m.height.float32) sk.drawQuad( - pos, - vec2(uv.width.float32, uv.height.float32), + alignedPos, + vec2(uv.width.float32, uv.height.float32) / density, vec2(uv.x.float32, uv.y.float32), vec2(uv.width.float32, uv.height.float32), color, @@ -796,23 +846,35 @@ proc draw9Patch*( return let scale = max(sk.sliceScale, 1) - topS = top * scale - rightS = right * scale - bottomS = bottom * scale - leftS = left * scale uv = sk.atlas.entries[name] - l = leftS.float32 - r = rightS.float32 - u = topS.float32 - d = bottomS.float32 + density = max(uv.pixelScale, 1) + topS = top * scale * density + 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 srcXOffsets = [0.int, leftS, uv.width - rightS] srcWidths = [leftS, uv.width - leftS - rightS, rightS] srcYOffsets = [0.int, topS, uv.height - bottomS] srcHeights = [topS, uv.height - topS - bottomS, bottomS] - dstXOffsets = [0.0'f, l, size.x - r] - dstWidths = [l, size.x - l - r, r] - dstYOffsets = [0.0'f, u, size.y - d] - dstHeights = [u, size.y - u - d, d] + dstXOffsets = [0.0'f, l, alignedSize.x - r] + dstWidths = [l, alignedSize.x - l - r, r] + dstYOffsets = [0.0'f, u, alignedSize.y - d] + dstHeights = [u, alignedSize.y - u - d, d] order = [ (0, 0), (2, 0), (0, 2), (2, 2), (1, 0), (0, 1), (2, 1), (1, 2), @@ -828,7 +890,7 @@ proc draw9Patch*( if dw <= 0.001 or dh <= 0.001 or sw <= 0 or sh <= 0: continue sk.drawQuad( - vec2(pos.x + dstXOffsets[x], pos.y + dstYOffsets[y]), + alignedPos + vec2(dstXOffsets[x], dstYOffsets[y]), vec2(dw, dh), vec2( (uv.x + srcXOffsets[x]).float32, diff --git a/src/silky/drawers/metal4.nim b/src/silky/drawers/metal4.nim index 4fa8630e..dbd8d125 100644 --- a/src/silky/drawers/metal4.nim +++ b/src/silky/drawers/metal4.nim @@ -144,18 +144,20 @@ fragment float4 texturedFragmentMain( 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(); } - float4 base = tex.sample(texSampler, in.uv); - if (in.maskUv.x >= 0.0) { - float maskR = tex.sample(texSampler, in.maskUv).r; - return float4(base.rgb * mix(float3(1.0), in.color.rgb, maskR), base.a * in.color.a); - } - return base * in.color; + return shaded; } """ diff --git a/src/silky/drawers/shader.nim b/src/silky/drawers/shader.nim index 4dd4a58c..7e975f47 100644 --- a/src/silky/drawers/shader.nim +++ b/src/silky/drawers/shader.nim @@ -41,17 +41,19 @@ proc silkyFrag*( fragmentMaskUv: Vec2, fragColor: var Vec4 ) = + # Sample before clipping so neighboring fragments provide valid derivatives. + let base = texture(atlasSampler, fragmentUv) + var shaded = base * fragmentColor + if fragmentMaskUv.x >= 0.0: + let maskR = texture(atlasSampler, fragmentMaskUv).r + shaded = vec4( + base.rgb * mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), + base.a * fragmentColor.a + ) if fragmentPos.x < fragmentClipPos.x or fragmentPos.y < fragmentClipPos.y or fragmentPos.x > fragmentClipPos.x + fragmentClipSize.x or fragmentPos.y > fragmentClipPos.y + fragmentClipSize.y: discardFragment() - elif fragmentMaskUv.x >= 0.0: - let base = texture(atlasSampler, fragmentUv) - let maskR = texture(atlasSampler, fragmentMaskUv).r - fragColor = vec4( - base.rgb * mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), - base.a * fragmentColor.a - ) else: - fragColor = texture(atlasSampler, fragmentUv) * fragmentColor + fragColor = shaded diff --git a/src/silky/dsl.nim b/src/silky/dsl.nim index 0b74d27d..632854c6 100644 --- a/src/silky/dsl.nim +++ b/src/silky/dsl.nim @@ -936,6 +936,38 @@ template button*(label: string, isEnabled: bool, body: untyped) = baseWidgets.button(label, isEnabled, false): body +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + isError: bool, + body: untyped +) = + ## Creates a native minimum-size button inside the current DSL layout. + profileBlock "button": + sk.startCurrentChildren() + baseWidgets.button(label, minimumSize, isEnabled, isError): + body + +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + body: untyped +) = + ## Creates a minimum-size button with an enabled state. + profileBlock "button": + sk.startCurrentChildren() + baseWidgets.button(label, minimumSize, isEnabled, false): + body + +template button*(label: string, minimumSize: Vec2, body: untyped) = + ## Creates an enabled minimum-size button. + profileBlock "button": + sk.startCurrentChildren() + baseWidgets.button(label, minimumSize, true, false): + body + template icon*(imageName: string) = profileBlock "icon": sk.startCurrentChildren() diff --git a/src/silky/internal/inputs.nim b/src/silky/internal/inputs.nim index 63c3c92c..e77e8f22 100644 --- a/src/silky/internal/inputs.nim +++ b/src/silky/internal/inputs.nim @@ -1,5 +1,6 @@ import std/unicode, + vmath, silky/common when defined(silkyTesting): @@ -11,12 +12,14 @@ const MaxPendingEvents = 65_536 type InputKind* = enum - KeyDown, KeyUp, TextInput + KeyDown, KeyUp, TextInput, TextCommit, NativeEdit InputEvent* = object kind*: InputKind button*: Button rune*: Rune + text*: string + edit*: TextInputEdit control*, shift*, alt*, super*: bool CallbackIdentity = tuple[code, environment: pointer] @@ -29,10 +32,12 @@ type epoch: uint64 submitted: bool consumed: bool - callbacks: array[4, CallbackIdentity] + callbacks: array[6, CallbackIdentity] forwardedKeys: set[Button] consumedKeys: set[Button] releaseCallback: proc(button: Button) + pendingText: TextInputState + placementSerial, placementLayer, placementVertex: int proc identity[T](callback: T): CallbackIdentity = ## Identifies a callback without retaining its closure environment. @@ -67,6 +72,8 @@ proc stopInput*(inputs: TextInputs, window: Window) = inputs.editable = false inputs.id.setLen(0) inputs.events.setLen(0) + inputs.pendingText = TextInputState() + window.setTextInputState(TextInputState()) if window.runeInputEnabled: window.runeInputEnabled = false @@ -99,6 +106,13 @@ proc installPress(inputs: TextInputs, window: Window) = event.kind = KeyDown event.button = button inputs.consumedKeys.incl(button) + if inputs.editable and button == KeyV and + (event.super or (event.control and not event.alt)): + event.kind = TextCommit + event.text = getClipboardString() + if event.text.len > 0: + inputs.addEvent(event) + return inputs.addEvent(event) return if button >= Key0: @@ -161,6 +175,38 @@ proc installFocus(inputs: TextInputs, window: Window) = previousFocus() inputs.callbacks[3] = identity(window.onFocusChange) +proc installText(inputs: TextInputs, window: Window) = + ## Captures complete native commits before a dictation tool restores state. + let + windowPointer = cast[pointer](window) + previousText = window.onTextInput + window.onTextInput = proc(text: string) = + ## Preserves one native insertion as one ordered editing operation. + let window = cast[Window](windowPointer) + if inputs.active: + if inputs.editable and text.len > 0: + inputs.addEvent(InputEvent(kind: TextCommit, text: text)) + return + if previousText != nil: + previousText(text) + elif window.onRune != nil: + for rune in text.runes: + window.onRune(rune) + inputs.callbacks[4] = identity(window.onTextInput) + +proc installEdit(inputs: TextInputs, window: Window) = + ## Queues native accessibility edits in the same order as keyboard input. + let previousEdit = window.onTextEdit + window.onTextEdit = proc(edit: TextInputEdit) = + ## Applies edits only to the field that currently owns text input. + if inputs.active: + if inputs.editable: + inputs.addEvent(InputEvent(kind: NativeEdit, edit: edit)) + return + if previousEdit != nil: + previousEdit(edit) + inputs.callbacks[5] = identity(window.onTextEdit) + proc overrideCallbacks( inputs: TextInputs, window: Window, initialize = false ) = @@ -173,6 +219,10 @@ proc overrideCallbacks( inputs.installRune(window) if initialize or identity(window.onFocusChange) != inputs.callbacks[3]: inputs.installFocus(window) + if initialize or identity(window.onTextInput) != inputs.callbacks[4]: + inputs.installText(window) + if initialize or identity(window.onTextEdit) != inputs.callbacks[5]: + inputs.installEdit(window) proc newTextInputs*(window: Window): TextInputs = ## Sets up all text input handling directly from the window. @@ -187,6 +237,51 @@ proc beginInputFrame*(inputs: TextInputs, window: Window) = inputs.overrideCallbacks(window) inputs.submitted = false inputs.consumed = false + inputs.pendingText = TextInputState() + inputs.placementSerial = 0 + +proc textPlacementMark*(inputs: TextInputs): int = + ## Marks the start of a deferred layout containing a focused editor. + if inputs != nil: + result = inputs.placementSerial + +proc publishTextInput*( + inputs: TextInputs, state: TextInputState, layer, firstVertex: int +) = + ## Stages native editor state until layout placement is complete. + inputs.pendingText = state + inputs.placementLayer = layer + inputs.placementVertex = firstVertex + inc inputs.placementSerial + +proc translateTextInput*(inputs: TextInputs, first: int, offset: Vec2) = + ## Moves an editor published inside a deferred layout span. + if inputs != nil and inputs.placementSerial > first: + inputs.pendingText.bounds.x += offset.x + inputs.pendingText.bounds.y += offset.y + +proc translateTextInputVertices*( + inputs: TextInputs, layer, first: int, offset: Vec2 +) = + ## Moves editor bounds along with their rendered vertices. + if inputs != nil and inputs.placementSerial > 0 and + inputs.placementLayer == layer and inputs.placementVertex >= first: + inputs.pendingText.bounds.x += offset.x + inputs.pendingText.bounds.y += offset.y + +proc moveTextInputBehind*( + inputs: TextInputs, layer, spanStart, chromeStart, total: int +) = + ## Preserves the editor's vertex position when parent chrome is reordered. + if inputs == nil or inputs.placementSerial == 0: + return + if inputs.placementLayer != layer or + inputs.placementVertex < spanStart or inputs.placementVertex >= total: + return + if inputs.placementVertex < chromeStart: + inputs.placementVertex += total - chromeStart + else: + inputs.placementVertex -= chromeStart - spanStart proc submitInput*( inputs: TextInputs, @@ -226,3 +321,7 @@ proc endInputFrame*(inputs: TextInputs, window: Window) = ## Ends capture when the active field was not submitted this frame. if not inputs.submitted: inputs.stopInput(window) + elif inputs.editable and inputs.pendingText.id == inputs.id: + window.setTextInputState(inputs.pendingText) + else: + window.setTextInputState(TextInputState()) diff --git a/src/silky/semantics.nim b/src/silky/semantics.nim index f455937e..013e7e8f 100644 --- a/src/silky/semantics.nim +++ b/src/silky/semantics.nim @@ -393,11 +393,16 @@ proc vertexMark*(sk: Silky): int = proc beginVertexSpan*(sk: Silky): VertexSpan = ## Captures clip bounds while a semantic layout awaits placement. result.clipMark = sk.clipStack.regions.len + result.textMark = sk.inputs.textPlacementMark() inc sk.clipStack.captures proc endVertexSpan*(sk: Silky, span: VertexSpan, offset: Vec2) = ## Places captured clip bounds without emitting GPU vertices. + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2(round(offset.x * scale), round(offset.y * scale)) sk.clipStack.translateClips(span.clipMark, offset) + sk.inputs.translateTextInput(span.textMark, paintOffset) dec sk.clipStack.captures proc moveVerticesBehind*(sk: Silky, layer, spanStart, chromeStart: int) = @@ -405,6 +410,7 @@ proc moveVerticesBehind*(sk: Silky, layer, spanStart, chromeStart: int) = ## span so late-drawn parent chrome renders behind its children (T2). let total = sk.layers[layer].len if chromeStart > spanStart and chromeStart < total: + sk.inputs.moveTextInputBehind(ord(layer), spanStart, chromeStart, total) sk.layers[layer].rotateLeft( spanStart ..< total, chromeStart - spanStart ) @@ -414,6 +420,10 @@ proc translateVertices*(sk: Silky, layer, spanStart: int, offset: Vec2) = ## whose position is only known at scope close (T6). if offset == vec2(0, 0): return + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2(round(offset.x * scale), round(offset.y * scale)) + sk.inputs.translateTextInputVertices(ord(layer), spanStart, paintOffset) for i in spanStart ..< sk.layers[layer].len: sk.layers[layer][i].pos += offset @@ -452,11 +462,11 @@ proc place*(sk: Silky, size: Vec2): Vec2 = sk.advance(size) proc getImageSize*(sk: Silky, image: string): Vec2 = - ## Returns the size of an image from the atlas. + ## Returns the logical size of an image from the atlas. if image notin sk.atlas.entries: return vec2(0, 0) let uv = sk.atlas.entries[image] - vec2(uv.width.float32, uv.height.float32) + vec2(uv.width.float32, uv.height.float32) / max(uv.pixelScale, 1).float32 proc nextRune(text: string, i: var int): Rune {.inline.} = ## Reads one UTF-8 rune and advances the byte index. @@ -609,6 +619,7 @@ 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) sk.inputs.beginInputFrame(window) sk.tooltipActive = sk.showTooltip sk.showTooltip = false @@ -635,6 +646,12 @@ proc resetInteractions*(sk: Silky) = proc endUi*(sk: Silky) = ## Ends the current UI frame. + let previousCursor = sk.window.cursor + if previousCursor.kind != sk.cursor.kind or + (sk.cursor.kind == CustomCursor and + (previousCursor.image != sk.cursor.image or + previousCursor.hotspot != sk.cursor.hotspot)): + sk.window.cursor = sk.cursor sk.interactor.endInteractions() sk.clear() sk.popLayout() diff --git a/src/silky/testwindow.nim b/src/silky/testwindow.nim index 8ae0b792..980baceb 100644 --- a/src/silky/testwindow.nim +++ b/src/silky/testwindow.nim @@ -3,8 +3,12 @@ import std/unicode, vmath -from windy/common import Button, CursorKind, Cursor -export Button, CursorKind, Cursor, unicode +from windy/common import + Button, CursorKind, Cursor, TextInputState, TextInputEdit, + TextInputEditKind, TextInputEditCallback +export + Button, CursorKind, Cursor, unicode, TextInputState, TextInputEdit, + TextInputEditKind, TextInputEditCallback type Window* = ref object ## Test window that simulates a windy Window. @@ -21,6 +25,9 @@ type Window* = ref object cursor*: Cursor = Cursor(kind: ArrowCursor) runeInputEnabled*: bool onRune*: proc(rune: Rune) + onTextInput*: proc(text: string) + onTextEdit*: TextInputEditCallback + textInput*: TextInputState onButtonPress*: proc(button: Button) onButtonRelease*: proc(button: Button) onFocusChange*: proc() @@ -28,6 +35,10 @@ type Window* = ref object var clipboard: string +proc setTextInputState*(window: Window, state: TextInputState) = + ## Records the editor exposed to native text services. + window.textInput = state + proc newWindow*(width = 800, height = 600): Window = ## Creates a new test window with the given dimensions. Window( @@ -98,9 +109,21 @@ proc typeRune*(w: Window, rune: Rune) = return if rune.int32 < 32 or rune.int32 in 127 .. 159: return - if w.onRune != nil: + if w.onTextInput != nil: + w.onTextInput($rune) + elif w.onRune != nil: w.onRune(rune) +proc typeText*(w: Window, text: string) = + ## Delivers one committed text edit without synthesizing Enter key presses. + if not w.runeInputEnabled or text.len == 0: + return + if w.onTextInput != nil: + w.onTextInput(text) + else: + for rune in text.runes: + w.typeRune(rune) + proc changeFocus*(w: Window) = ## Releases held buttons and delivers a window focus change. for button in Button: diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index e2aca6b8..c520cb3d 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -38,6 +38,7 @@ const LF = Rune(10) CR = Rune(13) Space = Rune(32) + Tab = Rune(9) CursorWidth* = 2.0f DoubleClickTime = 0.4 SelectionColor = rgbx(30, 60, 130, 128) @@ -48,6 +49,50 @@ else: const TextBoxScrollSpeed = -10.0f type + TextSpan* = object + ## Read-only formatting over a half-open range of rune offsets. + first*, last*: int + font*: string + color*: ColorRGBX + background*: ColorRGBX + strikethrough*: bool + linkId*: int + ## Matching positive IDs group the styled parts of one hoverable link. + + TextBlock* = object + ## A styled block over a half-open range of shared rune offsets. + first*, last*: int + font*: string + padding*: Vec2 + spacing*: float32 + patch*: string + patchBorder*: int + label*, labelFont*: string + labelColor*: ColorRGBX + labelSpacing*: float32 + ruleColor*: ColorRGBX + ruleThickness*: float32 + ## Positive thickness turns an empty block into a horizontal rule. + quoteDepth*, quoteContinue*: int + ## Continued quote levels also draw their borders through spacing. + quoteIndent*: float32 = 16 + quoteColor*: ColorRGBX + quoteThickness*: float32 = 2 + + BlockLayout = object + bounds: Rect + ruleBounds: Rect + quoteBounds: Rect + labelPosition: Vec2 + labelFont: string + + TextRun = object + text: string + font: string + position: Vec2 + bounds: Rect + span: int + TextBoxState* = ref object ## State for a multi-line text box widget. runes*: seq[Rune] @@ -73,10 +118,25 @@ type scrollingX*: bool scrollDragOffset*: Vec2 singleLine*: bool + submitOnEnter*: bool + submitted*: bool enabled*: bool = true password*: bool passwordChar*: Rune = Rune('*') allowedChars*: seq[Rune] + spans*: seq[TextSpan] + blocks*: seq[TextBlock] + activatedSpan*: int = -1 + hoveredSpan*: int = -1 + runeSpans: seq[int] + runs: seq[TextRun] + blockLayouts: seq[BlockLayout] + blockHeight: float32 + blockCursor: Rect + lastFont: string + pressedSpan: int = -1 + pressPosition: Vec2 + spanDragged: bool textCache: string textCacheValid: bool displayCache: string @@ -156,8 +216,12 @@ proc sameText*(state: TextBoxState, text: string): bool = inc runeIdx result = i == text.len and runeIdx == state.runes.len -proc setText*(state: TextBoxState, text: string) = - ## Sets the text content and resets cursor to end. +proc setText*( + state: TextBoxState, + text: string, + preserveSelection = false +) = + ## Sets text, optionally retaining the selection while content streams. ## In single-line mode, newlines are converted to spaces. ## Disallowed characters are removed. state.runes = text.toRunes @@ -171,8 +235,12 @@ proc setText*(state: TextBoxState, text: string) = if r in state.allowedChars: filtered.add(r) state.runes = filtered - state.cursor = state.runes.len - state.selector = state.cursor + if preserveSelection: + state.cursor = clamp(state.cursor, 0, state.runes.len) + state.selector = clamp(state.selector, 0, state.runes.len) + else: + state.cursor = state.runes.len + state.selector = state.cursor state.dirty = true state.invalidateTextCaches() @@ -243,6 +311,399 @@ proc computeLayout*(state: TextBoxState, fontData: FontAtlas, maxWidth: float32) inc i state.dirty = false +proc computeLayout*( + state: TextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) + +proc computeBlocks( + state: TextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) = + ## Combines block layouts into one selectable document and native run list. + state.lineHeight = fonts[baseFont].lineHeight + state.lastMaxWidth = maxWidth + state.layout.setLen(state.runes.len) + state.runeSpans.setLen(state.runes.len) + state.runs.setLen(0) + state.blockLayouts.setLen(0) + state.blockHeight = 0 + for index in state.runeSpans.mitems: + index = -1 + var + covered = 0 + previousEnd = rect(0, 0, 0, state.lineHeight) + for item in state.blocks: + let + first = clamp(item.first, covered, state.runes.len) + last = clamp(item.last, first, state.runes.len) + width = max(0.0'f, maxWidth) + depth = max(0, item.quoteDepth) + padding = vec2( + if depth > 0: + min(max(0.0'f, item.padding.x), width / 2) + else: + max(0.0'f, item.padding.x), + max(0.0'f, item.padding.y) + ) + quoteInset = min( + max(0.0'f, width - padding.x * 2), + depth.float32 * max(0.0'f, item.quoteIndent) + ) + blockWidth = width - quoteInset + for i in covered ..< first: + state.layout[i] = previousEnd + if first == last and item.ruleThickness > 0: + let + origin = vec2(quoteInset + padding.x, state.blockHeight + padding.y) + height = item.ruleThickness + padding.y * 2 + state.blockLayouts.add(BlockLayout( + bounds: rect(quoteInset, state.blockHeight, blockWidth, height), + ruleBounds: rect( + origin, + vec2(max(0.0'f, blockWidth - padding.x * 2), item.ruleThickness) + ), + quoteBounds: rect( + padding.x, state.blockHeight, max(0.0'f, width - padding.x * 2), + height + ) + )) + state.blockCursor = rect(origin, vec2(0)) + state.blockHeight += height + max(0.0'f, item.spacing) + previousEnd = state.blockCursor + covered = last + continue + let + font = + if item.font in fonts: + item.font + else: + baseFont + labelFont = + if item.labelFont in fonts: + item.labelFont + else: + baseFont + labelHeight = + if item.label.len > 0: + fonts[labelFont].lineHeight + max(0.0'f, item.labelSpacing) + else: + 0.0'f + origin = vec2( + quoteInset + padding.x, state.blockHeight + padding.y + labelHeight + ) + local = TextBoxState( + runes: state.runes[first ..< last], + wordWrap: state.wordWrap, + spans: @[TextSpan()] + ) + var spanIndices = @[-1] + for index, span in state.spans: + if span.first < last and span.last > first: + var relative = span + relative.first = max(first, span.first) - first + relative.last = min(last, span.last) - first + local.spans.add(relative) + spanIndices.add(index) + local.computeLayout(fonts, font, max(0.0'f, blockWidth - padding.x * 2)) + var contentHeight = local.lineHeight + for i, bounds in local.layout: + state.layout[first + i] = rect(origin + bounds.xy, bounds.wh) + let span = local.runeSpans[i] + if span >= 0: + state.runeSpans[first + i] = spanIndices[span] + for run in local.runs.mitems: + run.position += origin + run.bounds.x += origin.x + run.bounds.y += origin.y + if run.span >= 0: + run.span = spanIndices[run.span] + state.runs.add(run) + state.blockCursor = rect(origin.x, origin.y, 0, local.lineHeight) + if local.layout.len > 0: + let bounds = local.layout[^1] + contentHeight = bounds.y + bounds.h + state.blockCursor = rect( + origin.x + bounds.x + bounds.w, + origin.y + bounds.y, + 0, + bounds.h + ) + if local.runes[^1] == LF: + contentHeight += local.lineHeight + state.blockCursor.x = origin.x + state.blockCursor.y += local.lineHeight + let height = contentHeight + padding.y * 2 + labelHeight + state.blockLayouts.add(BlockLayout( + bounds: rect(quoteInset, state.blockHeight, blockWidth, height), + quoteBounds: rect( + padding.x, state.blockHeight, max(0.0'f, width - padding.x * 2), + height + ), + labelPosition: vec2( + quoteInset + padding.x, state.blockHeight + padding.y + ), + labelFont: labelFont + )) + state.blockHeight += height + max(0.0'f, item.spacing) + previousEnd = state.blockCursor + covered = last + for i in covered ..< state.runes.len: + state.layout[i] = previousEnd + state.dirty = false + +proc computeLayout*( + state: TextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) = + ## Lays out styled text with the same glyph positions used for selection. + state.lastFont = baseFont + if state.blocks.len > 0: + state.computeBlocks(fonts, baseFont, maxWidth) + return + state.blockLayouts.setLen(0) + state.blockHeight = 0 + if state.spans.len == 0: + state.runeSpans.setLen(0) + state.runs.setLen(0) + state.computeLayout(fonts[baseFont], maxWidth) + return + let base = fonts[baseFont] + var + resolvedFonts = @[base] + fontNames = @[baseFont] + baseline = base.ascent + descent = base.descent + lineGap = base.lineGap + state.lineHeight = base.lineHeight + state.lastMaxWidth = maxWidth + state.layout.setLen(0) + state.runs.setLen(0) + state.runeSpans.setLen(state.runes.len) + for index in state.runeSpans.mitems: + index = -1 + for index, span in state.spans: + let name = + if span.font.len > 0 and span.font in fonts: + span.font + else: + baseFont + let font = fonts[name] + resolvedFonts.add(font) + fontNames.add(name) + if span.first < state.runes.len and span.last > max(0, span.first): + state.lineHeight = max(state.lineHeight, font.lineHeight) + baseline = max(baseline, font.ascent) + descent = min(descent, font.descent) + lineGap = max(lineGap, font.lineGap) + for i in max(0, span.first) ..< min(span.last, state.runes.len): + state.runeSpans[i] = index + state.lineHeight = max(state.lineHeight, baseline - descent + lineGap) + var + advances = newSeq[float32](state.runes.len) + kernings = newSeq[float32](state.runes.len) + for i, rune in state.runes: + if rune == LF: + continue + let font = resolvedFonts[state.runeSpans[i] + 1] + var entry: ptr LetterEntry + if rune == Tab: + if font.lookupLetter(Space, 0, entry): + advances[i] = entry.advance * 4 + continue + if font.lookupLetter(rune, 0, entry): + advances[i] = entry.advance + if i + 1 < state.runes.len and state.runes[i + 1] != LF and + font == resolvedFonts[state.runeSpans[i + 1] + 1]: + kernings[i] = font.lookupKerning(rune, state.runes[i + 1]) + var position = vec2(0, 0) + for i, rune in state.runes: + if rune == LF: + state.layout.add(rect(position.x, position.y, 0, state.lineHeight)) + position.x = 0 + position.y += state.lineHeight + continue + if state.wordWrap and maxWidth < float32.high: + let wordStart = i == 0 or state.runes[i - 1] in [Space, Tab, LF] + if wordStart and rune notin [Space, Tab] and position.x > 0: + var + wordWidth = 0.0'f + j = i + while j < state.runes.len and state.runes[j] notin [Space, Tab, LF]: + wordWidth += advances[j] + if j + 1 < state.runes.len and + state.runes[j + 1] notin [Space, Tab, LF]: + wordWidth += kernings[j] + inc j + if position.x + wordWidth > maxWidth: + position.x = 0 + position.y += state.lineHeight + if position.x > 0 and position.x + advances[i] > maxWidth: + position.x = 0 + position.y += state.lineHeight + state.layout.add(rect( + position.x, position.y, advances[i], state.lineHeight + )) + position.x += advances[i] + kernings[i] + var i = 0 + while i < state.runes.len: + if state.runes[i] in [LF, Tab]: + inc i + continue + let + first = i + span = state.runeSpans[i] + font = resolvedFonts[span + 1] + bounds = state.layout[i] + var text = "" + while i < state.runes.len and state.runes[i] notin [LF, Tab] and + state.runeSpans[i] == span and state.layout[i].y == bounds.y: + text.add($state.runes[i]) + inc i + let last = state.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.dirty = false + +proc spanAt(state: TextBoxState, position: Vec2): int = + ## Finds a formatted span only when the pointer touches its glyph bounds. + for i, bounds in state.layout: + if position.overlaps(bounds) and i < state.runeSpans.len: + return state.runeSpans[i] + -1 + +proc drawSpanBackgrounds(sk: Silky, state: TextBoxState, origin: Vec2) = + ## Draws inline backgrounds before the native selection highlight. + for run in state.runs: + 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) + +proc drawBlocks( + sk: Silky, + state: TextBoxState, + origin: Vec2, + defaultColor: ColorRGBX +) = + ## Draws native block surfaces, borders, rules, and captions. + for i, bounds in state.blockLayouts: + let item = state.blocks[i] + if item.patch.len > 0: + sk.draw9Patch( + item.patch, + item.patchBorder, + origin + bounds.bounds.xy, + bounds.bounds.wh + ) + if item.quoteDepth > 0 and item.quoteThickness > 0 and + item.quoteColor.a > 0 and bounds.quoteBounds.w > 0: + let + scale = max(sk.uiScale, 0.001'f) + indent = max(0.0'f, item.quoteIndent) + position = origin + bounds.quoteBounds.xy + limit = floor((position.x + bounds.quoteBounds.w) * scale) / scale + top = round(position.y * scale) / scale + thickness = max(1.0'f, round(item.quoteThickness * scale)) / scale + continuation = clamp(item.quoteContinue, 0, item.quoteDepth) + for level in 0 ..< item.quoteDepth: + let + left = round((position.x + level.float32 * indent) * scale) / + scale + width = min(thickness, limit - left) + if width <= 0: + break + let + spacing = + if level < continuation: + max(0.0'f, item.spacing) + else: + 0.0'f + bottom = round( + (position.y + bounds.quoteBounds.h + spacing) * scale + ) / scale + sk.drawRect( + vec2(left, top), vec2(width, bottom - top), item.quoteColor + ) + if indent == 0: + break + if bounds.ruleBounds.h > 0: + if bounds.ruleBounds.w > 0 and item.ruleColor.a > 0: + let + scale = max(sk.uiScale, 0.001'f) + position = origin + bounds.ruleBounds.xy + left = round(position.x * scale) / scale + right = round((position.x + bounds.ruleBounds.w) * scale) / scale + top = round(position.y * scale) / scale + thickness = max(1.0'f, round(bounds.ruleBounds.h * scale)) / scale + sk.drawRect( + vec2(left, top), vec2(right - left, thickness), item.ruleColor + ) + continue + if item.label.len > 0: + let color = + if item.labelColor.a > 0: + item.labelColor + else: + defaultColor + discard sk.drawText( + bounds.labelFont, + item.label, + origin + bounds.labelPosition, + color, + maxWidth = max(0.0'f, bounds.bounds.w - item.padding.x * 2) + ) + +proc drawSpans( + sk: Silky, + state: TextBoxState, + origin: Vec2, + defaultColor: ColorRGBX +) = + ## Draws cached runs at their measured positions without wrapping again. + for run in state.runs: + let color = + if run.span >= 0 and state.spans[run.span].color.a > 0: + state.spans[run.span].color + else: + defaultColor + discard sk.drawText( + run.font, run.text, origin + run.position, color, clip = false + ) + if run.span >= 0: + let + span = state.spans[run.span] + underline = state.hoveredSpan >= 0 and span.linkId > 0 and + span.linkId == state.spans[state.hoveredSpan].linkId + if span.strikethrough or underline: + let + 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 + baseline = origin.y + run.position.y + font.ascent + thickness = max(1.0'f, round(scale)) / scale + if span.strikethrough: + let top = round((baseline - font.size * 0.3'f) * scale) / scale + sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) + if underline: + let top = round((baseline + 1) * scale) / scale + sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) + proc pickGlyphAt*(state: TextBoxState, pos: Vec2): int = ## Finds the character index closest to the given position. ## Returns -1 if no character found on that line. @@ -254,6 +715,17 @@ proc pickGlyphAt*(state: TextBoxState, pos: Vec2): int = if minDistance < 0 or dist < minDistance: minDistance = dist minGlyph = i + if minGlyph < 0 and state.blocks.len > 0: + var nearestY = float32.high + for i, bounds in state.layout: + let + distanceY = max(bounds.y - pos.y, pos.y - bounds.y - bounds.h) + distanceX = abs(pos.x - bounds.x) + if distanceY < nearestY or + (distanceY == nearestY and distanceX < minDistance): + nearestY = distanceY + minDistance = distanceX + minGlyph = i return minGlyph proc getSelectionRects*(layout: seq[Rect], start, stop: int): seq[Rect] = @@ -273,6 +745,8 @@ proc getSelectionRects*(layout: seq[Rect], start, stop: int): seq[Rect] = proc innerHeight*(state: TextBoxState): float32 = ## Returns the total content height. + if state.blocks.len > 0: + return state.blockHeight if state.layout.len > 0: let lastPos = state.layout[^1] return lastPos.y + lastPos.h @@ -287,6 +761,13 @@ proc innerWidth*(state: TextBoxState): float32 = proc locationRect*(state: TextBoxState, loc: int): Rect = ## Returns the rectangle where the cursor should be drawn. + if state.blocks.len > 0: + if loc >= state.layout.len: + result = state.blockCursor + elif loc >= 0: + result = state.layout[loc] + result.w = CursorWidth + return if state.layout.len > 0: if loc >= state.layout.len: let selectRect = state.layout[^1] @@ -527,12 +1008,39 @@ proc right*(state: TextBoxState, shift = false) = state.scrollToCursor() state.resetBlink() +proc adjacentLine(state: TextBoxState, forward: bool): int = + ## Finds a neighboring visual line when document blocks vary in height. + let currentY = state.cursorPos.y + var + nearest = float32.high + targetY = currentY + for bounds in state.layout: + let distance = + if forward: + bounds.y - currentY + else: + currentY - bounds.y + if distance > 0 and distance < nearest: + nearest = distance + targetY = bounds.y + bounds.h * 0.5'f + if nearest == float32.high: + if forward: + return state.runes.len + return 0 + state.pickGlyphAt(vec2(state.savedX, targetY)) + proc down*(state: TextBoxState, shift = false) = ## Moves the cursor down one line. if state.layout.len > 0: - let curPos = state.cursorPos - let index = state.pickGlyphAt( - vec2(state.savedX, curPos.y + state.lineHeight * 1.5)) + let + curPos = state.cursorPos + index = + if state.blocks.len > 0: + state.adjacentLine(true) + else: + state.pickGlyphAt( + vec2(state.savedX, curPos.y + state.lineHeight * 1.5) + ) if index != -1: state.cursor = index if not shift: @@ -547,9 +1055,15 @@ proc down*(state: TextBoxState, shift = false) = proc up*(state: TextBoxState, shift = false) = ## Moves the cursor up one line. if state.layout.len > 0: - let curPos = state.cursorPos - let index = state.pickGlyphAt( - vec2(state.savedX, curPos.y - state.lineHeight * 0.5)) + let + curPos = state.cursorPos + index = + if state.blocks.len > 0: + state.adjacentLine(false) + else: + state.pickGlyphAt( + vec2(state.savedX, curPos.y - state.lineHeight * 0.5) + ) if index != -1: state.cursor = index if not shift: @@ -769,7 +1283,9 @@ proc handleKey(state: TextBoxState, event: InputEvent) = of KeyPageDown: state.pageDown(shift) of KeyEnter: - if not state.singleLine: + if state.submitOnEnter and not shift: + state.submitted = state.enabled + elif not state.singleLine: state.typeCharacter(LF) of KeyA: if ctrl: @@ -804,7 +1320,8 @@ proc handleKey(state: TextBoxState, event: InputEvent) = proc handleInput( state: TextBoxState, inputs: TextInputs, - fontData: FontAtlas, + fonts: Table[string, FontAtlas], + baseFont: string, maxWidth: float32 ) = ## Drains ordered input and refreshes layout before cursor navigation. @@ -817,18 +1334,32 @@ proc handleInput( case event.kind of TextInput: state.typeCharacter(event.rune) + of TextCommit: + state.pasteText(event.text) + of NativeEdit: + if state.enabled: + let first = clamp(event.edit.start, 0, state.runes.len) + state.selector = first + state.cursor = first + clamp( + event.edit.length, 0, state.runes.len - first + ) + case event.edit.kind + of ReplaceText: + state.pasteText(event.edit.text) + of SelectText: + state.resetBlink() of InputKind.KeyDown: if state.dirty and event.button in { KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, KeyPageUp, KeyPageDown }: - state.computeLayout(fontData, maxWidth) + state.computeLayout(fonts, baseFont, maxWidth) state.handleKey(event) of InputKind.KeyUp: discard if events.len > 0: if state.dirty: - state.computeLayout(fontData, maxWidth) + state.computeLayout(fonts, baseFont, maxWidth) state.scrollToCursor() proc drawScrollbars*(sk: Silky, state: TextBoxState, window: Window, @@ -914,7 +1445,10 @@ proc textBox*( error: bool = false, password: bool = false, passwordChar: Rune = Rune('*'), - allowedChars: seq[Rune] = default(seq[Rune]) + allowedChars: seq[Rune] = default(seq[Rune]), + submitOnEnter: bool = false, + spans: seq[TextSpan] = default(seq[TextSpan]), + blocks: seq[TextBlock] = default(seq[TextBlock]) ) {.measure.} = ## Text box widget with editing, selection, and scroll. ## When disabled, text can be selected and copied but not modified. @@ -931,12 +1465,35 @@ proc textBox*( newState.setText(t) textBoxStates[id] = newState state = textBoxStates[id] + state.submitOnEnter = submitOnEnter + state.submitted = false + state.activatedSpan = -1 + state.hoveredSpan = -1 let inputs = sk.textInputs if state.focused and state.focusEpoch != inputs.focusEpoch: state.focused = false state.dragging = false + if not enabled: + state.selector = state.cursor state.enabled = enabled state.allowedChars = allowedChars + let + activeSpans = + if not enabled and not password: + spans + else: + default(seq[TextSpan]) + activeBlocks = + if not enabled and not password and not singleLine: + blocks + else: + default(seq[TextBlock]) + if state.spans != activeSpans: + state.spans = activeSpans + state.dirty = true + if state.blocks != activeBlocks: + state.blocks = activeBlocks + state.dirty = true if state.password != password: state.password = password state.dirty = true @@ -951,10 +1508,11 @@ proc textBox*( if state.wordWrap != effectiveWrap: state.wordWrap = effectiveWrap state.dirty = true - if not state.focused and not state.sameText(t): - state.setText(t) + if (not state.focused or not enabled) and not state.sameText(t): + state.setText(t, preserveSelection = not enabled) let - fontData = sk.atlas.fonts[sk.textStyle] + firstVertex = sk.vertexMark() + textLayer = sk.currentDrawLayer() padding = sk.theme.padding.float32 outerRect = rect(sk.at, vec2(boxWidth, boxHeight)) innerRect = rect( @@ -963,8 +1521,8 @@ proc textBox*( ) state.boxSize = vec2(innerRect.w, innerRect.h) if state.dirty or state.layout.len == 0 or - state.lastMaxWidth != innerRect.w: - state.computeLayout(fontData, innerRect.w) + state.lastMaxWidth != innerRect.w or state.lastFont != sk.textStyle: + state.computeLayout(sk.atlas.fonts, sk.textStyle, innerRect.w) let shift = window.buttonDown[KeyLeftShift] or window.buttonDown[KeyRightShift] let mouseVec = sk.mousePos @@ -972,6 +1530,7 @@ proc textBox*( mouseVec.overlaps(sk.clipRect) let onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) if window.buttonPressed[MouseLeft]: + state.pressedSpan = -1 if mouseInside and not onScrollbar: state.focused = true let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -985,11 +1544,31 @@ proc textBox*( of 1: state.mouseAction(localMouse, click = true, shift = shift) state.dragging = true + if not enabled and not shift: + state.pressedSpan = state.spanAt(localMouse) + state.pressPosition = mouseVec + state.spanDragged = false of 2: state.selectWord(localMouse) of 3: state.selectParagraph(localMouse) else: state.selectAll() elif not mouseInside: state.focused = false + state.dragging = false + if not enabled: + state.selector = state.cursor + if state.pressedSpan >= 0: + let distance = mouseVec - state.pressPosition + if distance.x * distance.x + distance.y * distance.y > 9: + state.spanDragged = true + if window.buttonReleased[MouseLeft]: + let localMouse = mouseVec - innerRect.xy + state.scrollPos + if mouseInside and not state.spanDragged and + state.cursor == state.selector and + state.spanAt(localMouse) == state.pressedSpan: + state.activatedSpan = state.pressedSpan + state.pressedSpan = -1 + elif not window.buttonDown[MouseLeft]: + state.pressedSpan = -1 if state.dragging and not state.scrollingX and not state.scrollingY: if window.buttonDown[MouseLeft] and not window.buttonPressed[MouseLeft]: let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -999,16 +1578,29 @@ proc textBox*( inputs.submitInput(window, id, state.focused, enabled) if state.focused: state.focusEpoch = inputs.focusEpoch - state.handleInput(inputs, fontData, innerRect.w) + state.handleInput(inputs, sk.atlas.fonts, sk.textStyle, innerRect.w) t = state.getText() if state.dirty: - state.computeLayout(fontData, innerRect.w) + state.computeLayout(sk.atlas.fonts, sk.textStyle, innerRect.w) let maxScrollY = max(0.0f, state.innerHeight - innerRect.h) state.scrollPos.y = clamp(state.scrollPos.y, 0.0f, maxScrollY) if state.wordWrap: state.scrollPos.x = 0 else: state.scrollPos.x = max(0.0f, state.scrollPos.x) + let + overVerticalBar = state.innerHeight > innerRect.h and + mouseVec.x >= outerRect.x + outerRect.w - 10 + overHorizontalBar = not state.wordWrap and + state.innerWidth > innerRect.w and + mouseVec.y >= outerRect.y + outerRect.h - 10 + if mouseInside and mouseVec.overlaps(innerRect) and + not state.scrollingX and not state.scrollingY and + not overVerticalBar and not overHorizontalBar: + let index = state.spanAt(mouseVec - innerRect.xy + state.scrollPos) + if index >= 0 and state.spans[index].linkId > 0: + state.hoveredSpan = index + sk.cursor = Cursor(kind: PointerCursor) let patch = if error: "textbox.error.9patch" elif not enabled: "textbox.disabled.9patch" @@ -1024,6 +1616,10 @@ proc textBox*( sk.draw9Patch(patch, sk.theme.textboxPatch, outerRect.xy, outerRect.wh) sk.pushClipRect(innerRect) let textOrigin = innerRect.xy - state.scrollPos + if state.blocks.len > 0: + sk.drawBlocks(state, textOrigin, textColor) + if state.spans.len > 0: + sk.drawSpanBackgrounds(state, textOrigin) if state.cursor != state.selector: let sel = state.selection let selRects = getSelectionRects(state.layout, sel.a, sel.b) @@ -1031,15 +1627,18 @@ proc textBox*( sk.drawRect( vec2(textOrigin.x + r.x, textOrigin.y + r.y), vec2(r.w, r.h), SelectionColor) - discard sk.drawText( - sk.textStyle, - state.displayText, - textOrigin, - textColor, - maxWidth = innerRect.w, - wordWrap = state.wordWrap, - clip = false - ) + if state.spans.len > 0 or state.blocks.len > 0: + sk.drawSpans(state, textOrigin, textColor) + else: + discard sk.drawText( + sk.textStyle, + state.displayText, + textOrigin, + textColor, + maxWidth = innerRect.w, + wordWrap = state.wordWrap, + clip = false + ) if state.focused and state.cursorVisible: let cr = state.locationRect(state.cursor) sk.drawRect( @@ -1053,6 +1652,31 @@ proc textBox*( window.scrollDelta.y != 0: state.scrollBy( window.scrollDelta.y * TextBoxScrollSpeed, innerRect.h) + if state.focused and enabled and not password: + let selection = state.selection + var + visibleStart = state.runes.len + visibleEnd = 0 + for i, bounds in state.layout: + if bounds.y + bounds.h > state.scrollPos.y and + bounds.y < state.scrollPos.y + innerRect.h and + bounds.x + bounds.w >= state.scrollPos.x and + bounds.x < state.scrollPos.x + innerRect.w: + visibleStart = min(visibleStart, i) + visibleEnd = i + 1 + if visibleEnd == 0: + visibleStart = min(state.cursor, state.runes.len) + visibleEnd = visibleStart + inputs.publishTextInput(TextInputState( + id: id, + text: t, + selectionStart: selection.a, + selectionEnd: selection.b, + visibleStart: visibleStart, + visibleEnd: visibleEnd, + bounds: rect(innerRect.xy * sk.uiScale, innerRect.wh * sk.uiScale), + multiline: not singleLine + ), textLayer, firstVertex) sk.advance(vec2(boxWidth, boxHeight)) template textBox*( @@ -1065,11 +1689,17 @@ template textBox*( isError = false, isPassword = false, passChar: Rune = Rune('*'), - chars: seq[Rune] = default(seq[Rune]) + chars: seq[Rune] = default(seq[Rune]), + submitOnEnter = false, + spans: seq[TextSpan] = default(seq[TextSpan]), + blocks: seq[TextBlock] = default(seq[TextBlock]) ) = ## Text box widget. Set singleLine for a single-line input. + ## submitOnEnter reports Enter in state.submitted and preserves Shift+Enter. + ## Read-only spans preserve selection and report clicks in activatedSpan. sk.textBox(window, id, t, boxWidth, boxHeight, wrapWords, singleLine, - isEnabled, isError, isPassword, passChar, chars + isEnabled, isError, isPassword, passChar, chars, submitOnEnter, spans, + blocks ) template textInput*( diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index 53423eec..d1a4f92c 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -449,26 +449,40 @@ template frame*(id: string, framePos, frameSize: Vec2, body: untyped) = sk.frameEnd(window, frameCtx.state, frameCtx.originPos) sk.endWidget() -template button*(label: string, isEnabled: bool, isError: bool, body: untyped) = - ## Create a button with enabled and error states. +template sizedButton( + label: string, + minimumSize: Vec2, + isEnabled: bool, + isError: bool, + body: untyped +) = + ## Creates a native button with a minimum size and a left-aligned label. let - textSize = sk.getTextSize(sk.textStyle, label) - buttonSize = textSize + vec2(sk.theme.padding) * 2 + buttonLabel = label + minimum = minimumSize + enabled = isEnabled + error = isError + padding = vec2(sk.theme.padding) + textSize = sk.getTextSize(sk.textStyle, buttonLabel) + intrinsicSize = textSize + padding * 2 + buttonSize = vec2( + max(intrinsicSize.x, minimum.x), max(intrinsicSize.y, minimum.y) + ) buttonOrigin = sk.placedAt(buttonSize) buttonRect = rect(buttonOrigin, buttonSize) when defined(silkyTesting): - sk.beginWidget("Button", text = label, rect = buttonRect) + sk.beginWidget("Button", text = buttonLabel, rect = buttonRect) let textColor = - if not isEnabled: + if not enabled: sk.theme.disabledTextColor - elif isError: + elif error: sk.theme.errorTextColor else: sk.theme.defaultTextColor - interaction = sk.interact(buttonRect, isEnabled, isError) + interaction = sk.interact(buttonRect, enabled, error) let patch = case interaction of Error: @@ -491,21 +505,48 @@ template button*(label: string, isEnabled: bool, isError: bool, body: untyped) = let pressed = interaction == Pressed or interaction == Held hovered = pressed or interaction == Hovered - sk.setWidgetState(enabled = isEnabled, pressed = pressed, hovered = hovered) + sk.setWidgetState(enabled = enabled, pressed = pressed, hovered = hovered) - let at = buttonOrigin + vec2(sk.theme.padding) - discard sk.drawText(sk.textStyle, label, at, textColor) + let at = buttonOrigin + vec2(padding.x, (buttonSize.y - textSize.y) / 2) + discard sk.drawText(sk.textStyle, buttonLabel, at, textColor) when defined(silkyTesting): sk.endWidget() - sk.advance(buttonSize + vec2(sk.theme.padding)) + sk.advance(buttonSize + padding) + +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + isError: bool, + body: untyped +) = + ## Creates a minimum-size button with enabled and error states. + sizedButton(label, minimumSize, isEnabled, isError, body) + +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + body: untyped +) = + ## Creates a native button with a minimum size and an enabled state. + sizedButton(label, minimumSize, isEnabled, false, body) + +template button*(label: string, minimumSize: Vec2, body: untyped) = + ## Creates a native button with a minimum size. + sizedButton(label, minimumSize, true, false, body) + +template button*(label: string, isEnabled: bool, isError: bool, body: untyped) = + ## Creates an intrinsic-size button with enabled and error states. + sizedButton(label, vec2(0), isEnabled, isError, body) template button*(label: string, body: untyped) = ## Create a button. - button(label, true, false, body) + sizedButton(label, vec2(0), true, false, body) template button*(label: string, isEnabled: bool, body: untyped) = ## Create a button. - button(label, isEnabled, false, body) + sizedButton(label, vec2(0), isEnabled, false, body) template icon*(image: string) = ## Draw an icon. diff --git a/tests/test_button_vertices.nim b/tests/test_button_vertices.nim new file mode 100644 index 00000000..fcce423e --- /dev/null +++ b/tests/test_button_vertices.nim @@ -0,0 +1,85 @@ +import + std/[importutils, tables], + bumpy, pixie, vmath, windy, + silky, silky/internal/inputs + +const FontPath = "tests/data/IBMPlexSans-Regular.ttf" + +proc close(a, b: float32): bool = + ## Compares font and button positions with float tolerance. + abs(a - b) < 0.001 + +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, + uiScale: density, + inFrame: true, + inputs: TextInputs(), + window: Window() + ) + new(result.drawer) + result.mousePos = vec2(-1) + result.pushLayout(vec2(0), vec2(400)) + result.pushClipRect(rect(0, 0, 400, 400)) + +proc glyphPosition(sk: Silky): Vec2 = + ## Finds the W glyph quad by its atlas entry. + let + glyph = sk.atlas.fonts["Default"].entries["W"][0] + uv = vec2(glyph.x.float32, glyph.y.float32) + for vertex in sk.drawer.layers[NormalLayer]: + if vertex.uv == uv: + return vertex.pos + doAssert false, "The button label must use the native glyph atlas." + +block: + echo "Testing minimum-size button text stays left and vertically centered" + for density in [1.0'f, 1.25'f, 1.5'f, 2.0'f]: + let builder = newAtlasBuilder(256, 2) + builder.addFont( + FontPath, "Default", 18, @["W"], pixelScale = density + ) + doAssert builder.addImage("button.9patch", newImage(24, 24)) + let + sk = fixture(builder, density) + reference = fixture(builder, density) + origin = vec2(20.17'f, 30.29'f) + textSize = sk.getTextSize("Default", "W") + padding = sk.theme.padding.float32 + spacing = sk.theme.spacing.float32 + expected = origin + vec2(padding, (64 - textSize.y) / 2) + sk.at = origin + button("W", vec2(180, 64)): + doAssert false, "A button outside the pointer must not activate." + discard reference.drawText( + "Default", "W", expected, sk.theme.defaultTextColor + ) + let + actualGlyph = sk.glyphPosition() + expectedGlyph = reference.glyphPosition() + doAssert close(actualGlyph.x, expectedGlyph.x) + doAssert close(actualGlyph.y, expectedGlyph.y) + doAssert actualGlyph.x < origin.x + 30, + "The label must not center horizontally across the wide button." + doAssert actualGlyph.y > origin.y + padding, + "The taller button must center the label vertically." + doAssert close(sk.at.y, origin.y + 64 + padding + spacing), + "Native layout must advance by the actual button height." + + sk.drawer.layers[NormalLayer].setLen(0) + reference.drawer.layers[NormalLayer].setLen(0) + sk.at = origin + button("W"): + discard + discard reference.drawText( + "Default", "W", origin + vec2(padding), sk.theme.defaultTextColor + ) + let legacy = sk.glyphPosition() + doAssert close(legacy.x, reference.glyphPosition().x) + doAssert close(legacy.y, reference.glyphPosition().y) + doAssert close(sk.at.y, origin.y + textSize.y + padding * 3 + spacing) + +echo "All native button vertex tests passed." diff --git a/tests/test_buttons.nim b/tests/test_buttons.nim new file mode 100644 index 00000000..20a98601 --- /dev/null +++ b/tests/test_buttons.nim @@ -0,0 +1,128 @@ +import + bumpy, vmath, + silky + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +var + clicks: int + enabled = true + clipped = false + evaluations: array[4, int] + +proc drawButtons(sk: Silky, window: Window) = + ## Draws a full-width model row and a legacy intrinsic button. + sk.pushLayout(vec2(40, 30), vec2(260, 220)) + if clipped: + sk.pushClipRect(rect(40, 30, 120, 80)) + button("Model", vec2(240, 64), enabled): + inc clicks + if clipped: + sk.popClipRect() + button("Legacy"): + discard + sk.popLayout() + +proc click(harness: var TestHarness, position: Vec2) = + ## Clicks a UI coordinate after warming the native hover state. + let pixels = (position * harness.sk.uiScale).ivec2 + harness.window.moveMouse(pixels.x, pixels.y) + discard harness.pumpFrame(drawButtons, 2) + harness.window.pressButton(MouseLeft) + discard harness.pumpFrame(drawButtons) + harness.window.releaseButton(MouseLeft) + discard harness.pumpFrame(drawButtons) + +proc countedLabel(): string = + ## Counts how many times a template evaluates its label expression. + inc evaluations[0] + "Counted" + +proc countedSize(): Vec2 = + ## Counts how many times a template evaluates its minimum size. + inc evaluations[1] + vec2(180, 64) + +proc countedEnabled(): bool = + ## Counts how many times a template evaluates its enabled expression. + inc evaluations[2] + true + +proc countedError(): bool = + ## Counts how many times a template evaluates its error expression. + inc evaluations[3] + false + +proc drawCounted(sk: Silky, window: Window) = + ## Exercises the full overload inside an actual deferred DSL group. + ui: + group "menu": + box 40, 30, 260, 300 + button( + countedLabel(), countedSize(), countedEnabled(), countedError() + ): + discard + button("Minimum", vec2(180, 32)): + discard + button("Enabled", true): + discard + button("Error", true, false): + discard + button("Too small", vec2(1)): + discard + +block: + echo "Testing minimum button size preserves native hit testing" + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + for scale in [1.0'f, 1.25'f, 1.5'f, 2.0'f]: + var harness = newTestHarness(builder.atlas, 1200, 1000) + harness.sk.uiScale = scale + clicks = 0 + enabled = true + clipped = false + discard harness.pumpFrame(drawButtons) + let + model = harness.findByText("Model", "Button") + legacy = harness.findByText("Legacy", "Button") + intrinsic = harness.sk.getTextSize("Default", "Legacy") + + vec2(harness.sk.theme.padding.float32 * 2) + rightEdge = model.rect.xy + vec2(model.rect.w - 2, model.rect.h / 2) + doAssert model.rect.wh == vec2(240, 64) + doAssert legacy.rect.wh == intrinsic + let pixels = (rightEdge * scale).ivec2 + harness.window.moveMouse(pixels.x, pixels.y) + discard harness.pumpFrame(drawButtons, 2) + doAssert harness.findByText("Model", "Button").state.hovered + harness.click(rightEdge) + doAssert clicks == 1 + + enabled = false + discard harness.pumpFrame(drawButtons) + doAssert not harness.findByText("Model", "Button").state.enabled + harness.click(rightEdge) + doAssert clicks == 1 + doAssert not harness.findByText("Model", "Button").state.hovered + + enabled = true + clipped = true + harness.click(rightEdge) + doAssert clicks == 1 + doAssert not harness.findByText("Model", "Button").state.hovered + harness.click(model.rect.xy + vec2(16, model.rect.h / 2)) + doAssert clicks == 2 + + echo "Testing sized button arguments are evaluated once per frame" + var harness = newTestHarness(builder.atlas) + evaluations = [0, 0, 0, 0] + for frame in 1 .. 3: + discard harness.pumpFrame(drawCounted) + doAssert evaluations == [frame, frame, frame, frame] + doAssert harness.findByText("Counted", "Button").rect.wh == vec2(180, 64) + doAssert harness.findByText("Minimum", "Button").rect.w == 180 + doAssert harness.findByText("Too small", "Button").rect.wh == + harness.sk.getTextSize("Default", "Too small") + + vec2(harness.sk.theme.padding.float32 * 2) + +echo "All native button interaction tests passed." diff --git a/tests/test_decorations.nim b/tests/test_decorations.nim new file mode 100644 index 00000000..8da10aeb --- /dev/null +++ b/tests/test_decorations.nim @@ -0,0 +1,118 @@ +import + std/[importutils, math, tables, unicode], + bumpy, pixie, vmath, windy, + silky, silky/internal/inputs + +const + FontPath = "tests/data/IBMPlexSans-Regular.ttf" + TextColor = rgbx(90, 150, 220, 255) + +proc close(a, b: float32): bool = + ## Compares physical and logical coordinates with float tolerance. + abs(a - b) < 0.001 + +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() + ) + new(result.drawer) + result.theme.padding = 0 + result.pushLayout(vec2(0), vec2(300, 300)) + result.pushClipRect(rect(0, 0, 300, 300)) + +proc rules(sk: Silky): seq[Rect] = + ## Extracts solid decoration quads and checks their color and clipping. + let vertices = sk.drawer.layers[NormalLayer] + for i in countup(0, vertices.high, 6): + if vertices[i].uv != vertices[i + 2].uv: + continue + doAssert vertices[i].color == TextColor + doAssert vertices[i].clipPos == vec2(10.17'f, 20.29'f) + doAssert vertices[i].clipSize == vec2(64, 220) + for j in i ..< i + 6: + let pixel = vertices[j].pos * sk.uiScale + doAssert close(pixel.x, round(pixel.x)) + doAssert close(pixel.y, round(pixel.y)) + result.add(rect( + vertices[i].pos, + vertices[i + 2].pos - vertices[i].pos + )) + +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) + origin = vec2(10.17'f, 20.29'f) + builder.addFont( + FontPath, + "Default", + 18, + @[" ", "W"], + pixelScale = density + ) + doAssert builder.addImage("textbox.disabled.9patch", newImage(16, 16)) + let sk = fixture(builder, density) + var + text = "WW WW WW" + spans = @[ + TextSpan( + first: 0, + last: text.runeLen, + strikethrough: true, + color: TextColor, + linkId: 1 + ) + ] + sk.at = origin + sk.mousePos = vec2(-1) + sk.textBox( + window, "decorations", text, 64, 220, + wrapWords = true, enabled = false, spans = spans + ) + let + state = textBoxStates["decorations"] + strikeRules = sk.rules() + doAssert strikeRules.len == 3 + for i, rule in strikeRules: + let line = origin.y + state.layout[i * 3].y + doAssert rule.y > line + doAssert rule.y + rule.h < line + state.lineHeight + doAssert rule.w <= 64 + doAssert close(rule.h * density, max(1.0'f, round(density))) + state.selectAll() + doAssert state.copyText() == text + state.selector = state.cursor + + sk.drawer.layers[NormalLayer].setLen(0) + sk.at = origin + sk.mousePos = origin + state.layout[0].xy + state.layout[0].wh / 2 + sk.textBox( + window, "decorations", text, 64, 220, + wrapWords = true, enabled = false, spans = spans + ) + let hoveredRules = sk.rules() + doAssert hoveredRules.len == strikeRules.len * 2 + for i, rule in strikeRules: + doAssert hoveredRules[i * 2] == rule + doAssert hoveredRules[i * 2 + 1].y > rule.y + + sk.drawer.layers[NormalLayer].setLen(0) + sk.at = origin + sk.mousePos = vec2(-1) + spans[0].strikethrough = false + sk.textBox( + window, "decorations", text, 64, 220, + wrapWords = true, enabled = false, spans = spans + ) + doAssert sk.rules().len == 0 + textBoxStates.del("decorations") + +echo "All text decoration tests passed." diff --git a/tests/test_density.nim b/tests/test_density.nim new file mode 100644 index 00000000..cff3d658 --- /dev/null +++ b/tests/test_density.nim @@ -0,0 +1,315 @@ +import + std/[importutils, math, os, tables], + bumpy, pixie, vmath, + silky + +const + FontPath = "tests/data/IBMPlexSans-Regular.ttf" + Glyphs = @[" ", "A", "V", "W", "g", "j", "@"] + +proc close(a, b: float32): bool = + ## Compares font metrics with a small floating point tolerance. + abs(a - b) < 0.001 + +proc overlaps(a, b: Entry): bool = + ## Returns whether two physical 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 newTextFixture(builder: AtlasBuilder, density: float32): Silky = + ## Queues native glyph vertices without creating a window or GPU. + privateAccess(Silky) + result = Silky( + atlas: builder.atlas, + image: builder.atlasImage, + uiScale: density, + inFrame: true + ) + new(result.drawer) + result.pushLayout(vec2(0, 0), vec2(300, 200)) + result.pushClipRect(rect(0, 0, 300, 200)) + +proc entryAt(font: FontAtlas, uv: Vec2): LetterEntry = + ## Finds the exact atlas variant emitted by the native renderer. + for variants in font.entries.values: + for entry in variants: + if uv == vec2(entry.x.float32, entry.y.float32): + return entry + doAssert false, "No glyph at texture coordinate " & $uv + +proc assertPixelQuads(sk: Silky) = + ## Requires each glyph texel to cover exactly one framebuffer pixel. + let vertices = sk.drawer.layers[NormalLayer] + doAssert vertices.len > 0 + doAssert vertices.len mod 6 == 0 + for vertex in vertices: + let pixel = vertex.pos * sk.uiScale + doAssert close(pixel.x, round(pixel.x)), $pixel + doAssert close(pixel.y, round(pixel.y)), $pixel + doAssert close(vertex.uv.x, round(vertex.uv.x)) + doAssert close(vertex.uv.y, round(vertex.uv.y)) + for i in countup(0, vertices.high, 6): + let + physical = (vertices[i + 2].pos - vertices[i].pos) * sk.uiScale + texture = vertices[i + 2].uv - vertices[i].uv + doAssert close(physical.x, texture.x), $physical & " != " & $texture + doAssert close(physical.y, texture.y), $physical & " != " & $texture + +block: + echo "Testing exact-scale font rasterization and native text vertices" + let regular = newAtlasBuilder(256, 2) + regular.addFont(FontPath, "Default", 17, Glyphs) + let reference = regular.atlas.fonts["Default"] + for density in [0.75'f, 1.0'f, 1.25'f, 1.5'f, 2.0'f]: + for steps in [0, 10]: + let builder = newAtlasBuilder(512, 2) + builder.addFont( + FontPath, + "Default", + 17, + Glyphs, + subpixelSteps = steps, + pixelScale = density + ) + let + font = builder.atlas.fonts["Default"] + sk = newTextFixture(builder, density) + origin = vec2(10.17, 20.29) + height = 100.0'f + doAssert font.pixelScale == density + doAssert close(font.size, reference.size) + doAssert close(font.ascent, reference.ascent) + doAssert close(font.descent, reference.descent) + doAssert close(font.lineHeight, reference.lineHeight) + for glyph in Glyphs: + let + entry = font.entries[glyph][0] + expected = reference.entries[glyph][0] + doAssert close(entry.advance, expected.advance), glyph + for next, adjustment in expected.kerning: + doAssert close(entry.kerning[next], adjustment), glyph & next + for horizontal in [LeftAlign, CenterAlign, RightAlign]: + for vertical in [TopAlign, MiddleAlign, BottomAlign]: + sk.drawer.layers[NormalLayer].setLen(0) + discard sk.drawText( + "Default", + "AVWgj@\n@jgWVA", + origin, + rgbx(255, 255, 255, 255), + maxWidth = 240, + maxHeight = height, + hAlign = horizontal, + vAlign = vertical + ) + sk.assertPixelQuads() + let + vertices = sk.drawer.layers[NormalLayer] + extra = height - font.lineHeight * 2 + alignment = + case vertical + of TopAlign: + 0.0'f + of MiddleAlign: + floor(extra * 0.5 * density) + of BottomAlign: + floor(extra * density) + doAssert vertices.len == 12 * 6 + for i in 0 ..< 12: + let + vertex = vertices[i * 6] + entry = font.entryAt(vertex.uv) + baseline = (vertex.pos.y - entry.boundsY) * density + expected = round( + (origin.y + font.ascent + (i div 6).float32 * + font.lineHeight) * density + ) + alignment + doAssert close(baseline, expected), + "Glyphs must share the line baseline: " & $baseline & + " != " & $expected + + echo "Testing deferred text placement at scale ", density + sk.drawer.layers[NormalLayer].setLen(0) + let span = sk.beginVertexSpan() + discard sk.drawText( + "Default", "AVWgj@", origin, rgbx(255, 255, 255, 255) + ) + sk.endVertexSpan(span, vec2(3.17, 4.29)) + sk.assertPixelQuads() + sk.translateVertices(NormalLayer, 0, vec2(1.39, -2.13)) + sk.assertPixelQuads() + var baseline = 0.0'f + for i in 0 ..< 6: + let + vertex = sk.drawer.layers[NormalLayer][i * 6] + entry = font.entryAt(vertex.uv) + current = (vertex.pos.y - entry.boundsY) * density + if i == 0: + baseline = current + doAssert close(current, baseline) + sk.popClipRect() + sk.popLayout() + + if steps == 0: + let path = "tests/dist/fractional_density.png" + builder.write(path) + let loaded = readAtlas(path).atlas.fonts["Default"] + doAssert loaded.pixelScale == density + doAssert loaded.entries == font.entries + +block: + echo "Testing dense fonts preserve logical layout metrics" + let + regular = newAtlasBuilder(256, 2) + dense = newAtlasBuilder(256, 2) + regular.addFont(FontPath, "Default", 17, Glyphs) + dense.addFont(FontPath, "Default", 17, Glyphs, pixelScale = 2) + let + regularFont = regular.atlas.fonts["Default"] + denseFont = dense.atlas.fonts["Default"] + doAssert regularFont.pixelScale == 1 + doAssert denseFont.pixelScale == 2 + doAssert close(regularFont.size, denseFont.size) + doAssert close(regularFont.ascent, denseFont.ascent) + doAssert close(regularFont.descent, denseFont.descent) + doAssert close(regularFont.lineHeight, denseFont.lineHeight) + doAssert close(regularFont.lineGap, denseFont.lineGap) + for glyph in Glyphs: + let + regularEntry = regularFont.entries[glyph][0] + denseEntry = denseFont.entries[glyph][0] + doAssert close(regularEntry.advance, denseEntry.advance), glyph + doAssert abs(regularEntry.boundsX - denseEntry.boundsX) <= 0.5 + doAssert abs(regularEntry.boundsY - denseEntry.boundsY) <= 0.5 + doAssert abs(regularEntry.boundsWidth - denseEntry.boundsWidth) <= 1 + doAssert abs(regularEntry.boundsHeight - denseEntry.boundsHeight) <= 1 + doAssert close( + denseEntry.boundsWidth * 2, + round(denseEntry.boundsWidth * 2) + ) + doAssert close( + denseEntry.boundsHeight * 2, + round(denseEntry.boundsHeight * 2) + ) + for next, adjustment in regularEntry.kerning: + doAssert close(adjustment, denseEntry.kerning[next]) + doAssert denseFont.entries["A"][0].boundsHeight * 2 > + regularFont.entries["A"][0].boundsHeight + + echo "Testing density survives embedded PNG metadata" + let path = "tests/dist/density.png" + doAssert dense.addImage("icon", newImage(48, 24), pixelScale = 2) + dense.write(path) + let loaded = readAtlas(path) + doAssert loaded.atlas.entries["icon"].pixelScale == 2 + doAssert loaded.atlas.entries["icon"].width == 48 + doAssert loaded.atlas.entries["icon"].height == 24 + doAssert loaded.atlas.fonts["Default"].pixelScale == 2 + doAssert close( + loaded.atlas.fonts["Default"].lineHeight, + regularFont.lineHeight + ) + doAssert loaded.atlas.fonts["Default"].entries["A"][0] == + denseFont.entries["A"][0] + +block: + echo "Testing directory images retain their density" + let + directory = "tests/dist/density_images/" + builder = newAtlasBuilder(128, 2) + createDir(directory) + newImage(40, 24).writeFile(directory & "icon.png") + builder.addDir(directory, directory, pixelScale = 2) + let entry = builder.atlas.entries["icon"] + doAssert entry.pixelScale == 2 + doAssert entry.width == 40 and entry.height == 24 + +block: + echo "Testing live packing reserves full dense glyph rectangles" + let builder = newAtlasBuilder(128, 1) + builder.addFont(FontPath, "Default", 24, Glyphs, pixelScale = 2) + let + live = newAtlasBuilderFromAtlas(builder.atlas, builder.atlasImage) + tile = newImage(5, 5) + var added = 0 + for i in 0 ..< 1024: + let name = "tile" & $i + if not live.addImage(name, tile): + break + inc added + let entry = live.atlas.entries[name] + for font in live.atlas.fonts.values: + for variants in font.entries.values: + for glyph in variants: + let bounds = Entry( + x: glyph.x, + y: glyph.y, + width: round(glyph.boundsWidth * font.pixelScale.float32).int, + height: round(glyph.boundsHeight * font.pixelScale.float32).int + ) + if bounds.width > 0 and bounds.height > 0: + doAssert not overlaps(entry, bounds), name & " overlaps a glyph" + doAssert added > 0 + doAssert added < 1024 + +block: + echo "Testing native image and patch coordinates at two densities" + for density in 1 .. 2: + let + builder = newAtlasBuilder(128, 2) + sk = Silky(atlas: builder.atlas, image: builder.atlasImage) + position = vec2(12, 20) + doAssert builder.addImage( + "patch", + newImage(32 * density, 32 * density), + pixelScale = density + ) + new(sk.drawer) + sk.uiScale = density.float32 + sk.pushLayout(vec2(0, 0), vec2(300, 200)) + sk.pushClipRect(rect(0, 0, 300, 200)) + let + entry = builder.atlas.entries["patch"] + uv = vec2(entry.x.float32, entry.y.float32) + doAssert sk.getImageSize("patch") == vec2(32, 32) + sk.drawImage("patch", position) + doAssert sk.drawer.layers[NormalLayer].len == 6 + doAssert sk.drawer.layers[NormalLayer][0].pos == position + doAssert sk.drawer.layers[NormalLayer][2].pos == position + vec2(32) + doAssert sk.drawer.layers[NormalLayer][0].uv == uv + doAssert sk.drawer.layers[NormalLayer][2].uv == + uv + vec2((32 * density).float32) + + sk.drawer.layers[NormalLayer].setLen(0) + sk.draw9Patch("patch", 4, position, vec2(100, 60)) + doAssert sk.drawer.layers[NormalLayer].len == 54 + for i in countup(0, 48, 6): + let + first = sk.drawer.layers[NormalLayer][i] + last = sk.drawer.layers[NormalLayer][i + 2] + destination = last.pos - first.pos + source = last.uv - first.uv + doAssert first.pos.x >= position.x + doAssert first.pos.y >= position.y + doAssert last.pos.x <= position.x + 100 + doAssert last.pos.y <= position.y + 60 + if i < 24: + doAssert destination == vec2(4) + doAssert source == vec2((4 * density).float32) + if density == 2: + for displayScale in [1.0'f, 1.5'f, 2.0'f]: + sk.uiScale = displayScale + sk.drawer.layers[NormalLayer].setLen(0) + sk.drawImage("patch", vec2(12.2, 20.3)) + let origin = sk.drawer.layers[NormalLayer][0].pos * displayScale + doAssert close(origin.x, round(origin.x)) + doAssert close(origin.y, round(origin.y)) + sk.drawer.layers[NormalLayer].setLen(0) + sk.draw9Patch("patch", 4, vec2(12.2, 20.3), vec2(100.3, 60.2)) + for vertex in sk.drawer.layers[NormalLayer]: + let pixel = vertex.pos * displayScale + doAssert close(pixel.x, round(pixel.x)) + doAssert close(pixel.y, round(pixel.y)) + sk.popClipRect() + sk.popLayout() + +echo "All density tests passed." diff --git a/tests/test_inputs.nim b/tests/test_inputs.nim index 2ad63d49..e0571fd2 100644 --- a/tests/test_inputs.nim +++ b/tests/test_inputs.nim @@ -1,6 +1,6 @@ import std/unicode, - vmath, + bumpy, vmath, silky, silky/internal/inputs when not defined(silkyTesting): @@ -11,9 +11,14 @@ type Fixture = object id: string text: string singleLine: bool + submitOnEnter: bool enabled: bool password: bool allowedChars: seq[Rune] + spans: seq[TextSpan] + blocks: seq[TextBlock] + height: float32 + clip: Rect var atlas: SilkyAtlas @@ -23,6 +28,8 @@ block: let builder = newAtlasBuilder(1024, 4) builder.addDir("tests/data/", "tests/data/") builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18.0) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Wide", 30.0) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Small", 12.0) atlas = builder.atlas proc fixture( @@ -30,7 +37,9 @@ proc fixture( onPress: proc(button: Button) = nil, onRelease: proc(button: Button) = nil, onRune: proc(rune: Rune) = nil, - onFocus: proc() = nil + onFocus: proc() = nil, + onTextInput: proc(text: string) = nil, + onTextEdit: TextInputEditCallback = nil ): Fixture = ## Creates a real Silky test context with optional application callbacks. inc nextId @@ -38,12 +47,15 @@ proc fixture( result.text = text result.singleLine = true result.enabled = true + result.height = 120 result.harness.window = newWindow() let window = result.harness.window window.onButtonPress = onPress window.onButtonRelease = onRelease window.onRune = onRune window.onFocusChange = onFocus + window.onTextInput = onTextInput + window.onTextEdit = onTextEdit result.harness.sk = newSilky(window, atlas) proc frame(f: var Fixture, visible = true, duplicate = false) = @@ -53,6 +65,8 @@ proc frame(f: var Fixture, visible = true, duplicate = false) = let sk = f.harness.sk window = f.harness.window + if f.clip.w > 0: + sk.pushClipRect(f.clip) for i in 0 .. ord(duplicate): sk.at = vec2(20, 20) sk.textBox( @@ -60,13 +74,18 @@ proc frame(f: var Fixture, visible = true, duplicate = false) = f.id, f.text, 240, - 120, + f.height, wrapWords = true, singleLine = f.singleLine, enabled = f.enabled, password = f.password, - allowedChars = f.allowedChars + allowedChars = f.allowedChars, + submitOnEnter = f.submitOnEnter, + spans = f.spans, + blocks = f.blocks ) + if f.clip.w > 0: + sk.popClipRect() f.harness.endFrame() f.harness.window.resetInputState() @@ -74,6 +93,16 @@ proc state(f: Fixture): TextBoxState = ## Returns the text state belonging to a fixture. textBoxStates[f.id] +proc hoverGlyph(f: var Fixture, index: int) = + ## Moves the pointer over a visible laid-out glyph in the current view. + let + bounds = f.state.layout[index] + padding = f.harness.sk.theme.padding.float32 + point = vec2(20 + padding) + bounds.xy + bounds.wh / 2 - + f.state.scrollPos + f.harness.window.moveMouse(point.x.int, point.y.int) + f.frame() + proc focus(f: var Fixture) = ## Clicks the field and positions the caret at the end of its text. f.frame() @@ -319,6 +348,297 @@ block: f.frame() doAssert f.text == "123" +block: + echo "Testing Enter submission and captured Shift modifiers" + var f = fixture("First") + f.singleLine = false + f.submitOnEnter = true + f.focus() + let window = f.harness.window + window.tap(KeyEnter) + f.frame() + doAssert f.state.submitted and f.text == "First" + f.frame() + doAssert not f.state.submitted + window.pressButton(KeyLeftShift) + window.tap(KeyEnter) + window.releaseButton(KeyLeftShift) + f.frame() + doAssert not f.state.submitted and f.text == "First\n" + setClipboardString("Second\nThird") + window.shortcut(KeyV) + window.tap(KeyEnter) + f.frame() + doAssert f.state.submitted and f.text == "First\nSecond\nThird" + f.enabled = false + window.tap(KeyEnter) + f.frame() + doAssert not f.state.submitted + +block: + echo "Testing clipboard restoration before the paste frame" + for modifier in [KeyLeftSuper, KeyLeftControl]: + var f = fixture("Original") + f.singleLine = false + f.submitOnEnter = true + f.focus() + let + window = f.harness.window + dictated = "First\tline\n\n第二段 👩‍💻" + window.shortcut(KeyA, modifier) + setClipboardString(dictated) + window.shortcut(KeyV, modifier) + setClipboardString("Restored clipboard") + doAssert f.text == "Original" + f.frame(duplicate = true) + doAssert f.text == dictated and not f.state.submitted + doAssert getClipboardString() == "Restored clipboard" + f.frame() + doAssert f.text == dictated + window.shortcut(KeyZ, modifier) + f.frame() + doAssert f.text == "Original" + window.shortcut(KeyY, modifier) + f.frame() + doAssert f.text == dictated + +block: + echo "Testing native text commits replace a Unicode selection atomically" + var f = fixture("Aé🙂Z") + f.singleLine = false + f.submitOnEnter = true + f.focus() + let + window = f.harness.window + committed = "First\tline\nSecond 👩‍💻" + expected = "A" & committed & "Z" + f.state.cursor = 1 + f.state.selector = 3 + window.onTextInput(committed) + doAssert f.text == "Aé🙂Z" + f.frame(duplicate = true) + doAssert f.text == expected and not f.state.submitted + doAssert f.state.cursor == 1 + committed.runeLen + doAssert f.state.selector == f.state.cursor + window.shortcut(KeyZ) + f.frame() + doAssert f.text == "Aé🙂Z" + window.shortcut(KeyY) + f.frame() + doAssert f.text == expected + +block: + echo "Testing disabled fields reject native commits and captured paste" + var f = fixture("Read only") + f.enabled = false + f.focus() + let window = f.harness.window + window.shortcut(KeyA) + window.onTextInput("Ignored\n👩‍💻") + setClipboardString("Ignored paste") + window.shortcut(KeyV) + f.frame() + doAssert f.text == "Read only" and not f.state.submitted + doAssert f.state.selection == (0 .. 9) + window.shortcut(KeyC) + f.frame() + doAssert getClipboardString() == "Read only" + +block: + echo "Testing native editor publication uses rune ranges and pixel bounds" + var f = fixture("Aé🙂Z\nNext") + f.singleLine = false + f.focus() + let + window = f.harness.window + padding = f.harness.sk.theme.padding.float32 + scale = 1.5'f + f.state.cursor = 3 + f.state.selector = 1 + f.harness.sk.uiScale = scale + f.frame() + doAssert window.textInput.id == f.id + doAssert window.textInput.text == f.text + doAssert window.textInput.selectionStart == 1 + doAssert window.textInput.selectionEnd == 3 + doAssert window.textInput.visibleStart == 0 + doAssert window.textInput.visibleEnd == f.text.runeLen + doAssert window.textInput.multiline and not window.textInput.password + doAssert window.textInput.bounds == rect( + (20 + padding) * scale, + (20 + padding) * scale, + (240 - padding * 2) * scale, + (f.height - padding * 2) * scale + ) + +block: + echo "Testing native editor bounds follow nested deferred layout spans" + for scale in [1.0'f, 1.5'f, 2.0'f]: + var f = fixture("Nested 🙂") + f.focus() + let + sk = f.harness.sk + window = f.harness.window + padding = sk.theme.padding.float32 + sk.uiScale = scale + f.harness.beginFrame() + let + outer = sk.beginVertexSpan() + inner = sk.beginVertexSpan() + sk.at = vec2(20, 20) + sk.textBox(window, f.id, f.text, 120, 60, wrapWords = true) + sk.endVertexSpan(inner, vec2(8, 16)) + sk.endVertexSpan(outer, vec2(40, -24)) + let unrelated = sk.beginVertexSpan() + sk.endVertexSpan(unrelated, vec2(200, 300)) + f.harness.endFrame() + doAssert window.textInput.id == f.id + let expected = rect( + (vec2(68, 12) + vec2(padding)) * scale, + (vec2(120, 60) - vec2(padding * 2)) * scale + ) + doAssert window.textInput.bounds == expected, + $scale & ": " & $window.textInput.bounds & " != " & $expected + +block: + echo "Testing native editor visibility follows the scrolled text" + var f = fixture("") + for i in 0 ..< 20: + if i > 0: + f.text.add("\n") + f.text.add("Line " & $i) + f.singleLine = false + f.height = 54 + f.focus() + let window = f.harness.window + window.onTextEdit(TextInputEdit(kind: SelectText, start: high(int))) + f.frame() + doAssert window.textInput.visibleStart > 0 + doAssert window.textInput.visibleEnd > window.textInput.visibleStart + doAssert window.textInput.visibleEnd <= f.text.runeLen + doAssert window.textInput.selectionStart == f.text.runeLen + +block: + echo "Testing native editor publication clears for unavailable fields" + for mode in 0 .. 3: + var f = fixture("Private text 🙂") + let window = f.harness.window + doAssert window.textInput == TextInputState() + f.focus() + f.frame() + doAssert window.textInput.text == f.text + case mode + of 0: + f.frame(visible = false) + of 1: + f.enabled = false + f.frame() + of 2: + f.password = true + f.frame() + else: + window.changeFocus() + doAssert window.textInput == TextInputState() + f.frame() + doAssert window.textInput == TextInputState() + +block: + echo "Testing native range replacement and deletion are single edits" + var f = fixture("Aé🙂Z") + f.singleLine = false + f.submitOnEnter = true + f.focus() + let + window = f.harness.window + replacement = "First\tline\n第二段 👩‍💻" + expected = "A" & replacement & "Z" + window.onTextEdit(TextInputEdit( + kind: ReplaceText, + text: replacement, + start: 1, + length: 2 + )) + doAssert f.text == "Aé🙂Z" + f.frame(duplicate = true) + doAssert f.text == expected and not f.state.submitted + doAssert f.state.undoStack.len == 1 + window.shortcut(KeyZ) + f.frame() + doAssert f.text == "Aé🙂Z" + window.shortcut(KeyY) + f.frame() + doAssert f.text == expected + window.onTextEdit(TextInputEdit( + kind: ReplaceText, + start: 1, + length: replacement.runeLen + )) + f.frame() + doAssert f.text == "AZ" and not f.state.submitted + window.shortcut(KeyZ) + f.frame() + doAssert f.text == expected + +block: + echo "Testing native edits clamp invalid and oversized rune ranges" + var f = fixture("Aé🙂Z") + f.focus() + let window = f.harness.window + window.onTextEdit(TextInputEdit( + kind: ReplaceText, + text: "!", + start: high(int), + length: high(int) + )) + f.frame() + doAssert f.text == "Aé🙂Z!" + window.onTextEdit(TextInputEdit( + kind: ReplaceText, + start: low(int), + length: 2 + )) + f.frame() + doAssert f.text == "🙂Z!" + window.onTextEdit(TextInputEdit( + kind: SelectText, + start: 1, + length: low(int) + )) + f.frame() + doAssert f.state.selection == (1 .. 1) + window.onTextEdit(TextInputEdit( + kind: ReplaceText, + start: 1, + length: high(int) + )) + f.frame() + doAssert f.text == "🙂" + window.shortcut(KeyZ) + f.frame() + doAssert f.text == "🙂Z!" + +block: + echo "Testing native selection preserves edit order and undo history" + var f = fixture("Aé🙂Z") + f.focus() + let window = f.harness.window + window.onTextInput("!") + window.onTextEdit(TextInputEdit(kind: SelectText, start: 1, length: 2)) + f.frame() + doAssert f.text == "Aé🙂Z!" and f.state.selection == (1 .. 3) + doAssert f.state.undoStack.len == 1 + window.shortcut(KeyZ) + f.frame() + doAssert f.text == "Aé🙂Z" + window.onTextEdit(TextInputEdit(kind: SelectText, start: 0, length: 1)) + f.frame() + doAssert f.state.undoStack.len == 0 and f.state.redoStack.len == 1 + window.shortcut(KeyY) + window.onTextEdit(TextInputEdit(kind: SelectText, start: 1, length: 2)) + window.onTextInput("R") + f.frame() + doAssert f.text == "ARZ!" + block: echo "Testing disabled fields retain selection and copy without editing" var f = fixture() @@ -341,6 +661,133 @@ block: doAssert f.text == "Hello!" and getClipboardString() == "Hello!" doAssert f.state.selection == (0 .. 6) +block: + echo "Testing read-only styled text retains selection and copy" + var f = fixture("é code 世界") + f.enabled = false + f.singleLine = false + f.spans = @[TextSpan(first: 2, last: 6, font: "Wide")] + f.focus() + let + window = f.harness.window + styledWidth = f.state.layout[2].w + window.shortcut(KeyA) + window.shortcut(KeyC) + window.tap(KeyBackspace) + window.typeText("ignored") + f.frame() + doAssert f.text == "é code 世界" + doAssert getClipboardString() == f.text + doAssert f.state.selection == (0 .. f.text.runeLen) + doAssert f.state.layout[2].w == styledWidth + f.enabled = true + f.frame() + doAssert f.state.layout[2].w < styledWidth + window.typeText("Editable") + f.frame() + doAssert f.text == "Editable" + +block: + echo "Testing styled span clicks activate only without dragging" + var f = fixture("Click here") + f.enabled = false + f.spans = @[TextSpan(first: 0, last: f.text.runeLen, font: "Wide")] + f.frame() + let + window = f.harness.window + bounds = f.state.layout[0] + padding = f.harness.sk.theme.padding.float32 + x = (20 + padding + bounds.x + bounds.w / 2).int + y = (20 + padding + bounds.y + bounds.h / 2).int + window.moveMouse(x, y) + window.pressButton(MouseLeft) + f.frame() + doAssert f.state.activatedSpan == -1 + window.releaseButton(MouseLeft) + f.frame() + doAssert f.state.activatedSpan == 0 + f.frame() + doAssert f.state.activatedSpan == -1 + f.state.lastClickTime = 0 + window.pressButton(MouseLeft) + f.frame() + window.moveMouse(x + 20, y) + f.frame() + window.moveMouse(x, y) + window.releaseButton(MouseLeft) + f.frame() + doAssert f.state.activatedSpan == -1 + +block: + echo "Testing link hover cursor and non-link text boundaries" + var f = fixture("Link bold text") + f.enabled = false + f.spans = @[ + TextSpan(first: 0, last: 4, linkId: 1), + TextSpan(first: 5, last: 9, font: "Wide") + ] + f.frame() + f.hoverGlyph(1) + doAssert f.state.hoveredSpan == 0 + doAssert f.harness.window.cursor.kind == PointerCursor + f.hoverGlyph(6) + doAssert f.state.hoveredSpan == -1 + doAssert f.harness.window.cursor.kind == ArrowCursor + f.hoverGlyph(1) + f.harness.window.moveMouse(21, 21) + f.frame() + doAssert f.state.hoveredSpan == -1 + doAssert f.harness.window.cursor.kind == ArrowCursor + f.hoverGlyph(1) + f.harness.window.moveMouse(600, 400) + f.frame() + doAssert f.state.hoveredSpan == -1 + doAssert f.harness.window.cursor.kind == ArrowCursor + f.hoverGlyph(1) + f.frame(visible = false) + doAssert f.harness.window.cursor.kind == ArrowCursor + +block: + echo "Testing wrapped links follow scrolling and ancestor clipping" + var f = fixture( + "A long linked sentence that wraps onto several lines in this text box." + ) + f.enabled = false + f.singleLine = false + f.spans = @[ + TextSpan(first: 0, last: f.text.runeLen, font: "Wide", linkId: 1) + ] + f.frame() + var secondLine = -1 + for i, bounds in f.state.layout: + if bounds.y > 0 and bounds.w > 0: + secondLine = i + break + doAssert secondLine >= 0 + f.hoverGlyph(secondLine) + doAssert f.state.hoveredSpan == 0 + doAssert f.harness.window.cursor.kind == PointerCursor + f.clip = rect(20, 20, 240, 20) + f.frame() + doAssert f.state.hoveredSpan == -1 + doAssert f.harness.window.cursor.kind == ArrowCursor + f.clip = rect(0, 0, 0, 0) + f.state.scrollPos.y = f.state.lineHeight + f.hoverGlyph(secondLine) + doAssert f.state.hoveredSpan == 0 + doAssert f.harness.window.cursor.kind == PointerCursor + f.spans[0].linkId = 0 + f.frame() + doAssert f.state.hoveredSpan == -1 + doAssert f.harness.window.cursor.kind == ArrowCursor + f.spans[0].linkId = 1 + f.frame() + doAssert f.state.hoveredSpan == 0 + f.spans.setLen(0) + f.frame() + doAssert f.state.hoveredSpan == -1 + doAssert f.harness.window.cursor.kind == ArrowCursor + block: echo "Testing focus loss, disappearing fields, and field switching" var f = fixture() @@ -369,6 +816,100 @@ block: f.frame() doAssert f.text == "Other!" +block: + echo "Testing one block widget selects and copies across all sections" + const Sample = "Title\nBody link\ncode()" + var f = fixture(Sample) + f.enabled = false + f.singleLine = false + f.height = 240 + f.blocks = @[ + TextBlock( + first: 0, last: 5, font: "Wide", + padding: vec2(4, 3), spacing: 12 + ), + TextBlock(first: 6, last: 15, padding: vec2(4, 3), spacing: 12), + TextBlock( + first: 16, last: Sample.runeLen, font: "Small", + padding: vec2(4, 3) + ) + ] + f.spans = @[TextSpan(first: 11, last: 15, linkId: 1)] + f.frame() + let + window = f.harness.window + origin = vec2(20 + f.harness.sk.theme.padding.float32) + first = f.state.layout[0] + last = f.state.layout[^1] + start = origin + first.xy + vec2(0, first.h / 2) + finish = origin + last.xy + vec2(last.w + 1, last.h / 2) + window.moveMouse(start.x.int, start.y.int) + window.pressButton(MouseLeft) + f.frame() + window.moveMouse(finish.x.int, finish.y.int) + f.frame() + window.releaseButton(MouseLeft) + f.frame() + doAssert f.state.selection == (0 .. Sample.runeLen) + window.shortcut(KeyC) + f.frame() + doAssert getClipboardString() == Sample + + echo "Testing block links retain hover, activation, and drag selection" + f.hoverGlyph(12) + doAssert f.state.hoveredSpan == 0 + doAssert window.cursor.kind == PointerCursor + f.state.lastClickTime = 0 + window.tap(MouseLeft) + f.frame() + doAssert f.state.activatedSpan == 0 + f.state.lastClickTime = 0 + window.pressButton(MouseLeft) + f.frame() + window.moveMouse(start.x.int, start.y.int) + f.frame() + window.releaseButton(MouseLeft) + f.frame() + doAssert f.state.activatedSpan == -1 + doAssert f.state.selection.a == 0 + doAssert f.state.selection.b >= 11 + + echo "Testing streaming text preserves one existing block selection" + f.state.cursor = 2 + f.state.selector = 13 + let copied = f.state.copyText() + f.text.add("\necho 1") + f.blocks[^1].last = f.text.runeLen + f.frame() + doAssert f.state.selection == (2 .. 13) + doAssert f.state.copyText() == copied + window.shortcut(KeyA) + window.shortcut(KeyC) + f.frame() + doAssert getClipboardString() == f.text + f.text = "Title\nBody" + f.blocks.setLen(2) + f.blocks[^1].last = f.text.runeLen + f.spans.setLen(0) + f.frame() + doAssert f.state.selection == (0 .. f.text.runeLen) + doAssert f.state.copyText() == f.text + + echo "Testing read-only selection clears on blur and focus epoch changes" + window.moveMouse(600, 400) + window.tap(MouseLeft) + f.frame() + doAssert not f.state.focused + doAssert f.state.cursor == f.state.selector + f.focus() + window.shortcut(KeyA) + f.frame() + doAssert f.state.cursor != f.state.selector + window.changeFocus() + f.frame() + doAssert not f.state.focused + doAssert f.state.cursor == f.state.selector + block: echo "Testing one-batch editing matches separate frames and layout" var fixtures = [fixture(""), fixture("")] @@ -459,6 +1000,98 @@ block: f.frame() doAssert f.text == "R" +block: + echo "Testing native commit callbacks forward only while inactive" + var + commits: seq[string] + f = fixture( + onTextInput = (proc(text: string) = commits.add(text)) + ) + let window = f.harness.window + window.onTextInput("Inactive\n🙂") + doAssert commits == @["Inactive\n🙂"] + f.focus() + doAssert f.text == "Hello" + window.onTextInput(" active") + f.frame() + doAssert f.text == "Hello active" + doAssert commits == @["Inactive\n🙂"] + window.onTextInput(" discarded") + window.changeFocus() + f.frame() + doAssert f.text == "Hello active" + window.onTextInput("After blur") + doAssert commits == @["Inactive\n🙂", "After blur"] + f.focus() + doAssert f.text == "Hello active" + +block: + echo "Testing replaced native commit callbacks are reinstalled once" + var + oldCommits, newCommits: seq[string] + f = fixture( + onTextInput = (proc(text: string) = oldCommits.add(text)) + ) + let window = f.harness.window + f.focus() + window.onTextInput(" pending") + window.onTextInput = proc(text: string) = newCommits.add(text) + f.frame() + doAssert f.text == "Hello pending" + for i in 0 ..< 5: + window.shortcut(KeyA) + window.onTextInput("Replacement") + f.frame() + doAssert f.text == "Replacement" + doAssert oldCommits.len == 0 and newCommits.len == 0 + window.changeFocus() + f.frame() + window.onTextInput("Forward once") + doAssert oldCommits.len == 0 and newCommits == @["Forward once"] + f.focus() + window.onTextInput = nil + f.frame() + window.onTextInput(" restored") + f.frame() + doAssert f.text == "Replacement restored" + doAssert oldCommits.len == 0 and newCommits == @["Forward once"] + +block: + echo "Testing native edit callbacks forward and reinstall without repeats" + var + oldEdits, newEdits: seq[TextInputEdit] + f = fixture(onTextEdit = (proc(edit: TextInputEdit) = oldEdits.add(edit))) + let + window = f.harness.window + edit = TextInputEdit(kind: ReplaceText, text: "R", start: 0, length: 5) + window.onTextEdit(edit) + doAssert oldEdits == @[edit] + f.focus() + window.onTextEdit(edit) + window.onTextEdit = proc(edit: TextInputEdit) = newEdits.add(edit) + f.frame() + doAssert f.text == "R" and oldEdits == @[edit] and newEdits.len == 0 + window.onTextEdit = nil + f.frame() + window.onTextEdit(TextInputEdit(kind: ReplaceText, text: "!", start: 1)) + f.frame() + doAssert f.text == "R!" + window.onTextEdit = proc(edit: TextInputEdit) = newEdits.add(edit) + f.frame() + f.enabled = false + f.frame() + window.onTextEdit(edit) + f.frame() + doAssert f.text == "R!" and newEdits.len == 0 + f.enabled = true + f.frame() + window.onTextEdit(edit) + window.changeFocus() + f.frame() + doAssert f.text == "R!" + window.onTextEdit(edit) + doAssert oldEdits == @[edit] and newEdits == @[edit] + block: echo "Testing application callbacks assigned after construction" var diff --git a/tests/test_quotes.nim b/tests/test_quotes.nim new file mode 100644 index 00000000..ede10f61 --- /dev/null +++ b/tests/test_quotes.nim @@ -0,0 +1,225 @@ +import + std/[importutils, math, tables], + bumpy, pixie, vmath, windy, + silky, silky/internal/inputs + +const + FontPath = "tests/data/IBMPlexSans-Regular.ttf" + QuoteColor = rgbx(90, 150, 220, 255) + RuleColor = rgbx(170, 120, 80, 255) + CaptionColor = rgbx(80, 190, 130, 255) + +proc close(a, b: float32): bool = + ## Compares logical and physical coordinates with float tolerance. + abs(a - b) < 0.001 + +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() + ) + new(result.drawer) + result.theme.padding = 0 + result.mousePos = vec2(-1) + result.pushLayout(vec2(0), vec2(300, 300)) + result.pushClipRect(rect(0, 0, 300, 300)) + +proc render( + sk: Silky, + source: string, + blocks: seq[TextBlock], + width = 180.0'f +): TextBoxState = + ## Draws one read-only quote document through the native textbox. + var text = source + textBoxStates.del("quotes") + sk.at = vec2(10.17'f, 20.29'f) + sk.textBox( + Window(), "quotes", text, width, 220, + wrapWords = true, enabled = false, blocks = blocks + ) + result = textBoxStates["quotes"] + +proc bars(sk: Silky, color: ColorRGBX, width = 180.0'f): seq[Rect] = + ## Finds solid rules and checks their physical alignment and clipping. + let vertices = sk.drawer.layers[NormalLayer] + for i in countup(0, vertices.high, 6): + if vertices[i].color != color: + continue + doAssert vertices[i].uv == vertices[i + 2].uv + doAssert vertices[i].clipPos == vec2(10.17'f, 20.29'f) + doAssert vertices[i].clipSize == vec2(width, 220) + for j in i ..< i + 6: + let pixel = vertices[j].pos * sk.uiScale + doAssert close(pixel.x, round(pixel.x)) + doAssert close(pixel.y, round(pixel.y)) + result.add(rect( + vertices[i].pos, + vertices[i + 2].pos - vertices[i].pos + )) + +proc patchBounds(sk: Silky, name: string): Rect = + ## Finds the outer bounds of one native code surface by atlas region. + let + sprite = sk.atlas.entries[name] + vertices = sk.drawer.layers[NormalLayer] + var + first = true + right, bottom: float32 + for i in countup(0, vertices.high, 6): + let uv = vertices[i].uv + if uv.x < sprite.x.float32 or uv.x >= (sprite.x + sprite.width).float32 or + uv.y < sprite.y.float32 or uv.y >= (sprite.y + sprite.height).float32: + continue + if first: + result.x = vertices[i].pos.x + result.y = vertices[i].pos.y + first = false + else: + result.x = min(result.x, vertices[i].pos.x) + result.y = min(result.y, vertices[i].pos.y) + right = max(right, vertices[i + 2].pos.x) + bottom = max(bottom, vertices[i + 2].pos.y) + doAssert not first + result.w = right - result.x + result.h = bottom - result.y + +proc caption(sk: Silky): Vec2 = + ## Finds the first caption glyph emitted by the native font renderer. + for vertex in sk.drawer.layers[NormalLayer]: + if vertex.color == CaptionColor: + return vertex.pos + doAssert false, "Expected a native code caption glyph." + +block: + echo "Testing nested quote bars and continued container spacing" + let builder = newAtlasBuilder(2048, 2) + builder.addFont(FontPath, "Default", 18) + builder.addFont(FontPath, "Heading", 26) + builder.addFont(FontPath, "Small", 12) + doAssert builder.addImage("textbox.disabled.9patch", newImage(16, 16)) + doAssert builder.addImage("code.9patch", newImage(16, 16)) + for density in [1.0'f, 1.25'f, 1.5'f, 2.0'f]: + for continuing in 0 .. 2: + let + sk = fixture(builder, density) + state = sk.render("Head\nBody", @[ + TextBlock( + first: 0, last: 4, font: "Heading", + padding: vec2(12, 6), spacing: 8, + quoteDepth: 2, quoteContinue: continuing, quoteColor: QuoteColor + ), + TextBlock( + first: 5, last: 9, padding: vec2(12, 6), + quoteDepth: 2, quoteColor: QuoteColor + ) + ]) + quads = sk.bars(QuoteColor) + firstHeight = builder.atlas.fonts["Heading"].lineHeight + 12 + doAssert quads.len == 4 + doAssert state.layout[0].x == 44 + doAssert state.layout[5].x == 44 + for level in 0 .. 1: + let extension = if level < continuing: 8.0'f else: 0.0'f + doAssert close( + quads[level].x * density, + round((10.17'f + 12 + level.float32 * 16) * density) + ) + doAssert close(quads[level].w * density, max(1.0'f, round(2 * density))) + doAssert close( + (quads[level].y + quads[level].h) * density, + round((20.29'f + firstHeight + extension) * density) + ) + doAssert close( + quads[level + 2].y * density, + round((20.29'f + firstHeight + 8) * density) + ) + state.selectAll() + doAssert state.copyText() == "Head\nBody" + doAssert state.layout.len == 9 + + echo "Testing quoted code surfaces, captions, and rules at ", density + let + plain = fixture(builder, density) + quoted = fixture(builder, density) + var code = TextBlock( + first: 0, last: 2, padding: vec2(12, 6), + patch: "code.9patch", patchBorder: 4, + label: "nim", labelFont: "Small", labelColor: CaptionColor, + labelSpacing: 4 + ) + let plainState = plain.render("WW", @[code]) + code.quoteDepth = 2 + code.quoteColor = QuoteColor + let + quoteState = quoted.render("WW", @[code]) + plainPatch = plain.patchBounds("code.9patch") + quotePatch = quoted.patchBounds("code.9patch") + doAssert close(quotePatch.x - plainPatch.x, 32) + doAssert close(plainPatch.w - quotePatch.w, 32) + doAssert close(quoteState.layout[0].x - plainState.layout[0].x, 32) + doAssert close(quoted.caption().x - plain.caption().x, 32) + doAssert quoteState.innerHeight == plainState.innerHeight + let + ruled = fixture(builder, density) + ruleState = ruled.render("", @[ + TextBlock( + first: 0, last: 0, padding: vec2(12, 6), + ruleColor: RuleColor, ruleThickness: 1, + quoteDepth: 2, quoteColor: QuoteColor + ) + ]) + horizontal = ruled.bars(RuleColor) + doAssert ruleState.innerHeight == 13 + doAssert ruleState.runes.len == 0 + doAssert horizontal.len == 1 + doAssert close(horizontal[0].x * density, round((10.17'f + 44) * density)) + + echo "Testing quote wrapping, empty paragraphs, and bounded indentation" + let + quoted = fixture(builder, 2) + wrapped = quoted.render("WW WW WW", @[ + TextBlock( + first: 0, last: 8, padding: vec2(12, 6), + quoteDepth: 1, quoteColor: QuoteColor + ) + ], 80) + doAssert wrapped.layout[3].y > wrapped.layout[0].y + wrapped.selectAll() + doAssert wrapped.copyText() == "WW WW WW" + let + empty = fixture(builder, 2) + emptyState = empty.render("", @[ + TextBlock( + first: 0, last: 0, padding: vec2(12, 6), + quoteDepth: 1, quoteColor: QuoteColor + ) + ]) + doAssert close( + emptyState.innerHeight, + builder.atlas.fonts["Default"].lineHeight + 12 + ) + doAssert emptyState.layout.len == 0 + doAssert empty.bars(QuoteColor).len == 1 + for width in [0.0'f, 10.0'f, 20.0'f, 80.0'f]: + let + narrow = fixture(builder, 2) + narrowState = narrow.render("", @[ + TextBlock( + first: 0, last: 0, padding: vec2(12, 6), + quoteDepth: 1000, quoteColor: QuoteColor + ) + ], width) + doAssert narrowState.innerHeight > 0 + for quad in narrow.bars(QuoteColor, width): + doAssert quad.w >= 0 and quad.h >= 0 + doAssert quad.x >= 10 + doAssert quad.x + quad.w <= 10.17'f + width + 0.5'f + textBoxStates.del("quotes") + +echo "All native quote tests passed." diff --git a/tests/test_rules.nim b/tests/test_rules.nim new file mode 100644 index 00000000..e1f4cba9 --- /dev/null +++ b/tests/test_rules.nim @@ -0,0 +1,141 @@ +import + std/[importutils, math, tables, unicode], + bumpy, pixie, vmath, windy, + silky, silky/internal/inputs + +const + FontPath = "tests/data/IBMPlexSans-Regular.ttf" + RuleColor = rgbx(90, 150, 220, 255) + +proc close(a, b: float32): bool = + ## Compares logical and physical coordinates with float tolerance. + abs(a - b) < 0.001 + +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() + ) + new(result.drawer) + result.theme.padding = 0 + result.mousePos = vec2(-1) + result.pushLayout(vec2(0), vec2(300, 300)) + result.pushClipRect(rect(0, 0, 300, 300)) + +proc rules(sk: Silky, clip: Rect): seq[Rect] = + ## Finds rule quads and checks their pixel alignment and native clip. + let vertices = sk.drawer.layers[NormalLayer] + for i in countup(0, vertices.high, 6): + if vertices[i].color != RuleColor: + continue + doAssert vertices[i].uv == vertices[i + 2].uv + doAssert vertices[i].clipPos == clip.xy + doAssert vertices[i].clipSize == clip.wh + for j in i ..< i + 6: + let pixel = vertices[j].pos * sk.uiScale + doAssert close(pixel.x, round(pixel.x)) + doAssert close(pixel.y, round(pixel.y)) + result.add(rect( + vertices[i].pos, + vertices[i + 2].pos - vertices[i].pos + )) + +block: + echo "Testing rule-only blocks have no text or implicit font line" + privateAccess(TextBoxState) + let + builder = newAtlasBuilder(1024, 2) + window = Window() + 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) + origin = vec2(10.17'f, 20.29'f) + rule = TextBlock( + first: 0, + last: 0, + ruleColor: RuleColor, + ruleThickness: 1, + padding: vec2(12, 6) + ) + var text = "" + sk.at = origin + sk.textBox( + window, "rule", text, 80, 100, + wrapWords = true, enabled = false, blocks = @[rule] + ) + let + state = textBoxStates["rule"] + quads = sk.rules(rect(origin, vec2(80, 100))) + doAssert state.runes.len == 0 + doAssert state.layout.len == 0 + doAssert state.runs.len == 0 + doAssert state.innerHeight == 13 + doAssert state.locationRect(0).h == 0 + state.selectAll() + doAssert state.copyText() == "" + doAssert state.cursor == 0 and state.selector == 0 + doAssert quads.len == 1 + doAssert close(quads[0].x * density, round((origin.x + 12) * density)) + doAssert close(quads[0].y * density, round((origin.y + 6) * density)) + doAssert close( + (quads[0].x + quads[0].w) * density, + round((origin.x + 80 - 12) * density) + ) + doAssert close(quads[0].h * density, max(1.0'f, round(density))) + + sk.drawer.layers[NormalLayer].setLen(0) + sk.at = origin + sk.textBox( + window, "rule", text, 20, 100, + wrapWords = true, enabled = false, blocks = @[rule] + ) + doAssert sk.rules(rect(origin, vec2(20, 100))).len == 0 + doAssert state.innerHeight == 13 + textBoxStates.del("rule") + + echo "Testing rules preserve shared selection and surrounding wrapping" + const Source = "WW WW WW\nAfter" + let + after = Source.find('\n') + 1 + before = TextBlock(first: 0, last: after - 1, padding: vec2(12, 6)) + rule = TextBlock( + first: after - 1, + last: after - 1, + ruleColor: RuleColor, + ruleThickness: 1, + padding: vec2(12, 6), + spacing: 8 + ) + following = TextBlock( + first: after, last: Source.runeLen, padding: vec2(12, 6) + ) + plain = TextBoxState(wordWrap: true, blocks: @[before, following]) + ruled = TextBoxState(wordWrap: true, blocks: @[before, rule, following]) + plain.setText(Source) + ruled.setText(Source) + plain.computeLayout(builder.atlas.fonts, "Default", 64) + ruled.computeLayout(builder.atlas.fonts, "Default", 64) + doAssert ruled.layout.len == plain.layout.len + doAssert ruled.runes == plain.runes + doAssert ruled.runs.len == plain.runs.len + doAssert ruled.layout[3].y > ruled.layout[0].y + for i in 0 ..< after - 1: + doAssert ruled.layout[i] == plain.layout[i] + for i in after ..< Source.runeLen: + doAssert ruled.layout[i].x == plain.layout[i].x + doAssert ruled.layout[i].wh == plain.layout[i].wh + doAssert close(ruled.layout[i].y - plain.layout[i].y, 21) + doAssert close(ruled.innerHeight - plain.innerHeight, 21) + ruled.selectAll() + doAssert ruled.copyText() == Source + doAssert ruled.locationRect(Source.runeLen).h == + plain.locationRect(Source.runeLen).h + +echo "All native rule tests passed." diff --git a/tests/test_shader_codegen.nim b/tests/test_shader_codegen.nim index 8f1a9a17..2d7b7ed2 100644 --- a/tests/test_shader_codegen.nim +++ b/tests/test_shader_codegen.nim @@ -1,5 +1,19 @@ import strutils, shady, silky/drawers/shader +proc checkSampleOrder(source, base, mask: string) = + ## Keeps texture derivatives valid at fragment clipping boundaries. + let + baseIndex = source.find(base) + maskIndex = source.find(mask) + clipIndex = source.find("fragmentPos.x < fragmentClipPos.x") + discardIndex = source.find("discard") + doAssert baseIndex >= 0 and maskIndex >= 0 + doAssert clipIndex >= 0 and discardIndex > clipIndex + doAssert baseIndex < clipIndex, + "The atlas must be sampled before nonuniform clipping." + doAssert maskIndex < clipIndex, + "The mask must be sampled before nonuniform clipping." + block: let vertex = toShader(silkyVert, glsl3Desktop, shaderVertex) doAssert "uniform vec2 viewportSize;" in vertex @@ -15,6 +29,10 @@ block: doAssert "texture(atlasSampler, fragmentUv)" in fragment doAssert "(texture(atlasSampler, fragmentMaskUv)).r" in fragment doAssert "mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR)" in fragment + fragment.checkSampleOrder( + "texture(atlasSampler, fragmentUv)", + "texture(atlasSampler, fragmentMaskUv)" + ) block: let vertex = toShader(silkyVert, vulkanGlsl450, shaderVertex) @@ -32,6 +50,10 @@ block: doAssert "layout(location = 5) in vec2 fragmentMaskUv;" in fragment doAssert "layout(location = 0) out vec4 fragColor;" in fragment doAssert "(texture(atlasSampler, fragmentMaskUv)).r" in fragment + fragment.checkSampleOrder( + "texture(atlasSampler, fragmentUv)", + "texture(atlasSampler, fragmentMaskUv)" + ) block: let vertex = toHLSL(silkyVert, shaderVertex) @@ -51,5 +73,16 @@ block: doAssert "atlasSampler.Sample(atlasSamplerSampler, fragmentUv)" in fragment doAssert "(atlasSampler.Sample(atlasSamplerSampler, fragmentMaskUv)).r" in fragment doAssert "lerp(float3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR)" in fragment + fragment.checkSampleOrder( + "atlasSampler.Sample(atlasSamplerSampler, fragmentUv)", + "atlasSampler.Sample(atlasSamplerSampler, fragmentMaskUv)" + ) + +block: + let fragment = toShader(silkyFrag, metalMSL, shaderFragment) + fragment.checkSampleOrder( + "atlasSampler.sample(atlasSamplerSampler, fragmentUv)", + "atlasSampler.sample(atlasSamplerSampler, fragmentMaskUv)" + ) echo "Silky Shady shader codegen tests passed" diff --git a/tests/test_textboxes.nim b/tests/test_textboxes.nim index 7683633a..1fb7ddb2 100644 --- a/tests/test_textboxes.nim +++ b/tests/test_textboxes.nim @@ -8,6 +8,8 @@ import # Build a real atlas with font metrics. let builder = newAtlasBuilder(1024, 4) builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18.0) +builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Wide", 30.0) +builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Small", 12.0) builder.write("tests/dist/atlas.png") let silkyAtlas = readAtlasFromPng("tests/dist/atlas.png") let fontData = silkyAtlas.fonts["Default"] @@ -31,6 +33,193 @@ proc newStateSingleLine(text: string, maxWidth = 500.0f): TextBoxState = result.setText(text) result.computeLayout(fontData, maxWidth) +proc advance(font: FontAtlas, rune: Rune): float32 = + ## Returns the actual atlas advance used by span layout assertions. + var entry: ptr LetterEntry + doAssert font.lookupLetter(rune, 0, entry) + entry.advance + +block: + echo "Testing styled text uses each span's font metrics" + let + s = newState("W a") + wide = silkyAtlas.fonts["Wide"] + small = silkyAtlas.fonts["Small"] + s.enabled = false + s.spans = @[ + TextSpan(first: 0, last: 1, font: "Wide"), + TextSpan(first: 2, last: 3, font: "Small") + ] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert s.layout.len == 3 + doAssert abs(s.layout[0].w - wide.advance(Rune('W'))) < 0.01 + doAssert abs(s.layout[1].w - fontData.advance(Rune(' '))) < 0.01 + doAssert abs(s.layout[2].w - small.advance(Rune('a'))) < 0.01 + doAssert abs(s.layout[1].x - s.layout[0].w) < 0.01 + doAssert s.lineHeight >= wide.lineHeight + for bounds in s.layout: + doAssert bounds.h == s.lineHeight + +block: + echo "Testing formatting and links preserve native pair kerning" + const Sample = "AVATAR To WAVY" + let + plain = newStateNoWrap(Sample) + styled = newStateNoWrap(Sample) + doAssert fontData.lookupKerning(Rune('A'), Rune('V')) != 0 + doAssert fontData.lookupKerning(Rune('T'), Rune('o')) != 0 + doAssert plain.layout[1].x < plain.layout[0].w + styled.enabled = false + for i in 0 ..< styled.runes.len: + styled.spans.add(TextSpan( + first: i, + last: i + 1, + font: + if i mod 2 == 0: + "Default" + else: + "", + linkId: + if i in 1 .. 8: + 1 + else: + 0 + )) + styled.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert styled.layout.len == plain.layout.len + for i in 0 ..< plain.layout.len: + let + expected = plain.layout[i] + actual = styled.layout[i] + doAssert abs(actual.x - expected.x) < 0.001 + doAssert abs(actual.y - expected.y) < 0.001 + doAssert abs(actual.w - expected.w) < 0.001 + doAssert abs(actual.h - expected.h) < 0.001 + +block: + echo "Testing styled long words wrap before crossing the width" + let + s = newState("WWWWWW") + wide = silkyAtlas.fonts["Wide"] + width = wide.advance(Rune('W')) * 2.5'f + s.enabled = false + s.spans = @[TextSpan(first: 0, last: 6, font: "Wide")] + s.computeLayout(silkyAtlas.fonts, "Default", width) + doAssert s.layout[0].y == s.layout[1].y + doAssert s.layout[2].y > s.layout[1].y + doAssert s.layout[4].y > s.layout[3].y + for bounds in s.layout: + doAssert bounds.x + bounds.w <= width + 0.01 + +block: + echo "Testing styled Unicode selection preserves the original text" + let s = newState("é code 世界") + s.enabled = false + s.spans = @[TextSpan(first: 2, last: 6, font: "Small")] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert s.layout.len == s.runes.len + s.cursor = 2 + s.selector = 6 + doAssert s.copyText() == "code" + doAssert getSelectionRects(s.layout, 2, 6).len == 1 + s.selectAll() + doAssert s.copyText() == "é code 世界" + +block: + echo "Testing styled code preserves tabs when copying" + let + s = newState("a\tb") + small = silkyAtlas.fonts["Small"] + s.enabled = false + s.spans = @[TextSpan(first: 0, last: 3, font: "Small")] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert abs(s.layout[1].w - small.advance(Rune(' ')) * 4) < 0.01 + doAssert abs(s.layout[2].x - s.layout[1].x - s.layout[1].w) < 0.01 + s.selectAll() + doAssert s.copyText() == "a\tb" + +block: + echo "Testing the styled layout overload preserves unstyled layout" + let + s = newState("A plain paragraph that wraps across lines.", 100) + expected = s.layout + s.computeLayout(silkyAtlas.fonts, "Default", 100) + doAssert s.layout == expected + +block: + echo "Testing one selection spans headings, wrapped prose, and code" + const + Heading = "Heading" + Body = "é body wraps over several lines for selection." + Code = "let x = 1\n echo x" + Sample = Heading & "\n" & Body & "\n" & Code + let + bodyStart = Heading.runeLen + 1 + codeStart = bodyStart + Body.runeLen + 1 + s = newState(Sample, 180) + s.enabled = false + s.blocks = @[ + TextBlock( + first: 0, last: Heading.runeLen, font: "Wide", + padding: vec2(12, 6), spacing: 8 + ), + TextBlock( + first: bodyStart, last: codeStart - 1, + padding: vec2(12, 6), spacing: 8 + ), + TextBlock( + first: codeStart, last: Sample.runeLen, font: "Small", + padding: vec2(12, 12), label: "nim", labelFont: "Small", + labelSpacing: 8 + ) + ] + s.computeLayout(silkyAtlas.fonts, "Default", 180) + doAssert s.layout.len == Sample.runeLen + doAssert s.layout[0].h > s.layout[bodyStart].h + doAssert s.layout[bodyStart].h > s.layout[codeStart].h + doAssert s.layout[codeStart - 2].y > s.layout[bodyStart].y + doAssert s.layout[bodyStart].x == 12 + doAssert s.layout[codeStart].x == 12 + doAssert abs(s.innerHeight - s.layout[^1].y - s.layout[^1].h - 12) < 0.001 + for index in [0, bodyStart, codeStart]: + doAssert s.locationRect(index).h == s.layout[index].h + s.selector = 2 + s.cursor = codeStart + 5 + doAssert s.copyText() == "ading\n" & Body & "\nlet x" + let selected = getSelectionRects(s.layout, s.selector, s.cursor) + doAssert selected.len >= 4 + doAssert selected[0].h > selected[^1].h + s.selectAll() + doAssert s.copyText() == Sample + + echo "Testing dragging through block spacing has no selection dead zone" + let + first = s.layout[0] + body = s.layout[bodyStart] + s.mouseAction(first.xy + vec2(0, first.h / 2)) + s.mouseAction( + vec2(body.x, body.y - 1), click = false, shift = true + ) + doAssert s.selector == 0 + doAssert s.cursor == bodyStart + doAssert s.copyText() == Heading & "\n" + + echo "Testing keyboard selection follows rows with different heights" + s.cursor = 0 + s.selector = 0 + s.savedX = first.x + s.down(shift = true) + doAssert s.cursor == bodyStart + doAssert s.selector == 0 + s.up(shift = true) + doAssert s.cursor == 0 + s.cursor = codeStart + s.selector = codeStart + s.savedX = s.layout[codeStart].x + s.up(shift = true) + doAssert s.cursor >= bodyStart and s.cursor < codeStart + doAssert s.selector == codeStart + block: echo "Testing getText / setText" let s = newState("") From 4d0f4bf9247762c6e5650faa2bd8a8e53dc70228 Mon Sep 17 00:00:00 2001 From: treeform Date: Tue, 10 Nov 2026 18:36:33 -0800 Subject: [PATCH 03/16] separate rich text from plain textboxes --- .github/workflows/build.yml | 1 + src/silky.nim | 11 +- src/silky/richtextboxes.nim | 715 +++++++++++++++++++++++++++++++++++ src/silky/textboxes.nim | 595 +++-------------------------- tests/test_decorations.nim | 117 ++++-- tests/test_inputs.nim | 195 ++++++++-- tests/test_quotes.nim | 41 +- tests/test_richtextboxes.nim | 224 +++++++++++ tests/test_rules.nim | 58 +-- tests/test_textboxes.nim | 192 +--------- 10 files changed, 1301 insertions(+), 848 deletions(-) create mode 100644 src/silky/richtextboxes.nim create mode 100644 tests/test_richtextboxes.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b29fa861..e9e5653b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -58,6 +58,7 @@ jobs: 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_buttons.nim nim r -d:silkyTesting tests/test_subwindow.nim diff --git a/src/silky.nim b/src/silky.nim index 9cf01600..af4dbfe1 100644 --- a/src/silky.nim +++ b/src/silky.nim @@ -3,9 +3,12 @@ from silky/common import SilkyError export SilkyError when defined(silkyTesting): - import silky/[semantics, atlas, widgets, textboxes, testing, dsl, menus, profiles] + import silky/[ + semantics, atlas, widgets, textboxes, richtextboxes, testing, dsl, menus, + profiles + ] export semantics except textInputs - export atlas, tables, textboxes, testing, dsl, menus, profiles + export atlas, tables, textboxes, richtextboxes, testing, dsl, menus, profiles export widgets except button, checkBox, clickableIcon, dropDown, frame, group, h1text, icon, iconButton, image, listBox, progressBar, radioButton, ribbon, scrubber, text @@ -16,14 +19,14 @@ else: not defined(useMetal4) and not defined(useCpu): import opengl - import silky/[contexts, atlas, widgets, textboxes, dsl, menus] + import silky/[contexts, atlas, widgets, textboxes, richtextboxes, dsl, menus] when not defined(useDirectX) and not defined(useVulkan) and not defined(useMetal4) and not defined(useCpu): export opengl export contexts except textInputs - export windy, atlas, tables, textboxes, dsl, menus + export windy, atlas, tables, textboxes, richtextboxes, dsl, menus export widgets except button, checkBox, clickableIcon, dropDown, frame, group, h1text, icon, iconButton, image, listBox, progressBar, radioButton, ribbon, scrubber, text diff --git a/src/silky/richtextboxes.nim b/src/silky/richtextboxes.nim new file mode 100644 index 00000000..994de3eb --- /dev/null +++ b/src/silky/richtextboxes.nim @@ -0,0 +1,715 @@ +import + std/[tables, unicode, times], + vmath, bumpy, chroma, + silky/atlas, silky/internal/inputs, silky/textboxes + +when defined(silkyTesting): + import silky/[semantics, testing, profiles] +else: + import silky/[contexts, profiles], windy + +const + LF = Rune(10) + Space = Rune(32) + Tab = Rune(9) + DoubleClickTime = 0.4 + SelectionColor = rgbx(30, 60, 130, 128) + +when defined(macos): + const TextBoxScrollSpeed = 10.0f +else: + const TextBoxScrollSpeed = -10.0f + +type + TextSpan* = object + ## Read-only formatting over a half-open range of rune offsets. + first*, last*: int + font*: string + color*: ColorRGBX + background*: ColorRGBX + strikethrough*: bool + linkId*: int + ## Matching positive IDs group the styled parts of one hoverable link. + + TextBlock* = object + ## A styled block over a half-open range of shared rune offsets. + first*, last*: int + font*: string + padding*: Vec2 + spacing*: float32 + patch*: string + patchBorder*: int + label*, labelFont*: string + labelColor*: ColorRGBX + labelSpacing*: float32 + ruleColor*: ColorRGBX + ruleThickness*: float32 + ## Positive thickness turns an empty block into a horizontal rule. + quoteDepth*, quoteContinue*: int + ## Continued quote levels also draw their borders through spacing. + quoteIndent*: float32 = 16 + quoteColor*: ColorRGBX + quoteThickness*: float32 = 2 + + BlockLayout = object + bounds: Rect + ruleBounds: Rect + quoteBounds: Rect + labelPosition: Vec2 + labelFont: string + + TextRun = object + text: string + font: string + position: Vec2 + bounds: Rect + span: int + + RichTextBoxState* = ref object + ## Read-only styled content with one shared plain-text selection state. + editor*: TextBoxState + spans*: seq[TextSpan] + blocks*: seq[TextBlock] + activatedSpan*: int = -1 + hoveredSpan*: int = -1 + runeSpans: seq[int] + runs: seq[TextRun] + blockLayouts: seq[BlockLayout] + lastFont: string + focusEpoch: uint64 + pressedSpan: int = -1 + pressPosition: Vec2 + spanDragged: bool + +var + richTextBoxStates*: Table[string, RichTextBoxState] + +proc newRichTextBoxState*(text = "", wordWrap = true): RichTextBoxState = + ## Creates a read-only document with its own selection and layout cache. + result = RichTextBoxState( + editor: TextBoxState(wordWrap: wordWrap, enabled: false) + ) + result.editor.setText(text) + +proc getText*(state: RichTextBoxState): string = + ## Returns the underlying selectable text without formatting markers. + state.editor.getText() + +proc sameText*(state: RichTextBoxState, text: string): bool = + ## Compares the selectable text without allocating. + state.editor.sameText(text) + +proc setText*( + state: RichTextBoxState, + text: string, + preserveSelection = false +) = + ## Replaces content while optionally retaining a streamed selection. + state.editor.setText(text, preserveSelection) + +proc innerHeight*(state: RichTextBoxState): float32 = + ## Returns the measured height of the complete styled document. + state.editor.innerHeight + +proc computeLayout*( + state: RichTextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) + +proc computeBlocks( + state: RichTextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) = + ## Combines block layouts into one selectable document and native run list. + state.editor.positionedLayout = true + state.editor.lineHeight = fonts[baseFont].lineHeight + state.editor.lastMaxWidth = maxWidth + state.editor.layout.setLen(state.editor.runes.len) + state.runeSpans.setLen(state.editor.runes.len) + state.runs.setLen(0) + state.blockLayouts.setLen(0) + state.editor.layoutHeight = 0 + for index in state.runeSpans.mitems: + index = -1 + var + covered = 0 + previousEnd = rect(0, 0, 0, state.editor.lineHeight) + for item in state.blocks: + let + first = clamp(item.first, covered, state.editor.runes.len) + last = clamp(item.last, first, state.editor.runes.len) + width = max(0.0'f, maxWidth) + depth = max(0, item.quoteDepth) + padding = vec2( + if depth > 0: + min(max(0.0'f, item.padding.x), width / 2) + else: + max(0.0'f, item.padding.x), + max(0.0'f, item.padding.y) + ) + quoteInset = min( + max(0.0'f, width - padding.x * 2), + depth.float32 * max(0.0'f, item.quoteIndent) + ) + blockWidth = width - quoteInset + for i in covered ..< first: + state.editor.layout[i] = previousEnd + if first == last and item.ruleThickness > 0: + let + origin = vec2( + quoteInset + padding.x, + state.editor.layoutHeight + padding.y + ) + height = item.ruleThickness + padding.y * 2 + state.blockLayouts.add(BlockLayout( + bounds: rect(quoteInset, state.editor.layoutHeight, blockWidth, height), + ruleBounds: rect( + origin, + vec2(max(0.0'f, blockWidth - padding.x * 2), item.ruleThickness) + ), + quoteBounds: rect( + padding.x, + state.editor.layoutHeight, + max(0.0'f, width - padding.x * 2), + height + ) + )) + state.editor.layoutCursor = rect(origin, vec2(0)) + state.editor.layoutHeight += height + max(0.0'f, item.spacing) + previousEnd = state.editor.layoutCursor + covered = last + continue + let + font = + if item.font in fonts: + item.font + else: + baseFont + labelFont = + if item.labelFont in fonts: + item.labelFont + else: + baseFont + labelHeight = + if item.label.len > 0: + fonts[labelFont].lineHeight + max(0.0'f, item.labelSpacing) + else: + 0.0'f + origin = vec2( + quoteInset + padding.x, + state.editor.layoutHeight + padding.y + labelHeight + ) + local = RichTextBoxState( + editor: TextBoxState( + runes: state.editor.runes[first ..< last], + wordWrap: state.editor.wordWrap, + enabled: false + ), + spans: @[TextSpan()] + ) + var spanIndices = @[-1] + for index, span in state.spans: + if span.first < last and span.last > first: + var relative = span + relative.first = max(first, span.first) - first + relative.last = min(last, span.last) - first + local.spans.add(relative) + spanIndices.add(index) + local.computeLayout(fonts, font, max(0.0'f, blockWidth - padding.x * 2)) + var contentHeight = local.editor.lineHeight + for i, bounds in local.editor.layout: + state.editor.layout[first + i] = rect(origin + bounds.xy, bounds.wh) + let span = local.runeSpans[i] + if span >= 0: + state.runeSpans[first + i] = spanIndices[span] + for run in local.runs.mitems: + run.position += origin + run.bounds.x += origin.x + run.bounds.y += origin.y + if run.span >= 0: + run.span = spanIndices[run.span] + state.runs.add(run) + state.editor.layoutCursor = rect( + origin.x, + origin.y, + 0, + local.editor.lineHeight + ) + if local.editor.layout.len > 0: + let bounds = local.editor.layout[^1] + contentHeight = bounds.y + bounds.h + state.editor.layoutCursor = rect( + origin.x + bounds.x + bounds.w, + origin.y + bounds.y, + 0, + bounds.h + ) + if local.editor.runes[^1] == LF: + contentHeight += local.editor.lineHeight + state.editor.layoutCursor.x = origin.x + state.editor.layoutCursor.y += local.editor.lineHeight + let height = contentHeight + padding.y * 2 + labelHeight + state.blockLayouts.add(BlockLayout( + bounds: rect(quoteInset, state.editor.layoutHeight, blockWidth, height), + 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 + ), + labelFont: labelFont + )) + state.editor.layoutHeight += height + max(0.0'f, item.spacing) + previousEnd = state.editor.layoutCursor + covered = last + for i in covered ..< state.editor.runes.len: + state.editor.layout[i] = previousEnd + state.editor.dirty = false + +proc computeLayout*( + state: RichTextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) = + ## Lays out styled text with the same glyph positions used for selection. + state.lastFont = baseFont + if state.blocks.len > 0: + state.computeBlocks(fonts, baseFont, maxWidth) + return + state.editor.positionedLayout = false + state.editor.layoutCursor = rect(0, 0, 0, 0) + state.blockLayouts.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) + return + let base = fonts[baseFont] + var + resolvedFonts = @[base] + fontNames = @[baseFont] + baseline = base.ascent + descent = base.descent + lineGap = base.lineGap + state.editor.lineHeight = base.lineHeight + state.editor.lastMaxWidth = maxWidth + state.editor.layout.setLen(0) + state.runs.setLen(0) + state.runeSpans.setLen(state.editor.runes.len) + for index in state.runeSpans.mitems: + index = -1 + for index, span in state.spans: + let name = + if span.font.len > 0 and span.font in fonts: + span.font + else: + baseFont + let font = fonts[name] + resolvedFonts.add(font) + fontNames.add(name) + if span.first < state.editor.runes.len and span.last > max(0, span.first): + state.editor.lineHeight = max(state.editor.lineHeight, font.lineHeight) + baseline = max(baseline, font.ascent) + descent = min(descent, font.descent) + lineGap = max(lineGap, font.lineGap) + for i in max(0, span.first) ..< min(span.last, state.editor.runes.len): + state.runeSpans[i] = index + state.editor.lineHeight = max( + state.editor.lineHeight, + baseline - descent + lineGap + ) + var + advances = newSeq[float32](state.editor.runes.len) + kernings = newSeq[float32](state.editor.runes.len) + for i, rune in state.editor.runes: + if rune == LF: + continue + let font = resolvedFonts[state.runeSpans[i] + 1] + var entry: ptr LetterEntry + if rune == Tab: + if font.lookupLetter(Space, 0, entry): + advances[i] = entry.advance * 4 + continue + if font.lookupLetter(rune, 0, entry): + advances[i] = entry.advance + if i + 1 < state.editor.runes.len and state.editor.runes[i + 1] != LF and + font == resolvedFonts[state.runeSpans[i + 1] + 1]: + kernings[i] = font.lookupKerning(rune, state.editor.runes[i + 1]) + var position = vec2(0, 0) + for i, rune in state.editor.runes: + if rune == LF: + state.editor.layout.add(rect( + position.x, + position.y, + 0, + state.editor.lineHeight + )) + position.x = 0 + position.y += state.editor.lineHeight + continue + if state.editor.wordWrap and maxWidth < float32.high: + let wordStart = i == 0 or state.editor.runes[i - 1] in [Space, Tab, LF] + if wordStart and rune notin [Space, Tab] and position.x > 0: + var + wordWidth = 0.0'f + j = i + while j < state.editor.runes.len and + state.editor.runes[j] notin [Space, Tab, LF]: + wordWidth += advances[j] + if j + 1 < state.editor.runes.len and + state.editor.runes[j + 1] notin [Space, Tab, LF]: + wordWidth += kernings[j] + inc j + if position.x + wordWidth > maxWidth: + position.x = 0 + position.y += state.editor.lineHeight + if position.x > 0 and position.x + advances[i] > maxWidth: + position.x = 0 + position.y += state.editor.lineHeight + state.editor.layout.add(rect( + 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.editor.dirty = false + +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] + -1 + +proc drawSpanBackgrounds(sk: Silky, state: RichTextBoxState, origin: Vec2) = + ## Draws inline backgrounds before the native selection highlight. + for run in state.runs: + 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) + +proc drawBlocks( + sk: Silky, + state: RichTextBoxState, + origin: Vec2, + defaultColor: ColorRGBX +) = + ## Draws native block surfaces, borders, rules, and captions. + for i, bounds in state.blockLayouts: + let item = state.blocks[i] + if item.patch.len > 0: + sk.draw9Patch( + item.patch, + item.patchBorder, + origin + bounds.bounds.xy, + bounds.bounds.wh + ) + if item.quoteDepth > 0 and item.quoteThickness > 0 and + item.quoteColor.a > 0 and bounds.quoteBounds.w > 0: + let + scale = max(sk.uiScale, 0.001'f) + indent = max(0.0'f, item.quoteIndent) + position = origin + bounds.quoteBounds.xy + limit = floor((position.x + bounds.quoteBounds.w) * scale) / scale + top = round(position.y * scale) / scale + thickness = max(1.0'f, round(item.quoteThickness * scale)) / scale + continuation = clamp(item.quoteContinue, 0, item.quoteDepth) + for level in 0 ..< item.quoteDepth: + let + left = round((position.x + level.float32 * indent) * scale) / + scale + width = min(thickness, limit - left) + if width <= 0: + break + let + spacing = + if level < continuation: + max(0.0'f, item.spacing) + else: + 0.0'f + bottom = round( + (position.y + bounds.quoteBounds.h + spacing) * scale + ) / scale + sk.drawRect( + vec2(left, top), vec2(width, bottom - top), item.quoteColor + ) + if indent == 0: + break + if bounds.ruleBounds.h > 0: + if bounds.ruleBounds.w > 0 and item.ruleColor.a > 0: + let + scale = max(sk.uiScale, 0.001'f) + position = origin + bounds.ruleBounds.xy + left = round(position.x * scale) / scale + right = round((position.x + bounds.ruleBounds.w) * scale) / scale + top = round(position.y * scale) / scale + thickness = max(1.0'f, round(bounds.ruleBounds.h * scale)) / scale + sk.drawRect( + vec2(left, top), vec2(right - left, thickness), item.ruleColor + ) + continue + if item.label.len > 0: + let color = + if item.labelColor.a > 0: + item.labelColor + else: + defaultColor + discard sk.drawText( + bounds.labelFont, + item.label, + origin + bounds.labelPosition, + color, + maxWidth = max(0.0'f, bounds.bounds.w - item.padding.x * 2) + ) + +proc drawSpans( + sk: Silky, + state: RichTextBoxState, + origin: Vec2, + defaultColor: ColorRGBX +) = + ## Draws cached runs at their measured positions without wrapping again. + for run in state.runs: + let color = + if run.span >= 0 and state.spans[run.span].color.a > 0: + state.spans[run.span].color + else: + defaultColor + discard sk.drawText( + run.font, run.text, origin + run.position, color, clip = false + ) + if run.span >= 0: + let + span = state.spans[run.span] + underline = state.hoveredSpan >= 0 and span.linkId > 0 and + span.linkId == state.spans[state.hoveredSpan].linkId + if span.strikethrough or underline: + let + 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 + baseline = origin.y + run.position.y + font.ascent + thickness = max(1.0'f, round(scale)) / scale + if span.strikethrough: + let top = round((baseline - font.size * 0.3'f) * scale) / scale + sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) + if underline: + let top = round((baseline + 1) * scale) / scale + sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) + +proc richTextBox*( + sk: Silky, + window: Window, + id, text: string, + boxWidth, boxHeight: float32, + wrapWords = true, + spans: seq[TextSpan] = default(seq[TextSpan]), + blocks: seq[TextBlock] = default(seq[TextBlock]) +) {.measure.} = + ## Draws a read-only styled document with one selection and link handling. + if id notin richTextBoxStates: + richTextBoxStates[id] = newRichTextBoxState(text, wrapWords) + let + state = richTextBoxStates[id] + editor = state.editor + inputs = sk.textInputs + editor.enabled = false + state.activatedSpan = -1 + state.hoveredSpan = -1 + if editor.focused and state.focusEpoch != inputs.focusEpoch: + editor.focused = false + editor.dragging = false + editor.selector = editor.cursor + if state.spans != spans: + state.spans = spans + editor.dirty = true + if state.blocks != blocks: + state.blocks = blocks + editor.dirty = true + if editor.wordWrap != wrapWords: + editor.wordWrap = wrapWords + editor.dirty = true + if not state.sameText(text): + state.setText(text, preserveSelection = true) + 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 + if editor.dirty or editor.lastMaxWidth != innerRect.w or + state.lastFont != sk.textStyle: + state.computeLayout(sk.atlas.fonts, sk.textStyle, innerRect.w) + let + shift = window.buttonDown[KeyLeftShift] or + window.buttonDown[KeyRightShift] + mouseVec = sk.mousePos + mouseInside = mouseVec.overlaps(outerRect) and + mouseVec.overlaps(sk.clipRect) + onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) + if window.buttonPressed[MouseLeft]: + state.pressedSpan = -1 + if mouseInside and not onScrollbar: + editor.focused = true + let + localMouse = mouseVec - innerRect.xy + editor.scrollPos + now = epochTime() + if now - editor.lastClickTime < DoubleClickTime: + inc editor.clickCount + else: + editor.clickCount = 1 + editor.lastClickTime = now + case editor.clickCount + of 1: + editor.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) + of 3: + editor.selectParagraph(localMouse) + else: + editor.selectAll() + elif not mouseInside: + editor.focused = false + editor.dragging = false + editor.selector = editor.cursor + if state.pressedSpan >= 0: + let distance = mouseVec - state.pressPosition + if distance.x * distance.x + distance.y * distance.y > 9: + state.spanDragged = true + if window.buttonReleased[MouseLeft]: + let localMouse = mouseVec - innerRect.xy + editor.scrollPos + if mouseInside and not state.spanDragged and + editor.cursor == editor.selector and + state.spanAt(localMouse) == state.pressedSpan: + state.activatedSpan = state.pressedSpan + state.pressedSpan = -1 + 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]: + let localMouse = mouseVec - innerRect.xy + editor.scrollPos + editor.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) + 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 + overVerticalBar = editor.innerHeight > innerRect.h and + mouseVec.x >= outerRect.x + outerRect.w - 10 + overHorizontalBar = not editor.wordWrap and + editor.innerWidth > innerRect.w and + mouseVec.y >= outerRect.y + outerRect.h - 10 + if mouseInside and mouseVec.overlaps(innerRect) and + not editor.scrollingX and not editor.scrollingY and + not overVerticalBar and not overHorizontalBar: + let index = state.spanAt(mouseVec - innerRect.xy + editor.scrollPos) + if index >= 0 and state.spans[index].linkId > 0: + state.hoveredSpan = index + sk.cursor = Cursor(kind: PointerCursor) + let textColor = sk.theme.disabledTextColor + sk.draw9Patch( + "textbox.disabled.9patch", sk.theme.textboxPatch, outerRect.xy, outerRect.wh + ) + sk.pushClipRect(innerRect) + let textOrigin = innerRect.xy - editor.scrollPos + if state.blocks.len > 0: + sk.drawBlocks(state, textOrigin, textColor) + 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 + ) + 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) + sk.advance(vec2(boxWidth, boxHeight)) + +template richTextBox*( + id: string, + text: string, + boxWidth, boxHeight: float32, + wrapWords = true, + spans: seq[TextSpan] = default(seq[TextSpan]), + blocks: seq[TextBlock] = default(seq[TextBlock]) +) = + ## Draws a selectable read-only rich document using the current context. + sk.richTextBox( + window, + id, + text, + boxWidth, + boxHeight, + wrapWords, + spans, + blocks + ) diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index c520cb3d..4e17f198 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -38,7 +38,6 @@ const LF = Rune(10) CR = Rune(13) Space = Rune(32) - Tab = Rune(9) CursorWidth* = 2.0f DoubleClickTime = 0.4 SelectionColor = rgbx(30, 60, 130, 128) @@ -49,50 +48,6 @@ else: const TextBoxScrollSpeed = -10.0f type - TextSpan* = object - ## Read-only formatting over a half-open range of rune offsets. - first*, last*: int - font*: string - color*: ColorRGBX - background*: ColorRGBX - strikethrough*: bool - linkId*: int - ## Matching positive IDs group the styled parts of one hoverable link. - - TextBlock* = object - ## A styled block over a half-open range of shared rune offsets. - first*, last*: int - font*: string - padding*: Vec2 - spacing*: float32 - patch*: string - patchBorder*: int - label*, labelFont*: string - labelColor*: ColorRGBX - labelSpacing*: float32 - ruleColor*: ColorRGBX - ruleThickness*: float32 - ## Positive thickness turns an empty block into a horizontal rule. - quoteDepth*, quoteContinue*: int - ## Continued quote levels also draw their borders through spacing. - quoteIndent*: float32 = 16 - quoteColor*: ColorRGBX - quoteThickness*: float32 = 2 - - BlockLayout = object - bounds: Rect - ruleBounds: Rect - quoteBounds: Rect - labelPosition: Vec2 - labelFont: string - - TextRun = object - text: string - font: string - position: Vec2 - bounds: Rect - span: int - TextBoxState* = ref object ## State for a multi-line text box widget. runes*: seq[Rune] @@ -103,6 +58,10 @@ type focused*: bool focusEpoch: uint64 layout*: seq[Rect] + positionedLayout*: bool + ## Selection geometry may have variable line heights and gaps. + layoutHeight*: float32 + layoutCursor*: Rect dirty*: bool undoStack*: seq[(seq[Rune], int)] redoStack*: seq[(seq[Rune], int)] @@ -124,19 +83,7 @@ type password*: bool passwordChar*: Rune = Rune('*') allowedChars*: seq[Rune] - spans*: seq[TextSpan] - blocks*: seq[TextBlock] - activatedSpan*: int = -1 - hoveredSpan*: int = -1 - runeSpans: seq[int] - runs: seq[TextRun] - blockLayouts: seq[BlockLayout] - blockHeight: float32 - blockCursor: Rect - lastFont: string - pressedSpan: int = -1 - pressPosition: Vec2 - spanDragged: bool + lastFont: FontAtlas textCache: string textCacheValid: bool displayCache: string @@ -252,6 +199,10 @@ proc computeLayout*(state: TextBoxState, fontData: FontAtlas, maxWidth: float32) ## Computes per-character selection rectangles in local coordinates. ## Mirrors the glyph-walking logic from drawText but stores positions ## instead of emitting GPU vertices. + state.positionedLayout = false + state.layoutHeight = 0 + state.layoutCursor = rect(0, 0, 0, 0) + state.lastFont = fontData state.layout.setLen(0) state.lineHeight = fontData.lineHeight state.lastMaxWidth = maxWidth @@ -311,399 +262,6 @@ proc computeLayout*(state: TextBoxState, fontData: FontAtlas, maxWidth: float32) inc i state.dirty = false -proc computeLayout*( - state: TextBoxState, - fonts: Table[string, FontAtlas], - baseFont: string, - maxWidth: float32 -) - -proc computeBlocks( - state: TextBoxState, - fonts: Table[string, FontAtlas], - baseFont: string, - maxWidth: float32 -) = - ## Combines block layouts into one selectable document and native run list. - state.lineHeight = fonts[baseFont].lineHeight - state.lastMaxWidth = maxWidth - state.layout.setLen(state.runes.len) - state.runeSpans.setLen(state.runes.len) - state.runs.setLen(0) - state.blockLayouts.setLen(0) - state.blockHeight = 0 - for index in state.runeSpans.mitems: - index = -1 - var - covered = 0 - previousEnd = rect(0, 0, 0, state.lineHeight) - for item in state.blocks: - let - first = clamp(item.first, covered, state.runes.len) - last = clamp(item.last, first, state.runes.len) - width = max(0.0'f, maxWidth) - depth = max(0, item.quoteDepth) - padding = vec2( - if depth > 0: - min(max(0.0'f, item.padding.x), width / 2) - else: - max(0.0'f, item.padding.x), - max(0.0'f, item.padding.y) - ) - quoteInset = min( - max(0.0'f, width - padding.x * 2), - depth.float32 * max(0.0'f, item.quoteIndent) - ) - blockWidth = width - quoteInset - for i in covered ..< first: - state.layout[i] = previousEnd - if first == last and item.ruleThickness > 0: - let - origin = vec2(quoteInset + padding.x, state.blockHeight + padding.y) - height = item.ruleThickness + padding.y * 2 - state.blockLayouts.add(BlockLayout( - bounds: rect(quoteInset, state.blockHeight, blockWidth, height), - ruleBounds: rect( - origin, - vec2(max(0.0'f, blockWidth - padding.x * 2), item.ruleThickness) - ), - quoteBounds: rect( - padding.x, state.blockHeight, max(0.0'f, width - padding.x * 2), - height - ) - )) - state.blockCursor = rect(origin, vec2(0)) - state.blockHeight += height + max(0.0'f, item.spacing) - previousEnd = state.blockCursor - covered = last - continue - let - font = - if item.font in fonts: - item.font - else: - baseFont - labelFont = - if item.labelFont in fonts: - item.labelFont - else: - baseFont - labelHeight = - if item.label.len > 0: - fonts[labelFont].lineHeight + max(0.0'f, item.labelSpacing) - else: - 0.0'f - origin = vec2( - quoteInset + padding.x, state.blockHeight + padding.y + labelHeight - ) - local = TextBoxState( - runes: state.runes[first ..< last], - wordWrap: state.wordWrap, - spans: @[TextSpan()] - ) - var spanIndices = @[-1] - for index, span in state.spans: - if span.first < last and span.last > first: - var relative = span - relative.first = max(first, span.first) - first - relative.last = min(last, span.last) - first - local.spans.add(relative) - spanIndices.add(index) - local.computeLayout(fonts, font, max(0.0'f, blockWidth - padding.x * 2)) - var contentHeight = local.lineHeight - for i, bounds in local.layout: - state.layout[first + i] = rect(origin + bounds.xy, bounds.wh) - let span = local.runeSpans[i] - if span >= 0: - state.runeSpans[first + i] = spanIndices[span] - for run in local.runs.mitems: - run.position += origin - run.bounds.x += origin.x - run.bounds.y += origin.y - if run.span >= 0: - run.span = spanIndices[run.span] - state.runs.add(run) - state.blockCursor = rect(origin.x, origin.y, 0, local.lineHeight) - if local.layout.len > 0: - let bounds = local.layout[^1] - contentHeight = bounds.y + bounds.h - state.blockCursor = rect( - origin.x + bounds.x + bounds.w, - origin.y + bounds.y, - 0, - bounds.h - ) - if local.runes[^1] == LF: - contentHeight += local.lineHeight - state.blockCursor.x = origin.x - state.blockCursor.y += local.lineHeight - let height = contentHeight + padding.y * 2 + labelHeight - state.blockLayouts.add(BlockLayout( - bounds: rect(quoteInset, state.blockHeight, blockWidth, height), - quoteBounds: rect( - padding.x, state.blockHeight, max(0.0'f, width - padding.x * 2), - height - ), - labelPosition: vec2( - quoteInset + padding.x, state.blockHeight + padding.y - ), - labelFont: labelFont - )) - state.blockHeight += height + max(0.0'f, item.spacing) - previousEnd = state.blockCursor - covered = last - for i in covered ..< state.runes.len: - state.layout[i] = previousEnd - state.dirty = false - -proc computeLayout*( - state: TextBoxState, - fonts: Table[string, FontAtlas], - baseFont: string, - maxWidth: float32 -) = - ## Lays out styled text with the same glyph positions used for selection. - state.lastFont = baseFont - if state.blocks.len > 0: - state.computeBlocks(fonts, baseFont, maxWidth) - return - state.blockLayouts.setLen(0) - state.blockHeight = 0 - if state.spans.len == 0: - state.runeSpans.setLen(0) - state.runs.setLen(0) - state.computeLayout(fonts[baseFont], maxWidth) - return - let base = fonts[baseFont] - var - resolvedFonts = @[base] - fontNames = @[baseFont] - baseline = base.ascent - descent = base.descent - lineGap = base.lineGap - state.lineHeight = base.lineHeight - state.lastMaxWidth = maxWidth - state.layout.setLen(0) - state.runs.setLen(0) - state.runeSpans.setLen(state.runes.len) - for index in state.runeSpans.mitems: - index = -1 - for index, span in state.spans: - let name = - if span.font.len > 0 and span.font in fonts: - span.font - else: - baseFont - let font = fonts[name] - resolvedFonts.add(font) - fontNames.add(name) - if span.first < state.runes.len and span.last > max(0, span.first): - state.lineHeight = max(state.lineHeight, font.lineHeight) - baseline = max(baseline, font.ascent) - descent = min(descent, font.descent) - lineGap = max(lineGap, font.lineGap) - for i in max(0, span.first) ..< min(span.last, state.runes.len): - state.runeSpans[i] = index - state.lineHeight = max(state.lineHeight, baseline - descent + lineGap) - var - advances = newSeq[float32](state.runes.len) - kernings = newSeq[float32](state.runes.len) - for i, rune in state.runes: - if rune == LF: - continue - let font = resolvedFonts[state.runeSpans[i] + 1] - var entry: ptr LetterEntry - if rune == Tab: - if font.lookupLetter(Space, 0, entry): - advances[i] = entry.advance * 4 - continue - if font.lookupLetter(rune, 0, entry): - advances[i] = entry.advance - if i + 1 < state.runes.len and state.runes[i + 1] != LF and - font == resolvedFonts[state.runeSpans[i + 1] + 1]: - kernings[i] = font.lookupKerning(rune, state.runes[i + 1]) - var position = vec2(0, 0) - for i, rune in state.runes: - if rune == LF: - state.layout.add(rect(position.x, position.y, 0, state.lineHeight)) - position.x = 0 - position.y += state.lineHeight - continue - if state.wordWrap and maxWidth < float32.high: - let wordStart = i == 0 or state.runes[i - 1] in [Space, Tab, LF] - if wordStart and rune notin [Space, Tab] and position.x > 0: - var - wordWidth = 0.0'f - j = i - while j < state.runes.len and state.runes[j] notin [Space, Tab, LF]: - wordWidth += advances[j] - if j + 1 < state.runes.len and - state.runes[j + 1] notin [Space, Tab, LF]: - wordWidth += kernings[j] - inc j - if position.x + wordWidth > maxWidth: - position.x = 0 - position.y += state.lineHeight - if position.x > 0 and position.x + advances[i] > maxWidth: - position.x = 0 - position.y += state.lineHeight - state.layout.add(rect( - position.x, position.y, advances[i], state.lineHeight - )) - position.x += advances[i] + kernings[i] - var i = 0 - while i < state.runes.len: - if state.runes[i] in [LF, Tab]: - inc i - continue - let - first = i - span = state.runeSpans[i] - font = resolvedFonts[span + 1] - bounds = state.layout[i] - var text = "" - while i < state.runes.len and state.runes[i] notin [LF, Tab] and - state.runeSpans[i] == span and state.layout[i].y == bounds.y: - text.add($state.runes[i]) - inc i - let last = state.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.dirty = false - -proc spanAt(state: TextBoxState, position: Vec2): int = - ## Finds a formatted span only when the pointer touches its glyph bounds. - for i, bounds in state.layout: - if position.overlaps(bounds) and i < state.runeSpans.len: - return state.runeSpans[i] - -1 - -proc drawSpanBackgrounds(sk: Silky, state: TextBoxState, origin: Vec2) = - ## Draws inline backgrounds before the native selection highlight. - for run in state.runs: - 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) - -proc drawBlocks( - sk: Silky, - state: TextBoxState, - origin: Vec2, - defaultColor: ColorRGBX -) = - ## Draws native block surfaces, borders, rules, and captions. - for i, bounds in state.blockLayouts: - let item = state.blocks[i] - if item.patch.len > 0: - sk.draw9Patch( - item.patch, - item.patchBorder, - origin + bounds.bounds.xy, - bounds.bounds.wh - ) - if item.quoteDepth > 0 and item.quoteThickness > 0 and - item.quoteColor.a > 0 and bounds.quoteBounds.w > 0: - let - scale = max(sk.uiScale, 0.001'f) - indent = max(0.0'f, item.quoteIndent) - position = origin + bounds.quoteBounds.xy - limit = floor((position.x + bounds.quoteBounds.w) * scale) / scale - top = round(position.y * scale) / scale - thickness = max(1.0'f, round(item.quoteThickness * scale)) / scale - continuation = clamp(item.quoteContinue, 0, item.quoteDepth) - for level in 0 ..< item.quoteDepth: - let - left = round((position.x + level.float32 * indent) * scale) / - scale - width = min(thickness, limit - left) - if width <= 0: - break - let - spacing = - if level < continuation: - max(0.0'f, item.spacing) - else: - 0.0'f - bottom = round( - (position.y + bounds.quoteBounds.h + spacing) * scale - ) / scale - sk.drawRect( - vec2(left, top), vec2(width, bottom - top), item.quoteColor - ) - if indent == 0: - break - if bounds.ruleBounds.h > 0: - if bounds.ruleBounds.w > 0 and item.ruleColor.a > 0: - let - scale = max(sk.uiScale, 0.001'f) - position = origin + bounds.ruleBounds.xy - left = round(position.x * scale) / scale - right = round((position.x + bounds.ruleBounds.w) * scale) / scale - top = round(position.y * scale) / scale - thickness = max(1.0'f, round(bounds.ruleBounds.h * scale)) / scale - sk.drawRect( - vec2(left, top), vec2(right - left, thickness), item.ruleColor - ) - continue - if item.label.len > 0: - let color = - if item.labelColor.a > 0: - item.labelColor - else: - defaultColor - discard sk.drawText( - bounds.labelFont, - item.label, - origin + bounds.labelPosition, - color, - maxWidth = max(0.0'f, bounds.bounds.w - item.padding.x * 2) - ) - -proc drawSpans( - sk: Silky, - state: TextBoxState, - origin: Vec2, - defaultColor: ColorRGBX -) = - ## Draws cached runs at their measured positions without wrapping again. - for run in state.runs: - let color = - if run.span >= 0 and state.spans[run.span].color.a > 0: - state.spans[run.span].color - else: - defaultColor - discard sk.drawText( - run.font, run.text, origin + run.position, color, clip = false - ) - if run.span >= 0: - let - span = state.spans[run.span] - underline = state.hoveredSpan >= 0 and span.linkId > 0 and - span.linkId == state.spans[state.hoveredSpan].linkId - if span.strikethrough or underline: - let - 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 - baseline = origin.y + run.position.y + font.ascent - thickness = max(1.0'f, round(scale)) / scale - if span.strikethrough: - let top = round((baseline - font.size * 0.3'f) * scale) / scale - sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) - if underline: - let top = round((baseline + 1) * scale) / scale - sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) - proc pickGlyphAt*(state: TextBoxState, pos: Vec2): int = ## Finds the character index closest to the given position. ## Returns -1 if no character found on that line. @@ -715,7 +273,7 @@ proc pickGlyphAt*(state: TextBoxState, pos: Vec2): int = if minDistance < 0 or dist < minDistance: minDistance = dist minGlyph = i - if minGlyph < 0 and state.blocks.len > 0: + if minGlyph < 0 and state.positionedLayout: var nearestY = float32.high for i, bounds in state.layout: let @@ -745,8 +303,8 @@ proc getSelectionRects*(layout: seq[Rect], start, stop: int): seq[Rect] = proc innerHeight*(state: TextBoxState): float32 = ## Returns the total content height. - if state.blocks.len > 0: - return state.blockHeight + if state.positionedLayout: + return state.layoutHeight if state.layout.len > 0: let lastPos = state.layout[^1] return lastPos.y + lastPos.h @@ -761,9 +319,9 @@ proc innerWidth*(state: TextBoxState): float32 = proc locationRect*(state: TextBoxState, loc: int): Rect = ## Returns the rectangle where the cursor should be drawn. - if state.blocks.len > 0: + if state.positionedLayout: if loc >= state.layout.len: - result = state.blockCursor + result = state.layoutCursor elif loc >= 0: result = state.layout[loc] result.w = CursorWidth @@ -1009,7 +567,7 @@ proc right*(state: TextBoxState, shift = false) = state.resetBlink() proc adjacentLine(state: TextBoxState, forward: bool): int = - ## Finds a neighboring visual line when document blocks vary in height. + ## Finds a neighboring visual line when cached lines vary in height. let currentY = state.cursorPos.y var nearest = float32.high @@ -1035,7 +593,7 @@ proc down*(state: TextBoxState, shift = false) = let curPos = state.cursorPos index = - if state.blocks.len > 0: + if state.positionedLayout: state.adjacentLine(true) else: state.pickGlyphAt( @@ -1058,7 +616,7 @@ proc up*(state: TextBoxState, shift = false) = let curPos = state.cursorPos index = - if state.blocks.len > 0: + if state.positionedLayout: state.adjacentLine(false) else: state.pickGlyphAt( @@ -1317,14 +875,30 @@ proc handleKey(state: TextBoxState, event: InputEvent) = else: discard +proc handleSelectionInput*(state: TextBoxState, inputs: TextInputs) = + ## Drains read-only navigation and copy events without accepting edits. + assert not state.enabled + let + epoch = inputs.focusEpoch + events = inputs.takeInput() + for event in events: + if inputs.focusEpoch != epoch: + break + if event.kind == InputKind.KeyDown: + state.handleKey(event) + if events.len > 0: + state.scrollToCursor() + proc handleInput( state: TextBoxState, inputs: TextInputs, - fonts: Table[string, FontAtlas], - baseFont: string, + fontData: FontAtlas, maxWidth: float32 ) = ## Drains ordered input and refreshes layout before cursor navigation. + if not state.enabled: + state.handleSelectionInput(inputs) + return let epoch = inputs.focusEpoch events = inputs.takeInput() @@ -1353,13 +927,13 @@ proc handleInput( KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, KeyPageUp, KeyPageDown }: - state.computeLayout(fonts, baseFont, maxWidth) + state.computeLayout(fontData, maxWidth) state.handleKey(event) of InputKind.KeyUp: discard if events.len > 0: if state.dirty: - state.computeLayout(fonts, baseFont, maxWidth) + state.computeLayout(fontData, maxWidth) state.scrollToCursor() proc drawScrollbars*(sk: Silky, state: TextBoxState, window: Window, @@ -1446,9 +1020,7 @@ proc textBox*( password: bool = false, passwordChar: Rune = Rune('*'), allowedChars: seq[Rune] = default(seq[Rune]), - submitOnEnter: bool = false, - spans: seq[TextSpan] = default(seq[TextSpan]), - blocks: seq[TextBlock] = default(seq[TextBlock]) + submitOnEnter: bool = false ) {.measure.} = ## Text box widget with editing, selection, and scroll. ## When disabled, text can be selected and copied but not modified. @@ -1467,8 +1039,6 @@ proc textBox*( state = textBoxStates[id] state.submitOnEnter = submitOnEnter state.submitted = false - state.activatedSpan = -1 - state.hoveredSpan = -1 let inputs = sk.textInputs if state.focused and state.focusEpoch != inputs.focusEpoch: state.focused = false @@ -1477,23 +1047,6 @@ proc textBox*( state.selector = state.cursor state.enabled = enabled state.allowedChars = allowedChars - let - activeSpans = - if not enabled and not password: - spans - else: - default(seq[TextSpan]) - activeBlocks = - if not enabled and not password and not singleLine: - blocks - else: - default(seq[TextBlock]) - if state.spans != activeSpans: - state.spans = activeSpans - state.dirty = true - if state.blocks != activeBlocks: - state.blocks = activeBlocks - state.dirty = true if state.password != password: state.password = password state.dirty = true @@ -1521,8 +1074,8 @@ proc textBox*( ) state.boxSize = vec2(innerRect.w, innerRect.h) if state.dirty or state.layout.len == 0 or - state.lastMaxWidth != innerRect.w or state.lastFont != sk.textStyle: - state.computeLayout(sk.atlas.fonts, sk.textStyle, innerRect.w) + state.lastMaxWidth != innerRect.w or state.lastFont != sk.atlas.fonts[sk.textStyle]: + state.computeLayout(sk.atlas.fonts[sk.textStyle], innerRect.w) let shift = window.buttonDown[KeyLeftShift] or window.buttonDown[KeyRightShift] let mouseVec = sk.mousePos @@ -1530,7 +1083,6 @@ proc textBox*( mouseVec.overlaps(sk.clipRect) let onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) if window.buttonPressed[MouseLeft]: - state.pressedSpan = -1 if mouseInside and not onScrollbar: state.focused = true let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -1544,10 +1096,6 @@ proc textBox*( of 1: state.mouseAction(localMouse, click = true, shift = shift) state.dragging = true - if not enabled and not shift: - state.pressedSpan = state.spanAt(localMouse) - state.pressPosition = mouseVec - state.spanDragged = false of 2: state.selectWord(localMouse) of 3: state.selectParagraph(localMouse) else: state.selectAll() @@ -1556,19 +1104,6 @@ proc textBox*( state.dragging = false if not enabled: state.selector = state.cursor - if state.pressedSpan >= 0: - let distance = mouseVec - state.pressPosition - if distance.x * distance.x + distance.y * distance.y > 9: - state.spanDragged = true - if window.buttonReleased[MouseLeft]: - let localMouse = mouseVec - innerRect.xy + state.scrollPos - if mouseInside and not state.spanDragged and - state.cursor == state.selector and - state.spanAt(localMouse) == state.pressedSpan: - state.activatedSpan = state.pressedSpan - state.pressedSpan = -1 - elif not window.buttonDown[MouseLeft]: - state.pressedSpan = -1 if state.dragging and not state.scrollingX and not state.scrollingY: if window.buttonDown[MouseLeft] and not window.buttonPressed[MouseLeft]: let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -1578,29 +1113,16 @@ proc textBox*( inputs.submitInput(window, id, state.focused, enabled) if state.focused: state.focusEpoch = inputs.focusEpoch - state.handleInput(inputs, sk.atlas.fonts, sk.textStyle, innerRect.w) + state.handleInput(inputs, sk.atlas.fonts[sk.textStyle], innerRect.w) t = state.getText() if state.dirty: - state.computeLayout(sk.atlas.fonts, sk.textStyle, innerRect.w) + state.computeLayout(sk.atlas.fonts[sk.textStyle], innerRect.w) let maxScrollY = max(0.0f, state.innerHeight - innerRect.h) state.scrollPos.y = clamp(state.scrollPos.y, 0.0f, maxScrollY) if state.wordWrap: state.scrollPos.x = 0 else: state.scrollPos.x = max(0.0f, state.scrollPos.x) - let - overVerticalBar = state.innerHeight > innerRect.h and - mouseVec.x >= outerRect.x + outerRect.w - 10 - overHorizontalBar = not state.wordWrap and - state.innerWidth > innerRect.w and - mouseVec.y >= outerRect.y + outerRect.h - 10 - if mouseInside and mouseVec.overlaps(innerRect) and - not state.scrollingX and not state.scrollingY and - not overVerticalBar and not overHorizontalBar: - let index = state.spanAt(mouseVec - innerRect.xy + state.scrollPos) - if index >= 0 and state.spans[index].linkId > 0: - state.hoveredSpan = index - sk.cursor = Cursor(kind: PointerCursor) let patch = if error: "textbox.error.9patch" elif not enabled: "textbox.disabled.9patch" @@ -1616,10 +1138,6 @@ proc textBox*( sk.draw9Patch(patch, sk.theme.textboxPatch, outerRect.xy, outerRect.wh) sk.pushClipRect(innerRect) let textOrigin = innerRect.xy - state.scrollPos - if state.blocks.len > 0: - sk.drawBlocks(state, textOrigin, textColor) - if state.spans.len > 0: - sk.drawSpanBackgrounds(state, textOrigin) if state.cursor != state.selector: let sel = state.selection let selRects = getSelectionRects(state.layout, sel.a, sel.b) @@ -1627,18 +1145,15 @@ proc textBox*( sk.drawRect( vec2(textOrigin.x + r.x, textOrigin.y + r.y), vec2(r.w, r.h), SelectionColor) - if state.spans.len > 0 or state.blocks.len > 0: - sk.drawSpans(state, textOrigin, textColor) - else: - discard sk.drawText( - sk.textStyle, - state.displayText, - textOrigin, - textColor, - maxWidth = innerRect.w, - wordWrap = state.wordWrap, - clip = false - ) + discard sk.drawText( + sk.textStyle, + state.displayText, + textOrigin, + textColor, + maxWidth = innerRect.w, + wordWrap = state.wordWrap, + clip = false + ) if state.focused and state.cursorVisible: let cr = state.locationRect(state.cursor) sk.drawRect( @@ -1690,16 +1205,12 @@ template textBox*( isPassword = false, passChar: Rune = Rune('*'), chars: seq[Rune] = default(seq[Rune]), - submitOnEnter = false, - spans: seq[TextSpan] = default(seq[TextSpan]), - blocks: seq[TextBlock] = default(seq[TextBlock]) + submitOnEnter = false ) = ## Text box widget. Set singleLine for a single-line input. ## submitOnEnter reports Enter in state.submitted and preserves Shift+Enter. - ## Read-only spans preserve selection and report clicks in activatedSpan. sk.textBox(window, id, t, boxWidth, boxHeight, wrapWords, singleLine, - isEnabled, isError, isPassword, passChar, chars, submitOnEnter, spans, - blocks + isEnabled, isError, isPassword, passChar, chars, submitOnEnter ) template textInput*( diff --git a/tests/test_decorations.nim b/tests/test_decorations.nim index 8da10aeb..b287c8fa 100644 --- a/tests/test_decorations.nim +++ b/tests/test_decorations.nim @@ -44,6 +44,30 @@ proc rules(sk: Silky): seq[Rect] = vertices[i + 2].pos - vertices[i].pos )) +proc glyphCount(sk: Silky, glyph: string): int = + ## Counts native glyph quads without depending on block decorations. + let + entry = sk.atlas.fonts["Default"].entries[glyph][0] + uv = vec2(entry.x.float32, entry.y.float32) + vertices = sk.drawer.layers[NormalLayer] + for i in countup(0, vertices.high, 6): + if vertices[i].uv == uv: + inc result + +proc transition( + sk: Silky, + text: string, + blocks: seq[TextBlock] = @[] +): RichTextBoxState = + ## Redraws one rich widget as its source and formatting change. + sk.drawer.layers[NormalLayer].setLen(0) + sk.at = vec2(10.17'f, 20.29'f) + sk.richTextBox( + 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() @@ -59,44 +83,45 @@ block: pixelScale = density ) doAssert builder.addImage("textbox.disabled.9patch", newImage(16, 16)) - let sk = fixture(builder, density) - var + let + sk = fixture(builder, density) text = "WW WW WW" - spans = @[ - TextSpan( - first: 0, - last: text.runeLen, - strikethrough: true, - color: TextColor, - linkId: 1 - ) - ] + var spans = @[ + TextSpan( + first: 0, + last: text.runeLen, + strikethrough: true, + color: TextColor, + linkId: 1 + ) + ] sk.at = origin sk.mousePos = vec2(-1) - sk.textBox( + sk.richTextBox( window, "decorations", text, 64, 220, - wrapWords = true, enabled = false, spans = spans + wrapWords = true, spans = spans ) let - state = textBoxStates["decorations"] + state = richTextBoxStates["decorations"] strikeRules = sk.rules() doAssert strikeRules.len == 3 for i, rule in strikeRules: - let line = origin.y + state.layout[i * 3].y + let line = origin.y + state.editor.layout[i * 3].y doAssert rule.y > line - doAssert rule.y + rule.h < line + state.lineHeight + doAssert rule.y + rule.h < line + state.editor.lineHeight doAssert rule.w <= 64 doAssert close(rule.h * density, max(1.0'f, round(density))) - state.selectAll() - doAssert state.copyText() == text - state.selector = state.cursor + state.editor.selectAll() + doAssert state.editor.copyText() == text + state.editor.selector = state.editor.cursor sk.drawer.layers[NormalLayer].setLen(0) sk.at = origin - sk.mousePos = origin + state.layout[0].xy + state.layout[0].wh / 2 - sk.textBox( + sk.mousePos = origin + state.editor.layout[0].xy + + state.editor.layout[0].wh / 2 + sk.richTextBox( window, "decorations", text, 64, 220, - wrapWords = true, enabled = false, spans = spans + wrapWords = true, spans = spans ) let hoveredRules = sk.rules() doAssert hoveredRules.len == strikeRules.len * 2 @@ -108,11 +133,53 @@ block: sk.at = origin sk.mousePos = vec2(-1) spans[0].strikethrough = false - sk.textBox( + sk.richTextBox( window, "decorations", text, 64, 220, - wrapWords = true, enabled = false, spans = spans + wrapWords = true, spans = spans ) doAssert sk.rules().len == 0 - textBoxStates.del("decorations") + richTextBoxStates.del("decorations") + +block: + echo "Testing rich formatting removal retains native text rendering" + privateAccess(RichTextBoxState) + let builder = newAtlasBuilder(256, 2) + builder.addFont( + FontPath, "Default", 18, @["W"], pixelScale = 2 + ) + doAssert builder.addImage("textbox.disabled.9patch", newImage(16, 16)) + let + sk = fixture(builder, 2) + font = builder.atlas.fonts["Default"] + state = sk.transition("WW", @[ + TextBlock( + first: 0, last: 2, padding: vec2(12, 6), spacing: 8, + quoteDepth: 1, quoteColor: TextColor + ), + TextBlock( + first: 2, last: 2, padding: vec2(12, 6), + ruleColor: TextColor, ruleThickness: 1 + ) + ]) + doAssert sk.glyphCount("W") == 2 + doAssert state.innerHeight > font.lineHeight + doAssert state.editor.layout[0].x > 0 + doAssert state.editor.locationRect(2).h == 0 + + doAssert sk.transition("WW") == state + doAssert sk.glyphCount("W") == 2, + "A rich widget with no spans or blocks must still draw its text." + doAssert state.editor.layout[0].xy == vec2(0) + doAssert close(state.innerHeight, font.lineHeight) + doAssert close(state.editor.locationRect(2).h, font.lineHeight) + + doAssert sk.transition("") == state + doAssert sk.glyphCount("W") == 0 + doAssert state.runs.len == 0 + doAssert state.editor.layout.len == 0 + doAssert state.editor.cursor == 0 and state.editor.selector == 0 + doAssert close(state.innerHeight, font.lineHeight) + doAssert close(state.editor.locationRect(0).h, font.lineHeight) + richTextBoxStates.del("transitions") echo "All text decoration tests passed." diff --git a/tests/test_inputs.nim b/tests/test_inputs.nim index e0571fd2..0bdc2742 100644 --- a/tests/test_inputs.nim +++ b/tests/test_inputs.nim @@ -13,6 +13,7 @@ type Fixture = object singleLine: bool submitOnEnter: bool enabled: bool + rich: bool password: bool allowedChars: seq[Rune] spans: seq[TextSpan] @@ -69,29 +70,40 @@ proc frame(f: var Fixture, visible = true, duplicate = false) = sk.pushClipRect(f.clip) for i in 0 .. ord(duplicate): sk.at = vec2(20, 20) - sk.textBox( - window, - f.id, - f.text, - 240, - f.height, - wrapWords = true, - singleLine = f.singleLine, - enabled = f.enabled, - password = f.password, - allowedChars = f.allowedChars, - submitOnEnter = f.submitOnEnter, - spans = f.spans, - blocks = f.blocks - ) + if f.rich: + sk.richTextBox( + window, f.id, f.text, 240, f.height, + wrapWords = true, spans = f.spans, blocks = f.blocks + ) + else: + sk.textBox( + window, + f.id, + f.text, + 240, + f.height, + wrapWords = true, + singleLine = f.singleLine, + enabled = f.enabled, + password = f.password, + allowedChars = f.allowedChars, + submitOnEnter = f.submitOnEnter + ) if f.clip.w > 0: sk.popClipRect() f.harness.endFrame() f.harness.window.resetInputState() proc state(f: Fixture): TextBoxState = - ## Returns the text state belonging to a fixture. - textBoxStates[f.id] + ## Returns the selection editor belonging to either widget kind. + if f.rich: + richTextBoxStates[f.id].editor + else: + textBoxStates[f.id] + +proc richState(f: Fixture): RichTextBoxState = + ## Returns formatting and link state owned only by the rich widget. + richTextBoxStates[f.id] proc hoverGlyph(f: var Fixture, index: int) = ## Moves the pointer over a visible laid-out glyph in the current view. @@ -664,7 +676,7 @@ block: block: echo "Testing read-only styled text retains selection and copy" var f = fixture("é code 世界") - f.enabled = false + f.rich = true f.singleLine = false f.spans = @[TextSpan(first: 2, last: 6, font: "Wide")] f.focus() @@ -680,17 +692,30 @@ block: doAssert getClipboardString() == f.text doAssert f.state.selection == (0 .. f.text.runeLen) doAssert f.state.layout[2].w == styledWidth - f.enabled = true + window.onTextInput("Ignored native commit") + window.onTextEdit(TextInputEdit( + kind: ReplaceText, start: 0, length: f.text.runeLen, text: "Ignored edit" + )) + setClipboardString("Ignored paste") + window.shortcut(KeyV) f.frame() + doAssert f.richState.getText() == "é code 世界" + doAssert f.state.undoStack.len == 0 + let rich = f.richState + f.rich = false + f.focus() + doAssert f.state != rich.editor doAssert f.state.layout[2].w < styledWidth + window.shortcut(KeyA) window.typeText("Editable") f.frame() doAssert f.text == "Editable" + doAssert rich.getText() == "é code 世界" block: echo "Testing styled span clicks activate only without dragging" var f = fixture("Click here") - f.enabled = false + f.rich = true f.spans = @[TextSpan(first: 0, last: f.text.runeLen, font: "Wide")] f.frame() let @@ -702,12 +727,12 @@ block: window.moveMouse(x, y) window.pressButton(MouseLeft) f.frame() - doAssert f.state.activatedSpan == -1 + doAssert f.richState.activatedSpan == -1 window.releaseButton(MouseLeft) f.frame() - doAssert f.state.activatedSpan == 0 + doAssert f.richState.activatedSpan == 0 f.frame() - doAssert f.state.activatedSpan == -1 + doAssert f.richState.activatedSpan == -1 f.state.lastClickTime = 0 window.pressButton(MouseLeft) f.frame() @@ -716,32 +741,32 @@ block: window.moveMouse(x, y) window.releaseButton(MouseLeft) f.frame() - doAssert f.state.activatedSpan == -1 + doAssert f.richState.activatedSpan == -1 block: echo "Testing link hover cursor and non-link text boundaries" var f = fixture("Link bold text") - f.enabled = false + f.rich = true f.spans = @[ TextSpan(first: 0, last: 4, linkId: 1), TextSpan(first: 5, last: 9, font: "Wide") ] f.frame() f.hoverGlyph(1) - doAssert f.state.hoveredSpan == 0 + doAssert f.richState.hoveredSpan == 0 doAssert f.harness.window.cursor.kind == PointerCursor f.hoverGlyph(6) - doAssert f.state.hoveredSpan == -1 + doAssert f.richState.hoveredSpan == -1 doAssert f.harness.window.cursor.kind == ArrowCursor f.hoverGlyph(1) f.harness.window.moveMouse(21, 21) f.frame() - doAssert f.state.hoveredSpan == -1 + doAssert f.richState.hoveredSpan == -1 doAssert f.harness.window.cursor.kind == ArrowCursor f.hoverGlyph(1) f.harness.window.moveMouse(600, 400) f.frame() - doAssert f.state.hoveredSpan == -1 + doAssert f.richState.hoveredSpan == -1 doAssert f.harness.window.cursor.kind == ArrowCursor f.hoverGlyph(1) f.frame(visible = false) @@ -752,7 +777,7 @@ block: var f = fixture( "A long linked sentence that wraps onto several lines in this text box." ) - f.enabled = false + f.rich = true f.singleLine = false f.spans = @[ TextSpan(first: 0, last: f.text.runeLen, font: "Wide", linkId: 1) @@ -765,27 +790,27 @@ block: break doAssert secondLine >= 0 f.hoverGlyph(secondLine) - doAssert f.state.hoveredSpan == 0 + doAssert f.richState.hoveredSpan == 0 doAssert f.harness.window.cursor.kind == PointerCursor f.clip = rect(20, 20, 240, 20) f.frame() - doAssert f.state.hoveredSpan == -1 + doAssert f.richState.hoveredSpan == -1 doAssert f.harness.window.cursor.kind == ArrowCursor f.clip = rect(0, 0, 0, 0) f.state.scrollPos.y = f.state.lineHeight f.hoverGlyph(secondLine) - doAssert f.state.hoveredSpan == 0 + doAssert f.richState.hoveredSpan == 0 doAssert f.harness.window.cursor.kind == PointerCursor f.spans[0].linkId = 0 f.frame() - doAssert f.state.hoveredSpan == -1 + doAssert f.richState.hoveredSpan == -1 doAssert f.harness.window.cursor.kind == ArrowCursor f.spans[0].linkId = 1 f.frame() - doAssert f.state.hoveredSpan == 0 + doAssert f.richState.hoveredSpan == 0 f.spans.setLen(0) f.frame() - doAssert f.state.hoveredSpan == -1 + doAssert f.richState.hoveredSpan == -1 doAssert f.harness.window.cursor.kind == ArrowCursor block: @@ -820,7 +845,7 @@ block: echo "Testing one block widget selects and copies across all sections" const Sample = "Title\nBody link\ncode()" var f = fixture(Sample) - f.enabled = false + f.rich = true f.singleLine = false f.height = 240 f.blocks = @[ @@ -857,12 +882,12 @@ block: echo "Testing block links retain hover, activation, and drag selection" f.hoverGlyph(12) - doAssert f.state.hoveredSpan == 0 + doAssert f.richState.hoveredSpan == 0 doAssert window.cursor.kind == PointerCursor f.state.lastClickTime = 0 window.tap(MouseLeft) f.frame() - doAssert f.state.activatedSpan == 0 + doAssert f.richState.activatedSpan == 0 f.state.lastClickTime = 0 window.pressButton(MouseLeft) f.frame() @@ -870,7 +895,7 @@ block: f.frame() window.releaseButton(MouseLeft) f.frame() - doAssert f.state.activatedSpan == -1 + doAssert f.richState.activatedSpan == -1 doAssert f.state.selection.a == 0 doAssert f.state.selection.b >= 11 @@ -910,6 +935,96 @@ block: doAssert not f.state.focused doAssert f.state.cursor == f.state.selector +block: + echo "Testing same-id plain and rich widgets isolate state and focus" + const RichSource = "Read only reply" + for reverse in [false, true]: + let id = "shared-widget-" & $reverse + var + harness = newTestHarness(atlas) + plain = "Editable" + + proc renderBoth(sk: Silky, window: Window) = + ## Draws independent widgets with the same public identifier. + template plainWidget() = + ## Draws the editable surface below the rich reply. + sk.at = vec2(20, 150) + sk.textBox(window, id, plain, 240, 80, wrapWords = true) + + template richWidget() = + ## Draws a read-only surface without borrowing plain widget state. + sk.at = vec2(20, 20) + sk.richTextBox( + window, id, RichSource, 240, 80, + spans = @[TextSpan(first: 0, last: RichSource.runeLen, font: "Wide")] + ) + + if reverse: + plainWidget() + richWidget() + else: + richWidget() + plainWidget() + + discard harness.pumpFrame(renderBoth) + let + window = harness.window + editor = textBoxStates[id] + rich = richTextBoxStates[id] + doAssert editor != rich.editor + doAssert editor.getText() == "Editable" + doAssert rich.getText() == RichSource + window.moveMouse(35, 165) + window.tap(MouseLeft) + discard harness.pumpFrame(renderBoth) + doAssert editor.focused and not rich.editor.focused + editor.cursor = plain.runeLen + editor.selector = editor.cursor + window.typeText("!") + discard harness.pumpFrame(renderBoth) + doAssert plain == "Editable!" + doAssert rich.getText() == RichSource + doAssert window.runeInputEnabled + + window.moveMouse(35, 35) + window.tap(MouseLeft) + discard harness.pumpFrame(renderBoth) + doAssert rich.editor.focused and not editor.focused + doAssert not window.runeInputEnabled + window.shortcut(KeyA) + window.typeText("Ignored typed text") + window.onTextInput("Ignored native commit") + window.onTextEdit(TextInputEdit( + kind: ReplaceText, + start: 0, + length: RichSource.runeLen, + text: "Ignored native edit" + )) + setClipboardString("Ignored paste") + window.shortcut(KeyV) + window.shortcut(KeyX) + window.tap(KeyBackspace) + discard harness.pumpFrame(renderBoth) + doAssert plain == "Editable!" + doAssert rich.getText() == RichSource + doAssert rich.editor.selection == (0 .. RichSource.runeLen) + doAssert rich.editor.undoStack.len == 0 + window.shortcut(KeyC) + discard harness.pumpFrame(renderBoth) + doAssert getClipboardString() == RichSource + + window.moveMouse(35, 165) + window.tap(MouseLeft) + discard harness.pumpFrame(renderBoth) + editor.cursor = plain.runeLen + editor.selector = editor.cursor + window.onTextInput("2") + discard harness.pumpFrame(renderBoth) + doAssert plain == "Editable!2" + doAssert rich.getText() == RichSource + textBoxStates.del(id) + richTextBoxStates.del(id) + block: echo "Testing one-batch editing matches separate frames and layout" var fixtures = [fixture(""), fixture("")] diff --git a/tests/test_quotes.nim b/tests/test_quotes.nim index ede10f61..1409f5e9 100644 --- a/tests/test_quotes.nim +++ b/tests/test_quotes.nim @@ -34,16 +34,15 @@ proc render( source: string, blocks: seq[TextBlock], width = 180.0'f -): TextBoxState = - ## Draws one read-only quote document through the native textbox. - var text = source - textBoxStates.del("quotes") +): RichTextBoxState = + ## Draws one selectable quote document through the native rich textbox. + richTextBoxStates.del("quotes") sk.at = vec2(10.17'f, 20.29'f) - sk.textBox( - Window(), "quotes", text, width, 220, - wrapWords = true, enabled = false, blocks = blocks + sk.richTextBox( + Window(), "quotes", source, width, 220, + wrapWords = true, blocks = blocks ) - result = textBoxStates["quotes"] + result = richTextBoxStates["quotes"] proc bars(sk: Silky, color: ColorRGBX, width = 180.0'f): seq[Rect] = ## Finds solid rules and checks their physical alignment and clipping. @@ -122,8 +121,8 @@ block: quads = sk.bars(QuoteColor) firstHeight = builder.atlas.fonts["Heading"].lineHeight + 12 doAssert quads.len == 4 - doAssert state.layout[0].x == 44 - doAssert state.layout[5].x == 44 + doAssert state.editor.layout[0].x == 44 + doAssert state.editor.layout[5].x == 44 for level in 0 .. 1: let extension = if level < continuing: 8.0'f else: 0.0'f doAssert close( @@ -139,9 +138,9 @@ block: quads[level + 2].y * density, round((20.29'f + firstHeight + 8) * density) ) - state.selectAll() - doAssert state.copyText() == "Head\nBody" - doAssert state.layout.len == 9 + state.editor.selectAll() + doAssert state.editor.copyText() == "Head\nBody" + doAssert state.editor.layout.len == 9 echo "Testing quoted code surfaces, captions, and rules at ", density let @@ -162,7 +161,9 @@ block: quotePatch = quoted.patchBounds("code.9patch") doAssert close(quotePatch.x - plainPatch.x, 32) doAssert close(plainPatch.w - quotePatch.w, 32) - doAssert close(quoteState.layout[0].x - plainState.layout[0].x, 32) + doAssert close( + quoteState.editor.layout[0].x - plainState.editor.layout[0].x, 32 + ) doAssert close(quoted.caption().x - plain.caption().x, 32) doAssert quoteState.innerHeight == plainState.innerHeight let @@ -176,7 +177,7 @@ block: ]) horizontal = ruled.bars(RuleColor) doAssert ruleState.innerHeight == 13 - doAssert ruleState.runes.len == 0 + doAssert ruleState.editor.runes.len == 0 doAssert horizontal.len == 1 doAssert close(horizontal[0].x * density, round((10.17'f + 44) * density)) @@ -189,9 +190,9 @@ block: quoteDepth: 1, quoteColor: QuoteColor ) ], 80) - doAssert wrapped.layout[3].y > wrapped.layout[0].y - wrapped.selectAll() - doAssert wrapped.copyText() == "WW WW WW" + doAssert wrapped.editor.layout[3].y > wrapped.editor.layout[0].y + wrapped.editor.selectAll() + doAssert wrapped.editor.copyText() == "WW WW WW" let empty = fixture(builder, 2) emptyState = empty.render("", @[ @@ -204,7 +205,7 @@ block: emptyState.innerHeight, builder.atlas.fonts["Default"].lineHeight + 12 ) - doAssert emptyState.layout.len == 0 + doAssert emptyState.editor.layout.len == 0 doAssert empty.bars(QuoteColor).len == 1 for width in [0.0'f, 10.0'f, 20.0'f, 80.0'f]: let @@ -220,6 +221,6 @@ block: doAssert quad.w >= 0 and quad.h >= 0 doAssert quad.x >= 10 doAssert quad.x + quad.w <= 10.17'f + width + 0.5'f - textBoxStates.del("quotes") + richTextBoxStates.del("quotes") echo "All native quote tests passed." diff --git a/tests/test_richtextboxes.nim b/tests/test_richtextboxes.nim new file mode 100644 index 00000000..68260dfd --- /dev/null +++ b/tests/test_richtextboxes.nim @@ -0,0 +1,224 @@ +import + std/[tables, unicode], + vmath, bumpy, + silky/atlas, silky/textboxes, silky/richtextboxes + +var silkyAtlas: SilkyAtlas + +block: + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Wide", 30) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Small", 12) + silkyAtlas = builder.atlas + +proc newState(text: string, maxWidth = 500.0'f): RichTextBoxState = + ## Creates a wrapped read-only document and computes its rich layout. + result = newRichTextBoxState(text) + result.editor.boxSize = vec2(maxWidth, 300) + result.computeLayout(silkyAtlas.fonts, "Default", maxWidth) + +proc newStateNoWrap(text: string): RichTextBoxState = + ## Creates an unwrapped rich document for exact font comparisons. + result = newRichTextBoxState(text, wordWrap = false) + result.computeLayout(silkyAtlas.fonts, "Default", 500) + +proc newPlainState( + text: string, + maxWidth = 500.0'f, + wordWrap = false +): TextBoxState = + ## Creates an independent single-font reference layout. + result = TextBoxState(wordWrap: wordWrap) + result.setText(text) + result.computeLayout(silkyAtlas.fonts["Default"], maxWidth) + +proc advance(font: FontAtlas, rune: Rune): float32 = + ## Returns the actual atlas advance used by span layout assertions. + var entry: ptr LetterEntry + doAssert font.lookupLetter(rune, 0, entry) + entry.advance + +block: + echo "Testing styled text uses each span's font metrics" + let + s = newState("W a") + wide = silkyAtlas.fonts["Wide"] + small = silkyAtlas.fonts["Small"] + regular = silkyAtlas.fonts["Default"] + s.spans = @[ + TextSpan(first: 0, last: 1, font: "Wide"), + TextSpan(first: 2, last: 3, font: "Small") + ] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert s.editor.layout.len == 3 + doAssert abs(s.editor.layout[0].w - wide.advance(Rune('W'))) < 0.01 + doAssert abs(s.editor.layout[1].w - regular.advance(Rune(' '))) < 0.01 + doAssert abs(s.editor.layout[2].w - small.advance(Rune('a'))) < 0.01 + doAssert abs(s.editor.layout[1].x - s.editor.layout[0].w) < 0.01 + doAssert s.editor.lineHeight >= wide.lineHeight + for bounds in s.editor.layout: + doAssert bounds.h == s.editor.lineHeight + +block: + echo "Testing formatting and links preserve native pair kerning" + const Sample = "AVATAR To WAVY" + let + plain = newPlainState(Sample) + styled = newStateNoWrap(Sample) + doAssert silkyAtlas.fonts["Default"].lookupKerning(Rune('A'), Rune('V')) != 0 + doAssert silkyAtlas.fonts["Default"].lookupKerning(Rune('T'), Rune('o')) != 0 + doAssert plain.layout[1].x < plain.layout[0].w + for i in 0 ..< styled.editor.runes.len: + styled.spans.add(TextSpan( + first: i, + last: i + 1, + font: + if i mod 2 == 0: + "Default" + else: + "", + linkId: + if i in 1 .. 8: + 1 + else: + 0 + )) + styled.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert styled.editor.layout.len == plain.layout.len + for i in 0 ..< plain.layout.len: + let + expected = plain.layout[i] + actual = styled.editor.layout[i] + doAssert abs(actual.x - expected.x) < 0.001 + doAssert abs(actual.y - expected.y) < 0.001 + doAssert abs(actual.w - expected.w) < 0.001 + doAssert abs(actual.h - expected.h) < 0.001 + +block: + echo "Testing styled long words wrap before crossing the width" + let + s = newState("WWWWWW") + wide = silkyAtlas.fonts["Wide"] + width = wide.advance(Rune('W')) * 2.5'f + s.spans = @[TextSpan(first: 0, last: 6, font: "Wide")] + s.computeLayout(silkyAtlas.fonts, "Default", width) + doAssert s.editor.layout[0].y == s.editor.layout[1].y + doAssert s.editor.layout[2].y > s.editor.layout[1].y + doAssert s.editor.layout[4].y > s.editor.layout[3].y + for bounds in s.editor.layout: + doAssert bounds.x + bounds.w <= width + 0.01 + +block: + echo "Testing styled Unicode selection preserves the original text" + let s = newState("é code 世界") + s.spans = @[TextSpan(first: 2, last: 6, font: "Small")] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert s.editor.layout.len == s.editor.runes.len + s.editor.cursor = 2 + s.editor.selector = 6 + doAssert s.editor.copyText() == "code" + doAssert getSelectionRects(s.editor.layout, 2, 6).len == 1 + s.editor.selectAll() + doAssert s.editor.copyText() == "é code 世界" + +block: + echo "Testing styled code preserves tabs when copying" + let + s = newState("a\tb") + small = silkyAtlas.fonts["Small"] + s.spans = @[TextSpan(first: 0, last: 3, font: "Small")] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert abs(s.editor.layout[1].w - small.advance(Rune(' ')) * 4) < 0.01 + doAssert abs( + s.editor.layout[2].x - s.editor.layout[1].x - s.editor.layout[1].w + ) < 0.01 + s.editor.selectAll() + doAssert s.editor.copyText() == "a\tb" + +block: + echo "Testing rich text without styles preserves plain layout" + const Source = "A plain paragraph that wraps across lines." + let + plain = newPlainState(Source, 100, wordWrap = true) + rich = newState(Source, 100) + doAssert rich.editor.layout == plain.layout + +block: + echo "Testing one selection spans headings, wrapped prose, and code" + const + Heading = "Heading" + Body = "é body wraps over several lines for selection." + Code = "let x = 1\n echo x" + Sample = Heading & "\n" & Body & "\n" & Code + let + bodyStart = Heading.runeLen + 1 + codeStart = bodyStart + Body.runeLen + 1 + s = newState(Sample, 180) + s.blocks = @[ + TextBlock( + first: 0, last: Heading.runeLen, font: "Wide", + padding: vec2(12, 6), spacing: 8 + ), + TextBlock( + first: bodyStart, last: codeStart - 1, + padding: vec2(12, 6), spacing: 8 + ), + TextBlock( + first: codeStart, last: Sample.runeLen, font: "Small", + padding: vec2(12, 12), label: "nim", labelFont: "Small", + labelSpacing: 8 + ) + ] + s.computeLayout(silkyAtlas.fonts, "Default", 180) + doAssert s.editor.layout.len == Sample.runeLen + doAssert s.editor.layout[0].h > s.editor.layout[bodyStart].h + doAssert s.editor.layout[bodyStart].h > s.editor.layout[codeStart].h + doAssert s.editor.layout[codeStart - 2].y > s.editor.layout[bodyStart].y + doAssert s.editor.layout[bodyStart].x == 12 + doAssert s.editor.layout[codeStart].x == 12 + doAssert abs( + s.innerHeight - s.editor.layout[^1].y - s.editor.layout[^1].h - 12 + ) < 0.001 + for index in [0, bodyStart, codeStart]: + doAssert s.editor.locationRect(index).h == s.editor.layout[index].h + s.editor.selector = 2 + s.editor.cursor = codeStart + 5 + doAssert s.editor.copyText() == "ading\n" & Body & "\nlet x" + let selected = getSelectionRects( + s.editor.layout, s.editor.selector, s.editor.cursor + ) + doAssert selected.len >= 4 + doAssert selected[0].h > selected[^1].h + s.editor.selectAll() + doAssert s.editor.copyText() == Sample + + echo "Testing dragging through block spacing has no selection dead zone" + let + first = s.editor.layout[0] + body = s.editor.layout[bodyStart] + s.editor.mouseAction(first.xy + vec2(0, first.h / 2)) + s.editor.mouseAction( + vec2(body.x, body.y - 1), click = false, shift = true + ) + doAssert s.editor.selector == 0 + doAssert s.editor.cursor == bodyStart + doAssert s.editor.copyText() == Heading & "\n" + + echo "Testing keyboard selection follows rows with different heights" + s.editor.cursor = 0 + s.editor.selector = 0 + s.editor.savedX = first.x + s.editor.down(shift = true) + doAssert s.editor.cursor == bodyStart + doAssert s.editor.selector == 0 + s.editor.up(shift = true) + doAssert s.editor.cursor == 0 + s.editor.cursor = codeStart + s.editor.selector = codeStart + s.editor.savedX = s.editor.layout[codeStart].x + s.editor.up(shift = true) + doAssert s.editor.cursor >= bodyStart and s.editor.cursor < codeStart + doAssert s.editor.selector == codeStart + +echo "All rich textbox layout tests passed." diff --git a/tests/test_rules.nim b/tests/test_rules.nim index e1f4cba9..bc7789eb 100644 --- a/tests/test_rules.nim +++ b/tests/test_rules.nim @@ -47,7 +47,7 @@ proc rules(sk: Silky, clip: Rect): seq[Rect] = block: echo "Testing rule-only blocks have no text or implicit font line" - privateAccess(TextBoxState) + privateAccess(RichTextBoxState) let builder = newAtlasBuilder(1024, 2) window = Window() @@ -64,23 +64,23 @@ block: ruleThickness: 1, padding: vec2(12, 6) ) - var text = "" + let text = "" sk.at = origin - sk.textBox( + sk.richTextBox( window, "rule", text, 80, 100, - wrapWords = true, enabled = false, blocks = @[rule] + wrapWords = true, blocks = @[rule] ) let - state = textBoxStates["rule"] + state = richTextBoxStates["rule"] quads = sk.rules(rect(origin, vec2(80, 100))) - doAssert state.runes.len == 0 - doAssert state.layout.len == 0 + doAssert state.editor.runes.len == 0 + doAssert state.editor.layout.len == 0 doAssert state.runs.len == 0 doAssert state.innerHeight == 13 - doAssert state.locationRect(0).h == 0 - state.selectAll() - doAssert state.copyText() == "" - doAssert state.cursor == 0 and state.selector == 0 + doAssert state.editor.locationRect(0).h == 0 + state.editor.selectAll() + doAssert state.editor.copyText() == "" + doAssert state.editor.cursor == 0 and state.editor.selector == 0 doAssert quads.len == 1 doAssert close(quads[0].x * density, round((origin.x + 12) * density)) doAssert close(quads[0].y * density, round((origin.y + 6) * density)) @@ -92,13 +92,13 @@ block: sk.drawer.layers[NormalLayer].setLen(0) sk.at = origin - sk.textBox( + sk.richTextBox( window, "rule", text, 20, 100, - wrapWords = true, enabled = false, blocks = @[rule] + wrapWords = true, blocks = @[rule] ) doAssert sk.rules(rect(origin, vec2(20, 100))).len == 0 doAssert state.innerHeight == 13 - textBoxStates.del("rule") + richTextBoxStates.del("rule") echo "Testing rules preserve shared selection and surrounding wrapping" const Source = "WW WW WW\nAfter" @@ -116,26 +116,26 @@ block: following = TextBlock( first: after, last: Source.runeLen, padding: vec2(12, 6) ) - plain = TextBoxState(wordWrap: true, blocks: @[before, following]) - ruled = TextBoxState(wordWrap: true, blocks: @[before, rule, following]) - plain.setText(Source) - ruled.setText(Source) + plain = newRichTextBoxState(Source) + ruled = newRichTextBoxState(Source) + plain.blocks = @[before, following] + ruled.blocks = @[before, rule, following] plain.computeLayout(builder.atlas.fonts, "Default", 64) ruled.computeLayout(builder.atlas.fonts, "Default", 64) - doAssert ruled.layout.len == plain.layout.len - doAssert ruled.runes == plain.runes + doAssert ruled.editor.layout.len == plain.editor.layout.len + doAssert ruled.editor.runes == plain.editor.runes doAssert ruled.runs.len == plain.runs.len - doAssert ruled.layout[3].y > ruled.layout[0].y + doAssert ruled.editor.layout[3].y > ruled.editor.layout[0].y for i in 0 ..< after - 1: - doAssert ruled.layout[i] == plain.layout[i] + doAssert ruled.editor.layout[i] == plain.editor.layout[i] for i in after ..< Source.runeLen: - doAssert ruled.layout[i].x == plain.layout[i].x - doAssert ruled.layout[i].wh == plain.layout[i].wh - doAssert close(ruled.layout[i].y - plain.layout[i].y, 21) + doAssert ruled.editor.layout[i].x == plain.editor.layout[i].x + doAssert ruled.editor.layout[i].wh == plain.editor.layout[i].wh + doAssert close(ruled.editor.layout[i].y - plain.editor.layout[i].y, 21) doAssert close(ruled.innerHeight - plain.innerHeight, 21) - ruled.selectAll() - doAssert ruled.copyText() == Source - doAssert ruled.locationRect(Source.runeLen).h == - plain.locationRect(Source.runeLen).h + ruled.editor.selectAll() + doAssert ruled.editor.copyText() == Source + doAssert ruled.editor.locationRect(Source.runeLen).h == + plain.editor.locationRect(Source.runeLen).h echo "All native rule tests passed." diff --git a/tests/test_textboxes.nim b/tests/test_textboxes.nim index 1fb7ddb2..8a374265 100644 --- a/tests/test_textboxes.nim +++ b/tests/test_textboxes.nim @@ -8,8 +8,6 @@ import # Build a real atlas with font metrics. let builder = newAtlasBuilder(1024, 4) builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18.0) -builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Wide", 30.0) -builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Small", 12.0) builder.write("tests/dist/atlas.png") let silkyAtlas = readAtlasFromPng("tests/dist/atlas.png") let fontData = silkyAtlas.fonts["Default"] @@ -33,192 +31,10 @@ proc newStateSingleLine(text: string, maxWidth = 500.0f): TextBoxState = result.setText(text) result.computeLayout(fontData, maxWidth) -proc advance(font: FontAtlas, rune: Rune): float32 = - ## Returns the actual atlas advance used by span layout assertions. - var entry: ptr LetterEntry - doAssert font.lookupLetter(rune, 0, entry) - entry.advance - -block: - echo "Testing styled text uses each span's font metrics" - let - s = newState("W a") - wide = silkyAtlas.fonts["Wide"] - small = silkyAtlas.fonts["Small"] - s.enabled = false - s.spans = @[ - TextSpan(first: 0, last: 1, font: "Wide"), - TextSpan(first: 2, last: 3, font: "Small") - ] - s.computeLayout(silkyAtlas.fonts, "Default", 500) - doAssert s.layout.len == 3 - doAssert abs(s.layout[0].w - wide.advance(Rune('W'))) < 0.01 - doAssert abs(s.layout[1].w - fontData.advance(Rune(' '))) < 0.01 - doAssert abs(s.layout[2].w - small.advance(Rune('a'))) < 0.01 - doAssert abs(s.layout[1].x - s.layout[0].w) < 0.01 - doAssert s.lineHeight >= wide.lineHeight - for bounds in s.layout: - doAssert bounds.h == s.lineHeight - -block: - echo "Testing formatting and links preserve native pair kerning" - const Sample = "AVATAR To WAVY" - let - plain = newStateNoWrap(Sample) - styled = newStateNoWrap(Sample) - doAssert fontData.lookupKerning(Rune('A'), Rune('V')) != 0 - doAssert fontData.lookupKerning(Rune('T'), Rune('o')) != 0 - doAssert plain.layout[1].x < plain.layout[0].w - styled.enabled = false - for i in 0 ..< styled.runes.len: - styled.spans.add(TextSpan( - first: i, - last: i + 1, - font: - if i mod 2 == 0: - "Default" - else: - "", - linkId: - if i in 1 .. 8: - 1 - else: - 0 - )) - styled.computeLayout(silkyAtlas.fonts, "Default", 500) - doAssert styled.layout.len == plain.layout.len - for i in 0 ..< plain.layout.len: - let - expected = plain.layout[i] - actual = styled.layout[i] - doAssert abs(actual.x - expected.x) < 0.001 - doAssert abs(actual.y - expected.y) < 0.001 - doAssert abs(actual.w - expected.w) < 0.001 - doAssert abs(actual.h - expected.h) < 0.001 - -block: - echo "Testing styled long words wrap before crossing the width" - let - s = newState("WWWWWW") - wide = silkyAtlas.fonts["Wide"] - width = wide.advance(Rune('W')) * 2.5'f - s.enabled = false - s.spans = @[TextSpan(first: 0, last: 6, font: "Wide")] - s.computeLayout(silkyAtlas.fonts, "Default", width) - doAssert s.layout[0].y == s.layout[1].y - doAssert s.layout[2].y > s.layout[1].y - doAssert s.layout[4].y > s.layout[3].y - for bounds in s.layout: - doAssert bounds.x + bounds.w <= width + 0.01 - -block: - echo "Testing styled Unicode selection preserves the original text" - let s = newState("é code 世界") - s.enabled = false - s.spans = @[TextSpan(first: 2, last: 6, font: "Small")] - s.computeLayout(silkyAtlas.fonts, "Default", 500) - doAssert s.layout.len == s.runes.len - s.cursor = 2 - s.selector = 6 - doAssert s.copyText() == "code" - doAssert getSelectionRects(s.layout, 2, 6).len == 1 - s.selectAll() - doAssert s.copyText() == "é code 世界" - -block: - echo "Testing styled code preserves tabs when copying" - let - s = newState("a\tb") - small = silkyAtlas.fonts["Small"] - s.enabled = false - s.spans = @[TextSpan(first: 0, last: 3, font: "Small")] - s.computeLayout(silkyAtlas.fonts, "Default", 500) - doAssert abs(s.layout[1].w - small.advance(Rune(' ')) * 4) < 0.01 - doAssert abs(s.layout[2].x - s.layout[1].x - s.layout[1].w) < 0.01 - s.selectAll() - doAssert s.copyText() == "a\tb" - -block: - echo "Testing the styled layout overload preserves unstyled layout" - let - s = newState("A plain paragraph that wraps across lines.", 100) - expected = s.layout - s.computeLayout(silkyAtlas.fonts, "Default", 100) - doAssert s.layout == expected - -block: - echo "Testing one selection spans headings, wrapped prose, and code" - const - Heading = "Heading" - Body = "é body wraps over several lines for selection." - Code = "let x = 1\n echo x" - Sample = Heading & "\n" & Body & "\n" & Code - let - bodyStart = Heading.runeLen + 1 - codeStart = bodyStart + Body.runeLen + 1 - s = newState(Sample, 180) - s.enabled = false - s.blocks = @[ - TextBlock( - first: 0, last: Heading.runeLen, font: "Wide", - padding: vec2(12, 6), spacing: 8 - ), - TextBlock( - first: bodyStart, last: codeStart - 1, - padding: vec2(12, 6), spacing: 8 - ), - TextBlock( - first: codeStart, last: Sample.runeLen, font: "Small", - padding: vec2(12, 12), label: "nim", labelFont: "Small", - labelSpacing: 8 - ) - ] - s.computeLayout(silkyAtlas.fonts, "Default", 180) - doAssert s.layout.len == Sample.runeLen - doAssert s.layout[0].h > s.layout[bodyStart].h - doAssert s.layout[bodyStart].h > s.layout[codeStart].h - doAssert s.layout[codeStart - 2].y > s.layout[bodyStart].y - doAssert s.layout[bodyStart].x == 12 - doAssert s.layout[codeStart].x == 12 - doAssert abs(s.innerHeight - s.layout[^1].y - s.layout[^1].h - 12) < 0.001 - for index in [0, bodyStart, codeStart]: - doAssert s.locationRect(index).h == s.layout[index].h - s.selector = 2 - s.cursor = codeStart + 5 - doAssert s.copyText() == "ading\n" & Body & "\nlet x" - let selected = getSelectionRects(s.layout, s.selector, s.cursor) - doAssert selected.len >= 4 - doAssert selected[0].h > selected[^1].h - s.selectAll() - doAssert s.copyText() == Sample - - echo "Testing dragging through block spacing has no selection dead zone" - let - first = s.layout[0] - body = s.layout[bodyStart] - s.mouseAction(first.xy + vec2(0, first.h / 2)) - s.mouseAction( - vec2(body.x, body.y - 1), click = false, shift = true - ) - doAssert s.selector == 0 - doAssert s.cursor == bodyStart - doAssert s.copyText() == Heading & "\n" - - echo "Testing keyboard selection follows rows with different heights" - s.cursor = 0 - s.selector = 0 - s.savedX = first.x - s.down(shift = true) - doAssert s.cursor == bodyStart - doAssert s.selector == 0 - s.up(shift = true) - doAssert s.cursor == 0 - s.cursor = codeStart - s.selector = codeStart - s.savedX = s.layout[codeStart].x - s.up(shift = true) - doAssert s.cursor >= bodyStart and s.cursor < codeStart - doAssert s.selector == codeStart +static: + doAssert not declared(TextSpan) + doAssert not declared(RichTextBoxState) + doAssert not compiles(TextBoxState(spans: @[])) block: echo "Testing getText / setText" From 574d0fea07554216a9aced7695c409463d09cc38 Mon Sep 17 00:00:00 2001 From: treeform Date: Tue, 10 Nov 2026 19:11:21 -0800 Subject: [PATCH 04/16] capture textbox input on programmatic focus --- .github/workflows/build.yml | 1 + src/silky/textboxes.nim | 9 +++ tests/test_focus.nim | 119 ++++++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 tests/test_focus.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e9e5653b..5070bed5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,6 +61,7 @@ jobs: 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_buttons.nim + nim r -d:silkyTesting tests/test_focus.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim nim r tests/test_shader_codegen.nim diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index 4e17f198..aaf5dffe 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -111,6 +111,15 @@ proc resetBlink*(state: TextBoxState) = ## Resets the cursor blink timer so the cursor is immediately visible. state.blinkTime = epochTime() +proc focus*(state: TextBoxState, sk: Silky, window: Window, id: string) = + ## Focuses a registered field and captures input before its next draw. + let inputs = sk.textInputs + inputs.submitInput(window, id, true, state.enabled) + state.focused = true + state.focusEpoch = inputs.focusEpoch + state.dragging = false + state.resetBlink() + proc cursorVisible*(state: TextBoxState): bool = ## Returns true when the blinking cursor should be drawn. ## Blinks 0.5s on, 0.5s off, always starting visible after a reset. diff --git a/tests/test_focus.nim b/tests/test_focus.nim new file mode 100644 index 00000000..701529f5 --- /dev/null +++ b/tests/test_focus.nim @@ -0,0 +1,119 @@ +import + std/unicode, + vmath, + silky, silky/semantics, silky/internal/inputs + +when not defined(silkyTesting): + {.error: "Compile with -d:silkyTesting".} + +type InputMode = enum + NoText, RuneInput, CommittedInput + +proc tap(window: Window, button: Button) = + ## Delivers a complete key or mouse event before the next draw. + window.pressButton(button) + window.releaseButton(button) + +block: + echo "Testing programmatic focus captures input before the first draw" + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + for oldFirst in [false, true]: + for mode in InputMode: + let + suffix = $oldFirst & $mode + oldId = "composer-" & suffix + newId = "rename-" & suffix + var + harness = newTestHarness(builder.atlas) + composer = "Composer draft" + title = "Old title" + showRename = false + + proc draw(sk: Silky, window: Window) = + ## Draws the old owner before or after the newly focused popup. + template oldField() = + ## Draws the original composer without changing its draft. + sk.at = vec2(20, 20) + sk.textBox(window, oldId, composer, 240, 64, wrapWords = true) + + template renameField() = + ## Draws the rename input once its popup has opened. + if showRename: + sk.at = vec2(20, 120) + sk.textBox( + window, newId, title, 240, 64, + wrapWords = false, singleLine = true, submitOnEnter = true + ) + + if oldFirst: + oldField() + renameField() + else: + renameField() + oldField() + + discard harness.pumpFrame(draw) + let window = harness.window + window.moveMouse(35, 35) + window.tap(MouseLeft) + discard harness.pumpFrame(draw) + let oldState = textBoxStates[oldId] + doAssert oldState.focused and window.runeInputEnabled + + harness.sk.textInputs.stopInput(window) + doAssert not window.runeInputEnabled + let state = TextBoxState(singleLine: true, dragging: true) + state.setText(title) + textBoxStates[newId] = state + state.focus(harness.sk, window, newId) + state.selectAll() + showRename = true + doAssert state.focused and not state.dragging + doAssert state.cursorVisible + doAssert window.runeInputEnabled + doAssert state.selection == (0 .. title.runeLen) + + window.moveMouse(600, 400) + window.releaseButton(MouseLeft) + let expected = + case mode + of NoText: + title + of RuneInput: + "R" + of CommittedInput: + "Renamed café" + case mode + of NoText: + discard + of RuneInput: + window.typeRune(Rune('R')) + of CommittedInput: + window.onTextInput(expected) + if mode != NoText: + window.tap(KeyEnter) + discard harness.pumpFrame(draw) + doAssert state.focused and not oldState.focused + doAssert title == expected + doAssert composer == "Composer draft" + doAssert state.submitted == (mode != NoText) + doAssert window.textInput.id == newId + doAssert window.textInput.text == expected + doAssert not window.textInput.multiline + if mode == NoText: + doAssert state.selection == (0 .. title.runeLen), + "The menu's stale mouse release must retain select-all." + else: + doAssert state.selection == (expected.runeLen .. expected.runeLen) + doAssert state.undoStack.len == 1 + window.pressButton(KeyLeftSuper) + window.tap(KeyZ) + window.releaseButton(KeyLeftSuper) + discard harness.pumpFrame(draw) + doAssert title == "Old title" + doAssert composer == "Composer draft" + textBoxStates.del(oldId) + textBoxStates.del(newId) + +echo "All programmatic focus tests passed." From f4935b0273b42ced840248be0e7cf4f3222a442d Mon Sep 17 00:00:00 2001 From: treeform Date: Fri, 13 Nov 2026 07:06:54 -0800 Subject: [PATCH 05/16] add on-demand rendering policy --- .github/workflows/build.yml | 1 + src/silky/contexts.nim | 55 +++++++- src/silky/frames.nim | 109 ++++++++++++++++ src/silky/internal/inputs.nim | 8 ++ src/silky/semantics.nim | 68 +++++++++- src/silky/testwindow.nim | 1 + src/silky/textboxes.nim | 23 ++++ src/silky/widgets.nim | 3 + tests/test_rendering.nim | 228 ++++++++++++++++++++++++++++++++++ 9 files changed, 491 insertions(+), 5 deletions(-) create mode 100644 src/silky/frames.nim create mode 100644 tests/test_rendering.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 605a63cb..66ac27c8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,6 +59,7 @@ jobs: run: | nim r tests/test_textboxes.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_subwindow.nim nim r tests/test_atlas_png.nim nim r -d:silkyTesting tests/test_layout.nim diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 0f79620c..19dc094d 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, layout, profiles], + silky/[atlas, clips, frames, layout, profiles], silky/internal/inputs -export layout, profiles +export frames, layout, profiles when defined(useDirectX): import silky/drawers/dx12 @@ -89,6 +89,9 @@ type theme*: Theme = Theme() cursor*: Cursor = Cursor(kind: ArrowCursor) inputs: TextInputs + frames: FrameSchedule + frameInput: FrameInput + frameHadInput: bool mousePos*: Vec2 mouseDelta*: Vec2 mouseIdleTime*: float64 @@ -125,6 +128,39 @@ proc textInputs*(sk: Silky): TextInputs = ## Provides internal text input state to the text widgets. sk.inputs +proc renderMode*(sk: Silky): RenderMode = + ## Returns continuous game rendering or event-driven application rendering. + sk.frames.mode + +proc requestFrame*(sk: Silky, delayMs = 0) = + ## Invalidates app data or schedules a visible animation on the UI thread. + sk.frames.requestFrame(delayMs) + +proc `renderMode=`*(sk: Silky, mode: RenderMode) = + ## Selects the rendering policy without changing the drawing API. + sk.frames.mode = mode + sk.requestFrame() + +proc `onFrameRequested=`*(sk: Silky, wake: proc()) = + ## Connects invalidation and native editor input to an event-loop wakeup. + sk.frames.wake = wake + if sk.inputs != nil: + sk.inputs.onEvent = wake + +proc needsFrame*(sk: Silky, window: Window): bool = + ## Checks UI input and scheduled deadlines before drawing an app frame. + if sk.frames.mode == ContinuousRender: + return true + if sk.frameInput.inputChanged(window, sk.inputs.hasPendingEvents()): + sk.requestFrame() + sk.frames.needsFrame() + +proc nextFrameDelay*(sk: Silky, window: Window, maxWaitMs = 1000): int = + ## Bounds an event-loop wait by pending UI work and animation deadlines. + if sk.needsFrame(window): + return 0 + sk.frames.nextFrameDelay(maxWaitMs) + proc pushLayer*(sk: Silky, layer: int) = ## Pushes a new rendering layer onto the stack. sk.drawer.layerStack.add(sk.drawer.currentLayer) @@ -295,6 +331,11 @@ proc peekRune(text: string, i: int, rune: var Rune): bool {.inline.} = proc shouldShowTooltip*(sk: Silky): bool = ## Returns true when a tooltip should be shown. + if sk.renderMode == OnDemandRender and sk.hover and + sk.mouseIdleTime < sk.tooltipThreshold: + sk.requestFrame(max( + 1, ((sk.tooltipThreshold - sk.mouseIdleTime) * 1000).int + 1 + )) sk.hover and sk.mouseIdleTime >= sk.tooltipThreshold proc resetInteractions*(sk: Silky) = @@ -305,6 +346,11 @@ proc resetInteractions*(sk: Silky) = proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = ## Starts a frame and updates the shared UI state. + if sk.frames.mode == OnDemandRender: + sk.frameHadInput = sk.frameInput.inputChanged( + window, sk.inputs.hasPendingEvents() + ) + sk.frames.beginFrame() sk.inputs.beginInputFrame(window) beginProfileFrame() @@ -348,6 +394,11 @@ proc endInteractions(interactor: var Interactor) = 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]: + sk.requestFrame(16) if sk.window.buttonReleased[MouseLeft]: sk.resetInteractions() sk.interactor.endInteractions() diff --git a/src/silky/frames.nim b/src/silky/frames.nim new file mode 100644 index 00000000..7f300361 --- /dev/null +++ b/src/silky/frames.nim @@ -0,0 +1,109 @@ +import + std/monotimes, + vmath + +from windy/common import Button + +type + RenderMode* = enum + ContinuousRender, OnDemandRender + + FrameSchedule* = object + mode*: RenderMode + wake*: proc() + dirty: bool = true + deadline: int64 = int64.high + + FrameInput* = object + initialized: bool + position, size: IVec2 + focused, visible, minimized: bool + scale: float32 + +proc frameMilliseconds*(): int64 {.raises: [].} = + ## Reads the monotonic clock used for redraw deadlines. + getMonoTime().ticks div 1_000_000 + +proc requestFrame*( + schedule: var FrameSchedule, + 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. + let + dirty = schedule.dirty + deadline = schedule.deadline + if delayMs <= 0: + schedule.dirty = true + else: + schedule.deadline = min(schedule.deadline, nowMs + delayMs.int64) + if (schedule.dirty != dirty or schedule.deadline < deadline) and + schedule.wake != nil: + schedule.wake() + +proc needsFrame*(schedule: FrameSchedule, nowMs = frameMilliseconds()): bool + {.raises: [].} = + ## Reports continuous rendering, invalidation, or an expired deadline. + schedule.mode == ContinuousRender or schedule.dirty or + schedule.deadline <= nowMs + +proc nextFrameDelay*( + schedule: FrameSchedule, + maxWaitMs = 1000, + nowMs = frameMilliseconds() +): int {.raises: [].} = + ## Returns the bounded native-event wait until another frame is due. + if schedule.needsFrame(nowMs): + return 0 + let limit = max(0, maxWaitMs) + if schedule.deadline == int64.high: + return limit + min(limit.int64, max(0'i64, schedule.deadline - nowMs)).int + +proc beginFrame*(schedule: var FrameSchedule, nowMs = frameMilliseconds()) + {.raises: [].} = + ## Consumes invalidation and expired timers before drawing the next frame. + schedule.dirty = false + if schedule.deadline <= nowMs: + schedule.deadline = int64.high + +proc inputChanged*( + previous: var FrameInput, + window: auto, + pendingText: bool +): bool = + ## Detects native geometry, pointer, focus, and queued editor input changes. + let + position = window.mousePos + size = window.size + focused = + when compiles(window.focused): window.focused + else: true + visible = + when compiles(window.visible): window.visible + else: true + minimized = + when compiles(window.minimized): window.minimized + else: false + scale = + when compiles(window.contentScale): window.contentScale + else: 1.0'f + result = pendingText or not previous.initialized or + position != previous.position or size != previous.size or + focused != previous.focused or visible != previous.visible or + minimized != previous.minimized or scale != previous.scale or + window.scrollDelta != vec2(0) or window.mouseDelta != ivec2(0) + for button in Button: + if window.buttonPressed[button] or window.buttonReleased[button]: + result = true + break + previous = FrameInput( + initialized: true, + position: position, + size: size, + focused: focused, + visible: visible, + minimized: minimized, + scale: scale + ) diff --git a/src/silky/internal/inputs.nim b/src/silky/internal/inputs.nim index 63c3c92c..2fb1c2a6 100644 --- a/src/silky/internal/inputs.nim +++ b/src/silky/internal/inputs.nim @@ -22,6 +22,8 @@ type CallbackIdentity = tuple[code, environment: pointer] TextInputs* = ref object + onEvent*: proc() + ## Wakes an on-demand UI after editor input has been queued. events: seq[InputEvent] active: bool editable: bool @@ -42,6 +44,10 @@ proc focusEpoch*(inputs: TextInputs): uint64 = ## Returns the generation of the current text focus. inputs.epoch +proc hasPendingEvents*(inputs: TextInputs): bool {.raises: [].} = + ## Reports queued edits without consuming the editor's input batch. + inputs != nil and inputs.events.len > 0 + when defined(silkyTesting): proc filterButtons*( inputs: TextInputs, buttons: array[Button, bool] @@ -86,6 +92,8 @@ proc addEvent(inputs: TextInputs, event: InputEvent) = if inputs.events.len >= MaxPendingEvents: raise newException(SilkyError, "Too many pending text input events") inputs.events.add(event) + if inputs.onEvent != nil: + inputs.onEvent() proc installPress(inputs: TextInputs, window: Window) = ## Installs this handler only when the window's callback changes. diff --git a/src/silky/semantics.nim b/src/silky/semantics.nim index f455937e..0393315e 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, layout], testwindow, + silky/[atlas, clips, frames, layout], testwindow, silky/internal/inputs from windy/common import Button, CursorKind, Cursor -export layout +export frames, layout const LineFeedRune = Rune(10) @@ -286,6 +286,9 @@ type theme*: Theme = Theme() cursor*: Cursor = Cursor(kind: ArrowCursor) inputs: TextInputs + frames: FrameSchedule + frameInput: FrameInput + frameHadInput: bool mousePos*: Vec2 mouseDelta*: Vec2 mouseIdleTime*: float64 @@ -321,6 +324,39 @@ proc textInputs*(sk: Silky): TextInputs = ## Provides internal text input state to the text widgets. sk.inputs +proc renderMode*(sk: Silky): RenderMode = + ## Returns continuous game rendering or event-driven application rendering. + sk.frames.mode + +proc requestFrame*(sk: Silky, delayMs = 0) = + ## Invalidates app data or schedules a visible animation on the UI thread. + sk.frames.requestFrame(delayMs) + +proc `renderMode=`*(sk: Silky, mode: RenderMode) = + ## Selects the rendering policy without changing the drawing API. + sk.frames.mode = mode + sk.requestFrame() + +proc `onFrameRequested=`*(sk: Silky, wake: proc()) = + ## Connects invalidation and native editor input to an event-loop wakeup. + sk.frames.wake = wake + if sk.inputs != nil: + sk.inputs.onEvent = wake + +proc needsFrame*(sk: Silky, window: Window): bool = + ## Checks UI input and scheduled deadlines before drawing an app frame. + if sk.frames.mode == ContinuousRender: + return true + if sk.frameInput.inputChanged(window, sk.inputs.hasPendingEvents()): + sk.requestFrame() + sk.frames.needsFrame() + +proc nextFrameDelay*(sk: Silky, window: Window, maxWaitMs = 1000): int = + ## Bounds an event-loop wait by pending UI work and animation deadlines. + if sk.needsFrame(window): + return 0 + sk.frames.nextFrameDelay(maxWaitMs) + proc pushLayer*(sk: Silky, layer: int) = ## Pushes a new rendering layer onto the stack. sk.layerStack.add(sk.currentLayer) @@ -503,6 +539,11 @@ proc contains*(sk: Silky, name: string): bool = proc shouldShowTooltip*(sk: Silky): bool = ## Returns true if a tooltip should be displayed. + if sk.renderMode == OnDemandRender and sk.hover and + sk.mouseIdleTime < sk.tooltipThreshold: + sk.requestFrame(max( + 1, ((sk.tooltipThreshold - sk.mouseIdleTime) * 1000).int + 1 + )) sk.hover and sk.mouseIdleTime >= sk.tooltipThreshold proc drawQuad*(sk: Silky, pos: Vec2, size: Vec2, uvPos: Vec2, uvSize: Vec2, color: ColorRGBX) {.inline.} = @@ -609,6 +650,11 @@ proc newSilky*(window: Window, atlasPngPath: string): Silky = proc beginUi*(sk: Silky, window: auto, size: IVec2) = ## Begins a new UI frame. + if sk.frames.mode == OnDemandRender: + sk.frameHadInput = sk.frameInput.inputChanged( + window, sk.inputs.hasPendingEvents() + ) + sk.frames.beginFrame() sk.inputs.beginInputFrame(window) sk.tooltipActive = sk.showTooltip sk.showTooltip = false @@ -617,8 +663,19 @@ proc beginUi*(sk: Silky, window: auto, size: IVec2) = sk.mouseDelta = window.mouseDelta.vec2 / sk.uiScale sk.pushLayout(vec2(0, 0), size.vec2 / sk.uiScale) sk.inFrame = true - let currentTime = epochTime() + let + currentTime = epochTime() + deltaTime = currentTime - sk.frameStartTime sk.frameStartTime = currentTime + if sk.mousePos != sk.lastMousePos: + sk.mouseIdleTime = 0 + sk.lastMousePos = sk.mousePos + else: + sk.mouseIdleTime += deltaTime + if sk.tooltipActive: + sk.tooltipFadeInTime += deltaTime + else: + sk.tooltipFadeInTime = 0 sk.pushClipRect(rect(0, 0, sk.size.x, sk.size.y)) sk.semantic.reset() @@ -635,6 +692,11 @@ proc resetInteractions*(sk: Silky) = 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]: + sk.requestFrame(16) sk.interactor.endInteractions() sk.clear() sk.popLayout() diff --git a/src/silky/testwindow.nim b/src/silky/testwindow.nim index 8ae0b792..978981c9 100644 --- a/src/silky/testwindow.nim +++ b/src/silky/testwindow.nim @@ -9,6 +9,7 @@ export Button, CursorKind, Cursor, unicode type Window* = ref object ## Test window that simulates a windy Window. size*: IVec2 + focused*: bool = true mousePrevPos*: IVec2 mousePos*: IVec2 mouseDelta*: IVec2 diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index e2aca6b8..e3f853da 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -305,6 +305,28 @@ proc cursorPos*(state: TextBoxState): Vec2 = ## Returns the position of the text cursor. state.locationRect(state.cursor).xy +proc requestCursorFrame*( + sk: Silky, + window: Window, + state: TextBoxState, + bounds: Rect +) = + ## Schedules blinking only for a visible caret that still owns focus. + if sk.renderMode != OnDemandRender or not state.focused or + state.focusEpoch != sk.textInputs.focusEpoch or + sk.clipRect.w <= 0 or sk.clipRect.h <= 0: + return + when compiles(window.focused): + if not window.focused: + return + let + cursor = state.locationRect(state.cursor) + placed = rect(bounds.xy - state.scrollPos + cursor.xy, cursor.wh) + if not placed.overlaps(bounds) or not placed.overlaps(sk.clipRect): + return + let elapsed = (max(0.0, epochTime() - state.blinkTime) * 1000).int64 + sk.requestFrame(500 - (elapsed mod 500).int) + proc undoSave*(state: TextBoxState) = ## Saves current state for undo. state.undoStack.add((state.runes, state.cursor)) @@ -1040,6 +1062,7 @@ proc textBox*( wordWrap = state.wordWrap, clip = false ) + sk.requestCursorFrame(window, state, innerRect) if state.focused and state.cursorVisible: let cr = state.locationRect(state.cursor) sk.drawRect( diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index 53423eec..ab34ec32 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -1002,6 +1002,9 @@ template tooltip*(text: string) = sk.tooltipFadeInTime = 0 sk.tooltipLastAnchor = sk.tooltipAnchor sk.showTooltip = true + if sk.renderMode == OnDemandRender and + sk.tooltipFadeInTime < sk.tooltipFadeInDuration: + sk.requestFrame(16) let fadeAlpha = clamp( diff --git a/tests/test_rendering.nim b/tests/test_rendering.nim new file mode 100644 index 00000000..c4ce57bd --- /dev/null +++ b/tests/test_rendering.nim @@ -0,0 +1,228 @@ +import + std/unicode, + pixie, silky, vmath, + silky/[frames, testwindow] + +when not defined(silkyTesting): + {.error: "Run rendering tests with -d:silkyTesting; no window is used.".} + +const InputId = "render scheduling input" + +proc renderHarness(): TestHarness = + ## Builds a test atlas without a native window or a generated atlas file. + let builder = newAtlasBuilder(1024, 4) + builder.addDir("tests/data/", "tests/data/") + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18.0) + newTestHarness(builder.atlas, 600, 400) + +proc typeText(window: Window, text: string) = + ## Sends text through the callback consumed by a focused editor. + for rune in text.runes: + window.typeRune(rune) + +proc testDeadlines() = + ## Coalesces redraws and resumes sleeping when animation requests stop. + echo "Testing deterministic redraw deadlines and animation lifetime" + var + schedule = FrameSchedule(mode: OnDemandRender) + wakes = 0 + schedule.wake = proc() = + ## Counts only requests that bring the next redraw forward. + inc wakes + doAssert schedule.needsFrame(nowMs = 100) + schedule.beginFrame(nowMs = 100) + doAssert not schedule.needsFrame(nowMs = 100) + doAssert schedule.nextFrameDelay(nowMs = 100) == 1000 + schedule.requestFrame(delayMs = 83, nowMs = 100) + doAssert wakes == 1 + doAssert not schedule.needsFrame(nowMs = 182) + doAssert schedule.nextFrameDelay(nowMs = 182) == 1 + doAssert schedule.needsFrame(nowMs = 183) + schedule.requestFrame(delayMs = 100, nowMs = 100) + doAssert wakes == 1 + doAssert schedule.nextFrameDelay(nowMs = 100) == 83 + schedule.requestFrame(delayMs = 60, nowMs = 100) + doAssert wakes == 2 + doAssert schedule.nextFrameDelay(nowMs = 100) == 60 + schedule.requestFrame(nowMs = 110) + schedule.requestFrame(nowMs = 110) + doAssert wakes == 3 + doAssert schedule.nextFrameDelay(nowMs = 110) == 0 + schedule.beginFrame(nowMs = 110) + doAssert schedule.nextFrameDelay(nowMs = 110) == 50 + doAssert not schedule.needsFrame(nowMs = 159) + schedule.beginFrame(nowMs = 160) + doAssert not schedule.needsFrame(nowMs = 160) + for time in [160'i64, 176, 192]: + schedule.requestFrame(delayMs = 16, nowMs = time) + doAssert schedule.nextFrameDelay(nowMs = time) == 16 + doAssert not schedule.needsFrame(nowMs = time + 15) + doAssert schedule.needsFrame(nowMs = time + 16) + schedule.beginFrame(nowMs = time + 16) + doAssert not schedule.needsFrame(nowMs = 10_000) + doAssert schedule.nextFrameDelay(maxWaitMs = 5000, nowMs = 10_000) == 5000 + schedule.mode = ContinuousRender + schedule.beginFrame(nowMs = 10_000) + doAssert schedule.needsFrame(nowMs = 10_000) + doAssert schedule.nextFrameDelay(nowMs = 10_000) == 0 + +proc emptyFrame(harness: var TestHarness) = + ## Draws a stable empty interface and consumes transient window input. + harness.beginFrame() + harness.endFrame() + harness.window.resetInputState() + +proc settle(harness: var TestHarness) = + ## Allows bounded interaction settling without permitting an idle frame loop. + for i in 0 ..< 4: + if not harness.sk.needsFrame(harness.window): + break + harness.emptyFrame() + doAssert not harness.sk.needsFrame(harness.window) + +proc inputFrame(harness: var TestHarness, text: var string) = + ## Uses the real editable textbox with a semantic window and no GPU. + harness.beginFrame() + harness.sk.at = vec2(12) + harness.sk.textBox( + harness.window, + InputId, + text, + 320, + 96, + wrapWords = true + ) + harness.endFrame() + harness.window.resetInputState() + +proc settleInput(harness: var TestHarness, text: var string) = + ## Finishes queued editor redraws before testing a sleeping input field. + for i in 0 ..< 4: + if not harness.sk.needsFrame(harness.window): + break + harness.inputFrame(text) + doAssert not harness.sk.needsFrame(harness.window) + +proc testModes() = + ## Keeps games continuous and lets a stable app stop rendering completely. + echo "Testing continuous and on-demand rendering modes" + var harness = renderHarness() + doAssert harness.sk.renderMode == ContinuousRender + for i in 0 ..< 3: + doAssert harness.sk.needsFrame(harness.window) + doAssert harness.sk.nextFrameDelay(harness.window, 1000) == 0 + harness.emptyFrame() + harness.sk.renderMode = OnDemandRender + doAssert harness.sk.needsFrame(harness.window) + harness.settle() + doAssert harness.sk.nextFrameDelay(harness.window, 1000) == 1000 + var wakes = 0 + harness.sk.onFrameRequested = proc() = + ## Counts requests that can wake the native event wait. + inc wakes + harness.sk.requestFrame() + doAssert wakes > 0 + doAssert harness.sk.needsFrame(harness.window) + doAssert harness.sk.nextFrameDelay(harness.window, 1000) == 0 + harness.settle() + harness.sk.renderMode = ContinuousRender + for i in 0 ..< 3: + doAssert harness.sk.needsFrame(harness.window) + harness.emptyFrame() + +proc testInputs() = + ## Wakes for consumed text and keyboard input while scheduling the caret. + echo "Testing on-demand editor input wakes and caret scheduling" + var + harness = renderHarness() + text = "" + wakes = 0 + harness.sk.renderMode = OnDemandRender + harness.inputFrame(text) + let editor = textBoxStates[InputId] + defer: + textBoxStates.del(InputId) + harness.window.moveMouse(30, 30) + harness.window.pressButton(MouseLeft) + harness.window.releaseButton(MouseLeft) + harness.inputFrame(text) + harness.settleInput(text) + harness.sk.onFrameRequested = proc() = + ## Counts queued input even when the focused editor consumes callbacks. + inc wakes + harness.window.typeText("Dictated text") + doAssert wakes > 0 + doAssert harness.sk.needsFrame(harness.window) + harness.inputFrame(text) + doAssert text == "Dictated text" + harness.settleInput(text) + let beforeKey = wakes + harness.window.pressButton(KeyLeft) + harness.window.releaseButton(KeyLeft) + doAssert wakes > beforeKey + doAssert harness.sk.needsFrame(harness.window) + harness.inputFrame(text) + doAssert editor.cursor == text.len - 1 + harness.settleInput(text) + let delay = harness.sk.nextFrameDelay(harness.window, 1000) + doAssert delay > 0 and delay <= 500 + editor.focused = false + harness.window.focused = false + harness.window.changeFocus() + doAssert harness.sk.needsFrame(harness.window) + harness.settle() + +proc testHover() = + ## Settles deferred hover state after input without redrawing forever. + echo "Testing on-demand hover settling" + var harness = renderHarness() + harness.sk.renderMode = OnDemandRender + harness.window.moveMouse(300, 300) + proc frame(): bool = + ## Resolves the same hover target through native Silky interaction state. + harness.beginFrame() + result = harness.sk.mouseHover(harness.window, rect(10, 10, 100, 40)) + harness.endFrame() + harness.window.resetInputState() + discard frame() + for i in 0 ..< 3: + if not harness.sk.needsFrame(harness.window): + break + discard frame() + doAssert not harness.sk.needsFrame(harness.window) + harness.window.moveMouse(30, 20) + doAssert harness.sk.needsFrame(harness.window) + discard frame() + doAssert harness.sk.needsFrame(harness.window) + doAssert frame() + doAssert not harness.sk.needsFrame(harness.window) + harness.window.moveMouse(300, 300) + doAssert harness.sk.needsFrame(harness.window) + doAssert not frame() + if harness.sk.needsFrame(harness.window): + doAssert not frame() + doAssert not harness.sk.needsFrame(harness.window) + +proc testClippedCaret() = + ## Keeps a focused caret outside the viewport from renewing animation work. + echo "Testing clipped carets do not keep app rendering active" + var harness = renderHarness() + harness.sk.renderMode = OnDemandRender + harness.settle() + let editor = TextBoxState(lineHeight: 20, focused: true) + harness.sk.requestFrame() + harness.beginFrame() + harness.sk.requestCursorFrame( + harness.window, editor, rect(0, 1000, 100, 40) + ) + harness.endFrame() + harness.window.resetInputState() + harness.settle() + doAssert harness.sk.nextFrameDelay(harness.window, 1000) == 1000 + +testDeadlines() +testModes() +testInputs() +testHover() +testClippedCaret() +echo "All rendering policy tests passed." From bc64a4de66eab46e241e5d3284acc7d55f72a256 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 09:13:23 -0800 Subject: [PATCH 06/16] add parent scrolling for rich text navigation --- .github/workflows/build.yml | 1 + docs/text_inputs.md | 50 ++++++ src/silky/layout.nim | 38 ++++ src/silky/richtextboxes.nim | 5 +- src/silky/textboxes.nim | 10 +- tests/test_cursor_scroll.nim | 335 +++++++++++++++++++++++++++++++++++ 6 files changed, 436 insertions(+), 3 deletions(-) create mode 100644 tests/test_cursor_scroll.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5070bed5..975029d3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -62,6 +62,7 @@ jobs: nim r -d:silkyTesting -d:nimTypeNames tests/test_inputs.nim nim r -d:silkyTesting tests/test_buttons.nim nim r -d:silkyTesting tests/test_focus.nim + nim r -d:silkyTesting tests/test_cursor_scroll.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim nim r tests/test_shader_codegen.nim 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/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 994de3eb..6f922eac 100644 --- a/src/silky/richtextboxes.nim +++ b/src/silky/richtextboxes.nim @@ -72,6 +72,8 @@ 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] @@ -550,6 +552,7 @@ proc richTextBox*( 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 @@ -635,7 +638,7 @@ proc richTextBox*( 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: diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index aaf5dffe..9adbba85 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -884,8 +884,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 keyboard navigation for parent scrolling. assert not state.enabled let epoch = inputs.focusEpoch @@ -895,6 +896,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() 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." From a319a5379ab2a2d4bfa8816d0bde2b76e0ed5983 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 14:10:42 -0800 Subject: [PATCH 07/16] add Retina iOS Metal rendering --- docs/ios.md | 102 ++++++++++++++ src/silky/atlas.nim | 55 ++++++-- src/silky/contexts.nim | 12 +- src/silky/drawers/metal4.nim | 213 +++++++++++++---------------- tests/metal_shader_pixels.m | 181 ++++++++++++++++++++++++ tests/test_metal_shader_pixels.nim | 34 +++++ tests/test_retina_atlas.nim | 114 +++++++++++++++ tests/test_shader_codegen.nim | 26 +++- 8 files changed, 601 insertions(+), 136 deletions(-) create mode 100644 docs/ios.md create mode 100644 tests/metal_shader_pixels.m create mode 100644 tests/test_metal_shader_pixels.nim create mode 100644 tests/test_retina_atlas.nim diff --git a/docs/ios.md b/docs/ios.md new file mode 100644 index 00000000..ea9d23fe --- /dev/null +++ b/docs/ios.md @@ -0,0 +1,102 @@ +# 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. + +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 44-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. + +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, text, clipping, tint masks, 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`. + +Windy supplies basic committed text input through UIKit's software keyboard; +Silky's text fields use that input. Native iOS text selection, IME composition, +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_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/src/silky/atlas.nim b/src/silky/atlas.nim index 75fd9f24..6e15b245 100644 --- a/src/silky/atlas.nim +++ b/src/silky/atlas.nim @@ -48,6 +48,8 @@ type FontAtlas* = ref object ## The font atlas that is used to draw text. size*: float32 + pixelScale*: float32 = 1.0'f + ## Atlas pixels per logical point; layout metrics remain in points. lineHeight*: float32 descent*: float32 ascent*: float32 @@ -76,6 +78,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 atlas pixels per logical point, including 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))) @@ -337,11 +346,12 @@ proc newAtlasBuilderFromAtlas*( for _, e in atlas.entries: result.markOccupiedEntry(e.x, e.y, e.width, e.height) for fontAtlas in atlas.fonts.values: + let pixelScale = fontAtlas.rasterScale for variants in fontAtlas.entries.values: for letter in variants: let - w = letter.boundsWidth.ceil.int - h = letter.boundsHeight.ceil.int + w = round(letter.boundsWidth * pixelScale).int + h = round(letter.boundsHeight * pixelScale).int if w > 0 and h > 0: result.markOccupiedEntry(letter.x, letter.y, w, h) @@ -393,18 +403,34 @@ proc finiteBounds(bounds: Rect): Rect = else: rect(0, 0, 0, 0) -proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, chars: seq[string] = AsciiGlyphs, subpixelSteps: int = 0) = - ## Add a font to the atlas. +proc addFont*( + builder: AtlasBuilder, + path: string, + name: string, + size: float32, + chars: seq[string] = AsciiGlyphs, + subpixelSteps: int = 0, + pixelScale = 1.0'f +) = + ## Rasterizes a font at pixelScale density while preserving logical metrics. + if pixelScale <= 0 or pixelScale.classify notin {fcNormal, fcSubnormal}: + raise newException( + SilkyAtlasError, + "Font pixelScale must be finite and positive" + ) let fontAtlas = FontAtlas() fontAtlas.size = size + fontAtlas.pixelScale = pixelScale fontAtlas.subpixelSteps = subpixelSteps let typeface = readTypeface(path) var fontObj = newFont(typeface) fontObj.size = size + let logicalScale = fontObj.scale fontAtlas.lineHeight = (typeface.ascent - typeface.descent + typeface.lineGap) * fontObj.scale fontAtlas.ascent = typeface.ascent * fontObj.scale fontAtlas.descent = typeface.descent * fontObj.scale fontAtlas.lineGap = typeface.lineGap * fontObj.scale + fontObj.size = size * pixelScale # 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 @@ -416,7 +442,7 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, scale = fontObj.scale scaleMat = scale(vec2(scale)) baseBounds = glyphPath.computeBounds(scaleMat).snapToPixels().finiteBounds() - advance = typeface.getAdvance(rune) * scale + advance = typeface.getAdvance(rune) * logicalScale fontAtlas.entries[glyphStr] = @[] for variant in 0 ..< numVariants: let @@ -453,20 +479,20 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, fontAtlas.entries[glyphStr].add(LetterEntry( x: allocation.x, y: allocation.y, - boundsX: baseBounds.x + subpixelOffset.floor, - boundsY: baseBounds.y, - boundsWidth: offsetBounds.w.ceil, - boundsHeight: offsetBounds.h.ceil, + boundsX: (baseBounds.x + subpixelOffset.floor) / pixelScale, + boundsY: baseBounds.y / pixelScale, + boundsWidth: offsetBounds.w.ceil / pixelScale, + boundsHeight: offsetBounds.h.ceil / pixelScale, advance: advance )) else: fontAtlas.entries[glyphStr].add(LetterEntry( x: 0, y: 0, - boundsX: baseBounds.x, - boundsY: baseBounds.y, - boundsWidth: baseBounds.w, - boundsHeight: baseBounds.h, + boundsX: baseBounds.x / pixelScale, + boundsY: baseBounds.y / pixelScale, + boundsWidth: baseBounds.w / pixelScale, + boundsHeight: baseBounds.h / pixelScale, advance: advance )) # Kerning only needs to be stored once per base glyph (variant 0). @@ -474,7 +500,8 @@ proc addFont*(builder: AtlasBuilder, path: string, name: string, size: float32, let rune2 = glyphStr2.runeAt(0) let kerning = typeface.getKerningAdjustment(rune, rune2) if kerning != 0: - fontAtlas.entries[glyphStr][0].kerning[glyphStr2] = kerning * scale + fontAtlas.entries[glyphStr][0].kerning[glyphStr2] = + kerning * logicalScale fontAtlas.rebuildGlyphLookups() builder.atlas.fonts[name] = fontAtlas diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 0f79620c..933ed5a6 100644 --- a/src/silky/contexts.nim +++ b/src/silky/contexts.nim @@ -527,6 +527,7 @@ proc drawText*( let fontData = sk.atlas.fonts[font] + pixelScale = fontData.rasterScale maxPos = pos + vec2(maxWidth, maxHeight) hasSubpixel = fontData.subpixelSteps > 0 layer = sk.drawer.currentLayer @@ -597,7 +598,9 @@ proc drawText*( let variant = if hasSubpixel: - let frac = currentPos.x - currentPos.x.floor + let + pixelX = currentPos.x * pixelScale + frac = pixelX - pixelX.floor (frac * fontData.subpixelSteps.float32).int mod fontData.subpixelSteps else: @@ -627,14 +630,14 @@ proc drawText*( if entry.boundsWidth > 0 and entry.boundsHeight > 0: let glyphPos = vec2( - floor(currentPos.x) + entry.boundsX, - round(currentPos.y + entry.boundsY) + floor(currentPos.x * pixelScale) / pixelScale + entry.boundsX, + round((currentPos.y + entry.boundsY) * pixelScale) / pixelScale ) sk.drawQuad( glyphPos, vec2(entry.boundsWidth, entry.boundsHeight), vec2(entry.x.float32, entry.y.float32), - vec2(entry.boundsWidth, entry.boundsHeight), + vec2(entry.boundsWidth, entry.boundsHeight) * pixelScale, color ) @@ -721,7 +724,6 @@ 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) diff --git a/src/silky/drawers/metal4.nim b/src/silky/drawers/metal4.nim index 4fa8630e..4653477b 100644 --- a/src/silky/drawers/metal4.nim +++ b/src/silky/drawers/metal4.nim @@ -1,11 +1,15 @@ -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 + pixie, shady, vmath, windy, pkg/metal4, + shader const InitialVertexCapacity = 4096 + VertexBufferIndex = 1 + VertexShaderSource = toMSL(silkyVert, shaderVertex) + FragmentShaderSource = toMSL(silkyFrag, shaderFragment) type DrawerVertex* {.packed.} = object @@ -17,6 +21,11 @@ type clipSize*: Vec2 maskUv*: Vec2 + ShaderUniforms = object + ## Matches the Shady vertex shader's constant buffer layout. + viewportSize: Vec2 + atlasSize: Vec2 + Drawer* = ref object ## Metal 4-backed drawer state. ctx: MetalContext @@ -27,41 +36,34 @@ type vertexBufferPtr: pointer maxVertexCount: int viewportSize: IVec2 + atlasSize: IVec2 clearColor: MTLClearColor layers*: array[2, seq[DrawerVertex]] currentLayer*: int layerStack*: seq[int] +static: + doAssert sizeof(DrawerVertex) == 44 + doAssert sizeof(ShaderUniforms) == 16 + doAssert offsetOf(ShaderUniforms, viewportSize) == 0 + doAssert offsetOf(ShaderUniforms, atlasSize) == 8 + 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 -) = - ## 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 - 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) = @@ -73,10 +75,10 @@ proc uploadTexture(state: Drawer, image: Image) = false ) descriptor.setUsage(MTLTextureUsageShaderRead) - state.texture = state.ctx.device.newTextureWithDescriptor(descriptor) - checkNil(state.texture, "Could not create the atlas texture") + let texture = state.ctx.device.newTextureWithDescriptor(descriptor) + checkNil(texture, "Could not create the atlas texture") - state.texture.replaceRegion( + texture.replaceRegion( MTLRegion( origin: MTLOrigin(x: 0, y: 0, z: 0), size: MTLSize( @@ -89,96 +91,68 @@ proc uploadTexture(state: Drawer, image: Image) = unsafeAddr image.data[0], (image.width * 4).uint ) + state.texture.release() + state.texture = texture + state.atlasSize = ivec2(image.width.int32, image.height.int32) 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)]] -) { - 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(); - } - float4 base = tex.sample(texSampler, in.uv); - if (in.maskUv.x >= 0.0) { - float maskR = tex.sample(texSampler, in.maskUv).r; - return float4(base.rgb * mix(float3(1.0), in.color.rgb, maskR), base.a * in.color.a); - } - return base * in.color; -} -""" - 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") + checkNSError(error, "Could not compile the Shady Metal vertex shader") + checkNil(vertexLibrary, "Metal vertex library was nil") + defer: vertexLibrary.release() - let vertexFunction = library.newFunctionWithName(@"vertexMain") - checkNil(vertexFunction, "Could not load Metal shader entry point: vertexMain") - - 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) @@ -206,6 +180,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) @@ -220,6 +195,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) @@ -282,7 +261,12 @@ proc recordDraw(state: Drawer, vertexCount: int) = ) ) encoder.setCullMode(MTLCullModeNone) - encoder.setVertexBuffer(state.vertexBuffer, 0, 0) + encoder.setVertexBuffer(state.vertexBuffer, 0, VertexBufferIndex) + var uniforms = ShaderUniforms( + viewportSize: state.viewportSize.vec2, + atlasSize: state.atlasSize.vec2 + ) + encoder.setVertexBytes(uniforms.addr, sizeof(uniforms).uint, 0) encoder.setFragmentTexture(state.texture, 0) encoder.setFragmentSamplerState(state.sampler, 0) if vertexCount > 0: @@ -290,6 +274,9 @@ proc recordDraw(state: Drawer, vertexCount: int) = 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 endFrame*( drawer: Drawer, @@ -300,21 +287,15 @@ proc endFrame*( ) = ## Flushes the queued quads through Metal 4. discard size - let - atlasSize = vec2(image.width.float32, image.height.float32) - vertexCount = quadCount + let vertexCount = quadCount + if drawer.atlasSize != ivec2(image.width.int32, image.height.int32): + drawer.uploadTexture(image) 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], + quads, vertexCount * sizeof(DrawerVertex) ) 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_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_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_shader_codegen.nim b/tests/test_shader_codegen.nim index 8f1a9a17..81e70b52 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 block: let vertex = toShader(silkyVert, glsl3Desktop, shaderVertex) @@ -52,4 +52,28 @@ block: doAssert "(atlasSampler.Sample(atlasSamplerSampler, fragmentMaskUv)).r" in fragment doAssert "lerp(float3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR)" in fragment +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" From 82e996dda0aad77b13c40faa20ea2aa072b449f4 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 14:23:31 -0800 Subject: [PATCH 08/16] support Runway rendering and native input --- src/silky.nim | 11 +- src/silky/atlas.nim | 111 +- src/silky/clips.nim | 1 + src/silky/contexts.nim | 237 ++++- src/silky/drawers/metal4.nim | 344 +++++-- src/silky/drawers/ogl.nim | 261 ++++- src/silky/drawers/shader.nim | 18 +- src/silky/dsl.nim | 51 +- src/silky/frames.nim | 108 ++ src/silky/internal/inputs.nim | 118 ++- src/silky/richtextboxes.nim | 1450 +++++++++++++++++++++++++++ src/silky/semantics.nim | 126 ++- src/silky/testwindow.nim | 30 +- src/silky/textboxes.nim | 241 ++++- src/silky/widgets.nim | 87 +- tests/test_input_hooks.nim | 177 ++++ tests/test_metal_texture_pixels.nim | 233 +++++ tests/test_richimages.nim | 74 ++ tests/test_richtextboxes.nim | 255 +++++ tests/test_textboxes.nim | 2 +- 20 files changed, 3725 insertions(+), 210 deletions(-) create mode 100644 src/silky/frames.nim create mode 100644 src/silky/richtextboxes.nim create mode 100644 tests/test_input_hooks.nim create mode 100644 tests/test_metal_texture_pixels.nim create mode 100644 tests/test_richimages.nim create mode 100644 tests/test_richtextboxes.nim diff --git a/src/silky.nim b/src/silky.nim index 9cf01600..af4dbfe1 100644 --- a/src/silky.nim +++ b/src/silky.nim @@ -3,9 +3,12 @@ from silky/common import SilkyError export SilkyError when defined(silkyTesting): - import silky/[semantics, atlas, widgets, textboxes, testing, dsl, menus, profiles] + import silky/[ + semantics, atlas, widgets, textboxes, richtextboxes, testing, dsl, menus, + profiles + ] export semantics except textInputs - export atlas, tables, textboxes, testing, dsl, menus, profiles + export atlas, tables, textboxes, richtextboxes, testing, dsl, menus, profiles export widgets except button, checkBox, clickableIcon, dropDown, frame, group, h1text, icon, iconButton, image, listBox, progressBar, radioButton, ribbon, scrubber, text @@ -16,14 +19,14 @@ else: not defined(useMetal4) and not defined(useCpu): import opengl - import silky/[contexts, atlas, widgets, textboxes, dsl, menus] + import silky/[contexts, atlas, widgets, textboxes, richtextboxes, dsl, menus] when not defined(useDirectX) and not defined(useVulkan) and not defined(useMetal4) and not defined(useCpu): export opengl export contexts except textInputs - export windy, atlas, tables, textboxes, dsl, menus + export windy, atlas, tables, textboxes, richtextboxes, dsl, menus export widgets except button, checkBox, clickableIcon, dropDown, frame, group, h1text, icon, iconButton, image, listBox, progressBar, radioButton, ribbon, scrubber, text diff --git a/src/silky/atlas.nim b/src/silky/atlas.nim index 6e15b245..8389e8f0 100644 --- a/src/silky/atlas.nim +++ b/src/silky/atlas.nim @@ -24,6 +24,8 @@ type y*: int width*: int height*: int + pixelScale*: int = 1 + ## The number of texture pixels per logical pixel. LetterEntry* = object ## The position and size of a letter in the font atlas. @@ -48,13 +50,13 @@ type FontAtlas* = ref object ## The font atlas that is used to draw text. size*: float32 - pixelScale*: float32 = 1.0'f - ## Atlas pixels per logical point; layout metrics remain in points. lineHeight*: float32 descent*: float32 ascent*: float32 lineGap*: float32 subpixelSteps*: int + pixelScale*: float32 = 1 + ## The glyph raster density; font metrics remain logical. entries*: Table[string, seq[LetterEntry]] lookup*: GlyphLookup @@ -79,7 +81,7 @@ proc skipHook*(T: typedesc[FontAtlasObject], key: static string): bool = key == "lookup" proc rasterScale*(fontAtlas: FontAtlas): float32 {.inline.} = - ## Returns atlas pixels per logical point, including legacy atlas metadata. + ## Returns physical glyph density while accepting legacy atlas metadata. if fontAtlas.pixelScale > 0: fontAtlas.pixelScale else: @@ -300,9 +302,12 @@ proc writePng*(path, json: string, image: Image) = proc addImage*( builder: AtlasBuilder, name: string, - image: Image + image: Image, + pixelScale: int = 1 ): bool = ## Pack one image into the atlas. False when the atlas is full. + if pixelScale < 1: + raise newException(SilkyAtlasError, "Image pixel scale must be positive") let allocation = builder.allocator.allocate(image.width, image.height) if not allocation.success: return false @@ -315,7 +320,8 @@ proc addImage*( x: allocation.x, y: allocation.y, width: image.width, - height: image.height + height: image.height, + pixelScale: pixelScale ) true @@ -346,12 +352,12 @@ proc newAtlasBuilderFromAtlas*( for _, e in atlas.entries: result.markOccupiedEntry(e.x, e.y, e.width, e.height) for fontAtlas in atlas.fonts.values: - let pixelScale = fontAtlas.rasterScale for variants in fontAtlas.entries.values: for letter in variants: let - w = round(letter.boundsWidth * pixelScale).int - h = round(letter.boundsHeight * pixelScale).int + density = max(fontAtlas.pixelScale, 0.001'f) + w = (letter.boundsWidth * density).ceil.int + h = (letter.boundsHeight * density).ceil.int if w > 0 and h > 0: result.markOccupiedEntry(letter.x, letter.y, w, h) @@ -370,7 +376,12 @@ proc growAtlas*(builder: AtlasBuilder, newSize: int) = builder.allocator = newSkylineAllocator(newSize, builder.margin) builder.allocator.markRegion(0, 0, oldSize, oldSize) -proc addDir*(builder: AtlasBuilder, path: string, removePrefix: string = "") = +proc addDir*( + builder: AtlasBuilder, + path: string, + removePrefix: string = "", + pixelScale: int = 1 +) = ## Add all images in the given directory to the atlas. for file in walkDir(path): if file.path.endsWith(".png"): @@ -379,19 +390,24 @@ proc addDir*(builder: AtlasBuilder, path: string, removePrefix: string = "") = if removePrefix.len > 0: key.removePrefix(removePrefix) key.removeSuffix(".png") - if not builder.addImage(key, image): + if not builder.addImage(key, image, pixelScale): raise newException( ValueError, "Failed to allocate space for " & file.path & "\n" & "You need to increase the size of the atlas" ) -proc addDirRecursive*(builder: AtlasBuilder, path: string, removePrefix: string = "") = +proc addDirRecursive*( + builder: AtlasBuilder, + path: string, + removePrefix: string = "", + pixelScale: int = 1 +) = ## Add all images in the given directory and its subdirectories to the atlas. - builder.addDir(path, removePrefix) + builder.addDir(path, removePrefix, pixelScale) for entry in walkDir(path): if entry.kind == pcDir: - builder.addDirRecursive(entry.path, removePrefix) + builder.addDirRecursive(entry.path, removePrefix, pixelScale) proc finiteBounds(bounds: Rect): Rect = ## Glyphs with no outline (such as space) compute to infinite/NaN bounds, @@ -405,32 +421,32 @@ proc finiteBounds(bounds: Rect): Rect = proc addFont*( builder: AtlasBuilder, - path: string, + typeface: Typeface, name: string, size: float32, chars: seq[string] = AsciiGlyphs, subpixelSteps: int = 0, - pixelScale = 1.0'f + pixelScale: float32 = 1 ) = - ## Rasterizes a font at pixelScale density while preserving logical metrics. - if pixelScale <= 0 or pixelScale.classify notin {fcNormal, fcSubnormal}: - raise newException( - SilkyAtlasError, - "Font pixelScale must be finite and positive" - ) - let fontAtlas = FontAtlas() + ## Rasterizes a font at pixelScale with logical layout metrics. + if pixelScale <= 0 or + pixelScale.classify notin {fcNormal, fcSubnormal}: + raise newException(SilkyAtlasError, "Font pixel scale must be positive") + let + density = pixelScale.float32 + fontAtlas = FontAtlas() fontAtlas.size = size - fontAtlas.pixelScale = pixelScale fontAtlas.subpixelSteps = subpixelSteps - let typeface = readTypeface(path) - var fontObj = newFont(typeface) + fontAtlas.pixelScale = pixelScale + let fontObj = newFont(typeface) fontObj.size = size let logicalScale = fontObj.scale - fontAtlas.lineHeight = (typeface.ascent - typeface.descent + typeface.lineGap) * fontObj.scale - fontAtlas.ascent = typeface.ascent * fontObj.scale - fontAtlas.descent = typeface.descent * fontObj.scale - fontAtlas.lineGap = typeface.lineGap * fontObj.scale - fontObj.size = size * pixelScale + fontAtlas.lineHeight = + (typeface.ascent - typeface.descent + typeface.lineGap) * logicalScale + 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 @@ -467,7 +483,7 @@ proc addFont*( let allocation = builder.allocator.allocate(glyphImage.width, glyphImage.height) if not allocation.success: raise newException( - ValueError, + SilkyAtlasError, "Failed to allocate space for glyph: " & glyphStr & " variant " & $variant & "\n" & "You need to increase the size of the atlas" ) @@ -479,20 +495,20 @@ proc addFont*( fontAtlas.entries[glyphStr].add(LetterEntry( x: allocation.x, y: allocation.y, - boundsX: (baseBounds.x + subpixelOffset.floor) / pixelScale, - boundsY: baseBounds.y / pixelScale, - boundsWidth: offsetBounds.w.ceil / pixelScale, - boundsHeight: offsetBounds.h.ceil / pixelScale, + boundsX: (baseBounds.x + subpixelOffset.floor) / density, + boundsY: baseBounds.y / density, + boundsWidth: offsetBounds.w.ceil / density, + boundsHeight: offsetBounds.h.ceil / density, advance: advance )) else: fontAtlas.entries[glyphStr].add(LetterEntry( x: 0, y: 0, - boundsX: baseBounds.x / pixelScale, - boundsY: baseBounds.y / pixelScale, - boundsWidth: baseBounds.w / pixelScale, - boundsHeight: baseBounds.h / pixelScale, + boundsX: baseBounds.x / density, + boundsY: baseBounds.y / density, + boundsWidth: baseBounds.w / density, + boundsHeight: baseBounds.h / density, advance: advance )) # Kerning only needs to be stored once per base glyph (variant 0). @@ -505,6 +521,23 @@ proc addFont*( fontAtlas.rebuildGlyphLookups() builder.atlas.fonts[name] = fontAtlas +proc addFont*( + builder: AtlasBuilder, + path: string, + name: string, + size: float32, + chars: seq[string] = AsciiGlyphs, + subpixelSteps: int = 0, + pixelScale: float32 = 1 +) = + ## Loads a font file and rasterizes it at the requested pixel density. + try: + builder.addFont( + readTypeface(path), name, size, chars, subpixelSteps, pixelScale + ) + except PixieError as error: + raise newException(SilkyAtlasError, "Could not load font: " & error.msg) + proc write*(builder: AtlasBuilder, outputPngPath: string) = ## Write atlas image and JSON metadata into a single PNG. writePng(outputPngPath, builder.atlas.toJson(), builder.atlasImage) diff --git a/src/silky/clips.nim b/src/silky/clips.nim index 14ae5cf6..5653d4f5 100644 --- a/src/silky/clips.nim +++ b/src/silky/clips.nim @@ -18,6 +18,7 @@ type ## Vertex and clip boundaries for a deferred layout on both layers. marks*: array[2, int] clipMark*: int + textMark*: int proc intersectClips(a, b: Rect): Rect = ## Intersects clip bounds while keeping empty intersections empty. diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 933ed5a6..1d235544 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, layout, profiles], + silky/[atlas, clips, common, frames, layout, profiles], silky/internal/inputs -export layout, profiles +export frames, layout, profiles when defined(useDirectX): import silky/drawers/dx12 @@ -89,6 +89,9 @@ type theme*: Theme = Theme() cursor*: Cursor = Cursor(kind: ArrowCursor) inputs: TextInputs + frames: FrameSchedule + frameInput: FrameInput + frameHadInput: bool mousePos*: Vec2 mouseDelta*: Vec2 mouseIdleTime*: float64 @@ -125,6 +128,39 @@ proc textInputs*(sk: Silky): TextInputs = ## Provides internal text input state to the text widgets. sk.inputs +proc renderMode*(sk: Silky): RenderMode = + ## Returns continuous game rendering or event-driven application rendering. + sk.frames.mode + +proc requestFrame*(sk: Silky, delayMs = 0) = + ## Invalidates data or schedules an animation frame on the UI thread. + sk.frames.requestFrame(delayMs) + +proc `renderMode=`*(sk: Silky, mode: RenderMode) = + ## Selects the rendering policy without changing the drawing API. + sk.frames.mode = mode + sk.requestFrame() + +proc `onFrameRequested=`*(sk: Silky, wake: proc()) = + ## Connects invalidation and native editor input to an event-loop wakeup. + sk.frames.wake = wake + if sk.inputs != nil: + sk.inputs.onEvent = wake + +proc needsFrame*(sk: Silky, window: Window): bool = + ## Checks UI input and scheduled deadlines before drawing an app frame. + if sk.frames.mode == ContinuousRender: + return true + if sk.frameInput.inputChanged(window, sk.inputs.hasPendingEvents()): + sk.requestFrame() + sk.frames.needsFrame() + +proc nextFrameDelay*(sk: Silky, window: Window, maxWaitMs = 1000): int = + ## Bounds an event-loop wait by pending UI work and animation deadlines. + if sk.needsFrame(window): + return 0 + sk.frames.nextFrameDelay(maxWaitMs) + proc pushLayer*(sk: Silky, layer: int) = ## Pushes a new rendering layer onto the stack. sk.drawer.layerStack.add(sk.drawer.currentLayer) @@ -236,6 +272,7 @@ proc vertexMark*(sk: Silky): int = proc beginVertexSpan*(sk: Silky): VertexSpan = ## Captures vertices and original clips until a layout is placed. result.clipMark = sk.clipStack.regions.len + result.textMark = sk.inputs.textPlacementMark() for layer in 0 ..< result.marks.len: result.marks[layer] = sk.drawer.layers[layer].len sk.vertexClips[layer].setLen(result.marks[layer]) @@ -243,11 +280,20 @@ proc beginVertexSpan*(sk: Silky): VertexSpan = proc endVertexSpan*(sk: Silky, span: VertexSpan, offset: Vec2) = ## Places a deferred span and resolves clips against fixed ancestors. + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2( + round(offset.x * scale) / scale, + round(offset.y * scale) / scale + ) + # Deferred placement must preserve the pixel grid used by text and images. + # Layout and clipping retain their exact logical positions. sk.clipStack.translateClips(span.clipMark, offset) + sk.inputs.translateTextInput(span.textMark, paintOffset * scale) for layer in 0 ..< span.marks.len: for i in span.marks[layer] ..< sk.drawer.layers[layer].len: let clip = sk.clipStack.regions[sk.vertexClips[layer][i]].visible - sk.drawer.layers[layer][i].pos += offset + sk.drawer.layers[layer][i].pos += paintOffset sk.drawer.layers[layer][i].clipPos = clip.xy sk.drawer.layers[layer][i].clipSize = clip.wh dec sk.clipStack.captures @@ -257,6 +303,7 @@ proc moveVerticesBehind*(sk: Silky, layer, spanStart, chromeStart: int) = ## span so late-drawn parent chrome renders behind its children (T2). let total = sk.drawer.layers[layer].len if chromeStart > spanStart and chromeStart < total: + sk.inputs.moveTextInputBehind(ord(layer), spanStart, chromeStart, total) sk.drawer.layers[layer].rotateLeft( spanStart ..< total, chromeStart - spanStart ) @@ -270,16 +317,23 @@ proc translateVertices*(sk: Silky, layer, spanStart: int, offset: Vec2) = ## whose position is only known at scope close (T6). if offset == vec2(0, 0): return + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2( + round(offset.x * scale) / scale, + round(offset.y * scale) / scale + ) + sk.inputs.translateTextInputVertices(ord(layer), spanStart, paintOffset * scale) for i in spanStart ..< sk.drawer.layers[layer].len: - sk.drawer.layers[layer][i].pos += offset + sk.drawer.layers[layer][i].pos += paintOffset proc getImageSize*(sk: Silky, image: string): Vec2 = - ## Returns the size of an atlas image in pixels. + ## Returns the logical size of an atlas image. if image notin sk.atlas.entries: echo "[Warning] Image not found in atlas: " & image return vec2(0, 0) let uv = sk.atlas.entries[image] - vec2(uv.width.float32, uv.height.float32) + vec2(uv.width.float32, uv.height.float32) / max(uv.pixelScale, 1).float32 proc nextRune(text: string, i: var int): Rune {.inline.} = ## Reads one UTF-8 rune and advances the byte index. @@ -295,6 +349,11 @@ proc peekRune(text: string, i: int, rune: var Rune): bool {.inline.} = proc shouldShowTooltip*(sk: Silky): bool = ## Returns true when a tooltip should be shown. + if sk.renderMode == OnDemandRender and sk.hover and + sk.mouseIdleTime < sk.tooltipThreshold: + sk.requestFrame(max( + 1, ((sk.tooltipThreshold - sk.mouseIdleTime) * 1000).int + 1 + )) sk.hover and sk.mouseIdleTime >= sk.tooltipThreshold proc resetInteractions*(sk: Silky) = @@ -305,6 +364,12 @@ proc resetInteractions*(sk: Silky) = 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.inputs.beginInputFrame(window) beginProfileFrame() @@ -348,6 +413,17 @@ proc endInteractions(interactor: var Interactor) = 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]: + sk.requestFrame(16) + let previousCursor = sk.window.cursor + if previousCursor.kind != sk.cursor.kind or + (sk.cursor.kind == CustomCursor and + (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() @@ -467,6 +543,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], @@ -527,7 +626,8 @@ proc drawText*( let fontData = sk.atlas.fonts[font] - pixelScale = fontData.rasterScale + density = max(fontData.pixelScale, 0.001'f) + displayScale = max(sk.uiScale, 0.001'f) maxPos = pos + vec2(maxWidth, maxHeight) hasSubpixel = fontData.subpixelSteps > 0 layer = sk.drawer.currentLayer @@ -552,9 +652,9 @@ proc drawText*( of LeftAlign: 0.0'f of CenterAlign: - floor((maxWidth - lineWidth) * 0.5) + floor((maxWidth - lineWidth) * 0.5 * displayScale) / displayScale of RightAlign: - floor(maxWidth - lineWidth) + floor((maxWidth - lineWidth) * displayScale) / displayScale if dx != 0: for j in lineStartIdx ..< sk.drawer.layers[layer].len: sk.drawer.layers[layer][j].pos.x += dx @@ -599,8 +699,8 @@ proc drawText*( let variant = if hasSubpixel: let - pixelX = currentPos.x * pixelScale - frac = pixelX - pixelX.floor + rasterX = currentPos.x * density + frac = rasterX - rasterX.floor (frac * fontData.subpixelSteps.float32).int mod fontData.subpixelSteps else: @@ -629,15 +729,24 @@ proc drawText*( break if entry.boundsWidth > 0 and entry.boundsHeight > 0: - let glyphPos = vec2( - floor(currentPos.x * pixelScale) / pixelScale + entry.boundsX, - round((currentPos.y + entry.boundsY) * pixelScale) / pixelScale - ) + let + glyphX = + if hasSubpixel: + floor(currentPos.x * density) / density + entry.boundsX + else: + floor((currentPos.x + entry.boundsX) * displayScale) / + displayScale + # Keep every glyph on one baseline, including mismatched atlas scales. + glyphPos = vec2( + glyphX, + round(currentPos.y * displayScale) / displayScale + entry.boundsY + ) + glyphSize = vec2(entry.boundsWidth, entry.boundsHeight) sk.drawQuad( glyphPos, - vec2(entry.boundsWidth, entry.boundsHeight), + glyphSize, vec2(entry.x.float32, entry.y.float32), - vec2(entry.boundsWidth, entry.boundsHeight) * pixelScale, + glyphSize * density, color ) @@ -660,9 +769,9 @@ proc drawText*( of TopAlign: 0.0'f of MiddleAlign: - floor((maxHeight - textHeight) * 0.5) + floor((maxHeight - textHeight) * 0.5 * displayScale) / displayScale of BottomAlign: - floor(maxHeight - textHeight) + floor((maxHeight - textHeight) * displayScale) / displayScale if dy != 0: for j in textStartIdx ..< sk.drawer.layers[layer].len: sk.drawer.layers[layer][j].pos.y += dy @@ -727,6 +836,47 @@ proc uploadAtlas*(sk: Silky) = 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: @@ -746,6 +896,10 @@ proc addAtlasImage*(sk: Silky, name: string, image: Image) = sk.atlas = sk.builder.atlas sk.uploadAtlas() +proc alignPixels(pos: Vec2, scale: float32): Vec2 = + ## Aligns a logical point to the framebuffer's pixel grid. + vec2(round(pos.x * scale), round(pos.y * scale)) / scale + proc drawImage*( sk: Silky, name: string, @@ -757,7 +911,15 @@ proc drawImage*( if name notin sk.atlas.entries: echo "[Warning] Sprite not found in atlas: " & name return - let uv = sk.atlas.entries[name] + let + uv = sk.atlas.entries[name] + density = max(uv.pixelScale, 1).float32 + displayScale = max(sk.uiScale, 0.001'f) + alignedPos = + if density > 1: + alignPixels(pos, displayScale) + else: + pos var mPos = vec2(-1, -1) mSize = vec2(0, 0) @@ -766,8 +928,8 @@ proc drawImage*( mPos = vec2(m.x.float32, m.y.float32) mSize = vec2(m.width.float32, m.height.float32) sk.drawQuad( - pos, - vec2(uv.width.float32, uv.height.float32), + alignedPos, + vec2(uv.width.float32, uv.height.float32) / density, vec2(uv.x.float32, uv.y.float32), vec2(uv.width.float32, uv.height.float32), color, @@ -798,23 +960,28 @@ proc draw9Patch*( return let scale = max(sk.sliceScale, 1) - topS = top * scale - rightS = right * scale - bottomS = bottom * scale - leftS = left * scale uv = sk.atlas.entries[name] - l = leftS.float32 - r = rightS.float32 - u = topS.float32 - d = bottomS.float32 + density = max(uv.pixelScale, 1) + topS = top * scale * density + rightS = right * scale * density + bottomS = bottom * scale * density + leftS = left * scale * density + displayScale = max(sk.uiScale, 0.001'f) + 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] srcHeights = [topS, uv.height - topS - bottomS, bottomS] - dstXOffsets = [0.0'f, l, size.x - r] - dstWidths = [l, size.x - l - r, r] - dstYOffsets = [0.0'f, u, size.y - d] - dstHeights = [u, size.y - u - d, d] + dstXOffsets = [0.0'f, l, alignedSize.x - r] + dstWidths = [l, alignedSize.x - l - r, r] + dstYOffsets = [0.0'f, u, alignedSize.y - d] + dstHeights = [u, alignedSize.y - u - d, d] order = [ (0, 0), (2, 0), (0, 2), (2, 2), (1, 0), (0, 1), (2, 1), (1, 2), @@ -830,7 +997,7 @@ proc draw9Patch*( if dw <= 0.001 or dh <= 0.001 or sw <= 0 or sh <= 0: continue sk.drawQuad( - vec2(pos.x + dstXOffsets[x], pos.y + dstYOffsets[y]), + alignedPos + vec2(dstXOffsets[x], dstYOffsets[y]), vec2(dw, dh), vec2( (uv.x + srcXOffsets[x]).float32, diff --git a/src/silky/drawers/metal4.nim b/src/silky/drawers/metal4.nim index 4653477b..3033e980 100644 --- a/src/silky/drawers/metal4.nim +++ b/src/silky/drawers/metal4.nim @@ -2,12 +2,14 @@ when not (defined(macosx) or defined(ios)): {.error: "The Silky Metal backend requires macOS or iOS.".} import + std/tables, pixie, shady, vmath, windy, pkg/metal4, - shader + ../common, shader const InitialVertexCapacity = 4096 VertexBufferIndex = 1 + MaximumTextureSize = 16384 VertexShaderSource = toMSL(silkyVert, shaderVertex) FragmentShaderSource = toMSL(silkyFrag, shaderFragment) @@ -20,6 +22,12 @@ 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. @@ -37,13 +45,17 @@ type maxVertexCount: int viewportSize: IVec2 atlasSize: IVec2 + 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) == 44 + doAssert sizeof(DrawerVertex) == 48 doAssert sizeof(ShaderUniforms) == 16 doAssert offsetOf(ShaderUniforms, viewportSize) == 0 doAssert offsetOf(ShaderUniforms, atlasSize) == 8 @@ -52,6 +64,62 @@ proc clampViewport(size: IVec2): IVec2 = ## Clamps the viewport to valid drawable dimensions. ivec2(max(1'i32, size.x), max(1'i32, size.y)) +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 > MaximumTextureSize or height > MaximumTextureSize: + raise newException(SilkyError, "Image texture exceeds the Metal 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 +) = + ## 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. let buffer = state.ctx.device.newBufferWithLength( @@ -68,32 +136,74 @@ proc createVertexBuffer(state: Drawer, maxVertexCount: int) = 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 - ) - descriptor.setUsage(MTLTextureUsageShaderRead) - let texture = state.ctx.device.newTextureWithDescriptor(descriptor) - checkNil(texture, "Could not create the atlas texture") + 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) - 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 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) ) - state.texture.release() - state.texture = texture - state.atlasSize = ivec2(image.width.int32, image.height.int32) + +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. @@ -210,8 +320,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. @@ -238,39 +352,65 @@ 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, VertexBufferIndex) - var uniforms = ShaderUniforms( - viewportSize: state.viewportSize.vec2, - atlasSize: state.atlasSize.vec2 - ) - encoder.setVertexBytes(uniforms.addr, sizeof(uniforms).uint, 0) - encoder.setFragmentTexture(state.texture, 0) 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() @@ -278,25 +418,111 @@ proc recordDraw(state: Drawer, vertexCount: int) = commandBuffer.waitUntilCompleted() checkNSError(commandBuffer.error(), "Metal failed to render the Silky frame") -proc endFrame*( +proc uploadVertices( drawer: Drawer, image: Image, - size: Vec2, - quads: pointer, - quadCount: int + vertices: pointer, + vertexCount: int ) = - ## Flushes the queued quads through Metal 4. - discard size - let vertexCount = quadCount + ## 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, - quads, + vertices, vertexCount * sizeof(DrawerVertex) ) - drawer.recordDraw(vertexCount) +proc endFrame*( + drawer: Drawer, + image: Image, + size: Vec2, + quads: pointer, + quadCount: int +) = + ## Flushes the queued quads through Metal 4. + discard size + 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 + ) + + 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/drawers/shader.nim b/src/silky/drawers/shader.nim index 4dd4a58c..7e975f47 100644 --- a/src/silky/drawers/shader.nim +++ b/src/silky/drawers/shader.nim @@ -41,17 +41,19 @@ proc silkyFrag*( fragmentMaskUv: Vec2, fragColor: var Vec4 ) = + # Sample before clipping so neighboring fragments provide valid derivatives. + let base = texture(atlasSampler, fragmentUv) + var shaded = base * fragmentColor + if fragmentMaskUv.x >= 0.0: + let maskR = texture(atlasSampler, fragmentMaskUv).r + shaded = vec4( + base.rgb * mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), + base.a * fragmentColor.a + ) if fragmentPos.x < fragmentClipPos.x or fragmentPos.y < fragmentClipPos.y or fragmentPos.x > fragmentClipPos.x + fragmentClipSize.x or fragmentPos.y > fragmentClipPos.y + fragmentClipSize.y: discardFragment() - elif fragmentMaskUv.x >= 0.0: - let base = texture(atlasSampler, fragmentUv) - let maskR = texture(atlasSampler, fragmentMaskUv).r - fragColor = vec4( - base.rgb * mix(vec3(1.0, 1.0, 1.0), fragmentColor.rgb, maskR), - base.a * fragmentColor.a - ) else: - fragColor = texture(atlasSampler, fragmentUv) * fragmentColor + fragColor = shaded diff --git a/src/silky/dsl.nim b/src/silky/dsl.nim index 0b74d27d..cd2dbf31 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) @@ -936,6 +953,38 @@ template button*(label: string, isEnabled: bool, body: untyped) = baseWidgets.button(label, isEnabled, false): body +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + isError: bool, + body: untyped +) = + ## Creates a native minimum-size button inside the current DSL layout. + profileBlock "button": + sk.startCurrentChildren() + baseWidgets.button(label, minimumSize, isEnabled, isError): + body + +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + body: untyped +) = + ## Creates a minimum-size button with an enabled state. + profileBlock "button": + sk.startCurrentChildren() + baseWidgets.button(label, minimumSize, isEnabled, false): + body + +template button*(label: string, minimumSize: Vec2, body: untyped) = + ## Creates an enabled minimum-size button. + profileBlock "button": + sk.startCurrentChildren() + baseWidgets.button(label, minimumSize, true, false): + body + template icon*(imageName: string) = profileBlock "icon": sk.startCurrentChildren() diff --git a/src/silky/frames.nim b/src/silky/frames.nim new file mode 100644 index 00000000..dbff1cb4 --- /dev/null +++ b/src/silky/frames.nim @@ -0,0 +1,108 @@ +import + std/monotimes, + vmath + +from windy/common import Button + +type + RenderMode* = enum + ContinuousRender, OnDemandRender + + FrameSchedule* = object + mode*: RenderMode + wake*: proc() + dirty: bool = true + deadline: int64 = int64.high + + FrameInput* = object + initialized: bool + position, size: IVec2 + focused, visible, minimized: bool + scale: float32 + +proc frameMilliseconds*(): int64 {.raises: [].} = + ## Reads the monotonic clock used for redraw deadlines. + getMonoTime().ticks div 1_000_000 + +proc requestFrame*( + schedule: var FrameSchedule, + delayMs = 0, + nowMs = frameMilliseconds() +) = + ## Requests a redraw on the UI thread, immediately or after a delay. + let + dirty = schedule.dirty + deadline = schedule.deadline + if delayMs <= 0: + schedule.dirty = true + else: + schedule.deadline = min(schedule.deadline, nowMs + delayMs.int64) + if (schedule.dirty != dirty or schedule.deadline < deadline) and + schedule.wake != nil: + schedule.wake() + +proc needsFrame*(schedule: FrameSchedule, nowMs = frameMilliseconds()): bool + {.raises: [].} = + ## Reports continuous rendering, invalidation, or an expired deadline. + schedule.mode == ContinuousRender or schedule.dirty or + schedule.deadline <= nowMs + +proc nextFrameDelay*( + schedule: FrameSchedule, + maxWaitMs = 1000, + nowMs = frameMilliseconds() +): int {.raises: [].} = + ## Returns the bounded native-event wait until another frame is due. + if schedule.needsFrame(nowMs): + return 0 + let limit = max(0, maxWaitMs) + if schedule.deadline == int64.high: + return limit + min(limit.int64, max(0'i64, schedule.deadline - nowMs)).int + +proc beginFrame*(schedule: var FrameSchedule, nowMs = frameMilliseconds()) + {.raises: [].} = + ## Consumes invalidation and expired timers before drawing the next frame. + schedule.dirty = false + if schedule.deadline <= nowMs: + schedule.deadline = int64.high + +proc inputChanged*( + previous: var FrameInput, + window: auto, + pendingText: bool +): bool = + ## Detects native geometry, pointer, focus, and queued editor input changes. + let + position = window.mousePos + size = window.size + focused = + when compiles(window.focused): window.focused + else: true + visible = + when compiles(window.visible): window.visible + else: true + minimized = + when compiles(window.minimized): window.minimized + else: false + scale = + when compiles(window.contentScale): window.contentScale + else: 1.0'f + result = pendingText or not previous.initialized or + position != previous.position or size != previous.size or + focused != previous.focused or visible != previous.visible or + minimized != previous.minimized or scale != previous.scale or + window.scrollDelta != vec2(0) or window.mouseDelta != ivec2(0) + for button in Button: + if window.buttonPressed[button] or window.buttonReleased[button]: + result = true + break + previous = FrameInput( + initialized: true, + position: position, + size: size, + focused: focused, + visible: visible, + minimized: minimized, + scale: scale + ) diff --git a/src/silky/internal/inputs.nim b/src/silky/internal/inputs.nim index 63c3c92c..4f248ec4 100644 --- a/src/silky/internal/inputs.nim +++ b/src/silky/internal/inputs.nim @@ -1,5 +1,6 @@ import std/unicode, + vmath, silky/common when defined(silkyTesting): @@ -11,17 +12,23 @@ const MaxPendingEvents = 65_536 type InputKind* = enum - KeyDown, KeyUp, TextInput + KeyDown, KeyUp, TextInput, TextCommit, NativeEdit InputEvent* = object kind*: InputKind button*: Button rune*: Rune + text*: string + edit*: TextInputEdit control*, shift*, alt*, super*: bool CallbackIdentity = tuple[code, environment: pointer] TextInputs* = ref object + onEvent*: proc() + ## 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 @@ -29,10 +36,12 @@ type epoch: uint64 submitted: bool consumed: bool - callbacks: array[4, CallbackIdentity] + callbacks: array[6, CallbackIdentity] forwardedKeys: set[Button] consumedKeys: set[Button] releaseCallback: proc(button: Button) + pendingText: TextInputState + placementSerial, placementLayer, placementVertex: int proc identity[T](callback: T): CallbackIdentity = ## Identifies a callback without retaining its closure environment. @@ -42,6 +51,10 @@ proc focusEpoch*(inputs: TextInputs): uint64 = ## Returns the generation of the current text focus. inputs.epoch +proc hasPendingEvents*(inputs: TextInputs): bool {.raises: [].} = + ## Reports queued edits without consuming the editor's input batch. + inputs != nil and inputs.events.len > 0 + when defined(silkyTesting): proc filterButtons*( inputs: TextInputs, buttons: array[Button, bool] @@ -67,6 +80,8 @@ proc stopInput*(inputs: TextInputs, window: Window) = inputs.editable = false inputs.id.setLen(0) inputs.events.setLen(0) + inputs.pendingText = TextInputState() + window.setTextInputState(TextInputState()) if window.runeInputEnabled: window.runeInputEnabled = false @@ -86,6 +101,8 @@ proc addEvent(inputs: TextInputs, event: InputEvent) = if inputs.events.len >= MaxPendingEvents: raise newException(SilkyError, "Too many pending text input events") inputs.events.add(event) + if inputs.onEvent != nil: + inputs.onEvent() proc installPress(inputs: TextInputs, window: Window) = ## Installs this handler only when the window's callback changes. @@ -99,6 +116,18 @@ proc installPress(inputs: TextInputs, window: Window) = event.kind = KeyDown event.button = button 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: + inputs.addEvent(event) + return inputs.addEvent(event) return if button >= Key0: @@ -161,6 +190,38 @@ proc installFocus(inputs: TextInputs, window: Window) = previousFocus() inputs.callbacks[3] = identity(window.onFocusChange) +proc installText(inputs: TextInputs, window: Window) = + ## Captures complete native commits before a dictation tool restores state. + let + windowPointer = cast[pointer](window) + previousText = window.onTextInput + window.onTextInput = proc(text: string) = + ## Preserves one native insertion as one ordered editing operation. + let window = cast[Window](windowPointer) + if inputs.active: + if inputs.editable and text.len > 0: + inputs.addEvent(InputEvent(kind: TextCommit, text: text)) + return + if previousText != nil: + previousText(text) + elif window.onRune != nil: + for rune in text.runes: + window.onRune(rune) + inputs.callbacks[4] = identity(window.onTextInput) + +proc installEdit(inputs: TextInputs, window: Window) = + ## Queues native accessibility edits in the same order as keyboard input. + let previousEdit = window.onTextEdit + window.onTextEdit = proc(edit: TextInputEdit) = + ## Applies edits only to the field that currently owns text input. + if inputs.active: + if inputs.editable: + inputs.addEvent(InputEvent(kind: NativeEdit, edit: edit)) + return + if previousEdit != nil: + previousEdit(edit) + inputs.callbacks[5] = identity(window.onTextEdit) + proc overrideCallbacks( inputs: TextInputs, window: Window, initialize = false ) = @@ -173,6 +234,10 @@ proc overrideCallbacks( inputs.installRune(window) if initialize or identity(window.onFocusChange) != inputs.callbacks[3]: inputs.installFocus(window) + if initialize or identity(window.onTextInput) != inputs.callbacks[4]: + inputs.installText(window) + if initialize or identity(window.onTextEdit) != inputs.callbacks[5]: + inputs.installEdit(window) proc newTextInputs*(window: Window): TextInputs = ## Sets up all text input handling directly from the window. @@ -187,6 +252,51 @@ proc beginInputFrame*(inputs: TextInputs, window: Window) = inputs.overrideCallbacks(window) inputs.submitted = false inputs.consumed = false + inputs.pendingText = TextInputState() + inputs.placementSerial = 0 + +proc textPlacementMark*(inputs: TextInputs): int = + ## Marks the start of a deferred layout containing a focused editor. + if inputs != nil: + result = inputs.placementSerial + +proc publishTextInput*( + inputs: TextInputs, state: TextInputState, layer, firstVertex: int +) = + ## Stages native editor state until layout placement is complete. + inputs.pendingText = state + inputs.placementLayer = layer + inputs.placementVertex = firstVertex + inc inputs.placementSerial + +proc translateTextInput*(inputs: TextInputs, first: int, offset: Vec2) = + ## Moves an editor published inside a deferred layout span. + if inputs != nil and inputs.placementSerial > first: + inputs.pendingText.bounds.x += offset.x + inputs.pendingText.bounds.y += offset.y + +proc translateTextInputVertices*( + inputs: TextInputs, layer, first: int, offset: Vec2 +) = + ## Moves editor bounds along with their rendered vertices. + if inputs != nil and inputs.placementSerial > 0 and + inputs.placementLayer == layer and inputs.placementVertex >= first: + inputs.pendingText.bounds.x += offset.x + inputs.pendingText.bounds.y += offset.y + +proc moveTextInputBehind*( + inputs: TextInputs, layer, spanStart, chromeStart, total: int +) = + ## Preserves the editor's vertex position when parent chrome is reordered. + if inputs == nil or inputs.placementSerial == 0: + return + if inputs.placementLayer != layer or + inputs.placementVertex < spanStart or inputs.placementVertex >= total: + return + if inputs.placementVertex < chromeStart: + inputs.placementVertex += total - chromeStart + else: + inputs.placementVertex -= chromeStart - spanStart proc submitInput*( inputs: TextInputs, @@ -226,3 +336,7 @@ proc endInputFrame*(inputs: TextInputs, window: Window) = ## Ends capture when the active field was not submitted this frame. if not inputs.submitted: inputs.stopInput(window) + elif inputs.editable and inputs.pendingText.id == inputs.id: + window.setTextInputState(inputs.pendingText) + else: + window.setTextInputState(TextInputState()) diff --git a/src/silky/richtextboxes.nim b/src/silky/richtextboxes.nim new file mode 100644 index 00000000..891f722a --- /dev/null +++ b/src/silky/richtextboxes.nim @@ -0,0 +1,1450 @@ +import + std/[algorithm, tables, unicode, times], + vmath, bumpy, chroma, + silky/atlas, silky/internal/inputs, silky/textboxes + +when defined(silkyTesting): + import silky/[semantics, testing, profiles] +else: + import silky/[contexts, profiles], windy + +const + LF = Rune(10) + Space = Rune(32) + Tab = Rune(9) + DoubleClickTime = 0.4 + SelectionColor = rgbx(30, 60, 130, 128) + MaxRunRunes = 128 + MaxTableColumns = 128 + +when defined(macos): + const TextBoxScrollSpeed = 10.0f +else: + const TextBoxScrollSpeed = -10.0f + +type + TextSpan* = object + ## Read-only formatting over a half-open range of rune offsets. + first*, last*: int + font*: string + color*: ColorRGBX + background*: ColorRGBX + strikethrough*: bool + 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 + patchBorder*: int + label*, labelFont*: string + labelColor*: ColorRGBX + labelSpacing*: float32 + ruleColor*: ColorRGBX + ruleThickness*: float32 + ## Positive thickness turns an empty block into a horizontal rule. + quoteDepth*, quoteContinue*: int + ## Continued quote levels also draw their borders through spacing. + 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 + 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. + editor*: TextBoxState + spans*: seq[TextSpan] + blocks*: seq[TextBlock] + activatedSpan*: int = -1 + hoveredSpan*: int = -1 + 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] + +proc newRichTextBoxState*(text = "", wordWrap = true): RichTextBoxState = + ## Creates a read-only document with its own selection and layout cache. + result = RichTextBoxState( + editor: TextBoxState(wordWrap: wordWrap, enabled: false) + ) + result.editor.setText(text) + +proc getText*(state: RichTextBoxState): string = + ## Returns the underlying selectable text without formatting markers. + state.editor.getText() + +proc sameText*(state: RichTextBoxState, text: string): bool = + ## 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, + text: string, + preserveSelection = false +) = + ## Replaces content while optionally retaining a streamed selection. + state.editor.setText(text, preserveSelection) + +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], + baseFont: string, + 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], + baseFont: string, + maxWidth: float32 +) = + ## Combines block layouts into one selectable document and native run list. + state.editor.positionedLayout = true + state.editor.lineHeight = fonts[baseFont].lineHeight + state.editor.lastMaxWidth = maxWidth + state.editor.layout.setLen(state.editor.runes.len) + 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 + var + covered = 0 + previousEnd = rect(0, 0, 0, state.editor.lineHeight) + for item in state.blocks: + let + first = clamp(item.first, covered, state.editor.runes.len) + last = clamp(item.last, first, state.editor.runes.len) + width = max(0.0'f, maxWidth) + depth = max(0, item.quoteDepth) + padding = vec2( + if depth > 0: + min(max(0.0'f, item.padding.x), width / 2) + else: + max(0.0'f, item.padding.x), + max(0.0'f, item.padding.y) + ) + quoteInset = min( + max(0.0'f, width - padding.x * 2), + depth.float32 * max(0.0'f, item.quoteIndent) + ) + 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( + quoteInset + padding.x, + state.editor.layoutHeight + padding.y + ) + height = item.ruleThickness + padding.y * 2 + state.blockLayouts.add(BlockLayout( + bounds: rect(quoteInset, state.editor.layoutHeight, blockWidth, height), + ruleBounds: rect( + origin, + vec2(max(0.0'f, blockWidth - padding.x * 2), item.ruleThickness) + ), + quoteBounds: rect( + padding.x, + state.editor.layoutHeight, + max(0.0'f, width - padding.x * 2), + height + ) + )) + state.editor.layoutCursor = rect(origin, vec2(0)) + state.editor.layoutHeight += height + max(0.0'f, item.spacing) + previousEnd = state.editor.layoutCursor + covered = last + continue + let + font = + if item.font in fonts: + item.font + else: + baseFont + labelFont = + if item.labelFont in fonts: + item.labelFont + else: + baseFont + labelHeight = + if item.label.len > 0: + 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 + imageHeight + ) + local = RichTextBoxState( + editor: TextBoxState( + runes: state.editor.runes[first ..< last], + wordWrap: state.editor.wordWrap and not item.noWrap, + enabled: false + ), + spans: @[TextSpan()] + ) + var spanIndices = @[-1] + for index, span in state.spans: + if span.first < last and span.last > first: + var relative = span + relative.first = max(first, span.first) - first + relative.last = min(last, span.last) - first + 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) + let span = local.runeSpans[i] + if span >= 0: + state.runeSpans[first + i] = spanIndices[span] + for run in local.runs.mitems: + 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) + state.editor.layoutCursor = rect( + origin.x, + origin.y, + 0, + local.editor.lineHeight + ) + if local.editor.layout.len > 0: + let bounds = local.editor.layout[^1] + contentHeight = bounds.y + bounds.h + state.editor.layoutCursor = rect( + origin.x + bounds.x + bounds.w, + origin.y + bounds.y, + 0, + bounds.h + ) + if local.editor.runes[^1] == LF: + contentHeight += local.editor.lineHeight + state.editor.layoutCursor.x = origin.x + state.editor.layoutCursor.y += local.editor.lineHeight + 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, 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 + ), + 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 + )) + state.editor.layoutHeight += height + max(0.0'f, item.spacing) + previousEnd = state.editor.layoutCursor + covered = last + for i in covered ..< state.editor.runes.len: + state.editor.layout[i] = previousEnd + state.editor.dirty = false + +proc computeLayout*( + state: RichTextBoxState, + fonts: Table[string, FontAtlas], + baseFont: string, + maxWidth: float32 +) = + ## 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.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 + resolvedFonts = @[base] + fontNames = @[baseFont] + baseline = base.ascent + descent = base.descent + lineGap = base.lineGap + state.editor.lineHeight = base.lineHeight + state.editor.lastMaxWidth = maxWidth + state.editor.layout.setLen(0) + state.runs.setLen(0) + state.runeSpans.setLen(state.editor.runes.len) + for index in state.runeSpans.mitems: + index = -1 + for index, span in state.spans: + let name = + if span.font.len > 0 and span.font in fonts: + span.font + else: + baseFont + let font = fonts[name] + resolvedFonts.add(font) + fontNames.add(name) + if span.first < state.editor.runes.len and span.last > max(0, span.first): + state.editor.lineHeight = max(state.editor.lineHeight, font.lineHeight) + baseline = max(baseline, font.ascent) + descent = min(descent, font.descent) + lineGap = max(lineGap, font.lineGap) + for i in max(0, span.first) ..< min(span.last, state.editor.runes.len): + state.runeSpans[i] = index + state.editor.lineHeight = max( + 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) + for i, rune in state.editor.runes: + if rune == LF: + continue + let font = resolvedFonts[state.runeSpans[i] + 1] + var entry: ptr LetterEntry + if rune == Tab: + if font.lookupLetter(Space, 0, entry): + advances[i] = entry.advance * 4 + continue + if font.lookupLetter(rune, 0, entry): + advances[i] = entry.advance + if i + 1 < state.editor.runes.len and state.editor.runes[i + 1] != LF and + font == resolvedFonts[state.runeSpans[i + 1] + 1]: + kernings[i] = font.lookupKerning(rune, state.editor.runes[i + 1]) + var position = vec2(0, 0) + for i, rune in state.editor.runes: + if rune == LF: + state.editor.layout.add(rect( + position.x, + position.y, + 0, + state.editor.lineHeight + )) + position.x = 0 + position.y += state.editor.lineHeight + continue + if state.editor.wordWrap and maxWidth < float32.high: + let wordStart = i == 0 or state.editor.runes[i - 1] in [Space, Tab, LF] + if wordStart and rune notin [Space, Tab] and position.x > 0: + var + wordWidth = 0.0'f + j = i + while j < state.editor.runes.len and + state.editor.runes[j] notin [Space, Tab, LF]: + wordWidth += advances[j] + if j + 1 < state.editor.runes.len and + state.editor.runes[j + 1] notin [Space, Tab, LF]: + wordWidth += kernings[j] + inc j + if position.x + wordWidth > maxWidth: + position.x = 0 + position.y += state.editor.lineHeight + if position.x > 0 and position.x + advances[i] > maxWidth: + position.x = 0 + position.y += state.editor.lineHeight + state.editor.layout.add(rect( + position.x, position.y, advances[i], state.editor.lineHeight + )) + position.x += advances[i] + kernings[i] + 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. + 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. + 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: + 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, + state: RichTextBoxState, + origin: Vec2, + defaultColor: ColorRGBX +) = + ## Draws native block surfaces, borders, rules, and captions. + 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, + item.patchBorder, + 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 + scale = max(sk.uiScale, 0.001'f) + indent = max(0.0'f, item.quoteIndent) + position = origin + bounds.quoteBounds.xy + limit = floor((position.x + bounds.quoteBounds.w) * scale) / scale + top = round(position.y * scale) / scale + thickness = max(1.0'f, round(item.quoteThickness * scale)) / scale + continuation = clamp(item.quoteContinue, 0, item.quoteDepth) + for level in 0 ..< item.quoteDepth: + let + left = round((position.x + level.float32 * indent) * scale) / + scale + width = min(thickness, limit - left) + if width <= 0: + break + let + spacing = + if level < continuation: + max(0.0'f, item.spacing) + else: + 0.0'f + bottom = round( + (position.y + bounds.quoteBounds.h + spacing) * scale + ) / scale + sk.drawRect( + vec2(left, top), vec2(width, bottom - top), item.quoteColor + ) + if indent == 0: + break + if bounds.ruleBounds.h > 0: + if bounds.ruleBounds.w > 0 and item.ruleColor.a > 0: + let + scale = max(sk.uiScale, 0.001'f) + position = origin + bounds.ruleBounds.xy + left = round(position.x * scale) / scale + right = round((position.x + bounds.ruleBounds.w) * scale) / scale + top = round(position.y * scale) / scale + thickness = max(1.0'f, round(bounds.ruleBounds.h * scale)) / scale + sk.drawRect( + vec2(left, top), vec2(right - left, thickness), item.ruleColor + ) + continue + if item.label.len > 0: + let color = + if item.labelColor.a > 0: + item.labelColor + else: + defaultColor + discard sk.drawText( + bounds.labelFont, + item.label, + origin + bounds.labelBounds.xy, + color, + maxWidth = bounds.labelBounds.w, + maxHeight = bounds.labelBounds.h, + wordWrap = true + ) + +proc drawSpans( + sk: Silky, + state: RichTextBoxState, + origin: Vec2, + defaultColor: ColorRGBX +) = + ## Draws cached runs at their measured positions without wrapping again. + 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 + ) + if run.span >= 0: + let + span = state.spans[run.span] + underline = state.hoveredSpan >= 0 and span.linkId > 0 and + span.linkId == state.spans[state.hoveredSpan].linkId + if span.strikethrough or underline: + let + 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.decorationRight) * scale) / scale + baseline = origin.y + run.position.y + font.ascent + thickness = max(1.0'f, round(scale)) / scale + if span.strikethrough: + let top = round((baseline - font.size * 0.3'f) * scale) / scale + sk.drawRect(vec2(left, top), vec2(right - left, thickness), color) + 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, + window: Window, + id, text: string, + boxWidth, boxHeight: float32, + wrapWords = true, + spans: seq[TextSpan] = default(seq[TextSpan]), + blocks: seq[TextBlock] = default(seq[TextBlock]) +) {.measure.} = + ## Draws a read-only styled document with one selection and link handling. + if id notin richTextBoxStates: + richTextBoxStates[id] = newRichTextBoxState(text, wrapWords) + let + 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 + if editor.focused and state.focusEpoch != inputs.focusEpoch: + editor.focused = false + editor.dragging = false + editor.selector = editor.cursor + if state.spans != spans: + state.spans = spans + editor.dirty = true + if state.blocks != blocks: + state.blocks = blocks + editor.dirty = true + if editor.wordWrap != wrapWords: + editor.wordWrap = wrapWords + editor.dirty = true + if not state.sameText(text): + state.setText(text, preserveSelection = true) + let + padding = sk.theme.padding.float32 + outerRect = rect(sk.at, vec2(boxWidth, boxHeight)) + 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] + mouseVec = sk.mousePos + mouseInside = mouseVec.overlaps(outerRect) and + mouseVec.overlaps(sk.clipRect) + onScrollbar = mouseInside and not mouseVec.overlaps(innerRect) + if window.buttonPressed[MouseLeft]: + state.pressedSpan = -1 + if mouseInside and not onScrollbar: + editor.focused = true + let + localMouse = mouseVec - innerRect.xy + editor.scrollPos + now = epochTime() + if now - editor.lastClickTime < DoubleClickTime: + inc editor.clickCount + else: + editor.clickCount = 1 + editor.lastClickTime = now + case editor.clickCount + of 1: + state.mouseAction(localMouse, click = true, shift = shift) + editor.dragging = true + if not shift: + state.pressedSpan = state.spanAt(localMouse) + state.pressPosition = mouseVec + state.spanDragged = false + of 2: + state.selectWord(localMouse) + of 3: + state.selectParagraph(localMouse) + else: + editor.selectAll() + elif not mouseInside: + editor.focused = false + editor.dragging = false + editor.selector = editor.cursor + if state.pressedSpan >= 0: + let distance = mouseVec - state.pressPosition + if distance.x * distance.x + distance.y * distance.y > 9: + state.spanDragged = true + if window.buttonReleased[MouseLeft]: + let localMouse = mouseVec - innerRect.xy + editor.scrollPos + if mouseInside and not state.spanDragged and + editor.cursor == editor.selector and + state.spanAt(localMouse) == state.pressedSpan: + state.activatedSpan = state.pressedSpan + state.pressedSpan = -1 + 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]: + let localMouse = mouseVec - innerRect.xy + editor.scrollPos + 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) + let maxScrollY = max(0.0'f, editor.innerHeight - innerRect.h) + editor.scrollPos.y = clamp(editor.scrollPos.y, 0.0'f, maxScrollY) + 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 = 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 + not overVerticalBar and not overHorizontalBar: + let index = state.spanAt(mouseVec - innerRect.xy + editor.scrollPos) + if index >= 0 and state.spans[index].linkId > 0: + state.hoveredSpan = index + sk.cursor = Cursor(kind: PointerCursor) + let textColor = sk.theme.disabledTextColor + sk.draw9Patch( + "textbox.disabled.9patch", sk.theme.textboxPatch, outerRect.xy, outerRect.wh + ) + sk.pushClipRect(innerRect) + let textOrigin = innerRect.xy - editor.scrollPos + if state.blocks.len > 0: + sk.drawBlocks(state, textOrigin, textColor) + if state.spans.len > 0: + sk.drawSpanBackgrounds(state, textOrigin) + if editor.cursor != editor.selector: + sk.drawSelection(state, textOrigin) + sk.drawSpans(state, textOrigin, textColor) + sk.requestCursorFrame(window, editor, innerRect) + if editor.focused and editor.cursorVisible: + let cursor = editor.locationRect(editor.cursor) + sk.drawRect(textOrigin + cursor.xy, cursor.wh, textColor) + sk.popClipRect() + 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*( + id: string, + text: string, + boxWidth, boxHeight: float32, + wrapWords = true, + spans: seq[TextSpan] = default(seq[TextSpan]), + blocks: seq[TextBlock] = default(seq[TextBlock]) +) = + ## Draws a selectable read-only rich document using the current context. + sk.richTextBox( + window, + id, + text, + boxWidth, + boxHeight, + wrapWords, + spans, + blocks + ) diff --git a/src/silky/semantics.nim b/src/silky/semantics.nim index f455937e..67e6303d 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, layout], testwindow, + silky/[atlas, clips, common, frames, layout], testwindow, silky/internal/inputs from windy/common import Button, CursorKind, Cursor -export layout +export frames, layout const LineFeedRune = Rune(10) @@ -286,6 +286,9 @@ type theme*: Theme = Theme() cursor*: Cursor = Cursor(kind: ArrowCursor) inputs: TextInputs + frames: FrameSchedule + frameInput: FrameInput + frameHadInput: bool mousePos*: Vec2 mouseDelta*: Vec2 mouseIdleTime*: float64 @@ -303,6 +306,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] @@ -321,6 +326,39 @@ proc textInputs*(sk: Silky): TextInputs = ## Provides internal text input state to the text widgets. sk.inputs +proc renderMode*(sk: Silky): RenderMode = + ## Returns continuous game rendering or event-driven application rendering. + sk.frames.mode + +proc requestFrame*(sk: Silky, delayMs = 0) = + ## Invalidates data or schedules an animation frame on the UI thread. + sk.frames.requestFrame(delayMs) + +proc `renderMode=`*(sk: Silky, mode: RenderMode) = + ## Selects the rendering policy without changing the drawing API. + sk.frames.mode = mode + sk.requestFrame() + +proc `onFrameRequested=`*(sk: Silky, wake: proc()) = + ## Connects invalidation and native editor input to an event-loop wakeup. + sk.frames.wake = wake + if sk.inputs != nil: + sk.inputs.onEvent = wake + +proc needsFrame*(sk: Silky, window: Window): bool = + ## Checks UI input and scheduled deadlines before drawing an app frame. + if sk.frames.mode == ContinuousRender: + return true + if sk.frameInput.inputChanged(window, sk.inputs.hasPendingEvents()): + sk.requestFrame() + sk.frames.needsFrame() + +proc nextFrameDelay*(sk: Silky, window: Window, maxWaitMs = 1000): int = + ## Bounds an event-loop wait by pending UI work and animation deadlines. + if sk.needsFrame(window): + return 0 + sk.frames.nextFrameDelay(maxWaitMs) + proc pushLayer*(sk: Silky, layer: int) = ## Pushes a new rendering layer onto the stack. sk.layerStack.add(sk.currentLayer) @@ -393,11 +431,16 @@ proc vertexMark*(sk: Silky): int = proc beginVertexSpan*(sk: Silky): VertexSpan = ## Captures clip bounds while a semantic layout awaits placement. result.clipMark = sk.clipStack.regions.len + result.textMark = sk.inputs.textPlacementMark() inc sk.clipStack.captures proc endVertexSpan*(sk: Silky, span: VertexSpan, offset: Vec2) = ## Places captured clip bounds without emitting GPU vertices. + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2(round(offset.x * scale), round(offset.y * scale)) sk.clipStack.translateClips(span.clipMark, offset) + sk.inputs.translateTextInput(span.textMark, paintOffset) dec sk.clipStack.captures proc moveVerticesBehind*(sk: Silky, layer, spanStart, chromeStart: int) = @@ -405,6 +448,7 @@ proc moveVerticesBehind*(sk: Silky, layer, spanStart, chromeStart: int) = ## span so late-drawn parent chrome renders behind its children (T2). let total = sk.layers[layer].len if chromeStart > spanStart and chromeStart < total: + sk.inputs.moveTextInputBehind(ord(layer), spanStart, chromeStart, total) sk.layers[layer].rotateLeft( spanStart ..< total, chromeStart - spanStart ) @@ -414,6 +458,10 @@ proc translateVertices*(sk: Silky, layer, spanStart: int, offset: Vec2) = ## whose position is only known at scope close (T6). if offset == vec2(0, 0): return + let + scale = max(sk.uiScale, 0.001'f) + paintOffset = vec2(round(offset.x * scale), round(offset.y * scale)) + sk.inputs.translateTextInputVertices(ord(layer), spanStart, paintOffset) for i in spanStart ..< sk.layers[layer].len: sk.layers[layer][i].pos += offset @@ -452,11 +500,11 @@ proc place*(sk: Silky, size: Vec2): Vec2 = sk.advance(size) proc getImageSize*(sk: Silky, image: string): Vec2 = - ## Returns the size of an image from the atlas. + ## Returns the logical size of an image from the atlas. if image notin sk.atlas.entries: return vec2(0, 0) let uv = sk.atlas.entries[image] - vec2(uv.width.float32, uv.height.float32) + vec2(uv.width.float32, uv.height.float32) / max(uv.pixelScale, 1).float32 proc nextRune(text: string, i: var int): Rune {.inline.} = ## Reads one UTF-8 rune and advances the byte index. @@ -503,12 +551,52 @@ proc contains*(sk: Silky, name: string): bool = proc shouldShowTooltip*(sk: Silky): bool = ## Returns true if a tooltip should be displayed. + if sk.renderMode == OnDemandRender and sk.hover and + sk.mouseIdleTime < sk.tooltipThreshold: + sk.requestFrame(max( + 1, ((sk.tooltipThreshold - sk.mouseIdleTime) * 1000).int + 1 + )) sk.hover and sk.mouseIdleTime >= sk.tooltipThreshold proc drawQuad*(sk: Silky, pos: Vec2, size: Vec2, uvPos: Vec2, uvSize: Vec2, color: ColorRGBX) {.inline.} = ## 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, @@ -609,6 +697,12 @@ 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.inputs.beginInputFrame(window) sk.tooltipActive = sk.showTooltip sk.showTooltip = false @@ -617,8 +711,19 @@ proc beginUi*(sk: Silky, window: auto, size: IVec2) = sk.mouseDelta = window.mouseDelta.vec2 / sk.uiScale sk.pushLayout(vec2(0, 0), size.vec2 / sk.uiScale) sk.inFrame = true - let currentTime = epochTime() + let + currentTime = epochTime() + deltaTime = currentTime - sk.frameStartTime sk.frameStartTime = currentTime + if sk.mousePos != sk.lastMousePos: + sk.mouseIdleTime = 0 + sk.lastMousePos = sk.mousePos + else: + sk.mouseIdleTime += deltaTime + if sk.tooltipActive: + sk.tooltipFadeInTime += deltaTime + else: + sk.tooltipFadeInTime = 0 sk.pushClipRect(rect(0, 0, sk.size.x, sk.size.y)) sk.semantic.reset() @@ -635,6 +740,17 @@ proc resetInteractions*(sk: Silky) = 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]: + sk.requestFrame(16) + let previousCursor = sk.window.cursor + if previousCursor.kind != sk.cursor.kind or + (sk.cursor.kind == CustomCursor and + (previousCursor.image != sk.cursor.image or + previousCursor.hotspot != sk.cursor.hotspot)): + sk.window.cursor = sk.cursor sk.interactor.endInteractions() sk.clear() sk.popLayout() diff --git a/src/silky/testwindow.nim b/src/silky/testwindow.nim index 8ae0b792..a4279c6e 100644 --- a/src/silky/testwindow.nim +++ b/src/silky/testwindow.nim @@ -3,12 +3,17 @@ import std/unicode, vmath -from windy/common import Button, CursorKind, Cursor -export Button, CursorKind, Cursor, unicode +from windy/common import + Button, CursorKind, Cursor, TextInputState, TextInputEdit, + TextInputEditKind, TextInputEditCallback +export + Button, CursorKind, Cursor, unicode, TextInputState, TextInputEdit, + TextInputEditKind, TextInputEditCallback type Window* = ref object ## Test window that simulates a windy Window. size*: IVec2 + focused*: bool = true mousePrevPos*: IVec2 mousePos*: IVec2 mouseDelta*: IVec2 @@ -21,6 +26,9 @@ type Window* = ref object cursor*: Cursor = Cursor(kind: ArrowCursor) runeInputEnabled*: bool onRune*: proc(rune: Rune) + onTextInput*: proc(text: string) + onTextEdit*: TextInputEditCallback + textInput*: TextInputState onButtonPress*: proc(button: Button) onButtonRelease*: proc(button: Button) onFocusChange*: proc() @@ -28,6 +36,10 @@ type Window* = ref object var clipboard: string +proc setTextInputState*(window: Window, state: TextInputState) = + ## Records the editor exposed to native text services. + window.textInput = state + proc newWindow*(width = 800, height = 600): Window = ## Creates a new test window with the given dimensions. Window( @@ -98,9 +110,21 @@ proc typeRune*(w: Window, rune: Rune) = return if rune.int32 < 32 or rune.int32 in 127 .. 159: return - if w.onRune != nil: + if w.onTextInput != nil: + w.onTextInput($rune) + elif w.onRune != nil: w.onRune(rune) +proc typeText*(w: Window, text: string) = + ## Delivers one committed text edit without synthesizing Enter key presses. + if not w.runeInputEnabled or text.len == 0: + return + if w.onTextInput != nil: + w.onTextInput(text) + else: + for rune in text.runes: + w.typeRune(rune) + proc changeFocus*(w: Window) = ## Releases held buttons and delivers a window focus change. for button in Button: diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index e2aca6b8..c55efdb0 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 @@ -58,6 +60,10 @@ type focused*: bool focusEpoch: uint64 layout*: seq[Rect] + positionedLayout*: bool + ## Selection geometry may have variable line heights and gaps. + layoutHeight*: float32 + layoutCursor*: Rect dirty*: bool undoStack*: seq[(seq[Rune], int)] redoStack*: seq[(seq[Rune], int)] @@ -73,10 +79,13 @@ type scrollingX*: bool scrollDragOffset*: Vec2 singleLine*: bool + submitOnEnter*: bool + submitted*: bool enabled*: bool = true password*: bool passwordChar*: Rune = Rune('*') allowedChars*: seq[Rune] + lastFont: FontAtlas textCache: string textCacheValid: bool displayCache: string @@ -104,6 +113,15 @@ proc resetBlink*(state: TextBoxState) = ## Resets the cursor blink timer so the cursor is immediately visible. state.blinkTime = epochTime() +proc focus*(state: TextBoxState, sk: Silky, window: Window, id: string) = + ## Focuses a registered field and captures input before its next draw. + let inputs = sk.textInputs + inputs.submitInput(window, id, true, state.enabled) + state.focused = true + state.focusEpoch = inputs.focusEpoch + state.dragging = false + state.resetBlink() + proc cursorVisible*(state: TextBoxState): bool = ## Returns true when the blinking cursor should be drawn. ## Blinks 0.5s on, 0.5s off, always starting visible after a reset. @@ -156,8 +174,12 @@ proc sameText*(state: TextBoxState, text: string): bool = inc runeIdx result = i == text.len and runeIdx == state.runes.len -proc setText*(state: TextBoxState, text: string) = - ## Sets the text content and resets cursor to end. +proc setText*( + state: TextBoxState, + text: string, + preserveSelection = false +) = + ## Sets text, optionally retaining the selection while content streams. ## In single-line mode, newlines are converted to spaces. ## Disallowed characters are removed. state.runes = text.toRunes @@ -171,8 +193,12 @@ proc setText*(state: TextBoxState, text: string) = if r in state.allowedChars: filtered.add(r) state.runes = filtered - state.cursor = state.runes.len - state.selector = state.cursor + if preserveSelection: + state.cursor = clamp(state.cursor, 0, state.runes.len) + state.selector = clamp(state.selector, 0, state.runes.len) + else: + state.cursor = state.runes.len + state.selector = state.cursor state.dirty = true state.invalidateTextCaches() @@ -184,6 +210,10 @@ proc computeLayout*(state: TextBoxState, fontData: FontAtlas, maxWidth: float32) ## Computes per-character selection rectangles in local coordinates. ## Mirrors the glyph-walking logic from drawText but stores positions ## instead of emitting GPU vertices. + state.positionedLayout = false + state.layoutHeight = 0 + state.layoutCursor = rect(0, 0, 0, 0) + state.lastFont = fontData state.layout.setLen(0) state.lineHeight = fontData.lineHeight state.lastMaxWidth = maxWidth @@ -254,6 +284,17 @@ proc pickGlyphAt*(state: TextBoxState, pos: Vec2): int = if minDistance < 0 or dist < minDistance: minDistance = dist minGlyph = i + if minGlyph < 0 and state.positionedLayout: + var nearestY = float32.high + for i, bounds in state.layout: + let + distanceY = max(bounds.y - pos.y, pos.y - bounds.y - bounds.h) + distanceX = abs(pos.x - bounds.x) + if distanceY < nearestY or + (distanceY == nearestY and distanceX < minDistance): + nearestY = distanceY + minDistance = distanceX + minGlyph = i return minGlyph proc getSelectionRects*(layout: seq[Rect], start, stop: int): seq[Rect] = @@ -272,9 +313,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 @@ -287,6 +332,13 @@ proc innerWidth*(state: TextBoxState): float32 = proc locationRect*(state: TextBoxState, loc: int): Rect = ## Returns the rectangle where the cursor should be drawn. + if state.positionedLayout: + if loc >= state.layout.len: + result = state.layoutCursor + elif loc >= 0: + result = state.layout[loc] + result.w = CursorWidth + return if state.layout.len > 0: if loc >= state.layout.len: let selectRect = state.layout[^1] @@ -305,6 +357,28 @@ proc cursorPos*(state: TextBoxState): Vec2 = ## Returns the position of the text cursor. state.locationRect(state.cursor).xy +proc requestCursorFrame*( + sk: Silky, + window: Window, + state: TextBoxState, + bounds: Rect +) = + ## Schedules blinking only for a visible caret that still owns focus. + if sk.renderMode != OnDemandRender or not state.focused or + state.focusEpoch != sk.textInputs.focusEpoch or + sk.clipRect.w <= 0 or sk.clipRect.h <= 0: + return + when compiles(window.focused): + if not window.focused: + return + let + cursor = state.locationRect(state.cursor) + placed = rect(bounds.xy - state.scrollPos + cursor.xy, cursor.wh) + if not placed.overlaps(bounds) or not placed.overlaps(sk.clipRect): + return + let elapsed = (max(0.0, epochTime() - state.blinkTime) * 1000).int64 + sk.requestFrame(500 - (elapsed mod 500).int) + proc undoSave*(state: TextBoxState) = ## Saves current state for undo. state.undoStack.add((state.runes, state.cursor)) @@ -527,12 +601,39 @@ proc right*(state: TextBoxState, shift = false) = state.scrollToCursor() state.resetBlink() +proc adjacentLine(state: TextBoxState, forward: bool): int = + ## Finds a neighboring visual line when cached lines vary in height. + let currentY = state.cursorPos.y + var + nearest = float32.high + targetY = currentY + for bounds in state.layout: + let distance = + if forward: + bounds.y - currentY + else: + currentY - bounds.y + if distance > 0 and distance < nearest: + nearest = distance + targetY = bounds.y + bounds.h * 0.5'f + if nearest == float32.high: + if forward: + return state.runes.len + return 0 + state.pickGlyphAt(vec2(state.savedX, targetY)) + proc down*(state: TextBoxState, shift = false) = ## Moves the cursor down one line. if state.layout.len > 0: - let curPos = state.cursorPos - let index = state.pickGlyphAt( - vec2(state.savedX, curPos.y + state.lineHeight * 1.5)) + let + curPos = state.cursorPos + index = + if state.positionedLayout: + state.adjacentLine(true) + else: + state.pickGlyphAt( + vec2(state.savedX, curPos.y + state.lineHeight * 1.5) + ) if index != -1: state.cursor = index if not shift: @@ -547,9 +648,15 @@ proc down*(state: TextBoxState, shift = false) = proc up*(state: TextBoxState, shift = false) = ## Moves the cursor up one line. if state.layout.len > 0: - let curPos = state.cursorPos - let index = state.pickGlyphAt( - vec2(state.savedX, curPos.y - state.lineHeight * 0.5)) + let + curPos = state.cursorPos + index = + if state.positionedLayout: + state.adjacentLine(false) + else: + state.pickGlyphAt( + vec2(state.savedX, curPos.y - state.lineHeight * 0.5) + ) if index != -1: state.cursor = index if not shift: @@ -769,7 +876,9 @@ proc handleKey(state: TextBoxState, event: InputEvent) = of KeyPageDown: state.pageDown(shift) of KeyEnter: - if not state.singleLine: + if state.submitOnEnter and not shift: + state.submitted = state.enabled + elif not state.singleLine: state.typeCharacter(LF) of KeyA: if ctrl: @@ -801,6 +910,20 @@ proc handleKey(state: TextBoxState, event: InputEvent) = else: discard +proc handleSelectionInput*(state: TextBoxState, inputs: TextInputs) = + ## Drains read-only navigation and copy events without accepting edits. + assert not state.enabled + let + epoch = inputs.focusEpoch + events = inputs.takeInput() + for event in events: + if inputs.focusEpoch != epoch: + break + if event.kind == InputKind.KeyDown: + state.handleKey(event) + if events.len > 0: + state.scrollToCursor() + proc handleInput( state: TextBoxState, inputs: TextInputs, @@ -808,15 +931,37 @@ proc handleInput( maxWidth: float32 ) = ## Drains ordered input and refreshes layout before cursor navigation. + if not state.enabled: + state.handleSelectionInput(inputs) + return let epoch = inputs.focusEpoch events = inputs.takeInput() 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) + of TextCommit: + state.pasteText(event.text) + of NativeEdit: + if state.enabled: + let first = clamp(event.edit.start, 0, state.runes.len) + state.selector = first + state.cursor = first + clamp( + event.edit.length, 0, state.runes.len - first + ) + case event.edit.kind + of ReplaceText: + state.pasteText(event.edit.text) + of SelectText: + state.resetBlink() of InputKind.KeyDown: if state.dirty and event.button in { KeyLeft, KeyRight, KeyUp, KeyDown, KeyHome, KeyEnd, @@ -831,11 +976,20 @@ 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 @@ -914,7 +1068,8 @@ proc textBox*( error: bool = false, password: bool = false, passwordChar: Rune = Rune('*'), - allowedChars: seq[Rune] = default(seq[Rune]) + allowedChars: seq[Rune] = default(seq[Rune]), + submitOnEnter: bool = false ) {.measure.} = ## Text box widget with editing, selection, and scroll. ## When disabled, text can be selected and copied but not modified. @@ -931,10 +1086,14 @@ proc textBox*( newState.setText(t) textBoxStates[id] = newState state = textBoxStates[id] + state.submitOnEnter = submitOnEnter + state.submitted = false let inputs = sk.textInputs if state.focused and state.focusEpoch != inputs.focusEpoch: state.focused = false state.dragging = false + if not enabled: + state.selector = state.cursor state.enabled = enabled state.allowedChars = allowedChars if state.password != password: @@ -951,10 +1110,11 @@ proc textBox*( if state.wordWrap != effectiveWrap: state.wordWrap = effectiveWrap state.dirty = true - if not state.focused and not state.sameText(t): - state.setText(t) + if (not state.focused or not enabled) and not state.sameText(t): + state.setText(t, preserveSelection = not enabled) let - fontData = sk.atlas.fonts[sk.textStyle] + firstVertex = sk.vertexMark() + textLayer = sk.currentDrawLayer() padding = sk.theme.padding.float32 outerRect = rect(sk.at, vec2(boxWidth, boxHeight)) innerRect = rect( @@ -963,8 +1123,8 @@ proc textBox*( ) state.boxSize = vec2(innerRect.w, innerRect.h) if state.dirty or state.layout.len == 0 or - state.lastMaxWidth != innerRect.w: - state.computeLayout(fontData, innerRect.w) + state.lastMaxWidth != innerRect.w or state.lastFont != sk.atlas.fonts[sk.textStyle]: + state.computeLayout(sk.atlas.fonts[sk.textStyle], innerRect.w) let shift = window.buttonDown[KeyLeftShift] or window.buttonDown[KeyRightShift] let mouseVec = sk.mousePos @@ -990,6 +1150,9 @@ proc textBox*( else: state.selectAll() elif not mouseInside: state.focused = false + state.dragging = false + if not enabled: + state.selector = state.cursor if state.dragging and not state.scrollingX and not state.scrollingY: if window.buttonDown[MouseLeft] and not window.buttonPressed[MouseLeft]: let localMouse = mouseVec - innerRect.xy + state.scrollPos @@ -999,10 +1162,10 @@ proc textBox*( inputs.submitInput(window, id, state.focused, enabled) if state.focused: state.focusEpoch = inputs.focusEpoch - state.handleInput(inputs, fontData, innerRect.w) + state.handleInput(inputs, sk.atlas.fonts[sk.textStyle], innerRect.w) t = state.getText() if state.dirty: - state.computeLayout(fontData, innerRect.w) + state.computeLayout(sk.atlas.fonts[sk.textStyle], innerRect.w) let maxScrollY = max(0.0f, state.innerHeight - innerRect.h) state.scrollPos.y = clamp(state.scrollPos.y, 0.0f, maxScrollY) if state.wordWrap: @@ -1040,6 +1203,7 @@ proc textBox*( wordWrap = state.wordWrap, clip = false ) + sk.requestCursorFrame(window, state, innerRect) if state.focused and state.cursorVisible: let cr = state.locationRect(state.cursor) sk.drawRect( @@ -1053,6 +1217,31 @@ proc textBox*( window.scrollDelta.y != 0: state.scrollBy( window.scrollDelta.y * TextBoxScrollSpeed, innerRect.h) + if state.focused and enabled and not password: + let selection = state.selection + var + visibleStart = state.runes.len + visibleEnd = 0 + for i, bounds in state.layout: + if bounds.y + bounds.h > state.scrollPos.y and + bounds.y < state.scrollPos.y + innerRect.h and + bounds.x + bounds.w >= state.scrollPos.x and + bounds.x < state.scrollPos.x + innerRect.w: + visibleStart = min(visibleStart, i) + visibleEnd = i + 1 + if visibleEnd == 0: + visibleStart = min(state.cursor, state.runes.len) + visibleEnd = visibleStart + inputs.publishTextInput(TextInputState( + id: id, + text: t, + selectionStart: selection.a, + selectionEnd: selection.b, + visibleStart: visibleStart, + visibleEnd: visibleEnd, + bounds: rect(innerRect.xy * sk.uiScale, innerRect.wh * sk.uiScale), + multiline: not singleLine + ), textLayer, firstVertex) sk.advance(vec2(boxWidth, boxHeight)) template textBox*( @@ -1065,11 +1254,13 @@ template textBox*( isError = false, isPassword = false, passChar: Rune = Rune('*'), - chars: seq[Rune] = default(seq[Rune]) + chars: seq[Rune] = default(seq[Rune]), + submitOnEnter = false ) = ## Text box widget. Set singleLine for a single-line input. + ## submitOnEnter reports Enter in state.submitted and preserves Shift+Enter. sk.textBox(window, id, t, boxWidth, boxHeight, wrapWords, singleLine, - isEnabled, isError, isPassword, passChar, chars + isEnabled, isError, isPassword, passChar, chars, submitOnEnter ) template textInput*( diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index 53423eec..5139dd70 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -322,6 +322,7 @@ 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. + const MinThumbSize = 16.0'f if frameState.scrollingY and (window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]): frameState.scrollingY = false @@ -362,9 +363,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) @@ -397,10 +401,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) @@ -449,26 +456,40 @@ template frame*(id: string, framePos, frameSize: Vec2, body: untyped) = sk.frameEnd(window, frameCtx.state, frameCtx.originPos) sk.endWidget() -template button*(label: string, isEnabled: bool, isError: bool, body: untyped) = - ## Create a button with enabled and error states. +template sizedButton( + label: string, + minimumSize: Vec2, + isEnabled: bool, + isError: bool, + body: untyped +) = + ## Creates a native button with a minimum size and a left-aligned label. let - textSize = sk.getTextSize(sk.textStyle, label) - buttonSize = textSize + vec2(sk.theme.padding) * 2 + buttonLabel = label + minimum = minimumSize + enabled = isEnabled + error = isError + padding = vec2(sk.theme.padding) + textSize = sk.getTextSize(sk.textStyle, buttonLabel) + intrinsicSize = textSize + padding * 2 + buttonSize = vec2( + max(intrinsicSize.x, minimum.x), max(intrinsicSize.y, minimum.y) + ) buttonOrigin = sk.placedAt(buttonSize) buttonRect = rect(buttonOrigin, buttonSize) when defined(silkyTesting): - sk.beginWidget("Button", text = label, rect = buttonRect) + sk.beginWidget("Button", text = buttonLabel, rect = buttonRect) let textColor = - if not isEnabled: + if not enabled: sk.theme.disabledTextColor - elif isError: + elif error: sk.theme.errorTextColor else: sk.theme.defaultTextColor - interaction = sk.interact(buttonRect, isEnabled, isError) + interaction = sk.interact(buttonRect, enabled, error) let patch = case interaction of Error: @@ -491,21 +512,48 @@ template button*(label: string, isEnabled: bool, isError: bool, body: untyped) = let pressed = interaction == Pressed or interaction == Held hovered = pressed or interaction == Hovered - sk.setWidgetState(enabled = isEnabled, pressed = pressed, hovered = hovered) + sk.setWidgetState(enabled = enabled, pressed = pressed, hovered = hovered) - let at = buttonOrigin + vec2(sk.theme.padding) - discard sk.drawText(sk.textStyle, label, at, textColor) + let at = buttonOrigin + vec2(padding.x, (buttonSize.y - textSize.y) / 2) + discard sk.drawText(sk.textStyle, buttonLabel, at, textColor) when defined(silkyTesting): sk.endWidget() - sk.advance(buttonSize + vec2(sk.theme.padding)) + sk.advance(buttonSize + padding) + +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + isError: bool, + body: untyped +) = + ## Creates a minimum-size button with enabled and error states. + sizedButton(label, minimumSize, isEnabled, isError, body) + +template button*( + label: string, + minimumSize: Vec2, + isEnabled: bool, + body: untyped +) = + ## Creates a native button with a minimum size and an enabled state. + sizedButton(label, minimumSize, isEnabled, false, body) + +template button*(label: string, minimumSize: Vec2, body: untyped) = + ## Creates a native button with a minimum size. + sizedButton(label, minimumSize, true, false, body) + +template button*(label: string, isEnabled: bool, isError: bool, body: untyped) = + ## Creates an intrinsic-size button with enabled and error states. + sizedButton(label, vec2(0), isEnabled, isError, body) template button*(label: string, body: untyped) = ## Create a button. - button(label, true, false, body) + sizedButton(label, vec2(0), true, false, body) template button*(label: string, isEnabled: bool, body: untyped) = ## Create a button. - button(label, isEnabled, false, body) + sizedButton(label, vec2(0), isEnabled, false, body) template icon*(image: string) = ## Draw an icon. @@ -1002,6 +1050,9 @@ template tooltip*(text: string) = sk.tooltipFadeInTime = 0 sk.tooltipLastAnchor = sk.tooltipAnchor sk.showTooltip = true + if sk.renderMode == OnDemandRender and + sk.tooltipFadeInTime < sk.tooltipFadeInDuration: + sk.requestFrame(16) let fadeAlpha = clamp( 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_texture_pixels.nim b/tests/test_metal_texture_pixels.nim new file mode 100644 index 00000000..350c17f5 --- /dev/null +++ b/tests/test_metal_texture_pixels.nim @@ -0,0 +1,233 @@ +## Exercises the production Metal drawer with an offscreen render target. +## Run on macOS with nim r -d:silkyMetalTesting tests/test_metal_texture_pixels.nim. + +when defined(macosx) and not 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) + 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." +else: + echo "Skipped Metal texture pixels: requires macOS with a Metal device." diff --git a/tests/test_richimages.nim b/tests/test_richimages.nim new file mode 100644 index 00000000..a9a835ba --- /dev/null +++ b/tests/test_richimages.nim @@ -0,0 +1,74 @@ +import + std/[importutils, tables], + bumpy, pixie, vmath, windy, + silky, silky/internal/inputs + +proc fixture(builder: AtlasBuilder): Silky = + ## Queues native image and text vertices without opening a platform window. + privateAccess(Silky) + result = Silky( + atlas: builder.atlas, + image: builder.atlasImage, + uiScale: 2, + inFrame: true, + inputs: TextInputs() + ) + 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( + 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 new file mode 100644 index 00000000..d344d34e --- /dev/null +++ b/tests/test_richtextboxes.nim @@ -0,0 +1,255 @@ +import + std/[tables, unicode], + vmath, bumpy, + silky/atlas, silky/textboxes, silky/richtextboxes + +var silkyAtlas: SilkyAtlas + +block: + let builder = newAtlasBuilder(1024, 4) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Default", 18) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Wide", 30) + builder.addFont("tests/data/IBMPlexSans-Regular.ttf", "Small", 12) + silkyAtlas = builder.atlas + +proc newState(text: string, maxWidth = 500.0'f): RichTextBoxState = + ## Creates a wrapped read-only document and computes its rich layout. + result = newRichTextBoxState(text) + result.editor.boxSize = vec2(maxWidth, 300) + result.computeLayout(silkyAtlas.fonts, "Default", maxWidth) + +proc newStateNoWrap(text: string): RichTextBoxState = + ## Creates an unwrapped rich document for exact font comparisons. + result = newRichTextBoxState(text, wordWrap = false) + result.computeLayout(silkyAtlas.fonts, "Default", 500) + +proc newPlainState( + text: string, + maxWidth = 500.0'f, + wordWrap = false +): TextBoxState = + ## Creates an independent single-font reference layout. + result = TextBoxState(wordWrap: wordWrap) + result.setText(text) + result.computeLayout(silkyAtlas.fonts["Default"], maxWidth) + +proc advance(font: FontAtlas, rune: Rune): float32 = + ## Returns the actual atlas advance used by span layout assertions. + var entry: ptr LetterEntry + doAssert font.lookupLetter(rune, 0, entry) + entry.advance + +block: + echo "Testing styled text uses each span's font metrics" + let + s = newState("W a") + wide = silkyAtlas.fonts["Wide"] + small = silkyAtlas.fonts["Small"] + regular = silkyAtlas.fonts["Default"] + s.spans = @[ + TextSpan(first: 0, last: 1, font: "Wide"), + TextSpan(first: 2, last: 3, font: "Small") + ] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert s.editor.layout.len == 3 + doAssert abs(s.editor.layout[0].w - wide.advance(Rune('W'))) < 0.01 + doAssert abs(s.editor.layout[1].w - regular.advance(Rune(' '))) < 0.01 + doAssert abs(s.editor.layout[2].w - small.advance(Rune('a'))) < 0.01 + doAssert abs(s.editor.layout[1].x - s.editor.layout[0].w) < 0.01 + doAssert s.editor.lineHeight >= wide.lineHeight + for bounds in s.editor.layout: + doAssert bounds.h == s.editor.lineHeight + +block: + echo "Testing formatting and links preserve native pair kerning" + const Sample = "AVATAR To WAVY" + let + plain = newPlainState(Sample) + styled = newStateNoWrap(Sample) + doAssert silkyAtlas.fonts["Default"].lookupKerning(Rune('A'), Rune('V')) != 0 + doAssert silkyAtlas.fonts["Default"].lookupKerning(Rune('T'), Rune('o')) != 0 + doAssert plain.layout[1].x < plain.layout[0].w + for i in 0 ..< styled.editor.runes.len: + styled.spans.add(TextSpan( + first: i, + last: i + 1, + font: + if i mod 2 == 0: + "Default" + else: + "", + linkId: + if i in 1 .. 8: + 1 + else: + 0 + )) + styled.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert styled.editor.layout.len == plain.layout.len + for i in 0 ..< plain.layout.len: + let + expected = plain.layout[i] + actual = styled.editor.layout[i] + doAssert abs(actual.x - expected.x) < 0.001 + doAssert abs(actual.y - expected.y) < 0.001 + doAssert abs(actual.w - expected.w) < 0.001 + doAssert abs(actual.h - expected.h) < 0.001 + +block: + echo "Testing styled long words wrap before crossing the width" + let + s = newState("WWWWWW") + wide = silkyAtlas.fonts["Wide"] + width = wide.advance(Rune('W')) * 2.5'f + s.spans = @[TextSpan(first: 0, last: 6, font: "Wide")] + s.computeLayout(silkyAtlas.fonts, "Default", width) + doAssert s.editor.layout[0].y == s.editor.layout[1].y + doAssert s.editor.layout[2].y > s.editor.layout[1].y + doAssert s.editor.layout[4].y > s.editor.layout[3].y + for bounds in s.editor.layout: + doAssert bounds.x + bounds.w <= width + 0.01 + +block: + echo "Testing styled Unicode selection preserves the original text" + let s = newState("é code 世界") + s.spans = @[TextSpan(first: 2, last: 6, font: "Small")] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert s.editor.layout.len == s.editor.runes.len + s.editor.cursor = 2 + s.editor.selector = 6 + doAssert s.editor.copyText() == "code" + doAssert getSelectionRects(s.editor.layout, 2, 6).len == 1 + s.editor.selectAll() + doAssert s.editor.copyText() == "é code 世界" + +block: + echo "Testing styled code preserves tabs when copying" + let + s = newState("a\tb") + small = silkyAtlas.fonts["Small"] + s.spans = @[TextSpan(first: 0, last: 3, font: "Small")] + s.computeLayout(silkyAtlas.fonts, "Default", 500) + doAssert abs(s.editor.layout[1].w - small.advance(Rune(' ')) * 4) < 0.01 + doAssert abs( + s.editor.layout[2].x - s.editor.layout[1].x - s.editor.layout[1].w + ) < 0.01 + s.editor.selectAll() + doAssert s.editor.copyText() == "a\tb" + +block: + echo "Testing rich text without styles preserves plain layout" + const Source = "A plain paragraph that wraps across lines." + let + plain = newPlainState(Source, 100, wordWrap = true) + rich = newState(Source, 100) + doAssert rich.editor.layout == plain.layout + +block: + echo "Testing one selection spans headings, wrapped prose, and code" + const + Heading = "Heading" + Body = "é body wraps over several lines for selection." + Code = "let x = 1\n echo x" + Sample = Heading & "\n" & Body & "\n" & Code + let + bodyStart = Heading.runeLen + 1 + codeStart = bodyStart + Body.runeLen + 1 + s = newState(Sample, 180) + s.blocks = @[ + TextBlock( + first: 0, last: Heading.runeLen, font: "Wide", + padding: vec2(12, 6), spacing: 8 + ), + TextBlock( + first: bodyStart, last: codeStart - 1, + padding: vec2(12, 6), spacing: 8 + ), + TextBlock( + first: codeStart, last: Sample.runeLen, font: "Small", + padding: vec2(12, 12), label: "nim", labelFont: "Small", + labelSpacing: 8 + ) + ] + s.computeLayout(silkyAtlas.fonts, "Default", 180) + doAssert s.editor.layout.len == Sample.runeLen + doAssert s.editor.layout[0].h > s.editor.layout[bodyStart].h + doAssert s.editor.layout[bodyStart].h > s.editor.layout[codeStart].h + doAssert s.editor.layout[codeStart - 2].y > s.editor.layout[bodyStart].y + doAssert s.editor.layout[bodyStart].x == 12 + doAssert s.editor.layout[codeStart].x == 12 + doAssert abs( + s.innerHeight - s.editor.layout[^1].y - s.editor.layout[^1].h - 12 + ) < 0.001 + for index in [0, bodyStart, codeStart]: + doAssert s.editor.locationRect(index).h == s.editor.layout[index].h + s.editor.selector = 2 + s.editor.cursor = codeStart + 5 + doAssert s.editor.copyText() == "ading\n" & Body & "\nlet x" + let selected = getSelectionRects( + s.editor.layout, s.editor.selector, s.editor.cursor + ) + doAssert selected.len >= 4 + doAssert selected[0].h > selected[^1].h + s.editor.selectAll() + doAssert s.editor.copyText() == Sample + + echo "Testing dragging through block spacing has no selection dead zone" + let + first = s.editor.layout[0] + body = s.editor.layout[bodyStart] + s.editor.mouseAction(first.xy + vec2(0, first.h / 2)) + s.editor.mouseAction( + vec2(body.x, body.y - 1), click = false, shift = true + ) + doAssert s.editor.selector == 0 + doAssert s.editor.cursor == bodyStart + doAssert s.editor.copyText() == Heading & "\n" + + echo "Testing keyboard selection follows rows with different heights" + s.editor.cursor = 0 + s.editor.selector = 0 + s.editor.savedX = first.x + s.editor.down(shift = true) + doAssert s.editor.cursor == bodyStart + doAssert s.editor.selector == 0 + s.editor.up(shift = true) + doAssert s.editor.cursor == 0 + s.editor.cursor = codeStart + s.editor.selector = codeStart + s.editor.savedX = s.editor.layout[codeStart].x + s.editor.up(shift = true) + 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_textboxes.nim b/tests/test_textboxes.nim index 7683633a..94e0f413 100644 --- a/tests/test_textboxes.nim +++ b/tests/test_textboxes.nim @@ -655,7 +655,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 From 0add9ce0057c28b2f02435efabcc4d97863b7318 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 14:32:32 -0800 Subject: [PATCH 09/16] respect Metal device texture limits --- docs/ios.md | 6 ++++++ src/silky/drawers/metal4.nim | 30 ++++++++++++++++++++++++++--- tests/test_metal_texture_pixels.nim | 7 +++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/docs/ios.md b/docs/ios.md index 1ff8ddb5..f1d9da0d 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -80,6 +80,12 @@ 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. diff --git a/src/silky/drawers/metal4.nim b/src/silky/drawers/metal4.nim index 3033e980..9d6b121e 100644 --- a/src/silky/drawers/metal4.nim +++ b/src/silky/drawers/metal4.nim @@ -9,7 +9,6 @@ import const InitialVertexCapacity = 4096 VertexBufferIndex = 1 - MaximumTextureSize = 16384 VertexShaderSource = toMSL(silkyVert, shaderVertex) FragmentShaderSource = toMSL(silkyFrag, shaderFragment) @@ -45,6 +44,7 @@ type maxVertexCount: int viewportSize: IVec2 atlasSize: IVec2 + textureLimit: int textures: Table[uint32, DrawerTexture] nextTexture: uint32 clearColor: MTLClearColor @@ -60,6 +60,26 @@ static: 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)) @@ -91,8 +111,11 @@ 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 > MaximumTextureSize or height > MaximumTextureSize: - raise newException(SilkyError, "Image texture exceeds the Metal size limit.") + 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, @@ -207,6 +230,7 @@ proc uploadAtlasRegion*( proc initRenderer(state: Drawer, image: Image, size: IVec2) = ## Creates the Metal pipeline, atlas texture, and dynamic buffers. + state.textureLimit = state.ctx.device.textureSizeLimit() var error: NSError let vertexLibrary = state.ctx.device.newLibraryWithSource( @VertexShaderSource, diff --git a/tests/test_metal_texture_pixels.nim b/tests/test_metal_texture_pixels.nim index 350c17f5..b0520f25 100644 --- a/tests/test_metal_texture_pixels.nim +++ b/tests/test_metal_texture_pixels.nim @@ -146,6 +146,13 @@ when defined(macosx) and not defined(ios): discard drawer.allocateTexture(0, 1) expectSilkyError: discard drawer.allocateTexture(1, -1) + doAssert drawer.maxTextureSize in [8192, 16384, 32768] + 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: From a8cf1d73db0765bde768c90cb7c2bcae7ec3eea8 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 14:34:33 -0800 Subject: [PATCH 10/16] support secure native text fields --- .github/workflows/build.yml | 1 + src/silky/textboxes.nim | 9 +-- tests/test_secure_inputs.nim | 124 +++++++++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 4 deletions(-) create mode 100644 tests/test_secure_inputs.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4a52f5d9..dd329fbe 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -64,6 +64,7 @@ jobs: 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_rendering.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim diff --git a/src/silky/textboxes.nim b/src/silky/textboxes.nim index 97a1d7f7..7e0f4cb5 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -884,12 +884,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) @@ -1223,7 +1223,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 @@ -1246,7 +1246,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/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." From c24fca132c7c4eede522916e7d72fd4133c3e2a9 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 14:35:52 -0800 Subject: [PATCH 11/16] test Metal pixels on iOS Simulator --- docs/ios.md | 5 ++++- tests/test_metal_texture_pixels.nim | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/ios.md b/docs/ios.md index f1d9da0d..850b3b17 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -119,7 +119,10 @@ 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 and checks the actual GPU pixels. `test_inputs`, +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. diff --git a/tests/test_metal_texture_pixels.nim b/tests/test_metal_texture_pixels.nim index b0520f25..864af280 100644 --- a/tests/test_metal_texture_pixels.nim +++ b/tests/test_metal_texture_pixels.nim @@ -1,7 +1,8 @@ ## 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) and not defined(ios): +when defined(macosx) or defined(ios): when not defined(silkyMetalTesting): {.error: "Build this test with -d:silkyMetalTesting.".} @@ -147,6 +148,8 @@ when defined(macosx) and not defined(ios): 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: @@ -236,5 +239,8 @@ when defined(macosx) and not defined(ios): 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 macOS with a Metal device." + echo "Skipped Metal texture pixels: requires a macOS or iOS Metal device." From 3956cfdcecf1d549619fbbe649ac293277fcbf9c Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 14:44:55 -0800 Subject: [PATCH 12/16] resolve first touches before widget presses --- .github/workflows/build.yml | 1 + docs/ios.md | 4 + src/silky/contexts.nim | 26 +---- src/silky/dsl.nim | 2 +- src/silky/interactions.nim | 68 ++++++++++++++ src/silky/semantics.nim | 22 +---- src/silky/widgets.nim | 47 ++++----- tests/test_first_touch.nim | 183 ++++++++++++++++++++++++++++++++++++ 8 files changed, 283 insertions(+), 70 deletions(-) create mode 100644 src/silky/interactions.nim create mode 100644 tests/test_first_touch.nim diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index dd329fbe..bb28d90d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -65,6 +65,7 @@ jobs: 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_rendering.nim nim r -d:silkyTesting tests/test_subwindow.nim nim r tests/test_atlas_png.nim diff --git a/docs/ios.md b/docs/ios.md index 850b3b17..09e63db4 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -29,6 +29,10 @@ Windy reports drawable sizes and pointer positions in pixels. Set 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 diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 1d235544..82fad1e4 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, common, frames, layout, profiles], + silky/[atlas, clips, common, frames, interactions, layout, profiles], silky/internal/inputs -export frames, layout, profiles +export frames, interactions, 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 @@ -357,10 +350,8 @@ 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() proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = ## Starts a frame and updates the shared UI state. @@ -404,13 +395,6 @@ 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: @@ -424,8 +408,6 @@ 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.clear() sk.popLayout() diff --git a/src/silky/dsl.nim b/src/silky/dsl.nim index cd2dbf31..4df28cee 100644 --- a/src/silky/dsl.nim +++ b/src/silky/dsl.nim @@ -908,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/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/semantics.nim b/src/silky/semantics.nim index 67e6303d..6eaff7a6 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, common, frames, layout], testwindow, + silky/[atlas, clips, common, frames, interactions, layout], testwindow, silky/internal/inputs from windy/common import Button, CursorKind, Cursor -export frames, layout +export frames, interactions, 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 @@ -727,16 +720,9 @@ 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() proc endUi*(sk: Silky) = ## Ends the current UI frame. diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index 5139dd70..b7c684dd 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) @@ -108,6 +90,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 +157,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 +237,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 @@ -390,7 +377,7 @@ proc frameScrollbars*( else: let thumb = thumbRectY() if sk.interact(thumb, true) == Pressed: - frameState.scrollingY = true + frameState.scrollingY = window.buttonDown[MouseLeft] frameState.scrollDragOffset.y = sk.mousePos.y - thumb.y let thumb = thumbRectY() sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, thumb.xy, thumb.wh) @@ -429,7 +416,7 @@ proc frameScrollbars*( else: let thumb = thumbRectX() if sk.interact(thumb, true) == Pressed: - frameState.scrollingX = true + frameState.scrollingX = window.buttonDown[MouseLeft] frameState.scrollDragOffset.x = sk.mousePos.x - thumb.x let thumb = thumbRectX() sk.draw9Patch("scrollbar.9patch", sk.theme.scrollbarPatch, thumb.xy, thumb.wh) @@ -505,7 +492,7 @@ template sizedButton( sk.draw9Patch(patch, sk.theme.buttonPatch, buttonOrigin, buttonSize) - if interaction == Released: + if interaction.isReleased(window): body when defined(silkyTesting): @@ -580,6 +567,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 @@ -636,7 +625,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 @@ -676,7 +665,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 @@ -728,7 +717,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 @@ -774,7 +763,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 @@ -820,7 +809,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: @@ -990,7 +979,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/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." From 40562580a4f50b8bf23baaae046f46fb2c6b3619 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 15:57:19 -0800 Subject: [PATCH 13/16] add touch scrolling and usable scrollbars --- src/silky/contexts.nim | 28 +++- src/silky/richtextboxes.nim | 10 +- src/silky/scrolls.nim | 236 ++++++++++++++++++++++++++++++ src/silky/semantics.nim | 28 +++- src/silky/testwindow.nim | 12 +- src/silky/textboxes.nim | 73 ++++++---- src/silky/widgets.nim | 48 ++++-- tests/test_touch_scroll.nim | 283 ++++++++++++++++++++++++++++++++++++ 8 files changed, 665 insertions(+), 53 deletions(-) create mode 100644 src/silky/scrolls.nim create mode 100644 tests/test_touch_scroll.nim diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 82fad1e4..89a148e0 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, common, frames, interactions, layout, profiles], + silky/[atlas, clips, common, frames, interactions, scrolls, layout, profiles], silky/internal/inputs -export frames, interactions, layout, profiles +export frames, interactions, scrolls, layout, profiles when defined(useDirectX): import silky/drawers/dx12 @@ -112,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 = @@ -352,6 +355,7 @@ proc shouldShowTooltip*(sk: Silky): bool = proc resetInteractions*(sk: Silky) = ## 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. @@ -361,6 +365,13 @@ proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = window, sk.inputs.hasPendingEvents() ) sk.frames.beginFrame() + 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 + ) sk.inputs.beginInputFrame(window) beginProfileFrame() @@ -409,6 +420,7 @@ proc endUiShared*(sk: Silky) = previousCursor.hotspot != sk.cursor.hotspot)): sk.window.cursor = sk.cursor sk.interactor.endInteractions() + sk.touchScroll.endTouchFrame() sk.clear() sk.popLayout() sk.popClipRect() @@ -1142,15 +1154,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/richtextboxes.nim b/src/silky/richtextboxes.nim index 79c6360a..fc921226 100644 --- a/src/silky/richtextboxes.nim +++ b/src/silky/richtextboxes.nim @@ -1316,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 @@ -1360,7 +1366,7 @@ 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 state.mouseAction(localMouse, click = false, shift = true) if window.buttonReleased[MouseLeft] or not window.buttonDown[MouseLeft]: diff --git a/src/silky/scrolls.nim b/src/silky/scrolls.nim new file mode 100644 index 00000000..a58c9577 --- /dev/null +++ b/src/silky/scrolls.nim @@ -0,0 +1,236 @@ +import vmath, bumpy + +const + TouchPanThreshold = 6.0'f + TouchScrollbarWidth = 28.0'f + +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 + pending, dragging, scrollbar, cancelled, invalidated, tap: bool + suppress*, touchInput*: bool + +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 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 +) = + ## 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: + touch.pending = false + touch.dragging = false + touch.cancelled = false + touch.target = nil + 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 + 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 + 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) + break + touch.last = point + if released or not down: + touch.tap = touch.pending and not touch.dragging and + max(abs(distance.x), abs(distance.y)) < TouchPanThreshold + touch.pending = false + touch.dragging = false + 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.target = nil + 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) + +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 6eaff7a6..daf06776 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, common, frames, interactions, layout], testwindow, + silky/[atlas, clips, common, frames, interactions, scrolls, layout], testwindow, silky/internal/inputs from windy/common import Button, CursorKind, Cursor -export frames, interactions, layout +export frames, interactions, scrolls, layout const LineFeedRune = Rune(10) @@ -310,6 +310,9 @@ type avgFrameTime*: float64 semantic*: SemanticCapture interactor*: Interactor + touchScroll*: TouchScroll + touchOrigin*: Vec2 + ## Logical window offset applied when the app removes safe-area insets. window*: Window proc currentDrawLayer*(sk: Silky): int = @@ -696,6 +699,13 @@ proc beginUi*(sk: Silky, window: auto, size: IVec2) = window, sk.inputs.hasPendingEvents() ) sk.frames.beginFrame() + 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 + ) sk.inputs.beginInputFrame(window) sk.tooltipActive = sk.showTooltip sk.showTooltip = false @@ -723,6 +733,7 @@ proc beginUi*(sk: Silky, window: auto, size: IVec2) = proc resetInteractions*(sk: Silky) = ## Invalidates cached pointer targets. sk.interactor.resetInteractions() + sk.touchScroll.resetTouchScroll() proc endUi*(sk: Silky) = ## Ends the current UI frame. @@ -738,6 +749,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() @@ -748,15 +760,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..a4389c43 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,7 @@ type Window* = ref object buttonPressed*: array[Button, bool] buttonReleased*: array[Button, bool] scrollDelta*: Vec2 + pointerSource*: PointerSource ## Starts true so `while not window.closeRequested` loops exit immediately in tests. closeRequested*: bool = true cursor*: Cursor = Cursor(kind: ArrowCursor) @@ -92,6 +93,8 @@ 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.buttonDown[button] = true w.buttonPressed[button] = true if w.onButtonPress != nil: @@ -137,7 +140,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 7e0f4cb5..6cc2e52a 100644 --- a/src/silky/textboxes.nim +++ b/src/silky/textboxes.nim @@ -1000,13 +1000,7 @@ proc drawScrollbars*( 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( @@ -1016,23 +1010,28 @@ proc drawScrollbars*( 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: @@ -1043,25 +1042,45 @@ proc drawScrollbars*( 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, @@ -1137,7 +1156,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 @@ -1160,7 +1183,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]: diff --git a/src/silky/widgets.nim b/src/silky/widgets.nim index b7c684dd..bb5c515b 100644 --- a/src/silky/widgets.nim +++ b/src/silky/widgets.nim @@ -68,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] @@ -78,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: @@ -310,12 +314,7 @@ proc frameScrollbars*( ## frame rests scrolled to the bottom, and its thumb rests at the ## bottom of the track, moving away from the origin as t grows. const MinThumbSize = 16.0'f - 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 + var tracks, thumbs: array[2, Rect] let scrollMax = max(contentSize - frameRect.wh, vec2(0, 0)) @@ -367,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 @@ -376,10 +376,12 @@ proc frameScrollbars*( frameState.scrollPos.y = frac * scrollMax.y else: let thumb = thumbRectY() - if sk.interact(thumb, true) == Pressed: - frameState.scrollingY = window.buttonDown[MouseLeft] - 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. @@ -406,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 @@ -415,12 +418,28 @@ proc frameScrollbars*( frameState.scrollPos.x = frac * scrollMax.x else: let thumb = thumbRectX() - if sk.interact(thumb, true) == Pressed: - frameState.scrollingX = window.buttonDown[MouseLeft] - 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 @@ -604,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) 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." From cc60159cf2419ef5aaf8788b45a61da0156eca0b Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 16:21:16 -0800 Subject: [PATCH 14/16] Add iOS style touch scrolling momentum --- src/silky/contexts.nim | 8 +- src/silky/scrolls.nim | 116 +++++++++- src/silky/semantics.nim | 10 +- src/silky/testwindow.nim | 2 + tests/test_scroll_momentum.nim | 382 +++++++++++++++++++++++++++++++++ 5 files changed, 507 insertions(+), 11 deletions(-) create mode 100644 tests/test_scroll_momentum.nim diff --git a/src/silky/contexts.nim b/src/silky/contexts.nim index 89a148e0..a918c247 100644 --- a/src/silky/contexts.nim +++ b/src/silky/contexts.nim @@ -370,7 +370,9 @@ proc beginUiShared*(sk: Silky, window: Window, size: IVec2) = window.buttonPressed[MouseLeft], window.buttonDown[MouseLeft], window.buttonReleased[MouseLeft], window.focused, window.mousePos.vec2 / sk.uiScale, - window.mouseDelta.vec2 / sk.uiScale + window.mouseDelta.vec2 / sk.uiScale, + velocity = window.pointerVelocity / sk.uiScale, + interrupted = window.scrollDelta != vec2(0) ) sk.inputs.beginInputFrame(window) beginProfileFrame() @@ -411,7 +413,9 @@ proc endUiShared*(sk: Silky) = 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 diff --git a/src/silky/scrolls.nim b/src/silky/scrolls.nim index a58c9577..761dd0bf 100644 --- a/src/silky/scrolls.nim +++ b/src/silky/scrolls.nim @@ -1,8 +1,15 @@ -import vmath, bumpy +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 @@ -25,9 +32,25 @@ type 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 @@ -37,6 +60,11 @@ proc setComponent(value: var Vec2, axis: int, amount: float32) = 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 @@ -59,17 +87,21 @@ proc trackHit(region: ScrollRegion, axis: int, point: Vec2): bool = proc beginTouchFrame*( touch: var TouchScroll, isTouch, pressed, down, released, focused: bool, - point, motion: Vec2 + 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: + 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.target = nil + touch.consumeTap = false + touch.stopMomentum() return if touch.cancelled: touch.suppress = true @@ -78,6 +110,53 @@ proc beginTouchFrame*( 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) @@ -110,6 +189,7 @@ proc beginTouchFrame*( 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 @@ -152,21 +232,35 @@ proc beginTouchFrame*( 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 + 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.target = nil + 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.target = nil + touch.consumeTap = false + touch.stopMomentum() touch.previous.setLen(0) touch.previousBlockers.setLen(0) touch.invalidated = true @@ -187,6 +281,14 @@ proc endTouchFrame*(touch: var TouchScroll) = 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. diff --git a/src/silky/semantics.nim b/src/silky/semantics.nim index daf06776..adc8eb71 100644 --- a/src/silky/semantics.nim +++ b/src/silky/semantics.nim @@ -311,6 +311,7 @@ type semantic*: SemanticCapture interactor*: Interactor touchScroll*: TouchScroll + touchTimeMs*: float64 = -1 touchOrigin*: Vec2 ## Logical window offset applied when the app removes safe-area insets. window*: Window @@ -704,7 +705,10 @@ proc beginUi*(sk: Silky, window: auto, size: IVec2) = window.buttonPressed[MouseLeft], window.buttonDown[MouseLeft], window.buttonReleased[MouseLeft], window.focused, window.mousePos.vec2 / sk.uiScale, - window.mouseDelta.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 @@ -740,7 +744,9 @@ proc endUi*(sk: Silky) = 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 diff --git a/src/silky/testwindow.nim b/src/silky/testwindow.nim index a4389c43..8bf1cea4 100644 --- a/src/silky/testwindow.nim +++ b/src/silky/testwindow.nim @@ -22,6 +22,7 @@ type Window* = ref object 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) @@ -95,6 +96,7 @@ 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: 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." From 8e46168b52003b8456041454848fe7655bd1b238 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 16:51:14 -0800 Subject: [PATCH 15/16] Update iOS CI dependencies and fixtures --- .github/workflows/build.yml | 8 ++++++++ nimby.lock | 12 ++++++------ tests/test_button_vertices.nim | 4 +++- tests/test_decorations.nim | 10 ++++++---- tests/test_quotes.nim | 8 +++++--- tests/test_richimages.nim | 8 +++++--- tests/test_rules.nim | 11 ++++++----- 7 files changed, 39 insertions(+), 22 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bb28d90d..6d01c0f0 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: @@ -66,14 +70,18 @@ jobs: 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/nimby.lock b/nimby.lock index 22999c53..d688f2fd 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 e84f5104fd05c5d31a6b32fa46b70c0b5c5c93d4 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 dbcd1e96896d86217e63ce263c971aef6ff5ba00 vk14 0.1.0 https://github.com/treeform/vk14 545a3b1516234ab4471c8f4c7b59b378c2de2c2c fluffy 1.0.0 https://github.com/treeform/fluffy 2012906732cc104dc08fb80a3cec976ddfd9a98a 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_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_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_richimages.nim b/tests/test_richimages.nim index a9a835ba..f3349409 100644 --- a/tests/test_richimages.nim +++ b/tests/test_richimages.nim @@ -3,15 +3,17 @@ import 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. - privateAccess(Silky) result = Silky( atlas: builder.atlas, image: builder.atlasImage, uiScale: 2, inFrame: true, - inputs: TextInputs() + inputs: TextInputs(), + window: Window() ) new(result.drawer) result.theme.padding = 0 @@ -53,7 +55,7 @@ block: doAssert state.editor.copyText() == "An image\n\nAfter the image." richTextBoxStates["images"] = state sk.richTextBox( - Window(), "images", state.getText(), 184, state.innerHeight, + sk.window, "images", state.getText(), 184, state.innerHeight, blocks = state.blocks ) let 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, From cdc073422ff7220e384c3f00602c651dd831c167 Mon Sep 17 00:00:00 2001 From: treeform Date: Sun, 15 Nov 2026 16:55:23 -0800 Subject: [PATCH 16/16] Install shader compilers in Windows CI --- .github/workflows/build.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6d01c0f0..7dec2d92 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -58,6 +58,34 @@ 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: |