Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ on:
pull_request:
branches: [master]

defaults:
run:
shell: bash

jobs:
build:
strategy:
Expand Down Expand Up @@ -54,22 +58,58 @@ jobs:
if: matrix.emscripten
uses: mymindstorm/setup-emsdk@v14

- name: Install DirectX shader compiler
if: matrix.build_flags == '-d:useDirectX'
shell: pwsh
run: |
$archive = Join-Path $env:RUNNER_TEMP 'dxc.zip'
$tools = Join-Path $env:RUNNER_TEMP 'dxc'
Invoke-WebRequest 'https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2609/dxc_2026_09_29.zip' -OutFile $archive
if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne 'ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1') { throw 'DXC archive checksum mismatch' }
Expand-Archive $archive -DestinationPath $tools
$compiler = Join-Path $tools 'bin/x64/dxc.exe'
"SHADY_HLSL_COMPILER=$compiler" >> $env:GITHUB_ENV
& $compiler --version
if ($LASTEXITCODE -ne 0) { throw 'DXC did not start' }

- name: Install SPIR-V shader compiler
if: matrix.build_flags == '-d:useVulkan'
shell: pwsh
run: |
$archive = Join-Path $env:RUNNER_TEMP 'glslang.zip'
$tools = Join-Path $env:RUNNER_TEMP 'glslang'
Invoke-WebRequest 'https://github.com/KhronosGroup/glslang/releases/download/16.6.0/glslang-16.6.0-windows-x86_64-release.zip' -OutFile $archive
if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne '82bf434e69b9bb4829de7e2b4bc2c5e7a7861e53d66cf75e5cc70f5f694a8d9b') { throw 'glslang archive checksum mismatch' }
Expand-Archive $archive -DestinationPath $tools
$compiler = Join-Path $tools 'bin/glslang.exe'
"SHADY_SPIRV_COMPILER=$compiler" >> $env:GITHUB_ENV
& $compiler --version
if ($LASTEXITCODE -ne 0) { throw 'glslang did not start' }

- name: Run unit tests
if: ${{ !matrix.emscripten }}
run: |
nim r tests/test_textboxes.nim
nim r ${{ matrix.build_flags }} tests/test_richtextboxes.nim
nim r -d:silkyTesting -d:nimTypeNames tests/test_inputs.nim
nim r -d:silkyTesting tests/test_rendering.nim
nim r -d:silkyTesting tests/test_buttons.nim
nim r -d:silkyTesting tests/test_focus.nim
nim r -d:silkyTesting tests/test_cursor_scroll.nim
nim r -d:silkyTesting tests/test_input_hooks.nim
nim r -d:silkyTesting tests/test_secure_inputs.nim
nim r -d:silkyTesting tests/test_first_touch.nim
nim r -d:silkyTesting tests/test_touch_scroll.nim
nim r -d:silkyTesting tests/test_scroll_momentum.nim
nim r -d:silkyTesting tests/test_rendering.nim
nim r -d:silkyTesting tests/test_subwindow.nim
nim r tests/test_atlas_png.nim
nim r tests/test_retina_atlas.nim
nim r tests/test_shader_codegen.nim
nim r ${{ matrix.build_flags }} tests/test_density.nim
nim r ${{ matrix.build_flags }} tests/test_decorations.nim
nim r ${{ matrix.build_flags }} tests/test_rules.nim
nim r ${{ matrix.build_flags }} tests/test_quotes.nim
nim r ${{ matrix.build_flags }} tests/test_richimages.nim
nim r ${{ matrix.build_flags }} tests/test_button_vertices.nim
nim r -d:silkyTesting tests/test_layout.nim
nim r -d:silkyTesting tests/test_layout_regressions.nim
Expand Down
136 changes: 136 additions & 0 deletions docs/ios.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# iOS Metal integration

The iOS drawer uses the same Nim `silkyVert` and `silkyFrag` shader procedures
as the other backends. Shady translates them to MSL during the Nim build, and
Metal compiles the generated source when the drawer is created. Select this
drawer with `-d:useMetal4` and compile for iOS with `--os:ios --cpu:arm64`.

The `windy-ios`, `silky-ios`, `shady-ios`, and `metal4-ios` worktrees must be
on the Nim import path. Use `--skipParentCfg` when a parent Nim configuration
points at desktop checkouts. No Shady source changes are required for the
current Silky shaders.

## Application setup

Create the Windy window in its `runApplication` startup callback. Create
Silky in the first `window.onFrame` callback, after the native Metal view
exists. Run `beginUI(window, window.size)` and `endUI()` once per frame.
UIKit drives the event loop. There is no `pollEvents` loop or OpenGL buffer
swap in an iOS application.

Windy's iOS platform owns the UIKit app and scene delegates, MetalKit view
and input callbacks. These are implemented in Nim using Windy's shared Apple
Objective-C runtime bindings. A small C entry point starts Nim, and a tiny
Objective-C bridge references the SDK protocol metadata. GLFM is a design
reference only; it is not compiled or linked into the app.

Windy reports drawable sizes and pointer positions in pixels. Set
`sk.uiScale = window.contentScale` before `beginUI` for a point-sized UI,
and use `sk.size` for the resulting logical layout dimensions. Account for
the device's safe area when positioning controls.

Touch presses resolve against the previous displayed frame's hit rectangles,
including layer order and clipping, so controls need no preceding hover event.
Call `resetInteractions` when replacing a modal or reorganizing controls.

Generate the atlas on the host and bundle its PNG with the application.
The PNG includes the font metrics and sprite metadata, so the device does
not need the original fonts or skin files. For the example skin, add
`examples/basicwindow/data/` with that directory as the removed prefix,
then add `IBMPlexSans-Regular.ttf` as `Default` and `H1` before writing the
atlas. `newSilky(window, atlasPngPath)` loads the packaged atlas.

Pass `pixelScale = 2` or `pixelScale = 3` to `addFont` when generating
Retina atlases. Font size, advances, kerning and line metrics stay in
logical points, while glyph pixels are rasterized at the requested
density. Select the matching atlas for the window's content scale and
keep `sk.uiScale = window.contentScale`. The text renderer uses physical
atlas coordinates and snaps glyph origins to that raster's pixel grid.
Older atlas files without density metadata continue to use 1x glyphs.
Raster image and button skin assets have their own density requirements.

## Shader bindings

The generated entry points are `vertexMain` and `fragmentMain`. Vertex
buffer 0 contains two `Vec2` uniforms: viewport size at byte 0 and atlas
size at byte 8. Vertex buffer 1 contains packed 48-byte `DrawerVertex`
values. Attributes 0 through 5 are position, UV, color, clip position,
clip size, and mask UV. The color attribute uses `UChar4Normalized`; the
other attributes use `Float2`. The atlas texture and sampler use fragment
index 0. The final `uint32` is a CPU texture handle used for batching;
it is not a shader attribute. Zero selects the atlas. Each contiguous
texture batch receives the bound texture's size in the uniform buffer.

Positions and atlas coordinates stay in pixels until the generated shader
transforms them. This also applies to tint-mask coordinates. The fragment
shader uses interpolated pixel positions for clipping.

## Current scope

The drawer renders atlas images, independent images, text, clipping, tint
masks, rich documents, and Silky controls. It uses the ordinary Metal API exposed by the `metal4` Nim
package, without requiring Apple's newer Metal 4 GPU features.

Each frame waits for GPU completion before reusing the shared vertex
buffer. This keeps the first port correct and reports command errors, but
does not overlap CPU and GPU work. A bounded set of buffers can replace
this synchronization after profiling. Runtime atlas changes are uploaded
through `uploadAtlas`, or `uploadAtlasRegion` for a changed rectangle.

Use `allocateTexture`, `uploadTextureRows`, `drawTexture` and `deleteTexture`
for images that should not consume font atlas space. Upload all image rows
before drawing the texture. Batches preserve the original layer and draw
order, including when atlas controls and independent images alternate.
Call the drawer's `close` after rendering has stopped to release its GPU
resources. Closing a drawer does not destroy Windy's UIKit view.

`drawer.maxTextureSize` reports the active device's 2D texture limit.
Simulator exposes Apple family 2 capabilities with an 8192-pixel limit;
newer physical devices can support larger textures. Repack the atlas within
this bound before uploading it. Oversized textures raise `SilkyError`
before reaching Metal's descriptor assertions.

Atlas icons and skins accept an integer `pixelScale` through `addImage`,
`addDir` and `addDirRecursive`. Their physical texture sizes remain intact;
layout uses the corresponding logical dimensions.

Silky accepts Windy's text commits and range-based native edits, and publishes
focused text, selection and caret geometry through `TextInputState`. The
platform owns the software keyboard and composition interface. Accessibility,
multitouch gestures and remote development transport remain separate Windy
and application milestones.

## Verification

The native UIKit simulator demo verified Retina rendering, button taps,
software keyboard presentation, text insertion, single-character deletion,
keyboard dismissal and portrait/landscape resizing at 3x scale. Signed arm64
builds passed strict code signature verification. Background/resume kept the
same process and preserved edited text and the counter. Both native demos
are signed and installed on an iPhone 14 Pro. The locked phone blocked
launch, so native device runtime verification awaits an unlocked device.
The earlier prototype's rendering, touch and Retina text were verified on
that phone.

`tests/test_shader_codegen.nim` checks generated MSL resource slots and
uniform layout alongside the existing GLSL and HLSL checks.
`tests/test_metal_shader_pixels.nim` compiles the generated shaders on
macOS, links the pipeline with Silky's packed vertex layout, renders to an
offscreen texture, and verifies colors, tint masks, and clipping by pixel
readback. This host test uses Metal's runtime compiler and does not need
the optional Xcode MetalToolchain download.

`tests/test_metal_texture_pixels.nim`, built with `-d:silkyMetalTesting`,
exercises the production drawer's allocation, row uploads, atlas rectangles,
texture growth, batching, stale handles, clipping and tint masks. It renders
offscreen on macOS or iOS Simulator and checks the actual GPU pixels. The
Simulator build uses `--os:ios --cpu:arm64 --noMain -d:iosSimulator` with the
Simulator SDK and target flags; run it with `simctl spawn`. It also asserts
the detected 8192-pixel texture limit. `test_inputs`,
`test_cursor_scroll` and `test_rendering`, built with `-d:silkyTesting`, cover
native edit ordering, parent scrolling and on-demand frame scheduling.

`tests/test_retina_atlas.nim` checks unchanged logical metrics at 1x, 2x
and 3x, compares 3x glyph pixels against a physical-size reference,
roundtrips density metadata, loads old metadata and checks that runtime
atlas additions preserve the full glyph rectangles.
50 changes: 50 additions & 0 deletions docs/text_inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
12 changes: 6 additions & 6 deletions nimby.lock
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
shady 0.1.5 https://github.com/treeform/shady f9ab26d946c32cd9da7c04394a1353a375a9dba5
shady 0.1.5 https://github.com/treeform/shady c899f7cd17dbe7021d6e3aa2908e6de6549c47f1
vmath 2.0.1 https://github.com/treeform/vmath ddfcd738578c47ed3330b917f5efecf5a15128b2
pixie 5.1.0 https://github.com/treeform/pixie 5eda4949a3c8bea318cfac8e42060a8f90f3f35d
chroma 1.0.0 https://github.com/treeform/chroma 2381748f92e5ea16cb2403ff7e20c6dd5443a59d
zippy 0.10.16 https://github.com/guzba/zippy a99f6a7d8a8e3e0213b3cad0daf0ea974bf58e3f
zippy 0.10.16 https://github.com/treeform/zippy a99f6a7d8a8e3e0213b3cad0daf0ea974bf58e3f
flatty 0.3.4 https://github.com/treeform/flatty 05d878b397933331966a7f80dd0c55664559201f
nimsimd 1.3.2 https://github.com/guzba/nimsimd 3f6b2668ffb0867d0bf786a658b817763e611350
nimsimd 1.3.2 https://github.com/treeform/nimsimd 3f6b2668ffb0867d0bf786a658b817763e611350
bumpy 1.1.3 https://github.com/treeform/bumpy dc9a3d6d15680ec7f603959d65ba8ee4f1ddbc72
crunchy 0.1.11 https://github.com/guzba/crunchy 98eb6526982bb8aae8eec6e8781f4539fa19e049
crunchy 0.1.11 https://github.com/treeform/crunchy 98eb6526982bb8aae8eec6e8781f4539fa19e049
bitty 0.1.4 https://github.com/treeform/bitty/ c40e81277c04befa37234cba5052f58648bef895
windy 0.5.0 https://github.com/treeform/windy 8e1e2499a050bcbb1546f239b8c3a8b1b16748c0
windy 0.5.0 https://github.com/treeform/windy bf6b93d872de6826a69b34752c6d766e46204530
opengl 1.2.9 https://github.com/nim-lang/opengl 8e2e098f82dc5eefd874488c37b5830233cd18f4
urlly 1.1.1 https://github.com/treeform/urlly 99784779f05649df25fd9c33003d8ef6de027345
ws 0.5.0 https://github.com/treeform/ws cbb8f763b436669392d10baec2a45778395395cc
jsony 1.1.6 https://github.com/treeform/jsony bb647e1ca21af25ffdc423bcb96feeeeae963ca2
dx12 0.1.0 https://github.com/treeform/dx12 2b50efe4211d0df41237d3b1d121566ccdea2d15
metal4 0.1.0 https://github.com/treeform/metal4 2ee853339f6444a8844a5e4156e726ee52530bef
metal4 0.1.0 https://github.com/treeform/metal4 eaec6cef21c446d512bbf18e6fa949eeae47a583
vk14 0.1.0 https://github.com/treeform/vk14 545a3b1516234ab4471c8f4c7b59b378c2de2c2c
fluffy 1.0.0 https://github.com/treeform/fluffy 2012906732cc104dc08fb80a3cec976ddfd9a98a
10 changes: 9 additions & 1 deletion src/silky/atlas.nim
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ proc skipHook*(T: typedesc[FontAtlasObject], key: static string): bool =
## Skips runtime-only lookup tables during atlas JSON serialization.
key == "lookup"

proc rasterScale*(fontAtlas: FontAtlas): float32 {.inline.} =
## Returns physical glyph density while accepting legacy atlas metadata.
if fontAtlas.pixelScale > 0:
fontAtlas.pixelScale
else:
1.0'f

proc kerningKey(left, right: Rune): uint64 {.inline.} =
## Packs two Unicode scalar values into one table key.
(uint64(uint32(int32(left))) shl 32) or uint64(uint32(int32(right)))
Expand Down Expand Up @@ -439,6 +446,7 @@ proc addFont*(
fontAtlas.ascent = typeface.ascent * logicalScale
fontAtlas.descent = typeface.descent * logicalScale
fontAtlas.lineGap = typeface.lineGap * logicalScale
fontObj.size = size * density
# If subpixelSteps > 0, generates multiple versions of each glyph shifted by 1/subpixelSteps pixels.
# For example, subpixelSteps=10 generates 10 versions per glyph at 0.0, 0.1, 0.2, ... 0.9 pixel offsets.
let numVariants = if subpixelSteps > 0: subpixelSteps else: 1
Expand All @@ -447,7 +455,7 @@ proc addFont*(
let
rune = glyphStr.runeAt(0)
glyphPath = typeface.getGlyphPath(rune)
scale = logicalScale * density
scale = fontObj.scale
scaleMat = scale(vec2(scale))
baseBounds = glyphPath.computeBounds(scaleMat).snapToPixels().finiteBounds()
advance = typeface.getAdvance(rune) * logicalScale
Expand Down
Loading
Loading